Ruby 4.0.10p0 (2026-11-19 revision a704b7cd95a42cc0cf5f307137bf3aac0285b915)
io.c
1/**********************************************************************
2
3 io.c -
4
5 $Author$
6 created at: Fri Oct 15 18:08:59 JST 1993
7
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9 Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
10 Copyright (C) 2000 Information-technology Promotion Agency, Japan
11
12**********************************************************************/
13
14#include "ruby/internal/config.h"
15
17#include "ruby/io/buffer.h"
18
19#include <ctype.h>
20#include <errno.h>
21#include <stddef.h>
22
23/* non-Linux poll may not work on all FDs */
24#if defined(HAVE_POLL)
25# if defined(__linux__)
26# define USE_POLL 1
27# endif
28# if defined(__FreeBSD_version) && __FreeBSD_version >= 1100000
29# define USE_POLL 1
30# endif
31#endif
32
33#ifndef USE_POLL
34# define USE_POLL 0
35#endif
36
37#undef free
38#define free(x) xfree(x)
39
40#if defined(DOSISH) || defined(__CYGWIN__)
41#include <io.h>
42#endif
43
44#include <sys/types.h>
45#if defined HAVE_NET_SOCKET_H
46# include <net/socket.h>
47#elif defined HAVE_SYS_SOCKET_H
48# include <sys/socket.h>
49#endif
50
51#if defined(__BOW__) || defined(__CYGWIN__) || defined(_WIN32)
52# define NO_SAFE_RENAME
53#endif
54
55#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__sun) || defined(_nec_ews)
56# define USE_SETVBUF
57#endif
58
59#ifdef __QNXNTO__
60#include <unix.h>
61#endif
62
63#include <sys/types.h>
64#if defined(HAVE_SYS_IOCTL_H) && !defined(_WIN32)
65#include <sys/ioctl.h>
66#endif
67#if defined(HAVE_FCNTL_H) || defined(_WIN32)
68#include <fcntl.h>
69#elif defined(HAVE_SYS_FCNTL_H)
70#include <sys/fcntl.h>
71#endif
72
73#ifdef HAVE_SYS_TIME_H
74# include <sys/time.h>
75#endif
76
77#include <sys/stat.h>
78
79#if defined(HAVE_SYS_PARAM_H) || defined(__HIUX_MPP__)
80# include <sys/param.h>
81#endif
82
83#if !defined NOFILE
84# define NOFILE 64
85#endif
86
87#ifdef HAVE_UNISTD_H
88#include <unistd.h>
89#endif
90
91#ifdef HAVE_SYSCALL_H
92#include <syscall.h>
93#elif defined HAVE_SYS_SYSCALL_H
94#include <sys/syscall.h>
95#endif
96
97#ifdef HAVE_SYS_UIO_H
98#include <sys/uio.h>
99#endif
100
101#ifdef HAVE_SYS_WAIT_H
102# include <sys/wait.h> /* for WNOHANG on BSD */
103#endif
104
105#ifdef HAVE_COPYFILE_H
106# include <copyfile.h>
107
108# ifndef COPYFILE_STATE_COPIED
109/*
110 * Some OSes (e.g., OSX < 10.6) implement fcopyfile() but not
111 * COPYFILE_STATE_COPIED. Since the only use of the former here
112 * requires the latter, we disable the former when the latter is undefined.
113 */
114# undef HAVE_FCOPYFILE
115# endif
116
117#endif
118
119#if defined __APPLE__
120# include <AvailabilityMacros.h>
121#endif
122
124#include "ccan/list/list.h"
125#include "dln.h"
126#include "encindex.h"
127#include "id.h"
128#include "internal.h"
129#include "internal/class.h"
130#include "internal/encoding.h"
131#include "internal/error.h"
132#include "internal/inits.h"
133#include "internal/io.h"
134#include "internal/numeric.h"
135#include "internal/object.h"
136#include "internal/process.h"
137#include "internal/string.h"
138#include "internal/thread.h"
139#include "internal/transcode.h"
140#include "internal/variable.h"
141#include "ruby/io.h"
142#include "ruby/io/buffer.h"
143#include "ruby/missing.h"
144#include "ruby/thread.h"
145#include "ruby/util.h"
146#include "ruby_atomic.h"
147#include "ruby/ractor.h"
148
149#if !USE_POLL
150# include "vm_core.h"
151#endif
152
153#include "builtin.h"
154
155#ifndef O_ACCMODE
156#define O_ACCMODE (O_RDONLY | O_WRONLY | O_RDWR)
157#endif
158
159#ifndef PIPE_BUF
160# ifdef _POSIX_PIPE_BUF
161# define PIPE_BUF _POSIX_PIPE_BUF
162# else
163# define PIPE_BUF 512 /* is this ok? */
164# endif
165#endif
166
167#ifndef EWOULDBLOCK
168# define EWOULDBLOCK EAGAIN
169#endif
170
171#if defined(HAVE___SYSCALL) && (defined(__APPLE__) || defined(__OpenBSD__))
172/* Mac OS X and OpenBSD have __syscall but don't define it in headers */
173off_t __syscall(quad_t number, ...);
174#endif
175
176#define IO_RBUF_CAPA_MIN 8192
177#define IO_CBUF_CAPA_MIN (128*1024)
178#define IO_RBUF_CAPA_FOR(fptr) (NEED_READCONV(fptr) ? IO_CBUF_CAPA_MIN : IO_RBUF_CAPA_MIN)
179#define IO_WBUF_CAPA_MIN 8192
180
181#define IO_MAX_BUFFER_GROWTH 8 * 1024 * 1024 // 8MB
182
183/* define system APIs */
184#ifdef _WIN32
185#undef open
186#define open rb_w32_uopen
187#undef rename
188#define rename(f, t) rb_w32_urename((f), (t))
189#include "win32/file.h"
190#endif
191
198
199static VALUE rb_eEAGAINWaitReadable;
200static VALUE rb_eEAGAINWaitWritable;
201static VALUE rb_eEWOULDBLOCKWaitReadable;
202static VALUE rb_eEWOULDBLOCKWaitWritable;
203static VALUE rb_eEINPROGRESSWaitWritable;
204static VALUE rb_eEINPROGRESSWaitReadable;
205
207static VALUE orig_stdout, orig_stderr;
208
210VALUE rb_rs;
213
214static VALUE argf;
215
216static ID id_write, id_read, id_getc, id_flush, id_readpartial, id_set_encoding, id_fileno;
217static VALUE sym_mode, sym_perm, sym_flags, sym_extenc, sym_intenc, sym_encoding, sym_open_args;
218static VALUE sym_textmode, sym_binmode, sym_autoclose;
219static VALUE sym_SET, sym_CUR, sym_END;
220static VALUE sym_wait_readable, sym_wait_writable;
221#ifdef SEEK_DATA
222static VALUE sym_DATA;
223#endif
224#ifdef SEEK_HOLE
225static VALUE sym_HOLE;
226#endif
227
228static VALUE prep_io(int fd, enum rb_io_mode fmode, VALUE klass, const char *path);
229
230VALUE
231rb_io_blocking_region_wait(struct rb_io *io, rb_blocking_function_t *function, void *argument, enum rb_io_event events)
232{
233 return rb_thread_io_blocking_call(io, function, argument, events);
234}
235
236VALUE rb_io_blocking_region(struct rb_io *io, rb_blocking_function_t *function, void *argument)
237{
238 return rb_io_blocking_region_wait(io, function, argument, 0);
239}
240
241struct argf {
242 VALUE filename, current_file;
243 long last_lineno; /* $. */
244 long lineno;
245 VALUE argv;
246 VALUE inplace;
247 struct rb_io_encoding encs;
248 int8_t init_p, next_p, binmode;
249};
250
251
252#if defined(__APPLE__) && \
253 (!defined(MAC_OS_VERSION_27_0) || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_VERSION_27_0))
254
255# if __has_attribute(availability) && __has_warning("-Wunguarded-availability-new")
256
258RBIMPL_WARNING_IGNORED(-Wunguarded-availability-new)
259
260# ifdef HAVE_DUP3
261static inline int (*rb_dup3(void))(int, int, int) {return &dup3;}
262# define dup3 rb_dup3()
263# endif
264
265# ifdef HAVE_PIPE2
266static inline int (*rb_pipe2(void))(int [2], int) {return &pipe2;}
267# define pipe2 rb_pipe2()
268# endif
269
271
272# else /* __API_AVAILABLE macro does nothing on gcc */
273
274# ifdef HAVE_DUP3
275__attribute__((weak)) int dup3(int, int, int);
276# endif
277# ifdef HAVE_PIPE2
278__attribute__((weak)) int pipe2(int [2], int);
279# endif
280
281# endif
282#endif /* __APPLE__ && < MAC_OS_X_VERSION_27_0 */
283
284static rb_atomic_t max_file_descriptor = NOFILE;
285void
287{
288 rb_atomic_t afd = (rb_atomic_t)fd;
289 rb_atomic_t max_fd = max_file_descriptor;
290 int err;
291
292 if (fd < 0 || afd <= max_fd)
293 return;
294
295#if defined(HAVE_FCNTL) && defined(F_GETFL)
296 err = fcntl(fd, F_GETFL) == -1;
297#else
298 {
299 struct stat buf;
300 err = fstat(fd, &buf) != 0;
301 }
302#endif
303 if (err && errno == EBADF) {
304 rb_bug("rb_update_max_fd: invalid fd (%d) given.", fd);
305 }
306
307 while (max_fd < afd) {
308 max_fd = ATOMIC_CAS(max_file_descriptor, max_fd, afd);
309 }
310}
311
312void
313rb_maygvl_fd_fix_cloexec(int fd)
314{
315 /* MinGW don't have F_GETFD and FD_CLOEXEC. [ruby-core:40281] */
316#if defined(HAVE_FCNTL) && defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
317 int flags, flags2, ret;
318 flags = fcntl(fd, F_GETFD); /* should not fail except EBADF. */
319 if (flags == -1) {
320 rb_bug("rb_maygvl_fd_fix_cloexec: fcntl(%d, F_GETFD) failed: %s", fd, strerror(errno));
321 }
322 if (fd <= 2)
323 flags2 = flags & ~FD_CLOEXEC; /* Clear CLOEXEC for standard file descriptors: 0, 1, 2. */
324 else
325 flags2 = flags | FD_CLOEXEC; /* Set CLOEXEC for non-standard file descriptors: 3, 4, 5, ... */
326 if (flags != flags2) {
327 ret = fcntl(fd, F_SETFD, flags2);
328 if (ret != 0) {
329 rb_bug("rb_maygvl_fd_fix_cloexec: fcntl(%d, F_SETFD, %d) failed: %s", fd, flags2, strerror(errno));
330 }
331 }
332#endif
333}
334
335void
337{
338 rb_maygvl_fd_fix_cloexec(fd);
340}
341
342/* this is only called once */
343static int
344rb_fix_detect_o_cloexec(int fd)
345{
346#if defined(O_CLOEXEC) && defined(F_GETFD)
347 int flags = fcntl(fd, F_GETFD);
348
349 if (flags == -1)
350 rb_bug("rb_fix_detect_o_cloexec: fcntl(%d, F_GETFD) failed: %s", fd, strerror(errno));
351
352 if (flags & FD_CLOEXEC)
353 return 1;
354#endif /* fall through if O_CLOEXEC does not work: */
355 rb_maygvl_fd_fix_cloexec(fd);
356 return 0;
357}
358
359static inline bool
360io_again_p(int e)
361{
362 return (e == EWOULDBLOCK) || (e == EAGAIN);
363}
364
365int
366rb_cloexec_open(const char *pathname, int flags, mode_t mode)
367{
368 int ret;
369 static int o_cloexec_state = -1; /* <0: unknown, 0: ignored, >0: working */
370
371 static const int retry_interval = 0;
372 static const int retry_max_count = 10000;
373
374 int retry_count = 0;
375
376#ifdef O_CLOEXEC
377 /* O_CLOEXEC is available since Linux 2.6.23. Linux 2.6.18 silently ignore it. */
378 flags |= O_CLOEXEC;
379#elif defined O_NOINHERIT
380 flags |= O_NOINHERIT;
381#endif
382
383 while ((ret = open(pathname, flags, mode)) == -1) {
384 int e = errno;
385 if (!io_again_p(e)) break;
386 if (retry_count++ >= retry_max_count) break;
387
388 sleep(retry_interval);
389 }
390
391 if (ret < 0) return ret;
392 if (ret <= 2 || o_cloexec_state == 0) {
393 rb_maygvl_fd_fix_cloexec(ret);
394 }
395 else if (o_cloexec_state > 0) {
396 return ret;
397 }
398 else {
399 o_cloexec_state = rb_fix_detect_o_cloexec(ret);
400 }
401 return ret;
402}
403
404int
406{
407 /* Don't allocate standard file descriptors: 0, 1, 2 */
408 return rb_cloexec_fcntl_dupfd(oldfd, 3);
409}
410
411int
412rb_cloexec_dup2(int oldfd, int newfd)
413{
414 int ret;
415
416 /* When oldfd == newfd, dup2 succeeds but dup3 fails with EINVAL.
417 * rb_cloexec_dup2 succeeds as dup2. */
418 if (oldfd == newfd) {
419 ret = newfd;
420 }
421 else {
422#if defined(HAVE_DUP3) && defined(O_CLOEXEC)
423# if defined(__APPLE__)
424# define try_dup3 (dup3 != NULL)
425# define abandon_dup3() true
426# else
427 static bool try_dup3 = true;
428# define abandon_dup3() (errno != ENOSYS || !!(try_dup3 = false))
429# endif
430 if (newfd <= 2) {
431 /* pass stdin, stdout and stderr to children */
432 }
433 else if (try_dup3) {
434 ret = dup3(oldfd, newfd, O_CLOEXEC);
435 /* dup3 is available since:
436 * - Linux 2.6.27, glibc 2.9
437 * - macOS 27.0
438 */
439 if (ret != -1)
440 return ret;
441 if (abandon_dup3()) return ret;
442 }
443#endif
444 ret = dup2(oldfd, newfd);
445 if (ret < 0) return ret;
446 }
447 rb_maygvl_fd_fix_cloexec(ret);
448 return ret;
449}
450
451static int
452rb_fd_set_nonblock(int fd)
453{
454#ifdef _WIN32
455 return rb_w32_set_nonblock(fd);
456#elif defined(F_GETFL)
457 int oflags = fcntl(fd, F_GETFL);
458
459 if (oflags == -1)
460 return -1;
461 if (oflags & O_NONBLOCK)
462 return 0;
463 oflags |= O_NONBLOCK;
464 return fcntl(fd, F_SETFL, oflags);
465#endif
466 return 0;
467}
468
469static inline int
470cloexec_pipe(int descriptors[2], int flags, bool force_cloexec)
471{
472 int result = -1;
473#ifdef HAVE_PIPE2
474# if defined(__APPLE__)
475# define try_pipe2 (pipe2 != NULL)
476# define abandon_pipe2() true
477# else
478 static bool try_pipe2 = true;
479# define abandon_pipe2() (errno != ENOSYS || !!(try_pipe2 = false))
480# endif
481 if (try_pipe2) {
482 result = pipe2(descriptors, O_CLOEXEC | flags);
483 if (result == 0) return result;
484 if (abandon_pipe2()) return result;
485 }
486#endif
487 if (result < 0 && (result = pipe(descriptors)) < 0)
488 return result;
489
490#ifdef __CYGWIN__
491 if (result == 0 && descriptors[1] == -1) {
492 close(descriptors[0]);
493 descriptors[0] = -1;
494 errno = ENFILE;
495 return -1;
496 }
497#endif
498
499 if (!force_cloexec) return result;
500
501 /* no pipe2 or fallenback to dup */
502 rb_maygvl_fd_fix_cloexec(descriptors[0]);
503 rb_maygvl_fd_fix_cloexec(descriptors[1]);
504
505#ifndef _WIN32
506 rb_fd_set_nonblock(descriptors[0]);
507 rb_fd_set_nonblock(descriptors[1]);
508#endif
509
510 return result;
511}
512
513int
514rb_cloexec_pipe(int descriptors[2])
515{
516 return cloexec_pipe(descriptors, O_NONBLOCK, true);
517}
518
519int
520rb_cloexec_fcntl_dupfd(int fd, int minfd)
521{
522 int ret;
523
524#if defined(HAVE_FCNTL) && defined(F_DUPFD_CLOEXEC) && defined(F_DUPFD)
525 static int try_dupfd_cloexec = 1;
526 if (try_dupfd_cloexec) {
527 ret = fcntl(fd, F_DUPFD_CLOEXEC, minfd);
528 if (ret != -1) {
529 if (ret <= 2)
530 rb_maygvl_fd_fix_cloexec(ret);
531 return ret;
532 }
533 /* F_DUPFD_CLOEXEC is available since Linux 2.6.24. Linux 2.6.18 fails with EINVAL */
534 if (errno == EINVAL) {
535 ret = fcntl(fd, F_DUPFD, minfd);
536 if (ret != -1) {
537 try_dupfd_cloexec = 0;
538 }
539 }
540 }
541 else {
542 ret = fcntl(fd, F_DUPFD, minfd);
543 }
544#elif defined(HAVE_FCNTL) && defined(F_DUPFD)
545 ret = fcntl(fd, F_DUPFD, minfd);
546#else
547 ret = dup(fd);
548 if (ret >= 0 && ret < minfd) {
549 const int prev_fd = ret;
550 ret = rb_cloexec_fcntl_dupfd(fd, minfd);
551 close(prev_fd);
552 }
553 return ret;
554#endif
555 if (ret < 0) return ret;
556 rb_maygvl_fd_fix_cloexec(ret);
557 return ret;
558}
559
560#define argf_of(obj) (*(struct argf *)DATA_PTR(obj))
561#define ARGF argf_of(argf)
562
563#define GetWriteIO(io) rb_io_get_write_io(io)
564
565#define READ_DATA_PENDING(fptr) ((fptr)->rbuf.len)
566#define READ_DATA_PENDING_COUNT(fptr) ((fptr)->rbuf.len)
567#define READ_DATA_PENDING_PTR(fptr) ((fptr)->rbuf.ptr+(fptr)->rbuf.off)
568#define READ_DATA_BUFFERED(fptr) READ_DATA_PENDING(fptr)
569
570#define READ_CHAR_PENDING(fptr) ((fptr)->cbuf.len)
571#define READ_CHAR_PENDING_COUNT(fptr) ((fptr)->cbuf.len)
572#define READ_CHAR_PENDING_PTR(fptr) ((fptr)->cbuf.ptr+(fptr)->cbuf.off)
573
574#if defined(_WIN32)
575#define WAIT_FD_IN_WIN32(fptr) \
576 (rb_w32_io_cancelable_p((fptr)->fd) ? Qnil : rb_io_wait(fptr->self, RB_INT2NUM(RUBY_IO_READABLE), RUBY_IO_TIMEOUT_DEFAULT))
577#else
578#define WAIT_FD_IN_WIN32(fptr)
579#endif
580
581#define READ_CHECK(fptr) do {\
582 if (!READ_DATA_PENDING(fptr)) {\
583 WAIT_FD_IN_WIN32(fptr);\
584 rb_io_check_closed(fptr);\
585 }\
586} while(0)
587
588#ifndef S_ISSOCK
589# ifdef _S_ISSOCK
590# define S_ISSOCK(m) _S_ISSOCK(m)
591# else
592# ifdef _S_IFSOCK
593# define S_ISSOCK(m) (((m) & S_IFMT) == _S_IFSOCK)
594# else
595# ifdef S_IFSOCK
596# define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK)
597# endif
598# endif
599# endif
600#endif
601
602static int io_fflush(rb_io_t *);
603static rb_io_t *flush_before_seek(rb_io_t *fptr, bool discard_rbuf);
604static void clear_codeconv(rb_io_t *fptr);
605
606#define FMODE_SIGNAL_ON_EPIPE (1<<17)
607
608#define fptr_signal_on_epipe(fptr) \
609 (((fptr)->mode & FMODE_SIGNAL_ON_EPIPE) != 0)
610
611#define fptr_set_signal_on_epipe(fptr, flag) \
612 ((flag) ? \
613 (fptr)->mode |= FMODE_SIGNAL_ON_EPIPE : \
614 (fptr)->mode &= ~FMODE_SIGNAL_ON_EPIPE)
615
616extern ID ruby_static_id_signo;
617
618NORETURN(static void rb_sys_fail_on_write(rb_io_t *fptr));
619static void
620rb_sys_fail_on_write(rb_io_t *fptr)
621{
622 int e = errno;
623 VALUE errinfo = rb_syserr_new_path(e, (fptr)->pathv);
624#if defined EPIPE
625 if (fptr_signal_on_epipe(fptr) && (e == EPIPE)) {
626 const VALUE sig =
627# if defined SIGPIPE
628 INT2FIX(SIGPIPE) - INT2FIX(0) +
629# endif
630 INT2FIX(0);
631 rb_ivar_set(errinfo, ruby_static_id_signo, sig);
632 }
633#endif
634 rb_exc_raise(errinfo);
635}
636
637#define NEED_NEWLINE_DECORATOR_ON_READ(fptr) ((fptr)->mode & FMODE_TEXTMODE)
638#define NEED_NEWLINE_DECORATOR_ON_WRITE(fptr) ((fptr)->mode & FMODE_TEXTMODE)
639#if defined(RUBY_TEST_CRLF_ENVIRONMENT) || defined(_WIN32)
640# define RUBY_CRLF_ENVIRONMENT 1
641#else
642# define RUBY_CRLF_ENVIRONMENT 0
643#endif
644
645#if RUBY_CRLF_ENVIRONMENT
646/* Windows */
647# define DEFAULT_TEXTMODE FMODE_TEXTMODE
648# define TEXTMODE_NEWLINE_DECORATOR_ON_WRITE ECONV_CRLF_NEWLINE_DECORATOR
649/*
650 * CRLF newline is set as default newline decorator.
651 * If only CRLF newline conversion is needed, we use binary IO process
652 * with OS's text mode for IO performance improvement.
653 * If encoding conversion is needed or a user sets text mode, we use encoding
654 * conversion IO process and universal newline decorator by default.
655 */
656#define NEED_READCONV(fptr) ((fptr)->encs.enc2 != NULL || (fptr)->encs.ecflags & ~ECONV_CRLF_NEWLINE_DECORATOR)
657#define WRITECONV_MASK ( \
658 (ECONV_DECORATOR_MASK & ~ECONV_CRLF_NEWLINE_DECORATOR)|\
659 ECONV_STATEFUL_DECORATOR_MASK|\
660 0)
661#define NEED_WRITECONV(fptr) ( \
662 ((fptr)->encs.enc != NULL && (fptr)->encs.enc != rb_ascii8bit_encoding()) || \
663 ((fptr)->encs.ecflags & WRITECONV_MASK) || \
664 0)
665#define SET_BINARY_MODE(fptr) setmode((fptr)->fd, O_BINARY)
666
667#define NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr) do {\
668 if (NEED_NEWLINE_DECORATOR_ON_READ(fptr)) {\
669 if (((fptr)->mode & FMODE_READABLE) &&\
670 !((fptr)->encs.ecflags & ECONV_NEWLINE_DECORATOR_MASK)) {\
671 setmode((fptr)->fd, O_BINARY);\
672 }\
673 else {\
674 setmode((fptr)->fd, O_TEXT);\
675 }\
676 }\
677} while(0)
678
679#define SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags) do {\
680 if ((enc2) && ((ecflags) & ECONV_DEFAULT_NEWLINE_DECORATOR)) {\
681 (ecflags) |= ECONV_UNIVERSAL_NEWLINE_DECORATOR;\
682 }\
683} while(0)
684
685/*
686 * IO unread with taking care of removed '\r' in text mode.
687 */
688static void
689io_unread(rb_io_t *fptr, bool discard_rbuf)
690{
691 rb_off_t r, pos;
692 ssize_t read_size;
693 long i;
694 long newlines = 0;
695 long extra_max;
696 char *p;
697 char *buf;
698
699 rb_io_check_closed(fptr);
700 if (fptr->rbuf.len == 0 || fptr->mode & FMODE_DUPLEX) {
701 return;
702 }
703
704 errno = 0;
705 if (!rb_w32_fd_is_text(fptr->fd)) {
706 r = lseek(fptr->fd, -fptr->rbuf.len, SEEK_CUR);
707 if (r < 0 && errno) {
708 if (errno == ESPIPE)
709 fptr->mode |= FMODE_DUPLEX;
710 if (!discard_rbuf) return;
711 }
712
713 goto end;
714 }
715
716 pos = lseek(fptr->fd, 0, SEEK_CUR);
717 if (pos < 0 && errno) {
718 if (errno == ESPIPE)
719 fptr->mode |= FMODE_DUPLEX;
720 if (!discard_rbuf) goto end;
721 }
722
723 /* add extra offset for removed '\r' in rbuf */
724 extra_max = (long)(pos - fptr->rbuf.len);
725 p = fptr->rbuf.ptr + fptr->rbuf.off;
726
727 /* if the end of rbuf is '\r', rbuf doesn't have '\r' within rbuf.len */
728 if (*(fptr->rbuf.ptr + fptr->rbuf.capa - 1) == '\r') {
729 newlines++;
730 }
731
732 for (i = 0; i < fptr->rbuf.len; i++) {
733 if (*p == '\n') newlines++;
734 if (extra_max == newlines) break;
735 p++;
736 }
737
738 buf = ALLOC_N(char, fptr->rbuf.len + newlines);
739 while (newlines >= 0) {
740 r = lseek(fptr->fd, pos - fptr->rbuf.len - newlines, SEEK_SET);
741 if (newlines == 0) break;
742 if (r < 0) {
743 newlines--;
744 continue;
745 }
746 read_size = _read(fptr->fd, buf, fptr->rbuf.len + newlines);
747 if (read_size < 0) {
748 int e = errno;
749 free(buf);
750 rb_syserr_fail_path(e, fptr->pathv);
751 }
752 if (read_size == fptr->rbuf.len) {
753 lseek(fptr->fd, r, SEEK_SET);
754 break;
755 }
756 else {
757 newlines--;
758 }
759 }
760 free(buf);
761 end:
762 fptr->rbuf.off = 0;
763 fptr->rbuf.len = 0;
764 clear_codeconv(fptr);
765 return;
766}
767
768/*
769 * We use io_seek to back cursor position when changing mode from text to binary,
770 * but stdin and pipe cannot seek back. Stdin and pipe read should use encoding
771 * conversion for working properly with mode change.
772 *
773 * Return previous translation mode.
774 */
775static inline int
776set_binary_mode_with_seek_cur(rb_io_t *fptr)
777{
778 if (!rb_w32_fd_is_text(fptr->fd)) return O_BINARY;
779
780 if (fptr->rbuf.len == 0 || fptr->mode & FMODE_DUPLEX) {
781 return setmode(fptr->fd, O_BINARY);
782 }
783 flush_before_seek(fptr, false);
784 return setmode(fptr->fd, O_BINARY);
785}
786#define SET_BINARY_MODE_WITH_SEEK_CUR(fptr) set_binary_mode_with_seek_cur(fptr)
787
788#else
789/* Unix */
790# define DEFAULT_TEXTMODE 0
791#define NEED_READCONV(fptr) ((fptr)->encs.enc2 != NULL || NEED_NEWLINE_DECORATOR_ON_READ(fptr))
792#define NEED_WRITECONV(fptr) ( \
793 ((fptr)->encs.enc != NULL && (fptr)->encs.enc != rb_ascii8bit_encoding()) || \
794 NEED_NEWLINE_DECORATOR_ON_WRITE(fptr) || \
795 ((fptr)->encs.ecflags & (ECONV_DECORATOR_MASK|ECONV_STATEFUL_DECORATOR_MASK)) || \
796 0)
797#define SET_BINARY_MODE(fptr) (void)(fptr)
798#define NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr) (void)(fptr)
799#define SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags) ((void)(enc2), (void)(ecflags))
800#define SET_BINARY_MODE_WITH_SEEK_CUR(fptr) (void)(fptr)
801#endif
802
803#if !defined HAVE_SHUTDOWN && !defined shutdown
804#define shutdown(a,b) 0
805#endif
806
807#if defined(_WIN32)
808#define is_socket(fd, path) rb_w32_is_socket(fd)
809#elif !defined(S_ISSOCK)
810#define is_socket(fd, path) 0
811#else
812static int
813is_socket(int fd, VALUE path)
814{
815 struct stat sbuf;
816 if (fstat(fd, &sbuf) < 0)
817 rb_sys_fail_path(path);
818 return S_ISSOCK(sbuf.st_mode);
819}
820#endif
821
822static const char closed_stream[] = "closed stream";
823
824static void
825io_fd_check_closed(int fd)
826{
827 if (fd < 0) {
828 rb_thread_check_ints(); /* check for ruby_error_stream_closed */
829 rb_raise(rb_eIOError, closed_stream);
830 }
831}
832
833void
835{
836 rb_raise(rb_eEOFError, "end of file reached");
837}
838
839VALUE
841{
842 rb_check_frozen(io);
843 return io;
844}
845
846void
848{
849 if (!fptr) {
850 rb_raise(rb_eIOError, "uninitialized stream");
851 }
852}
853
854void
855rb_io_check_closed(rb_io_t *fptr)
856{
858 io_fd_check_closed(fptr->fd);
859}
860
861static rb_io_t *
862rb_io_get_fptr(VALUE io)
863{
864 rb_io_t *fptr = RFILE(io)->fptr;
866 return fptr;
867}
868
869VALUE
871{
872 return rb_convert_type_with_id(io, T_FILE, "IO", idTo_io);
873}
874
875VALUE
877{
878 return rb_check_convert_type_with_id(io, T_FILE, "IO", idTo_io);
879}
880
881VALUE
883{
884 VALUE write_io;
885 write_io = rb_io_get_fptr(io)->tied_io_for_writing;
886 if (write_io) {
887 return write_io;
888 }
889 return io;
890}
891
892VALUE
894{
895 VALUE write_io;
896 rb_io_t *fptr = rb_io_get_fptr(io);
897 if (!RTEST(w)) {
898 w = 0;
899 }
900 else {
901 GetWriteIO(w);
902 }
903 write_io = fptr->tied_io_for_writing;
904 fptr->tied_io_for_writing = w;
905 return write_io ? write_io : Qnil;
906}
907
908/*
909 * call-seq:
910 * timeout -> duration or nil
911 *
912 * Get the internal timeout duration or nil if it was not set.
913 *
914 */
915VALUE
917{
918 rb_io_t *fptr = rb_io_get_fptr(self);
919
920 return fptr->timeout;
921}
922
923/*
924 * call-seq:
925 * timeout = duration -> duration
926 * timeout = nil -> nil
927 *
928 * Sets the internal timeout to the specified duration or nil. The timeout
929 * applies to all blocking operations where possible.
930 *
931 * When the operation performs longer than the timeout set, IO::TimeoutError
932 * is raised.
933 *
934 * This affects the following methods (but is not limited to): #gets, #puts,
935 * #read, #write, #wait_readable and #wait_writable. This also affects
936 * blocking socket operations like Socket#accept and Socket#connect.
937 *
938 * Some operations like File#open and IO#close are not affected by the
939 * timeout. A timeout during a write operation may leave the IO in an
940 * inconsistent state, e.g. data was partially written. Generally speaking, a
941 * timeout is a last ditch effort to prevent an application from hanging on
942 * slow I/O operations, such as those that occur during a slowloris attack.
943 */
944VALUE
946{
947 // Validate it:
948 if (RTEST(timeout)) {
949 rb_time_interval(timeout);
950 }
951
952 rb_io_t *fptr = rb_io_get_fptr(self);
953
954 RB_OBJ_WRITE(self, &fptr->timeout, timeout);
955
956 return self;
957}
958
959/*
960 * call-seq:
961 * IO.try_convert(object) -> new_io or nil
962 *
963 * Attempts to convert +object+ into an \IO object via method +to_io+;
964 * returns the new \IO object if successful, or +nil+ otherwise:
965 *
966 * IO.try_convert(STDOUT) # => #<IO:<STDOUT>>
967 * IO.try_convert(ARGF) # => #<IO:<STDIN>>
968 * IO.try_convert('STDOUT') # => nil
969 *
970 */
971static VALUE
972rb_io_s_try_convert(VALUE dummy, VALUE io)
973{
974 return rb_io_check_io(io);
975}
976
977#if !RUBY_CRLF_ENVIRONMENT
978static void
979io_unread(rb_io_t *fptr, bool discard_rbuf)
980{
981 rb_off_t r;
982 rb_io_check_closed(fptr);
983 if (fptr->rbuf.len == 0 || fptr->mode & FMODE_DUPLEX)
984 return;
985 /* xxx: target position may be negative if buffer is filled by ungetc */
986 errno = 0;
987 r = lseek(fptr->fd, -fptr->rbuf.len, SEEK_CUR);
988 if (r < 0 && errno) {
989 if (errno == ESPIPE)
990 fptr->mode |= FMODE_DUPLEX;
991 if (!discard_rbuf) return;
992 }
993 fptr->rbuf.off = 0;
994 fptr->rbuf.len = 0;
995 clear_codeconv(fptr);
996 return;
997}
998#endif
999
1000static rb_encoding *io_input_encoding(rb_io_t *fptr);
1001
1002static void
1003io_ungetbyte(VALUE str, rb_io_t *fptr)
1004{
1005 long len = RSTRING_LEN(str);
1006
1007 if (fptr->rbuf.ptr == NULL) {
1008 const int min_capa = IO_RBUF_CAPA_FOR(fptr);
1009 fptr->rbuf.off = 0;
1010 fptr->rbuf.len = 0;
1011#if SIZEOF_LONG > SIZEOF_INT
1012 if (len > INT_MAX)
1013 rb_raise(rb_eIOError, "ungetbyte failed");
1014#endif
1015 if (len > min_capa)
1016 fptr->rbuf.capa = (int)len;
1017 else
1018 fptr->rbuf.capa = min_capa;
1019 fptr->rbuf.ptr = ALLOC_N(char, fptr->rbuf.capa);
1020 }
1021 if (fptr->rbuf.capa < len + fptr->rbuf.len) {
1022 rb_raise(rb_eIOError, "ungetbyte failed");
1023 }
1024 if (fptr->rbuf.off < len) {
1025 MEMMOVE(fptr->rbuf.ptr+fptr->rbuf.capa-fptr->rbuf.len,
1026 fptr->rbuf.ptr+fptr->rbuf.off,
1027 char, fptr->rbuf.len);
1028 fptr->rbuf.off = fptr->rbuf.capa-fptr->rbuf.len;
1029 }
1030 fptr->rbuf.off-=(int)len;
1031 fptr->rbuf.len+=(int)len;
1032 MEMMOVE(fptr->rbuf.ptr+fptr->rbuf.off, RSTRING_PTR(str), char, len);
1033}
1034
1035static rb_io_t *
1036flush_before_seek(rb_io_t *fptr, bool discard_rbuf)
1037{
1038 if (io_fflush(fptr) < 0)
1039 rb_sys_fail_on_write(fptr);
1040 io_unread(fptr, discard_rbuf);
1041 errno = 0;
1042 return fptr;
1043}
1044
1045#define io_seek(fptr, ofs, whence) (errno = 0, lseek(flush_before_seek(fptr, true)->fd, (ofs), (whence)))
1046#define io_tell(fptr) lseek(flush_before_seek(fptr, false)->fd, 0, SEEK_CUR)
1047
1048#ifndef SEEK_CUR
1049# define SEEK_SET 0
1050# define SEEK_CUR 1
1051# define SEEK_END 2
1052#endif
1053
1054void
1056{
1057 rb_io_check_closed(fptr);
1058 if (!(fptr->mode & FMODE_READABLE)) {
1059 rb_raise(rb_eIOError, "not opened for reading");
1060 }
1061 if (fptr->wbuf.len) {
1062 if (io_fflush(fptr) < 0)
1063 rb_sys_fail_on_write(fptr);
1064 }
1065 if (fptr->tied_io_for_writing) {
1066 rb_io_t *wfptr;
1067 GetOpenFile(fptr->tied_io_for_writing, wfptr);
1068 if (io_fflush(wfptr) < 0)
1069 rb_sys_fail_on_write(wfptr);
1070 }
1071}
1072
1073void
1075{
1077 if (READ_CHAR_PENDING(fptr)) {
1078 rb_raise(rb_eIOError, "byte oriented read for character buffered IO");
1079 }
1080}
1081
1082void
1084{
1086}
1087
1088static rb_encoding*
1089io_read_encoding(rb_io_t *fptr)
1090{
1091 if (fptr->encs.enc) {
1092 return fptr->encs.enc;
1093 }
1094 return rb_default_external_encoding();
1095}
1096
1097static rb_encoding*
1098io_input_encoding(rb_io_t *fptr)
1099{
1100 if (fptr->encs.enc2) {
1101 return fptr->encs.enc2;
1102 }
1103 return io_read_encoding(fptr);
1104}
1105
1106void
1108{
1109 rb_io_check_closed(fptr);
1110 if (!(fptr->mode & FMODE_WRITABLE)) {
1111 rb_raise(rb_eIOError, "not opened for writing");
1112 }
1113 if (fptr->rbuf.len) {
1114 io_unread(fptr, true);
1115 }
1116}
1117
1118int
1120{
1121 /* This function is used for bytes and chars. Confusing. */
1122 if (READ_CHAR_PENDING(fptr))
1123 return 1; /* should raise? */
1124 return READ_DATA_PENDING(fptr);
1125}
1126
1127void
1128rb_io_read_check(rb_io_t *fptr)
1129{
1130 if (!READ_DATA_PENDING(fptr)) {
1131 rb_io_wait(fptr->self, RB_INT2NUM(RUBY_IO_READABLE), RUBY_IO_TIMEOUT_DEFAULT);
1132 }
1133 return;
1134}
1135
1136int
1137rb_gc_for_fd(int err)
1138{
1139 if (err == EMFILE || err == ENFILE || err == ENOMEM) {
1140 rb_gc();
1141 return 1;
1142 }
1143 return 0;
1144}
1145
1146/* try `expr` upto twice while it returns false and `errno`
1147 * is to GC. Each `errno`s are available as `first_errno` and
1148 * `retried_errno` respectively */
1149#define TRY_WITH_GC(expr) \
1150 for (int first_errno, retried_errno = 0, retried = 0; \
1151 (!retried && \
1152 !(expr) && \
1153 (!rb_gc_for_fd(first_errno = errno) || !(expr)) && \
1154 (retried_errno = errno, 1)); \
1155 (void)retried_errno, retried = 1)
1156
1157static int
1158ruby_dup(int orig)
1159{
1160 int fd = -1;
1161
1162 TRY_WITH_GC((fd = rb_cloexec_dup(orig)) >= 0) {
1163 rb_syserr_fail(first_errno, 0);
1164 }
1165 rb_update_max_fd(fd);
1166 return fd;
1167}
1168
1169static VALUE
1170io_alloc(VALUE klass)
1171{
1172 NEWOBJ_OF(io, struct RFile, klass, T_FILE, sizeof(struct RFile), 0);
1173
1174 io->fptr = 0;
1175
1176 return (VALUE)io;
1177}
1178
1179#ifndef S_ISREG
1180# define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
1181#endif
1182
1184 VALUE th;
1185 rb_io_t *fptr;
1186 int nonblock;
1187 int fd;
1188
1189 void *buf;
1190 size_t capa;
1191 struct timeval *timeout;
1192};
1193
1195 VALUE th;
1196 rb_io_t *fptr;
1197 int nonblock;
1198 int fd;
1199
1200 const void *buf;
1201 size_t capa;
1202 struct timeval *timeout;
1203};
1204
1205#ifdef HAVE_WRITEV
1206struct io_internal_writev_struct {
1207 VALUE th;
1208 rb_io_t *fptr;
1209 int nonblock;
1210 int fd;
1211
1212 int iovcnt;
1213 const struct iovec *iov;
1214 struct timeval *timeout;
1215};
1216#endif
1217
1218static int nogvl_wait_for(VALUE th, rb_io_t *fptr, short events, struct timeval *timeout);
1219
1225static inline int
1226io_internal_wait(VALUE thread, rb_io_t *fptr, int error, int events, struct timeval *timeout)
1227{
1228 if (!timeout && rb_thread_mn_schedulable(thread)) {
1229 RUBY_ASSERT(errno == EWOULDBLOCK || errno == EAGAIN);
1230 return -1;
1231 }
1232
1233 int ready = nogvl_wait_for(thread, fptr, events, timeout);
1234
1235 if (ready > 0) {
1236 return ready;
1237 }
1238 else if (ready == 0) {
1239 errno = ETIMEDOUT;
1240 return -1;
1241 }
1242
1243 // If there was an error BEFORE we started waiting, return it:
1244 if (error) {
1245 errno = error;
1246 return -1;
1247 }
1248 else {
1249 // Otherwise, whatever error was generated by `nogvl_wait_for` is the one we want:
1250 return ready;
1251 }
1252}
1253
1254static VALUE
1255internal_read_func(void *ptr)
1256{
1257 struct io_internal_read_struct *iis = ptr;
1258 ssize_t result;
1259
1260 if (iis->timeout && !iis->nonblock) {
1261 if (io_internal_wait(iis->th, iis->fptr, 0, RB_WAITFD_IN, iis->timeout) == -1) {
1262 return -1;
1263 }
1264 }
1265
1266 retry:
1267 result = read(iis->fd, iis->buf, iis->capa);
1268
1269 if (result < 0 && !iis->nonblock) {
1270 if (io_again_p(errno)) {
1271 if (io_internal_wait(iis->th, iis->fptr, errno, RB_WAITFD_IN, iis->timeout) == -1) {
1272 return -1;
1273 }
1274 else {
1275 goto retry;
1276 }
1277 }
1278 }
1279
1280 return result;
1281}
1282
1283#if defined __APPLE__
1284# define do_write_retry(code) do {result = code;} while (result == -1 && errno == EPROTOTYPE)
1285#else
1286# define do_write_retry(code) result = code
1287#endif
1288
1289static VALUE
1290internal_write_func(void *ptr)
1291{
1292 struct io_internal_write_struct *iis = ptr;
1293 ssize_t result;
1294
1295 if (iis->timeout && !iis->nonblock) {
1296 if (io_internal_wait(iis->th, iis->fptr, 0, RB_WAITFD_OUT, iis->timeout) == -1) {
1297 return -1;
1298 }
1299 }
1300
1301 retry:
1302 do_write_retry(write(iis->fd, iis->buf, iis->capa));
1303
1304 if (result < 0 && !iis->nonblock) {
1305 int e = errno;
1306 if (io_again_p(e)) {
1307 if (io_internal_wait(iis->th, iis->fptr, errno, RB_WAITFD_OUT, iis->timeout) == -1) {
1308 return -1;
1309 }
1310 else {
1311 goto retry;
1312 }
1313 }
1314 }
1315
1316 return result;
1317}
1318
1319#ifdef HAVE_WRITEV
1320static VALUE
1321internal_writev_func(void *ptr)
1322{
1323 struct io_internal_writev_struct *iis = ptr;
1324 ssize_t result;
1325
1326 if (iis->timeout && !iis->nonblock) {
1327 if (io_internal_wait(iis->th, iis->fptr, 0, RB_WAITFD_OUT, iis->timeout) == -1) {
1328 return -1;
1329 }
1330 }
1331
1332 retry:
1333 do_write_retry(writev(iis->fd, iis->iov, iis->iovcnt));
1334
1335 if (result < 0 && !iis->nonblock) {
1336 if (io_again_p(errno)) {
1337 if (io_internal_wait(iis->th, iis->fptr, errno, RB_WAITFD_OUT, iis->timeout) == -1) {
1338 return -1;
1339 }
1340 else {
1341 goto retry;
1342 }
1343 }
1344 }
1345
1346 return result;
1347}
1348#endif
1349
1350static ssize_t
1351rb_io_read_memory(rb_io_t *fptr, void *buf, size_t count)
1352{
1353 rb_thread_t *th = GET_THREAD();
1355 if (scheduler != Qnil) {
1356 VALUE result = rb_fiber_scheduler_io_read_memory(scheduler, fptr->self, buf, count, 0);
1357
1358 if (!UNDEF_P(result)) {
1359 return rb_fiber_scheduler_io_result_apply(result);
1360 }
1361 }
1362
1363 struct io_internal_read_struct iis = {
1364 .th = th->self,
1365 .fptr = fptr,
1366 .nonblock = 0,
1367 .fd = fptr->fd,
1368
1369 .buf = buf,
1370 .capa = count,
1371 .timeout = NULL,
1372 };
1373
1374 struct timeval timeout_storage;
1375
1376 if (fptr->timeout != Qnil) {
1377 timeout_storage = rb_time_interval(fptr->timeout);
1378 iis.timeout = &timeout_storage;
1379 }
1380
1381 return (ssize_t)rb_io_blocking_region_wait(fptr, internal_read_func, &iis, RUBY_IO_READABLE);
1382}
1383
1384static ssize_t
1385rb_io_write_memory(rb_io_t *fptr, const void *buf, size_t count)
1386{
1387 rb_thread_t *th = GET_THREAD();
1389 if (scheduler != Qnil) {
1390 VALUE result = rb_fiber_scheduler_io_write_memory(scheduler, fptr->self, buf, count, 0);
1391
1392 if (!UNDEF_P(result)) {
1393 return rb_fiber_scheduler_io_result_apply(result);
1394 }
1395 }
1396
1397 struct io_internal_write_struct iis = {
1398 .th = th->self,
1399 .fptr = fptr,
1400 .nonblock = 0,
1401 .fd = fptr->fd,
1402
1403 .buf = buf,
1404 .capa = count,
1405 .timeout = NULL
1406 };
1407
1408 struct timeval timeout_storage;
1409
1410 if (fptr->timeout != Qnil) {
1411 timeout_storage = rb_time_interval(fptr->timeout);
1412 iis.timeout = &timeout_storage;
1413 }
1414
1415 return (ssize_t)rb_io_blocking_region_wait(fptr, internal_write_func, &iis, RUBY_IO_WRITABLE);
1416}
1417
1418#ifdef HAVE_WRITEV
1419static ssize_t
1420rb_writev_internal(rb_io_t *fptr, const struct iovec *iov, int iovcnt)
1421{
1422 if (!iovcnt) return 0;
1423
1424 rb_thread_t *th = GET_THREAD();
1425
1427 if (scheduler != Qnil) {
1428 // This path assumes at least one `iov`:
1429 VALUE result = rb_fiber_scheduler_io_write_memory(scheduler, fptr->self, iov[0].iov_base, iov[0].iov_len, 0);
1430
1431 if (!UNDEF_P(result)) {
1432 return rb_fiber_scheduler_io_result_apply(result);
1433 }
1434 }
1435
1436 struct io_internal_writev_struct iis = {
1437 .th = th->self,
1438 .fptr = fptr,
1439 .nonblock = 0,
1440 .fd = fptr->fd,
1441
1442 .iov = iov,
1443 .iovcnt = iovcnt,
1444 .timeout = NULL
1445 };
1446
1447 struct timeval timeout_storage;
1448
1449 if (fptr->timeout != Qnil) {
1450 timeout_storage = rb_time_interval(fptr->timeout);
1451 iis.timeout = &timeout_storage;
1452 }
1453
1454 return (ssize_t)rb_io_blocking_region_wait(fptr, internal_writev_func, &iis, RUBY_IO_WRITABLE);
1455}
1456#endif
1457
1458static VALUE
1459io_flush_buffer_sync(void *arg)
1460{
1461 rb_io_t *fptr = arg;
1462 long l = fptr->wbuf.len;
1463 ssize_t r = write(fptr->fd, fptr->wbuf.ptr+fptr->wbuf.off, (size_t)l);
1464
1465 if (fptr->wbuf.len <= r) {
1466 fptr->wbuf.off = 0;
1467 fptr->wbuf.len = 0;
1468 return 0;
1469 }
1470
1471 if (0 <= r) {
1472 fptr->wbuf.off += (int)r;
1473 fptr->wbuf.len -= (int)r;
1474 errno = EAGAIN;
1475 }
1476
1477 return (VALUE)-1;
1478}
1479
1480static inline VALUE
1481io_flush_buffer_fiber_scheduler(VALUE scheduler, rb_io_t *fptr)
1482{
1483 VALUE ret = rb_fiber_scheduler_io_write_memory(scheduler, fptr->self, fptr->wbuf.ptr+fptr->wbuf.off, fptr->wbuf.len, 0);
1484 if (!UNDEF_P(ret)) {
1485 ssize_t result = rb_fiber_scheduler_io_result_apply(ret);
1486 if (result > 0) {
1487 fptr->wbuf.off += result;
1488 fptr->wbuf.len -= result;
1489 }
1490 return result >= 0 ? (VALUE)0 : (VALUE)-1;
1491 }
1492 return ret;
1493}
1494
1495static VALUE
1496io_flush_buffer_async(VALUE arg)
1497{
1498 rb_io_t *fptr = (rb_io_t *)arg;
1499
1500 VALUE scheduler = rb_fiber_scheduler_current();
1501 if (scheduler != Qnil) {
1502 VALUE result = io_flush_buffer_fiber_scheduler(scheduler, fptr);
1503 if (!UNDEF_P(result)) {
1504 return result;
1505 }
1506 }
1507
1508 return rb_io_blocking_region_wait(fptr, io_flush_buffer_sync, fptr, RUBY_IO_WRITABLE);
1509}
1510
1511static inline int
1512io_flush_buffer(rb_io_t *fptr)
1513{
1514 if (!NIL_P(fptr->write_lock) && rb_mutex_owned_p(fptr->write_lock)) {
1515 return (int)io_flush_buffer_async((VALUE)fptr);
1516 }
1517 else {
1518 return (int)rb_mutex_synchronize(fptr->write_lock, io_flush_buffer_async, (VALUE)fptr);
1519 }
1520}
1521
1522static int
1523io_fflush(rb_io_t *fptr)
1524{
1525 rb_io_check_closed(fptr);
1526
1527 if (fptr->wbuf.len == 0)
1528 return 0;
1529
1530 while (fptr->wbuf.len > 0 && io_flush_buffer(fptr) != 0) {
1531 if (!rb_io_maybe_wait_writable(errno, fptr->self, RUBY_IO_TIMEOUT_DEFAULT))
1532 return -1;
1533
1534 rb_io_check_closed(fptr);
1535 }
1536
1537 return 0;
1538}
1539
1540VALUE
1541rb_io_wait(VALUE io, VALUE events, VALUE timeout)
1542{
1543 rb_thread_t *th = GET_THREAD();
1545
1546 if (scheduler != Qnil) {
1547 return rb_fiber_scheduler_io_wait(scheduler, io, events, timeout);
1548 }
1549
1550 rb_io_t * fptr = NULL;
1551 RB_IO_POINTER(io, fptr);
1552
1553 struct timeval tv_storage;
1554 struct timeval *tv = NULL;
1555
1556 if (NIL_OR_UNDEF_P(timeout)) {
1557 timeout = fptr->timeout;
1558 }
1559
1560 if (timeout != Qnil) {
1561 tv_storage = rb_time_interval(timeout);
1562 tv = &tv_storage;
1563 }
1564
1565 int ready = rb_thread_io_wait(th, fptr, RB_NUM2INT(events), tv);
1566
1567 if (ready < 0) {
1568 rb_sys_fail(0);
1569 }
1570
1571 // Not sure if this is necessary:
1572 rb_io_check_closed(fptr);
1573
1574 if (ready) {
1575 return RB_INT2NUM(ready);
1576 }
1577 else {
1578 return Qfalse;
1579 }
1580}
1581
1582static VALUE
1583io_from_fd(int fd)
1584{
1585 return prep_io(fd, FMODE_EXTERNAL, rb_cIO, NULL);
1586}
1587
1588static int
1589io_wait_for_single_fd(int fd, int events, struct timeval *timeout, rb_thread_t *th, VALUE scheduler)
1590{
1591 if (scheduler != Qnil) {
1592 return RTEST(
1593 rb_fiber_scheduler_io_wait(scheduler, io_from_fd(fd), RB_INT2NUM(events), rb_fiber_scheduler_make_timeout(timeout))
1594 );
1595 }
1596
1597 return rb_thread_wait_for_single_fd(th, fd, events, timeout);
1598}
1599
1600int
1602{
1603 io_fd_check_closed(f);
1604
1605 rb_thread_t *th = GET_THREAD();
1607
1608 switch (errno) {
1609 case EINTR:
1610#if defined(ERESTART)
1611 case ERESTART:
1612#endif
1614 return TRUE;
1615
1616 case EAGAIN:
1617#if EWOULDBLOCK != EAGAIN
1618 case EWOULDBLOCK:
1619#endif
1620 if (scheduler != Qnil) {
1621 return RTEST(
1622 rb_fiber_scheduler_io_wait_readable(scheduler, io_from_fd(f))
1623 );
1624 }
1625 else {
1626 io_wait_for_single_fd(f, RUBY_IO_READABLE, NULL, th, scheduler);
1627 }
1628 return TRUE;
1629
1630 default:
1631 return FALSE;
1632 }
1633}
1634
1635int
1637{
1638 io_fd_check_closed(f);
1639
1640 rb_thread_t *th = GET_THREAD();
1642
1643 switch (errno) {
1644 case EINTR:
1645#if defined(ERESTART)
1646 case ERESTART:
1647#endif
1648 /*
1649 * In old Linux, several special files under /proc and /sys don't handle
1650 * select properly. Thus we need avoid to call if don't use O_NONBLOCK.
1651 * Otherwise, we face nasty hang up. Sigh.
1652 * e.g. https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=31b07093c44a7a442394d44423e21d783f5523b8
1653 * https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=31b07093c44a7a442394d44423e21d783f5523b8
1654 * In EINTR case, we only need to call RUBY_VM_CHECK_INTS_BLOCKING().
1655 * Then rb_thread_check_ints() is enough.
1656 */
1658 return TRUE;
1659
1660 case EAGAIN:
1661#if EWOULDBLOCK != EAGAIN
1662 case EWOULDBLOCK:
1663#endif
1664 if (scheduler != Qnil) {
1665 return RTEST(
1666 rb_fiber_scheduler_io_wait_writable(scheduler, io_from_fd(f))
1667 );
1668 }
1669 else {
1670 io_wait_for_single_fd(f, RUBY_IO_WRITABLE, NULL, th, scheduler);
1671 }
1672 return TRUE;
1673
1674 default:
1675 return FALSE;
1676 }
1677}
1678
1679int
1680rb_wait_for_single_fd(int fd, int events, struct timeval *timeout)
1681{
1682 rb_thread_t *th = GET_THREAD();
1684 return io_wait_for_single_fd(fd, events, timeout, th, scheduler);
1685}
1686
1687int
1689{
1690 return rb_wait_for_single_fd(fd, RUBY_IO_READABLE, NULL);
1691}
1692
1693int
1695{
1696 return rb_wait_for_single_fd(fd, RUBY_IO_WRITABLE, NULL);
1697}
1698
1699VALUE
1700rb_io_maybe_wait(int error, VALUE io, VALUE events, VALUE timeout)
1701{
1702 // fptr->fd can be set to -1 at any time by another thread when the GVL is
1703 // released. Many code, e.g. `io_bufread` didn't check this correctly and
1704 // instead relies on `read(-1) -> -1` which causes this code path. We then
1705 // check here whether the IO was in fact closed. Probably it's better to
1706 // check that `fptr->fd != -1` before using it in syscall.
1707 rb_io_check_closed(RFILE(io)->fptr);
1708
1709 switch (error) {
1710 // In old Linux, several special files under /proc and /sys don't handle
1711 // select properly. Thus we need avoid to call if don't use O_NONBLOCK.
1712 // Otherwise, we face nasty hang up. Sigh.
1713 // e.g. https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=31b07093c44a7a442394d44423e21d783f5523b8
1714 // https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=31b07093c44a7a442394d44423e21d783f5523b8
1715 // In EINTR case, we only need to call RUBY_VM_CHECK_INTS_BLOCKING().
1716 // Then rb_thread_check_ints() is enough.
1717 case EINTR:
1718#if defined(ERESTART)
1719 case ERESTART:
1720#endif
1721 // We might have pending interrupts since the previous syscall was interrupted:
1723
1724 // The operation was interrupted, so retry it immediately:
1725 return events;
1726
1727 case EAGAIN:
1728#if EWOULDBLOCK != EAGAIN
1729 case EWOULDBLOCK:
1730#endif
1731 {
1732 // The operation would block, so wait for the specified events:
1733 VALUE result = rb_io_wait(io, events, timeout);
1734 // The scheduler may change errno while waiting. Preserve the original
1735 // error in case no events are ready and the caller reports the failure.
1736 errno = error;
1737 return result;
1738 }
1739
1740 default:
1741 // Non-specific error, no event is ready:
1742 return Qnil;
1743 }
1744}
1745
1746int
1748{
1749 VALUE result = rb_io_maybe_wait(error, io, RB_INT2NUM(RUBY_IO_READABLE), timeout);
1750
1751 if (RTEST(result)) {
1752 return RB_NUM2INT(result);
1753 }
1754 else if (result == RUBY_Qfalse) {
1755 rb_raise(rb_eIOTimeoutError, "Timed out waiting for IO to become readable!");
1756 }
1757
1758 return 0;
1759}
1760
1761int
1763{
1764 VALUE result = rb_io_maybe_wait(error, io, RB_INT2NUM(RUBY_IO_WRITABLE), timeout);
1765
1766 if (RTEST(result)) {
1767 return RB_NUM2INT(result);
1768 }
1769 else if (result == RUBY_Qfalse) {
1770 rb_raise(rb_eIOTimeoutError, "Timed out waiting for IO to become writable!");
1771 }
1772
1773 return 0;
1774}
1775
1776static void
1777make_writeconv(rb_io_t *fptr)
1778{
1779 if (!fptr->writeconv_initialized) {
1780 const char *senc, *denc;
1781 rb_encoding *enc;
1782 int ecflags;
1783 VALUE ecopts;
1784
1785 fptr->writeconv_initialized = 1;
1786
1788 ecopts = fptr->encs.ecopts;
1789
1790 if (!fptr->encs.enc || (rb_is_ascii8bit_enc(fptr->encs.enc) && !fptr->encs.enc2)) {
1791 /* no encoding conversion */
1792 fptr->writeconv_pre_ecflags = 0;
1793 fptr->writeconv_pre_ecopts = Qnil;
1794 fptr->writeconv = rb_econv_open_opts("", "", ecflags, ecopts);
1795 if (!fptr->writeconv)
1796 rb_exc_raise(rb_econv_open_exc("", "", ecflags));
1798 }
1799 else {
1800 enc = fptr->encs.enc2 ? fptr->encs.enc2 : fptr->encs.enc;
1801 senc = rb_econv_asciicompat_encoding(rb_enc_name(enc));
1802 if (!senc && !(fptr->encs.ecflags & ECONV_STATEFUL_DECORATOR_MASK)) {
1803 /* single conversion */
1804 fptr->writeconv_pre_ecflags = ecflags;
1805 fptr->writeconv_pre_ecopts = ecopts;
1806 fptr->writeconv = NULL;
1808 }
1809 else {
1810 /* double conversion */
1812 fptr->writeconv_pre_ecopts = ecopts;
1813 if (senc) {
1814 denc = rb_enc_name(enc);
1815 fptr->writeconv_asciicompat = rb_str_new2(senc);
1816 }
1817 else {
1818 senc = denc = "";
1819 fptr->writeconv_asciicompat = rb_str_new2(rb_enc_name(enc));
1820 }
1822 ecopts = fptr->encs.ecopts;
1823 fptr->writeconv = rb_econv_open_opts(senc, denc, ecflags, ecopts);
1824 if (!fptr->writeconv)
1825 rb_exc_raise(rb_econv_open_exc(senc, denc, ecflags));
1826 }
1827 }
1828 }
1829}
1830
1831/* writing functions */
1833 rb_io_t *fptr;
1834 const char *ptr;
1835 long length;
1836};
1837
1839 VALUE io;
1840 VALUE str;
1841 int nosync;
1842};
1843
1844#ifdef HAVE_WRITEV
1845static ssize_t
1846io_binwrite_string_internal(rb_io_t *fptr, const char *ptr, long length)
1847{
1848 if (fptr->wbuf.len) {
1849 struct iovec iov[2];
1850
1851 iov[0].iov_base = fptr->wbuf.ptr+fptr->wbuf.off;
1852 iov[0].iov_len = fptr->wbuf.len;
1853 iov[1].iov_base = (void*)ptr;
1854 iov[1].iov_len = length;
1855
1856 ssize_t result = rb_writev_internal(fptr, iov, 2);
1857
1858 if (result < 0)
1859 return result;
1860
1861 if (result >= fptr->wbuf.len) {
1862 // We wrote more than the internal buffer:
1863 result -= fptr->wbuf.len;
1864 fptr->wbuf.off = 0;
1865 fptr->wbuf.len = 0;
1866 }
1867 else {
1868 // We only wrote less data than the internal buffer:
1869 fptr->wbuf.off += (int)result;
1870 fptr->wbuf.len -= (int)result;
1871
1872 result = 0;
1873 }
1874
1875 return result;
1876 }
1877 else {
1878 return rb_io_write_memory(fptr, ptr, length);
1879 }
1880}
1881#else
1882static ssize_t
1883io_binwrite_string_internal(rb_io_t *fptr, const char *ptr, long length)
1884{
1885 long remaining = length;
1886
1887 if (fptr->wbuf.len) {
1888 if (fptr->wbuf.len+length <= fptr->wbuf.capa) {
1889 if (fptr->wbuf.capa < fptr->wbuf.off+fptr->wbuf.len+length) {
1890 MEMMOVE(fptr->wbuf.ptr, fptr->wbuf.ptr+fptr->wbuf.off, char, fptr->wbuf.len);
1891 fptr->wbuf.off = 0;
1892 }
1893
1894 MEMMOVE(fptr->wbuf.ptr+fptr->wbuf.off+fptr->wbuf.len, ptr, char, length);
1895 fptr->wbuf.len += (int)length;
1896
1897 // We copied the entire incoming data to the internal buffer:
1898 remaining = 0;
1899 }
1900
1901 // Flush the internal buffer:
1902 if (io_fflush(fptr) < 0) {
1903 return -1;
1904 }
1905
1906 // If all the data was buffered, we are done:
1907 if (remaining == 0) {
1908 return length;
1909 }
1910 }
1911
1912 // Otherwise, we should write the data directly:
1913 return rb_io_write_memory(fptr, ptr, length);
1914}
1915#endif
1916
1917static VALUE
1918io_binwrite_string(VALUE arg)
1919{
1920 struct binwrite_arg *p = (struct binwrite_arg *)arg;
1921
1922 const char *ptr = p->ptr;
1923 size_t remaining = p->length;
1924
1925 while (remaining) {
1926 // Write as much as possible:
1927 ssize_t result = io_binwrite_string_internal(p->fptr, ptr, remaining);
1928
1929 if (result == 0) {
1930 // If only the internal buffer is written, result will be zero [bytes of given data written]. This means we
1931 // should try again immediately.
1932 }
1933 else if (result > 0) {
1934 if ((size_t)result == remaining) break;
1935 ptr += result;
1936 remaining -= result;
1937 }
1938 // Wait for it to become writable:
1939 else if (rb_io_maybe_wait_writable(errno, p->fptr->self, RUBY_IO_TIMEOUT_DEFAULT)) {
1940 rb_io_check_closed(p->fptr);
1941 }
1942 else {
1943 // The error was unrelated to waiting for it to become writable, so we fail:
1944 return -1;
1945 }
1946 }
1947
1948 return p->length;
1949}
1950
1951inline static void
1952io_allocate_write_buffer(rb_io_t *fptr, int sync)
1953{
1954 if (fptr->wbuf.ptr == NULL && !(sync && (fptr->mode & FMODE_SYNC))) {
1955 fptr->wbuf.off = 0;
1956 fptr->wbuf.len = 0;
1957 fptr->wbuf.capa = IO_WBUF_CAPA_MIN;
1958 fptr->wbuf.ptr = ALLOC_N(char, fptr->wbuf.capa);
1959 }
1960
1961 if (NIL_P(fptr->write_lock)) {
1962 fptr->write_lock = rb_mutex_new();
1963 rb_mutex_allow_trap(fptr->write_lock, 1);
1964 }
1965}
1966
1967static inline int
1968io_binwrite_requires_flush_write(rb_io_t *fptr, long len, int nosync)
1969{
1970 // If the requested operation was synchronous and the output mode is synchronous or a TTY:
1971 if (!nosync && (fptr->mode & (FMODE_SYNC|FMODE_TTY)))
1972 return 1;
1973
1974 // If the amount of data we want to write exceeds the internal buffer:
1975 if (fptr->wbuf.ptr && fptr->wbuf.capa <= fptr->wbuf.len + len)
1976 return 1;
1977
1978 // Otherwise, we can append to the internal buffer:
1979 return 0;
1980}
1981
1982static long
1983io_binwrite(const char *ptr, long len, rb_io_t *fptr, int nosync)
1984{
1985 if (len <= 0) return len;
1986
1987 // Don't write anything if current thread has a pending interrupt:
1989
1990 io_allocate_write_buffer(fptr, !nosync);
1991
1992 if (io_binwrite_requires_flush_write(fptr, len, nosync)) {
1993 struct binwrite_arg arg;
1994
1995 arg.fptr = fptr;
1996 arg.ptr = ptr;
1997 arg.length = len;
1998
1999 if (!NIL_P(fptr->write_lock)) {
2000 return rb_mutex_synchronize(fptr->write_lock, io_binwrite_string, (VALUE)&arg);
2001 }
2002 else {
2003 return io_binwrite_string((VALUE)&arg);
2004 }
2005 }
2006 else {
2007 if (fptr->wbuf.off) {
2008 if (fptr->wbuf.len)
2009 MEMMOVE(fptr->wbuf.ptr, fptr->wbuf.ptr+fptr->wbuf.off, char, fptr->wbuf.len);
2010 fptr->wbuf.off = 0;
2011 }
2012
2013 MEMMOVE(fptr->wbuf.ptr+fptr->wbuf.off+fptr->wbuf.len, ptr, char, len);
2014 fptr->wbuf.len += (int)len;
2015
2016 return len;
2017 }
2018}
2019
2020# define MODE_BTMODE(a,b,c) ((fmode & FMODE_BINMODE) ? (b) : \
2021 (fmode & FMODE_TEXTMODE) ? (c) : (a))
2022
2023#define MODE_BTXMODE(a, b, c, d, e, f) ((fmode & FMODE_EXCL) ? \
2024 MODE_BTMODE(d, e, f) : \
2025 MODE_BTMODE(a, b, c))
2026
2027static VALUE
2028do_writeconv(VALUE str, rb_io_t *fptr, int *converted)
2029{
2030 if (NEED_WRITECONV(fptr)) {
2031 VALUE common_encoding = Qnil;
2032 SET_BINARY_MODE(fptr);
2033
2034 make_writeconv(fptr);
2035
2036 if (fptr->writeconv) {
2037#define fmode (fptr->mode)
2038 if (!NIL_P(fptr->writeconv_asciicompat))
2039 common_encoding = fptr->writeconv_asciicompat;
2040 else if (MODE_BTMODE(DEFAULT_TEXTMODE,0,1) && !rb_enc_asciicompat(rb_enc_get(str))) {
2041 rb_raise(rb_eArgError, "ASCII incompatible string written for text mode IO without encoding conversion: %s",
2042 rb_enc_name(rb_enc_get(str)));
2043 }
2044#undef fmode
2045 }
2046 else {
2047 if (fptr->encs.enc2)
2048 common_encoding = rb_enc_from_encoding(fptr->encs.enc2);
2049 else if (fptr->encs.enc != rb_ascii8bit_encoding())
2050 common_encoding = rb_enc_from_encoding(fptr->encs.enc);
2051 }
2052
2053 if (!NIL_P(common_encoding)) {
2054 str = rb_str_encode(str, common_encoding,
2056 *converted = 1;
2057 }
2058
2059 if (fptr->writeconv) {
2061 *converted = 1;
2062 }
2063 }
2064#if RUBY_CRLF_ENVIRONMENT
2065#define fmode (fptr->mode)
2066 else if (MODE_BTMODE(DEFAULT_TEXTMODE,0,1)) {
2067 if ((fptr->mode & FMODE_READABLE) &&
2069 setmode(fptr->fd, O_BINARY);
2070 }
2071 else {
2072 setmode(fptr->fd, O_TEXT);
2073 }
2074 if (!rb_enc_asciicompat(rb_enc_get(str))) {
2075 rb_raise(rb_eArgError, "ASCII incompatible string written for text mode IO without encoding conversion: %s",
2076 rb_enc_name(rb_enc_get(str)));
2077 }
2078 }
2079#undef fmode
2080#endif
2081 return str;
2082}
2083
2084static long
2085io_fwrite(VALUE str, rb_io_t *fptr, int nosync)
2086{
2087 int converted = 0;
2088 VALUE tmp;
2089 long n, len;
2090 const char *ptr;
2091
2092#ifdef _WIN32
2093 if (fptr->mode & FMODE_TTY) {
2094 long len = rb_w32_write_console(str, fptr->fd);
2095 if (len > 0) return len;
2096 }
2097#endif
2098
2099 str = do_writeconv(str, fptr, &converted);
2100 if (converted)
2101 OBJ_FREEZE(str);
2102
2103 tmp = rb_str_tmp_frozen_no_embed_acquire(str);
2104 RSTRING_GETMEM(tmp, ptr, len);
2105 n = io_binwrite(ptr, len, fptr, nosync);
2106 rb_str_tmp_frozen_release(str, tmp);
2107
2108 return n;
2109}
2110
2111ssize_t
2112rb_io_bufwrite(VALUE io, const void *buf, size_t size)
2113{
2114 rb_io_t *fptr;
2115
2116 GetOpenFile(io, fptr);
2118 return (ssize_t)io_binwrite(buf, (long)size, fptr, 0);
2119}
2120
2121static VALUE
2122io_write(VALUE io, VALUE str, int nosync)
2123{
2124 rb_io_t *fptr;
2125 long n;
2126 VALUE tmp;
2127
2128 io = GetWriteIO(io);
2129 str = rb_obj_as_string(str);
2130 tmp = rb_io_check_io(io);
2131
2132 if (NIL_P(tmp)) {
2133 /* port is not IO, call write method for it. */
2134 return rb_funcall(io, id_write, 1, str);
2135 }
2136
2137 io = tmp;
2138 if (RSTRING_LEN(str) == 0) return INT2FIX(0);
2139
2140 GetOpenFile(io, fptr);
2142
2143 n = io_fwrite(str, fptr, nosync);
2144 if (n < 0L) rb_sys_fail_on_write(fptr);
2145
2146 return LONG2FIX(n);
2147}
2148
2149#ifdef HAVE_WRITEV
2150struct binwritev_arg {
2151 rb_io_t *fptr;
2152 struct iovec *iov;
2153 int iovcnt;
2154 size_t total;
2155};
2156
2157static VALUE
2158io_binwritev_internal(VALUE arg)
2159{
2160 struct binwritev_arg *p = (struct binwritev_arg *)arg;
2161
2162 size_t remaining = p->total;
2163 size_t offset = 0;
2164
2165 rb_io_t *fptr = p->fptr;
2166 struct iovec *iov = p->iov;
2167 int iovcnt = p->iovcnt;
2168
2169 while (remaining) {
2170 long result = rb_writev_internal(fptr, iov, iovcnt);
2171
2172 if (result >= 0) {
2173 offset += result;
2174 if (fptr->wbuf.ptr && fptr->wbuf.len) {
2175 if (offset < (size_t)fptr->wbuf.len) {
2176 fptr->wbuf.off += result;
2177 fptr->wbuf.len -= result;
2178 }
2179 else {
2180 offset -= (size_t)fptr->wbuf.len;
2181 fptr->wbuf.off = 0;
2182 fptr->wbuf.len = 0;
2183 }
2184 }
2185
2186 if (offset == p->total) {
2187 return p->total;
2188 }
2189
2190 while (result >= (ssize_t)iov->iov_len) {
2191 /* iovcnt > 0 */
2192 result -= iov->iov_len;
2193 iov->iov_len = 0;
2194 iov++;
2195
2196 if (!--iovcnt) {
2197 // I don't believe this code path can ever occur.
2198 return offset;
2199 }
2200 }
2201
2202 iov->iov_base = (char *)iov->iov_base + result;
2203 iov->iov_len -= result;
2204 }
2205 else if (rb_io_maybe_wait_writable(errno, fptr->self, RUBY_IO_TIMEOUT_DEFAULT)) {
2206 rb_io_check_closed(fptr);
2207 }
2208 else {
2209 return -1;
2210 }
2211 }
2212
2213 return offset;
2214}
2215
2216static long
2217io_binwritev(struct iovec *iov, int iovcnt, rb_io_t *fptr)
2218{
2219 // Don't write anything if current thread has a pending interrupt:
2221
2222 if (iovcnt == 0) return 0;
2223
2224 size_t total = 0;
2225 for (int i = 1; i < iovcnt; i++) total += iov[i].iov_len;
2226
2227 io_allocate_write_buffer(fptr, 1);
2228
2229 if (fptr->wbuf.ptr && fptr->wbuf.len) {
2230 // The end of the buffered data:
2231 size_t offset = fptr->wbuf.off + fptr->wbuf.len;
2232
2233 if (offset + total <= (size_t)fptr->wbuf.capa) {
2234 for (int i = 1; i < iovcnt; i++) {
2235 memcpy(fptr->wbuf.ptr+offset, iov[i].iov_base, iov[i].iov_len);
2236 offset += iov[i].iov_len;
2237 }
2238
2239 fptr->wbuf.len += total;
2240
2241 return total;
2242 }
2243 else {
2244 iov[0].iov_base = fptr->wbuf.ptr + fptr->wbuf.off;
2245 iov[0].iov_len = fptr->wbuf.len;
2246 }
2247 }
2248 else {
2249 // The first iov is reserved for the internal buffer, and it's empty.
2250 iov++;
2251
2252 if (!--iovcnt) {
2253 // If there are no other io vectors we are done.
2254 return 0;
2255 }
2256 }
2257
2258 struct binwritev_arg arg;
2259 arg.fptr = fptr;
2260 arg.iov = iov;
2261 arg.iovcnt = iovcnt;
2262 arg.total = total;
2263
2264 if (!NIL_P(fptr->write_lock)) {
2265 return rb_mutex_synchronize(fptr->write_lock, io_binwritev_internal, (VALUE)&arg);
2266 }
2267 else {
2268 return io_binwritev_internal((VALUE)&arg);
2269 }
2270}
2271
2272static long
2273io_fwritev(int argc, const VALUE *argv, rb_io_t *fptr)
2274{
2275 int i, converted, iovcnt = argc + 1;
2276 long n;
2277 VALUE v1, v2, str, tmp, *tmp_array;
2278 struct iovec *iov;
2279
2280 iov = ALLOCV_N(struct iovec, v1, iovcnt);
2281 tmp_array = ALLOCV_N(VALUE, v2, argc);
2282
2283 for (i = 0; i < argc; i++) {
2284 str = rb_obj_as_string(argv[i]);
2285 converted = 0;
2286 str = do_writeconv(str, fptr, &converted);
2287
2288 if (converted)
2289 OBJ_FREEZE(str);
2290
2291 tmp = rb_str_tmp_frozen_acquire(str);
2292 tmp_array[i] = tmp;
2293
2294 /* iov[0] is reserved for buffer of fptr */
2295 iov[i+1].iov_base = RSTRING_PTR(tmp);
2296 iov[i+1].iov_len = RSTRING_LEN(tmp);
2297 }
2298
2299 n = io_binwritev(iov, iovcnt, fptr);
2300 if (v1) ALLOCV_END(v1);
2301
2302 for (i = 0; i < argc; i++) {
2303 rb_str_tmp_frozen_release(argv[i], tmp_array[i]);
2304 }
2305
2306 if (v2) ALLOCV_END(v2);
2307
2308 return n;
2309}
2310
2311static int
2312iovcnt_ok(int iovcnt)
2313{
2314#ifdef IOV_MAX
2315 return iovcnt < IOV_MAX;
2316#else /* GNU/Hurd has writev, but no IOV_MAX */
2317 return 1;
2318#endif
2319}
2320#endif /* HAVE_WRITEV */
2321
2322static VALUE
2323io_writev(int argc, const VALUE *argv, VALUE io)
2324{
2325 rb_io_t *fptr;
2326 long n;
2327 VALUE tmp, total = INT2FIX(0);
2328 int i, cnt = 1;
2329
2330 io = GetWriteIO(io);
2331 tmp = rb_io_check_io(io);
2332
2333 if (NIL_P(tmp)) {
2334 /* port is not IO, call write method for it. */
2335 return rb_funcallv(io, id_write, argc, argv);
2336 }
2337
2338 io = tmp;
2339
2340 GetOpenFile(io, fptr);
2342
2343 for (i = 0; i < argc; i += cnt) {
2344#ifdef HAVE_WRITEV
2345 if ((fptr->mode & (FMODE_SYNC|FMODE_TTY)) && iovcnt_ok(cnt = argc - i)) {
2346 n = io_fwritev(cnt, &argv[i], fptr);
2347 }
2348 else
2349#endif
2350 {
2351 cnt = 1;
2352 /* sync at last item */
2353 n = io_fwrite(rb_obj_as_string(argv[i]), fptr, (i < argc-1));
2354 }
2355
2356 if (n < 0L)
2357 rb_sys_fail_on_write(fptr);
2358
2359 total = rb_fix_plus(LONG2FIX(n), total);
2360 }
2361
2362 return total;
2363}
2364
2365/*
2366 * call-seq:
2367 * write(*objects) -> integer
2368 *
2369 * Writes each of the given +objects+ to +self+,
2370 * which must be opened for writing
2371 * (see {Access Modes}[rdoc-ref:File@Access+Modes]);
2372 * returns the total number bytes written;
2373 * each of +objects+ that is not a string is converted via method +to_s+:
2374 *
2375 * $stdout.write('Hello', ', ', 'World!', "\n") # => 14
2376 * $stdout.write('foo', :bar, 2, "\n") # => 8
2377 *
2378 * Output:
2379 *
2380 * Hello, World!
2381 * foobar2
2382 *
2383 * Related: IO#read.
2384 */
2385
2386static VALUE
2387io_write_m(int argc, VALUE *argv, VALUE io)
2388{
2389 if (argc != 1) {
2390 return io_writev(argc, argv, io);
2391 }
2392 else {
2393 VALUE str = argv[0];
2394 return io_write(io, str, 0);
2395 }
2396}
2397
2398VALUE
2399rb_io_write(VALUE io, VALUE str)
2400{
2401 return rb_funcallv(io, id_write, 1, &str);
2402}
2403
2404static VALUE
2405rb_io_writev(VALUE io, int argc, const VALUE *argv)
2406{
2407 if (argc > 1 && rb_obj_method_arity(io, id_write) == 1) {
2408 if (io != rb_ractor_stderr() && RTEST(ruby_verbose)) {
2409 VALUE klass = CLASS_OF(io);
2410 char sep = RCLASS_SINGLETON_P(klass) ? (klass = io, '.') : '#';
2412 RB_WARN_CATEGORY_DEPRECATED, "%+"PRIsVALUE"%c""write is outdated interface"
2413 " which accepts just one argument",
2414 klass, sep
2415 );
2416 }
2417
2418 do rb_io_write(io, *argv++); while (--argc);
2419
2420 return Qnil;
2421 }
2422
2423 return rb_funcallv(io, id_write, argc, argv);
2424}
2425
2426/*
2427 * call-seq:
2428 * self << object -> self
2429 *
2430 * Writes the given +object+ to +self+,
2431 * which must be opened for writing (see {Access Modes}[rdoc-ref:File@Access+Modes]);
2432 * returns +self+;
2433 * if +object+ is not a string, it is converted via method +to_s+:
2434 *
2435 * $stdout << 'Hello' << ', ' << 'World!' << "\n"
2436 * $stdout << 'foo' << :bar << 2 << "\n"
2437 *
2438 * Output:
2439 *
2440 * Hello, World!
2441 * foobar2
2442 *
2443 */
2444
2445
2446VALUE
2448{
2449 rb_io_write(io, str);
2450 return io;
2451}
2452
2453#ifdef HAVE_FSYNC
2454static VALUE
2455nogvl_fsync(void *ptr)
2456{
2457 rb_io_t *fptr = ptr;
2458
2459#ifdef _WIN32
2460 if (GetFileType((HANDLE)rb_w32_get_osfhandle(fptr->fd)) != FILE_TYPE_DISK)
2461 return 0;
2462#endif
2463 return (VALUE)fsync(fptr->fd);
2464}
2465#endif
2466
2467VALUE
2468rb_io_flush_raw(VALUE io, int sync)
2469{
2470 rb_io_t *fptr;
2471
2472 if (!RB_TYPE_P(io, T_FILE)) {
2473 return rb_funcall(io, id_flush, 0);
2474 }
2475
2476 io = GetWriteIO(io);
2477 GetOpenFile(io, fptr);
2478
2479 if (fptr->mode & FMODE_WRITABLE) {
2480 if (io_fflush(fptr) < 0)
2481 rb_sys_fail_on_write(fptr);
2482 }
2483 if (fptr->mode & FMODE_READABLE) {
2484 io_unread(fptr, true);
2485 }
2486
2487 return io;
2488}
2489
2490/*
2491 * call-seq:
2492 * flush -> self
2493 *
2494 * Flushes data buffered in +self+ to the operating system
2495 * (but does not necessarily flush data buffered in the operating system):
2496 *
2497 * $stdout.print 'no newline' # Not necessarily flushed.
2498 * $stdout.flush # Flushed.
2499 *
2500 */
2501
2502VALUE
2503rb_io_flush(VALUE io)
2504{
2505 return rb_io_flush_raw(io, 1);
2506}
2507
2508/*
2509 * call-seq:
2510 * tell -> integer
2511 *
2512 * Returns the current position (in bytes) in +self+
2513 * (see {Position}[rdoc-ref:IO@Position]):
2514 *
2515 * f = File.open('t.txt')
2516 * f.tell # => 0
2517 * f.gets # => "First line\n"
2518 * f.tell # => 12
2519 * f.close
2520 *
2521 * Related: IO#pos=, IO#seek.
2522 */
2523
2524static VALUE
2525rb_io_tell(VALUE io)
2526{
2527 rb_io_t *fptr;
2528 rb_off_t pos;
2529
2530 GetOpenFile(io, fptr);
2531 pos = io_tell(fptr);
2532 if (pos < 0 && errno) rb_sys_fail_path(fptr->pathv);
2533 pos -= fptr->rbuf.len;
2534 return OFFT2NUM(pos);
2535}
2536
2537static VALUE
2538rb_io_seek(VALUE io, VALUE offset, int whence)
2539{
2540 rb_io_t *fptr;
2541 rb_off_t pos;
2542
2543 pos = NUM2OFFT(offset);
2544 GetOpenFile(io, fptr);
2545 pos = io_seek(fptr, pos, whence);
2546 if (pos < 0 && errno) rb_sys_fail_path(fptr->pathv);
2547
2548 return INT2FIX(0);
2549}
2550
2551static int
2552interpret_seek_whence(VALUE vwhence)
2553{
2554 if (vwhence == sym_SET)
2555 return SEEK_SET;
2556 if (vwhence == sym_CUR)
2557 return SEEK_CUR;
2558 if (vwhence == sym_END)
2559 return SEEK_END;
2560#ifdef SEEK_DATA
2561 if (vwhence == sym_DATA)
2562 return SEEK_DATA;
2563#endif
2564#ifdef SEEK_HOLE
2565 if (vwhence == sym_HOLE)
2566 return SEEK_HOLE;
2567#endif
2568 return NUM2INT(vwhence);
2569}
2570
2571/*
2572 * call-seq:
2573 * seek(offset, whence = IO::SEEK_SET) -> 0
2574 *
2575 * Seeks to the position given by integer +offset+
2576 * (see {Position}[rdoc-ref:IO@Position])
2577 * and constant +whence+, which is one of:
2578 *
2579 * - +:CUR+ or <tt>IO::SEEK_CUR</tt>:
2580 * Repositions the stream to its current position plus the given +offset+:
2581 *
2582 * f = File.open('t.txt')
2583 * f.tell # => 0
2584 * f.seek(20, :CUR) # => 0
2585 * f.tell # => 20
2586 * f.seek(-10, :CUR) # => 0
2587 * f.tell # => 10
2588 * f.close
2589 *
2590 * - +:END+ or <tt>IO::SEEK_END</tt>:
2591 * Repositions the stream to its end plus the given +offset+:
2592 *
2593 * f = File.open('t.txt')
2594 * f.tell # => 0
2595 * f.seek(0, :END) # => 0 # Repositions to stream end.
2596 * f.tell # => 52
2597 * f.seek(-20, :END) # => 0
2598 * f.tell # => 32
2599 * f.seek(-40, :END) # => 0
2600 * f.tell # => 12
2601 * f.close
2602 *
2603 * - +:SET+ or <tt>IO:SEEK_SET</tt>:
2604 * Repositions the stream to the given +offset+:
2605 *
2606 * f = File.open('t.txt')
2607 * f.tell # => 0
2608 * f.seek(20, :SET) # => 0
2609 * f.tell # => 20
2610 * f.seek(40, :SET) # => 0
2611 * f.tell # => 40
2612 * f.close
2613 *
2614 * Related: IO#pos=, IO#tell.
2615 *
2616 */
2617
2618static VALUE
2619rb_io_seek_m(int argc, VALUE *argv, VALUE io)
2620{
2621 VALUE offset, ptrname;
2622 int whence = SEEK_SET;
2623
2624 if (rb_scan_args(argc, argv, "11", &offset, &ptrname) == 2) {
2625 whence = interpret_seek_whence(ptrname);
2626 }
2627
2628 return rb_io_seek(io, offset, whence);
2629}
2630
2631/*
2632 * call-seq:
2633 * pos = new_position -> new_position
2634 *
2635 * Seeks to the given +new_position+ (in bytes);
2636 * see {Position}[rdoc-ref:IO@Position]:
2637 *
2638 * f = File.open('t.txt')
2639 * f.tell # => 0
2640 * f.pos = 20 # => 20
2641 * f.tell # => 20
2642 * f.close
2643 *
2644 * Related: IO#seek, IO#tell.
2645 *
2646 */
2647
2648static VALUE
2649rb_io_set_pos(VALUE io, VALUE offset)
2650{
2651 rb_io_t *fptr;
2652 rb_off_t pos;
2653
2654 pos = NUM2OFFT(offset);
2655 GetOpenFile(io, fptr);
2656 pos = io_seek(fptr, pos, SEEK_SET);
2657 if (pos < 0 && errno) rb_sys_fail_path(fptr->pathv);
2658
2659 return OFFT2NUM(pos);
2660}
2661
2662static void clear_readconv(rb_io_t *fptr);
2663
2664/*
2665 * call-seq:
2666 * rewind -> 0
2667 *
2668 * Repositions the stream to its beginning,
2669 * setting both the position and the line number to zero;
2670 * see {Position}[rdoc-ref:IO@Position]
2671 * and {Line Number}[rdoc-ref:IO@Line+Number]:
2672 *
2673 * f = File.open('t.txt')
2674 * f.tell # => 0
2675 * f.lineno # => 0
2676 * f.gets # => "First line\n"
2677 * f.tell # => 12
2678 * f.lineno # => 1
2679 * f.rewind # => 0
2680 * f.tell # => 0
2681 * f.lineno # => 0
2682 * f.close
2683 *
2684 * Note that this method cannot be used with streams such as pipes, ttys, and sockets.
2685 *
2686 */
2687
2688static VALUE
2689rb_io_rewind(VALUE io)
2690{
2691 rb_io_t *fptr;
2692
2693 GetOpenFile(io, fptr);
2694 if (io_seek(fptr, 0L, 0) < 0 && errno) rb_sys_fail_path(fptr->pathv);
2695 if (io == ARGF.current_file) {
2696 ARGF.lineno -= fptr->lineno;
2697 }
2698 fptr->lineno = 0;
2699 if (fptr->readconv) {
2700 clear_readconv(fptr);
2701 }
2702
2703 return INT2FIX(0);
2704}
2705
2706static int
2707fptr_wait_readable(rb_io_t *fptr)
2708{
2709 int result = rb_io_maybe_wait_readable(errno, fptr->self, RUBY_IO_TIMEOUT_DEFAULT);
2710
2711 if (result)
2712 rb_io_check_closed(fptr);
2713
2714 return result;
2715}
2716
2717static int
2718io_fillbuf(rb_io_t *fptr)
2719{
2720 ssize_t r;
2721
2722 if (fptr->rbuf.ptr == NULL) {
2723 fptr->rbuf.off = 0;
2724 fptr->rbuf.len = 0;
2725 fptr->rbuf.capa = IO_RBUF_CAPA_FOR(fptr);
2726 fptr->rbuf.ptr = ALLOC_N(char, fptr->rbuf.capa);
2727 }
2728 if (fptr->rbuf.len == 0) {
2729 retry:
2730 r = rb_io_read_memory(fptr, fptr->rbuf.ptr, fptr->rbuf.capa);
2731
2732 if (r < 0) {
2733 if (fptr_wait_readable(fptr))
2734 goto retry;
2735
2736 int e = errno;
2737 VALUE path = rb_sprintf("fd:%d ", fptr->fd);
2738 if (!NIL_P(fptr->pathv)) {
2739 rb_str_append(path, fptr->pathv);
2740 }
2741
2742 rb_syserr_fail_path(e, path);
2743 }
2744 if (r > 0) rb_io_check_closed(fptr);
2745 fptr->rbuf.off = 0;
2746 fptr->rbuf.len = (int)r; /* r should be <= rbuf_capa */
2747 if (r == 0)
2748 return -1; /* EOF */
2749 }
2750 return 0;
2751}
2752
2753/*
2754 * call-seq:
2755 * eof -> true or false
2756 *
2757 * Returns +true+ if the stream is positioned at its end, +false+ otherwise;
2758 * see {Position}[rdoc-ref:IO@Position]:
2759 *
2760 * f = File.open('t.txt')
2761 * f.eof # => false
2762 * f.seek(0, :END) # => 0
2763 * f.eof # => true
2764 * f.close
2765 *
2766 * Raises an exception unless the stream is opened for reading;
2767 * see {Mode}[rdoc-ref:File@Access+Modes].
2768 *
2769 * If +self+ is a stream such as pipe or socket, this method
2770 * blocks until the other end sends some data or closes it:
2771 *
2772 * r, w = IO.pipe
2773 * Thread.new { sleep 1; w.close }
2774 * r.eof? # => true # After 1-second wait.
2775 *
2776 * r, w = IO.pipe
2777 * Thread.new { sleep 1; w.puts "a" }
2778 * r.eof? # => false # After 1-second wait.
2779 *
2780 * r, w = IO.pipe
2781 * r.eof? # blocks forever
2782 *
2783 * Note that this method reads data to the input byte buffer. So
2784 * IO#sysread may not behave as you intend with IO#eof?, unless you
2785 * call IO#rewind first (which is not available for some streams).
2786 */
2787
2788VALUE
2790{
2791 rb_io_t *fptr;
2792
2793 GetOpenFile(io, fptr);
2795
2796 if (READ_CHAR_PENDING(fptr)) return Qfalse;
2797 if (READ_DATA_PENDING(fptr)) return Qfalse;
2798 READ_CHECK(fptr);
2799#if RUBY_CRLF_ENVIRONMENT
2800 if (!NEED_READCONV(fptr) && NEED_NEWLINE_DECORATOR_ON_READ(fptr)) {
2801 return RBOOL(eof(fptr->fd));
2802 }
2803#endif
2804 return RBOOL(io_fillbuf(fptr) < 0);
2805}
2806
2807/*
2808 * call-seq:
2809 * sync -> true or false
2810 *
2811 * Returns the current sync mode of the stream.
2812 * When sync mode is true, all output is immediately flushed to the underlying
2813 * operating system and is not buffered by Ruby internally. See also #fsync.
2814 *
2815 * f = File.open('t.tmp', 'w')
2816 * f.sync # => false
2817 * f.sync = true
2818 * f.sync # => true
2819 * f.close
2820 *
2821 */
2822
2823static VALUE
2824rb_io_sync(VALUE io)
2825{
2826 rb_io_t *fptr;
2827
2828 io = GetWriteIO(io);
2829 GetOpenFile(io, fptr);
2830 return RBOOL(fptr->mode & FMODE_SYNC);
2831}
2832
2833#ifdef HAVE_FSYNC
2834
2835/*
2836 * call-seq:
2837 * sync = boolean -> boolean
2838 *
2839 * Sets the _sync_ _mode_ for the stream to the given value;
2840 * returns the given value.
2841 *
2842 * Values for the sync mode:
2843 *
2844 * - +true+: All output is immediately flushed to the
2845 * underlying operating system and is not buffered internally.
2846 * - +false+: Output may be buffered internally.
2847 *
2848 * Example;
2849 *
2850 * f = File.open('t.tmp', 'w')
2851 * f.sync # => false
2852 * f.sync = true
2853 * f.sync # => true
2854 * f.close
2855 *
2856 * Related: IO#fsync.
2857 *
2858 */
2859
2860static VALUE
2861rb_io_set_sync(VALUE io, VALUE sync)
2862{
2863 rb_io_t *fptr;
2864
2865 io = GetWriteIO(io);
2866 GetOpenFile(io, fptr);
2867 if (RTEST(sync)) {
2868 fptr->mode |= FMODE_SYNC;
2869 }
2870 else {
2871 fptr->mode &= ~FMODE_SYNC;
2872 }
2873 return sync;
2874}
2875
2876/*
2877 * call-seq:
2878 * fsync -> 0
2879 *
2880 * Immediately writes to disk all data buffered in the stream,
2881 * via the operating system's <tt>fsync(2)</tt>.
2882
2883 * Note this difference:
2884 *
2885 * - IO#sync=: Ensures that data is flushed from the stream's internal buffers,
2886 * but does not guarantee that the operating system actually writes the data to disk.
2887 * - IO#fsync: Ensures both that data is flushed from internal buffers,
2888 * and that data is written to disk.
2889 *
2890 * Raises an exception if the operating system does not support <tt>fsync(2)</tt>.
2891 *
2892 */
2893
2894static VALUE
2895rb_io_fsync(VALUE io)
2896{
2897 rb_io_t *fptr;
2898
2899 io = GetWriteIO(io);
2900 GetOpenFile(io, fptr);
2901
2902 if (io_fflush(fptr) < 0)
2903 rb_sys_fail_on_write(fptr);
2904
2905 if ((int)rb_io_blocking_region(fptr, nogvl_fsync, fptr))
2906 rb_sys_fail_path(fptr->pathv);
2907
2908 return INT2FIX(0);
2909}
2910#else
2911# define rb_io_fsync rb_f_notimplement
2912# define rb_io_sync rb_f_notimplement
2913static VALUE
2914rb_io_set_sync(VALUE io, VALUE sync)
2915{
2918}
2919#endif
2920
2921#ifdef HAVE_FDATASYNC
2922static VALUE
2923nogvl_fdatasync(void *ptr)
2924{
2925 rb_io_t *fptr = ptr;
2926
2927#ifdef _WIN32
2928 if (GetFileType((HANDLE)rb_w32_get_osfhandle(fptr->fd)) != FILE_TYPE_DISK)
2929 return 0;
2930#endif
2931 return (VALUE)fdatasync(fptr->fd);
2932}
2933
2934/*
2935 * call-seq:
2936 * fdatasync -> 0
2937 *
2938 * Immediately writes to disk all data buffered in the stream,
2939 * via the operating system's: <tt>fdatasync(2)</tt>, if supported,
2940 * otherwise via <tt>fsync(2)</tt>, if supported;
2941 * otherwise raises an exception.
2942 *
2943 */
2944
2945static VALUE
2946rb_io_fdatasync(VALUE io)
2947{
2948 rb_io_t *fptr;
2949
2950 io = GetWriteIO(io);
2951 GetOpenFile(io, fptr);
2952
2953 if (io_fflush(fptr) < 0)
2954 rb_sys_fail_on_write(fptr);
2955
2956 if ((int)rb_io_blocking_region(fptr, nogvl_fdatasync, fptr) == 0)
2957 return INT2FIX(0);
2958
2959 /* fall back */
2960 return rb_io_fsync(io);
2961}
2962#else
2963#define rb_io_fdatasync rb_io_fsync
2964#endif
2965
2966/*
2967 * call-seq:
2968 * fileno -> integer
2969 *
2970 * Returns the integer file descriptor for the stream:
2971 *
2972 * $stdin.fileno # => 0
2973 * $stdout.fileno # => 1
2974 * $stderr.fileno # => 2
2975 * File.open('t.txt').fileno # => 10
2976 * f.close
2977 *
2978 */
2979
2980static VALUE
2981rb_io_fileno(VALUE io)
2982{
2983 rb_io_t *fptr = RFILE(io)->fptr;
2984 int fd;
2985
2986 rb_io_check_closed(fptr);
2987 fd = fptr->fd;
2988 return INT2FIX(fd);
2989}
2990
2991int
2993{
2994 if (RB_TYPE_P(io, T_FILE)) {
2995 rb_io_t *fptr = RFILE(io)->fptr;
2996 rb_io_check_closed(fptr);
2997 return fptr->fd;
2998 }
2999 else {
3000 VALUE fileno = rb_check_funcall(io, id_fileno, 0, NULL);
3001 if (!UNDEF_P(fileno)) {
3002 return RB_NUM2INT(fileno);
3003 }
3004 }
3005
3006 rb_raise(rb_eTypeError, "expected IO or #fileno, %"PRIsVALUE" given", rb_obj_class(io));
3007
3009}
3010
3011int
3012rb_io_mode(VALUE io)
3013{
3014 rb_io_t *fptr;
3015 GetOpenFile(io, fptr);
3016 return fptr->mode;
3017}
3018
3019/*
3020 * call-seq:
3021 * pid -> integer or nil
3022 *
3023 * Returns the process ID of a child process associated with the stream,
3024 * which will have been set by IO#popen, or +nil+ if the stream was not
3025 * created by IO#popen:
3026 *
3027 * pipe = IO.popen("-")
3028 * if pipe
3029 * $stderr.puts "In parent, child pid is #{pipe.pid}"
3030 * else
3031 * $stderr.puts "In child, pid is #{$$}"
3032 * end
3033 *
3034 * Output:
3035 *
3036 * In child, pid is 26209
3037 * In parent, child pid is 26209
3038 *
3039 */
3040
3041static VALUE
3042rb_io_pid(VALUE io)
3043{
3044 rb_io_t *fptr;
3045
3046 GetOpenFile(io, fptr);
3047 if (!fptr->pid)
3048 return Qnil;
3049 return PIDT2NUM(fptr->pid);
3050}
3051
3052/*
3053 * call-seq:
3054 * path -> string or nil
3055 *
3056 * Returns the path associated with the IO, or +nil+ if there is no path
3057 * associated with the IO. It is not guaranteed that the path exists on
3058 * the filesystem.
3059 *
3060 * $stdin.path # => "<STDIN>"
3061 *
3062 * File.open("testfile") {|f| f.path} # => "testfile"
3063 */
3064
3065VALUE
3067{
3068 rb_io_t *fptr = RFILE(io)->fptr;
3069
3070 if (!fptr)
3071 return Qnil;
3072
3073 return rb_obj_dup(fptr->pathv);
3074}
3075
3076/*
3077 * call-seq:
3078 * inspect -> string
3079 *
3080 * Returns a string representation of +self+:
3081 *
3082 * f = File.open('t.txt')
3083 * f.inspect # => "#<File:t.txt>"
3084 * f.close
3085 *
3086 */
3087
3088static VALUE
3089rb_io_inspect(VALUE obj)
3090{
3091 rb_io_t *fptr;
3092 VALUE result;
3093 static const char closed[] = " (closed)";
3094
3095 fptr = RFILE(obj)->fptr;
3096 if (!fptr) return rb_any_to_s(obj);
3097 result = rb_str_new_cstr("#<");
3098 rb_str_append(result, rb_class_name(CLASS_OF(obj)));
3099 rb_str_cat2(result, ":");
3100 if (NIL_P(fptr->pathv)) {
3101 if (fptr->fd < 0) {
3102 rb_str_cat(result, closed+1, strlen(closed)-1);
3103 }
3104 else {
3105 rb_str_catf(result, "fd %d", fptr->fd);
3106 }
3107 }
3108 else {
3109 rb_str_append(result, fptr->pathv);
3110 if (fptr->fd < 0) {
3111 rb_str_cat(result, closed, strlen(closed));
3112 }
3113 }
3114 return rb_str_cat2(result, ">");
3115}
3116
3117/*
3118 * call-seq:
3119 * to_io -> self
3120 *
3121 * Returns +self+.
3122 *
3123 */
3124
3125static VALUE
3126rb_io_to_io(VALUE io)
3127{
3128 return io;
3129}
3130
3131/* reading functions */
3132static long
3133read_buffered_data(char *ptr, long len, rb_io_t *fptr)
3134{
3135 int n;
3136
3137 n = READ_DATA_PENDING_COUNT(fptr);
3138 if (n <= 0) return 0;
3139 if (n > len) n = (int)len;
3140 MEMMOVE(ptr, fptr->rbuf.ptr+fptr->rbuf.off, char, n);
3141 fptr->rbuf.off += n;
3142 fptr->rbuf.len -= n;
3143 return n;
3144}
3145
3146static long
3147io_bufread(char *ptr, long len, rb_io_t *fptr)
3148{
3149 long offset = 0;
3150 long n = len;
3151 long c;
3152
3153 if (READ_DATA_PENDING(fptr) == 0) {
3154 while (n > 0) {
3155 again:
3156 rb_io_check_closed(fptr);
3157 c = rb_io_read_memory(fptr, ptr+offset, n);
3158 if (c == 0) break;
3159 if (c < 0) {
3160 if (fptr_wait_readable(fptr))
3161 goto again;
3162 return -1;
3163 }
3164 offset += c;
3165 if ((n -= c) <= 0) break;
3166 }
3167 return len - n;
3168 }
3169
3170 while (n > 0) {
3171 c = read_buffered_data(ptr+offset, n, fptr);
3172 if (c > 0) {
3173 offset += c;
3174 if ((n -= c) <= 0) break;
3175 }
3176 rb_io_check_closed(fptr);
3177 if (io_fillbuf(fptr) < 0) {
3178 break;
3179 }
3180 }
3181 return len - n;
3182}
3183
3184static int io_setstrbuf(VALUE *str, long len);
3185
3187 char *str_ptr;
3188 long len;
3189 rb_io_t *fptr;
3190};
3191
3192static VALUE
3193bufread_call(VALUE arg)
3194{
3195 struct bufread_arg *p = (struct bufread_arg *)arg;
3196 p->len = io_bufread(p->str_ptr, p->len, p->fptr);
3197 return Qundef;
3198}
3199
3200static long
3201io_fread(VALUE str, long offset, long size, rb_io_t *fptr)
3202{
3203 long len;
3204 struct bufread_arg arg;
3205
3206 io_setstrbuf(&str, offset + size);
3207 if (!READ_DATA_PENDING(fptr))
3208 rb_str_make_heap(str);
3209 arg.str_ptr = RSTRING_PTR(str) + offset;
3210 arg.len = size;
3211 arg.fptr = fptr;
3212 rb_str_locktmp_ensure(str, bufread_call, (VALUE)&arg);
3213 len = arg.len;
3214 if (len < 0) rb_sys_fail_path(fptr->pathv);
3215 return len;
3216}
3217
3218static long
3219remain_size(rb_io_t *fptr)
3220{
3221 struct stat st;
3222 rb_off_t siz = READ_DATA_PENDING_COUNT(fptr);
3223 rb_off_t pos;
3224
3225 if (fstat(fptr->fd, &st) == 0 && S_ISREG(st.st_mode)
3226#if defined(__HAIKU__)
3227 && (st.st_dev > 3)
3228#endif
3229 )
3230 {
3231 if (io_fflush(fptr) < 0)
3232 rb_sys_fail_on_write(fptr);
3233 pos = lseek(fptr->fd, 0, SEEK_CUR);
3234 if (st.st_size >= pos && pos >= 0) {
3235 siz += st.st_size - pos;
3236 if (siz > LONG_MAX) {
3237 rb_raise(rb_eIOError, "file too big for single read");
3238 }
3239 }
3240 }
3241 else {
3242 siz += BUFSIZ;
3243 }
3244 return (long)siz;
3245}
3246
3247static VALUE
3248io_enc_str(VALUE str, rb_io_t *fptr)
3249{
3250 rb_enc_associate(str, io_read_encoding(fptr));
3251 return str;
3252}
3253
3254static void
3255make_readconv(rb_io_t *fptr, int size)
3256{
3257 if (!fptr->readconv) {
3258 int ecflags;
3259 VALUE ecopts;
3260 const char *sname, *dname;
3262 ecopts = fptr->encs.ecopts;
3263 if (fptr->encs.enc2) {
3264 sname = rb_enc_name(fptr->encs.enc2);
3265 dname = rb_enc_name(io_read_encoding(fptr));
3266 }
3267 else {
3268 sname = dname = "";
3269 }
3270 fptr->readconv = rb_econv_open_opts(sname, dname, ecflags, ecopts);
3271 if (!fptr->readconv)
3272 rb_exc_raise(rb_econv_open_exc(sname, dname, ecflags));
3273 fptr->cbuf.off = 0;
3274 fptr->cbuf.len = 0;
3275 if (size < IO_CBUF_CAPA_MIN) size = IO_CBUF_CAPA_MIN;
3276 fptr->cbuf.capa = size;
3277 fptr->cbuf.ptr = ALLOC_N(char, fptr->cbuf.capa);
3278 }
3279}
3280
3281#define MORE_CHAR_SUSPENDED Qtrue
3282#define MORE_CHAR_FINISHED Qnil
3283static VALUE
3284fill_cbuf(rb_io_t *fptr, int ec_flags)
3285{
3286 const unsigned char *ss, *sp, *se;
3287 unsigned char *ds, *dp, *de;
3289 int putbackable;
3290 int cbuf_len0;
3291 VALUE exc;
3292
3293 ec_flags |= ECONV_PARTIAL_INPUT;
3294
3295 if (fptr->cbuf.len == fptr->cbuf.capa)
3296 return MORE_CHAR_SUSPENDED; /* cbuf full */
3297 if (fptr->cbuf.len == 0)
3298 fptr->cbuf.off = 0;
3299 else if (fptr->cbuf.off + fptr->cbuf.len == fptr->cbuf.capa) {
3300 memmove(fptr->cbuf.ptr, fptr->cbuf.ptr+fptr->cbuf.off, fptr->cbuf.len);
3301 fptr->cbuf.off = 0;
3302 }
3303
3304 cbuf_len0 = fptr->cbuf.len;
3305
3306 while (1) {
3307 ss = sp = (const unsigned char *)fptr->rbuf.ptr + fptr->rbuf.off;
3308 se = sp + fptr->rbuf.len;
3309 ds = dp = (unsigned char *)fptr->cbuf.ptr + fptr->cbuf.off + fptr->cbuf.len;
3310 de = (unsigned char *)fptr->cbuf.ptr + fptr->cbuf.capa;
3311 res = rb_econv_convert(fptr->readconv, &sp, se, &dp, de, ec_flags);
3312 fptr->rbuf.off += (int)(sp - ss);
3313 fptr->rbuf.len -= (int)(sp - ss);
3314 fptr->cbuf.len += (int)(dp - ds);
3315
3316 putbackable = rb_econv_putbackable(fptr->readconv);
3317 /* The converter can hold readagain bytes it received in an earlier
3318 * fill (a character split across reads). Only bytes still in rbuf
3319 * can be put back there; the rest stay in the converter. */
3320 if (putbackable > fptr->rbuf.off)
3321 putbackable = fptr->rbuf.off;
3322 if (putbackable) {
3323 rb_econv_putback(fptr->readconv, (unsigned char *)fptr->rbuf.ptr + fptr->rbuf.off - putbackable, putbackable);
3324 fptr->rbuf.off -= putbackable;
3325 fptr->rbuf.len += putbackable;
3326 }
3327
3328 exc = rb_econv_make_exception(fptr->readconv);
3329 if (!NIL_P(exc))
3330 return exc;
3331
3332 if (cbuf_len0 != fptr->cbuf.len)
3333 return MORE_CHAR_SUSPENDED;
3334
3335 if (res == econv_finished) {
3336 return MORE_CHAR_FINISHED;
3337 }
3338
3339 if (res == econv_source_buffer_empty) {
3340 if (fptr->rbuf.len == 0) {
3341 READ_CHECK(fptr);
3342 if (io_fillbuf(fptr) < 0) {
3343 if (!fptr->readconv) {
3344 return MORE_CHAR_FINISHED;
3345 }
3346 ds = dp = (unsigned char *)fptr->cbuf.ptr + fptr->cbuf.off + fptr->cbuf.len;
3347 de = (unsigned char *)fptr->cbuf.ptr + fptr->cbuf.capa;
3348 res = rb_econv_convert(fptr->readconv, NULL, NULL, &dp, de, 0);
3349 fptr->cbuf.len += (int)(dp - ds);
3351 break;
3352 }
3353 }
3354 }
3355 }
3356 if (cbuf_len0 != fptr->cbuf.len)
3357 return MORE_CHAR_SUSPENDED;
3358
3359 return MORE_CHAR_FINISHED;
3360}
3361
3362static VALUE
3363more_char(rb_io_t *fptr)
3364{
3365 VALUE v;
3366 v = fill_cbuf(fptr, ECONV_AFTER_OUTPUT);
3367 if (v != MORE_CHAR_SUSPENDED && v != MORE_CHAR_FINISHED)
3368 rb_exc_raise(v);
3369 return v;
3370}
3371
3372static VALUE
3373io_shift_cbuf(rb_io_t *fptr, int len, VALUE *strp)
3374{
3375 VALUE str = Qnil;
3376 if (strp) {
3377 str = *strp;
3378 if (NIL_P(str)) {
3379 *strp = str = rb_str_new(fptr->cbuf.ptr+fptr->cbuf.off, len);
3380 }
3381 else {
3382 rb_str_cat(str, fptr->cbuf.ptr+fptr->cbuf.off, len);
3383 }
3384 rb_enc_associate(str, fptr->encs.enc);
3385 }
3386 fptr->cbuf.off += len;
3387 fptr->cbuf.len -= len;
3388 /* xxx: set coderange */
3389 if (fptr->cbuf.len == 0)
3390 fptr->cbuf.off = 0;
3391 else if (fptr->cbuf.capa/2 < fptr->cbuf.off) {
3392 memmove(fptr->cbuf.ptr, fptr->cbuf.ptr+fptr->cbuf.off, fptr->cbuf.len);
3393 fptr->cbuf.off = 0;
3394 }
3395 return str;
3396}
3397
3398static int
3399io_setstrbuf(VALUE *str, long len)
3400{
3401 if (NIL_P(*str)) {
3402 *str = rb_str_new(0, len);
3403 return TRUE;
3404 }
3405 else {
3406 VALUE s = StringValue(*str);
3407 rb_str_modify(s);
3408
3409 long clen = RSTRING_LEN(s);
3410 if (clen >= len) {
3411 return FALSE;
3412 }
3413 len -= clen;
3414 }
3415 if ((rb_str_capacity(*str) - (size_t)RSTRING_LEN(*str)) < (size_t)len) {
3417 }
3418 return FALSE;
3419}
3420
3421#define MAX_REALLOC_GAP 4096
3422static void
3423io_shrink_read_string(VALUE str, long n)
3424{
3425 if (rb_str_capacity(str) - n > MAX_REALLOC_GAP) {
3426 rb_str_resize(str, n);
3427 }
3428}
3429
3430static void
3431io_set_read_length(VALUE str, long n, int shrinkable)
3432{
3433 if (RSTRING_LEN(str) != n) {
3434 rb_str_modify(str);
3435 rb_str_set_len(str, n);
3436 if (shrinkable) io_shrink_read_string(str, n);
3437 }
3438}
3439
3440static VALUE
3441read_all(rb_io_t *fptr, long siz, VALUE str)
3442{
3443 long bytes;
3444 long n;
3445 long pos;
3446 rb_encoding *enc;
3447 int cr;
3448 int shrinkable;
3449
3450 if (NEED_READCONV(fptr)) {
3451 int first = !NIL_P(str);
3452 SET_BINARY_MODE(fptr);
3453 shrinkable = io_setstrbuf(&str,0);
3454 make_readconv(fptr, 0);
3455 while (1) {
3456 VALUE v;
3457 if (fptr->cbuf.len) {
3458 if (first) rb_str_set_len(str, first = 0);
3459 io_shift_cbuf(fptr, fptr->cbuf.len, &str);
3460 }
3461 v = fill_cbuf(fptr, 0);
3462 if (v != MORE_CHAR_SUSPENDED && v != MORE_CHAR_FINISHED) {
3463 if (fptr->cbuf.len) {
3464 if (first) rb_str_set_len(str, first = 0);
3465 io_shift_cbuf(fptr, fptr->cbuf.len, &str);
3466 }
3467 rb_exc_raise(v);
3468 }
3469 if (v == MORE_CHAR_FINISHED) {
3470 clear_readconv(fptr);
3471 if (first) rb_str_set_len(str, first = 0);
3472 if (shrinkable) io_shrink_read_string(str, RSTRING_LEN(str));
3473 return io_enc_str(str, fptr);
3474 }
3475 }
3476 }
3477
3478 NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr);
3479 bytes = 0;
3480 pos = 0;
3481
3482 enc = io_read_encoding(fptr);
3483 cr = 0;
3484
3485 if (siz == 0) siz = BUFSIZ;
3486 shrinkable = io_setstrbuf(&str, siz);
3487 for (;;) {
3488 READ_CHECK(fptr);
3489 n = io_fread(str, bytes, siz - bytes, fptr);
3490 if (n == 0 && bytes == 0) {
3491 rb_str_set_len(str, 0);
3492 break;
3493 }
3494 bytes += n;
3495 rb_str_set_len(str, bytes);
3496 if (cr != ENC_CODERANGE_BROKEN)
3497 pos += rb_str_coderange_scan_restartable(RSTRING_PTR(str) + pos, RSTRING_PTR(str) + bytes, enc, &cr);
3498 if (bytes < siz) break;
3499 siz += BUFSIZ;
3500
3501 size_t capa = rb_str_capacity(str);
3502 if (capa < (size_t)RSTRING_LEN(str) + BUFSIZ) {
3503 if (capa < BUFSIZ) {
3504 capa = BUFSIZ;
3505 }
3506 else if (capa > IO_MAX_BUFFER_GROWTH) {
3507 capa = IO_MAX_BUFFER_GROWTH;
3508 }
3510 }
3511 }
3512 if (shrinkable) io_shrink_read_string(str, RSTRING_LEN(str));
3513 str = io_enc_str(str, fptr);
3514 ENC_CODERANGE_SET(str, cr);
3515 return str;
3516}
3517
3518void
3520{
3521 if (rb_fd_set_nonblock(fptr->fd) != 0) {
3522 rb_sys_fail_path(fptr->pathv);
3523 }
3524}
3525
3526static VALUE
3527io_read_memory_call(VALUE arg)
3528{
3529 struct io_internal_read_struct *iis = (struct io_internal_read_struct *)arg;
3530
3531 VALUE scheduler = rb_fiber_scheduler_current();
3532 if (scheduler != Qnil) {
3533 VALUE result = rb_fiber_scheduler_io_read_memory(scheduler, iis->fptr->self, iis->buf, iis->capa, 0);
3534
3535 if (!UNDEF_P(result)) {
3536 // This is actually returned as a pseudo-VALUE and later cast to a long:
3537 return (VALUE)rb_fiber_scheduler_io_result_apply(result);
3538 }
3539 }
3540
3541 if (iis->nonblock) {
3542 return rb_io_blocking_region(iis->fptr, internal_read_func, iis);
3543 }
3544 else {
3545 return rb_io_blocking_region_wait(iis->fptr, internal_read_func, iis, RUBY_IO_READABLE);
3546 }
3547}
3548
3549static long
3550io_read_memory_locktmp(VALUE str, struct io_internal_read_struct *iis)
3551{
3552 return (long)rb_str_locktmp_ensure(str, io_read_memory_call, (VALUE)iis);
3553}
3554
3555#define no_exception_p(opts) !rb_opts_exception_p((opts), TRUE)
3556
3557static VALUE
3558io_getpartial(int argc, VALUE *argv, VALUE io, int no_exception, int nonblock)
3559{
3560 rb_io_t *fptr;
3561 VALUE length, str;
3562 long n, len;
3563 struct io_internal_read_struct iis;
3564 int shrinkable;
3565
3566 rb_scan_args(argc, argv, "11", &length, &str);
3567
3568 if ((len = NUM2LONG(length)) < 0) {
3569 rb_raise(rb_eArgError, "negative length %ld given", len);
3570 }
3571
3572 shrinkable = io_setstrbuf(&str, len);
3573
3574 GetOpenFile(io, fptr);
3576
3577 if (len == 0) {
3578 io_set_read_length(str, 0, shrinkable);
3579 return str;
3580 }
3581
3582 if (!nonblock)
3583 READ_CHECK(fptr);
3584 n = read_buffered_data(RSTRING_PTR(str), len, fptr);
3585 if (n <= 0) {
3586 again:
3587 if (nonblock) {
3588 rb_io_set_nonblock(fptr);
3589 }
3590 io_setstrbuf(&str, len);
3591 rb_str_make_heap(str);
3592 iis.th = rb_thread_current();
3593 iis.fptr = fptr;
3594 iis.nonblock = nonblock;
3595 iis.fd = fptr->fd;
3596 iis.buf = RSTRING_PTR(str);
3597 iis.capa = len;
3598 iis.timeout = NULL;
3599 n = io_read_memory_locktmp(str, &iis);
3600 if (n < 0) {
3601 int e = errno;
3602 if (!nonblock && fptr_wait_readable(fptr))
3603 goto again;
3604 if (nonblock && (io_again_p(e))) {
3605 if (no_exception)
3606 return sym_wait_readable;
3607 else
3608 rb_readwrite_syserr_fail(RB_IO_WAIT_READABLE,
3609 e, "read would block");
3610 }
3611 rb_syserr_fail_path(e, fptr->pathv);
3612 }
3613 }
3614 io_set_read_length(str, n, shrinkable);
3615
3616 if (n == 0)
3617 return Qnil;
3618 else
3619 return str;
3620}
3621
3622/*
3623 * call-seq:
3624 * readpartial(maxlen) -> string
3625 * readpartial(maxlen, out_string) -> out_string
3626 *
3627 * Reads up to +maxlen+ bytes from the stream;
3628 * returns a string (either a new string or the given +out_string+).
3629 * Its encoding is:
3630 *
3631 * - The unchanged encoding of +out_string+, if +out_string+ is given.
3632 * - ASCII-8BIT, otherwise.
3633 *
3634 * - Contains +maxlen+ bytes from the stream, if available.
3635 * - Otherwise contains all available bytes, if any available.
3636 * - Otherwise is an empty string.
3637 *
3638 * With the single non-negative integer argument +maxlen+ given,
3639 * returns a new string:
3640 *
3641 * f = File.new('t.txt')
3642 * f.readpartial(20) # => "First line\nSecond l"
3643 * f.readpartial(20) # => "ine\n\nFourth line\n"
3644 * f.readpartial(20) # => "Fifth line\n"
3645 * f.readpartial(20) # Raises EOFError.
3646 * f.close
3647 *
3648 * With both argument +maxlen+ and string argument +out_string+ given,
3649 * returns modified +out_string+:
3650 *
3651 * f = File.new('t.txt')
3652 * s = 'foo'
3653 * f.readpartial(20, s) # => "First line\nSecond l"
3654 * s = 'bar'
3655 * f.readpartial(0, s) # => ""
3656 * f.close
3657 *
3658 * This method is useful for a stream such as a pipe, a socket, or a tty.
3659 * It blocks only when no data is immediately available.
3660 * This means that it blocks only when _all_ of the following are true:
3661 *
3662 * - The byte buffer in the stream is empty.
3663 * - The content of the stream is empty.
3664 * - The stream is not at EOF.
3665 *
3666 * When blocked, the method waits for either more data or EOF on the stream:
3667 *
3668 * - If more data is read, the method returns the data.
3669 * - If EOF is reached, the method raises EOFError.
3670 *
3671 * When not blocked, the method responds immediately:
3672 *
3673 * - Returns data from the buffer if there is any.
3674 * - Otherwise returns data from the stream if there is any.
3675 * - Otherwise raises EOFError if the stream has reached EOF.
3676 *
3677 * Note that this method is similar to sysread. The differences are:
3678 *
3679 * - If the byte buffer is not empty, read from the byte buffer
3680 * instead of "sysread for buffered IO (IOError)".
3681 * - It doesn't cause Errno::EWOULDBLOCK and Errno::EINTR. When
3682 * readpartial meets EWOULDBLOCK and EINTR by read system call,
3683 * readpartial retries the system call.
3684 *
3685 * The latter means that readpartial is non-blocking-flag insensitive.
3686 * It blocks on the situation IO#sysread causes Errno::EWOULDBLOCK as
3687 * if the fd is blocking mode.
3688 *
3689 * Examples:
3690 *
3691 * # # Returned Buffer Content Pipe Content
3692 * r, w = IO.pipe #
3693 * w << 'abc' # "" "abc".
3694 * r.readpartial(4096) # => "abc" "" ""
3695 * r.readpartial(4096) # (Blocks because buffer and pipe are empty.)
3696 *
3697 * # # Returned Buffer Content Pipe Content
3698 * r, w = IO.pipe #
3699 * w << 'abc' # "" "abc"
3700 * w.close # "" "abc" EOF
3701 * r.readpartial(4096) # => "abc" "" EOF
3702 * r.readpartial(4096) # raises EOFError
3703 *
3704 * # # Returned Buffer Content Pipe Content
3705 * r, w = IO.pipe #
3706 * w << "abc\ndef\n" # "" "abc\ndef\n"
3707 * r.gets # => "abc\n" "def\n" ""
3708 * w << "ghi\n" # "def\n" "ghi\n"
3709 * r.readpartial(4096) # => "def\n" "" "ghi\n"
3710 * r.readpartial(4096) # => "ghi\n" "" ""
3711 *
3712 */
3713
3714static VALUE
3715io_readpartial(int argc, VALUE *argv, VALUE io)
3716{
3717 VALUE ret;
3718
3719 ret = io_getpartial(argc, argv, io, Qnil, 0);
3720 if (NIL_P(ret))
3721 rb_eof_error();
3722 return ret;
3723}
3724
3725static VALUE
3726io_nonblock_eof(int no_exception)
3727{
3728 if (!no_exception) {
3729 rb_eof_error();
3730 }
3731 return Qnil;
3732}
3733
3734/* :nodoc: */
3735static VALUE
3736io_read_nonblock(rb_execution_context_t *ec, VALUE io, VALUE length, VALUE str, VALUE ex)
3737{
3738 rb_io_t *fptr;
3739 long n, len;
3740 struct io_internal_read_struct iis;
3741 int shrinkable;
3742
3743 if ((len = NUM2LONG(length)) < 0) {
3744 rb_raise(rb_eArgError, "negative length %ld given", len);
3745 }
3746
3747 shrinkable = io_setstrbuf(&str, len);
3748 rb_bool_expected(ex, "exception", TRUE);
3749
3750 GetOpenFile(io, fptr);
3752
3753 if (len == 0) {
3754 io_set_read_length(str, 0, shrinkable);
3755 return str;
3756 }
3757
3758 n = read_buffered_data(RSTRING_PTR(str), len, fptr);
3759 if (n <= 0) {
3760 rb_fd_set_nonblock(fptr->fd);
3761 shrinkable |= io_setstrbuf(&str, len);
3762 iis.fptr = fptr;
3763 iis.nonblock = 1;
3764 iis.fd = fptr->fd;
3765 iis.buf = RSTRING_PTR(str);
3766 iis.capa = len;
3767 iis.timeout = NULL;
3768 n = io_read_memory_locktmp(str, &iis);
3769 if (n < 0) {
3770 int e = errno;
3771 if (io_again_p(e)) {
3772 if (!ex) return sym_wait_readable;
3773 rb_readwrite_syserr_fail(RB_IO_WAIT_READABLE,
3774 e, "read would block");
3775 }
3776 rb_syserr_fail_path(e, fptr->pathv);
3777 }
3778 }
3779 io_set_read_length(str, n, shrinkable);
3780
3781 if (n == 0) {
3782 if (!ex) return Qnil;
3783 rb_eof_error();
3784 }
3785
3786 return str;
3787}
3788
3789/* :nodoc: */
3790static VALUE
3791io_write_nonblock(rb_execution_context_t *ec, VALUE io, VALUE str, VALUE ex)
3792{
3793 rb_io_t *fptr;
3794 long n;
3795
3796 if (!RB_TYPE_P(str, T_STRING))
3797 str = rb_obj_as_string(str);
3798 rb_bool_expected(ex, "exception", TRUE);
3799
3800 io = GetWriteIO(io);
3801 GetOpenFile(io, fptr);
3803
3804 if (io_fflush(fptr) < 0)
3805 rb_sys_fail_on_write(fptr);
3806
3807 rb_fd_set_nonblock(fptr->fd);
3808 n = write(fptr->fd, RSTRING_PTR(str), RSTRING_LEN(str));
3809 RB_GC_GUARD(str);
3810
3811 if (n < 0) {
3812 int e = errno;
3813 if (io_again_p(e)) {
3814 if (!ex) {
3815 return sym_wait_writable;
3816 }
3817 else {
3818 rb_readwrite_syserr_fail(RB_IO_WAIT_WRITABLE, e, "write would block");
3819 }
3820 }
3821 rb_syserr_fail_path(e, fptr->pathv);
3822 }
3823
3824 return LONG2FIX(n);
3825}
3826
3827/*
3828 * call-seq:
3829 * read(maxlen = nil, out_string = nil) -> new_string, out_string, or nil
3830 *
3831 * Reads bytes from the stream; the stream must be opened for reading
3832 * (see {Access Modes}[rdoc-ref:File@Access+Modes]):
3833 *
3834 * - If +maxlen+ is +nil+, reads all bytes using the stream's data mode.
3835 * - Otherwise reads up to +maxlen+ bytes in binary mode.
3836 *
3837 * Returns a string (either a new string or the given +out_string+)
3838 * containing the bytes read.
3839 * The encoding of the string depends on both +maxLen+ and +out_string+:
3840 *
3841 * - +maxlen+ is +nil+: uses internal encoding of +self+
3842 * (regardless of whether +out_string+ was given).
3843 * - +maxlen+ not +nil+:
3844 *
3845 * - +out_string+ given: encoding of +out_string+ not modified.
3846 * - +out_string+ not given: ASCII-8BIT is used.
3847 *
3848 * <b>Without Argument +out_string+</b>
3849 *
3850 * When argument +out_string+ is omitted,
3851 * the returned value is a new string:
3852 *
3853 * f = File.new('t.txt')
3854 * f.read
3855 * # => "First line\nSecond line\n\nFourth line\nFifth line\n"
3856 * f.rewind
3857 * f.read(30) # => "First line\r\nSecond line\r\n\r\nFou"
3858 * f.read(30) # => "rth line\r\nFifth line\r\n"
3859 * f.read(30) # => nil
3860 * f.close
3861 *
3862 * If +maxlen+ is zero, returns an empty string.
3863 *
3864 * <b> With Argument +out_string+</b>
3865 *
3866 * When argument +out_string+ is given,
3867 * the returned value is +out_string+, whose content is replaced:
3868 *
3869 * f = File.new('t.txt')
3870 * s = 'foo' # => "foo"
3871 * f.read(nil, s) # => "First line\nSecond line\n\nFourth line\nFifth line\n"
3872 * s # => "First line\nSecond line\n\nFourth line\nFifth line\n"
3873 * f.rewind
3874 * s = 'bar'
3875 * f.read(30, s) # => "First line\r\nSecond line\r\n\r\nFou"
3876 * s # => "First line\r\nSecond line\r\n\r\nFou"
3877 * s = 'baz'
3878 * f.read(30, s) # => "rth line\r\nFifth line\r\n"
3879 * s # => "rth line\r\nFifth line\r\n"
3880 * s = 'bat'
3881 * f.read(30, s) # => nil
3882 * s # => ""
3883 * f.close
3884 *
3885 * Note that this method behaves like the fread() function in C.
3886 * This means it retries to invoke read(2) system calls to read data
3887 * with the specified maxlen (or until EOF).
3888 *
3889 * This behavior is preserved even if the stream is in non-blocking mode.
3890 * (This method is non-blocking-flag insensitive as other methods.)
3891 *
3892 * If you need the behavior like a single read(2) system call,
3893 * consider #readpartial, #read_nonblock, and #sysread.
3894 *
3895 * Related: IO#write.
3896 */
3897
3898static VALUE
3899io_read(int argc, VALUE *argv, VALUE io)
3900{
3901 rb_io_t *fptr;
3902 long n, len;
3903 VALUE length, str;
3904 int shrinkable;
3905#if RUBY_CRLF_ENVIRONMENT
3906 int previous_mode;
3907#endif
3908
3909 rb_scan_args(argc, argv, "02", &length, &str);
3910
3911 if (NIL_P(length)) {
3912 GetOpenFile(io, fptr);
3914 return read_all(fptr, remain_size(fptr), str);
3915 }
3916 len = NUM2LONG(length);
3917 if (len < 0) {
3918 rb_raise(rb_eArgError, "negative length %ld given", len);
3919 }
3920
3921 shrinkable = io_setstrbuf(&str,len);
3922
3923 GetOpenFile(io, fptr);
3925 if (len == 0) {
3926 io_set_read_length(str, 0, shrinkable);
3927 return str;
3928 }
3929
3930 READ_CHECK(fptr);
3931#if RUBY_CRLF_ENVIRONMENT
3932 previous_mode = set_binary_mode_with_seek_cur(fptr);
3933#endif
3934 n = io_fread(str, 0, len, fptr);
3935 io_set_read_length(str, n, shrinkable);
3936#if RUBY_CRLF_ENVIRONMENT
3937 if (previous_mode == O_TEXT) {
3938 setmode(fptr->fd, O_TEXT);
3939 }
3940#endif
3941 if (n == 0) return Qnil;
3942
3943 return str;
3944}
3945
3946static void
3947rscheck(const char *rsptr, long rslen, VALUE rs)
3948{
3949 if (!rs) return;
3950 if (RSTRING_PTR(rs) != rsptr && RSTRING_LEN(rs) != rslen)
3951 rb_raise(rb_eRuntimeError, "rs modified");
3952}
3953
3954static const char *
3955search_delim(const char *p, long len, int delim, rb_encoding *enc)
3956{
3957 if (delim < 0) return NULL;
3958 if (rb_enc_mbminlen(enc) == 1) {
3959 p = memchr(p, delim, len);
3960 if (p) return p + 1;
3961 }
3962 else {
3963 const char *end = p + len;
3964 while (p < end) {
3965 int r = rb_enc_precise_mbclen(p, end, enc);
3966 if (!MBCLEN_CHARFOUND_P(r)) {
3967 p += rb_enc_mbminlen(enc);
3968 continue;
3969 }
3970 int n = MBCLEN_CHARFOUND_LEN(r);
3971 if (rb_enc_mbc_to_codepoint(p, end, enc) == (unsigned int)delim) {
3972 return p + n;
3973 }
3974 p += n;
3975 }
3976 }
3977 return NULL;
3978}
3979
3980static int
3981appendline(rb_io_t *fptr, int delim, VALUE *strp, long *lp, rb_encoding *enc)
3982{
3983 VALUE str = *strp;
3984 long limit = *lp;
3985
3986 if (NEED_READCONV(fptr)) {
3987 SET_BINARY_MODE(fptr);
3988 make_readconv(fptr, 0);
3989 do {
3990 const char *p, *e;
3991 int searchlen = READ_CHAR_PENDING_COUNT(fptr);
3992 if (searchlen) {
3993 p = READ_CHAR_PENDING_PTR(fptr);
3994 if (0 < limit && limit < searchlen)
3995 searchlen = (int)limit;
3996 e = search_delim(p, searchlen, delim, enc);
3997 if (e) {
3998 int len = (int)(e-p);
3999 if (NIL_P(str))
4000 *strp = str = rb_str_new(p, len);
4001 else
4002 rb_str_buf_cat(str, p, len);
4003 fptr->cbuf.off += len;
4004 fptr->cbuf.len -= len;
4005 limit -= len;
4006 *lp = limit;
4007 return delim;
4008 }
4009
4010 if (NIL_P(str))
4011 *strp = str = rb_str_new(p, searchlen);
4012 else
4013 rb_str_buf_cat(str, p, searchlen);
4014 fptr->cbuf.off += searchlen;
4015 fptr->cbuf.len -= searchlen;
4016 limit -= searchlen;
4017
4018 if (limit == 0) {
4019 *lp = limit;
4020 return (unsigned char)RSTRING_PTR(str)[RSTRING_LEN(str)-1];
4021 }
4022 }
4023 } while (more_char(fptr) != MORE_CHAR_FINISHED);
4024 clear_readconv(fptr);
4025 *lp = limit;
4026 return EOF;
4027 }
4028
4029 NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr);
4030 do {
4031 long pending = READ_DATA_PENDING_COUNT(fptr);
4032 if (pending > 0) {
4033 const char *p = READ_DATA_PENDING_PTR(fptr);
4034 const char *e;
4035 long last;
4036
4037 if (limit > 0 && pending > limit) pending = limit;
4038 e = search_delim(p, pending, delim, enc);
4039 if (e) pending = e - p;
4040 if (!NIL_P(str)) {
4041 last = RSTRING_LEN(str);
4042 rb_str_resize(str, last + pending);
4043 }
4044 else {
4045 last = 0;
4046 *strp = str = rb_str_buf_new(pending);
4047 rb_str_set_len(str, pending);
4048 }
4049 read_buffered_data(RSTRING_PTR(str) + last, pending, fptr); /* must not fail */
4050 limit -= pending;
4051 *lp = limit;
4052 if (e) return delim;
4053 if (limit == 0)
4054 return (unsigned char)RSTRING_PTR(str)[RSTRING_LEN(str)-1];
4055 }
4056 READ_CHECK(fptr);
4057 } while (io_fillbuf(fptr) >= 0);
4058 *lp = limit;
4059 return EOF;
4060}
4061
4062static inline int
4063swallow(rb_io_t *fptr, int term)
4064{
4065 if (NEED_READCONV(fptr)) {
4066 rb_encoding *enc = io_read_encoding(fptr);
4067 int needconv = rb_enc_mbminlen(enc) != 1;
4068 SET_BINARY_MODE(fptr);
4069 make_readconv(fptr, 0);
4070 do {
4071 size_t cnt;
4072 while ((cnt = READ_CHAR_PENDING_COUNT(fptr)) > 0) {
4073 const char *p = READ_CHAR_PENDING_PTR(fptr);
4074 int i;
4075 if (!needconv) {
4076 if (*p != term) return TRUE;
4077 i = (int)cnt;
4078 while (--i && *++p == term);
4079 }
4080 else {
4081 const char *e = p + cnt;
4082 if (rb_enc_ascget(p, e, &i, enc) != term) return TRUE;
4083 while ((p += i) < e && rb_enc_ascget(p, e, &i, enc) == term);
4084 i = (int)(e - p);
4085 }
4086 io_shift_cbuf(fptr, (int)cnt - i, NULL);
4087 }
4088 } while (more_char(fptr) != MORE_CHAR_FINISHED);
4089 return FALSE;
4090 }
4091
4092 NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr);
4093 do {
4094 size_t cnt;
4095 while ((cnt = READ_DATA_PENDING_COUNT(fptr)) > 0) {
4096 char buf[1024];
4097 const char *p = READ_DATA_PENDING_PTR(fptr);
4098 int i;
4099 if (cnt > sizeof buf) cnt = sizeof buf;
4100 if (*p != term) return TRUE;
4101 i = (int)cnt;
4102 while (--i && *++p == term);
4103 if (!read_buffered_data(buf, cnt - i, fptr)) /* must not fail */
4104 rb_sys_fail_path(fptr->pathv);
4105 }
4106 READ_CHECK(fptr);
4107 } while (io_fillbuf(fptr) == 0);
4108 return FALSE;
4109}
4110
4111static VALUE
4112rb_io_getline_fast(rb_io_t *fptr, rb_encoding *enc, int chomp)
4113{
4114 VALUE str = Qnil;
4115 int len = 0;
4116 long pos = 0;
4117 int cr = 0;
4118
4119 do {
4120 int pending = READ_DATA_PENDING_COUNT(fptr);
4121
4122 if (pending > 0) {
4123 const char *p = READ_DATA_PENDING_PTR(fptr);
4124 const char *e;
4125 int chomplen = 0;
4126
4127 e = memchr(p, '\n', pending);
4128 if (e) {
4129 pending = (int)(e - p + 1);
4130 if (chomp) {
4131 chomplen = (pending > 1 && *(e-1) == '\r') + 1;
4132 }
4133 }
4134 if (NIL_P(str)) {
4135 str = rb_str_new(p, pending - chomplen);
4136 fptr->rbuf.off += pending;
4137 fptr->rbuf.len -= pending;
4138 }
4139 else {
4140 rb_str_resize(str, len + pending - chomplen);
4141 read_buffered_data(RSTRING_PTR(str)+len, pending - chomplen, fptr);
4142 fptr->rbuf.off += chomplen;
4143 fptr->rbuf.len -= chomplen;
4144 if (pending == 1 && chomplen == 1 && len > 0) {
4145 if (RSTRING_PTR(str)[len-1] == '\r') {
4146 rb_str_resize(str, --len);
4147 break;
4148 }
4149 }
4150 }
4151 len += pending - chomplen;
4152 if (cr != ENC_CODERANGE_BROKEN)
4153 pos += rb_str_coderange_scan_restartable(RSTRING_PTR(str) + pos, RSTRING_PTR(str) + len, enc, &cr);
4154 if (e) break;
4155 }
4156 READ_CHECK(fptr);
4157 } while (io_fillbuf(fptr) >= 0);
4158 if (NIL_P(str)) return Qnil;
4159
4160 str = io_enc_str(str, fptr);
4161 ENC_CODERANGE_SET(str, cr);
4162 fptr->lineno++;
4163
4164 return str;
4165}
4166
4168 VALUE io;
4169 VALUE rs;
4170 long limit;
4171 unsigned int chomp: 1;
4172};
4173
4174static void
4175extract_getline_opts(VALUE opts, struct getline_arg *args)
4176{
4177 int chomp = FALSE;
4178 if (!NIL_P(opts)) {
4179 static ID kwds[1];
4180 VALUE vchomp;
4181 if (!kwds[0]) {
4182 kwds[0] = rb_intern_const("chomp");
4183 }
4184 rb_get_kwargs(opts, kwds, 0, -2, &vchomp);
4185 chomp = (!UNDEF_P(vchomp)) && RTEST(vchomp);
4186 }
4187 args->chomp = chomp;
4188}
4189
4190static void
4191extract_getline_args(int argc, VALUE *argv, struct getline_arg *args)
4192{
4193 VALUE rs = rb_rs, lim = Qnil;
4194
4195 if (argc == 1) {
4196 VALUE tmp = Qnil;
4197
4198 if (NIL_P(argv[0]) || !NIL_P(tmp = rb_check_string_type(argv[0]))) {
4199 rs = tmp;
4200 }
4201 else {
4202 lim = argv[0];
4203 }
4204 }
4205 else if (2 <= argc) {
4206 rs = argv[0], lim = argv[1];
4207 if (!NIL_P(rs))
4208 StringValue(rs);
4209 }
4210 args->rs = rs;
4211 args->limit = NIL_P(lim) ? -1L : NUM2LONG(lim);
4212}
4213
4214static void
4215check_getline_args(VALUE *rsp, long *limit, VALUE io)
4216{
4217 rb_io_t *fptr;
4218 VALUE rs = *rsp;
4219
4220 if (!NIL_P(rs)) {
4221 rb_encoding *enc_rs, *enc_io;
4222
4223 GetOpenFile(io, fptr);
4224 enc_rs = rb_enc_get(rs);
4225 enc_io = io_read_encoding(fptr);
4226 if (enc_io != enc_rs &&
4227 (!is_ascii_string(rs) ||
4228 (RSTRING_LEN(rs) > 0 && !rb_enc_asciicompat(enc_io)))) {
4229 if (rs == rb_default_rs) {
4230 rs = rb_enc_str_new(0, 0, enc_io);
4231 rb_str_buf_cat_ascii(rs, "\n");
4232 *rsp = rs;
4233 }
4234 else {
4235 rb_raise(rb_eArgError, "encoding mismatch: %s IO with %s RS",
4236 rb_enc_name(enc_io),
4237 rb_enc_name(enc_rs));
4238 }
4239 }
4240 }
4241}
4242
4243static void
4244prepare_getline_args(int argc, VALUE *argv, struct getline_arg *args, VALUE io)
4245{
4246 VALUE opts;
4247 argc = rb_scan_args(argc, argv, "02:", NULL, NULL, &opts);
4248 extract_getline_args(argc, argv, args);
4249 extract_getline_opts(opts, args);
4250 check_getline_args(&args->rs, &args->limit, io);
4251}
4252
4253static VALUE
4254rb_io_getline_0(VALUE rs, long limit, int chomp, rb_io_t *fptr)
4255{
4256 VALUE str = Qnil;
4257 int nolimit = 0;
4258 rb_encoding *enc;
4259
4261 if (NIL_P(rs) && limit < 0) {
4262 str = read_all(fptr, 0, Qnil);
4263 if (RSTRING_LEN(str) == 0) return Qnil;
4264 }
4265 else if (limit == 0) {
4266 return rb_enc_str_new(0, 0, io_read_encoding(fptr));
4267 }
4268 else if (rs == rb_default_rs && limit < 0 && !NEED_READCONV(fptr) &&
4269 rb_enc_asciicompat(enc = io_read_encoding(fptr))) {
4270 NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr);
4271 return rb_io_getline_fast(fptr, enc, chomp);
4272 }
4273 else {
4274 int c, newline = -1;
4275 const char *rsptr = 0;
4276 long rslen = 0;
4277 int rspara = 0;
4278 int extra_limit = 16;
4279 int chomp_cr = chomp;
4280
4281 SET_BINARY_MODE(fptr);
4282 enc = io_read_encoding(fptr);
4283
4284 if (!NIL_P(rs)) {
4285 rslen = RSTRING_LEN(rs);
4286 if (rslen == 0) {
4287 rsptr = "\n\n";
4288 rslen = 2;
4289 rspara = 1;
4290 swallow(fptr, '\n');
4291 rs = 0;
4292 if (!rb_enc_asciicompat(enc)) {
4293 rs = rb_usascii_str_new(rsptr, rslen);
4294 rs = rb_str_conv_enc(rs, 0, enc);
4295 OBJ_FREEZE(rs);
4296 rsptr = RSTRING_PTR(rs);
4297 rslen = RSTRING_LEN(rs);
4298 }
4299 newline = '\n';
4300 }
4301 else if (rb_enc_mbminlen(enc) == 1) {
4302 rsptr = RSTRING_PTR(rs);
4303 newline = (unsigned char)rsptr[rslen - 1];
4304 }
4305 else {
4306 rs = rb_str_conv_enc(rs, 0, enc);
4307 rsptr = RSTRING_PTR(rs);
4308 const char *e = rsptr + rslen;
4309 const char *last = rb_enc_prev_char(rsptr, e, e, enc);
4310 int n;
4311 newline = rb_enc_codepoint_len(last, e, &n, enc);
4312 if (last + n != e) rb_raise(rb_eArgError, "broken separator");
4313 }
4314 chomp_cr = chomp && newline == '\n' && rslen == rb_enc_mbminlen(enc);
4315 }
4316
4317 /* MS - Optimization */
4318 while ((c = appendline(fptr, newline, &str, &limit, enc)) != EOF) {
4319 const char *s, *p, *pp, *e;
4320
4321 if (c == newline && RSTRING_LEN(str) >= rslen) {
4322 s = RSTRING_PTR(str);
4323 e = RSTRING_END(str);
4324 p = e - rslen;
4325 if (at_char_boundary(s, p, e, enc)) {
4326 if (!rspara) rscheck(rsptr, rslen, rs);
4327 if (memcmp(p, rsptr, rslen) == 0) {
4328 if (chomp) {
4329 if (chomp_cr && p > s && *(p-1) == '\r') --p;
4330 rb_str_set_len(str, p - s);
4331 }
4332 break;
4333 }
4334 }
4335 }
4336 if (limit == 0) {
4337 s = RSTRING_PTR(str);
4338 p = RSTRING_END(str);
4339 pp = rb_enc_prev_char(s, p, p, enc);
4340 if (extra_limit && pp &&
4341 MBCLEN_NEEDMORE_P(rb_enc_precise_mbclen(pp, p, enc))) {
4342 /* relax the limit while incomplete character.
4343 * extra_limit limits the relax length */
4344 limit = 1;
4345 extra_limit--;
4346 }
4347 else {
4348 nolimit = 1;
4349 break;
4350 }
4351 }
4352 }
4353
4354 if (rspara && c != EOF)
4355 swallow(fptr, '\n');
4356 if (!NIL_P(str))
4357 str = io_enc_str(str, fptr);
4358 }
4359
4360 if (!NIL_P(str) && !nolimit) {
4361 fptr->lineno++;
4362 }
4363
4364 return str;
4365}
4366
4367static VALUE
4368rb_io_getline_1(VALUE rs, long limit, int chomp, VALUE io)
4369{
4370 rb_io_t *fptr;
4371 int old_lineno, new_lineno;
4372 VALUE str;
4373
4374 GetOpenFile(io, fptr);
4375 old_lineno = fptr->lineno;
4376 str = rb_io_getline_0(rs, limit, chomp, fptr);
4377 if (!NIL_P(str) && (new_lineno = fptr->lineno) != old_lineno) {
4378 if (io == ARGF.current_file) {
4379 ARGF.lineno += new_lineno - old_lineno;
4380 ARGF.last_lineno = ARGF.lineno;
4381 }
4382 else {
4383 ARGF.last_lineno = new_lineno;
4384 }
4385 }
4386
4387 return str;
4388}
4389
4390static VALUE
4391rb_io_getline(int argc, VALUE *argv, VALUE io)
4392{
4393 struct getline_arg args;
4394
4395 prepare_getline_args(argc, argv, &args, io);
4396 return rb_io_getline_1(args.rs, args.limit, args.chomp, io);
4397}
4398
4399VALUE
4401{
4402 return rb_io_getline_1(rb_default_rs, -1, FALSE, io);
4403}
4404
4405VALUE
4406rb_io_gets_limit_internal(VALUE io, long limit)
4407{
4408 rb_io_t *fptr;
4409 GetOpenFile(io, fptr);
4410 return rb_io_getline_0(rb_default_rs, limit, FALSE, fptr);
4411}
4412
4413VALUE
4414rb_io_gets_internal(VALUE io)
4415{
4416 return rb_io_gets_limit_internal(io, -1);
4417}
4418
4419/*
4420 * call-seq:
4421 * gets(sep = $/, chomp: false) -> string or nil
4422 * gets(limit, chomp: false) -> string or nil
4423 * gets(sep, limit, chomp: false) -> string or nil
4424 *
4425 * Reads and returns a line from the stream;
4426 * assigns the return value to <tt>$_</tt>.
4427 * See {Line IO}[rdoc-ref:IO@Line+IO].
4428 *
4429 * With no arguments given, returns the next line
4430 * as determined by line separator <tt>$/</tt>, or +nil+ if none:
4431 *
4432 * f = File.open('t.txt')
4433 * f.gets # => "First line\n"
4434 * $_ # => "First line\n"
4435 * f.gets # => "\n"
4436 * f.gets # => "Fourth line\n"
4437 * f.gets # => "Fifth line\n"
4438 * f.gets # => nil
4439 * f.close
4440 *
4441 * With only string argument +sep+ given,
4442 * returns the next line as determined by line separator +sep+,
4443 * or +nil+ if none;
4444 * see {Line Separator}[rdoc-ref:IO@Line+Separator]:
4445 *
4446 * f = File.new('t.txt')
4447 * f.gets('l') # => "First l"
4448 * f.gets('li') # => "ine\nSecond li"
4449 * f.gets('lin') # => "ne\n\nFourth lin"
4450 * f.gets # => "e\n"
4451 * f.close
4452 *
4453 * The two special values for +sep+ are honored:
4454 *
4455 * f = File.new('t.txt')
4456 * # Get all.
4457 * f.gets(nil) # => "First line\nSecond line\n\nFourth line\nFifth line\n"
4458 * f.rewind
4459 * # Get paragraph (up to two line separators).
4460 * f.gets('') # => "First line\nSecond line\n\n"
4461 * f.close
4462 *
4463 * With only integer argument +limit+ given,
4464 * limits the number of bytes in the line;
4465 * see {Line Limit}[rdoc-ref:IO@Line+Limit]:
4466 *
4467 * # No more than one line.
4468 * File.open('t.txt') {|f| f.gets(10) } # => "First line"
4469 * File.open('t.txt') {|f| f.gets(11) } # => "First line\n"
4470 * File.open('t.txt') {|f| f.gets(12) } # => "First line\n"
4471 *
4472 * With arguments +sep+ and +limit+ given,
4473 * combines the two behaviors
4474 * (see {Line Separator and Line Limit}[rdoc-ref:IO@Line+Separator+and+Line+Limit]).
4475 *
4476 * Optional keyword argument +chomp+ specifies whether line separators
4477 * are to be omitted:
4478 *
4479 * f = File.open('t.txt')
4480 * # Chomp the lines.
4481 * f.gets(chomp: true) # => "First line"
4482 * f.gets(chomp: true) # => "Second line"
4483 * f.gets(chomp: true) # => ""
4484 * f.gets(chomp: true) # => "Fourth line"
4485 * f.gets(chomp: true) # => "Fifth line"
4486 * f.gets(chomp: true) # => nil
4487 * f.close
4488 *
4489 */
4490
4491static VALUE
4492rb_io_gets_m(int argc, VALUE *argv, VALUE io)
4493{
4494 VALUE str;
4495
4496 str = rb_io_getline(argc, argv, io);
4497 rb_lastline_set(str);
4498
4499 return str;
4500}
4501
4502/*
4503 * call-seq:
4504 * lineno -> integer
4505 *
4506 * Returns the current line number for the stream;
4507 * see {Line Number}[rdoc-ref:IO@Line+Number].
4508 *
4509 */
4510
4511static VALUE
4512rb_io_lineno(VALUE io)
4513{
4514 rb_io_t *fptr;
4515
4516 GetOpenFile(io, fptr);
4518 return INT2NUM(fptr->lineno);
4519}
4520
4521/*
4522 * call-seq:
4523 * lineno = integer -> integer
4524 *
4525 * Sets and returns the line number for the stream;
4526 * see {Line Number}[rdoc-ref:IO@Line+Number].
4527 *
4528 */
4529
4530static VALUE
4531rb_io_set_lineno(VALUE io, VALUE lineno)
4532{
4533 rb_io_t *fptr;
4534
4535 GetOpenFile(io, fptr);
4537 fptr->lineno = NUM2INT(lineno);
4538 return lineno;
4539}
4540
4541/* :nodoc: */
4542static VALUE
4543io_readline(rb_execution_context_t *ec, VALUE io, VALUE sep, VALUE lim, VALUE chomp)
4544{
4545 long limit = -1;
4546 if (NIL_P(lim)) {
4547 VALUE tmp = Qnil;
4548 // If sep is specified, but it's not a string and not nil, then assume
4549 // it's the limit (it should be an integer)
4550 if (!NIL_P(sep) && NIL_P(tmp = rb_check_string_type(sep))) {
4551 // If the user has specified a non-nil / non-string value
4552 // for the separator, we assume it's the limit and set the
4553 // separator to default: rb_rs.
4554 lim = sep;
4555 limit = NUM2LONG(lim);
4556 sep = rb_rs;
4557 }
4558 else {
4559 sep = tmp;
4560 }
4561 }
4562 else {
4563 if (!NIL_P(sep)) StringValue(sep);
4564 limit = NUM2LONG(lim);
4565 }
4566
4567 check_getline_args(&sep, &limit, io);
4568
4569 VALUE line = rb_io_getline_1(sep, limit, RTEST(chomp), io);
4570 rb_lastline_set_up(line, 1);
4571
4572 if (NIL_P(line)) {
4573 rb_eof_error();
4574 }
4575 return line;
4576}
4577
4578static VALUE io_readlines(const struct getline_arg *arg, VALUE io);
4579
4580/*
4581 * call-seq:
4582 * readlines(sep = $/, chomp: false) -> array
4583 * readlines(limit, chomp: false) -> array
4584 * readlines(sep, limit, chomp: false) -> array
4585 *
4586 * Reads and returns all remaining line from the stream;
4587 * does not modify <tt>$_</tt>.
4588 * See {Line IO}[rdoc-ref:IO@Line+IO].
4589 *
4590 * With no arguments given, returns lines
4591 * as determined by line separator <tt>$/</tt>, or +nil+ if none:
4592 *
4593 * f = File.new('t.txt')
4594 * f.readlines
4595 * # => ["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"]
4596 * f.readlines # => []
4597 * f.close
4598 *
4599 * With only string argument +sep+ given,
4600 * returns lines as determined by line separator +sep+,
4601 * or +nil+ if none;
4602 * see {Line Separator}[rdoc-ref:IO@Line+Separator]:
4603 *
4604 * f = File.new('t.txt')
4605 * f.readlines('li')
4606 * # => ["First li", "ne\nSecond li", "ne\n\nFourth li", "ne\nFifth li", "ne\n"]
4607 * f.close
4608 *
4609 * The two special values for +sep+ are honored:
4610 *
4611 * f = File.new('t.txt')
4612 * # Get all into one string.
4613 * f.readlines(nil)
4614 * # => ["First line\nSecond line\n\nFourth line\nFifth line\n"]
4615 * # Get paragraphs (up to two line separators).
4616 * f.rewind
4617 * f.readlines('')
4618 * # => ["First line\nSecond line\n\n", "Fourth line\nFifth line\n"]
4619 * f.close
4620 *
4621 * With only integer argument +limit+ given,
4622 * limits the number of bytes in each line;
4623 * see {Line Limit}[rdoc-ref:IO@Line+Limit]:
4624 *
4625 * f = File.new('t.txt')
4626 * f.readlines(8)
4627 * # => ["First li", "ne\n", "Second l", "ine\n", "\n", "Fourth l", "ine\n", "Fifth li", "ne\n"]
4628 * f.close
4629 *
4630 * With arguments +sep+ and +limit+ given,
4631 * combines the two behaviors
4632 * (see {Line Separator and Line Limit}[rdoc-ref:IO@Line+Separator+and+Line+Limit]).
4633 *
4634 * Optional keyword argument +chomp+ specifies whether line separators
4635 * are to be omitted:
4636 *
4637 * f = File.new('t.txt')
4638 * f.readlines(chomp: true)
4639 * # => ["First line", "Second line", "", "Fourth line", "Fifth line"]
4640 * f.close
4641 *
4642 */
4643
4644static VALUE
4645rb_io_readlines(int argc, VALUE *argv, VALUE io)
4646{
4647 struct getline_arg args;
4648
4649 prepare_getline_args(argc, argv, &args, io);
4650 return io_readlines(&args, io);
4651}
4652
4653static VALUE
4654io_readlines(const struct getline_arg *arg, VALUE io)
4655{
4656 VALUE line, ary;
4657
4658 if (arg->limit == 0)
4659 rb_raise(rb_eArgError, "invalid limit: 0 for readlines");
4660 ary = rb_ary_new();
4661 while (!NIL_P(line = rb_io_getline_1(arg->rs, arg->limit, arg->chomp, io))) {
4662 rb_ary_push(ary, line);
4663 }
4664 return ary;
4665}
4666
4667/*
4668 * call-seq:
4669 * each_line(sep = $/, chomp: false) {|line| ... } -> self
4670 * each_line(limit, chomp: false) {|line| ... } -> self
4671 * each_line(sep, limit, chomp: false) {|line| ... } -> self
4672 * each_line -> enumerator
4673 *
4674 * Calls the block with each remaining line read from the stream;
4675 * returns +self+.
4676 * Does nothing if already at end-of-stream;
4677 * See {Line IO}[rdoc-ref:IO@Line+IO].
4678 *
4679 * With no arguments given, reads lines
4680 * as determined by line separator <tt>$/</tt>:
4681 *
4682 * f = File.new('t.txt')
4683 * f.each_line {|line| p line }
4684 * f.each_line {|line| fail 'Cannot happen' }
4685 * f.close
4686 *
4687 * Output:
4688 *
4689 * "First line\n"
4690 * "Second line\n"
4691 * "\n"
4692 * "Fourth line\n"
4693 * "Fifth line\n"
4694 *
4695 * With only string argument +sep+ given,
4696 * reads lines as determined by line separator +sep+;
4697 * see {Line Separator}[rdoc-ref:IO@Line+Separator]:
4698 *
4699 * f = File.new('t.txt')
4700 * f.each_line('li') {|line| p line }
4701 * f.close
4702 *
4703 * Output:
4704 *
4705 * "First li"
4706 * "ne\nSecond li"
4707 * "ne\n\nFourth li"
4708 * "ne\nFifth li"
4709 * "ne\n"
4710 *
4711 * The two special values for +sep+ are honored:
4712 *
4713 * f = File.new('t.txt')
4714 * # Get all into one string.
4715 * f.each_line(nil) {|line| p line }
4716 * f.close
4717 *
4718 * Output:
4719 *
4720 * "First line\nSecond line\n\nFourth line\nFifth line\n"
4721 *
4722 * f.rewind
4723 * # Get paragraphs (up to two line separators).
4724 * f.each_line('') {|line| p line }
4725 *
4726 * Output:
4727 *
4728 * "First line\nSecond line\n\n"
4729 * "Fourth line\nFifth line\n"
4730 *
4731 * With only integer argument +limit+ given,
4732 * limits the number of bytes in each line;
4733 * see {Line Limit}[rdoc-ref:IO@Line+Limit]:
4734 *
4735 * f = File.new('t.txt')
4736 * f.each_line(8) {|line| p line }
4737 * f.close
4738 *
4739 * Output:
4740 *
4741 * "First li"
4742 * "ne\n"
4743 * "Second l"
4744 * "ine\n"
4745 * "\n"
4746 * "Fourth l"
4747 * "ine\n"
4748 * "Fifth li"
4749 * "ne\n"
4750 *
4751 * With arguments +sep+ and +limit+ given,
4752 * combines the two behaviors
4753 * (see {Line Separator and Line Limit}[rdoc-ref:IO@Line+Separator+and+Line+Limit]).
4754 *
4755 * Optional keyword argument +chomp+ specifies whether line separators
4756 * are to be omitted:
4757 *
4758 * f = File.new('t.txt')
4759 * f.each_line(chomp: true) {|line| p line }
4760 * f.close
4761 *
4762 * Output:
4763 *
4764 * "First line"
4765 * "Second line"
4766 * ""
4767 * "Fourth line"
4768 * "Fifth line"
4769 *
4770 * Returns an Enumerator if no block is given.
4771 */
4772
4773static VALUE
4774rb_io_each_line(int argc, VALUE *argv, VALUE io)
4775{
4776 VALUE str;
4777 struct getline_arg args;
4778
4779 RETURN_ENUMERATOR(io, argc, argv);
4780 prepare_getline_args(argc, argv, &args, io);
4781 if (args.limit == 0)
4782 rb_raise(rb_eArgError, "invalid limit: 0 for each_line");
4783 while (!NIL_P(str = rb_io_getline_1(args.rs, args.limit, args.chomp, io))) {
4784 rb_yield(str);
4785 }
4786 return io;
4787}
4788
4789/*
4790 * call-seq:
4791 * each_byte {|byte| ... } -> self
4792 * each_byte -> enumerator
4793 *
4794 * Calls the given block with each byte (0..255) in the stream; returns +self+.
4795 * See {Byte IO}[rdoc-ref:IO@Byte+IO].
4796 *
4797 * f = File.new('t.rus')
4798 * a = []
4799 * f.each_byte {|b| a << b }
4800 * a # => [209, 130, 208, 181, 209, 129, 209, 130]
4801 * f.close
4802 *
4803 * Returns an Enumerator if no block is given.
4804 *
4805 * Related: IO#each_char, IO#each_codepoint.
4806 *
4807 */
4808
4809static VALUE
4810rb_io_each_byte(VALUE io)
4811{
4812 rb_io_t *fptr;
4813
4814 RETURN_ENUMERATOR(io, 0, 0);
4815 GetOpenFile(io, fptr);
4816
4817 do {
4818 while (fptr->rbuf.len > 0) {
4819 char *p = fptr->rbuf.ptr + fptr->rbuf.off++;
4820 fptr->rbuf.len--;
4821 rb_yield(INT2FIX(*p & 0xff));
4823 errno = 0;
4824 }
4825 READ_CHECK(fptr);
4826 } while (io_fillbuf(fptr) >= 0);
4827 return io;
4828}
4829
4830static VALUE
4831io_getc(rb_io_t *fptr, rb_encoding *enc)
4832{
4833 int r, n, cr = 0;
4834 VALUE str;
4835
4836 if (NEED_READCONV(fptr)) {
4837 rb_encoding *read_enc = io_read_encoding(fptr);
4838
4839 str = Qnil;
4840 SET_BINARY_MODE(fptr);
4841 make_readconv(fptr, 0);
4842
4843 while (1) {
4844 if (fptr->cbuf.len) {
4845 r = rb_enc_precise_mbclen(fptr->cbuf.ptr+fptr->cbuf.off,
4846 fptr->cbuf.ptr+fptr->cbuf.off+fptr->cbuf.len,
4847 read_enc);
4848 if (!MBCLEN_NEEDMORE_P(r))
4849 break;
4850 if (fptr->cbuf.len == fptr->cbuf.capa) {
4851 rb_raise(rb_eIOError, "too long character");
4852 }
4853 }
4854
4855 if (more_char(fptr) == MORE_CHAR_FINISHED) {
4856 if (fptr->cbuf.len == 0) {
4857 clear_readconv(fptr);
4858 return Qnil;
4859 }
4860 /* return an unit of an incomplete character just before EOF */
4861 str = rb_enc_str_new(fptr->cbuf.ptr+fptr->cbuf.off, 1, read_enc);
4862 fptr->cbuf.off += 1;
4863 fptr->cbuf.len -= 1;
4864 if (fptr->cbuf.len == 0) clear_readconv(fptr);
4866 return str;
4867 }
4868 }
4869 if (MBCLEN_INVALID_P(r)) {
4870 r = rb_enc_mbclen(fptr->cbuf.ptr+fptr->cbuf.off,
4871 fptr->cbuf.ptr+fptr->cbuf.off+fptr->cbuf.len,
4872 read_enc);
4873 io_shift_cbuf(fptr, r, &str);
4875 }
4876 else {
4877 io_shift_cbuf(fptr, MBCLEN_CHARFOUND_LEN(r), &str);
4879 if (MBCLEN_CHARFOUND_LEN(r) == 1 && rb_enc_asciicompat(read_enc) &&
4880 ISASCII(RSTRING_PTR(str)[0])) {
4881 cr = ENC_CODERANGE_7BIT;
4882 }
4883 }
4884 str = io_enc_str(str, fptr);
4885 ENC_CODERANGE_SET(str, cr);
4886 return str;
4887 }
4888
4889 NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr);
4890 if (io_fillbuf(fptr) < 0) {
4891 return Qnil;
4892 }
4893 if (rb_enc_asciicompat(enc) && ISASCII(fptr->rbuf.ptr[fptr->rbuf.off])) {
4894 str = rb_str_new(fptr->rbuf.ptr+fptr->rbuf.off, 1);
4895 fptr->rbuf.off += 1;
4896 fptr->rbuf.len -= 1;
4897 cr = ENC_CODERANGE_7BIT;
4898 }
4899 else {
4900 r = rb_enc_precise_mbclen(fptr->rbuf.ptr+fptr->rbuf.off, fptr->rbuf.ptr+fptr->rbuf.off+fptr->rbuf.len, enc);
4901 if (MBCLEN_CHARFOUND_P(r) &&
4902 (n = MBCLEN_CHARFOUND_LEN(r)) <= fptr->rbuf.len) {
4903 str = rb_str_new(fptr->rbuf.ptr+fptr->rbuf.off, n);
4904 fptr->rbuf.off += n;
4905 fptr->rbuf.len -= n;
4907 }
4908 else if (MBCLEN_NEEDMORE_P(r)) {
4909 str = rb_str_new(fptr->rbuf.ptr+fptr->rbuf.off, fptr->rbuf.len);
4910 fptr->rbuf.len = 0;
4911 getc_needmore:
4912 if (io_fillbuf(fptr) != -1) {
4913 rb_str_cat(str, fptr->rbuf.ptr+fptr->rbuf.off, 1);
4914 fptr->rbuf.off++;
4915 fptr->rbuf.len--;
4916 r = rb_enc_precise_mbclen(RSTRING_PTR(str), RSTRING_PTR(str)+RSTRING_LEN(str), enc);
4917 if (MBCLEN_NEEDMORE_P(r)) {
4918 goto getc_needmore;
4919 }
4920 else if (MBCLEN_CHARFOUND_P(r)) {
4922 }
4923 }
4924 }
4925 else {
4926 str = rb_str_new(fptr->rbuf.ptr+fptr->rbuf.off, 1);
4927 fptr->rbuf.off++;
4928 fptr->rbuf.len--;
4929 }
4930 }
4931 if (!cr) cr = ENC_CODERANGE_BROKEN;
4932 str = io_enc_str(str, fptr);
4933 ENC_CODERANGE_SET(str, cr);
4934 return str;
4935}
4936
4937/*
4938 * call-seq:
4939 * each_char {|c| ... } -> self
4940 * each_char -> enumerator
4941 *
4942 * Calls the given block with each character in the stream; returns +self+.
4943 * See {Character IO}[rdoc-ref:IO@Character+IO].
4944 *
4945 * f = File.new('t.rus')
4946 * a = []
4947 * f.each_char {|c| a << c.ord }
4948 * a # => [1090, 1077, 1089, 1090]
4949 * f.close
4950 *
4951 * Returns an Enumerator if no block is given.
4952 *
4953 * Related: IO#each_byte, IO#each_codepoint.
4954 *
4955 */
4956
4957static VALUE
4958rb_io_each_char(VALUE io)
4959{
4960 rb_io_t *fptr;
4961 rb_encoding *enc;
4962 VALUE c;
4963
4964 RETURN_ENUMERATOR(io, 0, 0);
4965 GetOpenFile(io, fptr);
4967
4968 enc = io_input_encoding(fptr);
4969 READ_CHECK(fptr);
4970 while (!NIL_P(c = io_getc(fptr, enc))) {
4971 rb_yield(c);
4972 }
4973 return io;
4974}
4975
4976/*
4977 * call-seq:
4978 * each_codepoint {|c| ... } -> self
4979 * each_codepoint -> enumerator
4980 *
4981 * Calls the given block with each codepoint in the stream; returns +self+:
4982 *
4983 * f = File.new('t.rus')
4984 * a = []
4985 * f.each_codepoint {|c| a << c }
4986 * a # => [1090, 1077, 1089, 1090]
4987 * f.close
4988 *
4989 * Returns an Enumerator if no block is given.
4990 *
4991 * Related: IO#each_byte, IO#each_char.
4992 *
4993 */
4994
4995static VALUE
4996rb_io_each_codepoint(VALUE io)
4997{
4998 rb_io_t *fptr;
4999 rb_encoding *enc;
5000 unsigned int c;
5001 int r, n;
5002
5003 RETURN_ENUMERATOR(io, 0, 0);
5004 GetOpenFile(io, fptr);
5006
5007 READ_CHECK(fptr);
5008 enc = io_read_encoding(fptr);
5009 if (NEED_READCONV(fptr)) {
5010 SET_BINARY_MODE(fptr);
5011 r = 1; /* no invalid char yet */
5012 for (;;) {
5013 make_readconv(fptr, 0);
5014 for (;;) {
5015 if (fptr->cbuf.len) {
5016 r = rb_enc_precise_mbclen(fptr->cbuf.ptr+fptr->cbuf.off,
5017 fptr->cbuf.ptr+fptr->cbuf.off+fptr->cbuf.len,
5018 enc);
5019 if (!MBCLEN_NEEDMORE_P(r))
5020 break;
5021 if (fptr->cbuf.len == fptr->cbuf.capa) {
5022 rb_raise(rb_eIOError, "too long character");
5023 }
5024 }
5025 if (more_char(fptr) == MORE_CHAR_FINISHED) {
5026 clear_readconv(fptr);
5027 if (!MBCLEN_CHARFOUND_P(r)) {
5028 goto invalid;
5029 }
5030 return io;
5031 }
5032 }
5033 if (MBCLEN_INVALID_P(r)) {
5034 goto invalid;
5035 }
5036 n = MBCLEN_CHARFOUND_LEN(r);
5037 c = rb_enc_codepoint(fptr->cbuf.ptr+fptr->cbuf.off,
5038 fptr->cbuf.ptr+fptr->cbuf.off+fptr->cbuf.len,
5039 enc);
5040 fptr->cbuf.off += n;
5041 fptr->cbuf.len -= n;
5042 rb_yield(UINT2NUM(c));
5044 }
5045 }
5046 NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr);
5047 while (io_fillbuf(fptr) >= 0) {
5048 r = rb_enc_precise_mbclen(fptr->rbuf.ptr+fptr->rbuf.off,
5049 fptr->rbuf.ptr+fptr->rbuf.off+fptr->rbuf.len, enc);
5050 if (MBCLEN_CHARFOUND_P(r) &&
5051 (n = MBCLEN_CHARFOUND_LEN(r)) <= fptr->rbuf.len) {
5052 c = rb_enc_codepoint(fptr->rbuf.ptr+fptr->rbuf.off,
5053 fptr->rbuf.ptr+fptr->rbuf.off+fptr->rbuf.len, enc);
5054 fptr->rbuf.off += n;
5055 fptr->rbuf.len -= n;
5056 rb_yield(UINT2NUM(c));
5057 }
5058 else if (MBCLEN_INVALID_P(r)) {
5059 goto invalid;
5060 }
5061 else if (MBCLEN_NEEDMORE_P(r)) {
5062 char cbuf[8], *p = cbuf;
5063 int more = MBCLEN_NEEDMORE_LEN(r);
5064 if (more > numberof(cbuf)) goto invalid;
5065 more += n = fptr->rbuf.len;
5066 if (more > numberof(cbuf)) goto invalid;
5067 while ((n = (int)read_buffered_data(p, more, fptr)) > 0 &&
5068 (p += n, (more -= n) > 0)) {
5069 if (io_fillbuf(fptr) < 0) goto invalid;
5070 if ((n = fptr->rbuf.len) > more) n = more;
5071 }
5072 r = rb_enc_precise_mbclen(cbuf, p, enc);
5073 if (!MBCLEN_CHARFOUND_P(r)) goto invalid;
5074 c = rb_enc_codepoint(cbuf, p, enc);
5075 rb_yield(UINT2NUM(c));
5076 }
5077 else {
5078 continue;
5079 }
5081 }
5082 return io;
5083
5084 invalid:
5085 rb_raise(rb_eArgError, "invalid byte sequence in %s", rb_enc_name(enc));
5087}
5088
5089/*
5090 * call-seq:
5091 * getc -> character or nil
5092 *
5093 * Reads and returns the next 1-character string from the stream;
5094 * returns +nil+ if already at end-of-stream.
5095 * See {Character IO}[rdoc-ref:IO@Character+IO].
5096 *
5097 * f = File.open('t.txt')
5098 * f.getc # => "F"
5099 * f.close
5100 * f = File.open('t.rus')
5101 * f.getc.ord # => 1090
5102 * f.close
5103 *
5104 * Related: IO#readchar (may raise EOFError).
5105 *
5106 */
5107
5108static VALUE
5109rb_io_getc(VALUE io)
5110{
5111 rb_io_t *fptr;
5112 rb_encoding *enc;
5113
5114 GetOpenFile(io, fptr);
5116
5117 enc = io_input_encoding(fptr);
5118 READ_CHECK(fptr);
5119 return io_getc(fptr, enc);
5120}
5121
5122/*
5123 * call-seq:
5124 * readchar -> string
5125 *
5126 * Reads and returns the next 1-character string from the stream;
5127 * raises EOFError if already at end-of-stream.
5128 * See {Character IO}[rdoc-ref:IO@Character+IO].
5129 *
5130 * f = File.open('t.txt')
5131 * f.readchar # => "F"
5132 * f.close
5133 * f = File.open('t.rus')
5134 * f.readchar.ord # => 1090
5135 * f.close
5136 *
5137 * Related: IO#getc (will not raise EOFError).
5138 *
5139 */
5140
5141static VALUE
5142rb_io_readchar(VALUE io)
5143{
5144 VALUE c = rb_io_getc(io);
5145
5146 if (NIL_P(c)) {
5147 rb_eof_error();
5148 }
5149 return c;
5150}
5151
5152/*
5153 * call-seq:
5154 * getbyte -> integer or nil
5155 *
5156 * Reads and returns the next byte (in range 0..255) from the stream;
5157 * returns +nil+ if already at end-of-stream.
5158 * See {Byte IO}[rdoc-ref:IO@Byte+IO].
5159 *
5160 * f = File.open('t.txt')
5161 * f.getbyte # => 70
5162 * f.close
5163 * f = File.open('t.rus')
5164 * f.getbyte # => 209
5165 * f.close
5166 *
5167 * Related: IO#readbyte (may raise EOFError).
5168 */
5169
5170VALUE
5172{
5173 rb_io_t *fptr;
5174 int c;
5175
5176 GetOpenFile(io, fptr);
5178 READ_CHECK(fptr);
5179 VALUE r_stdout = rb_ractor_stdout();
5180 if (fptr->fd == 0 && (fptr->mode & FMODE_TTY) && RB_TYPE_P(r_stdout, T_FILE)) {
5181 rb_io_t *ofp;
5182 GetOpenFile(r_stdout, ofp);
5183 if (ofp->mode & FMODE_TTY) {
5184 rb_io_flush(r_stdout);
5185 }
5186 }
5187 if (io_fillbuf(fptr) < 0) {
5188 return Qnil;
5189 }
5190 fptr->rbuf.off++;
5191 fptr->rbuf.len--;
5192 c = (unsigned char)fptr->rbuf.ptr[fptr->rbuf.off-1];
5193 return INT2FIX(c & 0xff);
5194}
5195
5196/*
5197 * call-seq:
5198 * readbyte -> integer
5199 *
5200 * Reads and returns the next byte (in range 0..255) from the stream;
5201 * raises EOFError if already at end-of-stream.
5202 * See {Byte IO}[rdoc-ref:IO@Byte+IO].
5203 *
5204 * f = File.open('t.txt')
5205 * f.readbyte # => 70
5206 * f.close
5207 * f = File.open('t.rus')
5208 * f.readbyte # => 209
5209 * f.close
5210 *
5211 * Related: IO#getbyte (will not raise EOFError).
5212 *
5213 */
5214
5215static VALUE
5216rb_io_readbyte(VALUE io)
5217{
5218 VALUE c = rb_io_getbyte(io);
5219
5220 if (NIL_P(c)) {
5221 rb_eof_error();
5222 }
5223 return c;
5224}
5225
5226/*
5227 * call-seq:
5228 * ungetbyte(integer) -> nil
5229 * ungetbyte(string) -> nil
5230 *
5231 * Pushes back ("unshifts") the given data onto the stream's buffer,
5232 * placing the data so that it is next to be read; returns +nil+.
5233 * See {Byte IO}[rdoc-ref:IO@Byte+IO].
5234 *
5235 * Note that:
5236 *
5237 * - Calling the method has no effect with unbuffered reads (such as IO#sysread).
5238 * - Calling #rewind on the stream discards the pushed-back data.
5239 *
5240 * When argument +integer+ is given, uses only its low-order byte:
5241 *
5242 * File.write('t.tmp', '012')
5243 * f = File.open('t.tmp')
5244 * f.ungetbyte(0x41) # => nil
5245 * f.read # => "A012"
5246 * f.rewind
5247 * f.ungetbyte(0x4243) # => nil
5248 * f.read # => "C012"
5249 * f.close
5250 *
5251 * When argument +string+ is given, uses all bytes:
5252 *
5253 * File.write('t.tmp', '012')
5254 * f = File.open('t.tmp')
5255 * f.ungetbyte('A') # => nil
5256 * f.read # => "A012"
5257 * f.rewind
5258 * f.ungetbyte('BCDE') # => nil
5259 * f.read # => "BCDE012"
5260 * f.close
5261 *
5262 */
5263
5264VALUE
5266{
5267 rb_io_t *fptr;
5268
5269 GetOpenFile(io, fptr);
5271 switch (TYPE(b)) {
5272 case T_NIL:
5273 return Qnil;
5274 case T_FIXNUM:
5275 case T_BIGNUM: ;
5276 VALUE v = rb_int_modulo(b, INT2FIX(256));
5277 unsigned char c = NUM2INT(v) & 0xFF;
5278 b = rb_str_new((const char *)&c, 1);
5279 break;
5280 default:
5281 StringValue(b);
5282 }
5283 io_ungetbyte(b, fptr);
5284 return Qnil;
5285}
5286
5287/*
5288 * call-seq:
5289 * ungetc(integer) -> nil
5290 * ungetc(string) -> nil
5291 *
5292 * Pushes back ("unshifts") the given data onto the stream's buffer,
5293 * placing the data so that it is next to be read; returns +nil+.
5294 * See {Character IO}[rdoc-ref:IO@Character+IO].
5295 *
5296 * Note that:
5297 *
5298 * - Calling the method has no effect with unbuffered reads (such as IO#sysread).
5299 * - Calling #rewind on the stream discards the pushed-back data.
5300 *
5301 * When argument +integer+ is given, interprets the integer as a character:
5302 *
5303 * File.write('t.tmp', '012')
5304 * f = File.open('t.tmp')
5305 * f.ungetc(0x41) # => nil
5306 * f.read # => "A012"
5307 * f.rewind
5308 * f.ungetc(0x0442) # => nil
5309 * f.getc.ord # => 1090
5310 * f.close
5311 *
5312 * When argument +string+ is given, uses all characters:
5313 *
5314 * File.write('t.tmp', '012')
5315 * f = File.open('t.tmp')
5316 * f.ungetc('A') # => nil
5317 * f.read # => "A012"
5318 * f.rewind
5319 * f.ungetc("\u0442\u0435\u0441\u0442") # => nil
5320 * f.getc.ord # => 1090
5321 * f.getc.ord # => 1077
5322 * f.getc.ord # => 1089
5323 * f.getc.ord # => 1090
5324 * f.close
5325 *
5326 */
5327
5328VALUE
5330{
5331 rb_io_t *fptr;
5332 long len;
5333
5334 GetOpenFile(io, fptr);
5336 if (FIXNUM_P(c)) {
5337 c = rb_enc_uint_chr(FIX2UINT(c), io_read_encoding(fptr));
5338 }
5339 else if (RB_BIGNUM_TYPE_P(c)) {
5340 c = rb_enc_uint_chr(NUM2UINT(c), io_read_encoding(fptr));
5341 }
5342 else {
5343 StringValue(c);
5344 }
5345 if (NEED_READCONV(fptr)) {
5346 SET_BINARY_MODE(fptr);
5347 len = RSTRING_LEN(c);
5348#if SIZEOF_LONG > SIZEOF_INT
5349 if (len > INT_MAX)
5350 rb_raise(rb_eIOError, "ungetc failed");
5351#endif
5352 make_readconv(fptr, (int)len);
5353 if (fptr->cbuf.capa - fptr->cbuf.len < len)
5354 rb_raise(rb_eIOError, "ungetc failed");
5355 if (fptr->cbuf.off < len) {
5356 MEMMOVE(fptr->cbuf.ptr+fptr->cbuf.capa-fptr->cbuf.len,
5357 fptr->cbuf.ptr+fptr->cbuf.off,
5358 char, fptr->cbuf.len);
5359 fptr->cbuf.off = fptr->cbuf.capa-fptr->cbuf.len;
5360 }
5361 fptr->cbuf.off -= (int)len;
5362 fptr->cbuf.len += (int)len;
5363 MEMMOVE(fptr->cbuf.ptr+fptr->cbuf.off, RSTRING_PTR(c), char, len);
5364 }
5365 else {
5366 NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr);
5367 io_ungetbyte(c, fptr);
5368 }
5369 return Qnil;
5370}
5371
5372/*
5373 * call-seq:
5374 * isatty -> true or false
5375 *
5376 * Returns +true+ if the stream is associated with a terminal device (tty),
5377 * +false+ otherwise:
5378 *
5379 * f = File.new('t.txt').isatty #=> false
5380 * f.close
5381 * f = File.new('/dev/tty').isatty #=> true
5382 * f.close
5383 *
5384 */
5385
5386static VALUE
5387rb_io_isatty(VALUE io)
5388{
5389 rb_io_t *fptr;
5390
5391 GetOpenFile(io, fptr);
5392 return RBOOL(isatty(fptr->fd) != 0);
5393}
5394
5395#if defined(HAVE_FCNTL) && defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
5396/*
5397 * call-seq:
5398 * close_on_exec? -> true or false
5399 *
5400 * Returns +true+ if the stream will be closed on exec, +false+ otherwise:
5401 *
5402 * f = File.open('t.txt')
5403 * f.close_on_exec? # => true
5404 * f.close_on_exec = false
5405 * f.close_on_exec? # => false
5406 * f.close
5407 *
5408 */
5409
5410static VALUE
5411rb_io_close_on_exec_p(VALUE io)
5412{
5413 rb_io_t *fptr;
5414 VALUE write_io;
5415 int fd, ret;
5416
5417 write_io = GetWriteIO(io);
5418 if (io != write_io) {
5419 GetOpenFile(write_io, fptr);
5420 if (fptr && 0 <= (fd = fptr->fd)) {
5421 if ((ret = fcntl(fd, F_GETFD)) == -1) rb_sys_fail_path(fptr->pathv);
5422 if (!(ret & FD_CLOEXEC)) return Qfalse;
5423 }
5424 }
5425
5426 GetOpenFile(io, fptr);
5427 if (fptr && 0 <= (fd = fptr->fd)) {
5428 if ((ret = fcntl(fd, F_GETFD)) == -1) rb_sys_fail_path(fptr->pathv);
5429 if (!(ret & FD_CLOEXEC)) return Qfalse;
5430 }
5431 return Qtrue;
5432}
5433#else
5434#define rb_io_close_on_exec_p rb_f_notimplement
5435#endif
5436
5437#if defined(HAVE_FCNTL) && defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
5438/*
5439 * call-seq:
5440 * self.close_on_exec = bool -> true or false
5441 *
5442 * Sets a close-on-exec flag.
5443 *
5444 * f = File.open(File::NULL)
5445 * f.close_on_exec = true
5446 * system("cat", "/proc/self/fd/#{f.fileno}") # cat: /proc/self/fd/3: No such file or directory
5447 * f.closed? #=> false
5448 *
5449 * Ruby sets close-on-exec flags of all file descriptors by default
5450 * since Ruby 2.0.0.
5451 * So you don't need to set by yourself.
5452 * Also, unsetting a close-on-exec flag can cause file descriptor leak
5453 * if another thread use fork() and exec() (via system() method for example).
5454 * If you really needs file descriptor inheritance to child process,
5455 * use spawn()'s argument such as fd=>fd.
5456 */
5457
5458static VALUE
5459rb_io_set_close_on_exec(VALUE io, VALUE arg)
5460{
5461 int flag = RTEST(arg) ? FD_CLOEXEC : 0;
5462 rb_io_t *fptr;
5463 VALUE write_io;
5464 int fd, ret;
5465
5466 write_io = GetWriteIO(io);
5467 if (io != write_io) {
5468 GetOpenFile(write_io, fptr);
5469 if (fptr && 0 <= (fd = fptr->fd)) {
5470 if ((ret = fcntl(fptr->fd, F_GETFD)) == -1) rb_sys_fail_path(fptr->pathv);
5471 if ((ret & FD_CLOEXEC) != flag) {
5472 ret = (ret & ~FD_CLOEXEC) | flag;
5473 ret = fcntl(fd, F_SETFD, ret);
5474 if (ret != 0) rb_sys_fail_path(fptr->pathv);
5475 }
5476 }
5477
5478 }
5479
5480 GetOpenFile(io, fptr);
5481 if (fptr && 0 <= (fd = fptr->fd)) {
5482 if ((ret = fcntl(fd, F_GETFD)) == -1) rb_sys_fail_path(fptr->pathv);
5483 if ((ret & FD_CLOEXEC) != flag) {
5484 ret = (ret & ~FD_CLOEXEC) | flag;
5485 ret = fcntl(fd, F_SETFD, ret);
5486 if (ret != 0) rb_sys_fail_path(fptr->pathv);
5487 }
5488 }
5489 return Qnil;
5490}
5491#else
5492#define rb_io_set_close_on_exec rb_f_notimplement
5493#endif
5494
5495#define RUBY_IO_EXTERNAL_P(f) ((f)->mode & FMODE_EXTERNAL)
5496#define PREP_STDIO_NAME(f) (RSTRING_PTR((f)->pathv))
5497
5498static VALUE
5499finish_writeconv(rb_io_t *fptr, int noalloc)
5500{
5501 unsigned char *ds, *dp, *de;
5503
5504 if (!fptr->wbuf.ptr) {
5505 unsigned char buf[1024];
5506
5508 while (res == econv_destination_buffer_full) {
5509 ds = dp = buf;
5510 de = buf + sizeof(buf);
5511 res = rb_econv_convert(fptr->writeconv, NULL, NULL, &dp, de, 0);
5512 while (dp-ds) {
5513 size_t remaining = dp-ds;
5514 long result = rb_io_write_memory(fptr, ds, remaining);
5515
5516 if (result > 0) {
5517 ds += result;
5518 if ((size_t)result == remaining) break;
5519 }
5520 else if (rb_io_maybe_wait_writable(errno, fptr->self, RUBY_IO_TIMEOUT_DEFAULT)) {
5521 if (fptr->fd < 0)
5522 return noalloc ? Qtrue : rb_exc_new3(rb_eIOError, rb_str_new_cstr(closed_stream));
5523 }
5524 else {
5525 return noalloc ? Qtrue : INT2NUM(errno);
5526 }
5527 }
5528 if (res == econv_invalid_byte_sequence ||
5529 res == econv_incomplete_input ||
5531 return noalloc ? Qtrue : rb_econv_make_exception(fptr->writeconv);
5532 }
5533 }
5534
5535 return Qnil;
5536 }
5537
5539 while (res == econv_destination_buffer_full) {
5540 if (fptr->wbuf.len == fptr->wbuf.capa) {
5541 if (io_fflush(fptr) < 0) {
5542 return noalloc ? Qtrue : INT2NUM(errno);
5543 }
5544 }
5545
5546 ds = dp = (unsigned char *)fptr->wbuf.ptr + fptr->wbuf.off + fptr->wbuf.len;
5547 de = (unsigned char *)fptr->wbuf.ptr + fptr->wbuf.capa;
5548 res = rb_econv_convert(fptr->writeconv, NULL, NULL, &dp, de, 0);
5549 fptr->wbuf.len += (int)(dp - ds);
5550 if (res == econv_invalid_byte_sequence ||
5551 res == econv_incomplete_input ||
5553 return noalloc ? Qtrue : rb_econv_make_exception(fptr->writeconv);
5554 }
5555 }
5556 return Qnil;
5557}
5558
5560 rb_io_t *fptr;
5561 int noalloc;
5562};
5563
5564static VALUE
5565finish_writeconv_sync(VALUE arg)
5566{
5567 struct finish_writeconv_arg *p = (struct finish_writeconv_arg *)arg;
5568 return finish_writeconv(p->fptr, p->noalloc);
5569}
5570
5571static void*
5572nogvl_close(void *ptr)
5573{
5574 int *fd = ptr;
5575
5576 return (void*)(intptr_t)close(*fd);
5577}
5578
5579static int
5580maygvl_close(int fd, int keepgvl)
5581{
5582 if (keepgvl)
5583 return close(fd);
5584
5585 /*
5586 * close() may block for certain file types (NFS, SO_LINGER sockets,
5587 * inotify), so let other threads run.
5588 */
5589 return IO_WITHOUT_GVL_INT(nogvl_close, &fd);
5590}
5591
5592static void*
5593nogvl_fclose(void *ptr)
5594{
5595 FILE *file = ptr;
5596
5597 return (void*)(intptr_t)fclose(file);
5598}
5599
5600static int
5601maygvl_fclose(FILE *file, int keepgvl)
5602{
5603 if (keepgvl)
5604 return fclose(file);
5605
5606 return IO_WITHOUT_GVL_INT(nogvl_fclose, file);
5607}
5608
5609static void free_io_buffer(rb_io_buffer_t *buf);
5610
5611static void
5612fptr_finalize_flush(rb_io_t *fptr, int noraise, int keepgvl)
5613{
5614 VALUE error = Qnil;
5615 int fd = fptr->fd;
5616 FILE *stdio_file = fptr->stdio_file;
5617 int mode = fptr->mode;
5618
5619 if (fptr->writeconv) {
5620 if (!NIL_P(fptr->write_lock) && !noraise) {
5621 struct finish_writeconv_arg arg;
5622 arg.fptr = fptr;
5623 arg.noalloc = noraise;
5624 error = rb_mutex_synchronize(fptr->write_lock, finish_writeconv_sync, (VALUE)&arg);
5625 }
5626 else {
5627 error = finish_writeconv(fptr, noraise);
5628 }
5629 }
5630 if (fptr->wbuf.len) {
5631 if (noraise) {
5632 io_flush_buffer_sync(fptr);
5633 }
5634 else {
5635 if (io_fflush(fptr) < 0 && NIL_P(error)) {
5636 error = INT2NUM(errno);
5637 }
5638 }
5639 }
5640
5641 int done = 0;
5642
5643 if (RUBY_IO_EXTERNAL_P(fptr) || fd <= 2) {
5644 // Need to keep FILE objects of stdin, stdout and stderr, so we are done:
5645 done = 1;
5646 }
5647
5648 fptr->fd = -1;
5649 fptr->stdio_file = 0;
5651
5652 // Wait for blocking operations to ensure they do not hit EBADF:
5653 rb_thread_io_close_wait(fptr);
5654
5655 if (!done && stdio_file) {
5656 // stdio_file is deallocated anyway even if fclose failed.
5657 if ((maygvl_fclose(stdio_file, noraise) < 0) && NIL_P(error)) {
5658 if (!noraise) {
5659 error = INT2NUM(errno);
5660 }
5661 }
5662
5663 done = 1;
5664 }
5665
5666 VALUE scheduler = rb_fiber_scheduler_current();
5667 if (!done && fd >= 0 && scheduler != Qnil) {
5668 VALUE result = rb_fiber_scheduler_io_close(scheduler, RB_INT2NUM(fd));
5669
5670 if (!UNDEF_P(result)) {
5671 done = RTEST(result);
5672 }
5673 }
5674
5675 if (!done && fd >= 0) {
5676 // fptr->fd may be closed even if close fails. POSIX doesn't specify it.
5677 // We assumes it is closed.
5678
5679 keepgvl |= !(mode & FMODE_WRITABLE);
5680 keepgvl |= noraise;
5681 if ((maygvl_close(fd, keepgvl) < 0) && NIL_P(error)) {
5682 if (!noraise) {
5683 error = INT2NUM(errno);
5684 }
5685 }
5686
5687 done = 1;
5688 }
5689
5690 if (!NIL_P(error) && !noraise) {
5691 if (RB_INTEGER_TYPE_P(error))
5692 rb_syserr_fail_path(NUM2INT(error), fptr->pathv);
5693 else
5694 rb_exc_raise(error);
5695 }
5696}
5697
5698static void
5699fptr_finalize(rb_io_t *fptr, int noraise)
5700{
5701 fptr_finalize_flush(fptr, noraise, FALSE);
5702 free_io_buffer(&fptr->rbuf);
5703 free_io_buffer(&fptr->wbuf);
5704 clear_codeconv(fptr);
5705}
5706
5707static void
5708rb_io_fptr_cleanup(rb_io_t *fptr, int noraise)
5709{
5710 if (fptr->finalize) {
5711 (*fptr->finalize)(fptr, noraise);
5712 }
5713 else {
5714 fptr_finalize(fptr, noraise);
5715 }
5716}
5717
5718static void
5719free_io_buffer(rb_io_buffer_t *buf)
5720{
5721 if (buf->ptr) {
5722 ruby_sized_xfree(buf->ptr, (size_t)buf->capa);
5723 buf->ptr = NULL;
5724 }
5725}
5726
5727static void
5728clear_readconv(rb_io_t *fptr)
5729{
5730 if (fptr->readconv) {
5731 rb_econv_close(fptr->readconv);
5732 fptr->readconv = NULL;
5733 }
5734 free_io_buffer(&fptr->cbuf);
5735}
5736
5737static void
5738clear_writeconv(rb_io_t *fptr)
5739{
5740 if (fptr->writeconv) {
5742 fptr->writeconv = NULL;
5743 }
5744 fptr->writeconv_initialized = 0;
5745}
5746
5747static void
5748clear_codeconv(rb_io_t *fptr)
5749{
5750 clear_readconv(fptr);
5751 clear_writeconv(fptr);
5752}
5753
5754static void
5755rb_io_fptr_cleanup_all(rb_io_t *fptr)
5756{
5757 fptr->pathv = Qnil;
5758 if (0 <= fptr->fd)
5759 rb_io_fptr_cleanup(fptr, TRUE);
5760 fptr->write_lock = Qnil;
5761 free_io_buffer(&fptr->rbuf);
5762 free_io_buffer(&fptr->wbuf);
5763 clear_codeconv(fptr);
5764}
5765
5766int
5768{
5769 if (!io) return 0;
5770 rb_io_fptr_cleanup_all(io);
5771 free(io);
5772
5773 return 1;
5774}
5775
5776size_t
5777rb_io_memsize(const rb_io_t *io)
5778{
5779 size_t size = sizeof(rb_io_t);
5780 size += io->rbuf.capa;
5781 size += io->wbuf.capa;
5782 size += io->cbuf.capa;
5783 if (io->readconv) size += rb_econv_memsize(io->readconv);
5784 if (io->writeconv) size += rb_econv_memsize(io->writeconv);
5785
5786 struct rb_io_blocking_operation *blocking_operation = 0;
5787
5788 // Validate the fork generation of the IO object. If the IO object fork generation is different, the list of blocking operations is not valid memory. See `rb_io_blocking_operations` for the exact semantics.
5789 rb_serial_t fork_generation = GET_VM()->fork_gen;
5790 if (io->fork_generation == fork_generation) {
5791 ccan_list_for_each(&io->blocking_operations, blocking_operation, list) {
5792 size += sizeof(struct rb_io_blocking_operation);
5793 }
5794 }
5795
5796 return size;
5797}
5798
5799#ifdef _WIN32
5800/* keep GVL while closing to prevent crash on Windows */
5801# define KEEPGVL TRUE
5802#else
5803# define KEEPGVL FALSE
5804#endif
5805
5806static rb_io_t *
5807io_close_fptr(VALUE io)
5808{
5809 rb_io_t *fptr;
5810 VALUE write_io;
5811 rb_io_t *write_fptr;
5812
5813 write_io = GetWriteIO(io);
5814 if (io != write_io) {
5815 write_fptr = RFILE(write_io)->fptr;
5816 if (write_fptr && 0 <= write_fptr->fd) {
5817 rb_io_fptr_cleanup(write_fptr, TRUE);
5818 }
5819 }
5820
5821 fptr = RFILE(io)->fptr;
5822 if (!fptr) return 0;
5823 if (fptr->fd < 0) return 0;
5824
5825 // This guards against multiple threads closing the same IO object:
5826 if (rb_thread_io_close_interrupt(fptr)) {
5827 /* calls close(fptr->fd): */
5828 fptr_finalize_flush(fptr, FALSE, KEEPGVL);
5829 }
5830
5831 rb_io_fptr_cleanup(fptr, FALSE);
5832 return fptr;
5833}
5834
5835static void
5836fptr_waitpid(rb_io_t *fptr, int nohang)
5837{
5838 int status;
5839 if (fptr->pid) {
5840 rb_last_status_clear();
5841 rb_waitpid(fptr->pid, &status, nohang ? WNOHANG : 0);
5842 fptr->pid = 0;
5843 }
5844}
5845
5846VALUE
5848{
5849 rb_io_t *fptr = io_close_fptr(io);
5850 if (fptr) fptr_waitpid(fptr, 0);
5851 return Qnil;
5852}
5853
5854/*
5855 * call-seq:
5856 * close -> nil
5857 *
5858 * Closes the stream for both reading and writing
5859 * if open for either or both; returns +nil+.
5860 * See {Open and Closed Streams}[rdoc-ref:IO@Open+and+Closed+Streams].
5861 *
5862 * If the stream is open for writing, flushes any buffered writes
5863 * to the operating system before closing.
5864 *
5865 * If the stream was opened by IO.popen, sets global variable <tt>$?</tt>
5866 * (child exit status).
5867 *
5868 * It is not an error to close an IO object that has already been closed.
5869 * It just returns nil.
5870 *
5871 * Example:
5872 *
5873 * IO.popen('ruby', 'r+') do |pipe|
5874 * puts pipe.closed?
5875 * pipe.close
5876 * puts $?
5877 * puts pipe.closed?
5878 * end
5879 *
5880 * Output:
5881 *
5882 * false
5883 * pid 13760 exit 0
5884 * true
5885 *
5886 * Related: IO#close_read, IO#close_write, IO#closed?.
5887 */
5888
5889static VALUE
5890rb_io_close_m(VALUE io)
5891{
5892 rb_io_t *fptr = rb_io_get_fptr(io);
5893 if (fptr->fd < 0) {
5894 return Qnil;
5895 }
5896 rb_io_close(io);
5897 return Qnil;
5898}
5899
5900static VALUE
5901io_call_close(VALUE io)
5902{
5903 rb_check_funcall(io, rb_intern("close"), 0, 0);
5904 return io;
5905}
5906
5907static VALUE
5908ignore_closed_stream(VALUE io, VALUE exc)
5909{
5910 enum {mesg_len = sizeof(closed_stream)-1};
5911 VALUE mesg = rb_attr_get(exc, idMesg);
5912 if (!RB_TYPE_P(mesg, T_STRING) ||
5913 RSTRING_LEN(mesg) != mesg_len ||
5914 memcmp(RSTRING_PTR(mesg), closed_stream, mesg_len)) {
5915 rb_exc_raise(exc);
5916 }
5917 return io;
5918}
5919
5920static VALUE
5921io_close(VALUE io)
5922{
5923 VALUE closed = rb_check_funcall(io, rb_intern("closed?"), 0, 0);
5924 if (!UNDEF_P(closed) && RTEST(closed)) return io;
5925 rb_rescue2(io_call_close, io, ignore_closed_stream, io,
5926 rb_eIOError, (VALUE)0);
5927 return io;
5928}
5929
5930/*
5931 * call-seq:
5932 * closed? -> true or false
5933 *
5934 * Returns +true+ if the stream is closed for both reading and writing,
5935 * +false+ otherwise.
5936 * See {Open and Closed Streams}[rdoc-ref:IO@Open+and+Closed+Streams].
5937 *
5938 * IO.popen('ruby', 'r+') do |pipe|
5939 * puts pipe.closed?
5940 * pipe.close_read
5941 * puts pipe.closed?
5942 * pipe.close_write
5943 * puts pipe.closed?
5944 * end
5945 *
5946 * Output:
5947 *
5948 * false
5949 * false
5950 * true
5951 *
5952 * Related: IO#close_read, IO#close_write, IO#close.
5953 */
5954VALUE
5956{
5957 rb_io_t *fptr;
5958 VALUE write_io;
5959 rb_io_t *write_fptr;
5960
5961 write_io = GetWriteIO(io);
5962 if (io != write_io) {
5963 write_fptr = RFILE(write_io)->fptr;
5964 if (write_fptr && 0 <= write_fptr->fd) {
5965 return Qfalse;
5966 }
5967 }
5968
5969 fptr = rb_io_get_fptr(io);
5970 return RBOOL(0 > fptr->fd);
5971}
5972
5973/*
5974 * call-seq:
5975 * close_read -> nil
5976 *
5977 * Closes the stream for reading if open for reading;
5978 * returns +nil+.
5979 * See {Open and Closed Streams}[rdoc-ref:IO@Open+and+Closed+Streams].
5980 *
5981 * If the stream was opened by IO.popen and is also closed for writing,
5982 * sets global variable <tt>$?</tt> (child exit status).
5983 *
5984 * Example:
5985 *
5986 * IO.popen('ruby', 'r+') do |pipe|
5987 * puts pipe.closed?
5988 * pipe.close_write
5989 * puts pipe.closed?
5990 * pipe.close_read
5991 * puts $?
5992 * puts pipe.closed?
5993 * end
5994 *
5995 * Output:
5996 *
5997 * false
5998 * false
5999 * pid 14748 exit 0
6000 * true
6001 *
6002 * Related: IO#close, IO#close_write, IO#closed?.
6003 */
6004
6005static VALUE
6006rb_io_close_read(VALUE io)
6007{
6008 rb_io_t *fptr;
6009 VALUE write_io;
6010
6011 fptr = rb_io_get_fptr(rb_io_taint_check(io));
6012 if (fptr->fd < 0) return Qnil;
6013 if (is_socket(fptr->fd, fptr->pathv)) {
6014#ifndef SHUT_RD
6015# define SHUT_RD 0
6016#endif
6017 if (shutdown(fptr->fd, SHUT_RD) < 0)
6018 rb_sys_fail_path(fptr->pathv);
6019 fptr->mode &= ~FMODE_READABLE;
6020 if (!(fptr->mode & FMODE_WRITABLE))
6021 return rb_io_close(io);
6022 return Qnil;
6023 }
6024
6025 write_io = GetWriteIO(io);
6026 if (io != write_io) {
6027 rb_io_t *wfptr;
6028 wfptr = rb_io_get_fptr(rb_io_taint_check(write_io));
6029 wfptr->pid = fptr->pid;
6030 fptr->pid = 0;
6031 RFILE(io)->fptr = wfptr;
6032 /* bind to write_io temporarily to get rid of memory/fd leak */
6033 fptr->tied_io_for_writing = 0;
6034 RFILE(write_io)->fptr = fptr;
6035 rb_io_fptr_cleanup(fptr, FALSE);
6036 /* should not finalize fptr because another thread may be reading it */
6037 return Qnil;
6038 }
6039
6040 if ((fptr->mode & (FMODE_DUPLEX|FMODE_WRITABLE)) == FMODE_WRITABLE) {
6041 rb_raise(rb_eIOError, "closing non-duplex IO for reading");
6042 }
6043 return rb_io_close(io);
6044}
6045
6046/*
6047 * call-seq:
6048 * close_write -> nil
6049 *
6050 * Closes the stream for writing if open for writing;
6051 * returns +nil+.
6052 * See {Open and Closed Streams}[rdoc-ref:IO@Open+and+Closed+Streams].
6053 *
6054 * Flushes any buffered writes to the operating system before closing.
6055 *
6056 * If the stream was opened by IO.popen and is also closed for reading,
6057 * sets global variable <tt>$?</tt> (child exit status).
6058 *
6059 * IO.popen('ruby', 'r+') do |pipe|
6060 * puts pipe.closed?
6061 * pipe.close_read
6062 * puts pipe.closed?
6063 * pipe.close_write
6064 * puts $?
6065 * puts pipe.closed?
6066 * end
6067 *
6068 * Output:
6069 *
6070 * false
6071 * false
6072 * pid 15044 exit 0
6073 * true
6074 *
6075 * Related: IO#close, IO#close_read, IO#closed?.
6076 */
6077
6078static VALUE
6079rb_io_close_write(VALUE io)
6080{
6081 rb_io_t *fptr;
6082 VALUE write_io;
6083
6084 write_io = GetWriteIO(io);
6085 fptr = rb_io_get_fptr(rb_io_taint_check(write_io));
6086 if (fptr->fd < 0) return Qnil;
6087 if (is_socket(fptr->fd, fptr->pathv)) {
6088#ifndef SHUT_WR
6089# define SHUT_WR 1
6090#endif
6091 if (shutdown(fptr->fd, SHUT_WR) < 0)
6092 rb_sys_fail_path(fptr->pathv);
6093 fptr->mode &= ~FMODE_WRITABLE;
6094 if (!(fptr->mode & FMODE_READABLE))
6095 return rb_io_close(write_io);
6096 return Qnil;
6097 }
6098
6099 if ((fptr->mode & (FMODE_DUPLEX|FMODE_READABLE)) == FMODE_READABLE) {
6100 rb_raise(rb_eIOError, "closing non-duplex IO for writing");
6101 }
6102
6103 if (io != write_io) {
6104 fptr = rb_io_get_fptr(rb_io_taint_check(io));
6105 fptr->tied_io_for_writing = 0;
6106 }
6107 rb_io_close(write_io);
6108 return Qnil;
6109}
6110
6111/*
6112 * call-seq:
6113 * sysseek(offset, whence = IO::SEEK_SET) -> integer
6114 *
6115 * Behaves like IO#seek, except that it:
6116 *
6117 * - Uses low-level system functions.
6118 * - Returns the new position.
6119 *
6120 */
6121
6122static VALUE
6123rb_io_sysseek(int argc, VALUE *argv, VALUE io)
6124{
6125 VALUE offset, ptrname;
6126 int whence = SEEK_SET;
6127 rb_io_t *fptr;
6128 rb_off_t pos;
6129
6130 if (rb_scan_args(argc, argv, "11", &offset, &ptrname) == 2) {
6131 whence = interpret_seek_whence(ptrname);
6132 }
6133 pos = NUM2OFFT(offset);
6134 GetOpenFile(io, fptr);
6135 if ((fptr->mode & FMODE_READABLE) &&
6136 (READ_DATA_BUFFERED(fptr) || READ_CHAR_PENDING(fptr))) {
6137 rb_raise(rb_eIOError, "sysseek for buffered IO");
6138 }
6139 if ((fptr->mode & FMODE_WRITABLE) && fptr->wbuf.len) {
6140 rb_warn("sysseek for buffered IO");
6141 }
6142 errno = 0;
6143 pos = lseek(fptr->fd, pos, whence);
6144 if (pos < 0 && errno) rb_sys_fail_path(fptr->pathv);
6145
6146 return OFFT2NUM(pos);
6147}
6148
6149/*
6150 * call-seq:
6151 * syswrite(object) -> integer
6152 *
6153 * Writes the given +object+ to self, which must be opened for writing (see Modes);
6154 * returns the number bytes written.
6155 * If +object+ is not a string is converted via method to_s:
6156 *
6157 * f = File.new('t.tmp', 'w')
6158 * f.syswrite('foo') # => 3
6159 * f.syswrite(30) # => 2
6160 * f.syswrite(:foo) # => 3
6161 * f.close
6162 *
6163 * This methods should not be used with other stream-writer methods.
6164 *
6165 */
6166
6167static VALUE
6168rb_io_syswrite(VALUE io, VALUE str)
6169{
6170 VALUE tmp;
6171 rb_io_t *fptr;
6172 long n, len;
6173 const char *ptr;
6174
6175 if (!RB_TYPE_P(str, T_STRING))
6176 str = rb_obj_as_string(str);
6177
6178 io = GetWriteIO(io);
6179 GetOpenFile(io, fptr);
6181
6182 if (fptr->wbuf.len) {
6183 rb_warn("syswrite for buffered IO");
6184 }
6185
6186 tmp = rb_str_tmp_frozen_acquire(str);
6187 RSTRING_GETMEM(tmp, ptr, len);
6188 n = rb_io_write_memory(fptr, ptr, len);
6189 if (n < 0) rb_sys_fail_path(fptr->pathv);
6190 rb_str_tmp_frozen_release(str, tmp);
6191
6192 return LONG2FIX(n);
6193}
6194
6195/*
6196 * call-seq:
6197 * sysread(maxlen) -> string
6198 * sysread(maxlen, out_string) -> string
6199 *
6200 * Behaves like IO#readpartial, except that it uses low-level system functions.
6201 *
6202 * This method should not be used with other stream-reader methods.
6203 *
6204 */
6205
6206static VALUE
6207rb_io_sysread(int argc, VALUE *argv, VALUE io)
6208{
6209 VALUE len, str;
6210 rb_io_t *fptr;
6211 long n, ilen;
6212 struct io_internal_read_struct iis;
6213 int shrinkable;
6214
6215 rb_scan_args(argc, argv, "11", &len, &str);
6216 ilen = NUM2LONG(len);
6217 if (ilen < 0) {
6218 rb_raise(rb_eArgError, "negative string size (or size too big)");
6219 }
6220 shrinkable = io_setstrbuf(&str, ilen);
6221 if (ilen == 0) return str;
6222
6223 GetOpenFile(io, fptr);
6225
6226 if (READ_DATA_BUFFERED(fptr)) {
6227 rb_raise(rb_eIOError, "sysread for buffered IO");
6228 }
6229
6230 rb_io_check_closed(fptr);
6231
6232 io_setstrbuf(&str, ilen);
6233 rb_str_make_heap(str);
6234 iis.th = rb_thread_current();
6235 iis.fptr = fptr;
6236 iis.nonblock = 0;
6237 iis.fd = fptr->fd;
6238 iis.buf = RSTRING_PTR(str);
6239 iis.capa = ilen;
6240 iis.timeout = NULL;
6241 n = io_read_memory_locktmp(str, &iis);
6242
6243 if (n < 0) {
6244 rb_sys_fail_path(fptr->pathv);
6245 }
6246
6247 io_set_read_length(str, n, shrinkable);
6248
6249 if (n == 0 && ilen > 0) {
6250 rb_eof_error();
6251 }
6252
6253 return str;
6254}
6255
6257 struct rb_io *io;
6258 int fd;
6259 void *buf;
6260 size_t count;
6261 rb_off_t offset;
6262};
6263
6264static VALUE
6265internal_pread_func(void *_arg)
6266{
6267 struct prdwr_internal_arg *arg = _arg;
6268
6269 return (VALUE)pread(arg->fd, arg->buf, arg->count, arg->offset);
6270}
6271
6272static VALUE
6273pread_internal_call(VALUE _arg)
6274{
6275 struct prdwr_internal_arg *arg = (struct prdwr_internal_arg *)_arg;
6276
6277 VALUE scheduler = rb_fiber_scheduler_current();
6278 if (scheduler != Qnil) {
6279 VALUE result = rb_fiber_scheduler_io_pread_memory(scheduler, arg->io->self, arg->offset, arg->buf, arg->count, 0);
6280
6281 if (!UNDEF_P(result)) {
6282 return rb_fiber_scheduler_io_result_apply(result);
6283 }
6284 }
6285
6286 return rb_io_blocking_region_wait(arg->io, internal_pread_func, arg, RUBY_IO_READABLE);
6287}
6288
6289/*
6290 * call-seq:
6291 * pread(maxlen, offset) -> string
6292 * pread(maxlen, offset, out_string) -> string
6293 *
6294 * Behaves like IO#readpartial, except that it:
6295 *
6296 * - Reads at the given +offset+ (in bytes).
6297 * - Disregards, and does not modify, the stream's position
6298 * (see {Position}[rdoc-ref:IO@Position]).
6299 * - Bypasses any user space buffering in the stream.
6300 *
6301 * Because this method does not disturb the stream's state
6302 * (its position, in particular), +pread+ allows multiple threads and processes
6303 * to use the same \IO object for reading at various offsets.
6304 *
6305 * f = File.open('t.txt')
6306 * f.read # => "First line\nSecond line\n\nFourth line\nFifth line\n"
6307 * f.pos # => 52
6308 * # Read 12 bytes at offset 0.
6309 * f.pread(12, 0) # => "First line\n"
6310 * # Read 9 bytes at offset 8.
6311 * f.pread(9, 8) # => "ne\nSecon"
6312 * f.close
6313 *
6314 * Not available on some platforms.
6315 *
6316 */
6317static VALUE
6318rb_io_pread(int argc, VALUE *argv, VALUE io)
6319{
6320 VALUE len, offset, str;
6321 long ilen;
6322 rb_io_t *fptr;
6323 ssize_t n;
6324 struct prdwr_internal_arg arg;
6325 int shrinkable;
6326
6327 rb_scan_args(argc, argv, "21", &len, &offset, &str);
6328 ilen = NUM2LONG(len);
6329 if (ilen < 0) {
6330 rb_raise(rb_eArgError, "negative string size (or size too big)");
6331 }
6332 arg.count = (size_t)ilen;
6333 arg.offset = NUM2OFFT(offset);
6334
6335 shrinkable = io_setstrbuf(&str, (long)arg.count);
6336 if (arg.count == 0) return str;
6337 rb_str_make_heap(str);
6338 arg.buf = RSTRING_PTR(str);
6339
6340 GetOpenFile(io, fptr);
6342
6343 arg.io = fptr;
6344 arg.fd = fptr->fd;
6345 rb_io_check_closed(fptr);
6346
6347 rb_str_locktmp(str);
6348 n = (ssize_t)rb_ensure(pread_internal_call, (VALUE)&arg, rb_str_unlocktmp, str);
6349
6350 if (n < 0) {
6351 rb_sys_fail_path(fptr->pathv);
6352 }
6353 io_set_read_length(str, n, shrinkable);
6354 if (n == 0 && arg.count > 0) {
6355 rb_eof_error();
6356 }
6357
6358 return str;
6359}
6360
6361static VALUE
6362internal_pwrite_func(void *_arg)
6363{
6364 struct prdwr_internal_arg *arg = _arg;
6365
6366 return (VALUE)pwrite(arg->fd, arg->buf, arg->count, arg->offset);
6367}
6368
6369static VALUE
6370pwrite_internal_call(VALUE _arg)
6371{
6372 struct prdwr_internal_arg *arg = (struct prdwr_internal_arg *)_arg;
6373
6374 VALUE scheduler = rb_fiber_scheduler_current();
6375 if (scheduler != Qnil) {
6376 VALUE result = rb_fiber_scheduler_io_pwrite_memory(scheduler, arg->io->self, arg->offset, arg->buf, arg->count, 0);
6377
6378 if (!UNDEF_P(result)) {
6379 return rb_fiber_scheduler_io_result_apply(result);
6380 }
6381 }
6382
6383 return rb_io_blocking_region_wait(arg->io, internal_pwrite_func, arg, RUBY_IO_WRITABLE);
6384}
6385
6386/*
6387 * call-seq:
6388 * pwrite(object, offset) -> integer
6389 *
6390 * Behaves like IO#write, except that it:
6391 *
6392 * - Writes at the given +offset+ (in bytes).
6393 * - Disregards, and does not modify, the stream's position
6394 * (see {Position}[rdoc-ref:IO@Position]).
6395 * - Bypasses any user space buffering in the stream.
6396 *
6397 * Because this method does not disturb the stream's state
6398 * (its position, in particular), +pwrite+ allows multiple threads and processes
6399 * to use the same \IO object for writing at various offsets.
6400 *
6401 * f = File.open('t.tmp', 'w+')
6402 * # Write 6 bytes at offset 3.
6403 * f.pwrite('ABCDEF', 3) # => 6
6404 * f.rewind
6405 * f.read # => "\u0000\u0000\u0000ABCDEF"
6406 * f.close
6407 *
6408 * Not available on some platforms.
6409 *
6410 */
6411static VALUE
6412rb_io_pwrite(VALUE io, VALUE str, VALUE offset)
6413{
6414 rb_io_t *fptr;
6415 ssize_t n;
6416 struct prdwr_internal_arg arg;
6417 VALUE tmp;
6418
6419 if (!RB_TYPE_P(str, T_STRING))
6420 str = rb_obj_as_string(str);
6421
6422 arg.offset = NUM2OFFT(offset);
6423
6424 io = GetWriteIO(io);
6425 GetOpenFile(io, fptr);
6427
6428 arg.io = fptr;
6429 arg.fd = fptr->fd;
6430
6431 tmp = rb_str_tmp_frozen_acquire(str);
6432 arg.buf = RSTRING_PTR(tmp);
6433 arg.count = (size_t)RSTRING_LEN(tmp);
6434
6435 n = (ssize_t)pwrite_internal_call((VALUE)&arg);
6436 if (n < 0) rb_sys_fail_path(fptr->pathv);
6437 rb_str_tmp_frozen_release(str, tmp);
6438
6439 return SSIZET2NUM(n);
6440}
6441
6442VALUE
6444{
6445 rb_io_t *fptr;
6446
6447 GetOpenFile(io, fptr);
6448 if (fptr->readconv)
6450 if (fptr->writeconv)
6452 fptr->mode |= FMODE_BINMODE;
6453 fptr->mode &= ~FMODE_TEXTMODE;
6455#ifdef O_BINARY
6456 if (!fptr->readconv) {
6457 SET_BINARY_MODE_WITH_SEEK_CUR(fptr);
6458 }
6459 else {
6460 setmode(fptr->fd, O_BINARY);
6461 }
6462#endif
6463 return io;
6464}
6465
6466static void
6467io_ascii8bit_binmode(rb_io_t *fptr)
6468{
6469 if (fptr->readconv) {
6470 rb_econv_close(fptr->readconv);
6471 fptr->readconv = NULL;
6472 }
6473 if (fptr->writeconv) {
6475 fptr->writeconv = NULL;
6476 }
6477 fptr->mode |= FMODE_BINMODE;
6478 fptr->mode &= ~FMODE_TEXTMODE;
6479 SET_BINARY_MODE_WITH_SEEK_CUR(fptr);
6480
6481 fptr->encs.enc = rb_ascii8bit_encoding();
6482 fptr->encs.enc2 = NULL;
6483 fptr->encs.ecflags = 0;
6484 fptr->encs.ecopts = Qnil;
6485 clear_codeconv(fptr);
6486}
6487
6488VALUE
6490{
6491 rb_io_t *fptr;
6492
6493 GetOpenFile(io, fptr);
6494 io_ascii8bit_binmode(fptr);
6495
6496 return io;
6497}
6498
6499/*
6500 * call-seq:
6501 * binmode -> self
6502 *
6503 * Sets the stream's data mode as binary
6504 * (see {Data Mode}[rdoc-ref:File@Data+Mode]).
6505 *
6506 * A stream's data mode may not be changed from binary to text.
6507 *
6508 */
6509
6510static VALUE
6511rb_io_binmode_m(VALUE io)
6512{
6513 VALUE write_io;
6514
6516
6517 write_io = GetWriteIO(io);
6518 if (write_io != io)
6519 rb_io_ascii8bit_binmode(write_io);
6520 return io;
6521}
6522
6523/*
6524 * call-seq:
6525 * binmode? -> true or false
6526 *
6527 * Returns +true+ if the stream is on binary mode, +false+ otherwise.
6528 * See {Data Mode}[rdoc-ref:File@Data+Mode].
6529 *
6530 */
6531static VALUE
6532rb_io_binmode_p(VALUE io)
6533{
6534 rb_io_t *fptr;
6535 GetOpenFile(io, fptr);
6536 return RBOOL(fptr->mode & FMODE_BINMODE);
6537}
6538
6539static const char*
6540rb_io_fmode_modestr(enum rb_io_mode fmode)
6541{
6542 if (fmode & FMODE_APPEND) {
6543 if ((fmode & FMODE_READWRITE) == FMODE_READWRITE) {
6544 return MODE_BTMODE("a+", "ab+", "at+");
6545 }
6546 return MODE_BTMODE("a", "ab", "at");
6547 }
6548 switch (fmode & FMODE_READWRITE) {
6549 default:
6550 rb_raise(rb_eArgError, "invalid access fmode 0x%x", fmode);
6551 case FMODE_READABLE:
6552 return MODE_BTMODE("r", "rb", "rt");
6553 case FMODE_WRITABLE:
6554 return MODE_BTXMODE("w", "wb", "wt", "wx", "wbx", "wtx");
6555 case FMODE_READWRITE:
6556 if (fmode & FMODE_CREATE) {
6557 return MODE_BTXMODE("w+", "wb+", "wt+", "w+x", "wb+x", "wt+x");
6558 }
6559 return MODE_BTMODE("r+", "rb+", "rt+");
6560 }
6561}
6562
6563static const char bom_prefix[] = "bom|";
6564static const char utf_prefix[] = "utf-";
6565enum {bom_prefix_len = (int)sizeof(bom_prefix) - 1};
6566enum {utf_prefix_len = (int)sizeof(utf_prefix) - 1};
6567
6568static int
6569io_encname_bom_p(const char *name, long len)
6570{
6571 return len > bom_prefix_len && STRNCASECMP(name, bom_prefix, bom_prefix_len) == 0;
6572}
6573
6574enum rb_io_mode
6575rb_io_modestr_fmode(const char *modestr)
6576{
6577 enum rb_io_mode fmode = 0;
6578 const char *m = modestr, *p = NULL;
6579
6580 switch (*m++) {
6581 case 'r':
6582 fmode |= FMODE_READABLE;
6583 break;
6584 case 'w':
6586 break;
6587 case 'a':
6589 break;
6590 default:
6591 goto error;
6592 }
6593
6594 while (*m) {
6595 switch (*m++) {
6596 case 'b':
6597 fmode |= FMODE_BINMODE;
6598 break;
6599 case 't':
6600 fmode |= FMODE_TEXTMODE;
6601 break;
6602 case '+':
6603 fmode |= FMODE_READWRITE;
6604 break;
6605 case 'x':
6606 if (modestr[0] != 'w')
6607 goto error;
6608 fmode |= FMODE_EXCL;
6609 break;
6610 default:
6611 goto error;
6612 case ':':
6613 p = strchr(m, ':');
6614 if (io_encname_bom_p(m, p ? (long)(p - m) : (long)strlen(m)))
6615 fmode |= FMODE_SETENC_BY_BOM;
6616 goto finished;
6617 }
6618 }
6619
6620 finished:
6621 if ((fmode & FMODE_BINMODE) && (fmode & FMODE_TEXTMODE))
6622 goto error;
6623
6624 return fmode;
6625
6626 error:
6627 rb_raise(rb_eArgError, "invalid access mode %s", modestr);
6629}
6630
6631int
6633{
6634 enum rb_io_mode fmode = 0;
6635
6636 switch (oflags & O_ACCMODE) {
6637 case O_RDONLY:
6638 fmode = FMODE_READABLE;
6639 break;
6640 case O_WRONLY:
6641 fmode = FMODE_WRITABLE;
6642 break;
6643 case O_RDWR:
6644 fmode = FMODE_READWRITE;
6645 break;
6646 }
6647
6648 if (oflags & O_APPEND) {
6649 fmode |= FMODE_APPEND;
6650 }
6651 if (oflags & O_TRUNC) {
6652 fmode |= FMODE_TRUNC;
6653 }
6654 if (oflags & O_CREAT) {
6655 fmode |= FMODE_CREATE;
6656 }
6657 if (oflags & O_EXCL) {
6658 fmode |= FMODE_EXCL;
6659 }
6660#ifdef O_BINARY
6661 if (oflags & O_BINARY) {
6662 fmode |= FMODE_BINMODE;
6663 }
6664#endif
6665
6666 return fmode;
6667}
6668
6669static int
6670rb_io_fmode_oflags(enum rb_io_mode fmode)
6671{
6672 int oflags = 0;
6673
6674 switch (fmode & FMODE_READWRITE) {
6675 case FMODE_READABLE:
6676 oflags |= O_RDONLY;
6677 break;
6678 case FMODE_WRITABLE:
6679 oflags |= O_WRONLY;
6680 break;
6681 case FMODE_READWRITE:
6682 oflags |= O_RDWR;
6683 break;
6684 }
6685
6686 if (fmode & FMODE_APPEND) {
6687 oflags |= O_APPEND;
6688 }
6689 if (fmode & FMODE_TRUNC) {
6690 oflags |= O_TRUNC;
6691 }
6692 if (fmode & FMODE_CREATE) {
6693 oflags |= O_CREAT;
6694 }
6695 if (fmode & FMODE_EXCL) {
6696 oflags |= O_EXCL;
6697 }
6698#ifdef O_BINARY
6699 if (fmode & FMODE_BINMODE) {
6700 oflags |= O_BINARY;
6701 }
6702#endif
6703
6704 return oflags;
6705}
6706
6707int
6708rb_io_modestr_oflags(const char *modestr)
6709{
6710 return rb_io_fmode_oflags(rb_io_modestr_fmode(modestr));
6711}
6712
6713static const char*
6714rb_io_oflags_modestr(int oflags)
6715{
6716#ifdef O_BINARY
6717# define MODE_BINARY(a,b) ((oflags & O_BINARY) ? (b) : (a))
6718#else
6719# define MODE_BINARY(a,b) (a)
6720#endif
6721 int accmode;
6722 if (oflags & O_EXCL) {
6723 rb_raise(rb_eArgError, "exclusive access mode is not supported");
6724 }
6725 accmode = oflags & (O_RDONLY|O_WRONLY|O_RDWR);
6726 if (oflags & O_APPEND) {
6727 if (accmode == O_WRONLY) {
6728 return MODE_BINARY("a", "ab");
6729 }
6730 if (accmode == O_RDWR) {
6731 return MODE_BINARY("a+", "ab+");
6732 }
6733 }
6734 switch (accmode) {
6735 default:
6736 rb_raise(rb_eArgError, "invalid access oflags 0x%x", oflags);
6737 case O_RDONLY:
6738 return MODE_BINARY("r", "rb");
6739 case O_WRONLY:
6740 return MODE_BINARY("w", "wb");
6741 case O_RDWR:
6742 if (oflags & O_TRUNC) {
6743 return MODE_BINARY("w+", "wb+");
6744 }
6745 return MODE_BINARY("r+", "rb+");
6746 }
6747}
6748
6749/*
6750 * Convert external/internal encodings to enc/enc2
6751 * NULL => use default encoding
6752 * Qnil => no encoding specified (internal only)
6753 */
6754static void
6755rb_io_ext_int_to_encs(rb_encoding *ext, rb_encoding *intern, rb_encoding **enc, rb_encoding **enc2, enum rb_io_mode fmode)
6756{
6757 int default_ext = 0;
6758
6759 if (ext == NULL) {
6760 ext = rb_default_external_encoding();
6761 default_ext = 1;
6762 }
6763 if (rb_is_ascii8bit_enc(ext)) {
6764 /* If external is ASCII-8BIT, no transcoding */
6765 intern = NULL;
6766 }
6767 else if (intern == NULL) {
6768 intern = rb_default_internal_encoding();
6769 }
6770 if (intern == NULL || intern == (rb_encoding *)Qnil ||
6771 (!(fmode & FMODE_SETENC_BY_BOM) && (intern == ext))) {
6772 /* No internal encoding => use external + no transcoding */
6773 *enc = (default_ext && intern != ext) ? NULL : ext;
6774 *enc2 = NULL;
6775 }
6776 else {
6777 *enc = intern;
6778 *enc2 = ext;
6779 }
6780}
6781
6782static void
6783unsupported_encoding(const char *name, rb_encoding *enc)
6784{
6785 rb_enc_warn(enc, "Unsupported encoding %s ignored", name);
6786}
6787
6788static void
6789parse_mode_enc(const char *estr, rb_encoding *estr_enc,
6790 rb_encoding **enc_p, rb_encoding **enc2_p, enum rb_io_mode *fmode_p)
6791{
6792 const char *p;
6793 char encname[ENCODING_MAXNAMELEN+1];
6794 int idx, idx2;
6795 enum rb_io_mode fmode = fmode_p ? *fmode_p : 0;
6796 rb_encoding *ext_enc, *int_enc;
6797 long len;
6798
6799 /* parse estr as "enc" or "enc2:enc" or "enc:-" */
6800
6801 p = strrchr(estr, ':');
6802 len = p ? (p++ - estr) : (long)strlen(estr);
6803 if ((fmode & FMODE_SETENC_BY_BOM) || io_encname_bom_p(estr, len)) {
6804 estr += bom_prefix_len;
6805 len -= bom_prefix_len;
6806 if (!STRNCASECMP(estr, utf_prefix, utf_prefix_len)) {
6807 fmode |= FMODE_SETENC_BY_BOM;
6808 }
6809 else {
6810 rb_enc_warn(estr_enc, "BOM with non-UTF encoding %s is nonsense", estr);
6811 fmode &= ~FMODE_SETENC_BY_BOM;
6812 }
6813 }
6814 if (len == 0 || len > ENCODING_MAXNAMELEN) {
6815 idx = -1;
6816 }
6817 else {
6818 if (p) {
6819 memcpy(encname, estr, len);
6820 encname[len] = '\0';
6821 estr = encname;
6822 }
6823 idx = rb_enc_find_index(estr);
6824 }
6825 if (fmode_p) *fmode_p = fmode;
6826
6827 if (idx >= 0)
6828 ext_enc = rb_enc_from_index(idx);
6829 else {
6830 if (idx != -2)
6831 unsupported_encoding(estr, estr_enc);
6832 ext_enc = NULL;
6833 }
6834
6835 int_enc = NULL;
6836 if (p) {
6837 if (*p == '-' && *(p+1) == '\0') {
6838 /* Special case - "-" => no transcoding */
6839 int_enc = (rb_encoding *)Qnil;
6840 }
6841 else {
6842 idx2 = rb_enc_find_index(p);
6843 if (idx2 < 0)
6844 unsupported_encoding(p, estr_enc);
6845 else if (!(fmode & FMODE_SETENC_BY_BOM) && (idx2 == idx)) {
6846 int_enc = (rb_encoding *)Qnil;
6847 }
6848 else
6849 int_enc = rb_enc_from_index(idx2);
6850 }
6851 }
6852
6853 rb_io_ext_int_to_encs(ext_enc, int_enc, enc_p, enc2_p, fmode);
6854}
6855
6856int
6857rb_io_extract_encoding_option(VALUE opt, rb_encoding **enc_p, rb_encoding **enc2_p, enum rb_io_mode *fmode_p)
6858{
6859 VALUE encoding=Qnil, extenc=Qundef, intenc=Qundef, tmp;
6860 int extracted = 0;
6861 rb_encoding *extencoding = NULL;
6862 rb_encoding *intencoding = NULL;
6863
6864 if (!NIL_P(opt)) {
6865 VALUE v;
6866 v = rb_hash_lookup2(opt, sym_encoding, Qnil);
6867 if (v != Qnil) encoding = v;
6868 v = rb_hash_lookup2(opt, sym_extenc, Qundef);
6869 if (v != Qnil) extenc = v;
6870 v = rb_hash_lookup2(opt, sym_intenc, Qundef);
6871 if (!UNDEF_P(v)) intenc = v;
6872 }
6873 if ((!UNDEF_P(extenc) || !UNDEF_P(intenc)) && !NIL_P(encoding)) {
6874 if (!NIL_P(ruby_verbose)) {
6875 int idx = rb_to_encoding_index(encoding);
6876 if (idx >= 0) encoding = rb_enc_from_encoding(rb_enc_from_index(idx));
6877 rb_warn("Ignoring encoding parameter '%"PRIsVALUE"': %s_encoding is used",
6878 encoding, UNDEF_P(extenc) ? "internal" : "external");
6879 }
6880 encoding = Qnil;
6881 }
6882 if (!UNDEF_P(extenc) && !NIL_P(extenc)) {
6883 extencoding = rb_to_encoding(extenc);
6884 }
6885 if (!UNDEF_P(intenc)) {
6886 if (NIL_P(intenc)) {
6887 /* internal_encoding: nil => no transcoding */
6888 intencoding = (rb_encoding *)Qnil;
6889 }
6890 else if (!NIL_P(tmp = rb_check_string_type(intenc))) {
6891 char *p = StringValueCStr(tmp);
6892
6893 if (*p == '-' && *(p+1) == '\0') {
6894 /* Special case - "-" => no transcoding */
6895 intencoding = (rb_encoding *)Qnil;
6896 }
6897 else {
6898 intencoding = rb_to_encoding(intenc);
6899 }
6900 }
6901 else {
6902 intencoding = rb_to_encoding(intenc);
6903 }
6904 if (extencoding == intencoding) {
6905 intencoding = (rb_encoding *)Qnil;
6906 }
6907 }
6908 if (!NIL_P(encoding)) {
6909 extracted = 1;
6910 if (!NIL_P(tmp = rb_check_string_type(encoding))) {
6911 parse_mode_enc(StringValueCStr(tmp), rb_enc_get(tmp),
6912 enc_p, enc2_p, fmode_p);
6913 }
6914 else {
6915 rb_io_ext_int_to_encs(rb_to_encoding(encoding), NULL, enc_p, enc2_p, 0);
6916 }
6917 }
6918 else if (!UNDEF_P(extenc) || !UNDEF_P(intenc)) {
6919 extracted = 1;
6920 rb_io_ext_int_to_encs(extencoding, intencoding, enc_p, enc2_p, 0);
6921 }
6922 return extracted;
6923}
6924
6925static void
6926validate_enc_binmode(enum rb_io_mode *fmode_p, int ecflags, rb_encoding *enc, rb_encoding *enc2)
6927{
6928 enum rb_io_mode fmode = *fmode_p;
6929
6930 if ((fmode & FMODE_READABLE) &&
6931 !enc2 &&
6932 !(fmode & FMODE_BINMODE) &&
6933 !rb_enc_asciicompat(enc ? enc : rb_default_external_encoding()))
6934 rb_raise(rb_eArgError, "ASCII incompatible encoding needs binmode");
6935
6936 if ((fmode & FMODE_BINMODE) && (ecflags & ECONV_NEWLINE_DECORATOR_MASK)) {
6937 rb_raise(rb_eArgError, "newline decorator with binary mode");
6938 }
6939 if (!(fmode & FMODE_BINMODE) &&
6940 (DEFAULT_TEXTMODE || (ecflags & ECONV_NEWLINE_DECORATOR_MASK))) {
6941 fmode |= FMODE_TEXTMODE;
6942 *fmode_p = fmode;
6943 }
6944#if !DEFAULT_TEXTMODE
6945 else if (!(ecflags & ECONV_NEWLINE_DECORATOR_MASK)) {
6946 fmode &= ~FMODE_TEXTMODE;
6947 *fmode_p = fmode;
6948 }
6949#endif
6950}
6951
6952static void
6953extract_binmode(VALUE opthash, enum rb_io_mode *fmode)
6954{
6955 if (!NIL_P(opthash)) {
6956 VALUE v;
6957 v = rb_hash_aref(opthash, sym_textmode);
6958 if (!NIL_P(v)) {
6959 if (*fmode & FMODE_TEXTMODE)
6960 rb_raise(rb_eArgError, "textmode specified twice");
6961 if (*fmode & FMODE_BINMODE)
6962 rb_raise(rb_eArgError, "both textmode and binmode specified");
6963 if (RTEST(v))
6964 *fmode |= FMODE_TEXTMODE;
6965 }
6966 v = rb_hash_aref(opthash, sym_binmode);
6967 if (!NIL_P(v)) {
6968 if (*fmode & FMODE_BINMODE)
6969 rb_raise(rb_eArgError, "binmode specified twice");
6970 if (*fmode & FMODE_TEXTMODE)
6971 rb_raise(rb_eArgError, "both textmode and binmode specified");
6972 if (RTEST(v))
6973 *fmode |= FMODE_BINMODE;
6974 }
6975
6976 if ((*fmode & FMODE_BINMODE) && (*fmode & FMODE_TEXTMODE))
6977 rb_raise(rb_eArgError, "both textmode and binmode specified");
6978 }
6979}
6980
6981void
6982rb_io_extract_modeenc(VALUE *vmode_p, VALUE *vperm_p, VALUE opthash,
6983 int *oflags_p, enum rb_io_mode *fmode_p, struct rb_io_encoding *convconfig_p)
6984{
6985 VALUE vmode;
6986 int oflags;
6987 enum rb_io_mode fmode;
6988 rb_encoding *enc, *enc2;
6989 int ecflags;
6990 VALUE ecopts;
6991 int has_enc = 0, has_vmode = 0;
6992 VALUE intmode;
6993
6994 vmode = *vmode_p;
6995
6996 /* Set to defaults */
6997 rb_io_ext_int_to_encs(NULL, NULL, &enc, &enc2, 0);
6998
6999 vmode_handle:
7000 if (NIL_P(vmode)) {
7001 fmode = FMODE_READABLE;
7002 oflags = O_RDONLY;
7003 }
7004 else if (!NIL_P(intmode = rb_check_to_integer(vmode, "to_int"))) {
7005 vmode = intmode;
7006 oflags = NUM2INT(intmode);
7007 fmode = rb_io_oflags_fmode(oflags);
7008 }
7009 else {
7010 const char *p;
7011
7012 StringValue(vmode);
7013 p = StringValueCStr(vmode);
7014 fmode = rb_io_modestr_fmode(p);
7015 oflags = rb_io_fmode_oflags(fmode);
7016 p = strchr(p, ':');
7017 if (p) {
7018 has_enc = 1;
7019 parse_mode_enc(p+1, rb_enc_get(vmode), &enc, &enc2, &fmode);
7020 }
7021 else {
7022 rb_encoding *e;
7023
7024 e = (fmode & FMODE_BINMODE) ? rb_ascii8bit_encoding() : NULL;
7025 rb_io_ext_int_to_encs(e, NULL, &enc, &enc2, fmode);
7026 }
7027 }
7028
7029 if (NIL_P(opthash)) {
7030 ecflags = (fmode & FMODE_READABLE) ?
7033#ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE
7034 ecflags |= (fmode & FMODE_WRITABLE) ?
7035 MODE_BTMODE(TEXTMODE_NEWLINE_DECORATOR_ON_WRITE,
7036 0, TEXTMODE_NEWLINE_DECORATOR_ON_WRITE) : 0;
7037#endif
7038 SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags);
7039 ecopts = Qnil;
7040 if (fmode & FMODE_BINMODE) {
7041#ifdef O_BINARY
7042 oflags |= O_BINARY;
7043#endif
7044 if (!has_enc)
7045 rb_io_ext_int_to_encs(rb_ascii8bit_encoding(), NULL, &enc, &enc2, fmode);
7046 }
7047#if DEFAULT_TEXTMODE
7048 else if (NIL_P(vmode)) {
7049 fmode |= DEFAULT_TEXTMODE;
7050 }
7051#endif
7052 }
7053 else {
7054 VALUE v;
7055 if (!has_vmode) {
7056 v = rb_hash_aref(opthash, sym_mode);
7057 if (!NIL_P(v)) {
7058 if (!NIL_P(vmode)) {
7059 rb_raise(rb_eArgError, "mode specified twice");
7060 }
7061 has_vmode = 1;
7062 vmode = v;
7063 goto vmode_handle;
7064 }
7065 }
7066 v = rb_hash_aref(opthash, sym_flags);
7067 if (!NIL_P(v)) {
7068 v = rb_to_int(v);
7069 oflags |= NUM2INT(v);
7070 vmode = INT2NUM(oflags);
7071 fmode = rb_io_oflags_fmode(oflags);
7072 }
7073 extract_binmode(opthash, &fmode);
7074 if (fmode & FMODE_BINMODE) {
7075#ifdef O_BINARY
7076 oflags |= O_BINARY;
7077#endif
7078 if (!has_enc)
7079 rb_io_ext_int_to_encs(rb_ascii8bit_encoding(), NULL, &enc, &enc2, fmode);
7080 }
7081#if DEFAULT_TEXTMODE
7082 else if (NIL_P(vmode)) {
7083 fmode |= DEFAULT_TEXTMODE;
7084 }
7085#endif
7086 v = rb_hash_aref(opthash, sym_perm);
7087 if (!NIL_P(v)) {
7088 if (vperm_p) {
7089 if (!NIL_P(*vperm_p)) {
7090 rb_raise(rb_eArgError, "perm specified twice");
7091 }
7092 *vperm_p = v;
7093 }
7094 else {
7095 /* perm no use, just ignore */
7096 }
7097 }
7098 ecflags = (fmode & FMODE_READABLE) ?
7101#ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE
7102 ecflags |= (fmode & FMODE_WRITABLE) ?
7103 MODE_BTMODE(TEXTMODE_NEWLINE_DECORATOR_ON_WRITE,
7104 0, TEXTMODE_NEWLINE_DECORATOR_ON_WRITE) : 0;
7105#endif
7106
7107 if (rb_io_extract_encoding_option(opthash, &enc, &enc2, &fmode)) {
7108 if (has_enc) {
7109 rb_raise(rb_eArgError, "encoding specified twice");
7110 }
7111 }
7112 SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags);
7113 ecflags = rb_econv_prepare_options(opthash, &ecopts, ecflags);
7114 }
7115
7116 validate_enc_binmode(&fmode, ecflags, enc, enc2);
7117
7118 *vmode_p = vmode;
7119
7120 *oflags_p = oflags;
7121 *fmode_p = fmode;
7122 convconfig_p->enc = enc;
7123 convconfig_p->enc2 = enc2;
7124 convconfig_p->ecflags = ecflags;
7125 convconfig_p->ecopts = ecopts;
7126}
7127
7129 VALUE fname;
7130 int oflags;
7131 mode_t perm;
7132};
7133
7134static void *
7135sysopen_func(void *ptr)
7136{
7137 const struct sysopen_struct *data = ptr;
7138 const char *fname = RSTRING_PTR(data->fname);
7139 return (void *)(VALUE)rb_cloexec_open(fname, data->oflags, data->perm);
7140}
7141
7142static inline int
7143rb_sysopen_internal(struct sysopen_struct *data)
7144{
7145 int fd;
7146 do {
7147 fd = IO_WITHOUT_GVL_INT(sysopen_func, data);
7148 } while (fd < 0 && errno == EINTR);
7149 if (0 <= fd)
7150 rb_update_max_fd(fd);
7151 return fd;
7152}
7153
7154static int
7155rb_sysopen(VALUE fname, int oflags, mode_t perm)
7156{
7157 int fd = -1;
7158 struct sysopen_struct data;
7159
7160 data.fname = rb_str_encode_ospath(fname);
7161 StringValueCStr(data.fname);
7162 data.oflags = oflags;
7163 data.perm = perm;
7164
7165 TRY_WITH_GC((fd = rb_sysopen_internal(&data)) >= 0) {
7166 rb_syserr_fail_path(first_errno, fname);
7167 }
7168 return fd;
7169}
7170
7171static inline FILE *
7172fdopen_internal(int fd, const char *modestr)
7173{
7174 FILE *file;
7175
7176#if defined(__sun)
7177 errno = 0;
7178#endif
7179 file = fdopen(fd, modestr);
7180 if (!file) {
7181#ifdef _WIN32
7182 if (errno == 0) errno = EINVAL;
7183#elif defined(__sun)
7184 if (errno == 0) errno = EMFILE;
7185#endif
7186 }
7187 return file;
7188}
7189
7190FILE *
7191rb_fdopen(int fd, const char *modestr)
7192{
7193 FILE *file = 0;
7194
7195 TRY_WITH_GC((file = fdopen_internal(fd, modestr)) != 0) {
7196 rb_syserr_fail(first_errno, 0);
7197 }
7198
7199 /* xxx: should be _IONBF? A buffer in FILE may have trouble. */
7200#ifdef USE_SETVBUF
7201 if (setvbuf(file, NULL, _IOFBF, 0) != 0)
7202 rb_warn("setvbuf() can't be honoured (fd=%d)", fd);
7203#endif
7204 return file;
7205}
7206
7207static int
7208io_check_tty(rb_io_t *fptr)
7209{
7210 int t = isatty(fptr->fd);
7211 if (t)
7212 fptr->mode |= FMODE_TTY|FMODE_DUPLEX;
7213 return t;
7214}
7215
7216static VALUE rb_io_internal_encoding(VALUE);
7217static void io_encoding_set(rb_io_t *, VALUE, VALUE, VALUE);
7218
7219static int
7220io_strip_bom(VALUE io)
7221{
7222 VALUE b1, b2, b3, b4;
7223 rb_io_t *fptr;
7224
7225 GetOpenFile(io, fptr);
7226 if (!(fptr->mode & FMODE_READABLE)) return 0;
7227 if (NIL_P(b1 = rb_io_getbyte(io))) return 0;
7228 switch (b1) {
7229 case INT2FIX(0xEF):
7230 if (NIL_P(b2 = rb_io_getbyte(io))) break;
7231 if (b2 == INT2FIX(0xBB) && !NIL_P(b3 = rb_io_getbyte(io))) {
7232 if (b3 == INT2FIX(0xBF)) {
7233 return rb_utf8_encindex();
7234 }
7235 rb_io_ungetbyte(io, b3);
7236 }
7237 rb_io_ungetbyte(io, b2);
7238 break;
7239
7240 case INT2FIX(0xFE):
7241 if (NIL_P(b2 = rb_io_getbyte(io))) break;
7242 if (b2 == INT2FIX(0xFF)) {
7243 return ENCINDEX_UTF_16BE;
7244 }
7245 rb_io_ungetbyte(io, b2);
7246 break;
7247
7248 case INT2FIX(0xFF):
7249 if (NIL_P(b2 = rb_io_getbyte(io))) break;
7250 if (b2 == INT2FIX(0xFE)) {
7251 b3 = rb_io_getbyte(io);
7252 if (b3 == INT2FIX(0) && !NIL_P(b4 = rb_io_getbyte(io))) {
7253 if (b4 == INT2FIX(0)) {
7254 return ENCINDEX_UTF_32LE;
7255 }
7256 rb_io_ungetbyte(io, b4);
7257 }
7258 rb_io_ungetbyte(io, b3);
7259 return ENCINDEX_UTF_16LE;
7260 }
7261 rb_io_ungetbyte(io, b2);
7262 break;
7263
7264 case INT2FIX(0):
7265 if (NIL_P(b2 = rb_io_getbyte(io))) break;
7266 if (b2 == INT2FIX(0) && !NIL_P(b3 = rb_io_getbyte(io))) {
7267 if (b3 == INT2FIX(0xFE) && !NIL_P(b4 = rb_io_getbyte(io))) {
7268 if (b4 == INT2FIX(0xFF)) {
7269 return ENCINDEX_UTF_32BE;
7270 }
7271 rb_io_ungetbyte(io, b4);
7272 }
7273 rb_io_ungetbyte(io, b3);
7274 }
7275 rb_io_ungetbyte(io, b2);
7276 break;
7277 }
7278 rb_io_ungetbyte(io, b1);
7279 return 0;
7280}
7281
7282static rb_encoding *
7283io_set_encoding_by_bom(VALUE io)
7284{
7285 int idx = io_strip_bom(io);
7286 rb_io_t *fptr;
7287 rb_encoding *extenc = NULL;
7288
7289 GetOpenFile(io, fptr);
7290 if (idx) {
7291 extenc = rb_enc_from_index(idx);
7292 io_encoding_set(fptr, rb_enc_from_encoding(extenc),
7293 rb_io_internal_encoding(io), Qnil);
7294 }
7295 else {
7296 fptr->encs.enc2 = NULL;
7297 }
7298 return extenc;
7299}
7300
7301static VALUE
7302rb_file_open_generic(VALUE io, VALUE filename, int oflags, enum rb_io_mode fmode,
7303 const struct rb_io_encoding *convconfig, mode_t perm)
7304{
7305 VALUE pathv;
7306 rb_io_t *fptr;
7307 struct rb_io_encoding cc;
7308 if (!convconfig) {
7309 /* Set to default encodings */
7310 rb_io_ext_int_to_encs(NULL, NULL, &cc.enc, &cc.enc2, fmode);
7311 cc.ecflags = 0;
7312 cc.ecopts = Qnil;
7313 convconfig = &cc;
7314 }
7315 validate_enc_binmode(&fmode, convconfig->ecflags,
7316 convconfig->enc, convconfig->enc2);
7317
7318 MakeOpenFile(io, fptr);
7319 fptr->mode = fmode;
7320 fptr->encs = *convconfig;
7321 pathv = rb_str_new_frozen(filename);
7322#ifdef O_TMPFILE
7323 if (!(oflags & O_TMPFILE)) {
7324 fptr->pathv = pathv;
7325 }
7326#else
7327 fptr->pathv = pathv;
7328#endif
7329 fptr->fd = rb_sysopen(pathv, oflags, perm);
7330 io_check_tty(fptr);
7331 if (fmode & FMODE_SETENC_BY_BOM) io_set_encoding_by_bom(io);
7332
7333 return io;
7334}
7335
7336static VALUE
7337rb_file_open_internal(VALUE io, VALUE filename, const char *modestr)
7338{
7339 enum rb_io_mode fmode = rb_io_modestr_fmode(modestr);
7340 const char *p = strchr(modestr, ':');
7341 struct rb_io_encoding convconfig;
7342
7343 if (p) {
7344 parse_mode_enc(p+1, rb_usascii_encoding(),
7345 &convconfig.enc, &convconfig.enc2, &fmode);
7346 }
7347 else {
7348 rb_encoding *e;
7349 /* Set to default encodings */
7350
7351 e = (fmode & FMODE_BINMODE) ? rb_ascii8bit_encoding() : NULL;
7352 rb_io_ext_int_to_encs(e, NULL, &convconfig.enc, &convconfig.enc2, fmode);
7353 }
7354
7355 convconfig.ecflags = (fmode & FMODE_READABLE) ?
7358#ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE
7359 convconfig.ecflags |= (fmode & FMODE_WRITABLE) ?
7360 MODE_BTMODE(TEXTMODE_NEWLINE_DECORATOR_ON_WRITE,
7361 0, TEXTMODE_NEWLINE_DECORATOR_ON_WRITE) : 0;
7362#endif
7363 SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(convconfig.enc2, convconfig.ecflags);
7364 convconfig.ecopts = Qnil;
7365
7366 return rb_file_open_generic(io, filename,
7367 rb_io_fmode_oflags(fmode),
7368 fmode,
7369 &convconfig,
7370 0666);
7371}
7372
7373VALUE
7374rb_file_open_str(VALUE fname, const char *modestr)
7375{
7376 FilePathValue(fname);
7377 return rb_file_open_internal(io_alloc(rb_cFile), fname, modestr);
7378}
7379
7380VALUE
7381rb_file_open(const char *fname, const char *modestr)
7382{
7383 return rb_file_open_internal(io_alloc(rb_cFile), rb_str_new_cstr(fname), modestr);
7384}
7385
7386#if defined(__CYGWIN__) || !defined(HAVE_WORKING_FORK)
7387static struct pipe_list {
7388 rb_io_t *fptr;
7389 struct pipe_list *next;
7390} *pipe_list;
7391
7392static void
7393pipe_add_fptr(rb_io_t *fptr)
7394{
7395 struct pipe_list *list;
7396
7397 list = ALLOC(struct pipe_list);
7398 list->fptr = fptr;
7399 list->next = pipe_list;
7400 pipe_list = list;
7401}
7402
7403static void
7404pipe_del_fptr(rb_io_t *fptr)
7405{
7406 struct pipe_list **prev = &pipe_list;
7407 struct pipe_list *tmp;
7408
7409 while ((tmp = *prev) != 0) {
7410 if (tmp->fptr == fptr) {
7411 *prev = tmp->next;
7412 free(tmp);
7413 return;
7414 }
7415 prev = &tmp->next;
7416 }
7417}
7418
7419#if defined (_WIN32) || defined(__CYGWIN__)
7420static void
7421pipe_atexit(void)
7422{
7423 struct pipe_list *list = pipe_list;
7424 struct pipe_list *tmp;
7425
7426 while (list) {
7427 tmp = list->next;
7428 rb_io_fptr_finalize(list->fptr);
7429 list = tmp;
7430 }
7431}
7432#endif
7433
7434static void
7435pipe_finalize(rb_io_t *fptr, int noraise)
7436{
7437#if !defined(HAVE_WORKING_FORK) && !defined(_WIN32)
7438 int status = 0;
7439 if (fptr->stdio_file) {
7440 status = pclose(fptr->stdio_file);
7441 }
7442 fptr->fd = -1;
7443 fptr->stdio_file = 0;
7444 rb_last_status_set(status, fptr->pid);
7445#else
7446 fptr_finalize(fptr, noraise);
7447#endif
7448 pipe_del_fptr(fptr);
7449}
7450#endif
7451
7452static void
7453fptr_copy_finalizer(rb_io_t *fptr, const rb_io_t *orig)
7454{
7455#if defined(__CYGWIN__) || !defined(HAVE_WORKING_FORK)
7456 void (*const old_finalize)(struct rb_io*,int) = fptr->finalize;
7457
7458 if (old_finalize == orig->finalize) return;
7459#endif
7460
7461 fptr->finalize = orig->finalize;
7462
7463#if defined(__CYGWIN__) || !defined(HAVE_WORKING_FORK)
7464 if (old_finalize != pipe_finalize) {
7465 struct pipe_list *list;
7466 for (list = pipe_list; list; list = list->next) {
7467 if (list->fptr == fptr) break;
7468 }
7469 if (!list) pipe_add_fptr(fptr);
7470 }
7471 else {
7472 pipe_del_fptr(fptr);
7473 }
7474#endif
7475}
7476
7477void
7479{
7481 fptr->mode |= FMODE_SYNC;
7482}
7483
7484void
7485rb_io_unbuffered(rb_io_t *fptr)
7486{
7487 rb_io_synchronized(fptr);
7488}
7489
7490int
7491rb_pipe(int *pipes)
7492{
7493 int ret;
7494 TRY_WITH_GC((ret = rb_cloexec_pipe(pipes)) >= 0);
7495 if (ret == 0) {
7496 rb_update_max_fd(pipes[0]);
7497 rb_update_max_fd(pipes[1]);
7498 }
7499 return ret;
7500}
7501
7502#ifdef _WIN32
7503#define HAVE_SPAWNV 1
7504#define spawnv(mode, cmd, args) rb_w32_uaspawn((mode), (cmd), (args))
7505#define spawn(mode, cmd) rb_w32_uspawn((mode), (cmd), 0)
7506#endif
7507
7508#if defined(HAVE_WORKING_FORK) || defined(HAVE_SPAWNV)
7509struct popen_arg {
7510 VALUE execarg_obj;
7511 struct rb_execarg *eargp;
7512 int modef;
7513 int pair[2];
7514 int write_pair[2];
7515};
7516#endif
7517
7518#ifdef HAVE_WORKING_FORK
7519# ifndef __EMSCRIPTEN__
7520static void
7521popen_redirect(struct popen_arg *p)
7522{
7523 if ((p->modef & FMODE_READABLE) && (p->modef & FMODE_WRITABLE)) {
7524 close(p->write_pair[1]);
7525 if (p->write_pair[0] != 0) {
7526 dup2(p->write_pair[0], 0);
7527 close(p->write_pair[0]);
7528 }
7529 close(p->pair[0]);
7530 if (p->pair[1] != 1) {
7531 dup2(p->pair[1], 1);
7532 close(p->pair[1]);
7533 }
7534 }
7535 else if (p->modef & FMODE_READABLE) {
7536 close(p->pair[0]);
7537 if (p->pair[1] != 1) {
7538 dup2(p->pair[1], 1);
7539 close(p->pair[1]);
7540 }
7541 }
7542 else {
7543 close(p->pair[1]);
7544 if (p->pair[0] != 0) {
7545 dup2(p->pair[0], 0);
7546 close(p->pair[0]);
7547 }
7548 }
7549}
7550# endif
7551
7552#if defined(__linux__)
7553/* Linux /proc/self/status contains a line: "FDSize:\t<nnn>\n"
7554 * Since /proc may not be available, linux_get_maxfd is just a hint.
7555 * This function, linux_get_maxfd, must be async-signal-safe.
7556 * I.e. opendir() is not usable.
7557 *
7558 * Note that memchr() and memcmp is *not* async-signal-safe in POSIX.
7559 * However they are easy to re-implement in async-signal-safe manner.
7560 * (Also note that there is missing/memcmp.c.)
7561 */
7562static int
7563linux_get_maxfd(void)
7564{
7565 int fd;
7566 char buf[4096], *p, *np, *e;
7567 ssize_t ss;
7568 fd = rb_cloexec_open("/proc/self/status", O_RDONLY|O_NOCTTY, 0);
7569 if (fd < 0) return fd;
7570 ss = read(fd, buf, sizeof(buf));
7571 if (ss < 0) goto err;
7572 p = buf;
7573 e = buf + ss;
7574 while ((int)sizeof("FDSize:\t0\n")-1 <= e-p &&
7575 (np = memchr(p, '\n', e-p)) != NULL) {
7576 if (memcmp(p, "FDSize:", sizeof("FDSize:")-1) == 0) {
7577 int fdsize;
7578 p += sizeof("FDSize:")-1;
7579 *np = '\0';
7580 fdsize = (int)ruby_strtoul(p, (char **)NULL, 10);
7581 close(fd);
7582 return fdsize;
7583 }
7584 p = np+1;
7585 }
7586 /* fall through */
7587
7588 err:
7589 close(fd);
7590 return (int)ss;
7591}
7592#endif
7593
7594/* This function should be async-signal-safe. */
7595void
7596rb_close_before_exec(int lowfd, int maxhint, VALUE noclose_fds)
7597{
7598#if defined(HAVE_FCNTL) && defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
7599 int fd, ret;
7600 int max = (int)max_file_descriptor;
7601# ifdef F_MAXFD
7602 /* F_MAXFD is available since NetBSD 2.0. */
7603 ret = fcntl(0, F_MAXFD); /* async-signal-safe */
7604 if (ret != -1)
7605 maxhint = max = ret;
7606# elif defined(__linux__)
7607 ret = linux_get_maxfd();
7608 if (maxhint < ret)
7609 maxhint = ret;
7610 /* maxhint = max = ret; if (ret == -1) abort(); // test */
7611# endif
7612 if (max < maxhint)
7613 max = maxhint;
7614 for (fd = lowfd; fd <= max; fd++) {
7615 if (!NIL_P(noclose_fds) &&
7616 RTEST(rb_hash_lookup(noclose_fds, INT2FIX(fd)))) /* async-signal-safe */
7617 continue;
7618 ret = fcntl(fd, F_GETFD); /* async-signal-safe */
7619 if (ret != -1 && !(ret & FD_CLOEXEC)) {
7620 fcntl(fd, F_SETFD, ret|FD_CLOEXEC); /* async-signal-safe */
7621 }
7622# define CONTIGUOUS_CLOSED_FDS 20
7623 if (ret != -1) {
7624 if (max < fd + CONTIGUOUS_CLOSED_FDS)
7625 max = fd + CONTIGUOUS_CLOSED_FDS;
7626 }
7627 }
7628#endif
7629}
7630
7631# ifndef __EMSCRIPTEN__
7632static int
7633popen_exec(void *pp, char *errmsg, size_t errmsg_len)
7634{
7635 struct popen_arg *p = (struct popen_arg*)pp;
7636
7637 return rb_exec_async_signal_safe(p->eargp, errmsg, errmsg_len);
7638}
7639# endif
7640#endif
7641
7642#if (defined(HAVE_WORKING_FORK) || defined(HAVE_SPAWNV)) && !defined __EMSCRIPTEN__
7643static VALUE
7644rb_execarg_fixup_v(VALUE execarg_obj)
7645{
7646 rb_execarg_parent_start(execarg_obj);
7647 return Qnil;
7648}
7649#else
7650char *rb_execarg_commandline(const struct rb_execarg *eargp, VALUE *prog);
7651#endif
7652
7653#ifndef __EMSCRIPTEN__
7654static VALUE
7655pipe_open(VALUE execarg_obj, const char *modestr, enum rb_io_mode fmode,
7656 const struct rb_io_encoding *convconfig)
7657{
7658 struct rb_execarg *eargp = NIL_P(execarg_obj) ? NULL : rb_execarg_get(execarg_obj);
7659 VALUE prog = eargp ? (eargp->use_shell ? eargp->invoke.sh.shell_script : eargp->invoke.cmd.command_name) : Qfalse ;
7660 rb_pid_t pid = 0;
7661 rb_io_t *fptr;
7662 VALUE port;
7663 rb_io_t *write_fptr;
7664 VALUE write_port;
7665#if defined(HAVE_WORKING_FORK)
7666 int status;
7667 char errmsg[80] = { '\0' };
7668#endif
7669#if defined(HAVE_WORKING_FORK) || defined(HAVE_SPAWNV)
7670 int state;
7671 struct popen_arg arg;
7672#endif
7673 int e = 0;
7674#if defined(HAVE_SPAWNV)
7675# if defined(HAVE_SPAWNVE)
7676# define DO_SPAWN(cmd, args, envp) ((args) ? \
7677 spawnve(P_NOWAIT, (cmd), (args), (envp)) : \
7678 spawne(P_NOWAIT, (cmd), (envp)))
7679# else
7680# define DO_SPAWN(cmd, args, envp) ((args) ? \
7681 spawnv(P_NOWAIT, (cmd), (args)) : \
7682 spawn(P_NOWAIT, (cmd)))
7683# endif
7684# if !defined(HAVE_WORKING_FORK)
7685 char **args = NULL;
7686# if defined(HAVE_SPAWNVE)
7687 char **envp = NULL;
7688# endif
7689# endif
7690#endif
7691#if !defined(HAVE_WORKING_FORK)
7692 struct rb_execarg sarg, *sargp = &sarg;
7693#endif
7694 FILE *fp = 0;
7695 int fd = -1;
7696 int write_fd = -1;
7697#if !defined(HAVE_WORKING_FORK)
7698 const char *cmd = 0;
7699
7700 if (prog)
7701 cmd = StringValueCStr(prog);
7702#endif
7703
7704#if defined(HAVE_WORKING_FORK) || defined(HAVE_SPAWNV)
7705 arg.execarg_obj = execarg_obj;
7706 arg.eargp = eargp;
7707 arg.modef = fmode;
7708 arg.pair[0] = arg.pair[1] = -1;
7709 arg.write_pair[0] = arg.write_pair[1] = -1;
7710# if !defined(HAVE_WORKING_FORK)
7711 if (eargp && !eargp->use_shell) {
7712 args = ARGVSTR2ARGV(eargp->invoke.cmd.argv_str);
7713 }
7714# endif
7715 switch (fmode & (FMODE_READABLE|FMODE_WRITABLE)) {
7717 if (rb_pipe(arg.write_pair) < 0)
7718 rb_sys_fail_str(prog);
7719 if (rb_pipe(arg.pair) < 0) {
7720 e = errno;
7721 close(arg.write_pair[0]);
7722 close(arg.write_pair[1]);
7723 rb_syserr_fail_str(e, prog);
7724 }
7725 if (eargp) {
7726 rb_execarg_addopt(execarg_obj, INT2FIX(0), INT2FIX(arg.write_pair[0]));
7727 rb_execarg_addopt(execarg_obj, INT2FIX(1), INT2FIX(arg.pair[1]));
7728 }
7729 break;
7730 case FMODE_READABLE:
7731 if (rb_pipe(arg.pair) < 0)
7732 rb_sys_fail_str(prog);
7733 if (eargp)
7734 rb_execarg_addopt(execarg_obj, INT2FIX(1), INT2FIX(arg.pair[1]));
7735 break;
7736 case FMODE_WRITABLE:
7737 if (rb_pipe(arg.pair) < 0)
7738 rb_sys_fail_str(prog);
7739 if (eargp)
7740 rb_execarg_addopt(execarg_obj, INT2FIX(0), INT2FIX(arg.pair[0]));
7741 break;
7742 default:
7743 rb_sys_fail_str(prog);
7744 }
7745 if (!NIL_P(execarg_obj)) {
7746 rb_protect(rb_execarg_fixup_v, execarg_obj, &state);
7747 if (state) {
7748 if (0 <= arg.write_pair[0]) close(arg.write_pair[0]);
7749 if (0 <= arg.write_pair[1]) close(arg.write_pair[1]);
7750 if (0 <= arg.pair[0]) close(arg.pair[0]);
7751 if (0 <= arg.pair[1]) close(arg.pair[1]);
7752 rb_execarg_parent_end(execarg_obj);
7753 rb_jump_tag(state);
7754 }
7755
7756# if defined(HAVE_WORKING_FORK)
7757 pid = rb_fork_async_signal_safe(&status, popen_exec, &arg, arg.eargp->redirect_fds, errmsg, sizeof(errmsg));
7758# else
7759 rb_execarg_run_options(eargp, sargp, NULL, 0);
7760# if defined(HAVE_SPAWNVE)
7761 if (eargp->envp_str) envp = (char **)RSTRING_PTR(eargp->envp_str);
7762# endif
7763 while ((pid = DO_SPAWN(cmd, args, envp)) < 0) {
7764 /* exec failed */
7765 switch (e = errno) {
7766 case EAGAIN:
7767# if EWOULDBLOCK != EAGAIN
7768 case EWOULDBLOCK:
7769# endif
7770 rb_thread_sleep(1);
7771 continue;
7772 }
7773 break;
7774 }
7775 if (eargp)
7776 rb_execarg_run_options(sargp, NULL, NULL, 0);
7777# endif
7778 rb_execarg_parent_end(execarg_obj);
7779 }
7780 else {
7781# if defined(HAVE_WORKING_FORK)
7782 pid = rb_call_proc__fork();
7783 if (pid == 0) { /* child */
7784 popen_redirect(&arg);
7785 rb_io_synchronized(RFILE(orig_stdout)->fptr);
7786 rb_io_synchronized(RFILE(orig_stderr)->fptr);
7787 return Qnil;
7788 }
7789# else
7791# endif
7792 }
7793
7794 /* parent */
7795 if (pid < 0) {
7796# if defined(HAVE_WORKING_FORK)
7797 e = errno;
7798# endif
7799 close(arg.pair[0]);
7800 close(arg.pair[1]);
7802 close(arg.write_pair[0]);
7803 close(arg.write_pair[1]);
7804 }
7805# if defined(HAVE_WORKING_FORK)
7806 if (errmsg[0])
7807 rb_syserr_fail(e, errmsg);
7808# endif
7809 rb_syserr_fail_str(e, prog);
7810 }
7811 if ((fmode & FMODE_READABLE) && (fmode & FMODE_WRITABLE)) {
7812 close(arg.pair[1]);
7813 fd = arg.pair[0];
7814 close(arg.write_pair[0]);
7815 write_fd = arg.write_pair[1];
7816 }
7817 else if (fmode & FMODE_READABLE) {
7818 close(arg.pair[1]);
7819 fd = arg.pair[0];
7820 }
7821 else {
7822 close(arg.pair[0]);
7823 fd = arg.pair[1];
7824 }
7825#else
7826 cmd = rb_execarg_commandline(eargp, &prog);
7827 if (!NIL_P(execarg_obj)) {
7828 rb_execarg_parent_start(execarg_obj);
7829 rb_execarg_run_options(eargp, sargp, NULL, 0);
7830 }
7831 fp = popen(cmd, modestr);
7832 e = errno;
7833 if (eargp) {
7834 rb_execarg_parent_end(execarg_obj);
7835 rb_execarg_run_options(sargp, NULL, NULL, 0);
7836 }
7837 if (!fp) rb_syserr_fail_path(e, prog);
7838 fd = fileno(fp);
7839#endif
7840
7841 port = io_alloc(rb_cIO);
7842 MakeOpenFile(port, fptr);
7843 fptr->fd = fd;
7844 fptr->stdio_file = fp;
7845 fptr->mode = fmode | FMODE_SYNC|FMODE_DUPLEX;
7846 if (convconfig) {
7847 fptr->encs = *convconfig;
7848#if RUBY_CRLF_ENVIRONMENT
7851 }
7852#endif
7853 }
7854 else {
7855 if (NEED_NEWLINE_DECORATOR_ON_READ(fptr)) {
7857 }
7858#ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE
7859 if (NEED_NEWLINE_DECORATOR_ON_WRITE(fptr)) {
7860 fptr->encs.ecflags |= TEXTMODE_NEWLINE_DECORATOR_ON_WRITE;
7861 }
7862#endif
7863 }
7864 fptr->pid = pid;
7865
7866 if (0 <= write_fd) {
7867 write_port = io_alloc(rb_cIO);
7868 MakeOpenFile(write_port, write_fptr);
7869 write_fptr->fd = write_fd;
7870 write_fptr->mode = (fmode & ~FMODE_READABLE)| FMODE_SYNC|FMODE_DUPLEX;
7871 fptr->mode &= ~FMODE_WRITABLE;
7872 fptr->tied_io_for_writing = write_port;
7873 rb_ivar_set(port, rb_intern("@tied_io_for_writing"), write_port);
7874 }
7875
7876#if defined (__CYGWIN__) || !defined(HAVE_WORKING_FORK)
7877 fptr->finalize = pipe_finalize;
7878 pipe_add_fptr(fptr);
7879#endif
7880 return port;
7881}
7882#else
7883static VALUE
7884pipe_open(VALUE execarg_obj, const char *modestr, enum rb_io_mode fmode,
7885 const struct rb_io_encoding *convconfig)
7886{
7887 rb_raise(rb_eNotImpError, "popen() is not available");
7888}
7889#endif
7890
7891static int
7892is_popen_fork(VALUE prog)
7893{
7894 if (RSTRING_LEN(prog) == 1 && RSTRING_PTR(prog)[0] == '-') {
7895#if !defined(HAVE_WORKING_FORK)
7896 rb_raise(rb_eNotImpError,
7897 "fork() function is unimplemented on this machine");
7898#else
7899 return TRUE;
7900#endif
7901 }
7902 return FALSE;
7903}
7904
7905static VALUE
7906pipe_open_s(VALUE prog, const char *modestr, enum rb_io_mode fmode,
7907 const struct rb_io_encoding *convconfig)
7908{
7909 int argc = 1;
7910 VALUE *argv = &prog;
7911 VALUE execarg_obj = Qnil;
7912
7913 if (!is_popen_fork(prog))
7914 execarg_obj = rb_execarg_new(argc, argv, TRUE, FALSE);
7915 return pipe_open(execarg_obj, modestr, fmode, convconfig);
7916}
7917
7918static VALUE
7919pipe_close(VALUE io)
7920{
7921 rb_io_t *fptr = io_close_fptr(io);
7922 if (fptr) {
7923 fptr_waitpid(fptr, rb_thread_to_be_killed(rb_thread_current()));
7924 }
7925 return Qnil;
7926}
7927
7928static VALUE popen_finish(VALUE port, VALUE klass);
7929
7930/*
7931 * call-seq:
7932 * IO.popen(env = {}, cmd, mode = 'r', **opts) -> io
7933 * IO.popen(env = {}, cmd, mode = 'r', **opts) {|io| ... } -> object
7934 *
7935 * Executes the given command +cmd+ as a subprocess
7936 * whose $stdin and $stdout are connected to a new stream +io+.
7937 *
7938 * This method has potential security vulnerabilities if called with untrusted input;
7939 * see {Command Injection}[rdoc-ref:security/command_injection.rdoc].
7940 *
7941 * If no block is given, returns the new stream,
7942 * which depending on given +mode+ may be open for reading, writing, or both.
7943 * The stream should be explicitly closed (eventually) to avoid resource leaks.
7944 *
7945 * If a block is given, the stream is passed to the block
7946 * (again, open for reading, writing, or both);
7947 * when the block exits, the stream is closed,
7948 * the block's value is returned,
7949 * and the global variable <tt>$?</tt> is set to the child's exit status.
7950 *
7951 * Optional argument +mode+ may be any valid \IO mode.
7952 * See {Access Modes}[rdoc-ref:File@Access+Modes].
7953 *
7954 * Required argument +cmd+ determines which of the following occurs:
7955 *
7956 * - The process forks.
7957 * - A specified program runs in a shell.
7958 * - A specified program runs with specified arguments.
7959 * - A specified program runs with specified arguments and a specified +argv0+.
7960 *
7961 * Each of these is detailed below.
7962 *
7963 * The optional hash argument +env+ specifies name/value pairs that are to be added
7964 * to the environment variables for the subprocess:
7965 *
7966 * IO.popen({'FOO' => 'bar'}, 'ruby', 'r+') do |pipe|
7967 * pipe.puts 'puts ENV["FOO"]'
7968 * pipe.close_write
7969 * pipe.gets
7970 * end => "bar\n"
7971 *
7972 * Optional keyword arguments +opts+ specify:
7973 *
7974 * - {Open options}[rdoc-ref:IO@Open+Options].
7975 * - {Encoding options}[rdoc-ref:encodings.rdoc@Encoding+Options].
7976 * - Options for Kernel#spawn.
7977 *
7978 * <b>Forked Process</b>
7979 *
7980 * When argument +cmd+ is the 1-character string <tt>'-'</tt>, causes the process to fork:
7981 * IO.popen('-') do |pipe|
7982 * if pipe
7983 * $stderr.puts "In parent, child pid is #{pipe.pid}\n"
7984 * else
7985 * $stderr.puts "In child, pid is #{$$}\n"
7986 * end
7987 * end
7988 *
7989 * Output:
7990 *
7991 * In parent, child pid is 26253
7992 * In child, pid is 26253
7993 *
7994 * Note that this is not supported on all platforms.
7995 *
7996 * <b>Shell Subprocess</b>
7997 *
7998 * When argument +cmd+ is a single string (but not <tt>'-'</tt>),
7999 * the program named +cmd+ is run as a shell command:
8000 *
8001 * IO.popen('uname') do |pipe|
8002 * pipe.readlines
8003 * end
8004 *
8005 * Output:
8006 *
8007 * ["Linux\n"]
8008 *
8009 * Another example:
8010 *
8011 * IO.popen('/bin/sh', 'r+') do |pipe|
8012 * pipe.puts('ls')
8013 * pipe.close_write
8014 * $stderr.puts pipe.readlines.size
8015 * end
8016 *
8017 * Output:
8018 *
8019 * 213
8020 *
8021 * <b>Program Subprocess</b>
8022 *
8023 * When argument +cmd+ is an array of strings,
8024 * the program named <tt>cmd[0]</tt> is run with all elements of +cmd+ as its arguments:
8025 *
8026 * IO.popen(['du', '..', '.']) do |pipe|
8027 * $stderr.puts pipe.readlines.size
8028 * end
8029 *
8030 * Output:
8031 *
8032 * 1111
8033 *
8034 * <b>Program Subprocess with <tt>argv0</tt></b>
8035 *
8036 * When argument +cmd+ is an array whose first element is a 2-element string array
8037 * and whose remaining elements (if any) are strings:
8038 *
8039 * - <tt>cmd[0][0]</tt> (the first string in the nested array) is the name of a program that is run.
8040 * - <tt>cmd[0][1]</tt> (the second string in the nested array) is set as the program's <tt>argv[0]</tt>.
8041 * - <tt>cmd[1..-1]</tt> (the strings in the outer array) are the program's arguments.
8042 *
8043 * Example (sets <tt>$0</tt> to 'foo'):
8044 *
8045 * IO.popen([['/bin/sh', 'foo'], '-c', 'echo $0']).read # => "foo\n"
8046 *
8047 * <b>Some Special Examples</b>
8048 *
8049 * # Set IO encoding.
8050 * IO.popen("nkf -e filename", :external_encoding=>"EUC-JP") {|nkf_io|
8051 * euc_jp_string = nkf_io.read
8052 * }
8053 *
8054 * # Merge standard output and standard error using Kernel#spawn option. See Kernel#spawn.
8055 * IO.popen(["ls", "/", :err=>[:child, :out]]) do |io|
8056 * ls_result_with_error = io.read
8057 * end
8058 *
8059 * # Use mixture of spawn options and IO options.
8060 * IO.popen(["ls", "/"], :err=>[:child, :out]) do |io|
8061 * ls_result_with_error = io.read
8062 * end
8063 *
8064 * f = IO.popen("uname")
8065 * p f.readlines
8066 * f.close
8067 * puts "Parent is #{Process.pid}"
8068 * IO.popen("date") {|f| puts f.gets }
8069 * IO.popen("-") {|f| $stderr.puts "#{Process.pid} is here, f is #{f.inspect}"}
8070 * p $?
8071 * IO.popen(%w"sed -e s|^|<foo>| -e s&$&;zot;&", "r+") {|f|
8072 * f.puts "bar"; f.close_write; puts f.gets
8073 * }
8074 *
8075 * Output (from last section):
8076 *
8077 * ["Linux\n"]
8078 * Parent is 21346
8079 * Thu Jan 15 22:41:19 JST 2009
8080 * 21346 is here, f is #<IO:fd 3>
8081 * 21352 is here, f is nil
8082 * #<Process::Status: pid 21352 exit 0>
8083 * <foo>bar;zot;
8084 *
8085 * Raises exceptions that IO.pipe and Kernel.spawn raise.
8086 *
8087 */
8088
8089static VALUE
8090rb_io_s_popen(int argc, VALUE *argv, VALUE klass)
8091{
8092 VALUE pname, pmode = Qnil, opt = Qnil, env = Qnil;
8093
8094 if (argc > 1 && !NIL_P(opt = rb_check_hash_type(argv[argc-1]))) --argc;
8095 if (argc > 1 && !NIL_P(env = rb_check_hash_type(argv[0]))) --argc, ++argv;
8096 switch (argc) {
8097 case 2:
8098 pmode = argv[1];
8099 case 1:
8100 pname = argv[0];
8101 break;
8102 default:
8103 {
8104 int ex = !NIL_P(opt);
8105 rb_error_arity(argc + ex, 1 + ex, 2 + ex);
8106 }
8107 }
8108 return popen_finish(rb_io_popen(pname, pmode, env, opt), klass);
8109}
8110
8111VALUE
8112rb_io_popen(VALUE pname, VALUE pmode, VALUE env, VALUE opt)
8113{
8114 const char *modestr;
8115 VALUE tmp, execarg_obj = Qnil;
8116 int oflags;
8117 enum rb_io_mode fmode;
8118 struct rb_io_encoding convconfig;
8119
8120 tmp = rb_check_array_type(pname);
8121 if (!NIL_P(tmp)) {
8122 long len = RARRAY_LEN(tmp);
8123#if SIZEOF_LONG > SIZEOF_INT
8124 if (len > INT_MAX) {
8125 rb_raise(rb_eArgError, "too many arguments");
8126 }
8127#endif
8128 execarg_obj = rb_execarg_new((int)len, RARRAY_CONST_PTR(tmp), FALSE, FALSE);
8129 RB_GC_GUARD(tmp);
8130 }
8131 else {
8132 StringValue(pname);
8133 execarg_obj = Qnil;
8134 if (!is_popen_fork(pname))
8135 execarg_obj = rb_execarg_new(1, &pname, TRUE, FALSE);
8136 }
8137 if (!NIL_P(execarg_obj)) {
8138 if (!NIL_P(opt))
8139 opt = rb_execarg_extract_options(execarg_obj, opt);
8140 if (!NIL_P(env))
8141 rb_execarg_setenv(execarg_obj, env);
8142 }
8143 rb_io_extract_modeenc(&pmode, 0, opt, &oflags, &fmode, &convconfig);
8144 modestr = rb_io_oflags_modestr(oflags);
8145
8146 return pipe_open(execarg_obj, modestr, fmode, &convconfig);
8147}
8148
8149static VALUE
8150popen_finish(VALUE port, VALUE klass)
8151{
8152 if (NIL_P(port)) {
8153 /* child */
8154 if (rb_block_given_p()) {
8155 rb_protect(rb_yield, Qnil, NULL);
8156 rb_io_flush(rb_ractor_stdout());
8157 rb_io_flush(rb_ractor_stderr());
8158 _exit(0);
8159 }
8160 return Qnil;
8161 }
8162 RBASIC_SET_CLASS(port, klass);
8163 if (rb_block_given_p()) {
8164 return rb_ensure(rb_yield, port, pipe_close, port);
8165 }
8166 return port;
8167}
8168
8169#if defined(HAVE_WORKING_FORK) && !defined(__EMSCRIPTEN__)
8170struct popen_writer_arg {
8171 char *const *argv;
8172 struct popen_arg popen;
8173};
8174
8175static int
8176exec_popen_writer(void *arg, char *errmsg, size_t buflen)
8177{
8178 struct popen_writer_arg *pw = arg;
8179 pw->popen.modef = FMODE_WRITABLE;
8180 popen_redirect(&pw->popen);
8181 execv(pw->argv[0], pw->argv);
8182 strlcpy(errmsg, strerror(errno), buflen);
8183 return -1;
8184}
8185#endif
8186
8187FILE *
8188ruby_popen_writer(char *const *argv, rb_pid_t *pid)
8189{
8190#if (defined(HAVE_WORKING_FORK) && !defined(__EMSCRIPTEN__)) || defined(_WIN32)
8191# ifdef HAVE_WORKING_FORK
8192 struct popen_writer_arg pw;
8193 int *const write_pair = pw.popen.pair;
8194# else
8195 int write_pair[2];
8196# endif
8197
8198 *pid = -1;
8199 if (cloexec_pipe(write_pair, 0, false) == 0) {
8200# ifdef HAVE_WORKING_FORK
8201 pw.argv = argv;
8202 int status;
8203 char errmsg[80] = {'\0'};
8204 *pid = rb_fork_async_signal_safe(&status, exec_popen_writer, &pw, Qnil, errmsg, sizeof(errmsg));
8205# else
8206 *pid = rb_w32_uspawn_process(P_NOWAIT, argv[0], argv, write_pair[0], -1, -1, 0);
8207 const char *errmsg = (*pid < 0) ? strerror(errno) : NULL;
8208# endif
8209 close(write_pair[0]);
8210 if (*pid < 0) {
8211 close(write_pair[1]);
8212 fprintf(stderr, "ruby_popen_writer(%s): %s\n", argv[0], errmsg);
8213 }
8214 else {
8215 return fdopen(write_pair[1], "w");
8216 }
8217 }
8218#endif
8219 return NULL;
8220}
8221
8222static VALUE
8223rb_open_file(VALUE io, VALUE fname, VALUE vmode, VALUE vperm, VALUE opt)
8224{
8225 int oflags;
8226 enum rb_io_mode fmode;
8227 struct rb_io_encoding convconfig;
8228 mode_t perm;
8229
8230 FilePathValue(fname);
8231
8232 rb_io_extract_modeenc(&vmode, &vperm, opt, &oflags, &fmode, &convconfig);
8233 perm = NIL_P(vperm) ? 0666 : NUM2MODET(vperm);
8234
8235 rb_file_open_generic(io, fname, oflags, fmode, &convconfig, perm);
8236
8237 return io;
8238}
8239
8240/*
8241 * Document-method: File::open
8242 *
8243 * call-seq:
8244 * File.open(path, mode = 'r', perm = 0666, **opts) -> file
8245 * File.open(path, mode = 'r', perm = 0666, **opts) {|f| ... } -> object
8246 *
8247 * Creates a new File object, via File.new with the given arguments.
8248 *
8249 * With no block given, returns the File object.
8250 *
8251 * With a block given, calls the block with the File object
8252 * and returns the block's value.
8253 *
8254 */
8255
8256/*
8257 * Document-method: IO::open
8258 *
8259 * call-seq:
8260 * IO.open(fd, mode = 'r', **opts) -> io
8261 * IO.open(fd, mode = 'r', **opts) {|io| ... } -> object
8262 *
8263 * Creates a new \IO object, via IO.new with the given arguments.
8264 *
8265 * With no block given, returns the \IO object.
8266 *
8267 * With a block given, calls the block with the \IO object
8268 * and returns the block's value.
8269 *
8270 */
8271
8272static VALUE
8273rb_io_s_open(int argc, VALUE *argv, VALUE klass)
8274{
8276
8277 if (rb_block_given_p()) {
8278 return rb_ensure(rb_yield, io, io_close, io);
8279 }
8280
8281 return io;
8282}
8283
8284/*
8285 * call-seq:
8286 * IO.sysopen(path, mode = 'r', perm = 0666) -> integer
8287 *
8288 * Opens the file at the given path with the given mode and permissions;
8289 * returns the integer file descriptor.
8290 *
8291 * If the file is to be readable, it must exist;
8292 * if the file is to be writable and does not exist,
8293 * it is created with the given permissions:
8294 *
8295 * File.write('t.tmp', '') # => 0
8296 * IO.sysopen('t.tmp') # => 8
8297 * IO.sysopen('t.tmp', 'w') # => 9
8298 *
8299 *
8300 */
8301
8302static VALUE
8303rb_io_s_sysopen(int argc, VALUE *argv, VALUE _)
8304{
8305 VALUE fname, vmode, vperm;
8306 VALUE intmode;
8307 int oflags, fd;
8308 mode_t perm;
8309
8310 rb_scan_args(argc, argv, "12", &fname, &vmode, &vperm);
8311 FilePathValue(fname);
8312
8313 if (NIL_P(vmode))
8314 oflags = O_RDONLY;
8315 else if (!NIL_P(intmode = rb_check_to_integer(vmode, "to_int")))
8316 oflags = NUM2INT(intmode);
8317 else {
8318 StringValue(vmode);
8319 oflags = rb_io_modestr_oflags(StringValueCStr(vmode));
8320 }
8321 if (NIL_P(vperm)) perm = 0666;
8322 else perm = NUM2MODET(vperm);
8323
8324 RB_GC_GUARD(fname) = rb_str_new4(fname);
8325 fd = rb_sysopen(fname, oflags, perm);
8326 return INT2NUM(fd);
8327}
8328
8329/*
8330 * call-seq:
8331 * open(path, mode = 'r', perm = 0666, **opts) -> io or nil
8332 * open(path, mode = 'r', perm = 0666, **opts) {|io| ... } -> obj
8333 *
8334 * Creates an IO object connected to the given file.
8335 *
8336 * With no block given, file stream is returned:
8337 *
8338 * open('t.txt') # => #<File:t.txt>
8339 *
8340 * With a block given, calls the block with the open file stream,
8341 * then closes the stream:
8342 *
8343 * open('t.txt') {|f| p f } # => #<File:t.txt (closed)>
8344 *
8345 * Output:
8346 *
8347 * #<File:t.txt>
8348 *
8349 * See File.open for details.
8350 *
8351 */
8352
8353static VALUE
8354rb_f_open(int argc, VALUE *argv, VALUE _)
8355{
8356 ID to_open = 0;
8357 int redirect = FALSE;
8358
8359 if (argc >= 1) {
8360 CONST_ID(to_open, "to_open");
8361 if (rb_respond_to(argv[0], to_open)) {
8362 redirect = TRUE;
8363 }
8364 else {
8365 VALUE tmp = argv[0];
8366 FilePathValue(tmp);
8367 if (NIL_P(tmp)) {
8368 redirect = TRUE;
8369 }
8370 else {
8371 argv[0] = tmp;
8372 }
8373 }
8374 }
8375 if (redirect) {
8376 VALUE io = rb_funcallv_kw(argv[0], to_open, argc-1, argv+1, RB_PASS_CALLED_KEYWORDS);
8377
8378 if (rb_block_given_p()) {
8379 return rb_ensure(rb_yield, io, io_close, io);
8380 }
8381 return io;
8382 }
8383 return rb_io_s_open(argc, argv, rb_cFile);
8384}
8385
8386static VALUE
8387rb_io_open_generic(VALUE klass, VALUE filename, int oflags, enum rb_io_mode fmode,
8388 const struct rb_io_encoding *convconfig, mode_t perm)
8389{
8390 return rb_file_open_generic(io_alloc(klass), filename,
8391 oflags, fmode, convconfig, perm);
8392}
8393
8394static VALUE
8395rb_io_open(VALUE io, VALUE filename, VALUE vmode, VALUE vperm, VALUE opt)
8396{
8397 int oflags;
8398 enum rb_io_mode fmode;
8399 struct rb_io_encoding convconfig;
8400 mode_t perm;
8401
8402 rb_io_extract_modeenc(&vmode, &vperm, opt, &oflags, &fmode, &convconfig);
8403 perm = NIL_P(vperm) ? 0666 : NUM2MODET(vperm);
8404 return rb_io_open_generic(io, filename, oflags, fmode, &convconfig, perm);
8405}
8406
8407static VALUE
8408io_reopen(VALUE io, VALUE nfile)
8409{
8410 rb_io_t *fptr, *orig;
8411 int fd, fd2;
8412 rb_off_t pos = 0;
8413
8414 nfile = rb_io_get_io(nfile);
8415 GetOpenFile(io, fptr);
8416 GetOpenFile(nfile, orig);
8417
8418 if (fptr == orig) return io;
8419 if (RUBY_IO_EXTERNAL_P(fptr)) {
8420 if ((fptr->stdio_file == stdin && !(orig->mode & FMODE_READABLE)) ||
8421 (fptr->stdio_file == stdout && !(orig->mode & FMODE_WRITABLE)) ||
8422 (fptr->stdio_file == stderr && !(orig->mode & FMODE_WRITABLE))) {
8423 rb_raise(rb_eArgError,
8424 "%s can't change access mode from \"%s\" to \"%s\"",
8425 PREP_STDIO_NAME(fptr), rb_io_fmode_modestr(fptr->mode),
8426 rb_io_fmode_modestr(orig->mode));
8427 }
8428 }
8429 if (fptr->mode & FMODE_WRITABLE) {
8430 if (io_fflush(fptr) < 0)
8431 rb_sys_fail_on_write(fptr);
8432 }
8433 else {
8434 flush_before_seek(fptr, true);
8435 }
8436 if (orig->mode & FMODE_READABLE) {
8437 pos = io_tell(orig);
8438 }
8439 if (orig->mode & FMODE_WRITABLE) {
8440 if (io_fflush(orig) < 0)
8441 rb_sys_fail_on_write(fptr);
8442 }
8443
8444 /* copy rb_io_t structure */
8445 fptr->mode = orig->mode | (fptr->mode & FMODE_EXTERNAL);
8446 fptr->encs = orig->encs;
8447 fptr->pid = orig->pid;
8448 fptr->lineno = orig->lineno;
8449 if (RTEST(orig->pathv)) fptr->pathv = orig->pathv;
8450 else if (!RUBY_IO_EXTERNAL_P(fptr)) fptr->pathv = Qnil;
8451 fptr_copy_finalizer(fptr, orig);
8452
8453 fd = fptr->fd;
8454 fd2 = orig->fd;
8455 if (fd != fd2) {
8456 // Interrupt all usage of the old file descriptor:
8457 rb_thread_io_close_interrupt(fptr);
8458 rb_thread_io_close_wait(fptr);
8459
8460 if (RUBY_IO_EXTERNAL_P(fptr) || fd <= 2 || !fptr->stdio_file) {
8461 /* need to keep FILE objects of stdin, stdout and stderr */
8462 if (rb_cloexec_dup2(fd2, fd) < 0)
8463 rb_sys_fail_path(orig->pathv);
8464 rb_update_max_fd(fd);
8465 }
8466 else {
8467 fclose(fptr->stdio_file);
8468 fptr->stdio_file = 0;
8469 fptr->fd = -1;
8470 if (rb_cloexec_dup2(fd2, fd) < 0)
8471 rb_sys_fail_path(orig->pathv);
8472 rb_update_max_fd(fd);
8473 fptr->fd = fd;
8474 }
8475
8476 if ((orig->mode & FMODE_READABLE) && pos >= 0) {
8477 if (io_seek(fptr, pos, SEEK_SET) < 0 && errno) {
8478 rb_sys_fail_path(fptr->pathv);
8479 }
8480 if (io_seek(orig, pos, SEEK_SET) < 0 && errno) {
8481 rb_sys_fail_path(orig->pathv);
8482 }
8483 }
8484 }
8485
8486 if (fptr->mode & FMODE_BINMODE) {
8487 rb_io_binmode(io);
8488 }
8489
8490 RBASIC_SET_CLASS(io, rb_obj_class(nfile));
8491 return io;
8492}
8493
8494#ifdef _WIN32
8495int rb_freopen(VALUE fname, const char *mode, FILE *fp);
8496#else
8497static int
8498rb_freopen(VALUE fname, const char *mode, FILE *fp)
8499{
8500 if (!freopen(RSTRING_PTR(fname), mode, fp)) {
8501 RB_GC_GUARD(fname);
8502 return errno;
8503 }
8504 return 0;
8505}
8506#endif
8507
8508/*
8509 * call-seq:
8510 * reopen(other_io) -> self
8511 * reopen(path, mode = 'r', **opts) -> self
8512 *
8513 * Reassociates the stream with another stream,
8514 * which may be of a different class.
8515 * This method may be used to redirect an existing stream
8516 * to a new destination.
8517 *
8518 * With argument +other_io+ given, reassociates with that stream:
8519 *
8520 * # Redirect $stdin from a file.
8521 * f = File.open('t.txt')
8522 * $stdin.reopen(f)
8523 * f.close
8524 *
8525 * # Redirect $stdout to a file.
8526 * f = File.open('t.tmp', 'w')
8527 * $stdout.reopen(f)
8528 * f.close
8529 *
8530 * With argument +path+ given, reassociates with a new stream to that file path:
8531 *
8532 * $stdin.reopen('t.txt')
8533 * $stdout.reopen('t.tmp', 'w')
8534 *
8535 * Optional keyword arguments +opts+ specify:
8536 *
8537 * - {Open Options}[rdoc-ref:IO@Open+Options].
8538 * - {Encoding options}[rdoc-ref:encodings.rdoc@Encoding+Options].
8539 *
8540 */
8541
8542static VALUE
8543rb_io_reopen(int argc, VALUE *argv, VALUE file)
8544{
8545 VALUE fname, nmode, opt;
8546 int oflags;
8547 rb_io_t *fptr;
8548
8549 if (rb_scan_args(argc, argv, "11:", &fname, &nmode, &opt) == 1) {
8550 VALUE tmp = rb_io_check_io(fname);
8551 if (!NIL_P(tmp)) {
8552 return io_reopen(file, tmp);
8553 }
8554 }
8555
8556 FilePathValue(fname);
8557 rb_io_taint_check(file);
8558 fptr = RFILE(file)->fptr;
8559 if (!fptr) {
8560 fptr = RFILE(file)->fptr = ZALLOC(rb_io_t);
8561 }
8562
8563 if (!NIL_P(nmode) || !NIL_P(opt)) {
8564 enum rb_io_mode fmode;
8565 struct rb_io_encoding convconfig;
8566
8567 rb_io_extract_modeenc(&nmode, 0, opt, &oflags, &fmode, &convconfig);
8568 if (RUBY_IO_EXTERNAL_P(fptr) &&
8569 ((fptr->mode & FMODE_READWRITE) & (fmode & FMODE_READWRITE)) !=
8570 (fptr->mode & FMODE_READWRITE)) {
8571 rb_raise(rb_eArgError,
8572 "%s can't change access mode from \"%s\" to \"%s\"",
8573 PREP_STDIO_NAME(fptr), rb_io_fmode_modestr(fptr->mode),
8574 rb_io_fmode_modestr(fmode));
8575 }
8576 fptr->mode = fmode;
8577 fptr->encs = convconfig;
8578 }
8579 else {
8580 oflags = rb_io_fmode_oflags(fptr->mode);
8581 }
8582
8583 fptr->pathv = fname;
8584 if (fptr->fd < 0) {
8585 fptr->fd = rb_sysopen(fptr->pathv, oflags, 0666);
8586 fptr->stdio_file = 0;
8587 return file;
8588 }
8589
8590 if (fptr->mode & FMODE_WRITABLE) {
8591 if (io_fflush(fptr) < 0)
8592 rb_sys_fail_on_write(fptr);
8593 }
8594 fptr->rbuf.off = fptr->rbuf.len = 0;
8595
8596 if (fptr->stdio_file) {
8597 int e = rb_freopen(rb_str_encode_ospath(fptr->pathv),
8598 rb_io_oflags_modestr(oflags),
8599 fptr->stdio_file);
8600 if (e) rb_syserr_fail_path(e, fptr->pathv);
8601 fptr->fd = fileno(fptr->stdio_file);
8602 rb_fd_fix_cloexec(fptr->fd);
8603#ifdef USE_SETVBUF
8604 if (setvbuf(fptr->stdio_file, NULL, _IOFBF, 0) != 0)
8605 rb_warn("setvbuf() can't be honoured for %"PRIsVALUE, fptr->pathv);
8606#endif
8607 if (fptr->stdio_file == stderr) {
8608 if (setvbuf(fptr->stdio_file, NULL, _IONBF, BUFSIZ) != 0)
8609 rb_warn("setvbuf() can't be honoured for %"PRIsVALUE, fptr->pathv);
8610 }
8611 else if (fptr->stdio_file == stdout && isatty(fptr->fd)) {
8612 if (setvbuf(fptr->stdio_file, NULL, _IOLBF, BUFSIZ) != 0)
8613 rb_warn("setvbuf() can't be honoured for %"PRIsVALUE, fptr->pathv);
8614 }
8615 }
8616 else {
8617 int tmpfd = rb_sysopen(fptr->pathv, oflags, 0666);
8618 int err = 0;
8619 if (rb_cloexec_dup2(tmpfd, fptr->fd) < 0)
8620 err = errno;
8621 (void)close(tmpfd);
8622 if (err) {
8623 rb_syserr_fail_path(err, fptr->pathv);
8624 }
8625 }
8626
8627 return file;
8628}
8629
8630/* :nodoc: */
8631static VALUE
8632rb_io_init_copy(VALUE dest, VALUE io)
8633{
8634 rb_io_t *fptr, *orig;
8635 int fd;
8636 VALUE write_io;
8637 rb_off_t pos;
8638
8639 io = rb_io_get_io(io);
8640 if (!OBJ_INIT_COPY(dest, io)) return dest;
8641 GetOpenFile(io, orig);
8642 MakeOpenFile(dest, fptr);
8643
8644 rb_io_flush(io);
8645
8646 /* copy rb_io_t structure */
8647 fptr->mode = orig->mode & ~FMODE_EXTERNAL;
8648 fptr->encs = orig->encs;
8649 fptr->pid = orig->pid;
8650 fptr->lineno = orig->lineno;
8651 fptr->timeout = orig->timeout;
8652
8653 ccan_list_head_init(&fptr->blocking_operations);
8654 fptr->closing_ec = NULL;
8655 fptr->wakeup_mutex = Qnil;
8656 fptr->fork_generation = GET_VM()->fork_gen;
8657
8658 if (!NIL_P(orig->pathv)) fptr->pathv = orig->pathv;
8659 fptr_copy_finalizer(fptr, orig);
8660
8661 fd = ruby_dup(orig->fd);
8662 fptr->fd = fd;
8663 pos = io_tell(orig);
8664 if (0 <= pos)
8665 io_seek(fptr, pos, SEEK_SET);
8666 if (fptr->mode & FMODE_BINMODE) {
8667 rb_io_binmode(dest);
8668 }
8669
8670 write_io = GetWriteIO(io);
8671 if (io != write_io) {
8672 write_io = rb_obj_dup(write_io);
8673 fptr->tied_io_for_writing = write_io;
8674 rb_ivar_set(dest, rb_intern("@tied_io_for_writing"), write_io);
8675 }
8676
8677 return dest;
8678}
8679
8680/*
8681 * call-seq:
8682 * printf(format_string, *objects) -> nil
8683 *
8684 * Formats and writes +objects+ to the stream.
8685 *
8686 * For details on +format_string+, see
8687 * {Format Specifications}[rdoc-ref:language/format_specifications.rdoc].
8688 *
8689 */
8690
8691VALUE
8692rb_io_printf(int argc, const VALUE *argv, VALUE out)
8693{
8694 rb_io_write(out, rb_f_sprintf(argc, argv));
8695 return Qnil;
8696}
8697
8698/*
8699 * call-seq:
8700 * printf(format_string, *objects) -> nil
8701 * printf(io, format_string, *objects) -> nil
8702 *
8703 * Equivalent to:
8704 *
8705 * io.write(sprintf(format_string, *objects))
8706 *
8707 * For details on +format_string+, see
8708 * {Format Specifications}[rdoc-ref:language/format_specifications.rdoc].
8709 *
8710 * With the single argument +format_string+, formats +objects+ into the string,
8711 * then writes the formatted string to $stdout:
8712 *
8713 * printf('%4.4d %10s %2.2f', 24, 24, 24.0)
8714 *
8715 * Output (on $stdout):
8716 *
8717 * 0024 24 24.00#
8718 *
8719 * With arguments +io+ and +format_string+, formats +objects+ into the string,
8720 * then writes the formatted string to +io+:
8721 *
8722 * printf($stderr, '%4.4d %10s %2.2f', 24, 24, 24.0)
8723 *
8724 * Output (on $stderr):
8725 *
8726 * 0024 24 24.00# => nil
8727 *
8728 * With no arguments, does nothing.
8729 *
8730 */
8731
8732static VALUE
8733rb_f_printf(int argc, VALUE *argv, VALUE _)
8734{
8735 VALUE out;
8736
8737 if (argc == 0) return Qnil;
8738 if (RB_TYPE_P(argv[0], T_STRING)) {
8739 out = rb_ractor_stdout();
8740 }
8741 else {
8742 out = argv[0];
8743 argv++;
8744 argc--;
8745 }
8746 rb_io_write(out, rb_f_sprintf(argc, argv));
8747
8748 return Qnil;
8749}
8750
8751extern void rb_deprecated_str_setter(VALUE val, ID id, VALUE *var);
8752
8753static void
8754deprecated_rs_setter(VALUE val, ID id, VALUE *var)
8755{
8756 rb_deprecated_str_setter(val, id, &val);
8757 if (!NIL_P(val)) {
8758 if (rb_str_equal(val, rb_default_rs)) {
8759 val = rb_default_rs;
8760 }
8761 else {
8762 val = rb_str_frozen_bare_string(val);
8763 }
8764 }
8765 *var = val;
8766}
8767
8768/*
8769 * call-seq:
8770 * print(*objects) -> nil
8771 *
8772 * Writes the given objects to the stream; returns +nil+.
8773 * Appends the output record separator <tt>$OUTPUT_RECORD_SEPARATOR</tt>
8774 * (<tt>$\</tt>), if it is not +nil+.
8775 * See {Line IO}[rdoc-ref:IO@Line+IO].
8776 *
8777 * With argument +objects+ given, for each object:
8778 *
8779 * - Converts via its method +to_s+ if not a string.
8780 * - Writes to the stream.
8781 * - If not the last object, writes the output field separator
8782 * <tt>$OUTPUT_FIELD_SEPARATOR</tt> (<tt>$,</tt>) if it is not +nil+.
8783 *
8784 * With default separators:
8785 *
8786 * f = File.open('t.tmp', 'w+')
8787 * objects = [0, 0.0, Rational(0, 1), Complex(0, 0), :zero, 'zero']
8788 * p $OUTPUT_RECORD_SEPARATOR
8789 * p $OUTPUT_FIELD_SEPARATOR
8790 * f.print(*objects)
8791 * f.rewind
8792 * p f.read
8793 * f.close
8794 *
8795 * Output:
8796 *
8797 * nil
8798 * nil
8799 * "00.00/10+0izerozero"
8800 *
8801 * With specified separators:
8802 *
8803 * $\ = "\n"
8804 * $, = ','
8805 * f.rewind
8806 * f.print(*objects)
8807 * f.rewind
8808 * p f.read
8809 *
8810 * Output:
8811 *
8812 * "0,0.0,0/1,0+0i,zero,zero\n"
8813 *
8814 * With no argument given, writes the content of <tt>$_</tt>
8815 * (which is usually the most recent user input):
8816 *
8817 * f = File.open('t.tmp', 'w+')
8818 * gets # Sets $_ to the most recent user input.
8819 * f.print
8820 * f.close
8821 *
8822 */
8823
8824VALUE
8825rb_io_print(int argc, const VALUE *argv, VALUE out)
8826{
8827 int i;
8828 VALUE line;
8829
8830 /* if no argument given, print `$_' */
8831 if (argc == 0) {
8832 argc = 1;
8833 line = rb_lastline_get();
8834 argv = &line;
8835 }
8836 if (argc > 1 && !NIL_P(rb_output_fs)) {
8837 rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "$, is set to non-nil value");
8838 }
8839 for (i=0; i<argc; i++) {
8840 if (!NIL_P(rb_output_fs) && i>0) {
8841 rb_io_write(out, rb_output_fs);
8842 }
8843 rb_io_write(out, argv[i]);
8844 }
8845 if (argc > 0 && !NIL_P(rb_output_rs)) {
8846 rb_io_write(out, rb_output_rs);
8847 }
8848
8849 return Qnil;
8850}
8851
8852/*
8853 * call-seq:
8854 * print(*objects) -> nil
8855 *
8856 * Equivalent to <tt>$stdout.print(*objects)</tt>,
8857 * this method is the straightforward way to write to <tt>$stdout</tt>.
8858 *
8859 * Writes the given objects to <tt>$stdout</tt>; returns +nil+.
8860 * Appends the output record separator <tt>$OUTPUT_RECORD_SEPARATOR</tt>
8861 * <tt>$\</tt>), if it is not +nil+.
8862 *
8863 * With argument +objects+ given, for each object:
8864 *
8865 * - Converts via its method +to_s+ if not a string.
8866 * - Writes to <tt>stdout</tt>.
8867 * - If not the last object, writes the output field separator
8868 * <tt>$OUTPUT_FIELD_SEPARATOR</tt> (<tt>$,</tt> if it is not +nil+.
8869 *
8870 * With default separators:
8871 *
8872 * objects = [0, 0.0, Rational(0, 1), Complex(0, 0), :zero, 'zero']
8873 * $OUTPUT_RECORD_SEPARATOR
8874 * $OUTPUT_FIELD_SEPARATOR
8875 * print(*objects)
8876 *
8877 * Output:
8878 *
8879 * nil
8880 * nil
8881 * 00.00/10+0izerozero
8882 *
8883 * With specified separators:
8884 *
8885 * $OUTPUT_RECORD_SEPARATOR = "\n"
8886 * $OUTPUT_FIELD_SEPARATOR = ','
8887 * print(*objects)
8888 *
8889 * Output:
8890 *
8891 * 0,0.0,0/1,0+0i,zero,zero
8892 *
8893 * With no argument given, writes the content of <tt>$_</tt>
8894 * (which is usually the most recent user input):
8895 *
8896 * gets # Sets $_ to the most recent user input.
8897 * print # Prints $_.
8898 *
8899 */
8900
8901static VALUE
8902rb_f_print(int argc, const VALUE *argv, VALUE _)
8903{
8904 rb_io_print(argc, argv, rb_ractor_stdout());
8905 return Qnil;
8906}
8907
8908/*
8909 * call-seq:
8910 * putc(object) -> object
8911 *
8912 * Writes a character to the stream.
8913 * See {Character IO}[rdoc-ref:IO@Character+IO].
8914 *
8915 * If +object+ is numeric, converts to integer if necessary,
8916 * then writes the character whose code is the
8917 * least significant byte;
8918 * if +object+ is a string, writes the first character:
8919 *
8920 * $stdout.putc "A"
8921 * $stdout.putc 65
8922 *
8923 * Output:
8924 *
8925 * AA
8926 *
8927 */
8928
8929static VALUE
8930rb_io_putc(VALUE io, VALUE ch)
8931{
8932 VALUE str;
8933 if (RB_TYPE_P(ch, T_STRING)) {
8934 str = rb_str_substr(ch, 0, 1);
8935 }
8936 else {
8937 char c = NUM2CHR(ch);
8938 str = rb_str_new(&c, 1);
8939 }
8940 rb_io_write(io, str);
8941 return ch;
8942}
8943
8944#define forward(obj, id, argc, argv) \
8945 rb_funcallv_kw(obj, id, argc, argv, RB_PASS_CALLED_KEYWORDS)
8946#define forward_public(obj, id, argc, argv) \
8947 rb_funcallv_public_kw(obj, id, argc, argv, RB_PASS_CALLED_KEYWORDS)
8948#define forward_current(id, argc, argv) \
8949 forward_public(ARGF.current_file, id, argc, argv)
8950
8951/*
8952 * call-seq:
8953 * putc(int) -> int
8954 *
8955 * Equivalent to:
8956 *
8957 * $stdout.putc(int)
8958 *
8959 * See IO#putc for important information regarding multi-byte characters.
8960 *
8961 */
8962
8963static VALUE
8964rb_f_putc(VALUE recv, VALUE ch)
8965{
8966 VALUE r_stdout = rb_ractor_stdout();
8967 if (recv == r_stdout) {
8968 return rb_io_putc(recv, ch);
8969 }
8970 return forward(r_stdout, rb_intern("putc"), 1, &ch);
8971}
8972
8973
8974int
8975rb_str_end_with_asciichar(VALUE str, int c)
8976{
8977 long len = RSTRING_LEN(str);
8978 const char *ptr = RSTRING_PTR(str);
8979 rb_encoding *enc = rb_enc_from_index(ENCODING_GET(str));
8980 int n;
8981
8982 if (len == 0) return 0;
8983 if ((n = rb_enc_mbminlen(enc)) == 1) {
8984 return ptr[len - 1] == c;
8985 }
8986 return rb_enc_ascget(ptr + ((len - 1) / n) * n, ptr + len, &n, enc) == c;
8987}
8988
8989static VALUE
8990io_puts_ary(VALUE ary, VALUE out, int recur)
8991{
8992 VALUE tmp;
8993 long i;
8994
8995 if (recur) {
8996 tmp = rb_str_new2("[...]");
8997 rb_io_puts(1, &tmp, out);
8998 return Qtrue;
8999 }
9000 ary = rb_check_array_type(ary);
9001 if (NIL_P(ary)) return Qfalse;
9002 for (i=0; i<RARRAY_LEN(ary); i++) {
9003 tmp = RARRAY_AREF(ary, i);
9004 rb_io_puts(1, &tmp, out);
9005 }
9006 return Qtrue;
9007}
9008
9009/*
9010 * call-seq:
9011 * puts(*objects) -> nil
9012 *
9013 * Writes the given +objects+ to the stream, which must be open for writing;
9014 * returns +nil+.\
9015 * Writes a newline after each that does not already end with a newline sequence.
9016 * If called without arguments, writes a newline.
9017 * See {Line IO}[rdoc-ref:IO@Line+IO].
9018 *
9019 * Note that each added newline is the character <tt>"\n"<//tt>,
9020 * not the output record separator (<tt>$\</tt>).
9021 *
9022 * Treatment for each object:
9023 *
9024 * - String: writes the string.
9025 * - Neither string nor array: writes <tt>object.to_s</tt>.
9026 * - Array: writes each element of the array; arrays may be nested.
9027 *
9028 * To keep these examples brief, we define this helper method:
9029 *
9030 * def show(*objects)
9031 * # Puts objects to file.
9032 * f = File.new('t.tmp', 'w+')
9033 * f.puts(objects)
9034 * # Return file content.
9035 * f.rewind
9036 * p f.read
9037 * f.close
9038 * end
9039 *
9040 * # Strings without newlines.
9041 * show('foo', 'bar', 'baz') # => "foo\nbar\nbaz\n"
9042 * # Strings, some with newlines.
9043 * show("foo\n", 'bar', "baz\n") # => "foo\nbar\nbaz\n"
9044 *
9045 * # Neither strings nor arrays:
9046 * show(0, 0.0, Rational(0, 1), Complex(9, 0), :zero)
9047 * # => "0\n0.0\n0/1\n9+0i\nzero\n"
9048 *
9049 * # Array of strings.
9050 * show(['foo', "bar\n", 'baz']) # => "foo\nbar\nbaz\n"
9051 * # Nested arrays.
9052 * show([[[0, 1], 2, 3], 4, 5]) # => "0\n1\n2\n3\n4\n5\n"
9053 *
9054 */
9055
9056VALUE
9057rb_io_puts(int argc, const VALUE *argv, VALUE out)
9058{
9059 VALUE line, args[2];
9060
9061 /* if no argument given, print newline. */
9062 if (argc == 0) {
9063 rb_io_write(out, rb_default_rs);
9064 return Qnil;
9065 }
9066 for (int i = 0; i < argc; i++) {
9067 // Convert the argument to a string:
9068 if (RB_TYPE_P(argv[i], T_STRING)) {
9069 line = argv[i];
9070 }
9071 else if (rb_exec_recursive(io_puts_ary, argv[i], out)) {
9072 continue;
9073 }
9074 else {
9075 line = rb_obj_as_string(argv[i]);
9076 }
9077
9078 // Write the line:
9079 int n = 0;
9080 if (RSTRING_LEN(line) == 0) {
9081 args[n++] = rb_default_rs;
9082 }
9083 else {
9084 args[n++] = line;
9085 if (!rb_str_end_with_asciichar(line, '\n')) {
9086 args[n++] = rb_default_rs;
9087 }
9088 }
9089
9090 rb_io_writev(out, n, args);
9091 }
9092
9093 return Qnil;
9094}
9095
9096/*
9097 * call-seq:
9098 * puts(*objects) -> nil
9099 *
9100 * Equivalent to
9101 *
9102 * $stdout.puts(objects)
9103 */
9104
9105static VALUE
9106rb_f_puts(int argc, VALUE *argv, VALUE recv)
9107{
9108 VALUE r_stdout = rb_ractor_stdout();
9109 if (recv == r_stdout) {
9110 return rb_io_puts(argc, argv, recv);
9111 }
9112 return forward(r_stdout, rb_intern("puts"), argc, argv);
9113}
9114
9115static VALUE
9116rb_p_write(VALUE str)
9117{
9118 VALUE args[2];
9119 args[0] = str;
9120 args[1] = rb_default_rs;
9121 VALUE r_stdout = rb_ractor_stdout();
9122 if (RB_TYPE_P(r_stdout, T_FILE) &&
9123 rb_method_basic_definition_p(CLASS_OF(r_stdout), id_write)) {
9124 io_writev(2, args, r_stdout);
9125 }
9126 else {
9127 rb_io_writev(r_stdout, 2, args);
9128 }
9129 return Qnil;
9130}
9131
9132void
9133rb_p(VALUE obj) /* for debug print within C code */
9134{
9135 rb_p_write(rb_obj_as_string(rb_inspect(obj)));
9136}
9137
9138static VALUE
9139rb_p_result(int argc, const VALUE *argv)
9140{
9141 VALUE ret = Qnil;
9142
9143 if (argc == 1) {
9144 ret = argv[0];
9145 }
9146 else if (argc > 1) {
9147 ret = rb_ary_new4(argc, argv);
9148 }
9149 VALUE r_stdout = rb_ractor_stdout();
9150 if (RB_TYPE_P(r_stdout, T_FILE)) {
9151 rb_uninterruptible(rb_io_flush, r_stdout);
9152 }
9153 return ret;
9154}
9155
9156/*
9157 * call-seq:
9158 * p(object) -> obj
9159 * p(*objects) -> array of objects
9160 * p -> nil
9161 *
9162 * For each object +obj+, executes:
9163 *
9164 * $stdout.write(obj.inspect, "\n")
9165 *
9166 * With one object given, returns the object;
9167 * with multiple objects given, returns an array containing the objects;
9168 * with no object given, returns +nil+.
9169 *
9170 * Examples:
9171 *
9172 * r = Range.new(0, 4)
9173 * p r # => 0..4
9174 * p [r, r, r] # => [0..4, 0..4, 0..4]
9175 * p # => nil
9176 *
9177 * Output:
9178 *
9179 * 0..4
9180 * [0..4, 0..4, 0..4]
9181 *
9182 * Kernel#p is designed for debugging purposes.
9183 * Ruby implementations may define Kernel#p to be uninterruptible
9184 * in whole or in part.
9185 * On CRuby, Kernel#p's writing of data is uninterruptible.
9186 */
9187
9188static VALUE
9189rb_f_p(int argc, VALUE *argv, VALUE self)
9190{
9191 int i;
9192 for (i=0; i<argc; i++) {
9193 VALUE inspected = rb_obj_as_string(rb_inspect(argv[i]));
9194 rb_uninterruptible(rb_p_write, inspected);
9195 }
9196 return rb_p_result(argc, argv);
9197}
9198
9199/*
9200 * call-seq:
9201 * display(port = $>) -> nil
9202 *
9203 * Writes +self+ on the given port:
9204 *
9205 * 1.display
9206 * "cat".display
9207 * [ 4, 5, 6 ].display
9208 * puts
9209 *
9210 * Output:
9211 *
9212 * 1cat[4, 5, 6]
9213 *
9214 */
9215
9216static VALUE
9217rb_obj_display(int argc, VALUE *argv, VALUE self)
9218{
9219 VALUE out;
9220
9221 out = (!rb_check_arity(argc, 0, 1) ? rb_ractor_stdout() : argv[0]);
9222 rb_io_write(out, self);
9223
9224 return Qnil;
9225}
9226
9227static int
9228rb_stderr_to_original_p(VALUE err)
9229{
9230 return (err == orig_stderr || RFILE(orig_stderr)->fptr->fd < 0);
9231}
9232
9233void
9234rb_write_error2(const char *mesg, long len)
9235{
9236 VALUE out = rb_ractor_stderr();
9237 if (rb_stderr_to_original_p(out)) {
9238#ifdef _WIN32
9239 if (isatty(fileno(stderr))) {
9240 if (rb_w32_write_console(rb_str_new(mesg, len), fileno(stderr)) > 0) return;
9241 }
9242#endif
9243 if (fwrite(mesg, sizeof(char), (size_t)len, stderr) < (size_t)len) {
9244 /* failed to write to stderr, what can we do? */
9245 return;
9246 }
9247 }
9248 else {
9249 rb_io_write(out, rb_str_new(mesg, len));
9250 }
9251}
9252
9253void
9254rb_write_error(const char *mesg)
9255{
9256 rb_write_error2(mesg, strlen(mesg));
9257}
9258
9259void
9260rb_write_error_str(VALUE mesg)
9261{
9262 VALUE out = rb_ractor_stderr();
9263 /* a stopgap measure for the time being */
9264 if (rb_stderr_to_original_p(out)) {
9265 size_t len = (size_t)RSTRING_LEN(mesg);
9266#ifdef _WIN32
9267 if (isatty(fileno(stderr))) {
9268 if (rb_w32_write_console(mesg, fileno(stderr)) > 0) return;
9269 }
9270#endif
9271 if (fwrite(RSTRING_PTR(mesg), sizeof(char), len, stderr) < len) {
9272 RB_GC_GUARD(mesg);
9273 return;
9274 }
9275 }
9276 else {
9277 /* may unlock GVL, and */
9278 rb_io_write(out, mesg);
9279 }
9280}
9281
9282int
9283rb_stderr_tty_p(void)
9284{
9285 if (rb_stderr_to_original_p(rb_ractor_stderr()))
9286 return isatty(fileno(stderr));
9287 return 0;
9288}
9289
9290static void
9291must_respond_to(ID mid, VALUE val, ID id)
9292{
9293 if (!rb_respond_to(val, mid)) {
9294 rb_raise(rb_eTypeError, "%"PRIsVALUE" must have %"PRIsVALUE" method, %"PRIsVALUE" given",
9295 rb_id2str(id), rb_id2str(mid),
9296 rb_obj_class(val));
9297 }
9298}
9299
9300static void
9301stdin_setter(VALUE val, ID id, VALUE *ptr)
9302{
9304}
9305
9306static VALUE
9307stdin_getter(ID id, VALUE *ptr)
9308{
9309 return rb_ractor_stdin();
9310}
9311
9312static void
9313stdout_setter(VALUE val, ID id, VALUE *ptr)
9314{
9315 must_respond_to(id_write, val, id);
9317}
9318
9319static VALUE
9320stdout_getter(ID id, VALUE *ptr)
9321{
9322 return rb_ractor_stdout();
9323}
9324
9325static void
9326stderr_setter(VALUE val, ID id, VALUE *ptr)
9327{
9328 must_respond_to(id_write, val, id);
9330}
9331
9332static VALUE
9333stderr_getter(ID id, VALUE *ptr)
9334{
9335 return rb_ractor_stderr();
9336}
9337
9338static VALUE
9339allocate_and_open_new_file(VALUE klass)
9340{
9341 VALUE self = io_alloc(klass);
9342 rb_io_make_open_file(self);
9343 return self;
9344}
9345
9346VALUE
9347rb_io_open_descriptor(VALUE klass, int descriptor, int mode, VALUE path, VALUE timeout, struct rb_io_encoding *encoding)
9348{
9349 int state;
9350 VALUE self = rb_protect(allocate_and_open_new_file, klass, &state);
9351 if (state) {
9352 /* if we raised an exception allocating an IO object, but the caller
9353 intended to transfer ownership of this FD to us, close the fd before
9354 raising the exception. Otherwise, we would leak a FD - the caller
9355 expects GC to close the file, but we never got around to assigning
9356 it to a rb_io. */
9357 if (!(mode & FMODE_EXTERNAL)) {
9358 maygvl_close(descriptor, 0);
9359 }
9360 rb_jump_tag(state);
9361 }
9362
9363
9364 rb_io_t *io = RFILE(self)->fptr;
9365 io->self = self;
9366 io->fd = descriptor;
9367 io->mode = mode;
9368
9369 /* At this point, Ruby fully owns the descriptor, and will close it when
9370 the IO gets GC'd (unless FMODE_EXTERNAL was set), no matter what happens
9371 in the rest of this method. */
9372
9373 if (NIL_P(path)) {
9374 io->pathv = Qnil;
9375 }
9376 else {
9377 StringValue(path);
9378 io->pathv = rb_str_new_frozen(path);
9379 }
9380
9381 io->timeout = timeout;
9382
9383 ccan_list_head_init(&io->blocking_operations);
9384 io->closing_ec = NULL;
9385 io->wakeup_mutex = Qnil;
9386 io->fork_generation = GET_VM()->fork_gen;
9387
9388 if (encoding) {
9389 io->encs = *encoding;
9390 }
9391
9392 rb_update_max_fd(descriptor);
9393
9394 return self;
9395}
9396
9397static VALUE
9398prep_io(int fd, enum rb_io_mode fmode, VALUE klass, const char *path)
9399{
9400 VALUE path_value = Qnil;
9401 rb_encoding *e;
9402 struct rb_io_encoding convconfig;
9403
9404 if (path) {
9405 path_value = rb_obj_freeze(rb_str_new_cstr(path));
9406 }
9407
9408 e = (fmode & FMODE_BINMODE) ? rb_ascii8bit_encoding() : NULL;
9409 rb_io_ext_int_to_encs(e, NULL, &convconfig.enc, &convconfig.enc2, fmode);
9410 convconfig.ecflags = (fmode & FMODE_READABLE) ?
9413#ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE
9414 convconfig.ecflags |= (fmode & FMODE_WRITABLE) ?
9415 MODE_BTMODE(TEXTMODE_NEWLINE_DECORATOR_ON_WRITE,
9416 0, TEXTMODE_NEWLINE_DECORATOR_ON_WRITE) : 0;
9417#endif
9418 SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(convconfig.enc2, convconfig.ecflags);
9419 convconfig.ecopts = Qnil;
9420
9421 VALUE self = rb_io_open_descriptor(klass, fd, fmode, path_value, Qnil, &convconfig);
9422 rb_io_t*io = RFILE(self)->fptr;
9423
9424 if (!io_check_tty(io)) {
9425#ifdef __CYGWIN__
9426 io->mode |= FMODE_BINMODE;
9427 setmode(fd, O_BINARY);
9428#endif
9429 }
9430
9431 return self;
9432}
9433
9434VALUE
9435rb_io_fdopen(int fd, int oflags, const char *path)
9436{
9437 VALUE klass = rb_cIO;
9438
9439 if (path && strcmp(path, "-")) klass = rb_cFile;
9440 return prep_io(fd, rb_io_oflags_fmode(oflags), klass, path);
9441}
9442
9443static VALUE
9444prep_stdio(FILE *f, enum rb_io_mode fmode, VALUE klass, const char *path)
9445{
9446 rb_io_t *fptr;
9447 VALUE io = prep_io(fileno(f), fmode|FMODE_EXTERNAL|DEFAULT_TEXTMODE, klass, path);
9448
9449 GetOpenFile(io, fptr);
9451#ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE
9452 fptr->encs.ecflags |= TEXTMODE_NEWLINE_DECORATOR_ON_WRITE;
9453 if (fmode & FMODE_READABLE) {
9455 }
9456#endif
9457 fptr->stdio_file = f;
9458
9459 return io;
9460}
9461
9462VALUE
9463rb_io_prep_stdin(void)
9464{
9465 return prep_stdio(stdin, FMODE_READABLE, rb_cIO, "<STDIN>");
9466}
9467
9468VALUE
9469rb_io_prep_stdout(void)
9470{
9471 return prep_stdio(stdout, FMODE_WRITABLE|FMODE_SIGNAL_ON_EPIPE, rb_cIO, "<STDOUT>");
9472}
9473
9474VALUE
9475rb_io_prep_stderr(void)
9476{
9477 return prep_stdio(stderr, FMODE_WRITABLE|FMODE_SYNC, rb_cIO, "<STDERR>");
9478}
9479
9480FILE *
9481rb_io_stdio_file(rb_io_t *fptr)
9482{
9483 if (!fptr->stdio_file) {
9484 int oflags = rb_io_fmode_oflags(fptr->mode) & ~O_EXCL;
9485 fptr->stdio_file = rb_fdopen(fptr->fd, rb_io_oflags_modestr(oflags));
9486 }
9487 return fptr->stdio_file;
9488}
9489
9490static inline void
9491rb_io_buffer_init(struct rb_io_internal_buffer *buf)
9492{
9493 buf->ptr = NULL;
9494 buf->off = 0;
9495 buf->len = 0;
9496 buf->capa = 0;
9497}
9498
9499static inline rb_io_t *
9500rb_io_fptr_new(void)
9501{
9502 rb_io_t *fp = ALLOC(rb_io_t);
9503 fp->self = Qnil;
9504 fp->fd = -1;
9505 fp->stdio_file = NULL;
9506 fp->mode = 0;
9507 fp->pid = 0;
9508 fp->lineno = 0;
9509 fp->pathv = Qnil;
9510 fp->finalize = 0;
9511 rb_io_buffer_init(&fp->wbuf);
9512 rb_io_buffer_init(&fp->rbuf);
9513 rb_io_buffer_init(&fp->cbuf);
9514 fp->readconv = NULL;
9515 fp->writeconv = NULL;
9517 fp->writeconv_pre_ecflags = 0;
9519 fp->writeconv_initialized = 0;
9520 fp->tied_io_for_writing = 0;
9521 fp->encs.enc = NULL;
9522 fp->encs.enc2 = NULL;
9523 fp->encs.ecflags = 0;
9524 fp->encs.ecopts = Qnil;
9525 fp->write_lock = Qnil;
9526 fp->timeout = Qnil;
9527 ccan_list_head_init(&fp->blocking_operations);
9528 fp->closing_ec = NULL;
9529 fp->wakeup_mutex = Qnil;
9530 fp->fork_generation = GET_VM()->fork_gen;
9531 return fp;
9532}
9533
9534rb_io_t *
9535rb_io_make_open_file(VALUE obj)
9536{
9537 rb_io_t *fp = 0;
9538
9539 Check_Type(obj, T_FILE);
9540 if (RFILE(obj)->fptr) {
9541 rb_io_close(obj);
9542 rb_io_fptr_finalize(RFILE(obj)->fptr);
9543 RFILE(obj)->fptr = 0;
9544 }
9545 fp = rb_io_fptr_new();
9546 fp->self = obj;
9547 RFILE(obj)->fptr = fp;
9548 return fp;
9549}
9550
9551static VALUE io_initialize(VALUE io, VALUE fnum, VALUE vmode, VALUE opt);
9552
9553/*
9554 * call-seq:
9555 * IO.new(fd, mode = 'r', **opts) -> io
9556 *
9557 * Creates and returns a new \IO object (file stream) from a file descriptor.
9558 *
9559 * \IO.new may be useful for interaction with low-level libraries.
9560 * For higher-level interactions, it may be simpler to create
9561 * the file stream using File.open.
9562 *
9563 * Argument +fd+ must be a valid file descriptor (integer):
9564 *
9565 * path = 't.tmp'
9566 * fd = IO.sysopen(path) # => 3
9567 * IO.new(fd) # => #<IO:fd 3>
9568 *
9569 * The new \IO object does not inherit encoding
9570 * (because the integer file descriptor does not have an encoding):
9571 *
9572 * fd = IO.sysopen('t.rus', 'rb')
9573 * io = IO.new(fd)
9574 * io.external_encoding # => #<Encoding:UTF-8> # Not ASCII-8BIT.
9575 *
9576 * Optional argument +mode+ (defaults to 'r') must specify a valid mode;
9577 * see {Access Modes}[rdoc-ref:File@Access+Modes]:
9578 *
9579 * IO.new(fd, 'w') # => #<IO:fd 3>
9580 * IO.new(fd, File::WRONLY) # => #<IO:fd 3>
9581 *
9582 * Optional keyword arguments +opts+ specify:
9583 *
9584 * - {Open Options}[rdoc-ref:IO@Open+Options].
9585 * - {Encoding options}[rdoc-ref:encodings.rdoc@Encoding+Options].
9586 *
9587 * Examples:
9588 *
9589 * IO.new(fd, internal_encoding: nil) # => #<IO:fd 3>
9590 * IO.new(fd, autoclose: true) # => #<IO:fd 3>
9591 *
9592 */
9593
9594static VALUE
9595rb_io_initialize(int argc, VALUE *argv, VALUE io)
9596{
9597 VALUE fnum, vmode;
9598 VALUE opt;
9599
9600 rb_scan_args(argc, argv, "11:", &fnum, &vmode, &opt);
9601 return io_initialize(io, fnum, vmode, opt);
9602}
9603
9604static VALUE
9605io_initialize(VALUE io, VALUE fnum, VALUE vmode, VALUE opt)
9606{
9607 rb_io_t *fp;
9608 int fd, oflags = O_RDONLY;
9609 enum rb_io_mode fmode;
9610 struct rb_io_encoding convconfig;
9611#if defined(HAVE_FCNTL) && defined(F_GETFL)
9612 int ofmode;
9613#else
9614 struct stat st;
9615#endif
9616
9617 rb_io_extract_modeenc(&vmode, 0, opt, &oflags, &fmode, &convconfig);
9618
9619 fd = NUM2INT(fnum);
9620 if (rb_reserved_fd_p(fd)) {
9621 rb_raise(rb_eArgError, "The given fd is not accessible because RubyVM reserves it");
9622 }
9623#if defined(HAVE_FCNTL) && defined(F_GETFL)
9624 oflags = fcntl(fd, F_GETFL);
9625 if (oflags == -1) rb_sys_fail(0);
9626#else
9627 if (fstat(fd, &st) < 0) rb_sys_fail(0);
9628#endif
9629 rb_update_max_fd(fd);
9630#if defined(HAVE_FCNTL) && defined(F_GETFL)
9631 ofmode = rb_io_oflags_fmode(oflags);
9632 if (NIL_P(vmode)) {
9633 fmode = ofmode;
9634 }
9635 else if ((~ofmode & fmode) & FMODE_READWRITE) {
9636 VALUE error = INT2FIX(EINVAL);
9638 }
9639#endif
9640 VALUE path = Qnil;
9641
9642 if (!NIL_P(opt)) {
9643 if (rb_hash_aref(opt, sym_autoclose) == Qfalse) {
9644 fmode |= FMODE_EXTERNAL;
9645 }
9646
9647 path = rb_hash_aref(opt, RB_ID2SYM(idPath));
9648 if (!NIL_P(path)) {
9649 StringValue(path);
9650 path = rb_str_new_frozen(path);
9651 }
9652 }
9653
9654 MakeOpenFile(io, fp);
9655 fp->self = io;
9656 fp->fd = fd;
9657 fp->mode = fmode;
9658 fp->encs = convconfig;
9659 fp->pathv = path;
9660 fp->timeout = Qnil;
9661 ccan_list_head_init(&fp->blocking_operations);
9662 fp->closing_ec = NULL;
9663 fp->wakeup_mutex = Qnil;
9664 fp->fork_generation = GET_VM()->fork_gen;
9665 clear_codeconv(fp);
9666 io_check_tty(fp);
9667 if (fileno(stdin) == fd)
9668 fp->stdio_file = stdin;
9669 else if (fileno(stdout) == fd)
9670 fp->stdio_file = stdout;
9671 else if (fileno(stderr) == fd)
9672 fp->stdio_file = stderr;
9673
9674 if (fmode & FMODE_SETENC_BY_BOM) io_set_encoding_by_bom(io);
9675 return io;
9676}
9677
9678/*
9679 * call-seq:
9680 * set_encoding_by_bom -> encoding or nil
9681 *
9682 * If the stream begins with a BOM
9683 * ({byte order marker}[https://en.wikipedia.org/wiki/Byte_order_mark]),
9684 * consumes the BOM and sets the external encoding accordingly;
9685 * returns the result encoding if found, or +nil+ otherwise:
9686 *
9687 * File.write('t.tmp', "\u{FEFF}abc")
9688 * io = File.open('t.tmp', 'rb')
9689 * io.set_encoding_by_bom # => #<Encoding:UTF-8>
9690 * io.close
9691 *
9692 * File.write('t.tmp', 'abc')
9693 * io = File.open('t.tmp', 'rb')
9694 * io.set_encoding_by_bom # => nil
9695 * io.close
9696 *
9697 * Raises an exception if the stream is not binmode
9698 * or its encoding has already been set.
9699 *
9700 */
9701
9702static VALUE
9703rb_io_set_encoding_by_bom(VALUE io)
9704{
9705 rb_io_t *fptr;
9706
9707 GetOpenFile(io, fptr);
9708 if (!(fptr->mode & FMODE_BINMODE)) {
9709 rb_raise(rb_eArgError, "ASCII incompatible encoding needs binmode");
9710 }
9711 if (fptr->encs.enc2) {
9712 rb_raise(rb_eArgError, "encoding conversion is set");
9713 }
9714 else if (fptr->encs.enc && fptr->encs.enc != rb_ascii8bit_encoding()) {
9715 rb_raise(rb_eArgError, "encoding is set to %s already",
9716 rb_enc_name(fptr->encs.enc));
9717 }
9718 if (!io_set_encoding_by_bom(io)) return Qnil;
9719 return rb_enc_from_encoding(fptr->encs.enc);
9720}
9721
9722/*
9723 * call-seq:
9724 * File.new(path, mode = 'r', perm = 0666, **opts) -> file
9725 *
9726 * Opens the file at the given +path+ according to the given +mode+;
9727 * creates and returns a new File object for that file.
9728 *
9729 * The new File object is buffered mode (or non-sync mode), unless
9730 * +filename+ is a tty.
9731 * See IO#flush, IO#fsync, IO#fdatasync, and IO#sync=.
9732 *
9733 * Argument +path+ must be a valid file path:
9734 *
9735 * f = File.new('/etc/fstab')
9736 * f.close
9737 * f = File.new('t.txt')
9738 * f.close
9739 *
9740 * Optional argument +mode+ (defaults to 'r') must specify a valid mode;
9741 * see {Access Modes}[rdoc-ref:File@Access+Modes]:
9742 *
9743 * f = File.new('t.tmp', 'w')
9744 * f.close
9745 * f = File.new('t.tmp', File::RDONLY)
9746 * f.close
9747 *
9748 * Optional argument +perm+ (defaults to 0666) must specify valid permissions
9749 * see {File Permissions}[rdoc-ref:File@File+Permissions]:
9750 *
9751 * f = File.new('t.tmp', File::CREAT, 0644)
9752 * f.close
9753 * f = File.new('t.tmp', File::CREAT, 0444)
9754 * f.close
9755 *
9756 * Optional keyword arguments +opts+ specify:
9757 *
9758 * - {Open Options}[rdoc-ref:IO@Open+Options].
9759 * - {Encoding options}[rdoc-ref:encodings.rdoc@Encoding+Options].
9760 *
9761 */
9762
9763static VALUE
9764rb_file_initialize(int argc, VALUE *argv, VALUE io)
9765{
9766 if (RFILE(io)->fptr) {
9767 rb_raise(rb_eRuntimeError, "reinitializing File");
9768 }
9769 VALUE fname, vmode, vperm, opt;
9770 int posargc = rb_scan_args(argc, argv, "12:", &fname, &vmode, &vperm, &opt);
9771 if (posargc < 3) { /* perm is File only */
9772 VALUE fd = rb_check_to_int(fname);
9773
9774 if (!NIL_P(fd)) {
9775 return io_initialize(io, fd, vmode, opt);
9776 }
9777 }
9778 return rb_open_file(io, fname, vmode, vperm, opt);
9779}
9780
9781/* :nodoc: */
9782static VALUE
9783rb_io_s_new(int argc, VALUE *argv, VALUE klass)
9784{
9785 if (rb_block_given_p()) {
9786 VALUE cname = rb_obj_as_string(klass);
9787
9788 rb_warn("%"PRIsVALUE"::new() does not take block; use %"PRIsVALUE"::open() instead",
9789 cname, cname);
9790 }
9791 return rb_class_new_instance_kw(argc, argv, klass, RB_PASS_CALLED_KEYWORDS);
9792}
9793
9794
9795/*
9796 * call-seq:
9797 * IO.for_fd(fd, mode = 'r', **opts) -> io
9798 *
9799 * Synonym for IO.new.
9800 *
9801 */
9802
9803static VALUE
9804rb_io_s_for_fd(int argc, VALUE *argv, VALUE klass)
9805{
9806 VALUE io = rb_obj_alloc(klass);
9807 rb_io_initialize(argc, argv, io);
9808 return io;
9809}
9810
9811/*
9812 * call-seq:
9813 * ios.autoclose? -> true or false
9814 *
9815 * Returns +true+ if the underlying file descriptor of _ios_ will be
9816 * closed at its finalization or at calling #close, otherwise +false+.
9817 */
9818
9819static VALUE
9820rb_io_autoclose_p(VALUE io)
9821{
9822 rb_io_t *fptr = RFILE(io)->fptr;
9823 rb_io_check_closed(fptr);
9824 return RBOOL(!(fptr->mode & FMODE_EXTERNAL));
9825}
9826
9827/*
9828 * call-seq:
9829 * io.autoclose = bool -> true or false
9830 *
9831 * Sets auto-close flag.
9832 *
9833 * f = File.open(File::NULL)
9834 * IO.for_fd(f.fileno).close
9835 * f.gets # raises Errno::EBADF
9836 *
9837 * f = File.open(File::NULL)
9838 * g = IO.for_fd(f.fileno)
9839 * g.autoclose = false
9840 * g.close
9841 * f.gets # won't cause Errno::EBADF
9842 */
9843
9844static VALUE
9845rb_io_set_autoclose(VALUE io, VALUE autoclose)
9846{
9847 rb_io_t *fptr;
9848 GetOpenFile(io, fptr);
9849 if (!RTEST(autoclose))
9850 fptr->mode |= FMODE_EXTERNAL;
9851 else
9852 fptr->mode &= ~FMODE_EXTERNAL;
9853 return autoclose;
9854}
9855
9856static VALUE
9857io_wait_event(VALUE io, int event, VALUE timeout, int return_io)
9858{
9859 VALUE result = rb_io_wait(io, RB_INT2NUM(event), timeout);
9860
9861 if (!RB_TEST(result)) {
9862 return Qnil;
9863 }
9864
9865 int mask = RB_NUM2INT(result);
9866
9867 if (mask & event) {
9868 if (return_io)
9869 return io;
9870 else
9871 return result;
9872 }
9873 else {
9874 return Qfalse;
9875 }
9876}
9877
9878/*
9879 * call-seq:
9880 * io.wait_readable -> truthy or falsy
9881 * io.wait_readable(timeout) -> truthy or falsy
9882 *
9883 * Waits until IO is readable and returns a truthy value, or a falsy
9884 * value when times out. Returns a truthy value immediately when
9885 * buffered data is available.
9886 */
9887
9888static VALUE
9889io_wait_readable(int argc, VALUE *argv, VALUE io)
9890{
9891 rb_io_t *fptr;
9892
9893 RB_IO_POINTER(io, fptr);
9895
9896 if (rb_io_read_pending(fptr)) return Qtrue;
9897
9898 rb_check_arity(argc, 0, 1);
9899 VALUE timeout = (argc == 1 ? argv[0] : Qnil);
9900
9901 return io_wait_event(io, RUBY_IO_READABLE, timeout, 1);
9902}
9903
9904/*
9905 * call-seq:
9906 * io.wait_writable -> truthy or falsy
9907 * io.wait_writable(timeout) -> truthy or falsy
9908 *
9909 * Waits until IO is writable and returns a truthy value or a falsy
9910 * value when times out.
9911 */
9912static VALUE
9913io_wait_writable(int argc, VALUE *argv, VALUE io)
9914{
9915 rb_io_t *fptr;
9916
9917 RB_IO_POINTER(io, fptr);
9919
9920 rb_check_arity(argc, 0, 1);
9921 VALUE timeout = (argc == 1 ? argv[0] : Qnil);
9922
9923 return io_wait_event(io, RUBY_IO_WRITABLE, timeout, 1);
9924}
9925
9926/*
9927 * call-seq:
9928 * io.wait_priority -> truthy or falsy
9929 * io.wait_priority(timeout) -> truthy or falsy
9930 *
9931 * Waits until IO is priority and returns a truthy value or a falsy
9932 * value when times out. Priority data is sent and received using
9933 * the Socket::MSG_OOB flag and is typically limited to streams.
9934 */
9935static VALUE
9936io_wait_priority(int argc, VALUE *argv, VALUE io)
9937{
9938 rb_io_t *fptr = NULL;
9939
9940 RB_IO_POINTER(io, fptr);
9942
9943 if (rb_io_read_pending(fptr)) return Qtrue;
9944
9945 rb_check_arity(argc, 0, 1);
9946 VALUE timeout = argc == 1 ? argv[0] : Qnil;
9947
9948 return io_wait_event(io, RUBY_IO_PRIORITY, timeout, 1);
9949}
9950
9951static int
9952wait_mode_sym(VALUE mode)
9953{
9954 if (mode == ID2SYM(rb_intern("r"))) {
9955 return RB_WAITFD_IN;
9956 }
9957 if (mode == ID2SYM(rb_intern("read"))) {
9958 return RB_WAITFD_IN;
9959 }
9960 if (mode == ID2SYM(rb_intern("readable"))) {
9961 return RB_WAITFD_IN;
9962 }
9963 if (mode == ID2SYM(rb_intern("w"))) {
9964 return RB_WAITFD_OUT;
9965 }
9966 if (mode == ID2SYM(rb_intern("write"))) {
9967 return RB_WAITFD_OUT;
9968 }
9969 if (mode == ID2SYM(rb_intern("writable"))) {
9970 return RB_WAITFD_OUT;
9971 }
9972 if (mode == ID2SYM(rb_intern("rw"))) {
9973 return RB_WAITFD_IN|RB_WAITFD_OUT;
9974 }
9975 if (mode == ID2SYM(rb_intern("read_write"))) {
9976 return RB_WAITFD_IN|RB_WAITFD_OUT;
9977 }
9978 if (mode == ID2SYM(rb_intern("readable_writable"))) {
9979 return RB_WAITFD_IN|RB_WAITFD_OUT;
9980 }
9981
9982 rb_raise(rb_eArgError, "unsupported mode: %"PRIsVALUE, mode);
9983}
9984
9985static inline enum rb_io_event
9986io_event_from_value(VALUE value)
9987{
9988 int events = RB_NUM2INT(value);
9989
9990 if (events <= 0) rb_raise(rb_eArgError, "Events must be positive integer!");
9991
9992 return events;
9993}
9994
9995/*
9996 * call-seq:
9997 * io.wait(events, timeout) -> event mask, false or nil
9998 * io.wait(*event_symbols[, timeout]) -> self, true, or false
9999 *
10000 * Waits until the IO becomes ready for the specified events and returns the
10001 * subset of events that become ready, or a falsy value when times out.
10002 *
10003 * The events can be a bit mask of +IO::READABLE+, +IO::WRITABLE+ or
10004 * +IO::PRIORITY+.
10005 *
10006 * Returns an event mask (truthy value) immediately when buffered data is
10007 * available.
10008 *
10009 * The second form: if one or more event symbols (+:read+, +:write+, or
10010 * +:read_write+) are passed, the event mask is the bit OR of the bitmask
10011 * corresponding to those symbols. In this form, +timeout+ is optional, the
10012 * order of the arguments is arbitrary, and returns +io+ if any of the
10013 * events is ready.
10014 */
10015
10016static VALUE
10017io_wait(int argc, VALUE *argv, VALUE io)
10018{
10019 VALUE timeout = Qundef;
10020 enum rb_io_event events = 0;
10021 int return_io = 0;
10022
10023 if (argc != 2 || (RB_SYMBOL_P(argv[0]) || RB_SYMBOL_P(argv[1]))) {
10024 // We'd prefer to return the actual mask, but this form would return the io itself:
10025 return_io = 1;
10026
10027 // Slow/messy path:
10028 for (int i = 0; i < argc; i += 1) {
10029 if (RB_SYMBOL_P(argv[i])) {
10030 events |= wait_mode_sym(argv[i]);
10031 }
10032 else if (UNDEF_P(timeout)) {
10033 rb_time_interval(timeout = argv[i]);
10034 }
10035 else {
10036 rb_raise(rb_eArgError, "timeout given more than once");
10037 }
10038 }
10039
10040 if (UNDEF_P(timeout)) timeout = Qnil;
10041
10042 if (events == 0) {
10043 events = RUBY_IO_READABLE;
10044 }
10045 }
10046 else /* argc == 2 and neither are symbols */ {
10047 // This is the fast path:
10048 events = io_event_from_value(argv[0]);
10049 timeout = argv[1];
10050 }
10051
10052 if (events & RUBY_IO_READABLE) {
10053 rb_io_t *fptr = NULL;
10054 RB_IO_POINTER(io, fptr);
10055
10056 if (rb_io_read_pending(fptr)) {
10057 // This was the original behaviour:
10058 if (return_io) return Qtrue;
10059 // New behaviour always returns an event mask:
10060 else return RB_INT2NUM(RUBY_IO_READABLE);
10061 }
10062 }
10063
10064 return io_wait_event(io, events, timeout, return_io);
10065}
10066
10067static void
10068argf_mark_and_move(void *ptr)
10069{
10070 struct argf *p = ptr;
10071 rb_gc_mark_and_move(&p->filename);
10072 rb_gc_mark_and_move(&p->current_file);
10073 rb_gc_mark_and_move(&p->argv);
10074 rb_gc_mark_and_move(&p->inplace);
10075 rb_gc_mark_and_move(&p->encs.ecopts);
10076}
10077
10078static size_t
10079argf_memsize(const void *ptr)
10080{
10081 const struct argf *p = ptr;
10082 size_t size = sizeof(*p);
10083 return size;
10084}
10085
10086static const rb_data_type_t argf_type = {
10087 "ARGF",
10088 {argf_mark_and_move, RUBY_TYPED_DEFAULT_FREE, argf_memsize, argf_mark_and_move},
10089 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
10090};
10091
10092static inline void
10093argf_init(struct argf *p, VALUE v)
10094{
10095 p->filename = Qnil;
10096 p->current_file = Qnil;
10097 p->lineno = 0;
10098 p->argv = v;
10099}
10100
10101static VALUE
10102argf_alloc(VALUE klass)
10103{
10104 struct argf *p;
10105 VALUE argf = TypedData_Make_Struct(klass, struct argf, &argf_type, p);
10106
10107 argf_init(p, Qnil);
10108 return argf;
10109}
10110
10111#undef rb_argv
10112
10113/* :nodoc: */
10114static VALUE
10115argf_initialize(VALUE argf, VALUE argv)
10116{
10117 memset(&ARGF, 0, sizeof(ARGF));
10118 argf_init(&ARGF, argv);
10119
10120 return argf;
10121}
10122
10123/* :nodoc: */
10124static VALUE
10125argf_initialize_copy(VALUE argf, VALUE orig)
10126{
10127 if (!OBJ_INIT_COPY(argf, orig)) return argf;
10128 ARGF = argf_of(orig);
10129 ARGF.argv = rb_obj_dup(ARGF.argv);
10130 return argf;
10131}
10132
10133/*
10134 * call-seq:
10135 * ARGF.lineno = integer -> integer
10136 *
10137 * Sets the line number of ARGF as a whole to the given Integer.
10138 *
10139 * ARGF sets the line number automatically as you read data, so normally
10140 * you will not need to set it explicitly. To access the current line number
10141 * use ARGF.lineno.
10142 *
10143 * For example:
10144 *
10145 * ARGF.lineno #=> 0
10146 * ARGF.readline #=> "This is line 1\n"
10147 * ARGF.lineno #=> 1
10148 * ARGF.lineno = 0 #=> 0
10149 * ARGF.lineno #=> 0
10150 */
10151static VALUE
10152argf_set_lineno(VALUE argf, VALUE val)
10153{
10154 ARGF.lineno = NUM2INT(val);
10155 ARGF.last_lineno = ARGF.lineno;
10156 return val;
10157}
10158
10159/*
10160 * call-seq:
10161 * ARGF.lineno -> integer
10162 *
10163 * Returns the current line number of ARGF as a whole. This value
10164 * can be set manually with ARGF.lineno=.
10165 *
10166 * For example:
10167 *
10168 * ARGF.lineno #=> 0
10169 * ARGF.readline #=> "This is line 1\n"
10170 * ARGF.lineno #=> 1
10171 */
10172static VALUE
10173argf_lineno(VALUE argf)
10174{
10175 return INT2FIX(ARGF.lineno);
10176}
10177
10178static VALUE
10179argf_forward(int argc, VALUE *argv, VALUE argf)
10180{
10181 return forward_current(rb_frame_this_func(), argc, argv);
10182}
10183
10184#define next_argv() argf_next_argv(argf)
10185#define ARGF_GENERIC_INPUT_P() \
10186 (ARGF.current_file == rb_stdin && !RB_TYPE_P(ARGF.current_file, T_FILE))
10187#define ARGF_FORWARD(argc, argv) do {\
10188 if (ARGF_GENERIC_INPUT_P())\
10189 return argf_forward((argc), (argv), argf);\
10190} while (0)
10191#define NEXT_ARGF_FORWARD(argc, argv) do {\
10192 if (!next_argv()) return Qnil;\
10193 ARGF_FORWARD((argc), (argv));\
10194} while (0)
10195
10196static void
10197argf_close(VALUE argf)
10198{
10199 VALUE file = ARGF.current_file;
10200 if (file == rb_stdin) return;
10201 if (RB_TYPE_P(file, T_FILE)) {
10202 rb_io_set_write_io(file, Qnil);
10203 }
10204 io_close(file);
10205 ARGF.init_p = -1;
10206}
10207
10208static int
10209argf_next_argv(VALUE argf)
10210{
10211 char *fn;
10212 rb_io_t *fptr;
10213 int stdout_binmode = 0;
10214 enum rb_io_mode fmode;
10215
10216 VALUE r_stdout = rb_ractor_stdout();
10217
10218 if (RB_TYPE_P(r_stdout, T_FILE)) {
10219 GetOpenFile(r_stdout, fptr);
10220 if (fptr->mode & FMODE_BINMODE)
10221 stdout_binmode = 1;
10222 }
10223
10224 if (ARGF.init_p == 0) {
10225 if (!NIL_P(ARGF.argv) && RARRAY_LEN(ARGF.argv) > 0) {
10226 ARGF.next_p = 1;
10227 }
10228 else {
10229 ARGF.next_p = -1;
10230 }
10231 ARGF.init_p = 1;
10232 }
10233 else {
10234 if (NIL_P(ARGF.argv)) {
10235 ARGF.next_p = -1;
10236 }
10237 else if (ARGF.next_p == -1 && RARRAY_LEN(ARGF.argv) > 0) {
10238 ARGF.next_p = 1;
10239 }
10240 }
10241
10242 if (ARGF.next_p == 1) {
10243 if (ARGF.init_p == 1) argf_close(argf);
10244 retry:
10245 if (RARRAY_LEN(ARGF.argv) > 0) {
10246 VALUE filename = rb_ary_shift(ARGF.argv);
10247 FilePathValue(filename);
10248 ARGF.filename = filename;
10249 filename = rb_str_encode_ospath(filename);
10250 fn = StringValueCStr(filename);
10251 if (RSTRING_LEN(filename) == 1 && fn[0] == '-') {
10252 ARGF.current_file = rb_stdin;
10253 if (ARGF.inplace) {
10254 rb_warn("Can't do inplace edit for stdio; skipping");
10255 goto retry;
10256 }
10257 }
10258 else {
10259 VALUE write_io = Qnil;
10260 int fr = rb_sysopen(filename, O_RDONLY, 0);
10261
10262 if (ARGF.inplace) {
10263 struct stat st;
10264#ifndef NO_SAFE_RENAME
10265 struct stat st2;
10266#endif
10267 VALUE str;
10268 int fw;
10269
10270 if (RB_TYPE_P(r_stdout, T_FILE) && r_stdout != orig_stdout) {
10271 rb_io_close(r_stdout);
10272 }
10273 fstat(fr, &st);
10274 str = filename;
10275 if (!NIL_P(ARGF.inplace)) {
10276 VALUE suffix = ARGF.inplace;
10277 str = rb_str_dup(str);
10278 if (NIL_P(rb_str_cat_conv_enc_opts(str, RSTRING_LEN(str),
10279 RSTRING_PTR(suffix), RSTRING_LEN(suffix),
10280 rb_enc_get(suffix), 0, Qnil))) {
10281 rb_str_append(str, suffix);
10282 }
10283#ifdef NO_SAFE_RENAME
10284 (void)close(fr);
10285 (void)unlink(RSTRING_PTR(str));
10286 if (rename(fn, RSTRING_PTR(str)) < 0) {
10287 rb_warn("Can't rename %"PRIsVALUE" to %"PRIsVALUE": %s, skipping file",
10288 filename, str, strerror(errno));
10289 goto retry;
10290 }
10291 fr = rb_sysopen(str, O_RDONLY, 0);
10292#else
10293 if (rename(fn, RSTRING_PTR(str)) < 0) {
10294 rb_warn("Can't rename %"PRIsVALUE" to %"PRIsVALUE": %s, skipping file",
10295 filename, str, strerror(errno));
10296 close(fr);
10297 goto retry;
10298 }
10299#endif
10300 }
10301 else {
10302#ifdef NO_SAFE_RENAME
10303 rb_fatal("Can't do inplace edit without backup");
10304#else
10305 if (unlink(fn) < 0) {
10306 rb_warn("Can't remove %"PRIsVALUE": %s, skipping file",
10307 filename, strerror(errno));
10308 close(fr);
10309 goto retry;
10310 }
10311#endif
10312 }
10313 fw = rb_sysopen(filename, O_WRONLY|O_CREAT|O_TRUNC, 0666);
10314#ifndef NO_SAFE_RENAME
10315 fstat(fw, &st2);
10316#ifdef HAVE_FCHMOD
10317 fchmod(fw, st.st_mode);
10318#else
10319 chmod(fn, st.st_mode);
10320#endif
10321 if (st.st_uid!=st2.st_uid || st.st_gid!=st2.st_gid) {
10322 int err;
10323#ifdef HAVE_FCHOWN
10324 err = fchown(fw, st.st_uid, st.st_gid);
10325#else
10326 err = chown(fn, st.st_uid, st.st_gid);
10327#endif
10328 if (err && getuid() == 0 && st2.st_uid == 0) {
10329 const char *wkfn = RSTRING_PTR(filename);
10330 rb_warn("Can't set owner/group of %"PRIsVALUE" to same as %"PRIsVALUE": %s, skipping file",
10331 filename, str, strerror(errno));
10332 (void)close(fr);
10333 (void)close(fw);
10334 (void)unlink(wkfn);
10335 goto retry;
10336 }
10337 }
10338#endif
10339 write_io = prep_io(fw, FMODE_WRITABLE, rb_cFile, fn);
10340 rb_ractor_stdout_set(write_io);
10341 if (stdout_binmode) rb_io_binmode(rb_stdout);
10342 }
10343 fmode = FMODE_READABLE;
10344 if (!ARGF.binmode) {
10345 fmode |= DEFAULT_TEXTMODE;
10346 }
10347 ARGF.current_file = prep_io(fr, fmode, rb_cFile, fn);
10348 if (!NIL_P(write_io)) {
10349 rb_io_set_write_io(ARGF.current_file, write_io);
10350 }
10351 RB_GC_GUARD(filename);
10352 }
10353 if (ARGF.binmode) rb_io_ascii8bit_binmode(ARGF.current_file);
10354 GetOpenFile(ARGF.current_file, fptr);
10355 if (ARGF.encs.enc) {
10356 fptr->encs = ARGF.encs;
10357 clear_codeconv(fptr);
10358 }
10359 else {
10361 if (!ARGF.binmode) {
10363#ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE
10364 fptr->encs.ecflags |= TEXTMODE_NEWLINE_DECORATOR_ON_WRITE;
10365#endif
10366 }
10367 }
10368 ARGF.next_p = 0;
10369 }
10370 else {
10371 ARGF.next_p = 1;
10372 return FALSE;
10373 }
10374 }
10375 else if (ARGF.next_p == -1) {
10376 ARGF.current_file = rb_stdin;
10377 ARGF.filename = rb_str_new2("-");
10378 if (ARGF.inplace) {
10379 rb_warn("Can't do inplace edit for stdio");
10380 rb_ractor_stdout_set(orig_stdout);
10381 }
10382 }
10383 if (ARGF.init_p == -1) ARGF.init_p = 1;
10384 return TRUE;
10385}
10386
10387static VALUE
10388argf_getline(int argc, VALUE *argv, VALUE argf)
10389{
10390 VALUE line;
10391 long lineno = ARGF.lineno;
10392
10393 retry:
10394 if (!next_argv()) return Qnil;
10395 if (ARGF_GENERIC_INPUT_P()) {
10396 line = forward_current(idGets, argc, argv);
10397 }
10398 else {
10399 if (argc == 0 && rb_rs == rb_default_rs) {
10400 line = rb_io_gets(ARGF.current_file);
10401 }
10402 else {
10403 line = rb_io_getline(argc, argv, ARGF.current_file);
10404 }
10405 if (NIL_P(line) && ARGF.next_p != -1) {
10406 argf_close(argf);
10407 ARGF.next_p = 1;
10408 goto retry;
10409 }
10410 }
10411 if (!NIL_P(line)) {
10412 ARGF.lineno = ++lineno;
10413 ARGF.last_lineno = ARGF.lineno;
10414 }
10415 return line;
10416}
10417
10418static VALUE
10419argf_lineno_getter(ID id, VALUE *var)
10420{
10421 VALUE argf = *var;
10422 return INT2FIX(ARGF.last_lineno);
10423}
10424
10425static void
10426argf_lineno_setter(VALUE val, ID id, VALUE *var)
10427{
10428 VALUE argf = *var;
10429 int n = NUM2INT(val);
10430 ARGF.last_lineno = ARGF.lineno = n;
10431}
10432
10433void
10434rb_reset_argf_lineno(long n)
10435{
10436 ARGF.last_lineno = ARGF.lineno = n;
10437}
10438
10439static VALUE argf_gets(int, VALUE *, VALUE);
10440
10441/*
10442 * call-seq:
10443 * gets(sep=$/ [, getline_args]) -> string or nil
10444 * gets(limit [, getline_args]) -> string or nil
10445 * gets(sep, limit [, getline_args]) -> string or nil
10446 *
10447 * Returns (and assigns to <code>$_</code>) the next line from the list
10448 * of files in +ARGV+ (or <code>$*</code>), or from standard input if
10449 * no files are present on the command line. Returns +nil+ at end of
10450 * file. The optional argument specifies the record separator. The
10451 * separator is included with the contents of each record. A separator
10452 * of +nil+ reads the entire contents, and a zero-length separator
10453 * reads the input one paragraph at a time, where paragraphs are
10454 * divided by two consecutive newlines. If the first argument is an
10455 * integer, or optional second argument is given, the returning string
10456 * would not be longer than the given value in bytes. If multiple
10457 * filenames are present in +ARGV+, <code>gets(nil)</code> will read
10458 * the contents one file at a time.
10459 *
10460 * ARGV << "testfile"
10461 * print while gets
10462 *
10463 * <em>produces:</em>
10464 *
10465 * This is line one
10466 * This is line two
10467 * This is line three
10468 * And so on...
10469 *
10470 * The style of programming using <code>$_</code> as an implicit
10471 * parameter is gradually losing favor in the Ruby community.
10472 */
10473
10474static VALUE
10475rb_f_gets(int argc, VALUE *argv, VALUE recv)
10476{
10477 if (recv == argf) {
10478 return argf_gets(argc, argv, argf);
10479 }
10480 return forward(argf, idGets, argc, argv);
10481}
10482
10483/*
10484 * call-seq:
10485 * ARGF.gets(sep=$/ [, getline_args]) -> string or nil
10486 * ARGF.gets(limit [, getline_args]) -> string or nil
10487 * ARGF.gets(sep, limit [, getline_args]) -> string or nil
10488 *
10489 * Returns the next line from the current file in ARGF.
10490 *
10491 * By default lines are assumed to be separated by <code>$/</code>;
10492 * to use a different character as a separator, supply it as a String
10493 * for the _sep_ argument.
10494 *
10495 * The optional _limit_ argument specifies how many characters of each line
10496 * to return. By default all characters are returned.
10497 *
10498 * See IO.readlines for details about getline_args.
10499 *
10500 */
10501static VALUE
10502argf_gets(int argc, VALUE *argv, VALUE argf)
10503{
10504 VALUE line;
10505
10506 line = argf_getline(argc, argv, argf);
10507 rb_lastline_set(line);
10508
10509 return line;
10510}
10511
10512VALUE
10514{
10515 VALUE line;
10516
10517 if (rb_rs != rb_default_rs) {
10518 return rb_f_gets(0, 0, argf);
10519 }
10520
10521 retry:
10522 if (!next_argv()) return Qnil;
10523 line = rb_io_gets(ARGF.current_file);
10524 if (NIL_P(line) && ARGF.next_p != -1) {
10525 rb_io_close(ARGF.current_file);
10526 ARGF.next_p = 1;
10527 goto retry;
10528 }
10529 rb_lastline_set(line);
10530 if (!NIL_P(line)) {
10531 ARGF.lineno++;
10532 ARGF.last_lineno = ARGF.lineno;
10533 }
10534
10535 return line;
10536}
10537
10538static VALUE argf_readline(int, VALUE *, VALUE);
10539
10540/*
10541 * call-seq:
10542 * readline(sep = $/, chomp: false) -> string
10543 * readline(limit, chomp: false) -> string
10544 * readline(sep, limit, chomp: false) -> string
10545 *
10546 * Equivalent to method Kernel#gets, except that it raises an exception
10547 * if called at end-of-stream:
10548 *
10549 * $ cat t.txt | ruby -e "p readlines; readline"
10550 * ["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"]
10551 * in `readline': end of file reached (EOFError)
10552 *
10553 * Optional keyword argument +chomp+ specifies whether line separators
10554 * are to be omitted.
10555 */
10556
10557static VALUE
10558rb_f_readline(int argc, VALUE *argv, VALUE recv)
10559{
10560 if (recv == argf) {
10561 return argf_readline(argc, argv, argf);
10562 }
10563 return forward(argf, rb_intern("readline"), argc, argv);
10564}
10565
10566
10567/*
10568 * call-seq:
10569 * ARGF.readline(sep=$/) -> string
10570 * ARGF.readline(limit) -> string
10571 * ARGF.readline(sep, limit) -> string
10572 *
10573 * Returns the next line from the current file in ARGF.
10574 *
10575 * By default lines are assumed to be separated by <code>$/</code>;
10576 * to use a different character as a separator, supply it as a String
10577 * for the _sep_ argument.
10578 *
10579 * The optional _limit_ argument specifies how many characters of each line
10580 * to return. By default all characters are returned.
10581 *
10582 * An EOFError is raised at the end of the file.
10583 */
10584static VALUE
10585argf_readline(int argc, VALUE *argv, VALUE argf)
10586{
10587 VALUE line;
10588
10589 if (!next_argv()) rb_eof_error();
10590 ARGF_FORWARD(argc, argv);
10591 line = argf_gets(argc, argv, argf);
10592 if (NIL_P(line)) {
10593 rb_eof_error();
10594 }
10595
10596 return line;
10597}
10598
10599static VALUE argf_readlines(int, VALUE *, VALUE);
10600
10601/*
10602 * call-seq:
10603 * readlines(sep = $/, chomp: false, **enc_opts) -> array
10604 * readlines(limit, chomp: false, **enc_opts) -> array
10605 * readlines(sep, limit, chomp: false, **enc_opts) -> array
10606 *
10607 * Returns an array containing the lines returned by calling
10608 * Kernel#gets until the end-of-stream is reached;
10609 * (see {Line IO}[rdoc-ref:IO@Line+IO]).
10610 *
10611 * With only string argument +sep+ given,
10612 * returns the remaining lines as determined by line separator +sep+,
10613 * or +nil+ if none;
10614 * see {Line Separator}[rdoc-ref:IO@Line+Separator]:
10615 *
10616 * # Default separator.
10617 * $ cat t.txt | ruby -e "p readlines"
10618 * ["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"]
10619 *
10620 * # Specified separator.
10621 * $ cat t.txt | ruby -e "p readlines 'li'"
10622 * ["First li", "ne\nSecond li", "ne\n\nFourth li", "ne\nFifth li", "ne\n"]
10623 *
10624 * # Get-all separator.
10625 * $ cat t.txt | ruby -e "p readlines nil"
10626 * ["First line\nSecond line\n\nFourth line\nFifth line\n"]
10627 *
10628 * # Get-paragraph separator.
10629 * $ cat t.txt | ruby -e "p readlines ''"
10630 * ["First line\nSecond line\n\n", "Fourth line\nFifth line\n"]
10631 *
10632 * With only integer argument +limit+ given,
10633 * limits the number of bytes in the line;
10634 * see {Line Limit}[rdoc-ref:IO@Line+Limit]:
10635 *
10636 * $cat t.txt | ruby -e "p readlines 10"
10637 * ["First line", "\n", "Second lin", "e\n", "\n", "Fourth lin", "e\n", "Fifth line", "\n"]
10638 *
10639 * $cat t.txt | ruby -e "p readlines 11"
10640 * ["First line\n", "Second line", "\n", "\n", "Fourth line", "\n", "Fifth line\n"]
10641 *
10642 * $cat t.txt | ruby -e "p readlines 12"
10643 * ["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"]
10644 *
10645 * With arguments +sep+ and +limit+ given,
10646 * combines the two behaviors
10647 * (see {Line Separator and Line Limit}[rdoc-ref:IO@Line+Separator+and+Line+Limit]).
10648 *
10649 * Optional keyword argument +chomp+ specifies whether line separators
10650 * are to be omitted:
10651 *
10652 * $ cat t.txt | ruby -e "p readlines(chomp: true)"
10653 * ["First line", "Second line", "", "Fourth line", "Fifth line"]
10654 *
10655 * Optional keyword arguments +enc_opts+ specify encoding options;
10656 * see {Encoding options}[rdoc-ref:encodings.rdoc@Encoding+Options].
10657 *
10658 */
10659
10660static VALUE
10661rb_f_readlines(int argc, VALUE *argv, VALUE recv)
10662{
10663 if (recv == argf) {
10664 return argf_readlines(argc, argv, argf);
10665 }
10666 return forward(argf, rb_intern("readlines"), argc, argv);
10667}
10668
10669/*
10670 * call-seq:
10671 * ARGF.readlines(sep = $/, chomp: false) -> array
10672 * ARGF.readlines(limit, chomp: false) -> array
10673 * ARGF.readlines(sep, limit, chomp: false) -> array
10674 *
10675 * ARGF.to_a(sep = $/, chomp: false) -> array
10676 * ARGF.to_a(limit, chomp: false) -> array
10677 * ARGF.to_a(sep, limit, chomp: false) -> array
10678 *
10679 * Reads each file in ARGF in its entirety, returning an Array containing
10680 * lines from the files. Lines are assumed to be separated by _sep_.
10681 *
10682 * lines = ARGF.readlines
10683 * lines[0] #=> "This is line one\n"
10684 *
10685 * See +IO.readlines+ for a full description of all options.
10686 */
10687static VALUE
10688argf_readlines(int argc, VALUE *argv, VALUE argf)
10689{
10690 long lineno = ARGF.lineno;
10691 VALUE lines, ary;
10692
10693 ary = rb_ary_new();
10694 while (next_argv()) {
10695 if (ARGF_GENERIC_INPUT_P()) {
10696 lines = forward_current(rb_intern("readlines"), argc, argv);
10697 }
10698 else {
10699 lines = rb_io_readlines(argc, argv, ARGF.current_file);
10700 argf_close(argf);
10701 }
10702 ARGF.next_p = 1;
10703 rb_ary_concat(ary, lines);
10704 ARGF.lineno = lineno + RARRAY_LEN(ary);
10705 ARGF.last_lineno = ARGF.lineno;
10706 }
10707 ARGF.init_p = 0;
10708 return ary;
10709}
10710
10711/*
10712 * call-seq:
10713 * `command` -> string
10714 *
10715 * Returns the <tt>$stdout</tt> output from running +command+ in a subshell;
10716 * sets global variable <tt>$?</tt> to the process status.
10717 *
10718 * This method has potential security vulnerabilities if called with untrusted input;
10719 * see {Command Injection}[rdoc-ref:security/command_injection.rdoc].
10720 *
10721 * Examples:
10722 *
10723 * $ `date` # => "Wed Apr 9 08:56:30 CDT 2003\n"
10724 * $ `echo oops && exit 99` # => "oops\n"
10725 * $ $? # => #<Process::Status: pid 17088 exit 99>
10726 * $ $?.exitstatus # => 99
10727 *
10728 * The built-in syntax <tt>%x{...}</tt> uses this method.
10729 *
10730 */
10731
10732static VALUE
10733rb_f_backquote(VALUE obj, VALUE str)
10734{
10735 VALUE port;
10736 VALUE result;
10737 rb_io_t *fptr;
10738
10739 StringValue(str);
10740 rb_last_status_clear();
10741 port = pipe_open_s(str, "r", FMODE_READABLE|DEFAULT_TEXTMODE, NULL);
10742 if (NIL_P(port)) return rb_str_new(0,0);
10743
10744 GetOpenFile(port, fptr);
10745 result = read_all(fptr, remain_size(fptr), Qnil);
10746 rb_io_close(port);
10747 rb_io_fptr_cleanup_all(fptr);
10748 RB_GC_GUARD(port);
10749
10750 return result;
10751}
10752
10753#ifdef HAVE_SYS_SELECT_H
10754#include <sys/select.h>
10755#endif
10756
10757static VALUE
10758select_internal(VALUE read, VALUE write, VALUE except, struct timeval *tp, rb_fdset_t *fds)
10759{
10760 VALUE res, list;
10761 rb_fdset_t *rp, *wp, *ep;
10762 rb_io_t *fptr;
10763 long i;
10764 int max = 0, n;
10765 int pending = 0;
10766 struct timeval timerec;
10767
10768 if (!NIL_P(read)) {
10769 Check_Type(read, T_ARRAY);
10770 for (i=0; i<RARRAY_LEN(read); i++) {
10771 GetOpenFile(rb_io_get_io(RARRAY_AREF(read, i)), fptr);
10772 rb_fd_set(fptr->fd, &fds[0]);
10773 if (READ_DATA_PENDING(fptr) || READ_CHAR_PENDING(fptr)) { /* check for buffered data */
10774 pending++;
10775 rb_fd_set(fptr->fd, &fds[3]);
10776 }
10777 if (max < fptr->fd) max = fptr->fd;
10778 }
10779 if (pending) { /* no blocking if there's buffered data */
10780 timerec.tv_sec = timerec.tv_usec = 0;
10781 tp = &timerec;
10782 }
10783 rp = &fds[0];
10784 }
10785 else
10786 rp = 0;
10787
10788 if (!NIL_P(write)) {
10789 Check_Type(write, T_ARRAY);
10790 for (i=0; i<RARRAY_LEN(write); i++) {
10791 VALUE write_io = GetWriteIO(rb_io_get_io(RARRAY_AREF(write, i)));
10792 GetOpenFile(write_io, fptr);
10793 rb_fd_set(fptr->fd, &fds[1]);
10794 if (max < fptr->fd) max = fptr->fd;
10795 }
10796 wp = &fds[1];
10797 }
10798 else
10799 wp = 0;
10800
10801 if (!NIL_P(except)) {
10802 Check_Type(except, T_ARRAY);
10803 for (i=0; i<RARRAY_LEN(except); i++) {
10804 VALUE io = rb_io_get_io(RARRAY_AREF(except, i));
10805 VALUE write_io = GetWriteIO(io);
10806 GetOpenFile(io, fptr);
10807 rb_fd_set(fptr->fd, &fds[2]);
10808 if (max < fptr->fd) max = fptr->fd;
10809 if (io != write_io) {
10810 GetOpenFile(write_io, fptr);
10811 rb_fd_set(fptr->fd, &fds[2]);
10812 if (max < fptr->fd) max = fptr->fd;
10813 }
10814 }
10815 ep = &fds[2];
10816 }
10817 else {
10818 ep = 0;
10819 }
10820
10821 max++;
10822
10823 n = rb_thread_fd_select(max, rp, wp, ep, tp);
10824 if (n < 0) {
10825 rb_sys_fail(0);
10826 }
10827 if (!pending && n == 0) return Qnil; /* returns nil on timeout */
10828
10829 res = rb_ary_new2(3);
10830 rb_ary_push(res, rp?rb_ary_new():rb_ary_new2(0));
10831 rb_ary_push(res, wp?rb_ary_new():rb_ary_new2(0));
10832 rb_ary_push(res, ep?rb_ary_new():rb_ary_new2(0));
10833
10834 if (rp) {
10835 list = RARRAY_AREF(res, 0);
10836 for (i=0; i< RARRAY_LEN(read); i++) {
10837 VALUE obj = rb_ary_entry(read, i);
10838 VALUE io = rb_io_get_io(obj);
10839 GetOpenFile(io, fptr);
10840 if (rb_fd_isset(fptr->fd, &fds[0]) ||
10841 rb_fd_isset(fptr->fd, &fds[3])) {
10842 rb_ary_push(list, obj);
10843 }
10844 }
10845 }
10846
10847 if (wp) {
10848 list = RARRAY_AREF(res, 1);
10849 for (i=0; i< RARRAY_LEN(write); i++) {
10850 VALUE obj = rb_ary_entry(write, i);
10851 VALUE io = rb_io_get_io(obj);
10852 VALUE write_io = GetWriteIO(io);
10853 GetOpenFile(write_io, fptr);
10854 if (rb_fd_isset(fptr->fd, &fds[1])) {
10855 rb_ary_push(list, obj);
10856 }
10857 }
10858 }
10859
10860 if (ep) {
10861 list = RARRAY_AREF(res, 2);
10862 for (i=0; i< RARRAY_LEN(except); i++) {
10863 VALUE obj = rb_ary_entry(except, i);
10864 VALUE io = rb_io_get_io(obj);
10865 VALUE write_io = GetWriteIO(io);
10866 GetOpenFile(io, fptr);
10867 if (rb_fd_isset(fptr->fd, &fds[2])) {
10868 rb_ary_push(list, obj);
10869 }
10870 else if (io != write_io) {
10871 GetOpenFile(write_io, fptr);
10872 if (rb_fd_isset(fptr->fd, &fds[2])) {
10873 rb_ary_push(list, obj);
10874 }
10875 }
10876 }
10877 }
10878
10879 return res; /* returns an empty array on interrupt */
10880}
10881
10883 VALUE read, write, except;
10884 struct timeval *timeout;
10885 rb_fdset_t fdsets[4];
10886};
10887
10888static VALUE
10889select_call(VALUE arg)
10890{
10891 struct select_args *p = (struct select_args *)arg;
10892
10893 return select_internal(p->read, p->write, p->except, p->timeout, p->fdsets);
10894}
10895
10896static VALUE
10897select_end(VALUE arg)
10898{
10899 struct select_args *p = (struct select_args *)arg;
10900 int i;
10901
10902 for (i = 0; i < numberof(p->fdsets); ++i)
10903 rb_fd_term(&p->fdsets[i]);
10904 return Qnil;
10905}
10906
10907static VALUE sym_normal, sym_sequential, sym_random,
10908 sym_willneed, sym_dontneed, sym_noreuse;
10909
10910#ifdef HAVE_POSIX_FADVISE
10911struct io_advise_struct {
10912 int fd;
10913 int advice;
10914 rb_off_t offset;
10915 rb_off_t len;
10916};
10917
10918static VALUE
10919io_advise_internal(void *arg)
10920{
10921 struct io_advise_struct *ptr = arg;
10922 return posix_fadvise(ptr->fd, ptr->offset, ptr->len, ptr->advice);
10923}
10924
10925static VALUE
10926io_advise_sym_to_const(VALUE sym)
10927{
10928#ifdef POSIX_FADV_NORMAL
10929 if (sym == sym_normal)
10930 return INT2NUM(POSIX_FADV_NORMAL);
10931#endif
10932
10933#ifdef POSIX_FADV_RANDOM
10934 if (sym == sym_random)
10935 return INT2NUM(POSIX_FADV_RANDOM);
10936#endif
10937
10938#ifdef POSIX_FADV_SEQUENTIAL
10939 if (sym == sym_sequential)
10940 return INT2NUM(POSIX_FADV_SEQUENTIAL);
10941#endif
10942
10943#ifdef POSIX_FADV_WILLNEED
10944 if (sym == sym_willneed)
10945 return INT2NUM(POSIX_FADV_WILLNEED);
10946#endif
10947
10948#ifdef POSIX_FADV_DONTNEED
10949 if (sym == sym_dontneed)
10950 return INT2NUM(POSIX_FADV_DONTNEED);
10951#endif
10952
10953#ifdef POSIX_FADV_NOREUSE
10954 if (sym == sym_noreuse)
10955 return INT2NUM(POSIX_FADV_NOREUSE);
10956#endif
10957
10958 return Qnil;
10959}
10960
10961static VALUE
10962do_io_advise(rb_io_t *fptr, VALUE advice, rb_off_t offset, rb_off_t len)
10963{
10964 int rv;
10965 struct io_advise_struct ias;
10966 VALUE num_adv;
10967
10968 num_adv = io_advise_sym_to_const(advice);
10969
10970 /*
10971 * The platform doesn't support this hint. We don't raise exception, instead
10972 * silently ignore it. Because IO::advise is only hint.
10973 */
10974 if (NIL_P(num_adv))
10975 return Qnil;
10976
10977 ias.fd = fptr->fd;
10978 ias.advice = NUM2INT(num_adv);
10979 ias.offset = offset;
10980 ias.len = len;
10981
10982 rv = (int)rb_io_blocking_region(fptr, io_advise_internal, &ias);
10983 if (rv && rv != ENOSYS) {
10984 /* posix_fadvise(2) doesn't set errno. On success it returns 0; otherwise
10985 it returns the error code. */
10986 VALUE message = rb_sprintf("%"PRIsVALUE" "
10987 "(%"PRI_OFFT_PREFIX"d, "
10988 "%"PRI_OFFT_PREFIX"d, "
10989 "%"PRIsVALUE")",
10990 fptr->pathv, offset, len, advice);
10991 rb_syserr_fail_str(rv, message);
10992 }
10993
10994 return Qnil;
10995}
10996
10997#endif /* HAVE_POSIX_FADVISE */
10998
10999static void
11000advice_arg_check(VALUE advice)
11001{
11002 if (!SYMBOL_P(advice))
11003 rb_raise(rb_eTypeError, "advice must be a Symbol");
11004
11005 if (advice != sym_normal &&
11006 advice != sym_sequential &&
11007 advice != sym_random &&
11008 advice != sym_willneed &&
11009 advice != sym_dontneed &&
11010 advice != sym_noreuse) {
11011 rb_raise(rb_eNotImpError, "Unsupported advice: %+"PRIsVALUE, advice);
11012 }
11013}
11014
11015/*
11016 * call-seq:
11017 * advise(advice, offset = 0, len = 0) -> nil
11018 *
11019 * Invokes Posix system call
11020 * {posix_fadvise(2)}[https://linux.die.net/man/2/posix_fadvise],
11021 * which announces an intention to access data from the current file
11022 * in a particular manner.
11023 *
11024 * The arguments and results are platform-dependent.
11025 *
11026 * The relevant data is specified by:
11027 *
11028 * - +offset+: The offset of the first byte of data.
11029 * - +len+: The number of bytes to be accessed;
11030 * if +len+ is zero, or is larger than the number of bytes remaining,
11031 * all remaining bytes will be accessed.
11032 *
11033 * Argument +advice+ is one of the following symbols:
11034 *
11035 * - +:normal+: The application has no advice to give
11036 * about its access pattern for the specified data.
11037 * If no advice is given for an open file, this is the default assumption.
11038 * - +:sequential+: The application expects to access the specified data sequentially
11039 * (with lower offsets read before higher ones).
11040 * - +:random+: The specified data will be accessed in random order.
11041 * - +:noreuse+: The specified data will be accessed only once.
11042 * - +:willneed+: The specified data will be accessed in the near future.
11043 * - +:dontneed+: The specified data will not be accessed in the near future.
11044 *
11045 * Not implemented on all platforms.
11046 *
11047 */
11048static VALUE
11049rb_io_advise(int argc, VALUE *argv, VALUE io)
11050{
11051 VALUE advice, offset, len;
11052 rb_off_t off, l;
11053 rb_io_t *fptr;
11054
11055 rb_scan_args(argc, argv, "12", &advice, &offset, &len);
11056 advice_arg_check(advice);
11057
11058 io = GetWriteIO(io);
11059 GetOpenFile(io, fptr);
11060
11061 off = NIL_P(offset) ? 0 : NUM2OFFT(offset);
11062 l = NIL_P(len) ? 0 : NUM2OFFT(len);
11063
11064#ifdef HAVE_POSIX_FADVISE
11065 return do_io_advise(fptr, advice, off, l);
11066#else
11067 ((void)off, (void)l); /* Ignore all hint */
11068 return Qnil;
11069#endif
11070}
11071
11072static int
11073is_pos_inf(VALUE x)
11074{
11075 double f;
11076 if (!RB_FLOAT_TYPE_P(x))
11077 return 0;
11078 f = RFLOAT_VALUE(x);
11079 return isinf(f) && 0 < f;
11080}
11081
11082/*
11083 * call-seq:
11084 * IO.select(read_ios, write_ios = [], error_ios = [], timeout = nil) -> array or nil
11085 *
11086 * Invokes system call {select(2)}[https://linux.die.net/man/2/select],
11087 * which monitors multiple file descriptors,
11088 * waiting until one or more of the file descriptors
11089 * becomes ready for some class of I/O operation.
11090 *
11091 * Not implemented on all platforms.
11092 *
11093 * Each of the arguments +read_ios+, +write_ios+, and +error_ios+
11094 * is an array of IO objects.
11095 *
11096 * Argument +timeout+ is a numeric value (such as integer or float) timeout
11097 * interval in seconds.
11098 * +timeout+ can also be +nil+ or +Float::INFINITY+.
11099 * +nil+ and +Float::INFINITY+ means no timeout.
11100 *
11101 * The method monitors the \IO objects given in all three arrays,
11102 * waiting for some to be ready;
11103 * returns a 3-element array whose elements are:
11104 *
11105 * - An array of the objects in +read_ios+ that are ready for reading.
11106 * - An array of the objects in +write_ios+ that are ready for writing.
11107 * - An array of the objects in +error_ios+ have pending exceptions.
11108 *
11109 * If no object becomes ready within the given +timeout+, +nil+ is returned.
11110 *
11111 * \IO.select peeks the buffer of \IO objects for testing readability.
11112 * If the \IO buffer is not empty, \IO.select immediately notifies
11113 * readability. This "peek" only happens for \IO objects. It does not
11114 * happen for IO-like objects such as OpenSSL::SSL::SSLSocket.
11115 *
11116 * The best way to use \IO.select is invoking it after non-blocking
11117 * methods such as #read_nonblock, #write_nonblock, etc. The methods
11118 * raise an exception which is extended by IO::WaitReadable or
11119 * IO::WaitWritable. The modules notify how the caller should wait
11120 * with \IO.select. If IO::WaitReadable is raised, the caller should
11121 * wait for reading. If IO::WaitWritable is raised, the caller should
11122 * wait for writing.
11123 *
11124 * So, blocking read (#readpartial) can be emulated using
11125 * #read_nonblock and \IO.select as follows:
11126 *
11127 * begin
11128 * result = io_like.read_nonblock(maxlen)
11129 * rescue IO::WaitReadable
11130 * IO.select([io_like])
11131 * retry
11132 * rescue IO::WaitWritable
11133 * IO.select(nil, [io_like])
11134 * retry
11135 * end
11136 *
11137 * Especially, the combination of non-blocking methods and \IO.select is
11138 * preferred for IO like objects such as OpenSSL::SSL::SSLSocket. It
11139 * has #to_io method to return underlying IO object. IO.select calls
11140 * #to_io to obtain the file descriptor to wait.
11141 *
11142 * This means that readability notified by \IO.select doesn't mean
11143 * readability from OpenSSL::SSL::SSLSocket object.
11144 *
11145 * The most likely situation is that OpenSSL::SSL::SSLSocket buffers
11146 * some data. \IO.select doesn't see the buffer. So \IO.select can
11147 * block when OpenSSL::SSL::SSLSocket#readpartial doesn't block.
11148 *
11149 * However, several more complicated situations exist.
11150 *
11151 * SSL is a protocol which is sequence of records.
11152 * The record consists of multiple bytes.
11153 * So, the remote side of SSL sends a partial record, IO.select
11154 * notifies readability but OpenSSL::SSL::SSLSocket cannot decrypt a
11155 * byte and OpenSSL::SSL::SSLSocket#readpartial will block.
11156 *
11157 * Also, the remote side can request SSL renegotiation which forces
11158 * the local SSL engine to write some data.
11159 * This means OpenSSL::SSL::SSLSocket#readpartial may invoke #write
11160 * system call and it can block.
11161 * In such a situation, OpenSSL::SSL::SSLSocket#read_nonblock raises
11162 * IO::WaitWritable instead of blocking.
11163 * So, the caller should wait for ready for writability as above
11164 * example.
11165 *
11166 * The combination of non-blocking methods and \IO.select is also useful
11167 * for streams such as tty, pipe socket socket when multiple processes
11168 * read from a stream.
11169 *
11170 * Finally, Linux kernel developers don't guarantee that
11171 * readability of select(2) means readability of following read(2) even
11172 * for a single process;
11173 * see {select(2)}[https://linux.die.net/man/2/select]
11174 *
11175 * Invoking \IO.select before IO#readpartial works well as usual.
11176 * However it is not the best way to use \IO.select.
11177 *
11178 * The writability notified by select(2) doesn't show
11179 * how many bytes are writable.
11180 * IO#write method blocks until given whole string is written.
11181 * So, <tt>IO#write(two or more bytes)</tt> can block after
11182 * writability is notified by \IO.select. IO#write_nonblock is required
11183 * to avoid the blocking.
11184 *
11185 * Blocking write (#write) can be emulated using #write_nonblock and
11186 * IO.select as follows: IO::WaitReadable should also be rescued for
11187 * SSL renegotiation in OpenSSL::SSL::SSLSocket.
11188 *
11189 * while 0 < string.bytesize
11190 * begin
11191 * written = io_like.write_nonblock(string)
11192 * rescue IO::WaitReadable
11193 * IO.select([io_like])
11194 * retry
11195 * rescue IO::WaitWritable
11196 * IO.select(nil, [io_like])
11197 * retry
11198 * end
11199 * string = string.byteslice(written..-1)
11200 * end
11201 *
11202 * Example:
11203 *
11204 * rp, wp = IO.pipe
11205 * mesg = "ping "
11206 * 100.times {
11207 * # IO.select follows IO#read. Not the best way to use IO.select.
11208 * rs, ws, = IO.select([rp], [wp])
11209 * if r = rs[0]
11210 * ret = r.read(5)
11211 * print ret
11212 * case ret
11213 * when /ping/
11214 * mesg = "pong\n"
11215 * when /pong/
11216 * mesg = "ping "
11217 * end
11218 * end
11219 * if w = ws[0]
11220 * w.write(mesg)
11221 * end
11222 * }
11223 *
11224 * Output:
11225 *
11226 * ping pong
11227 * ping pong
11228 * ping pong
11229 * (snipped)
11230 * ping
11231 *
11232 */
11233
11234static VALUE
11235rb_f_select(int argc, VALUE *argv, VALUE obj)
11236{
11237 VALUE scheduler = rb_fiber_scheduler_current();
11238 if (scheduler != Qnil) {
11239 // It's optionally supported.
11240 VALUE result = rb_fiber_scheduler_io_selectv(scheduler, argc, argv);
11241 if (!UNDEF_P(result)) return result;
11242 }
11243
11244 VALUE timeout;
11245 struct select_args args;
11246 struct timeval timerec;
11247 int i;
11248
11249 rb_scan_args(argc, argv, "13", &args.read, &args.write, &args.except, &timeout);
11250 if (NIL_P(timeout) || is_pos_inf(timeout)) {
11251 args.timeout = 0;
11252 }
11253 else {
11254 timerec = rb_time_interval(timeout);
11255 args.timeout = &timerec;
11256 }
11257
11258 for (i = 0; i < numberof(args.fdsets); ++i)
11259 rb_fd_init(&args.fdsets[i]);
11260
11261 return rb_ensure(select_call, (VALUE)&args, select_end, (VALUE)&args);
11262}
11263
11264#ifdef IOCTL_REQ_TYPE
11265 typedef IOCTL_REQ_TYPE ioctl_req_t;
11266#else
11267 typedef int ioctl_req_t;
11268# define NUM2IOCTLREQ(num) ((int)NUM2LONG(num))
11269#endif
11270
11271#ifdef HAVE_IOCTL
11272struct ioctl_arg {
11273 int fd;
11274 ioctl_req_t cmd;
11275 long narg;
11276};
11277
11278static VALUE
11279nogvl_ioctl(void *ptr)
11280{
11281 struct ioctl_arg *arg = ptr;
11282
11283 return (VALUE)ioctl(arg->fd, arg->cmd, arg->narg);
11284}
11285
11286static int
11287do_ioctl(struct rb_io *io, ioctl_req_t cmd, long narg)
11288{
11289 int retval;
11290 struct ioctl_arg arg;
11291
11292 arg.fd = io->fd;
11293 arg.cmd = cmd;
11294 arg.narg = narg;
11295
11296 retval = (int)rb_io_blocking_region(io, nogvl_ioctl, &arg);
11297
11298 return retval;
11299}
11300#endif
11301
11302#define DEFAULT_IOCTL_NARG_LEN (256)
11303
11304#if defined(__linux__) && defined(_IOC_SIZE)
11305static long
11306linux_iocparm_len(ioctl_req_t cmd)
11307{
11308 long len;
11309
11310 if ((cmd & 0xFFFF0000) == 0) {
11311 /* legacy and unstructured ioctl number. */
11312 return DEFAULT_IOCTL_NARG_LEN;
11313 }
11314
11315 len = _IOC_SIZE(cmd);
11316
11317 /* paranoia check for silly drivers which don't keep ioctl convention */
11318 if (len < DEFAULT_IOCTL_NARG_LEN)
11319 len = DEFAULT_IOCTL_NARG_LEN;
11320
11321 return len;
11322}
11323#endif
11324
11325#ifdef HAVE_IOCTL
11326static long
11327ioctl_narg_len(ioctl_req_t cmd)
11328{
11329 long len;
11330
11331#ifdef IOCPARM_MASK
11332#ifndef IOCPARM_LEN
11333#define IOCPARM_LEN(x) (((x) >> 16) & IOCPARM_MASK)
11334#endif
11335#endif
11336#ifdef IOCPARM_LEN
11337 len = IOCPARM_LEN(cmd); /* on BSDish systems we're safe */
11338#elif defined(__linux__) && defined(_IOC_SIZE)
11339 len = linux_iocparm_len(cmd);
11340#else
11341 /* otherwise guess at what's safe */
11342 len = DEFAULT_IOCTL_NARG_LEN;
11343#endif
11344
11345 return len;
11346}
11347#endif
11348
11349#ifdef HAVE_FCNTL
11350#ifdef __linux__
11351typedef long fcntl_arg_t;
11352#else
11353/* posix */
11354typedef int fcntl_arg_t;
11355#endif
11356
11357static long
11358fcntl_narg_len(ioctl_req_t cmd)
11359{
11360 long len;
11361
11362 switch (cmd) {
11363#ifdef F_DUPFD
11364 case F_DUPFD:
11365 len = sizeof(fcntl_arg_t);
11366 break;
11367#endif
11368#ifdef F_DUP2FD /* bsd specific */
11369 case F_DUP2FD:
11370 len = sizeof(int);
11371 break;
11372#endif
11373#ifdef F_DUPFD_CLOEXEC /* linux specific */
11374 case F_DUPFD_CLOEXEC:
11375 len = sizeof(fcntl_arg_t);
11376 break;
11377#endif
11378#ifdef F_GETFD
11379 case F_GETFD:
11380 len = 1;
11381 break;
11382#endif
11383#ifdef F_SETFD
11384 case F_SETFD:
11385 len = sizeof(fcntl_arg_t);
11386 break;
11387#endif
11388#ifdef F_GETFL
11389 case F_GETFL:
11390 len = 1;
11391 break;
11392#endif
11393#ifdef F_SETFL
11394 case F_SETFL:
11395 len = sizeof(fcntl_arg_t);
11396 break;
11397#endif
11398#ifdef F_GETOWN
11399 case F_GETOWN:
11400 len = 1;
11401 break;
11402#endif
11403#ifdef F_SETOWN
11404 case F_SETOWN:
11405 len = sizeof(fcntl_arg_t);
11406 break;
11407#endif
11408#ifdef F_GETOWN_EX /* linux specific */
11409 case F_GETOWN_EX:
11410 len = sizeof(struct f_owner_ex);
11411 break;
11412#endif
11413#ifdef F_SETOWN_EX /* linux specific */
11414 case F_SETOWN_EX:
11415 len = sizeof(struct f_owner_ex);
11416 break;
11417#endif
11418#ifdef F_GETLK
11419 case F_GETLK:
11420 len = sizeof(struct flock);
11421 break;
11422#endif
11423#ifdef F_SETLK
11424 case F_SETLK:
11425 len = sizeof(struct flock);
11426 break;
11427#endif
11428#ifdef F_SETLKW
11429 case F_SETLKW:
11430 len = sizeof(struct flock);
11431 break;
11432#endif
11433#ifdef F_READAHEAD /* bsd specific */
11434 case F_READAHEAD:
11435 len = sizeof(int);
11436 break;
11437#endif
11438#ifdef F_RDAHEAD /* Darwin specific */
11439 case F_RDAHEAD:
11440 len = sizeof(int);
11441 break;
11442#endif
11443#ifdef F_GETSIG /* linux specific */
11444 case F_GETSIG:
11445 len = 1;
11446 break;
11447#endif
11448#ifdef F_SETSIG /* linux specific */
11449 case F_SETSIG:
11450 len = sizeof(fcntl_arg_t);
11451 break;
11452#endif
11453#ifdef F_GETLEASE /* linux specific */
11454 case F_GETLEASE:
11455 len = 1;
11456 break;
11457#endif
11458#ifdef F_SETLEASE /* linux specific */
11459 case F_SETLEASE:
11460 len = sizeof(fcntl_arg_t);
11461 break;
11462#endif
11463#ifdef F_NOTIFY /* linux specific */
11464 case F_NOTIFY:
11465 len = sizeof(fcntl_arg_t);
11466 break;
11467#endif
11468
11469 default:
11470 len = 256;
11471 break;
11472 }
11473
11474 return len;
11475}
11476#else /* HAVE_FCNTL */
11477static long
11478fcntl_narg_len(ioctl_req_t cmd)
11479{
11480 return 0;
11481}
11482#endif /* HAVE_FCNTL */
11483
11484#define NARG_SENTINEL 17
11485
11486static long
11487setup_narg(ioctl_req_t cmd, VALUE *argp, long (*narg_len)(ioctl_req_t))
11488{
11489 long narg = 0;
11490 VALUE arg = *argp;
11491
11492 if (!RTEST(arg)) {
11493 narg = 0;
11494 }
11495 else if (FIXNUM_P(arg)) {
11496 narg = FIX2LONG(arg);
11497 }
11498 else if (arg == Qtrue) {
11499 narg = 1;
11500 }
11501 else {
11502 VALUE tmp = rb_check_string_type(arg);
11503
11504 if (NIL_P(tmp)) {
11505 narg = NUM2LONG(arg);
11506 }
11507 else {
11508 char *ptr;
11509 long len, slen;
11510
11511 *argp = arg = tmp;
11512 len = narg_len(cmd);
11513 rb_str_modify(arg);
11514
11515 slen = RSTRING_LEN(arg);
11516 /* expand for data + sentinel. */
11517 if (slen < len+1) {
11518 rb_str_resize(arg, len+1);
11519 MEMZERO(RSTRING_PTR(arg)+slen, char, len-slen);
11520 slen = len+1;
11521 }
11522 /* a little sanity check here */
11523 ptr = RSTRING_PTR(arg);
11524 ptr[slen - 1] = NARG_SENTINEL;
11525 narg = (long)(SIGNED_VALUE)ptr;
11526 }
11527 }
11528
11529 return narg;
11530}
11531
11532static VALUE
11533finish_narg(int retval, VALUE arg, const rb_io_t *fptr)
11534{
11535 if (retval < 0) rb_sys_fail_path(fptr->pathv);
11536 if (RB_TYPE_P(arg, T_STRING)) {
11537 char *ptr;
11538 long slen;
11539 RSTRING_GETMEM(arg, ptr, slen);
11540 if (ptr[slen-1] != NARG_SENTINEL)
11541 rb_raise(rb_eArgError, "return value overflowed string");
11542 ptr[slen-1] = '\0';
11543 }
11544
11545 return INT2NUM(retval);
11546}
11547
11548#ifdef HAVE_IOCTL
11549static VALUE
11550rb_ioctl(VALUE io, VALUE req, VALUE arg)
11551{
11552 ioctl_req_t cmd = NUM2IOCTLREQ(req);
11553 rb_io_t *fptr;
11554 long narg;
11555 int retval;
11556
11557 narg = setup_narg(cmd, &arg, ioctl_narg_len);
11558 GetOpenFile(io, fptr);
11559 retval = do_ioctl(fptr, cmd, narg);
11560 return finish_narg(retval, arg, fptr);
11561}
11562
11563/*
11564 * call-seq:
11565 * ioctl(integer_cmd, argument) -> integer
11566 *
11567 * Invokes Posix system call {ioctl(2)}[https://linux.die.net/man/2/ioctl],
11568 * which issues a low-level command to an I/O device.
11569 *
11570 * Issues a low-level command to an I/O device.
11571 * The arguments and returned value are platform-dependent.
11572 * The effect of the call is platform-dependent.
11573 *
11574 * If argument +argument+ is an integer, it is passed directly;
11575 * if it is a string, it is interpreted as a binary sequence of bytes.
11576 *
11577 * Not implemented on all platforms.
11578 *
11579 */
11580
11581static VALUE
11582rb_io_ioctl(int argc, VALUE *argv, VALUE io)
11583{
11584 VALUE req, arg;
11585
11586 rb_scan_args(argc, argv, "11", &req, &arg);
11587 return rb_ioctl(io, req, arg);
11588}
11589#else
11590#define rb_io_ioctl rb_f_notimplement
11591#endif
11592
11593#ifdef HAVE_FCNTL
11594struct fcntl_arg {
11595 int fd;
11596 int cmd;
11597 long narg;
11598};
11599
11600static VALUE
11601nogvl_fcntl(void *ptr)
11602{
11603 struct fcntl_arg *arg = ptr;
11604
11605#if defined(F_DUPFD)
11606 if (arg->cmd == F_DUPFD)
11607 return (VALUE)rb_cloexec_fcntl_dupfd(arg->fd, (int)arg->narg);
11608#endif
11609 return (VALUE)fcntl(arg->fd, arg->cmd, arg->narg);
11610}
11611
11612static int
11613do_fcntl(struct rb_io *io, int cmd, long narg)
11614{
11615 int retval;
11616 struct fcntl_arg arg;
11617
11618 arg.fd = io->fd;
11619 arg.cmd = cmd;
11620 arg.narg = narg;
11621
11622 retval = (int)rb_io_blocking_region(io, nogvl_fcntl, &arg);
11623 if (retval != -1) {
11624 switch (cmd) {
11625#if defined(F_DUPFD)
11626 case F_DUPFD:
11627#endif
11628#if defined(F_DUPFD_CLOEXEC)
11629 case F_DUPFD_CLOEXEC:
11630#endif
11631 rb_update_max_fd(retval);
11632 }
11633 }
11634
11635 return retval;
11636}
11637
11638static VALUE
11639rb_fcntl(VALUE io, VALUE req, VALUE arg)
11640{
11641 int cmd = NUM2INT(req);
11642 rb_io_t *fptr;
11643 long narg;
11644 int retval;
11645
11646 narg = setup_narg(cmd, &arg, fcntl_narg_len);
11647 GetOpenFile(io, fptr);
11648 retval = do_fcntl(fptr, cmd, narg);
11649 return finish_narg(retval, arg, fptr);
11650}
11651
11652/*
11653 * call-seq:
11654 * fcntl(integer_cmd, argument) -> integer
11655 *
11656 * Invokes Posix system call {fcntl(2)}[https://linux.die.net/man/2/fcntl],
11657 * which provides a mechanism for issuing low-level commands to control or query
11658 * a file-oriented I/O stream. Arguments and results are platform
11659 * dependent.
11660 *
11661 * If +argument+ is a number, its value is passed directly;
11662 * if it is a string, it is interpreted as a binary sequence of bytes.
11663 * (Array#pack might be a useful way to build this string.)
11664 *
11665 * Not implemented on all platforms.
11666 *
11667 */
11668
11669static VALUE
11670rb_io_fcntl(int argc, VALUE *argv, VALUE io)
11671{
11672 VALUE req, arg;
11673
11674 rb_scan_args(argc, argv, "11", &req, &arg);
11675 return rb_fcntl(io, req, arg);
11676}
11677#else
11678#define rb_io_fcntl rb_f_notimplement
11679#endif
11680
11681#if defined(HAVE_SYSCALL) || defined(HAVE___SYSCALL)
11682/*
11683 * call-seq:
11684 * syscall(integer_callno, *arguments) -> integer
11685 *
11686 * Invokes Posix system call {syscall(2)}[https://linux.die.net/man/2/syscall],
11687 * which calls a specified function.
11688 *
11689 * Calls the operating system function identified by +integer_callno+;
11690 * returns the result of the function or raises SystemCallError if it failed.
11691 * The effect of the call is platform-dependent.
11692 * The arguments and returned value are platform-dependent.
11693 *
11694 * For each of +arguments+: if it is an integer, it is passed directly;
11695 * if it is a string, it is interpreted as a binary sequence of bytes.
11696 * There may be as many as nine such arguments.
11697 *
11698 * Arguments +integer_callno+ and +argument+, as well as the returned value,
11699 * are platform-dependent.
11700 *
11701 * Note: Method +syscall+ is essentially unsafe and unportable.
11702 * The DL (Fiddle) library is preferred for safer and a bit
11703 * more portable programming.
11704 *
11705 * Not implemented on all platforms.
11706 *
11707 */
11708
11709static VALUE
11710rb_f_syscall(int argc, VALUE *argv, VALUE _)
11711{
11712 VALUE arg[8];
11713#if SIZEOF_VOIDP == 8 && defined(HAVE___SYSCALL) && SIZEOF_INT != 8 /* mainly *BSD */
11714# define SYSCALL __syscall
11715# define NUM2SYSCALLID(x) NUM2LONG(x)
11716# define RETVAL2NUM(x) LONG2NUM(x)
11717# if SIZEOF_LONG == 8
11718 long num, retval = -1;
11719# elif SIZEOF_LONG_LONG == 8
11720 long long num, retval = -1;
11721# else
11722# error ---->> it is asserted that __syscall takes the first argument and returns retval in 64bit signed integer. <<----
11723# endif
11724#elif defined(__linux__)
11725# define SYSCALL syscall
11726# define NUM2SYSCALLID(x) NUM2LONG(x)
11727# define RETVAL2NUM(x) LONG2NUM(x)
11728 /*
11729 * Linux man page says, syscall(2) function prototype is below.
11730 *
11731 * int syscall(int number, ...);
11732 *
11733 * But, it's incorrect. Actual one takes and returned long. (see unistd.h)
11734 */
11735 long num, retval = -1;
11736#else
11737# define SYSCALL syscall
11738# define NUM2SYSCALLID(x) NUM2INT(x)
11739# define RETVAL2NUM(x) INT2NUM(x)
11740 int num, retval = -1;
11741#endif
11742 int i;
11743
11744 if (RTEST(ruby_verbose)) {
11746 "We plan to remove a syscall function at future release. DL(Fiddle) provides safer alternative.");
11747 }
11748
11749 if (argc == 0)
11750 rb_raise(rb_eArgError, "too few arguments for syscall");
11751 if (argc > numberof(arg))
11752 rb_raise(rb_eArgError, "too many arguments for syscall");
11753 num = NUM2SYSCALLID(argv[0]); ++argv;
11754 for (i = argc - 1; i--; ) {
11755 VALUE v = rb_check_string_type(argv[i]);
11756
11757 if (!NIL_P(v)) {
11758 StringValue(v);
11759 rb_str_modify(v);
11760 arg[i] = (VALUE)StringValueCStr(v);
11761 }
11762 else {
11763 arg[i] = (VALUE)NUM2LONG(argv[i]);
11764 }
11765 }
11766
11767 switch (argc) {
11768 case 1:
11769 retval = SYSCALL(num);
11770 break;
11771 case 2:
11772 retval = SYSCALL(num, arg[0]);
11773 break;
11774 case 3:
11775 retval = SYSCALL(num, arg[0],arg[1]);
11776 break;
11777 case 4:
11778 retval = SYSCALL(num, arg[0],arg[1],arg[2]);
11779 break;
11780 case 5:
11781 retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3]);
11782 break;
11783 case 6:
11784 retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3],arg[4]);
11785 break;
11786 case 7:
11787 retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3],arg[4],arg[5]);
11788 break;
11789 case 8:
11790 retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6]);
11791 break;
11792 }
11793
11794 if (retval == -1)
11795 rb_sys_fail(0);
11796 return RETVAL2NUM(retval);
11797#undef SYSCALL
11798#undef NUM2SYSCALLID
11799#undef RETVAL2NUM
11800}
11801#else
11802#define rb_f_syscall rb_f_notimplement
11803#endif
11804
11805static VALUE
11806io_new_instance(VALUE args)
11807{
11808 return rb_class_new_instance(2, (VALUE*)args+1, *(VALUE*)args);
11809}
11810
11811static rb_encoding *
11812find_encoding(VALUE v)
11813{
11814 rb_encoding *enc = rb_find_encoding(v);
11815 if (!enc) rb_warn("Unsupported encoding %"PRIsVALUE" ignored", v);
11816 return enc;
11817}
11818
11819static void
11820io_encoding_set(rb_io_t *fptr, VALUE v1, VALUE v2, VALUE opt)
11821{
11822 rb_encoding *enc, *enc2;
11823 int ecflags = fptr->encs.ecflags;
11824 VALUE ecopts, tmp;
11825
11826 if (!NIL_P(v2)) {
11827 enc2 = find_encoding(v1);
11828 tmp = rb_check_string_type(v2);
11829 if (!NIL_P(tmp)) {
11830 if (RSTRING_LEN(tmp) == 1 && RSTRING_PTR(tmp)[0] == '-') {
11831 /* Special case - "-" => no transcoding */
11832 enc = enc2;
11833 enc2 = NULL;
11834 }
11835 else
11836 enc = find_encoding(v2);
11837 if (enc == enc2) {
11838 /* Special case - "-" => no transcoding */
11839 enc2 = NULL;
11840 }
11841 }
11842 else {
11843 enc = find_encoding(v2);
11844 if (enc == enc2) {
11845 /* Special case - "-" => no transcoding */
11846 enc2 = NULL;
11847 }
11848 }
11849 if (enc2 == rb_ascii8bit_encoding()) {
11850 /* If external is ASCII-8BIT, no transcoding */
11851 enc = enc2;
11852 enc2 = NULL;
11853 }
11854 SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags);
11855 ecflags = rb_econv_prepare_options(opt, &ecopts, ecflags);
11856 }
11857 else {
11858 if (NIL_P(v1)) {
11859 /* Set to default encodings */
11860 rb_io_ext_int_to_encs(NULL, NULL, &enc, &enc2, 0);
11861 SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags);
11862 ecopts = Qnil;
11863 }
11864 else {
11865 tmp = rb_check_string_type(v1);
11866 if (!NIL_P(tmp) && rb_enc_asciicompat(enc = rb_enc_get(tmp))) {
11867 parse_mode_enc(RSTRING_PTR(tmp), enc, &enc, &enc2, NULL);
11868 SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags);
11869 ecflags = rb_econv_prepare_options(opt, &ecopts, ecflags);
11870 }
11871 else {
11872 rb_io_ext_int_to_encs(find_encoding(v1), NULL, &enc, &enc2, 0);
11873 SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags);
11874 ecopts = Qnil;
11875 }
11876 }
11877 }
11878 validate_enc_binmode(&fptr->mode, ecflags, enc, enc2);
11879 fptr->encs.enc = enc;
11880 fptr->encs.enc2 = enc2;
11881 fptr->encs.ecflags = ecflags;
11882 fptr->encs.ecopts = ecopts;
11883 clear_codeconv(fptr);
11884
11885}
11886
11888 rb_io_t *fptr;
11889 VALUE v1;
11890 VALUE v2;
11891 VALUE opt;
11892};
11893
11894static VALUE
11895io_encoding_set_v(VALUE v)
11896{
11897 struct io_encoding_set_args *arg = (struct io_encoding_set_args *)v;
11898 io_encoding_set(arg->fptr, arg->v1, arg->v2, arg->opt);
11899 return Qnil;
11900}
11901
11902static VALUE
11903pipe_pair_close(VALUE rw)
11904{
11905 VALUE *rwp = (VALUE *)rw;
11906 return rb_ensure(io_close, rwp[0], io_close, rwp[1]);
11907}
11908
11909/*
11910 * call-seq:
11911 * IO.pipe(**opts) -> [read_io, write_io]
11912 * IO.pipe(enc, **opts) -> [read_io, write_io]
11913 * IO.pipe(ext_enc, int_enc, **opts) -> [read_io, write_io]
11914 * IO.pipe(**opts) {|read_io, write_io| ...} -> object
11915 * IO.pipe(enc, **opts) {|read_io, write_io| ...} -> object
11916 * IO.pipe(ext_enc, int_enc, **opts) {|read_io, write_io| ...} -> object
11917 *
11918 * Creates a pair of pipe endpoints, +read_io+ and +write_io+,
11919 * connected to each other.
11920 *
11921 * If argument +enc_string+ is given, it must be a string containing one of:
11922 *
11923 * - The name of the encoding to be used as the external encoding.
11924 * - The colon-separated names of two encodings to be used as the external
11925 * and internal encodings.
11926 *
11927 * If argument +int_enc+ is given, it must be an Encoding object
11928 * or encoding name string that specifies the internal encoding to be used;
11929 * if argument +ext_enc+ is also given, it must be an Encoding object
11930 * or encoding name string that specifies the external encoding to be used.
11931 *
11932 * The string read from +read_io+ is tagged with the external encoding;
11933 * if an internal encoding is also specified, the string is converted
11934 * to, and tagged with, that encoding.
11935 *
11936 * If any encoding is specified,
11937 * optional hash arguments specify the conversion option.
11938 *
11939 * Optional keyword arguments +opts+ specify:
11940 *
11941 * - {Open Options}[rdoc-ref:IO@Open+Options].
11942 * - {Encoding Options}[rdoc-ref:encodings.rdoc@Encoding+Options].
11943 *
11944 * With no block given, returns the two endpoints in an array:
11945 *
11946 * IO.pipe # => [#<IO:fd 4>, #<IO:fd 5>]
11947 *
11948 * With a block given, calls the block with the two endpoints;
11949 * closes both endpoints and returns the value of the block:
11950 *
11951 * IO.pipe {|read_io, write_io| p read_io; p write_io }
11952 *
11953 * Output:
11954 *
11955 * #<IO:fd 6>
11956 * #<IO:fd 7>
11957 *
11958 * Not available on all platforms.
11959 *
11960 * In the example below, the two processes close the ends of the pipe
11961 * that they are not using. This is not just a cosmetic nicety. The
11962 * read end of a pipe will not generate an end of file condition if
11963 * there are any writers with the pipe still open. In the case of the
11964 * parent process, the <tt>rd.read</tt> will never return if it
11965 * does not first issue a <tt>wr.close</tt>:
11966 *
11967 * rd, wr = IO.pipe
11968 *
11969 * if fork
11970 * wr.close
11971 * puts "Parent got: <#{rd.read}>"
11972 * rd.close
11973 * Process.wait
11974 * else
11975 * rd.close
11976 * puts 'Sending message to parent'
11977 * wr.write "Hi Dad"
11978 * wr.close
11979 * end
11980 *
11981 * <em>produces:</em>
11982 *
11983 * Sending message to parent
11984 * Parent got: <Hi Dad>
11985 *
11986 */
11987
11988static VALUE
11989rb_io_s_pipe(int argc, VALUE *argv, VALUE klass)
11990{
11991 int pipes[2], state;
11992 VALUE r, w, args[3], v1, v2;
11993 VALUE opt;
11994 rb_io_t *fptr, *fptr2;
11995 struct io_encoding_set_args ies_args;
11996 enum rb_io_mode fmode = 0;
11997 VALUE ret;
11998
11999 argc = rb_scan_args(argc, argv, "02:", &v1, &v2, &opt);
12000 if (rb_pipe(pipes) < 0)
12001 rb_sys_fail(0);
12002
12003 args[0] = klass;
12004 args[1] = INT2NUM(pipes[0]);
12005 args[2] = INT2FIX(O_RDONLY);
12006 r = rb_protect(io_new_instance, (VALUE)args, &state);
12007 if (state) {
12008 close(pipes[0]);
12009 close(pipes[1]);
12010 rb_jump_tag(state);
12011 }
12012 GetOpenFile(r, fptr);
12013
12014 ies_args.fptr = fptr;
12015 ies_args.v1 = v1;
12016 ies_args.v2 = v2;
12017 ies_args.opt = opt;
12018 rb_protect(io_encoding_set_v, (VALUE)&ies_args, &state);
12019 if (state) {
12020 close(pipes[1]);
12021 io_close(r);
12022 rb_jump_tag(state);
12023 }
12024
12025 args[1] = INT2NUM(pipes[1]);
12026 args[2] = INT2FIX(O_WRONLY);
12027 w = rb_protect(io_new_instance, (VALUE)args, &state);
12028 if (state) {
12029 close(pipes[1]);
12030 if (!NIL_P(r)) rb_io_close(r);
12031 rb_jump_tag(state);
12032 }
12033 GetOpenFile(w, fptr2);
12034 rb_io_synchronized(fptr2);
12035
12036 extract_binmode(opt, &fmode);
12037
12038 if ((fmode & FMODE_BINMODE) && NIL_P(v1)) {
12041 }
12042
12043#if DEFAULT_TEXTMODE
12044 if ((fptr->mode & FMODE_TEXTMODE) && (fmode & FMODE_BINMODE)) {
12045 fptr->mode &= ~FMODE_TEXTMODE;
12046 setmode(fptr->fd, O_BINARY);
12047 }
12048#if RUBY_CRLF_ENVIRONMENT
12051 }
12052#endif
12053#endif
12054 fptr->mode |= fmode;
12055#if DEFAULT_TEXTMODE
12056 if ((fptr2->mode & FMODE_TEXTMODE) && (fmode & FMODE_BINMODE)) {
12057 fptr2->mode &= ~FMODE_TEXTMODE;
12058 setmode(fptr2->fd, O_BINARY);
12059 }
12060#endif
12061 fptr2->mode |= fmode;
12062
12063 ret = rb_assoc_new(r, w);
12064 if (rb_block_given_p()) {
12065 VALUE rw[2];
12066 rw[0] = r;
12067 rw[1] = w;
12068 return rb_ensure(rb_yield, ret, pipe_pair_close, (VALUE)rw);
12069 }
12070 return ret;
12071}
12072
12074 int argc;
12075 VALUE *argv;
12076 VALUE io;
12077};
12078
12079static void
12080open_key_args(VALUE klass, int argc, VALUE *argv, VALUE opt, struct foreach_arg *arg)
12081{
12082 VALUE path, v;
12083 VALUE vmode = Qnil, vperm = Qnil;
12084
12085 path = *argv++;
12086 argc--;
12087 FilePathValue(path);
12088 arg->io = 0;
12089 arg->argc = argc;
12090 arg->argv = argv;
12091 if (NIL_P(opt)) {
12092 vmode = INT2NUM(O_RDONLY);
12093 vperm = INT2FIX(0666);
12094 }
12095 else if (!NIL_P(v = rb_hash_aref(opt, sym_open_args))) {
12096 int n;
12097
12098 v = rb_to_array_type(v);
12099 n = RARRAY_LENINT(v);
12100 rb_check_arity(n, 0, 3); /* rb_io_open */
12101 rb_scan_args_kw(RB_SCAN_ARGS_LAST_HASH_KEYWORDS, n, RARRAY_CONST_PTR(v), "02:", &vmode, &vperm, &opt);
12102 }
12103 arg->io = rb_io_open(klass, path, vmode, vperm, opt);
12104}
12105
12106static VALUE
12107io_s_foreach(VALUE v)
12108{
12109 struct getline_arg *arg = (void *)v;
12110 VALUE str;
12111
12112 if (arg->limit == 0)
12113 rb_raise(rb_eArgError, "invalid limit: 0 for foreach");
12114 while (!NIL_P(str = rb_io_getline_1(arg->rs, arg->limit, arg->chomp, arg->io))) {
12115 rb_lastline_set(str);
12116 rb_yield(str);
12117 }
12119 return Qnil;
12120}
12121
12122/*
12123 * call-seq:
12124 * IO.foreach(path, sep = $/, **opts) {|line| block } -> nil
12125 * IO.foreach(path, limit, **opts) {|line| block } -> nil
12126 * IO.foreach(path, sep, limit, **opts) {|line| block } -> nil
12127 * IO.foreach(...) -> an_enumerator
12128 *
12129 * Calls the block with each successive line read from the stream.
12130 *
12131 * The first argument must be a string that is the path to a file.
12132 *
12133 * With only argument +path+ given, parses lines from the file at the given +path+,
12134 * as determined by the default line separator,
12135 * and calls the block with each successive line:
12136 *
12137 * File.foreach('t.txt') {|line| p line }
12138 *
12139 * Output: the same as above.
12140 *
12141 * For both forms, command and path, the remaining arguments are the same.
12142 *
12143 * With argument +sep+ given, parses lines as determined by that line separator
12144 * (see {Line Separator}[rdoc-ref:IO@Line+Separator]):
12145 *
12146 * File.foreach('t.txt', 'li') {|line| p line }
12147 *
12148 * Output:
12149 *
12150 * "First li"
12151 * "ne\nSecond li"
12152 * "ne\n\nThird li"
12153 * "ne\nFourth li"
12154 * "ne\n"
12155 *
12156 * Each paragraph:
12157 *
12158 * File.foreach('t.txt', '') {|paragraph| p paragraph }
12159 *
12160 * Output:
12161 *
12162 * "First line\nSecond line\n\n"
12163 * "Third line\nFourth line\n"
12164 *
12165 * With argument +limit+ given, parses lines as determined by the default
12166 * line separator and the given line-length limit
12167 * (see {Line Separator}[rdoc-ref:IO@Line+Separator] and {Line Limit}[rdoc-ref:IO@Line+Limit]):
12168 *
12169 * File.foreach('t.txt', 7) {|line| p line }
12170 *
12171 * Output:
12172 *
12173 * "First l"
12174 * "ine\n"
12175 * "Second "
12176 * "line\n"
12177 * "\n"
12178 * "Third l"
12179 * "ine\n"
12180 * "Fourth l"
12181 * "line\n"
12182 *
12183 * With arguments +sep+ and +limit+ given,
12184 * combines the two behaviors
12185 * (see {Line Separator and Line Limit}[rdoc-ref:IO@Line+Separator+and+Line+Limit]).
12186 *
12187 * Optional keyword arguments +opts+ specify:
12188 *
12189 * - {Open Options}[rdoc-ref:IO@Open+Options].
12190 * - {Encoding options}[rdoc-ref:encodings.rdoc@Encoding+Options].
12191 * - {Line Options}[rdoc-ref:IO@Line+IO].
12192 *
12193 * Returns an Enumerator if no block is given.
12194 *
12195 */
12196
12197static VALUE
12198rb_io_s_foreach(int argc, VALUE *argv, VALUE self)
12199{
12200 VALUE opt;
12201 int orig_argc = argc;
12202 struct foreach_arg arg;
12203 struct getline_arg garg;
12204
12205 argc = rb_scan_args(argc, argv, "12:", NULL, NULL, NULL, &opt);
12206 RETURN_ENUMERATOR(self, orig_argc, argv);
12207 extract_getline_args(argc-1, argv+1, &garg);
12208 open_key_args(self, argc, argv, opt, &arg);
12209 if (NIL_P(arg.io)) return Qnil;
12210 extract_getline_opts(opt, &garg);
12211 check_getline_args(&garg.rs, &garg.limit, garg.io = arg.io);
12212 return rb_ensure(io_s_foreach, (VALUE)&garg, rb_io_close, arg.io);
12213}
12214
12215static VALUE
12216io_s_readlines(VALUE v)
12217{
12218 struct getline_arg *arg = (void *)v;
12219 return io_readlines(arg, arg->io);
12220}
12221
12222/*
12223 * call-seq:
12224 * IO.readlines(path, sep = $/, **opts) -> array
12225 * IO.readlines(path, limit, **opts) -> array
12226 * IO.readlines(path, sep, limit, **opts) -> array
12227 *
12228 * Returns an array of all lines read from the stream.
12229 *
12230 * The first argument must be a string that is the path to a file.
12231 *
12232 * With only argument +path+ given, parses lines from the file at the given +path+,
12233 * as determined by the default line separator,
12234 * and returns those lines in an array:
12235 *
12236 * IO.readlines('t.txt')
12237 * # => ["First line\n", "Second line\n", "\n", "Third line\n", "Fourth line\n"]
12238 *
12239 * With argument +sep+ given, parses lines as determined by that line separator
12240 * (see {Line Separator}[rdoc-ref:IO@Line+Separator]):
12241 *
12242 * # Ordinary separator.
12243 * IO.readlines('t.txt', 'li')
12244 * # =>["First li", "ne\nSecond li", "ne\n\nThird li", "ne\nFourth li", "ne\n"]
12245 * # Get-paragraphs separator.
12246 * IO.readlines('t.txt', '')
12247 * # => ["First line\nSecond line\n\n", "Third line\nFourth line\n"]
12248 * # Get-all separator.
12249 * IO.readlines('t.txt', nil)
12250 * # => ["First line\nSecond line\n\nThird line\nFourth line\n"]
12251 *
12252 * With argument +limit+ given, parses lines as determined by the default
12253 * line separator and the given line-length limit
12254 * (see {Line Separator}[rdoc-ref:IO@Line+Separator] and {Line Limit}[rdoc-ref:IO@Line+Limit]:
12255 *
12256 * IO.readlines('t.txt', 7)
12257 * # => ["First l", "ine\n", "Second ", "line\n", "\n", "Third l", "ine\n", "Fourth ", "line\n"]
12258 *
12259 * With arguments +sep+ and +limit+ given,
12260 * combines the two behaviors
12261 * (see {Line Separator and Line Limit}[rdoc-ref:IO@Line+Separator+and+Line+Limit]).
12262 *
12263 * Optional keyword arguments +opts+ specify:
12264 *
12265 * - {Open Options}[rdoc-ref:IO@Open+Options].
12266 * - {Encoding options}[rdoc-ref:encodings.rdoc@Encoding+Options].
12267 * - {Line Options}[rdoc-ref:IO@Line+IO].
12268 *
12269 */
12270
12271static VALUE
12272rb_io_s_readlines(int argc, VALUE *argv, VALUE io)
12273{
12274 VALUE opt;
12275 struct foreach_arg arg;
12276 struct getline_arg garg;
12277
12278 argc = rb_scan_args(argc, argv, "12:", NULL, NULL, NULL, &opt);
12279 extract_getline_args(argc-1, argv+1, &garg);
12280 open_key_args(io, argc, argv, opt, &arg);
12281 if (NIL_P(arg.io)) return Qnil;
12282 extract_getline_opts(opt, &garg);
12283 check_getline_args(&garg.rs, &garg.limit, garg.io = arg.io);
12284 return rb_ensure(io_s_readlines, (VALUE)&garg, rb_io_close, arg.io);
12285}
12286
12287static VALUE
12288io_s_read(VALUE v)
12289{
12290 struct foreach_arg *arg = (void *)v;
12291 return io_read(arg->argc, arg->argv, arg->io);
12292}
12293
12294struct seek_arg {
12295 VALUE io;
12296 VALUE offset;
12297 int mode;
12298};
12299
12300static VALUE
12301seek_before_access(VALUE argp)
12302{
12303 struct seek_arg *arg = (struct seek_arg *)argp;
12304 rb_io_binmode(arg->io);
12305 return rb_io_seek(arg->io, arg->offset, arg->mode);
12306}
12307
12308/*
12309 * call-seq:
12310 * IO.read(path, length = nil, offset = 0, **opts) -> string or nil
12311 *
12312 * Opens the stream, reads and returns some or all of its content,
12313 * and closes the stream; returns +nil+ if no bytes were read.
12314 *
12315 * The first argument must be a string that is the path to a file.
12316 *
12317 * With only argument +path+ given, reads in text mode and returns the entire content
12318 * of the file at the given path:
12319 *
12320 * IO.read('t.txt')
12321 * # => "First line\nSecond line\n\nThird line\nFourth line\n"
12322 *
12323 * On Windows, text mode can terminate reading and leave bytes in the file
12324 * unread when encountering certain special bytes. Consider using
12325 * IO.binread if all bytes in the file should be read.
12326 *
12327 * With argument +length+, returns +length+ bytes if available:
12328 *
12329 * IO.read('t.txt', 7) # => "First l"
12330 * IO.read('t.txt', 700)
12331 * # => "First line\r\nSecond line\r\n\r\nFourth line\r\nFifth line\r\n"
12332 *
12333 * With arguments +length+ and +offset+, returns +length+ bytes
12334 * if available, beginning at the given +offset+:
12335 *
12336 * IO.read('t.txt', 10, 2) # => "rst line\nS"
12337 * IO.read('t.txt', 10, 200) # => nil
12338 *
12339 * Optional keyword arguments +opts+ specify:
12340 *
12341 * - {Open Options}[rdoc-ref:IO@Open+Options].
12342 * - {Encoding options}[rdoc-ref:encodings.rdoc@Encoding+Options].
12343 *
12344 */
12345
12346static VALUE
12347rb_io_s_read(int argc, VALUE *argv, VALUE io)
12348{
12349 VALUE opt, offset;
12350 long off;
12351 struct foreach_arg arg;
12352
12353 argc = rb_scan_args(argc, argv, "13:", NULL, NULL, &offset, NULL, &opt);
12354 if (!NIL_P(offset) && (off = NUM2LONG(offset)) < 0) {
12355 rb_raise(rb_eArgError, "negative offset %ld given", off);
12356 }
12357 open_key_args(io, argc, argv, opt, &arg);
12358 if (NIL_P(arg.io)) return Qnil;
12359 if (!NIL_P(offset)) {
12360 struct seek_arg sarg;
12361 int state = 0;
12362 sarg.io = arg.io;
12363 sarg.offset = offset;
12364 sarg.mode = SEEK_SET;
12365 rb_protect(seek_before_access, (VALUE)&sarg, &state);
12366 if (state) {
12367 rb_io_close(arg.io);
12368 rb_jump_tag(state);
12369 }
12370 if (arg.argc == 2) arg.argc = 1;
12371 }
12372 return rb_ensure(io_s_read, (VALUE)&arg, rb_io_close, arg.io);
12373}
12374
12375/*
12376 * call-seq:
12377 * IO.binread(path, length = nil, offset = 0) -> string or nil
12378 *
12379 * Behaves like IO.read, except that the stream is opened in binary mode
12380 * with ASCII-8BIT encoding.
12381 *
12382 */
12383
12384static VALUE
12385rb_io_s_binread(int argc, VALUE *argv, VALUE io)
12386{
12387 VALUE offset;
12388 struct foreach_arg arg;
12389 enum rb_io_mode fmode = FMODE_READABLE|FMODE_BINMODE;
12390 enum {
12391 oflags = O_RDONLY
12392#ifdef O_BINARY
12393 |O_BINARY
12394#endif
12395 };
12396 struct rb_io_encoding convconfig = {NULL, NULL, 0, Qnil};
12397
12398 rb_scan_args(argc, argv, "12", NULL, NULL, &offset);
12399 FilePathValue(argv[0]);
12400 convconfig.enc = rb_ascii8bit_encoding();
12401 arg.io = rb_io_open_generic(io, argv[0], oflags, fmode, &convconfig, 0);
12402 if (NIL_P(arg.io)) return Qnil;
12403 arg.argv = argv+1;
12404 arg.argc = (argc > 1) ? 1 : 0;
12405 if (!NIL_P(offset)) {
12406 struct seek_arg sarg;
12407 int state = 0;
12408 sarg.io = arg.io;
12409 sarg.offset = offset;
12410 sarg.mode = SEEK_SET;
12411 rb_protect(seek_before_access, (VALUE)&sarg, &state);
12412 if (state) {
12413 rb_io_close(arg.io);
12414 rb_jump_tag(state);
12415 }
12416 }
12417 return rb_ensure(io_s_read, (VALUE)&arg, rb_io_close, arg.io);
12418}
12419
12420static VALUE
12421io_s_write0(VALUE v)
12422{
12423 struct write_arg *arg = (void *)v;
12424 return io_write(arg->io,arg->str,arg->nosync);
12425}
12426
12427static VALUE
12428io_s_write(int argc, VALUE *argv, VALUE klass, int binary)
12429{
12430 VALUE string, offset, opt;
12431 struct foreach_arg arg;
12432 struct write_arg warg;
12433
12434 rb_scan_args(argc, argv, "21:", NULL, &string, &offset, &opt);
12435
12436 if (NIL_P(opt)) opt = rb_hash_new();
12437 else opt = rb_hash_dup(opt);
12438
12439
12440 if (NIL_P(rb_hash_aref(opt,sym_mode))) {
12441 int mode = O_WRONLY|O_CREAT;
12442#ifdef O_BINARY
12443 if (binary) mode |= O_BINARY;
12444#endif
12445 if (NIL_P(offset)) mode |= O_TRUNC;
12446 rb_hash_aset(opt,sym_mode,INT2NUM(mode));
12447 }
12448 open_key_args(klass, argc, argv, opt, &arg);
12449
12450#ifndef O_BINARY
12451 if (binary) rb_io_binmode_m(arg.io);
12452#endif
12453
12454 if (NIL_P(arg.io)) return Qnil;
12455 if (!NIL_P(offset)) {
12456 struct seek_arg sarg;
12457 int state = 0;
12458 sarg.io = arg.io;
12459 sarg.offset = offset;
12460 sarg.mode = SEEK_SET;
12461 rb_protect(seek_before_access, (VALUE)&sarg, &state);
12462 if (state) {
12463 rb_io_close(arg.io);
12464 rb_jump_tag(state);
12465 }
12466 }
12467
12468 warg.io = arg.io;
12469 warg.str = string;
12470 warg.nosync = 0;
12471
12472 return rb_ensure(io_s_write0, (VALUE)&warg, rb_io_close, arg.io);
12473}
12474
12475/*
12476 * call-seq:
12477 * IO.write(path, data, offset = 0, **opts) -> integer
12478 *
12479 * Opens the stream, writes the given +data+ to it,
12480 * and closes the stream; returns the number of bytes written.
12481 *
12482 * The first argument must be a string that is the path to a file.
12483 *
12484 * With only argument +path+ given, writes the given +data+ to the file at that path:
12485 *
12486 * IO.write('t.tmp', 'abc') # => 3
12487 * File.read('t.tmp') # => "abc"
12488 *
12489 * If +offset+ is zero (the default), the file is overwritten:
12490 *
12491 * IO.write('t.tmp', 'A') # => 1
12492 * File.read('t.tmp') # => "A"
12493 *
12494 * If +offset+ in within the file content, the file is partly overwritten:
12495 *
12496 * IO.write('t.tmp', 'abcdef') # => 3
12497 * File.read('t.tmp') # => "abcdef"
12498 * # Offset within content.
12499 * IO.write('t.tmp', '012', 2) # => 3
12500 * File.read('t.tmp') # => "ab012f"
12501 *
12502 * If +offset+ is outside the file content,
12503 * the file is padded with null characters <tt>"\u0000"</tt>:
12504 *
12505 * IO.write('t.tmp', 'xyz', 10) # => 3
12506 * File.read('t.tmp') # => "ab012f\u0000\u0000\u0000\u0000xyz"
12507 *
12508 * Optional keyword arguments +opts+ specify:
12509 *
12510 * - {Open Options}[rdoc-ref:IO@Open+Options].
12511 * - {Encoding options}[rdoc-ref:encodings.rdoc@Encoding+Options].
12512 *
12513 */
12514
12515static VALUE
12516rb_io_s_write(int argc, VALUE *argv, VALUE io)
12517{
12518 return io_s_write(argc, argv, io, 0);
12519}
12520
12521/*
12522 * call-seq:
12523 * IO.binwrite(path, string, offset = 0) -> integer
12524 *
12525 * Behaves like IO.write, except that the stream is opened in binary mode
12526 * with ASCII-8BIT encoding.
12527 *
12528 */
12529
12530static VALUE
12531rb_io_s_binwrite(int argc, VALUE *argv, VALUE io)
12532{
12533 return io_s_write(argc, argv, io, 1);
12534}
12535
12537 VALUE src;
12538 VALUE dst;
12539 rb_off_t copy_length; /* (rb_off_t)-1 if not specified */
12540 rb_off_t src_offset; /* (rb_off_t)-1 if not specified */
12541
12542 rb_io_t *src_fptr;
12543 rb_io_t *dst_fptr;
12544 unsigned close_src : 1;
12545 unsigned close_dst : 1;
12546 int error_no;
12547 rb_off_t total;
12548 const char *syserr;
12549 const char *notimp;
12550 VALUE th;
12551 struct stat src_stat;
12552 struct stat dst_stat;
12553#ifdef HAVE_FCOPYFILE
12554 copyfile_state_t copyfile_state;
12555#endif
12556};
12557
12558static void *
12559exec_interrupts(void *arg)
12560{
12561 VALUE th = (VALUE)arg;
12562 rb_thread_execute_interrupts(th);
12563 return NULL;
12564}
12565
12566/*
12567 * returns TRUE if the preceding system call was interrupted
12568 * so we can continue. If the thread was interrupted, we
12569 * reacquire the GVL to execute interrupts before continuing.
12570 */
12571static int
12572maygvl_copy_stream_continue_p(int has_gvl, struct copy_stream_struct *stp)
12573{
12574 switch (errno) {
12575 case EINTR:
12576#if defined(ERESTART)
12577 case ERESTART:
12578#endif
12579 if (rb_thread_interrupted(stp->th)) {
12580 if (has_gvl)
12581 rb_thread_execute_interrupts(stp->th);
12582 else
12583 rb_thread_call_with_gvl(exec_interrupts, (void *)stp->th);
12584 }
12585 return TRUE;
12586 }
12587 return FALSE;
12588}
12589
12591 VALUE scheduler;
12592
12593 rb_io_t *fptr;
12594 short events;
12595
12596 VALUE result;
12597};
12598
12599static void *
12600fiber_scheduler_wait_for(void * _arguments)
12601{
12602 struct fiber_scheduler_wait_for_arguments *arguments = (struct fiber_scheduler_wait_for_arguments *)_arguments;
12603
12604 arguments->result = rb_fiber_scheduler_io_wait(arguments->scheduler, arguments->fptr->self, INT2NUM(arguments->events), RUBY_IO_TIMEOUT_DEFAULT);
12605
12606 return NULL;
12607}
12608
12609#if USE_POLL
12610# define IOWAIT_SYSCALL "poll"
12611STATIC_ASSERT(pollin_expected, POLLIN == RB_WAITFD_IN);
12612STATIC_ASSERT(pollout_expected, POLLOUT == RB_WAITFD_OUT);
12613static int
12614nogvl_wait_for(VALUE th, rb_io_t *fptr, short events, struct timeval *timeout)
12615{
12617 if (scheduler != Qnil) {
12618 struct fiber_scheduler_wait_for_arguments args = {.scheduler = scheduler, .fptr = fptr, .events = events};
12619 rb_thread_call_with_gvl(fiber_scheduler_wait_for, &args);
12620 return RTEST(args.result);
12621 }
12622
12623 int fd = fptr->fd;
12624 if (fd == -1) return 0;
12625
12626 struct pollfd fds;
12627
12628 fds.fd = fd;
12629 fds.events = events;
12630
12631 int timeout_milliseconds = -1;
12632
12633 if (timeout) {
12634 timeout_milliseconds = (int)(timeout->tv_sec * 1000) + (int)(timeout->tv_usec / 1000);
12635 }
12636
12637 return poll(&fds, 1, timeout_milliseconds);
12638}
12639#else /* !USE_POLL */
12640# define IOWAIT_SYSCALL "select"
12641static int
12642nogvl_wait_for(VALUE th, rb_io_t *fptr, short events, struct timeval *timeout)
12643{
12645 if (scheduler != Qnil) {
12646 struct fiber_scheduler_wait_for_arguments args = {.scheduler = scheduler, .fptr = fptr, .events = events};
12647 rb_thread_call_with_gvl(fiber_scheduler_wait_for, &args);
12648 return RTEST(args.result);
12649 }
12650
12651 int fd = fptr->fd;
12652
12653 if (fd == -1) {
12654 errno = EBADF;
12655 return -1;
12656 }
12657
12658 rb_fdset_t fds;
12659 int ret;
12660
12661 rb_fd_init(&fds);
12662 rb_fd_set(fd, &fds);
12663
12664 switch (events) {
12665 case RB_WAITFD_IN:
12666 ret = rb_fd_select(fd + 1, &fds, 0, 0, timeout);
12667 break;
12668 case RB_WAITFD_OUT:
12669 ret = rb_fd_select(fd + 1, 0, &fds, 0, timeout);
12670 break;
12671 default:
12672 VM_UNREACHABLE(nogvl_wait_for);
12673 }
12674
12675 rb_fd_term(&fds);
12676
12677 // On timeout, this returns 0.
12678 return ret;
12679}
12680#endif /* !USE_POLL */
12681
12682static int
12683maygvl_copy_stream_wait_read(int has_gvl, struct copy_stream_struct *stp)
12684{
12685 int ret;
12686
12687 do {
12688 if (has_gvl) {
12690 }
12691 else {
12692 ret = nogvl_wait_for(stp->th, stp->src_fptr, RB_WAITFD_IN, NULL);
12693 }
12694 } while (ret < 0 && maygvl_copy_stream_continue_p(has_gvl, stp));
12695
12696 if (ret < 0) {
12697 stp->syserr = IOWAIT_SYSCALL;
12698 stp->error_no = errno;
12699 return ret;
12700 }
12701 return 0;
12702}
12703
12704static int
12705nogvl_copy_stream_wait_write(struct copy_stream_struct *stp)
12706{
12707 int ret;
12708
12709 do {
12710 ret = nogvl_wait_for(stp->th, stp->dst_fptr, RB_WAITFD_OUT, NULL);
12711 } while (ret < 0 && maygvl_copy_stream_continue_p(0, stp));
12712
12713 if (ret < 0) {
12714 stp->syserr = IOWAIT_SYSCALL;
12715 stp->error_no = errno;
12716 return ret;
12717 }
12718 return 0;
12719}
12720
12721#ifdef USE_COPY_FILE_RANGE
12722
12723static ssize_t
12724simple_copy_file_range(int in_fd, rb_off_t *in_offset, int out_fd, rb_off_t *out_offset, size_t count, unsigned int flags)
12725{
12726#ifdef HAVE_COPY_FILE_RANGE
12727 return copy_file_range(in_fd, in_offset, out_fd, out_offset, count, flags);
12728#else
12729 return syscall(__NR_copy_file_range, in_fd, in_offset, out_fd, out_offset, count, flags);
12730#endif
12731}
12732
12733static int
12734nogvl_copy_file_range(struct copy_stream_struct *stp)
12735{
12736 ssize_t ss;
12737 rb_off_t src_size;
12738 rb_off_t copy_length, src_offset, *src_offset_ptr;
12739
12740 if (!S_ISREG(stp->src_stat.st_mode))
12741 return 0;
12742
12743 src_size = stp->src_stat.st_size;
12744 src_offset = stp->src_offset;
12745 if (src_offset >= (rb_off_t)0) {
12746 src_offset_ptr = &src_offset;
12747 }
12748 else {
12749 src_offset_ptr = NULL; /* if src_offset_ptr is NULL, then bytes are read from in_fd starting from the file offset */
12750 }
12751
12752 copy_length = stp->copy_length;
12753 if (copy_length < (rb_off_t)0) {
12754 if (src_offset < (rb_off_t)0) {
12755 rb_off_t current_offset;
12756 errno = 0;
12757 current_offset = lseek(stp->src_fptr->fd, 0, SEEK_CUR);
12758 if (current_offset < (rb_off_t)0 && errno) {
12759 stp->syserr = "lseek";
12760 stp->error_no = errno;
12761 return (int)current_offset;
12762 }
12763 copy_length = src_size - current_offset;
12764 }
12765 else {
12766 copy_length = src_size - src_offset;
12767 }
12768 }
12769
12770 retry_copy_file_range:
12771# if SIZEOF_OFF_T > SIZEOF_SIZE_T
12772 /* we are limited by the 32-bit ssize_t return value on 32-bit */
12773 ss = (copy_length > (rb_off_t)SSIZE_MAX) ? SSIZE_MAX : (ssize_t)copy_length;
12774# else
12775 ss = (ssize_t)copy_length;
12776# endif
12777 ss = simple_copy_file_range(stp->src_fptr->fd, src_offset_ptr, stp->dst_fptr->fd, NULL, ss, 0);
12778 if (0 < ss) {
12779 stp->total += ss;
12780 copy_length -= ss;
12781 if (0 < copy_length) {
12782 goto retry_copy_file_range;
12783 }
12784 }
12785 if (ss < 0) {
12786 if (maygvl_copy_stream_continue_p(0, stp)) {
12787 goto retry_copy_file_range;
12788 }
12789 switch (errno) {
12790 case EINVAL:
12791 case EPERM: /* copy_file_range(2) doesn't exist (may happen in
12792 docker container) */
12793#ifdef ENOSYS
12794 case ENOSYS:
12795#endif
12796#ifdef EXDEV
12797 case EXDEV: /* in_fd and out_fd are not on the same filesystem */
12798#endif
12799 return 0;
12800 case EAGAIN:
12801#if EWOULDBLOCK != EAGAIN
12802 case EWOULDBLOCK:
12803#endif
12804 {
12805 int ret = nogvl_copy_stream_wait_write(stp);
12806 if (ret < 0) return ret;
12807 }
12808 goto retry_copy_file_range;
12809 case EBADF:
12810 {
12811 int e = errno;
12812 int flags = fcntl(stp->dst_fptr->fd, F_GETFL);
12813
12814 if (flags != -1 && flags & O_APPEND) {
12815 return 0;
12816 }
12817 errno = e;
12818 }
12819 }
12820 stp->syserr = "copy_file_range";
12821 stp->error_no = errno;
12822 return (int)ss;
12823 }
12824 return 1;
12825}
12826#endif
12827
12828#ifdef HAVE_FCOPYFILE
12829static int
12830nogvl_fcopyfile(struct copy_stream_struct *stp)
12831{
12832 rb_off_t cur, ss = 0;
12833 const rb_off_t src_offset = stp->src_offset;
12834 int ret;
12835
12836 if (stp->copy_length >= (rb_off_t)0) {
12837 /* copy_length can't be specified in fcopyfile(3) */
12838 return 0;
12839 }
12840
12841 if (!S_ISREG(stp->src_stat.st_mode))
12842 return 0;
12843
12844 if (!S_ISREG(stp->dst_stat.st_mode))
12845 return 0;
12846 if (lseek(stp->dst_fptr->fd, 0, SEEK_CUR) > (rb_off_t)0) /* if dst IO was already written */
12847 return 0;
12848 if (fcntl(stp->dst_fptr->fd, F_GETFL) & O_APPEND) {
12849 /* fcopyfile(3) appends src IO to dst IO and then truncates
12850 * dst IO to src IO's original size. */
12851 rb_off_t end = lseek(stp->dst_fptr->fd, 0, SEEK_END);
12852 lseek(stp->dst_fptr->fd, 0, SEEK_SET);
12853 if (end > (rb_off_t)0) return 0;
12854 }
12855
12856 if (src_offset > (rb_off_t)0) {
12857 rb_off_t r;
12858
12859 /* get current offset */
12860 errno = 0;
12861 cur = lseek(stp->src_fptr->fd, 0, SEEK_CUR);
12862 if (cur < (rb_off_t)0 && errno) {
12863 stp->error_no = errno;
12864 return 1;
12865 }
12866
12867 errno = 0;
12868 r = lseek(stp->src_fptr->fd, src_offset, SEEK_SET);
12869 if (r < (rb_off_t)0 && errno) {
12870 stp->error_no = errno;
12871 return 1;
12872 }
12873 }
12874
12875 stp->copyfile_state = copyfile_state_alloc(); /* this will be freed by copy_stream_finalize() */
12876 ret = fcopyfile(stp->src_fptr->fd, stp->dst_fptr->fd, stp->copyfile_state, COPYFILE_DATA);
12877 copyfile_state_get(stp->copyfile_state, COPYFILE_STATE_COPIED, &ss); /* get copied bytes */
12878
12879 if (ret == 0) { /* success */
12880 stp->total = ss;
12881 if (src_offset > (rb_off_t)0) {
12882 rb_off_t r;
12883 errno = 0;
12884 /* reset offset */
12885 r = lseek(stp->src_fptr->fd, cur, SEEK_SET);
12886 if (r < (rb_off_t)0 && errno) {
12887 stp->error_no = errno;
12888 return 1;
12889 }
12890 }
12891 }
12892 else {
12893 switch (errno) {
12894 case ENOTSUP:
12895 case EPERM:
12896 case EINVAL:
12897 return 0;
12898 }
12899 stp->syserr = "fcopyfile";
12900 stp->error_no = errno;
12901 return (int)ret;
12902 }
12903 return 1;
12904}
12905#endif
12906
12907#ifdef HAVE_SENDFILE
12908
12909# ifdef __linux__
12910# define USE_SENDFILE
12911
12912# ifdef HAVE_SYS_SENDFILE_H
12913# include <sys/sendfile.h>
12914# endif
12915
12916static ssize_t
12917simple_sendfile(int out_fd, int in_fd, rb_off_t *offset, rb_off_t count)
12918{
12919 return sendfile(out_fd, in_fd, offset, (size_t)count);
12920}
12921
12922# elif 0 /* defined(__FreeBSD__) || defined(__DragonFly__) */ || defined(__APPLE__)
12923/* This runs on FreeBSD8.1 r30210, but sendfiles blocks its execution
12924 * without cpuset -l 0.
12925 */
12926# define USE_SENDFILE
12927
12928static ssize_t
12929simple_sendfile(int out_fd, int in_fd, rb_off_t *offset, rb_off_t count)
12930{
12931 int r;
12932 rb_off_t pos = offset ? *offset : lseek(in_fd, 0, SEEK_CUR);
12933 rb_off_t sbytes;
12934# ifdef __APPLE__
12935 r = sendfile(in_fd, out_fd, pos, &count, NULL, 0);
12936 sbytes = count;
12937# else
12938 r = sendfile(in_fd, out_fd, pos, (size_t)count, NULL, &sbytes, 0);
12939# endif
12940 if (r != 0 && sbytes == 0) return r;
12941 if (offset) {
12942 *offset += sbytes;
12943 }
12944 else {
12945 lseek(in_fd, sbytes, SEEK_CUR);
12946 }
12947 return (ssize_t)sbytes;
12948}
12949
12950# endif
12951
12952#endif
12953
12954#ifdef USE_SENDFILE
12955static int
12956nogvl_copy_stream_sendfile(struct copy_stream_struct *stp)
12957{
12958 ssize_t ss;
12959 rb_off_t src_size;
12960 rb_off_t copy_length;
12961 rb_off_t src_offset;
12962 int use_pread;
12963
12964 if (!S_ISREG(stp->src_stat.st_mode))
12965 return 0;
12966
12967 src_size = stp->src_stat.st_size;
12968#ifndef __linux__
12969 if ((stp->dst_stat.st_mode & S_IFMT) != S_IFSOCK)
12970 return 0;
12971#endif
12972
12973 src_offset = stp->src_offset;
12974 use_pread = src_offset >= (rb_off_t)0;
12975
12976 copy_length = stp->copy_length;
12977 if (copy_length < (rb_off_t)0) {
12978 if (use_pread)
12979 copy_length = src_size - src_offset;
12980 else {
12981 rb_off_t cur;
12982 errno = 0;
12983 cur = lseek(stp->src_fptr->fd, 0, SEEK_CUR);
12984 if (cur < (rb_off_t)0 && errno) {
12985 stp->syserr = "lseek";
12986 stp->error_no = errno;
12987 return (int)cur;
12988 }
12989 copy_length = src_size - cur;
12990 }
12991 }
12992
12993 retry_sendfile:
12994# if SIZEOF_OFF_T > SIZEOF_SIZE_T
12995 /* we are limited by the 32-bit ssize_t return value on 32-bit */
12996 ss = (copy_length > (rb_off_t)SSIZE_MAX) ? SSIZE_MAX : (ssize_t)copy_length;
12997# else
12998 ss = (ssize_t)copy_length;
12999# endif
13000 if (use_pread) {
13001 ss = simple_sendfile(stp->dst_fptr->fd, stp->src_fptr->fd, &src_offset, ss);
13002 }
13003 else {
13004 ss = simple_sendfile(stp->dst_fptr->fd, stp->src_fptr->fd, NULL, ss);
13005 }
13006 if (0 < ss) {
13007 stp->total += ss;
13008 copy_length -= ss;
13009 if (0 < copy_length) {
13010 goto retry_sendfile;
13011 }
13012 }
13013 if (ss < 0) {
13014 if (maygvl_copy_stream_continue_p(0, stp))
13015 goto retry_sendfile;
13016 switch (errno) {
13017 case EINVAL:
13018#ifdef ENOSYS
13019 case ENOSYS:
13020#endif
13021#ifdef EOPNOTSUP
13022 /* some RedHat kernels may return EOPNOTSUP on an NFS mount.
13023 see also: [Feature #16965] */
13024 case EOPNOTSUP:
13025#endif
13026 return 0;
13027 case EAGAIN:
13028#if EWOULDBLOCK != EAGAIN
13029 case EWOULDBLOCK:
13030#endif
13031 {
13032 int ret;
13033#ifndef __linux__
13034 /*
13035 * Linux requires stp->src_fptr->fd to be a mmap-able (regular) file,
13036 * select() reports regular files to always be "ready", so
13037 * there is no need to select() on it.
13038 * Other OSes may have the same limitation for sendfile() which
13039 * allow us to bypass maygvl_copy_stream_wait_read()...
13040 */
13041 ret = maygvl_copy_stream_wait_read(0, stp);
13042 if (ret < 0) return ret;
13043#endif
13044 ret = nogvl_copy_stream_wait_write(stp);
13045 if (ret < 0) return ret;
13046 }
13047 goto retry_sendfile;
13048 }
13049 stp->syserr = "sendfile";
13050 stp->error_no = errno;
13051 return (int)ss;
13052 }
13053 return 1;
13054}
13055#endif
13056
13057static ssize_t
13058maygvl_read(int has_gvl, rb_io_t *fptr, void *buf, size_t count)
13059{
13060 if (has_gvl)
13061 return rb_io_read_memory(fptr, buf, count);
13062 else
13063 return read(fptr->fd, buf, count);
13064}
13065
13066static ssize_t
13067maygvl_copy_stream_read(int has_gvl, struct copy_stream_struct *stp, char *buf, size_t len, rb_off_t offset)
13068{
13069 ssize_t ss;
13070 retry_read:
13071 if (offset < (rb_off_t)0) {
13072 ss = maygvl_read(has_gvl, stp->src_fptr, buf, len);
13073 }
13074 else {
13075 ss = pread(stp->src_fptr->fd, buf, len, offset);
13076 }
13077 if (ss == 0) {
13078 return 0;
13079 }
13080 if (ss < 0) {
13081 if (maygvl_copy_stream_continue_p(has_gvl, stp))
13082 goto retry_read;
13083 switch (errno) {
13084 case EAGAIN:
13085#if EWOULDBLOCK != EAGAIN
13086 case EWOULDBLOCK:
13087#endif
13088 {
13089 int ret = maygvl_copy_stream_wait_read(has_gvl, stp);
13090 if (ret < 0) return ret;
13091 }
13092 goto retry_read;
13093#ifdef ENOSYS
13094 case ENOSYS:
13095 stp->notimp = "pread";
13096 return ss;
13097#endif
13098 }
13099 stp->syserr = offset < (rb_off_t)0 ? "read" : "pread";
13100 stp->error_no = errno;
13101 }
13102 return ss;
13103}
13104
13105static int
13106nogvl_copy_stream_write(struct copy_stream_struct *stp, char *buf, size_t len)
13107{
13108 ssize_t ss;
13109 int off = 0;
13110 while (len) {
13111 ss = write(stp->dst_fptr->fd, buf+off, len);
13112 if (ss < 0) {
13113 if (maygvl_copy_stream_continue_p(0, stp))
13114 continue;
13115 if (io_again_p(errno)) {
13116 int ret = nogvl_copy_stream_wait_write(stp);
13117 if (ret < 0) return ret;
13118 continue;
13119 }
13120 stp->syserr = "write";
13121 stp->error_no = errno;
13122 return (int)ss;
13123 }
13124 off += (int)ss;
13125 len -= (int)ss;
13126 stp->total += ss;
13127 }
13128 return 0;
13129}
13130
13131static void
13132nogvl_copy_stream_read_write(struct copy_stream_struct *stp)
13133{
13134 char buf[1024*16];
13135 size_t len;
13136 ssize_t ss;
13137 int ret;
13138 rb_off_t copy_length;
13139 rb_off_t src_offset;
13140 int use_eof;
13141 int use_pread;
13142
13143 copy_length = stp->copy_length;
13144 use_eof = copy_length < (rb_off_t)0;
13145 src_offset = stp->src_offset;
13146 use_pread = src_offset >= (rb_off_t)0;
13147
13148 if (use_pread && stp->close_src) {
13149 rb_off_t r;
13150 errno = 0;
13151 r = lseek(stp->src_fptr->fd, src_offset, SEEK_SET);
13152 if (r < (rb_off_t)0 && errno) {
13153 stp->syserr = "lseek";
13154 stp->error_no = errno;
13155 return;
13156 }
13157 src_offset = (rb_off_t)-1;
13158 use_pread = 0;
13159 }
13160
13161 while (use_eof || 0 < copy_length) {
13162 if (!use_eof && copy_length < (rb_off_t)sizeof(buf)) {
13163 len = (size_t)copy_length;
13164 }
13165 else {
13166 len = sizeof(buf);
13167 }
13168 if (use_pread) {
13169 ss = maygvl_copy_stream_read(0, stp, buf, len, src_offset);
13170 if (0 < ss)
13171 src_offset += ss;
13172 }
13173 else {
13174 ss = maygvl_copy_stream_read(0, stp, buf, len, (rb_off_t)-1);
13175 }
13176 if (ss <= 0) /* EOF or error */
13177 return;
13178
13179 ret = nogvl_copy_stream_write(stp, buf, ss);
13180 if (ret < 0)
13181 return;
13182
13183 if (!use_eof)
13184 copy_length -= ss;
13185 }
13186}
13187
13188static void *
13189nogvl_copy_stream_func(void *arg)
13190{
13191 struct copy_stream_struct *stp = (struct copy_stream_struct *)arg;
13192#if defined(USE_SENDFILE) || defined(USE_COPY_FILE_RANGE) || defined(HAVE_FCOPYFILE)
13193 int ret;
13194#endif
13195
13196#ifdef USE_COPY_FILE_RANGE
13197 ret = nogvl_copy_file_range(stp);
13198 if (ret != 0)
13199 goto finish; /* error or success */
13200#endif
13201
13202#ifdef HAVE_FCOPYFILE
13203 ret = nogvl_fcopyfile(stp);
13204 if (ret != 0)
13205 goto finish; /* error or success */
13206#endif
13207
13208#ifdef USE_SENDFILE
13209 ret = nogvl_copy_stream_sendfile(stp);
13210 if (ret != 0)
13211 goto finish; /* error or success */
13212#endif
13213
13214 nogvl_copy_stream_read_write(stp);
13215
13216#if defined(USE_SENDFILE) || defined(USE_COPY_FILE_RANGE) || defined(HAVE_FCOPYFILE)
13217 finish:
13218#endif
13219 return 0;
13220}
13221
13223 struct copy_stream_struct *stp;
13224 VALUE buf;
13225 long len;
13226 rb_off_t offset;
13227};
13228
13229static VALUE
13230copy_stream_fallback_read(VALUE arg)
13231{
13232 struct copy_stream_fallback_read_arg *p = (void *)arg;
13233 return (VALUE)maygvl_copy_stream_read(1, p->stp, RSTRING_PTR(p->buf),
13234 p->len, p->offset);
13235}
13236
13237static VALUE
13238copy_stream_fallback_body(VALUE arg)
13239{
13240 struct copy_stream_struct *stp = (struct copy_stream_struct *)arg;
13241 const int buflen = 16*1024;
13242 VALUE n;
13243 VALUE buf = rb_str_buf_new(buflen);
13244 rb_off_t rest = stp->copy_length;
13245 rb_off_t off = stp->src_offset;
13246 ID read_method = id_readpartial;
13247
13248 if (!stp->src_fptr) {
13249 if (!rb_respond_to(stp->src, read_method)) {
13250 read_method = id_read;
13251 }
13252 }
13253
13254 while (1) {
13255 long numwrote;
13256 long l;
13257 rb_str_make_independent(buf);
13258 if (stp->copy_length < (rb_off_t)0) {
13259 l = buflen;
13260 }
13261 else {
13262 if (rest == 0) {
13263 rb_str_resize(buf, 0);
13264 break;
13265 }
13266 l = buflen < rest ? buflen : (long)rest;
13267 }
13268 if (!stp->src_fptr) {
13269 VALUE rc = rb_funcall(stp->src, read_method, 2, INT2FIX(l), buf);
13270
13271 if (read_method == id_read && NIL_P(rc))
13272 break;
13273 }
13274 else {
13275 rb_str_resize(buf, buflen);
13276 struct copy_stream_fallback_read_arg read_arg = {stp, buf, l, off};
13277 ssize_t ss =
13278 (ssize_t)rb_str_locktmp_ensure(buf, copy_stream_fallback_read,
13279 (VALUE)&read_arg);
13280 rb_str_resize(buf, ss > 0 ? ss : 0);
13281 if (ss < 0)
13282 return Qnil;
13283 if (ss == 0)
13284 rb_eof_error();
13285 if (off >= (rb_off_t)0)
13286 off += ss;
13287 }
13288 n = rb_io_write(stp->dst, buf);
13289 numwrote = NUM2LONG(n);
13290 stp->total += numwrote;
13291 rest -= numwrote;
13292 if (read_method == id_read && RSTRING_LEN(buf) == 0) {
13293 break;
13294 }
13295 }
13296
13297 return Qnil;
13298}
13299
13300static VALUE
13301copy_stream_fallback(struct copy_stream_struct *stp)
13302{
13303 if (!stp->src_fptr && stp->src_offset >= (rb_off_t)0) {
13304 rb_raise(rb_eArgError, "cannot specify src_offset for non-IO");
13305 }
13306 rb_rescue2(copy_stream_fallback_body, (VALUE)stp,
13307 (VALUE (*) (VALUE, VALUE))0, (VALUE)0,
13308 rb_eEOFError, (VALUE)0);
13309 return Qnil;
13310}
13311
13312static VALUE
13313copy_stream_body(VALUE arg)
13314{
13315 struct copy_stream_struct *stp = (struct copy_stream_struct *)arg;
13316 VALUE src_io = stp->src, dst_io = stp->dst;
13317 const int common_oflags = 0
13318#ifdef O_NOCTTY
13319 | O_NOCTTY
13320#endif
13321 ;
13322
13323 stp->th = rb_thread_current();
13324
13325 stp->total = 0;
13326
13327 if (src_io == argf ||
13328 !(RB_TYPE_P(src_io, T_FILE) ||
13329 RB_TYPE_P(src_io, T_STRING) ||
13330 rb_respond_to(src_io, rb_intern("to_path")))) {
13331 stp->src_fptr = NULL;
13332 }
13333 else {
13334 int stat_ret;
13335 VALUE tmp_io = rb_io_check_io(src_io);
13336 if (!NIL_P(tmp_io)) {
13337 src_io = tmp_io;
13338 }
13339 else if (!RB_TYPE_P(src_io, T_FILE)) {
13340 VALUE args[2];
13341 FilePathValue(src_io);
13342 args[0] = src_io;
13343 args[1] = INT2NUM(O_RDONLY|common_oflags);
13344 src_io = rb_class_new_instance(2, args, rb_cFile);
13345 stp->src = src_io;
13346 stp->close_src = 1;
13347 }
13348 RB_IO_POINTER(src_io, stp->src_fptr);
13349 rb_io_check_byte_readable(stp->src_fptr);
13350
13351 stat_ret = fstat(stp->src_fptr->fd, &stp->src_stat);
13352 if (stat_ret < 0) {
13353 stp->syserr = "fstat";
13354 stp->error_no = errno;
13355 return Qnil;
13356 }
13357 }
13358
13359 if (dst_io == argf ||
13360 !(RB_TYPE_P(dst_io, T_FILE) ||
13361 RB_TYPE_P(dst_io, T_STRING) ||
13362 rb_respond_to(dst_io, rb_intern("to_path")))) {
13363 stp->dst_fptr = NULL;
13364 }
13365 else {
13366 int stat_ret;
13367 VALUE tmp_io = rb_io_check_io(dst_io);
13368 if (!NIL_P(tmp_io)) {
13369 dst_io = GetWriteIO(tmp_io);
13370 }
13371 else if (!RB_TYPE_P(dst_io, T_FILE)) {
13372 VALUE args[3];
13373 FilePathValue(dst_io);
13374 args[0] = dst_io;
13375 args[1] = INT2NUM(O_WRONLY|O_CREAT|O_TRUNC|common_oflags);
13376 args[2] = INT2FIX(0666);
13377 dst_io = rb_class_new_instance(3, args, rb_cFile);
13378 stp->dst = dst_io;
13379 stp->close_dst = 1;
13380 }
13381 else {
13382 dst_io = GetWriteIO(dst_io);
13383 stp->dst = dst_io;
13384 }
13385 RB_IO_POINTER(dst_io, stp->dst_fptr);
13386 rb_io_check_writable(stp->dst_fptr);
13387
13388 stat_ret = fstat(stp->dst_fptr->fd, &stp->dst_stat);
13389 if (stat_ret < 0) {
13390 stp->syserr = "fstat";
13391 stp->error_no = errno;
13392 return Qnil;
13393 }
13394 }
13395
13396#ifdef O_BINARY
13397 if (stp->src_fptr)
13398 SET_BINARY_MODE_WITH_SEEK_CUR(stp->src_fptr);
13399#endif
13400 if (stp->dst_fptr)
13401 io_ascii8bit_binmode(stp->dst_fptr);
13402
13403 if (stp->src_offset < (rb_off_t)0 && stp->src_fptr && stp->src_fptr->rbuf.len) {
13404 size_t len = stp->src_fptr->rbuf.len;
13405 VALUE str;
13406 if (stp->copy_length >= (rb_off_t)0 && stp->copy_length < (rb_off_t)len) {
13407 len = (size_t)stp->copy_length;
13408 }
13409 str = rb_str_buf_new(len);
13410 rb_str_resize(str,len);
13411 read_buffered_data(RSTRING_PTR(str), len, stp->src_fptr);
13412 if (stp->dst_fptr) { /* IO or filename */
13413 if (io_binwrite(RSTRING_PTR(str), RSTRING_LEN(str), stp->dst_fptr, 0) < 0)
13414 rb_sys_fail_on_write(stp->dst_fptr);
13415 }
13416 else /* others such as StringIO */
13417 rb_io_write(dst_io, str);
13418 rb_str_resize(str, 0);
13419 stp->total += len;
13420 if (stp->copy_length >= (rb_off_t)0)
13421 stp->copy_length -= len;
13422 }
13423
13424 if (stp->dst_fptr && io_fflush(stp->dst_fptr) < 0) {
13425 rb_raise(rb_eIOError, "flush failed");
13426 }
13427
13428 if (stp->copy_length == 0)
13429 return Qnil;
13430
13431 if (stp->src_fptr == NULL || stp->dst_fptr == NULL) {
13432 return copy_stream_fallback(stp);
13433 }
13434
13435 IO_WITHOUT_GVL(nogvl_copy_stream_func, stp);
13436 return Qnil;
13437}
13438
13439static VALUE
13440copy_stream_finalize(VALUE arg)
13441{
13442 struct copy_stream_struct *stp = (struct copy_stream_struct *)arg;
13443
13444#ifdef HAVE_FCOPYFILE
13445 if (stp->copyfile_state) {
13446 copyfile_state_free(stp->copyfile_state);
13447 }
13448#endif
13449
13450 if (stp->close_src) {
13451 rb_io_close_m(stp->src);
13452 }
13453 if (stp->close_dst) {
13454 rb_io_close_m(stp->dst);
13455 }
13456 if (stp->syserr) {
13457 rb_syserr_fail(stp->error_no, stp->syserr);
13458 }
13459 if (stp->notimp) {
13460 rb_raise(rb_eNotImpError, "%s() not implemented", stp->notimp);
13461 }
13462 return Qnil;
13463}
13464
13465/*
13466 * call-seq:
13467 * IO.copy_stream(src, dst, src_length = nil, src_offset = 0) -> integer
13468 *
13469 * Copies from the given +src+ to the given +dst+,
13470 * returning the number of bytes copied.
13471 *
13472 * - The given +src+ must be one of the following:
13473 *
13474 * - The path to a readable file, from which source data is to be read.
13475 * - An \IO-like object, opened for reading and capable of responding
13476 * to method +:readpartial+ or method +:read+.
13477 *
13478 * - The given +dst+ must be one of the following:
13479 *
13480 * - The path to a writable file, to which data is to be written.
13481 * - An \IO-like object, opened for writing and capable of responding
13482 * to method +:write+.
13483 *
13484 * The examples here use file <tt>t.txt</tt> as source:
13485 *
13486 * File.read('t.txt')
13487 * # => "First line\nSecond line\n\nThird line\nFourth line\n"
13488 * File.read('t.txt').size # => 47
13489 *
13490 * If only arguments +src+ and +dst+ are given,
13491 * the entire source stream is copied:
13492 *
13493 * # Paths.
13494 * IO.copy_stream('t.txt', 't.tmp') # => 47
13495 *
13496 * # IOs (recall that a File is also an IO).
13497 * src_io = File.open('t.txt', 'r') # => #<File:t.txt>
13498 * dst_io = File.open('t.tmp', 'w') # => #<File:t.tmp>
13499 * IO.copy_stream(src_io, dst_io) # => 47
13500 * src_io.close
13501 * dst_io.close
13502 *
13503 * With argument +src_length+ a non-negative integer,
13504 * no more than that many bytes are copied:
13505 *
13506 * IO.copy_stream('t.txt', 't.tmp', 10) # => 10
13507 * File.read('t.tmp') # => "First line"
13508 *
13509 * With argument +src_offset+ also given,
13510 * the source stream is read beginning at that offset:
13511 *
13512 * IO.copy_stream('t.txt', 't.tmp', 11, 11) # => 11
13513 * IO.read('t.tmp') # => "Second line"
13514 *
13515 */
13516static VALUE
13517rb_io_s_copy_stream(int argc, VALUE *argv, VALUE io)
13518{
13519 VALUE src, dst, length, src_offset;
13520 struct copy_stream_struct st;
13521
13522 MEMZERO(&st, struct copy_stream_struct, 1);
13523
13524 rb_scan_args(argc, argv, "22", &src, &dst, &length, &src_offset);
13525
13526 st.src = src;
13527 st.dst = dst;
13528
13529 st.src_fptr = NULL;
13530 st.dst_fptr = NULL;
13531
13532 if (NIL_P(length))
13533 st.copy_length = (rb_off_t)-1;
13534 else
13535 st.copy_length = NUM2OFFT(length);
13536
13537 if (NIL_P(src_offset))
13538 st.src_offset = (rb_off_t)-1;
13539 else
13540 st.src_offset = NUM2OFFT(src_offset);
13541
13542 rb_ensure(copy_stream_body, (VALUE)&st, copy_stream_finalize, (VALUE)&st);
13543
13544 return OFFT2NUM(st.total);
13545}
13546
13547/*
13548 * call-seq:
13549 * external_encoding -> encoding or nil
13550 *
13551 * Returns the Encoding object that represents the encoding of the stream,
13552 * or +nil+ if the stream is in write mode and no encoding is specified.
13553 *
13554 * See {Encodings}[rdoc-ref:File@Encodings].
13555 *
13556 */
13557
13558static VALUE
13559rb_io_external_encoding(VALUE io)
13560{
13561 rb_io_t *fptr = rb_io_get_fptr(rb_io_taint_check(io));
13562
13563 if (fptr->encs.enc2) {
13564 return rb_enc_from_encoding(fptr->encs.enc2);
13565 }
13566 if (fptr->mode & FMODE_WRITABLE) {
13567 if (fptr->encs.enc)
13568 return rb_enc_from_encoding(fptr->encs.enc);
13569 return Qnil;
13570 }
13571 return rb_enc_from_encoding(io_read_encoding(fptr));
13572}
13573
13574/*
13575 * call-seq:
13576 * internal_encoding -> encoding or nil
13577 *
13578 * Returns the Encoding object that represents the encoding of the internal string,
13579 * if conversion is specified,
13580 * or +nil+ otherwise.
13581 *
13582 * See {Encodings}[rdoc-ref:File@Encodings].
13583 *
13584 */
13585
13586static VALUE
13587rb_io_internal_encoding(VALUE io)
13588{
13589 rb_io_t *fptr = rb_io_get_fptr(rb_io_taint_check(io));
13590
13591 if (!fptr->encs.enc2) return Qnil;
13592 return rb_enc_from_encoding(io_read_encoding(fptr));
13593}
13594
13595/*
13596 * call-seq:
13597 * set_encoding(ext_enc) -> self
13598 * set_encoding(ext_enc, int_enc, **enc_opts) -> self
13599 * set_encoding('ext_enc:int_enc', **enc_opts) -> self
13600 *
13601 * See {Encodings}[rdoc-ref:File@Encodings].
13602 *
13603 * Argument +ext_enc+, if given, must be an Encoding object
13604 * or a String with the encoding name;
13605 * it is assigned as the encoding for the stream.
13606 *
13607 * Argument +int_enc+, if given, must be an Encoding object
13608 * or a String with the encoding name;
13609 * it is assigned as the encoding for the internal string.
13610 *
13611 * Argument <tt>'ext_enc:int_enc'</tt>, if given, is a string
13612 * containing two colon-separated encoding names;
13613 * corresponding Encoding objects are assigned as the external
13614 * and internal encodings for the stream.
13615 *
13616 * If the external encoding of a string is binary/ASCII-8BIT,
13617 * the internal encoding of the string is set to nil, since no
13618 * transcoding is needed.
13619 *
13620 * Optional keyword arguments +enc_opts+ specify
13621 * {Encoding options}[rdoc-ref:encodings.rdoc@Encoding+Options].
13622 *
13623 */
13624
13625static VALUE
13626rb_io_set_encoding(int argc, VALUE *argv, VALUE io)
13627{
13628 rb_io_t *fptr;
13629 VALUE v1, v2, opt;
13630
13631 if (!RB_TYPE_P(io, T_FILE)) {
13632 return forward(io, id_set_encoding, argc, argv);
13633 }
13634
13635 argc = rb_scan_args(argc, argv, "11:", &v1, &v2, &opt);
13636 GetOpenFile(io, fptr);
13637 io_encoding_set(fptr, v1, v2, opt);
13638 return io;
13639}
13640
13641void
13642rb_stdio_set_default_encoding(void)
13643{
13644 VALUE val = Qnil;
13645
13646#ifdef _WIN32
13647 if (isatty(fileno(stdin))) {
13648 rb_encoding *external = rb_locale_encoding();
13649 rb_encoding *internal = rb_default_internal_encoding();
13650 if (!internal) internal = rb_default_external_encoding();
13651 io_encoding_set(RFILE(rb_stdin)->fptr,
13652 rb_enc_from_encoding(external),
13653 rb_enc_from_encoding(internal),
13654 Qnil);
13655 }
13656 else
13657#endif
13658 rb_io_set_encoding(1, &val, rb_stdin);
13659 rb_io_set_encoding(1, &val, rb_stdout);
13660 rb_io_set_encoding(1, &val, rb_stderr);
13661}
13662
13663static inline int
13664global_argf_p(VALUE arg)
13665{
13666 return arg == argf;
13667}
13668
13669typedef VALUE (*argf_encoding_func)(VALUE io);
13670
13671static VALUE
13672argf_encoding(VALUE argf, argf_encoding_func func)
13673{
13674 if (!RTEST(ARGF.current_file)) {
13675 return rb_enc_default_external();
13676 }
13677 return func(rb_io_check_io(ARGF.current_file));
13678}
13679
13680/*
13681 * call-seq:
13682 * ARGF.external_encoding -> encoding
13683 *
13684 * Returns the external encoding for files read from ARGF as an Encoding
13685 * object. The external encoding is the encoding of the text as stored in a
13686 * file. Contrast with ARGF.internal_encoding, which is the encoding used to
13687 * represent this text within Ruby.
13688 *
13689 * To set the external encoding use ARGF.set_encoding.
13690 *
13691 * For example:
13692 *
13693 * ARGF.external_encoding #=> #<Encoding:UTF-8>
13694 *
13695 */
13696static VALUE
13697argf_external_encoding(VALUE argf)
13698{
13699 return argf_encoding(argf, rb_io_external_encoding);
13700}
13701
13702/*
13703 * call-seq:
13704 * ARGF.internal_encoding -> encoding
13705 *
13706 * Returns the internal encoding for strings read from ARGF as an
13707 * Encoding object.
13708 *
13709 * If ARGF.set_encoding has been called with two encoding names, the second
13710 * is returned. Otherwise, if +Encoding.default_external+ has been set, that
13711 * value is returned. Failing that, if a default external encoding was
13712 * specified on the command-line, that value is used. If the encoding is
13713 * unknown, +nil+ is returned.
13714 */
13715static VALUE
13716argf_internal_encoding(VALUE argf)
13717{
13718 return argf_encoding(argf, rb_io_internal_encoding);
13719}
13720
13721/*
13722 * call-seq:
13723 * ARGF.set_encoding(ext_enc) -> ARGF
13724 * ARGF.set_encoding("ext_enc:int_enc") -> ARGF
13725 * ARGF.set_encoding(ext_enc, int_enc) -> ARGF
13726 * ARGF.set_encoding("ext_enc:int_enc", opt) -> ARGF
13727 * ARGF.set_encoding(ext_enc, int_enc, opt) -> ARGF
13728 *
13729 * If single argument is specified, strings read from ARGF are tagged with
13730 * the encoding specified.
13731 *
13732 * If two encoding names separated by a colon are given, e.g. "ascii:utf-8",
13733 * the read string is converted from the first encoding (external encoding)
13734 * to the second encoding (internal encoding), then tagged with the second
13735 * encoding.
13736 *
13737 * If two arguments are specified, they must be encoding objects or encoding
13738 * names. Again, the first specifies the external encoding; the second
13739 * specifies the internal encoding.
13740 *
13741 * If the external encoding and the internal encoding are specified, the
13742 * optional Hash argument can be used to adjust the conversion process. The
13743 * structure of this hash is explained in the String#encode documentation.
13744 *
13745 * For example:
13746 *
13747 * ARGF.set_encoding('ascii') # Tag the input as US-ASCII text
13748 * ARGF.set_encoding(Encoding::UTF_8) # Tag the input as UTF-8 text
13749 * ARGF.set_encoding('utf-8','ascii') # Transcode the input from US-ASCII
13750 * # to UTF-8.
13751 */
13752static VALUE
13753argf_set_encoding(int argc, VALUE *argv, VALUE argf)
13754{
13755 rb_io_t *fptr;
13756
13757 if (!next_argv()) {
13758 rb_raise(rb_eArgError, "no stream to set encoding");
13759 }
13760 rb_io_set_encoding(argc, argv, ARGF.current_file);
13761 GetOpenFile(ARGF.current_file, fptr);
13762 ARGF.encs = fptr->encs;
13763 return argf;
13764}
13765
13766/*
13767 * call-seq:
13768 * ARGF.tell -> Integer
13769 * ARGF.pos -> Integer
13770 *
13771 * Returns the current offset (in bytes) of the current file in ARGF.
13772 *
13773 * ARGF.pos #=> 0
13774 * ARGF.gets #=> "This is line one\n"
13775 * ARGF.pos #=> 17
13776 *
13777 */
13778static VALUE
13779argf_tell(VALUE argf)
13780{
13781 if (!next_argv()) {
13782 rb_raise(rb_eArgError, "no stream to tell");
13783 }
13784 ARGF_FORWARD(0, 0);
13785 return rb_io_tell(ARGF.current_file);
13786}
13787
13788/*
13789 * call-seq:
13790 * ARGF.seek(amount, whence=IO::SEEK_SET) -> 0
13791 *
13792 * Seeks to offset _amount_ (an Integer) in the ARGF stream according to
13793 * the value of _whence_. See IO#seek for further details.
13794 */
13795static VALUE
13796argf_seek_m(int argc, VALUE *argv, VALUE argf)
13797{
13798 if (!next_argv()) {
13799 rb_raise(rb_eArgError, "no stream to seek");
13800 }
13801 ARGF_FORWARD(argc, argv);
13802 return rb_io_seek_m(argc, argv, ARGF.current_file);
13803}
13804
13805/*
13806 * call-seq:
13807 * ARGF.pos = position -> Integer
13808 *
13809 * Seeks to the position given by _position_ (in bytes) in ARGF.
13810 *
13811 * For example:
13812 *
13813 * ARGF.pos = 17
13814 * ARGF.gets #=> "This is line two\n"
13815 */
13816static VALUE
13817argf_set_pos(VALUE argf, VALUE offset)
13818{
13819 if (!next_argv()) {
13820 rb_raise(rb_eArgError, "no stream to set position");
13821 }
13822 ARGF_FORWARD(1, &offset);
13823 return rb_io_set_pos(ARGF.current_file, offset);
13824}
13825
13826/*
13827 * call-seq:
13828 * ARGF.rewind -> 0
13829 *
13830 * Positions the current file to the beginning of input, resetting
13831 * ARGF.lineno to zero.
13832 *
13833 * ARGF.readline #=> "This is line one\n"
13834 * ARGF.rewind #=> 0
13835 * ARGF.lineno #=> 0
13836 * ARGF.readline #=> "This is line one\n"
13837 */
13838static VALUE
13839argf_rewind(VALUE argf)
13840{
13841 VALUE ret;
13842 int old_lineno;
13843
13844 if (!next_argv()) {
13845 rb_raise(rb_eArgError, "no stream to rewind");
13846 }
13847 ARGF_FORWARD(0, 0);
13848 old_lineno = RFILE(ARGF.current_file)->fptr->lineno;
13849 ret = rb_io_rewind(ARGF.current_file);
13850 if (!global_argf_p(argf)) {
13851 ARGF.last_lineno = ARGF.lineno -= old_lineno;
13852 }
13853 return ret;
13854}
13855
13856/*
13857 * call-seq:
13858 * ARGF.fileno -> integer
13859 * ARGF.to_i -> integer
13860 *
13861 * Returns an integer representing the numeric file descriptor for
13862 * the current file. Raises an ArgumentError if there isn't a current file.
13863 *
13864 * ARGF.fileno #=> 3
13865 */
13866static VALUE
13867argf_fileno(VALUE argf)
13868{
13869 if (!next_argv()) {
13870 rb_raise(rb_eArgError, "no stream");
13871 }
13872 ARGF_FORWARD(0, 0);
13873 return rb_io_fileno(ARGF.current_file);
13874}
13875
13876/*
13877 * call-seq:
13878 * ARGF.to_io -> IO
13879 *
13880 * Returns an IO object representing the current file. This will be a
13881 * File object unless the current file is a stream such as STDIN.
13882 *
13883 * For example:
13884 *
13885 * ARGF.to_io #=> #<File:glark.txt>
13886 * ARGF.to_io #=> #<IO:<STDIN>>
13887 */
13888static VALUE
13889argf_to_io(VALUE argf)
13890{
13891 next_argv();
13892 ARGF_FORWARD(0, 0);
13893 return ARGF.current_file;
13894}
13895
13896/*
13897 * call-seq:
13898 * ARGF.eof? -> true or false
13899 * ARGF.eof -> true or false
13900 *
13901 * Returns true if the current file in ARGF is at end of file, i.e. it has
13902 * no data to read. The stream must be opened for reading or an IOError
13903 * will be raised.
13904 *
13905 * $ echo "eof" | ruby argf.rb
13906 *
13907 * ARGF.eof? #=> false
13908 * 3.times { ARGF.readchar }
13909 * ARGF.eof? #=> false
13910 * ARGF.readchar #=> "\n"
13911 * ARGF.eof? #=> true
13912 */
13913
13914static VALUE
13915argf_eof(VALUE argf)
13916{
13917 next_argv();
13918 if (RTEST(ARGF.current_file)) {
13919 if (ARGF.init_p == 0) return Qtrue;
13920 next_argv();
13921 ARGF_FORWARD(0, 0);
13922 if (rb_io_eof(ARGF.current_file)) {
13923 return Qtrue;
13924 }
13925 }
13926 return Qfalse;
13927}
13928
13929/*
13930 * call-seq:
13931 * ARGF.read([length [, outbuf]]) -> string, outbuf, or nil
13932 *
13933 * Reads _length_ bytes from ARGF. The files named on the command line
13934 * are concatenated and treated as a single file by this method, so when
13935 * called without arguments the contents of this pseudo file are returned in
13936 * their entirety.
13937 *
13938 * _length_ must be a non-negative integer or +nil+.
13939 *
13940 * If _length_ is a positive integer, +read+ tries to read
13941 * _length_ bytes without any conversion (binary mode).
13942 * It returns +nil+ if an EOF is encountered before anything can be read.
13943 * Fewer than _length_ bytes are returned if an EOF is encountered during
13944 * the read.
13945 * In the case of an integer _length_, the resulting string is always
13946 * in ASCII-8BIT encoding.
13947 *
13948 * If _length_ is omitted or is +nil+, it reads until EOF
13949 * and the encoding conversion is applied, if applicable.
13950 * A string is returned even if EOF is encountered before any data is read.
13951 *
13952 * If _length_ is zero, it returns an empty string (<code>""</code>).
13953 *
13954 * If the optional _outbuf_ argument is present,
13955 * it must reference a String, which will receive the data.
13956 * The _outbuf_ will contain only the received data after the method call
13957 * even if it is not empty at the beginning.
13958 *
13959 * For example:
13960 *
13961 * $ echo "small" > small.txt
13962 * $ echo "large" > large.txt
13963 * $ ./glark.rb small.txt large.txt
13964 *
13965 * ARGF.read #=> "small\nlarge"
13966 * ARGF.read(200) #=> "small\nlarge"
13967 * ARGF.read(2) #=> "sm"
13968 * ARGF.read(0) #=> ""
13969 *
13970 * Note that this method behaves like the fread() function in C.
13971 * This means it retries to invoke read(2) system calls to read data
13972 * with the specified length.
13973 * If you need the behavior like a single read(2) system call,
13974 * consider ARGF#readpartial or ARGF#read_nonblock.
13975 */
13976
13977static VALUE
13978argf_read(int argc, VALUE *argv, VALUE argf)
13979{
13980 VALUE tmp, str, length;
13981 long len = 0;
13982
13983 rb_scan_args(argc, argv, "02", &length, &str);
13984 if (!NIL_P(length)) {
13985 len = NUM2LONG(argv[0]);
13986 }
13987 if (!NIL_P(str)) {
13988 StringValue(str);
13989 rb_str_resize(str,0);
13990 argv[1] = Qnil;
13991 }
13992
13993 retry:
13994 if (!next_argv()) {
13995 return str;
13996 }
13997 if (ARGF_GENERIC_INPUT_P()) {
13998 tmp = argf_forward(argc, argv, argf);
13999 }
14000 else {
14001 tmp = io_read(argc, argv, ARGF.current_file);
14002 }
14003 if (NIL_P(str)) str = tmp;
14004 else if (!NIL_P(tmp)) rb_str_append(str, tmp);
14005 if (NIL_P(tmp) || NIL_P(length)) {
14006 if (ARGF.next_p != -1) {
14007 argf_close(argf);
14008 ARGF.next_p = 1;
14009 goto retry;
14010 }
14011 }
14012 else if (argc >= 1) {
14013 long slen = RSTRING_LEN(str);
14014 if (slen < len) {
14015 argv[0] = LONG2NUM(len - slen);
14016 goto retry;
14017 }
14018 }
14019 return str;
14020}
14021
14023 int argc;
14024 VALUE *argv;
14025 VALUE argf;
14026};
14027
14028static VALUE
14029argf_forward_call(VALUE arg)
14030{
14031 struct argf_call_arg *p = (struct argf_call_arg *)arg;
14032 argf_forward(p->argc, p->argv, p->argf);
14033 return Qnil;
14034}
14035
14036static VALUE argf_getpartial(int argc, VALUE *argv, VALUE argf, VALUE opts,
14037 int nonblock);
14038
14039/*
14040 * call-seq:
14041 * ARGF.readpartial(maxlen) -> string
14042 * ARGF.readpartial(maxlen, outbuf) -> outbuf
14043 *
14044 * Reads at most _maxlen_ bytes from the ARGF stream.
14045 *
14046 * If the optional _outbuf_ argument is present,
14047 * it must reference a String, which will receive the data.
14048 * The _outbuf_ will contain only the received data after the method call
14049 * even if it is not empty at the beginning.
14050 *
14051 * It raises EOFError on end of ARGF stream.
14052 * Since ARGF stream is a concatenation of multiple files,
14053 * internally EOF is occur for each file.
14054 * ARGF.readpartial returns empty strings for EOFs except the last one and
14055 * raises EOFError for the last one.
14056 *
14057 */
14058
14059static VALUE
14060argf_readpartial(int argc, VALUE *argv, VALUE argf)
14061{
14062 return argf_getpartial(argc, argv, argf, Qnil, 0);
14063}
14064
14065/*
14066 * call-seq:
14067 * ARGF.read_nonblock(maxlen[, options]) -> string
14068 * ARGF.read_nonblock(maxlen, outbuf[, options]) -> outbuf
14069 *
14070 * Reads at most _maxlen_ bytes from the ARGF stream in non-blocking mode.
14071 */
14072
14073static VALUE
14074argf_read_nonblock(int argc, VALUE *argv, VALUE argf)
14075{
14076 VALUE opts;
14077
14078 rb_scan_args(argc, argv, "11:", NULL, NULL, &opts);
14079
14080 if (!NIL_P(opts))
14081 argc--;
14082
14083 return argf_getpartial(argc, argv, argf, opts, 1);
14084}
14085
14086static VALUE
14087argf_getpartial(int argc, VALUE *argv, VALUE argf, VALUE opts, int nonblock)
14088{
14089 VALUE tmp, str, length;
14090 int no_exception;
14091
14092 rb_scan_args(argc, argv, "11", &length, &str);
14093 if (!NIL_P(str)) {
14094 StringValue(str);
14095 argv[1] = str;
14096 }
14097 no_exception = no_exception_p(opts);
14098
14099 if (!next_argv()) {
14100 if (!NIL_P(str)) {
14101 rb_str_resize(str, 0);
14102 }
14103 rb_eof_error();
14104 }
14105 if (ARGF_GENERIC_INPUT_P()) {
14106 VALUE (*const rescue_does_nothing)(VALUE, VALUE) = 0;
14107 struct argf_call_arg arg;
14108 arg.argc = argc;
14109 arg.argv = argv;
14110 arg.argf = argf;
14111 tmp = rb_rescue2(argf_forward_call, (VALUE)&arg,
14112 rescue_does_nothing, Qnil, rb_eEOFError, (VALUE)0);
14113 }
14114 else {
14115 tmp = io_getpartial(argc, argv, ARGF.current_file, no_exception, nonblock);
14116 }
14117 if (NIL_P(tmp)) {
14118 if (ARGF.next_p == -1) {
14119 return io_nonblock_eof(no_exception);
14120 }
14121 argf_close(argf);
14122 ARGF.next_p = 1;
14123 if (RARRAY_LEN(ARGF.argv) == 0) {
14124 return io_nonblock_eof(no_exception);
14125 }
14126 if (NIL_P(str))
14127 str = rb_str_new(NULL, 0);
14128 return str;
14129 }
14130 return tmp;
14131}
14132
14133/*
14134 * call-seq:
14135 * ARGF.getc -> String or nil
14136 *
14137 * Reads the next character from ARGF and returns it as a String. Returns
14138 * +nil+ at the end of the stream.
14139 *
14140 * ARGF treats the files named on the command line as a single file created
14141 * by concatenating their contents. After returning the last character of the
14142 * first file, it returns the first character of the second file, and so on.
14143 *
14144 * For example:
14145 *
14146 * $ echo "foo" > file
14147 * $ ruby argf.rb file
14148 *
14149 * ARGF.getc #=> "f"
14150 * ARGF.getc #=> "o"
14151 * ARGF.getc #=> "o"
14152 * ARGF.getc #=> "\n"
14153 * ARGF.getc #=> nil
14154 * ARGF.getc #=> nil
14155 */
14156static VALUE
14157argf_getc(VALUE argf)
14158{
14159 VALUE ch;
14160
14161 retry:
14162 if (!next_argv()) return Qnil;
14163 if (ARGF_GENERIC_INPUT_P()) {
14164 ch = forward_current(rb_intern("getc"), 0, 0);
14165 }
14166 else {
14167 ch = rb_io_getc(ARGF.current_file);
14168 }
14169 if (NIL_P(ch) && ARGF.next_p != -1) {
14170 argf_close(argf);
14171 ARGF.next_p = 1;
14172 goto retry;
14173 }
14174
14175 return ch;
14176}
14177
14178/*
14179 * call-seq:
14180 * ARGF.getbyte -> Integer or nil
14181 *
14182 * Gets the next 8-bit byte (0..255) from ARGF. Returns +nil+ if called at
14183 * the end of the stream.
14184 *
14185 * For example:
14186 *
14187 * $ echo "foo" > file
14188 * $ ruby argf.rb file
14189 *
14190 * ARGF.getbyte #=> 102
14191 * ARGF.getbyte #=> 111
14192 * ARGF.getbyte #=> 111
14193 * ARGF.getbyte #=> 10
14194 * ARGF.getbyte #=> nil
14195 */
14196static VALUE
14197argf_getbyte(VALUE argf)
14198{
14199 VALUE ch;
14200
14201 retry:
14202 if (!next_argv()) return Qnil;
14203 if (!RB_TYPE_P(ARGF.current_file, T_FILE)) {
14204 ch = forward_current(rb_intern("getbyte"), 0, 0);
14205 }
14206 else {
14207 ch = rb_io_getbyte(ARGF.current_file);
14208 }
14209 if (NIL_P(ch) && ARGF.next_p != -1) {
14210 argf_close(argf);
14211 ARGF.next_p = 1;
14212 goto retry;
14213 }
14214
14215 return ch;
14216}
14217
14218/*
14219 * call-seq:
14220 * ARGF.readchar -> String or nil
14221 *
14222 * Reads the next character from ARGF and returns it as a String. Raises
14223 * an EOFError after the last character of the last file has been read.
14224 *
14225 * For example:
14226 *
14227 * $ echo "foo" > file
14228 * $ ruby argf.rb file
14229 *
14230 * ARGF.readchar #=> "f"
14231 * ARGF.readchar #=> "o"
14232 * ARGF.readchar #=> "o"
14233 * ARGF.readchar #=> "\n"
14234 * ARGF.readchar #=> end of file reached (EOFError)
14235 */
14236static VALUE
14237argf_readchar(VALUE argf)
14238{
14239 VALUE ch;
14240
14241 retry:
14242 if (!next_argv()) rb_eof_error();
14243 if (!RB_TYPE_P(ARGF.current_file, T_FILE)) {
14244 ch = forward_current(rb_intern("getc"), 0, 0);
14245 }
14246 else {
14247 ch = rb_io_getc(ARGF.current_file);
14248 }
14249 if (NIL_P(ch) && ARGF.next_p != -1) {
14250 argf_close(argf);
14251 ARGF.next_p = 1;
14252 goto retry;
14253 }
14254
14255 return ch;
14256}
14257
14258/*
14259 * call-seq:
14260 * ARGF.readbyte -> Integer
14261 *
14262 * Reads the next 8-bit byte from ARGF and returns it as an Integer. Raises
14263 * an EOFError after the last byte of the last file has been read.
14264 *
14265 * For example:
14266 *
14267 * $ echo "foo" > file
14268 * $ ruby argf.rb file
14269 *
14270 * ARGF.readbyte #=> 102
14271 * ARGF.readbyte #=> 111
14272 * ARGF.readbyte #=> 111
14273 * ARGF.readbyte #=> 10
14274 * ARGF.readbyte #=> end of file reached (EOFError)
14275 */
14276static VALUE
14277argf_readbyte(VALUE argf)
14278{
14279 VALUE c;
14280
14281 NEXT_ARGF_FORWARD(0, 0);
14282 c = argf_getbyte(argf);
14283 if (NIL_P(c)) {
14284 rb_eof_error();
14285 }
14286 return c;
14287}
14288
14289#define FOREACH_ARGF() while (next_argv())
14290
14291static VALUE
14292argf_block_call_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, argf))
14293{
14294 const VALUE current = ARGF.current_file;
14295 rb_yield_values2(argc, argv);
14296 if (ARGF.init_p == -1 || current != ARGF.current_file) {
14298 }
14299 return Qnil;
14300}
14301
14302#define ARGF_block_call(mid, argc, argv, func, argf) \
14303 rb_block_call_kw(ARGF.current_file, mid, argc, argv, \
14304 func, argf, rb_keyword_given_p())
14305
14306static void
14307argf_block_call(ID mid, int argc, VALUE *argv, VALUE argf)
14308{
14309 VALUE ret = ARGF_block_call(mid, argc, argv, argf_block_call_i, argf);
14310 if (!UNDEF_P(ret)) ARGF.next_p = 1;
14311}
14312
14313static VALUE
14314argf_block_call_line_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, argf))
14315{
14316 if (!global_argf_p(argf)) {
14317 ARGF.last_lineno = ++ARGF.lineno;
14318 }
14319 return argf_block_call_i(i, argf, argc, argv, blockarg);
14320}
14321
14322static void
14323argf_block_call_line(ID mid, int argc, VALUE *argv, VALUE argf)
14324{
14325 VALUE ret = ARGF_block_call(mid, argc, argv, argf_block_call_line_i, argf);
14326 if (!UNDEF_P(ret)) ARGF.next_p = 1;
14327}
14328
14329/*
14330 * call-seq:
14331 * ARGF.each(sep=$/) {|line| block } -> ARGF
14332 * ARGF.each(sep=$/, limit) {|line| block } -> ARGF
14333 * ARGF.each(...) -> an_enumerator
14334 *
14335 * ARGF.each_line(sep=$/) {|line| block } -> ARGF
14336 * ARGF.each_line(sep=$/, limit) {|line| block } -> ARGF
14337 * ARGF.each_line(...) -> an_enumerator
14338 *
14339 * Returns an enumerator which iterates over each line (separated by _sep_,
14340 * which defaults to your platform's newline character) of each file in
14341 * +ARGV+. If a block is supplied, each line in turn will be yielded to the
14342 * block, otherwise an enumerator is returned.
14343 * The optional _limit_ argument is an Integer specifying the maximum
14344 * length of each line; longer lines will be split according to this limit.
14345 *
14346 * This method allows you to treat the files supplied on the command line as
14347 * a single file consisting of the concatenation of each named file. After
14348 * the last line of the first file has been returned, the first line of the
14349 * second file is returned. The ARGF.filename and ARGF.lineno methods can be
14350 * used to determine the filename of the current line and line number of the
14351 * whole input, respectively.
14352 *
14353 * For example, the following code prints out each line of each named file
14354 * prefixed with its line number, displaying the filename once per file:
14355 *
14356 * ARGF.each_line do |line|
14357 * puts ARGF.filename if ARGF.file.lineno == 1
14358 * puts "#{ARGF.file.lineno}: #{line}"
14359 * end
14360 *
14361 * While the following code prints only the first file's name at first, and
14362 * the contents with line number counted through all named files.
14363 *
14364 * ARGF.each_line do |line|
14365 * puts ARGF.filename if ARGF.lineno == 1
14366 * puts "#{ARGF.lineno}: #{line}"
14367 * end
14368 */
14369static VALUE
14370argf_each_line(int argc, VALUE *argv, VALUE argf)
14371{
14372 RETURN_ENUMERATOR(argf, argc, argv);
14373 FOREACH_ARGF() {
14374 argf_block_call_line(rb_intern("each_line"), argc, argv, argf);
14375 }
14376 return argf;
14377}
14378
14379/*
14380 * call-seq:
14381 * ARGF.each_byte {|byte| block } -> ARGF
14382 * ARGF.each_byte -> an_enumerator
14383 *
14384 * Iterates over each byte of each file in +ARGV+.
14385 * A byte is returned as an Integer in the range 0..255.
14386 *
14387 * This method allows you to treat the files supplied on the command line as
14388 * a single file consisting of the concatenation of each named file. After
14389 * the last byte of the first file has been returned, the first byte of the
14390 * second file is returned. The ARGF.filename method can be used to
14391 * determine the filename of the current byte.
14392 *
14393 * If no block is given, an enumerator is returned instead.
14394 *
14395 * For example:
14396 *
14397 * ARGF.bytes.to_a #=> [35, 32, ... 95, 10]
14398 *
14399 */
14400static VALUE
14401argf_each_byte(VALUE argf)
14402{
14403 RETURN_ENUMERATOR(argf, 0, 0);
14404 FOREACH_ARGF() {
14405 argf_block_call(rb_intern("each_byte"), 0, 0, argf);
14406 }
14407 return argf;
14408}
14409
14410/*
14411 * call-seq:
14412 * ARGF.each_char {|char| block } -> ARGF
14413 * ARGF.each_char -> an_enumerator
14414 *
14415 * Iterates over each character of each file in ARGF.
14416 *
14417 * This method allows you to treat the files supplied on the command line as
14418 * a single file consisting of the concatenation of each named file. After
14419 * the last character of the first file has been returned, the first
14420 * character of the second file is returned. The ARGF.filename method can
14421 * be used to determine the name of the file in which the current character
14422 * appears.
14423 *
14424 * If no block is given, an enumerator is returned instead.
14425 */
14426static VALUE
14427argf_each_char(VALUE argf)
14428{
14429 RETURN_ENUMERATOR(argf, 0, 0);
14430 FOREACH_ARGF() {
14431 argf_block_call(rb_intern("each_char"), 0, 0, argf);
14432 }
14433 return argf;
14434}
14435
14436/*
14437 * call-seq:
14438 * ARGF.each_codepoint {|codepoint| block } -> ARGF
14439 * ARGF.each_codepoint -> an_enumerator
14440 *
14441 * Iterates over each codepoint of each file in ARGF.
14442 *
14443 * This method allows you to treat the files supplied on the command line as
14444 * a single file consisting of the concatenation of each named file. After
14445 * the last codepoint of the first file has been returned, the first
14446 * codepoint of the second file is returned. The ARGF.filename method can
14447 * be used to determine the name of the file in which the current codepoint
14448 * appears.
14449 *
14450 * If no block is given, an enumerator is returned instead.
14451 */
14452static VALUE
14453argf_each_codepoint(VALUE argf)
14454{
14455 RETURN_ENUMERATOR(argf, 0, 0);
14456 FOREACH_ARGF() {
14457 argf_block_call(rb_intern("each_codepoint"), 0, 0, argf);
14458 }
14459 return argf;
14460}
14461
14462/*
14463 * call-seq:
14464 * ARGF.filename -> String
14465 * ARGF.path -> String
14466 *
14467 * Returns the current filename. "-" is returned when the current file is
14468 * STDIN.
14469 *
14470 * For example:
14471 *
14472 * $ echo "foo" > foo
14473 * $ echo "bar" > bar
14474 * $ echo "glark" > glark
14475 *
14476 * $ ruby argf.rb foo bar glark
14477 *
14478 * ARGF.filename #=> "foo"
14479 * ARGF.read(5) #=> "foo\nb"
14480 * ARGF.filename #=> "bar"
14481 * ARGF.skip
14482 * ARGF.filename #=> "glark"
14483 */
14484static VALUE
14485argf_filename(VALUE argf)
14486{
14487 next_argv();
14488 return ARGF.filename;
14489}
14490
14491static VALUE
14492argf_filename_getter(ID id, VALUE *var)
14493{
14494 return argf_filename(*var);
14495}
14496
14497/*
14498 * call-seq:
14499 * ARGF.file -> IO or File object
14500 *
14501 * Returns the current file as an IO or File object.
14502 * <code>$stdin</code> is returned when the current file is STDIN.
14503 *
14504 * For example:
14505 *
14506 * $ echo "foo" > foo
14507 * $ echo "bar" > bar
14508 *
14509 * $ ruby argf.rb foo bar
14510 *
14511 * ARGF.file #=> #<File:foo>
14512 * ARGF.read(5) #=> "foo\nb"
14513 * ARGF.file #=> #<File:bar>
14514 */
14515static VALUE
14516argf_file(VALUE argf)
14517{
14518 next_argv();
14519 return ARGF.current_file;
14520}
14521
14522/*
14523 * call-seq:
14524 * ARGF.binmode -> ARGF
14525 *
14526 * Puts ARGF into binary mode. Once a stream is in binary mode, it cannot
14527 * be reset to non-binary mode. This option has the following effects:
14528 *
14529 * * Newline conversion is disabled.
14530 * * Encoding conversion is disabled.
14531 * * Content is treated as ASCII-8BIT.
14532 */
14533static VALUE
14534argf_binmode_m(VALUE argf)
14535{
14536 ARGF.binmode = 1;
14537 next_argv();
14538 ARGF_FORWARD(0, 0);
14539 rb_io_ascii8bit_binmode(ARGF.current_file);
14540 return argf;
14541}
14542
14543/*
14544 * call-seq:
14545 * ARGF.binmode? -> true or false
14546 *
14547 * Returns true if ARGF is being read in binary mode; false otherwise.
14548 * To enable binary mode use ARGF.binmode.
14549 *
14550 * For example:
14551 *
14552 * ARGF.binmode? #=> false
14553 * ARGF.binmode
14554 * ARGF.binmode? #=> true
14555 */
14556static VALUE
14557argf_binmode_p(VALUE argf)
14558{
14559 return RBOOL(ARGF.binmode);
14560}
14561
14562/*
14563 * call-seq:
14564 * ARGF.skip -> ARGF
14565 *
14566 * Sets the current file to the next file in ARGV. If there aren't any more
14567 * files it has no effect.
14568 *
14569 * For example:
14570 *
14571 * $ ruby argf.rb foo bar
14572 * ARGF.filename #=> "foo"
14573 * ARGF.skip
14574 * ARGF.filename #=> "bar"
14575 */
14576static VALUE
14577argf_skip(VALUE argf)
14578{
14579 if (ARGF.init_p && ARGF.next_p == 0) {
14580 argf_close(argf);
14581 ARGF.next_p = 1;
14582 }
14583 return argf;
14584}
14585
14586/*
14587 * call-seq:
14588 * ARGF.close -> ARGF
14589 *
14590 * Closes the current file and skips to the next file in ARGV. If there are
14591 * no more files to open, just closes the current file. STDIN will not be
14592 * closed.
14593 *
14594 * For example:
14595 *
14596 * $ ruby argf.rb foo bar
14597 *
14598 * ARGF.filename #=> "foo"
14599 * ARGF.close
14600 * ARGF.filename #=> "bar"
14601 * ARGF.close
14602 */
14603static VALUE
14604argf_close_m(VALUE argf)
14605{
14606 next_argv();
14607 argf_close(argf);
14608 if (ARGF.next_p != -1) {
14609 ARGF.next_p = 1;
14610 }
14611 ARGF.lineno = 0;
14612 return argf;
14613}
14614
14615/*
14616 * call-seq:
14617 * ARGF.closed? -> true or false
14618 *
14619 * Returns _true_ if the current file has been closed; _false_ otherwise. Use
14620 * ARGF.close to actually close the current file.
14621 */
14622static VALUE
14623argf_closed(VALUE argf)
14624{
14625 next_argv();
14626 ARGF_FORWARD(0, 0);
14627 return rb_io_closed_p(ARGF.current_file);
14628}
14629
14630/*
14631 * call-seq:
14632 * ARGF.to_s -> String
14633 *
14634 * Returns "ARGF".
14635 */
14636static VALUE
14637argf_to_s(VALUE argf)
14638{
14639 return rb_str_new2("ARGF");
14640}
14641
14642/*
14643 * call-seq:
14644 * ARGF.inplace_mode -> String
14645 *
14646 * Returns the file extension appended to the names of backup copies of
14647 * modified files under in-place edit mode. This value can be set using
14648 * ARGF.inplace_mode= or passing the +-i+ switch to the Ruby binary.
14649 */
14650static VALUE
14651argf_inplace_mode_get(VALUE argf)
14652{
14653 if (!ARGF.inplace) return Qnil;
14654 if (NIL_P(ARGF.inplace)) return rb_str_new(0, 0);
14655 return rb_str_dup(ARGF.inplace);
14656}
14657
14658static VALUE
14659opt_i_get(ID id, VALUE *var)
14660{
14661 return argf_inplace_mode_get(*var);
14662}
14663
14664/*
14665 * call-seq:
14666 * ARGF.inplace_mode = ext -> ARGF
14667 *
14668 * Sets the filename extension for in-place editing mode to the given String.
14669 * The backup copy of each file being edited has this value appended to its
14670 * filename.
14671 *
14672 * For example:
14673 *
14674 * $ ruby argf.rb file.txt
14675 *
14676 * ARGF.inplace_mode = '.bak'
14677 * ARGF.each_line do |line|
14678 * print line.sub("foo","bar")
14679 * end
14680 *
14681 * First, _file.txt.bak_ is created as a backup copy of _file.txt_.
14682 * Then, each line of _file.txt_ has the first occurrence of "foo" replaced with
14683 * "bar".
14684 */
14685static VALUE
14686argf_inplace_mode_set(VALUE argf, VALUE val)
14687{
14688 if (!RTEST(val)) {
14689 ARGF.inplace = Qfalse;
14690 }
14691 else if (StringValueCStr(val), !RSTRING_LEN(val)) {
14692 ARGF.inplace = Qnil;
14693 }
14694 else {
14695 ARGF.inplace = rb_str_new_frozen(val);
14696 }
14697 return argf;
14698}
14699
14700static void
14701opt_i_set(VALUE val, ID id, VALUE *var)
14702{
14703 argf_inplace_mode_set(*var, val);
14704}
14705
14706void
14707ruby_set_inplace_mode(const char *suffix)
14708{
14709 ARGF.inplace = !suffix ? Qfalse : !*suffix ? Qnil : rb_str_new(suffix, strlen(suffix));
14710}
14711
14712/*
14713 * call-seq:
14714 * ARGF.argv -> ARGV
14715 *
14716 * Returns the +ARGV+ array, which contains the arguments passed to your
14717 * script, one per element.
14718 *
14719 * For example:
14720 *
14721 * $ ruby argf.rb -v glark.txt
14722 *
14723 * ARGF.argv #=> ["-v", "glark.txt"]
14724 *
14725 */
14726static VALUE
14727argf_argv(VALUE argf)
14728{
14729 return ARGF.argv;
14730}
14731
14732static VALUE
14733argf_argv_getter(ID id, VALUE *var)
14734{
14735 return argf_argv(*var);
14736}
14737
14738VALUE
14740{
14741 return ARGF.argv;
14742}
14743
14744/*
14745 * call-seq:
14746 * ARGF.to_write_io -> io
14747 *
14748 * Returns IO instance tied to _ARGF_ for writing if inplace mode is
14749 * enabled.
14750 */
14751static VALUE
14752argf_write_io(VALUE argf)
14753{
14754 if (!RTEST(ARGF.current_file)) {
14755 rb_raise(rb_eIOError, "not opened for writing");
14756 }
14757 return GetWriteIO(ARGF.current_file);
14758}
14759
14760/*
14761 * call-seq:
14762 * ARGF.write(*objects) -> integer
14763 *
14764 * Writes each of the given +objects+ if inplace mode.
14765 */
14766static VALUE
14767argf_write(int argc, VALUE *argv, VALUE argf)
14768{
14769 return rb_io_writev(argf_write_io(argf), argc, argv);
14770}
14771
14772void
14773rb_readwrite_sys_fail(enum rb_io_wait_readwrite waiting, const char *mesg)
14774{
14775 rb_readwrite_syserr_fail(waiting, errno, mesg);
14776}
14777
14778void
14779rb_readwrite_syserr_fail(enum rb_io_wait_readwrite waiting, int n, const char *mesg)
14780{
14781 VALUE arg, c = Qnil;
14782 arg = mesg ? rb_str_new2(mesg) : Qnil;
14783 switch (waiting) {
14784 case RB_IO_WAIT_WRITABLE:
14785 switch (n) {
14786 case EAGAIN:
14787 c = rb_eEAGAINWaitWritable;
14788 break;
14789#if EAGAIN != EWOULDBLOCK
14790 case EWOULDBLOCK:
14791 c = rb_eEWOULDBLOCKWaitWritable;
14792 break;
14793#endif
14794 case EINPROGRESS:
14795 c = rb_eEINPROGRESSWaitWritable;
14796 break;
14797 default:
14799 }
14800 break;
14801 case RB_IO_WAIT_READABLE:
14802 switch (n) {
14803 case EAGAIN:
14804 c = rb_eEAGAINWaitReadable;
14805 break;
14806#if EAGAIN != EWOULDBLOCK
14807 case EWOULDBLOCK:
14808 c = rb_eEWOULDBLOCKWaitReadable;
14809 break;
14810#endif
14811 case EINPROGRESS:
14812 c = rb_eEINPROGRESSWaitReadable;
14813 break;
14814 default:
14816 }
14817 break;
14818 default:
14819 rb_bug("invalid read/write type passed to rb_readwrite_sys_fail: %d", waiting);
14820 }
14822}
14823
14824static VALUE
14825get_LAST_READ_LINE(ID _x, VALUE *_y)
14826{
14827 return rb_lastline_get();
14828}
14829
14830static void
14831set_LAST_READ_LINE(VALUE val, ID _x, VALUE *_y)
14832{
14833 rb_lastline_set(val);
14834}
14835
14836/*
14837 * Document-class: IOError
14838 *
14839 * Raised when an IO operation fails.
14840 *
14841 * File.open("/etc/hosts") {|f| f << "example"}
14842 * #=> IOError: not opened for writing
14843 *
14844 * File.open("/etc/hosts") {|f| f.close; f.read }
14845 * #=> IOError: closed stream
14846 *
14847 * Note that some IO failures raise <code>SystemCallError</code>s
14848 * and these are not subclasses of IOError:
14849 *
14850 * File.open("does/not/exist")
14851 * #=> Errno::ENOENT: No such file or directory - does/not/exist
14852 */
14853
14854/*
14855 * Document-class: EOFError
14856 *
14857 * Raised by some IO operations when reaching the end of file. Many IO
14858 * methods exist in two forms,
14859 *
14860 * one that returns +nil+ when the end of file is reached, the other
14861 * raises EOFError.
14862 *
14863 * EOFError is a subclass of IOError.
14864 *
14865 * file = File.open("/etc/hosts")
14866 * file.read
14867 * file.gets #=> nil
14868 * file.readline #=> EOFError: end of file reached
14869 * file.close
14870 */
14871
14872/*
14873 * Document-class: ARGF
14874 *
14875 * == \ARGF and +ARGV+
14876 *
14877 * The \ARGF object works with the array at global variable +ARGV+
14878 * to make <tt>$stdin</tt> and file streams available in the Ruby program:
14879 *
14880 * - **ARGV** may be thought of as the <b>argument vector</b> array.
14881 *
14882 * Initially, it contains the command-line arguments and options
14883 * that are passed to the Ruby program;
14884 * the program can modify that array as it likes.
14885 *
14886 * - **ARGF** may be thought of as the <b>argument files</b> object.
14887 *
14888 * It can access file streams and/or the <tt>$stdin</tt> stream,
14889 * based on what it finds in +ARGV+.
14890 * This provides a convenient way for the command line
14891 * to specify streams for a Ruby program to read.
14892 *
14893 * == Reading
14894 *
14895 * \ARGF may read from _source_ streams,
14896 * which at any particular time are determined by the content of +ARGV+.
14897 *
14898 * === Simplest Case
14899 *
14900 * When the <i>very first</i> \ARGF read occurs with an empty +ARGV+ (<tt>[]</tt>),
14901 * the source is <tt>$stdin</tt>:
14902 *
14903 * - \File +t.rb+:
14904 *
14905 * p ['ARGV', ARGV]
14906 * p ['ARGF.read', ARGF.read]
14907 *
14908 * - Commands and outputs
14909 * (see below for the content of files +foo.txt+ and +bar.txt+):
14910 *
14911 * $ echo "Open the pod bay doors, Hal." | ruby t.rb
14912 * ["ARGV", []]
14913 * ["ARGF.read", "Open the pod bay doors, Hal.\n"]
14914 *
14915 * $ cat foo.txt bar.txt | ruby t.rb
14916 * ["ARGV", []]
14917 * ["ARGF.read", "Foo 0\nFoo 1\nBar 0\nBar 1\nBar 2\nBar 3\n"]
14918 *
14919 * === About the Examples
14920 *
14921 * Many examples here assume the existence of files +foo.txt+ and +bar.txt+:
14922 *
14923 * $ cat foo.txt
14924 * Foo 0
14925 * Foo 1
14926 * $ cat bar.txt
14927 * Bar 0
14928 * Bar 1
14929 * Bar 2
14930 * Bar 3
14931 *
14932 * === Sources in +ARGV+
14933 *
14934 * For any \ARGF read _except_ the {simplest case}[rdoc-ref:ARGF@Simplest+Case]
14935 * (that is, _except_ for the <i>very first</i> \ARGF read with an empty +ARGV+),
14936 * the sources are found in +ARGV+.
14937 *
14938 * \ARGF assumes that each element in array +ARGV+ is a potential source,
14939 * and is one of:
14940 *
14941 * - The string path to a file that may be opened as a stream.
14942 * - The character <tt>'-'</tt>, meaning stream <tt>$stdin</tt>.
14943 *
14944 * Each element that is _not_ one of these
14945 * should be removed from +ARGV+ before \ARGF accesses that source.
14946 *
14947 * In the following example:
14948 *
14949 * - Filepaths +foo.txt+ and +bar.txt+ may be retained as potential sources.
14950 * - Options <tt>--xyzzy</tt> and <tt>--mojo</tt> should be removed.
14951 *
14952 * Example:
14953 *
14954 * - \File +t.rb+:
14955 *
14956 * # Print arguments (and options, if any) found on command line.
14957 * p ['ARGV', ARGV]
14958 *
14959 * - Command and output:
14960 *
14961 * $ ruby t.rb --xyzzy --mojo foo.txt bar.txt
14962 * ["ARGV", ["--xyzzy", "--mojo", "foo.txt", "bar.txt"]]
14963 *
14964 * \ARGF's stream access considers the elements of +ARGV+, left to right:
14965 *
14966 * - \File +t.rb+:
14967 *
14968 * p "ARGV: #{ARGV}"
14969 * p "Read: #{ARGF.read}" # Read everything from all specified streams.
14970 *
14971 * - Command and output:
14972 *
14973 * $ ruby t.rb foo.txt bar.txt
14974 * "ARGV: [\"foo.txt\", \"bar.txt\"]"
14975 * "Read: Foo 0\nFoo 1\nBar 0\nBar 1\nBar 2\nBar 3\n"
14976 *
14977 * Because the value at +ARGV+ is an ordinary array,
14978 * you can manipulate it to control which sources \ARGF considers:
14979 *
14980 * - If you remove an element from +ARGV+, \ARGF will not consider the corresponding source.
14981 * - If you add an element to +ARGV+, \ARGF will consider the corresponding source.
14982 *
14983 * Each element in +ARGV+ is removed when its corresponding source is accessed;
14984 * when all sources have been accessed, the array is empty:
14985 *
14986 * - \File +t.rb+:
14987 *
14988 * until ARGV.empty? && ARGF.eof?
14989 * p "ARGV: #{ARGV}"
14990 * p "Line: #{ARGF.readline}" # Read each line from each specified stream.
14991 * end
14992 *
14993 * - Command and output:
14994 *
14995 * $ ruby t.rb foo.txt bar.txt
14996 * "ARGV: [\"foo.txt\", \"bar.txt\"]"
14997 * "Line: Foo 0\n"
14998 * "ARGV: [\"bar.txt\"]"
14999 * "Line: Foo 1\n"
15000 * "ARGV: [\"bar.txt\"]"
15001 * "Line: Bar 0\n"
15002 * "ARGV: []"
15003 * "Line: Bar 1\n"
15004 * "ARGV: []"
15005 * "Line: Bar 2\n"
15006 * "ARGV: []"
15007 * "Line: Bar 3\n"
15008 *
15009 * ==== Filepaths in +ARGV+
15010 *
15011 * The +ARGV+ array may contain filepaths the specify sources for \ARGF reading.
15012 *
15013 * This program prints what it reads from files at the paths specified
15014 * on the command line:
15015 *
15016 * - \File +t.rb+:
15017 *
15018 * p ['ARGV', ARGV]
15019 * # Read and print all content from the specified sources.
15020 * p ['ARGF.read', ARGF.read]
15021 *
15022 * - Command and output:
15023 *
15024 * $ ruby t.rb foo.txt bar.txt
15025 * ["ARGV", [foo.txt, bar.txt]
15026 * ["ARGF.read", "Foo 0\nFoo 1\nBar 0\nBar 1\nBar 2\nBar 3\n"]
15027 *
15028 * ==== Specifying <tt>$stdin</tt> in +ARGV+
15029 *
15030 * To specify stream <tt>$stdin</tt> in +ARGV+, us the character <tt>'-'</tt>:
15031 *
15032 * - \File +t.rb+:
15033 *
15034 * p ['ARGV', ARGV]
15035 * p ['ARGF.read', ARGF.read]
15036 *
15037 * - Command and output:
15038 *
15039 * $ echo "Open the pod bay doors, Hal." | ruby t.rb -
15040 * ["ARGV", ["-"]]
15041 * ["ARGF.read", "Open the pod bay doors, Hal.\n"]
15042 *
15043 * When no character <tt>'-'</tt> is given, stream <tt>$stdin</tt> is ignored
15044 * (exception:
15045 * see {Specifying $stdin in ARGV}[rdoc-ref:ARGF@Specifying+-24stdin+in+ARGV]):
15046 *
15047 * - Command and output:
15048 *
15049 * $ echo "Open the pod bay doors, Hal." | ruby t.rb foo.txt bar.txt
15050 * "ARGV: [\"foo.txt\", \"bar.txt\"]"
15051 * "Read: Foo 0\nFoo 1\nBar 0\nBar 1\nBar 2\nBar 3\n"
15052 *
15053 * ==== Mixtures and Repetitions in +ARGV+
15054 *
15055 * For an \ARGF reader, +ARGV+ may contain any mixture of filepaths
15056 * and character <tt>'-'</tt>, including repetitions.
15057 *
15058 * ==== Modifications to +ARGV+
15059 *
15060 * The running Ruby program may make any modifications to the +ARGV+ array;
15061 * the current value of +ARGV+ affects \ARGF reading.
15062 *
15063 * ==== Empty +ARGV+
15064 *
15065 * For an empty +ARGV+, an \ARGF read method either returns +nil+
15066 * or raises an exception, depending on the specific method.
15067 *
15068 * === More Read Methods
15069 *
15070 * As seen above, method ARGF#read reads the content of all sources
15071 * into a single string.
15072 * Other \ARGF methods provide other ways to access that content;
15073 * these include:
15074 *
15075 * - Byte access: #each_byte, #getbyte, #readbyte.
15076 * - Character access: #each_char, #getc, #readchar.
15077 * - Codepoint access: #each_codepoint.
15078 * - Line access: #each_line, #gets, #readline, #readlines.
15079 * - Source access: #read, #read_nonblock, #readpartial.
15080 *
15081 * === About \Enumerable
15082 *
15083 * \ARGF includes module Enumerable.
15084 * Virtually all methods in \Enumerable call method <tt>#each</tt> in the including class.
15085 *
15086 * <b>Note well</b>: In \ARGF, method #each returns data from the _sources_,
15087 * _not_ from +ARGV+;
15088 * therefore, for example, <tt>ARGF#entries</tt> returns an array of lines from the sources,
15089 * not an array of the strings from +ARGV+:
15090 *
15091 * - \File +t.rb+:
15092 *
15093 * p ['ARGV', ARGV]
15094 * p ['ARGF.entries', ARGF.entries]
15095 *
15096 * - Command and output:
15097 *
15098 * $ ruby t.rb foo.txt bar.txt
15099 * ["ARGV", ["foo.txt", "bar.txt"]]
15100 * ["ARGF.entries", ["Foo 0\n", "Foo 1\n", "Bar 0\n", "Bar 1\n", "Bar 2\n", "Bar 3\n"]]
15101 *
15102 * == Writing
15103 *
15104 * If <i>inplace mode</i> is in effect,
15105 * \ARGF may write to target streams,
15106 * which at any particular time are determined by the content of ARGV.
15107 *
15108 * Methods about inplace mode:
15109 *
15110 * - #inplace_mode
15111 * - #inplace_mode=
15112 * - #to_write_io
15113 *
15114 * Methods for writing:
15115 *
15116 * - #print
15117 * - #printf
15118 * - #putc
15119 * - #puts
15120 * - #write
15121 *
15122 */
15123
15124/*
15125 * An instance of class \IO (commonly called a _stream_)
15126 * represents an input/output stream in the underlying operating system.
15127 * Class \IO is the basis for input and output in Ruby.
15128 *
15129 * Class File is the only class in the Ruby core that is a subclass of \IO.
15130 * Some classes in the Ruby standard library are also subclasses of \IO;
15131 * these include TCPSocket and UDPSocket.
15132 *
15133 * The global constant ARGF (also accessible as <tt>$<</tt>)
15134 * provides an IO-like stream that allows access to all file paths
15135 * found in ARGV (or found in STDIN if ARGV is empty).
15136 * ARGF is not itself a subclass of \IO.
15137 *
15138 * Class StringIO provides an IO-like stream that handles a String.
15139 * StringIO is not itself a subclass of \IO.
15140 *
15141 * Important objects based on \IO include:
15142 *
15143 * - $stdin.
15144 * - $stdout.
15145 * - $stderr.
15146 * - Instances of class File.
15147 *
15148 * An instance of \IO may be created using:
15149 *
15150 * - IO.new: returns a new \IO object for the given integer file descriptor.
15151 * - IO.open: passes a new \IO object to the given block.
15152 * - IO.popen: returns a new \IO object that is connected to the $stdin and $stdout
15153 * of a newly-launched subprocess.
15154 * - Kernel#open: Returns a new \IO object connected to a given source:
15155 * stream, file, or subprocess.
15156 *
15157 * Like a File stream, an \IO stream has:
15158 *
15159 * - A read/write mode, which may be read-only, write-only, or read/write;
15160 * see {Read/Write Mode}[rdoc-ref:File@Read-2FWrite+Mode].
15161 * - A data mode, which may be text-only or binary;
15162 * see {Data Mode}[rdoc-ref:File@Data+Mode].
15163 * - Internal and external encodings;
15164 * see {Encodings}[rdoc-ref:File@Encodings].
15165 *
15166 * And like other \IO streams, it has:
15167 *
15168 * - A position, which determines where in the stream the next
15169 * read or write is to occur;
15170 * see {Position}[rdoc-ref:IO@Position].
15171 * - A line number, which is a special, line-oriented, "position"
15172 * (different from the position mentioned above);
15173 * see {Line Number}[rdoc-ref:IO@Line+Number].
15174 *
15175 * == Extension <tt>io/console</tt>
15176 *
15177 * Extension <tt>io/console</tt> provides numerous methods
15178 * for interacting with the console;
15179 * requiring it adds numerous methods to class \IO.
15180 *
15181 * == Example Files
15182 *
15183 * Many examples here use these variables:
15184 *
15185 * :include: doc/examples/files.rdoc
15186 *
15187 * == Open Options
15188 *
15189 * A number of \IO methods accept optional keyword arguments
15190 * that determine how a new stream is to be opened:
15191 *
15192 * - +:mode+: Stream mode.
15193 * - +:flags+: Integer file open flags;
15194 * If +mode+ is also given, the two are bitwise-ORed.
15195 * - +:external_encoding+: External encoding for the stream.
15196 * - +:internal_encoding+: Internal encoding for the stream.
15197 * <tt>'-'</tt> is a synonym for the default internal encoding.
15198 * If the value is +nil+ no conversion occurs.
15199 * - +:encoding+: Specifies external and internal encodings as <tt>'extern:intern'</tt>.
15200 * - +:textmode+: If a truthy value, specifies the mode as text-only, binary otherwise.
15201 * - +:binmode+: If a truthy value, specifies the mode as binary, text-only otherwise.
15202 * - +:autoclose+: If a truthy value, specifies that the +fd+ will close
15203 * when the stream closes; otherwise it remains open.
15204 * - +:path:+ If a string value is provided, it is used in #inspect and is available as
15205 * #path method.
15206 *
15207 * Also available are the options offered in String#encode,
15208 * which may control conversion between external and internal encoding.
15209 *
15210 * == Basic \IO
15211 *
15212 * You can perform basic stream \IO with these methods,
15213 * which typically operate on multi-byte strings:
15214 *
15215 * - IO#read: Reads and returns some or all of the remaining bytes from the stream.
15216 * - IO#write: Writes zero or more strings to the stream;
15217 * each given object that is not already a string is converted via +to_s+.
15218 *
15219 * === Position
15220 *
15221 * An \IO stream has a nonnegative integer _position_,
15222 * which is the byte offset at which the next read or write is to occur.
15223 * A new stream has position zero (and line number zero);
15224 * method +rewind+ resets the position (and line number) to zero.
15225 *
15226 * These methods discard {buffers}[rdoc-ref:IO@Buffering] and the
15227 * Encoding::Converter instances used for that \IO.
15228 *
15229 * The relevant methods:
15230 *
15231 * - IO#tell (aliased as +#pos+): Returns the current position (in bytes) in the stream.
15232 * - IO#pos=: Sets the position of the stream to a given integer +new_position+ (in bytes).
15233 * - IO#seek: Sets the position of the stream to a given integer +offset+ (in bytes),
15234 * relative to a given position +whence+
15235 * (indicating the beginning, end, or current position).
15236 * - IO#rewind: Positions the stream at the beginning (also resetting the line number).
15237 *
15238 * === Open and Closed Streams
15239 *
15240 * A new \IO stream may be open for reading, open for writing, or both.
15241 *
15242 * A stream is automatically closed when claimed by the garbage collector.
15243 *
15244 * Attempted reading or writing on a closed stream raises an exception.
15245 *
15246 * The relevant methods:
15247 *
15248 * - IO#close: Closes the stream for both reading and writing.
15249 * - IO#close_read: Closes the stream for reading.
15250 * - IO#close_write: Closes the stream for writing.
15251 * - IO#closed?: Returns whether the stream is closed.
15252 *
15253 * === End-of-Stream
15254 *
15255 * You can query whether a stream is positioned at its end:
15256 *
15257 * - IO#eof? (also aliased as +#eof+): Returns whether the stream is at end-of-stream.
15258 *
15259 * You can reposition to end-of-stream by using method IO#seek:
15260 *
15261 * f = File.new('t.txt')
15262 * f.eof? # => false
15263 * f.seek(0, :END)
15264 * f.eof? # => true
15265 * f.close
15266 *
15267 * Or by reading all stream content (which is slower than using IO#seek):
15268 *
15269 * f.rewind
15270 * f.eof? # => false
15271 * f.read # => "First line\nSecond line\n\nFourth line\nFifth line\n"
15272 * f.eof? # => true
15273 *
15274 * == Line \IO
15275 *
15276 * Class \IO supports line-oriented
15277 * {input}[rdoc-ref:IO@Line+Input] and {output}[rdoc-ref:IO@Line+Output]
15278 *
15279 * === Line Input
15280 *
15281 * Class \IO supports line-oriented input for
15282 * {files}[rdoc-ref:IO@File+Line+Input] and {IO streams}[rdoc-ref:IO@Stream+Line+Input]
15283 *
15284 * ==== \File Line Input
15285 *
15286 * You can read lines from a file using these methods:
15287 *
15288 * - IO.foreach: Reads each line and passes it to the given block.
15289 * - IO.readlines: Reads and returns all lines in an array.
15290 *
15291 * For each of these methods:
15292 *
15293 * - You can specify {open options}[rdoc-ref:IO@Open+Options].
15294 * - Line parsing depends on the effective <i>line separator</i>;
15295 * see {Line Separator}[rdoc-ref:IO@Line+Separator].
15296 * - The length of each returned line depends on the effective <i>line limit</i>;
15297 * see {Line Limit}[rdoc-ref:IO@Line+Limit].
15298 *
15299 * ==== Stream Line Input
15300 *
15301 * You can read lines from an \IO stream using these methods:
15302 *
15303 * - IO#each_line: Reads each remaining line, passing it to the given block.
15304 * - IO#gets: Returns the next line.
15305 * - IO#readline: Like #gets, but raises an exception at end-of-stream.
15306 * - IO#readlines: Returns all remaining lines in an array.
15307 *
15308 * For each of these methods:
15309 *
15310 * - Reading may begin mid-line,
15311 * depending on the stream's _position_;
15312 * see {Position}[rdoc-ref:IO@Position].
15313 * - Line parsing depends on the effective <i>line separator</i>;
15314 * see {Line Separator}[rdoc-ref:IO@Line+Separator].
15315 * - The length of each returned line depends on the effective <i>line limit</i>;
15316 * see {Line Limit}[rdoc-ref:IO@Line+Limit].
15317 *
15318 * ===== Line Separator
15319 *
15320 * Each of the {line input methods}[rdoc-ref:IO@Line+Input] uses a <i>line separator</i>:
15321 * the string that determines what is considered a line;
15322 * it is sometimes called the <i>input record separator</i>.
15323 *
15324 * The default line separator is taken from global variable <tt>$/</tt>,
15325 * whose initial value is <tt>"\n"</tt>.
15326 *
15327 * Generally, the line to be read next is all data
15328 * from the current {position}[rdoc-ref:IO@Position]
15329 * to the next line separator
15330 * (but see {Special Line Separator Values}[rdoc-ref:IO@Special+Line+Separator+Values]):
15331 *
15332 * f = File.new('t.txt')
15333 * # Method gets with no sep argument returns the next line, according to $/.
15334 * f.gets # => "First line\n"
15335 * f.gets # => "Second line\n"
15336 * f.gets # => "\n"
15337 * f.gets # => "Fourth line\n"
15338 * f.gets # => "Fifth line\n"
15339 * f.close
15340 *
15341 * You can use a different line separator by passing argument +sep+:
15342 *
15343 * f = File.new('t.txt')
15344 * f.gets('l') # => "First l"
15345 * f.gets('li') # => "ine\nSecond li"
15346 * f.gets('lin') # => "ne\n\nFourth lin"
15347 * f.gets # => "e\n"
15348 * f.close
15349 *
15350 * Or by setting global variable <tt>$/</tt>:
15351 *
15352 * f = File.new('t.txt')
15353 * $/ = 'l'
15354 * f.gets # => "First l"
15355 * f.gets # => "ine\nSecond l"
15356 * f.gets # => "ine\n\nFourth l"
15357 * f.close
15358 *
15359 * ===== Special Line Separator Values
15360 *
15361 * Each of the {line input methods}[rdoc-ref:IO@Line+Input]
15362 * accepts two special values for parameter +sep+:
15363 *
15364 * - +nil+: The entire stream is to be read ("slurped") into a single string:
15365 *
15366 * f = File.new('t.txt')
15367 * f.gets(nil) # => "First line\nSecond line\n\nFourth line\nFifth line\n"
15368 * f.close
15369 *
15370 * - <tt>''</tt> (the empty string): The next "paragraph" is to be read
15371 * (paragraphs being separated by two consecutive line separators):
15372 *
15373 * f = File.new('t.txt')
15374 * f.gets('') # => "First line\nSecond line\n\n"
15375 * f.gets('') # => "Fourth line\nFifth line\n"
15376 * f.close
15377 *
15378 * ===== Line Limit
15379 *
15380 * Each of the {line input methods}[rdoc-ref:IO@Line+Input]
15381 * uses an integer <i>line limit</i>,
15382 * which restricts the number of bytes that may be returned.
15383 * (A multi-byte character will not be split, and so a returned line may be slightly longer
15384 * than the limit).
15385 *
15386 * The default limit value is <tt>-1</tt>;
15387 * any negative limit value means that there is no limit.
15388 *
15389 * If there is no limit, the line is determined only by +sep+.
15390 *
15391 * # Text with 1-byte characters.
15392 * File.open('t.txt') {|f| f.gets(1) } # => "F"
15393 * File.open('t.txt') {|f| f.gets(2) } # => "Fi"
15394 * File.open('t.txt') {|f| f.gets(3) } # => "Fir"
15395 * File.open('t.txt') {|f| f.gets(4) } # => "Firs"
15396 * # No more than one line.
15397 * File.open('t.txt') {|f| f.gets(10) } # => "First line"
15398 * File.open('t.txt') {|f| f.gets(11) } # => "First line\n"
15399 * File.open('t.txt') {|f| f.gets(12) } # => "First line\n"
15400 *
15401 * # Text with 2-byte characters, which will not be split.
15402 * File.open('t.rus') {|f| f.gets(1).size } # => 1
15403 * File.open('t.rus') {|f| f.gets(2).size } # => 1
15404 * File.open('t.rus') {|f| f.gets(3).size } # => 2
15405 * File.open('t.rus') {|f| f.gets(4).size } # => 2
15406 *
15407 * ===== Line Separator and Line Limit
15408 *
15409 * With arguments +sep+ and +limit+ given, combines the two behaviors:
15410 *
15411 * - Returns the next line as determined by line separator +sep+.
15412 * - But returns no more bytes than are allowed by the limit +limit+.
15413 *
15414 * Example:
15415 *
15416 * File.open('t.txt') {|f| f.gets('li', 20) } # => "First li"
15417 * File.open('t.txt') {|f| f.gets('li', 2) } # => "Fi"
15418 *
15419 * ===== Line Number
15420 *
15421 * A readable \IO stream has a non-negative integer <i>line number</i>:
15422 *
15423 * - IO#lineno: Returns the line number.
15424 * - IO#lineno=: Resets and returns the line number.
15425 *
15426 * Unless modified by a call to method IO#lineno=,
15427 * the line number is the number of lines read
15428 * by certain line-oriented methods,
15429 * according to the effective {line separator}[rdoc-ref:IO@Line+Separator]:
15430 *
15431 * - IO.foreach: Increments the line number on each call to the block.
15432 * - IO#each_line: Increments the line number on each call to the block.
15433 * - IO#gets: Increments the line number.
15434 * - IO#readline: Increments the line number.
15435 * - IO#readlines: Increments the line number for each line read.
15436 *
15437 * A new stream is initially has line number zero (and position zero);
15438 * method +rewind+ resets the line number (and position) to zero:
15439 *
15440 * f = File.new('t.txt')
15441 * f.lineno # => 0
15442 * f.gets # => "First line\n"
15443 * f.lineno # => 1
15444 * f.rewind
15445 * f.lineno # => 0
15446 * f.close
15447 *
15448 * Reading lines from a stream usually changes its line number:
15449 *
15450 * f = File.new('t.txt', 'r')
15451 * f.lineno # => 0
15452 * f.readline # => "This is line one.\n"
15453 * f.lineno # => 1
15454 * f.readline # => "This is the second line.\n"
15455 * f.lineno # => 2
15456 * f.readline # => "Here's the third line.\n"
15457 * f.lineno # => 3
15458 * f.eof? # => true
15459 * f.close
15460 *
15461 * Iterating over lines in a stream usually changes its line number:
15462 *
15463 * File.open('t.txt') do |f|
15464 * f.each_line do |line|
15465 * p "position=#{f.pos} eof?=#{f.eof?} lineno=#{f.lineno}"
15466 * end
15467 * end
15468 *
15469 * Output:
15470 *
15471 * "position=11 eof?=false lineno=1"
15472 * "position=23 eof?=false lineno=2"
15473 * "position=24 eof?=false lineno=3"
15474 * "position=36 eof?=false lineno=4"
15475 * "position=47 eof?=true lineno=5"
15476 *
15477 * Unlike the stream's {position}[rdoc-ref:IO@Position],
15478 * the line number does not affect where the next read or write will occur:
15479 *
15480 * f = File.new('t.txt')
15481 * f.lineno = 1000
15482 * f.lineno # => 1000
15483 * f.gets # => "First line\n"
15484 * f.lineno # => 1001
15485 * f.close
15486 *
15487 * Associated with the line number is the global variable <tt>$.</tt>:
15488 *
15489 * - When a stream is opened, <tt>$.</tt> is not set;
15490 * its value is left over from previous activity in the process:
15491 *
15492 * $. = 41
15493 * f = File.new('t.txt')
15494 * $. = 41
15495 * # => 41
15496 * f.close
15497 *
15498 * - When a stream is read, <tt>$.</tt> is set to the line number for that stream:
15499 *
15500 * f0 = File.new('t.txt')
15501 * f1 = File.new('t.dat')
15502 * f0.readlines # => ["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"]
15503 * $. # => 5
15504 * f1.readlines # => ["\xFE\xFF\x99\x90\x99\x91\x99\x92\x99\x93\x99\x94"]
15505 * $. # => 1
15506 * f0.close
15507 * f1.close
15508 *
15509 * - Methods IO#rewind and IO#seek do not affect <tt>$.</tt>:
15510 *
15511 * f = File.new('t.txt')
15512 * f.readlines # => ["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"]
15513 * $. # => 5
15514 * f.rewind
15515 * f.seek(0, :SET)
15516 * $. # => 5
15517 * f.close
15518 *
15519 * === Line Output
15520 *
15521 * You can write to an \IO stream line-by-line using this method:
15522 *
15523 * - IO#puts: Writes objects to the stream.
15524 *
15525 * == Character \IO
15526 *
15527 * You can process an \IO stream character-by-character using these methods:
15528 *
15529 * - IO#getc: Reads and returns the next character from the stream.
15530 * - IO#readchar: Like #getc, but raises an exception at end-of-stream.
15531 * - IO#ungetc: Pushes back ("unshifts") a character or integer onto the stream.
15532 * - IO#putc: Writes a character to the stream.
15533 * - IO#each_char: Reads each remaining character in the stream,
15534 * passing the character to the given block.
15535 *
15536 * == Byte \IO
15537 *
15538 * You can process an \IO stream byte-by-byte using these methods:
15539 *
15540 * - IO#getbyte: Returns the next 8-bit byte as an integer in range 0..255.
15541 * - IO#readbyte: Like #getbyte, but raises an exception if at end-of-stream.
15542 * - IO#ungetbyte: Pushes back ("unshifts") a byte back onto the stream.
15543 * - IO#each_byte: Reads each remaining byte in the stream,
15544 * passing the byte to the given block.
15545 *
15546 * == Codepoint \IO
15547 *
15548 * You can process an \IO stream codepoint-by-codepoint:
15549 *
15550 * - IO#each_codepoint: Reads each remaining codepoint, passing it to the given block.
15551 *
15552 * == What's Here
15553 *
15554 * First, what's elsewhere. Class \IO:
15555 *
15556 * - Inherits from {class Object}[rdoc-ref:Object@What-27s+Here].
15557 * - Includes {module Enumerable}[rdoc-ref:Enumerable@What-27s+Here],
15558 * which provides dozens of additional methods.
15559 *
15560 * Here, class \IO provides methods that are useful for:
15561 *
15562 * - {Creating}[rdoc-ref:IO@Creating]
15563 * - {Reading}[rdoc-ref:IO@Reading]
15564 * - {Writing}[rdoc-ref:IO@Writing]
15565 * - {Positioning}[rdoc-ref:IO@Positioning]
15566 * - {Iterating}[rdoc-ref:IO@Iterating]
15567 * - {Settings}[rdoc-ref:IO@Settings]
15568 * - {Querying}[rdoc-ref:IO@Querying]
15569 * - {Buffering}[rdoc-ref:IO@Buffering]
15570 * - {Low-Level Access}[rdoc-ref:IO@Low-Level+Access]
15571 * - {Other}[rdoc-ref:IO@Other]
15572 *
15573 * === Creating
15574 *
15575 * - ::new (aliased as ::for_fd): Creates and returns a new \IO object for the given
15576 * integer file descriptor.
15577 * - ::open: Creates a new \IO object.
15578 * - ::pipe: Creates a connected pair of reader and writer \IO objects.
15579 * - ::popen: Creates an \IO object to interact with a subprocess.
15580 * - ::select: Selects which given \IO instances are ready for reading,
15581 * writing, or have pending exceptions.
15582 *
15583 * === Reading
15584 *
15585 * - ::binread: Returns a binary string with all or a subset of bytes
15586 * from the given file.
15587 * - ::read: Returns a string with all or a subset of bytes from the given file.
15588 * - ::readlines: Returns an array of strings, which are the lines from the given file.
15589 * - #getbyte: Returns the next 8-bit byte read from +self+ as an integer.
15590 * - #getc: Returns the next character read from +self+ as a string.
15591 * - #gets: Returns the line read from +self+.
15592 * - #pread: Returns all or the next _n_ bytes read from +self+,
15593 * not updating the receiver's offset.
15594 * - #read: Returns all remaining or the next _n_ bytes read from +self+
15595 * for a given _n_.
15596 * - #read_nonblock: the next _n_ bytes read from +self+ for a given _n_,
15597 * in non-block mode.
15598 * - #readbyte: Returns the next byte read from +self+;
15599 * same as #getbyte, but raises an exception on end-of-stream.
15600 * - #readchar: Returns the next character read from +self+;
15601 * same as #getc, but raises an exception on end-of-stream.
15602 * - #readline: Returns the next line read from +self+;
15603 * same as #getline, but raises an exception of end-of-stream.
15604 * - #readlines: Returns an array of all lines read read from +self+.
15605 * - #readpartial: Returns up to the given number of bytes from +self+.
15606 *
15607 * === Writing
15608 *
15609 * - ::binwrite: Writes the given string to the file at the given filepath,
15610 * in binary mode.
15611 * - ::write: Writes the given string to +self+.
15612 * - #<<: Appends the given string to +self+.
15613 * - #print: Prints last read line or given objects to +self+.
15614 * - #printf: Writes to +self+ based on the given format string and objects.
15615 * - #putc: Writes a character to +self+.
15616 * - #puts: Writes lines to +self+, making sure line ends with a newline.
15617 * - #pwrite: Writes the given string at the given offset,
15618 * not updating the receiver's offset.
15619 * - #write: Writes one or more given strings to +self+.
15620 * - #write_nonblock: Writes one or more given strings to +self+ in non-blocking mode.
15621 *
15622 * === Positioning
15623 *
15624 * - #lineno: Returns the current line number in +self+.
15625 * - #lineno=: Sets the line number is +self+.
15626 * - #pos (aliased as #tell): Returns the current byte offset in +self+.
15627 * - #pos=: Sets the byte offset in +self+.
15628 * - #reopen: Reassociates +self+ with a new or existing \IO stream.
15629 * - #rewind: Positions +self+ to the beginning of input.
15630 * - #seek: Sets the offset for +self+ relative to given position.
15631 *
15632 * === Iterating
15633 *
15634 * - ::foreach: Yields each line of given file to the block.
15635 * - #each (aliased as #each_line): Calls the given block
15636 * with each successive line in +self+.
15637 * - #each_byte: Calls the given block with each successive byte in +self+
15638 * as an integer.
15639 * - #each_char: Calls the given block with each successive character in +self+
15640 * as a string.
15641 * - #each_codepoint: Calls the given block with each successive codepoint in +self+
15642 * as an integer.
15643 *
15644 * === Settings
15645 *
15646 * - #autoclose=: Sets whether +self+ auto-closes.
15647 * - #binmode: Sets +self+ to binary mode.
15648 * - #close: Closes +self+.
15649 * - #close_on_exec=: Sets the close-on-exec flag.
15650 * - #close_read: Closes +self+ for reading.
15651 * - #close_write: Closes +self+ for writing.
15652 * - #set_encoding: Sets the encoding for +self+.
15653 * - #set_encoding_by_bom: Sets the encoding for +self+, based on its
15654 * Unicode byte-order-mark.
15655 * - #sync=: Sets the sync-mode to the given value.
15656 *
15657 * === Querying
15658 *
15659 * - #autoclose?: Returns whether +self+ auto-closes.
15660 * - #binmode?: Returns whether +self+ is in binary mode.
15661 * - #close_on_exec?: Returns the close-on-exec flag for +self+.
15662 * - #closed?: Returns whether +self+ is closed.
15663 * - #eof? (aliased as #eof): Returns whether +self+ is at end-of-stream.
15664 * - #external_encoding: Returns the external encoding object for +self+.
15665 * - #fileno (aliased as #to_i): Returns the integer file descriptor for +self+
15666 * - #internal_encoding: Returns the internal encoding object for +self+.
15667 * - #pid: Returns the process ID of a child process associated with +self+,
15668 * if +self+ was created by ::popen.
15669 * - #stat: Returns the File::Stat object containing status information for +self+.
15670 * - #sync: Returns whether +self+ is in sync-mode.
15671 * - #tty? (aliased as #isatty): Returns whether +self+ is a terminal.
15672 *
15673 * === Buffering
15674 *
15675 * - #fdatasync: Immediately writes all buffered data in +self+ to disk.
15676 * - #flush: Flushes any buffered data within +self+ to the underlying
15677 * operating system.
15678 * - #fsync: Immediately writes all buffered data and attributes in +self+ to disk.
15679 * - #ungetbyte: Prepends buffer for +self+ with given integer byte or string.
15680 * - #ungetc: Prepends buffer for +self+ with given string.
15681 *
15682 * === Low-Level Access
15683 *
15684 * - ::sysopen: Opens the file given by its path,
15685 * returning the integer file descriptor.
15686 * - #advise: Announces the intention to access data from +self+ in a specific way.
15687 * - #fcntl: Passes a low-level command to the file specified
15688 * by the given file descriptor.
15689 * - #ioctl: Passes a low-level command to the device specified
15690 * by the given file descriptor.
15691 * - #sysread: Returns up to the next _n_ bytes read from self using a low-level read.
15692 * - #sysseek: Sets the offset for +self+.
15693 * - #syswrite: Writes the given string to +self+ using a low-level write.
15694 *
15695 * === Other
15696 *
15697 * - ::copy_stream: Copies data from a source to a destination,
15698 * each of which is a filepath or an \IO-like object.
15699 * - ::try_convert: Returns a new \IO object resulting from converting
15700 * the given object.
15701 * - #inspect: Returns the string representation of +self+.
15702 *
15703 */
15704
15705void
15706Init_IO(void)
15707{
15708 VALUE rb_cARGF;
15709#ifdef __CYGWIN__
15710#include <sys/cygwin.h>
15711 static struct __cygwin_perfile pf[] =
15712 {
15713 {"", O_RDONLY | O_BINARY},
15714 {"", O_WRONLY | O_BINARY},
15715 {"", O_RDWR | O_BINARY},
15716 {"", O_APPEND | O_BINARY},
15717 {NULL, 0}
15718 };
15719 cygwin_internal(CW_PERFILE, pf);
15720#endif
15721
15724
15725 id_write = rb_intern_const("write");
15726 id_read = rb_intern_const("read");
15727 id_getc = rb_intern_const("getc");
15728 id_flush = rb_intern_const("flush");
15729 id_readpartial = rb_intern_const("readpartial");
15730 id_set_encoding = rb_intern_const("set_encoding");
15731 id_fileno = rb_intern_const("fileno");
15732
15733 rb_define_global_function("syscall", rb_f_syscall, -1);
15734
15735 rb_define_global_function("open", rb_f_open, -1);
15736 rb_define_global_function("printf", rb_f_printf, -1);
15737 rb_define_global_function("print", rb_f_print, -1);
15738 rb_define_global_function("putc", rb_f_putc, 1);
15739 rb_define_global_function("puts", rb_f_puts, -1);
15740 rb_define_global_function("gets", rb_f_gets, -1);
15741 rb_define_global_function("readline", rb_f_readline, -1);
15742 rb_define_global_function("select", rb_f_select, -1);
15743
15744 rb_define_global_function("readlines", rb_f_readlines, -1);
15745
15746 rb_define_global_function("`", rb_f_backquote, 1);
15747
15748 rb_define_global_function("p", rb_f_p, -1);
15749 rb_define_method(rb_mKernel, "display", rb_obj_display, -1);
15750
15751 rb_cIO = rb_define_class("IO", rb_cObject);
15753
15754 /* Can be raised by IO operations when IO#timeout= is set. */
15756
15757 /* Readable event mask for IO#wait. */
15758 rb_define_const(rb_cIO, "READABLE", INT2NUM(RUBY_IO_READABLE));
15759 /* Writable event mask for IO#wait. */
15760 rb_define_const(rb_cIO, "WRITABLE", INT2NUM(RUBY_IO_WRITABLE));
15761 /* Priority event mask for IO#wait. */
15762 rb_define_const(rb_cIO, "PRIORITY", INT2NUM(RUBY_IO_PRIORITY));
15763
15764 /* exception to wait for reading. see IO.select. */
15766 /* exception to wait for writing. see IO.select. */
15768 /* exception to wait for reading by EAGAIN. see IO.select. */
15769 rb_eEAGAINWaitReadable = rb_define_class_under(rb_cIO, "EAGAINWaitReadable", rb_eEAGAIN);
15770 rb_include_module(rb_eEAGAINWaitReadable, rb_mWaitReadable);
15771 /* exception to wait for writing by EAGAIN. see IO.select. */
15772 rb_eEAGAINWaitWritable = rb_define_class_under(rb_cIO, "EAGAINWaitWritable", rb_eEAGAIN);
15773 rb_include_module(rb_eEAGAINWaitWritable, rb_mWaitWritable);
15774#if EAGAIN == EWOULDBLOCK
15775 rb_eEWOULDBLOCKWaitReadable = rb_eEAGAINWaitReadable;
15776 /* same as IO::EAGAINWaitReadable */
15777 rb_define_const(rb_cIO, "EWOULDBLOCKWaitReadable", rb_eEAGAINWaitReadable);
15778 rb_eEWOULDBLOCKWaitWritable = rb_eEAGAINWaitWritable;
15779 /* same as IO::EAGAINWaitWritable */
15780 rb_define_const(rb_cIO, "EWOULDBLOCKWaitWritable", rb_eEAGAINWaitWritable);
15781#else
15782 /* exception to wait for reading by EWOULDBLOCK. see IO.select. */
15783 rb_eEWOULDBLOCKWaitReadable = rb_define_class_under(rb_cIO, "EWOULDBLOCKWaitReadable", rb_eEWOULDBLOCK);
15784 rb_include_module(rb_eEWOULDBLOCKWaitReadable, rb_mWaitReadable);
15785 /* exception to wait for writing by EWOULDBLOCK. see IO.select. */
15786 rb_eEWOULDBLOCKWaitWritable = rb_define_class_under(rb_cIO, "EWOULDBLOCKWaitWritable", rb_eEWOULDBLOCK);
15787 rb_include_module(rb_eEWOULDBLOCKWaitWritable, rb_mWaitWritable);
15788#endif
15789 /* exception to wait for reading by EINPROGRESS. see IO.select. */
15790 rb_eEINPROGRESSWaitReadable = rb_define_class_under(rb_cIO, "EINPROGRESSWaitReadable", rb_eEINPROGRESS);
15791 rb_include_module(rb_eEINPROGRESSWaitReadable, rb_mWaitReadable);
15792 /* exception to wait for writing by EINPROGRESS. see IO.select. */
15793 rb_eEINPROGRESSWaitWritable = rb_define_class_under(rb_cIO, "EINPROGRESSWaitWritable", rb_eEINPROGRESS);
15794 rb_include_module(rb_eEINPROGRESSWaitWritable, rb_mWaitWritable);
15795
15796#if 0
15797 /* This is necessary only for forcing rdoc handle File::open */
15798 rb_define_singleton_method(rb_cFile, "open", rb_io_s_open, -1);
15799#endif
15800
15801 rb_define_alloc_func(rb_cIO, io_alloc);
15802 rb_define_singleton_method(rb_cIO, "new", rb_io_s_new, -1);
15803 rb_define_singleton_method(rb_cIO, "open", rb_io_s_open, -1);
15804 rb_define_singleton_method(rb_cIO, "sysopen", rb_io_s_sysopen, -1);
15805 rb_define_singleton_method(rb_cIO, "for_fd", rb_io_s_for_fd, -1);
15806 rb_define_singleton_method(rb_cIO, "popen", rb_io_s_popen, -1);
15807 rb_define_singleton_method(rb_cIO, "foreach", rb_io_s_foreach, -1);
15808 rb_define_singleton_method(rb_cIO, "readlines", rb_io_s_readlines, -1);
15809 rb_define_singleton_method(rb_cIO, "read", rb_io_s_read, -1);
15810 rb_define_singleton_method(rb_cIO, "binread", rb_io_s_binread, -1);
15811 rb_define_singleton_method(rb_cIO, "write", rb_io_s_write, -1);
15812 rb_define_singleton_method(rb_cIO, "binwrite", rb_io_s_binwrite, -1);
15813 rb_define_singleton_method(rb_cIO, "select", rb_f_select, -1);
15814 rb_define_singleton_method(rb_cIO, "pipe", rb_io_s_pipe, -1);
15815 rb_define_singleton_method(rb_cIO, "try_convert", rb_io_s_try_convert, 1);
15816 rb_define_singleton_method(rb_cIO, "copy_stream", rb_io_s_copy_stream, -1);
15817
15818 rb_define_method(rb_cIO, "initialize", rb_io_initialize, -1);
15819
15821 rb_define_hooked_variable("$,", &rb_output_fs, 0, rb_deprecated_str_setter);
15822
15823 rb_default_rs = rb_fstring_lit("\n"); /* avoid modifying RS_default */
15824 rb_vm_register_global_object(rb_default_rs);
15825 rb_rs = rb_default_rs;
15827 rb_define_hooked_variable("$/", &rb_rs, 0, deprecated_rs_setter);
15828 rb_gvar_ractor_local("$/"); // not local but ractor safe
15829 rb_define_hooked_variable("$-0", &rb_rs, 0, deprecated_rs_setter);
15830 rb_gvar_ractor_local("$-0"); // not local but ractor safe
15831 rb_define_hooked_variable("$\\", &rb_output_rs, 0, rb_deprecated_str_setter);
15832
15833 rb_define_virtual_variable("$_", get_LAST_READ_LINE, set_LAST_READ_LINE);
15834 rb_gvar_ractor_local("$_");
15835 rb_gvar_box_dynamic("$_");
15836
15837 rb_define_method(rb_cIO, "initialize_copy", rb_io_init_copy, 1);
15838 rb_define_method(rb_cIO, "reopen", rb_io_reopen, -1);
15839
15840 rb_define_method(rb_cIO, "print", rb_io_print, -1);
15841 rb_define_method(rb_cIO, "putc", rb_io_putc, 1);
15842 rb_define_method(rb_cIO, "puts", rb_io_puts, -1);
15843 rb_define_method(rb_cIO, "printf", rb_io_printf, -1);
15844
15845 rb_define_method(rb_cIO, "each", rb_io_each_line, -1);
15846 rb_define_method(rb_cIO, "each_line", rb_io_each_line, -1);
15847 rb_define_method(rb_cIO, "each_byte", rb_io_each_byte, 0);
15848 rb_define_method(rb_cIO, "each_char", rb_io_each_char, 0);
15849 rb_define_method(rb_cIO, "each_codepoint", rb_io_each_codepoint, 0);
15850
15851 rb_define_method(rb_cIO, "syswrite", rb_io_syswrite, 1);
15852 rb_define_method(rb_cIO, "sysread", rb_io_sysread, -1);
15853
15854 rb_define_method(rb_cIO, "pread", rb_io_pread, -1);
15855 rb_define_method(rb_cIO, "pwrite", rb_io_pwrite, 2);
15856
15857 rb_define_method(rb_cIO, "fileno", rb_io_fileno, 0);
15858 rb_define_alias(rb_cIO, "to_i", "fileno");
15859 rb_define_method(rb_cIO, "to_io", rb_io_to_io, 0);
15860
15861 rb_define_method(rb_cIO, "timeout", rb_io_timeout, 0);
15862 rb_define_method(rb_cIO, "timeout=", rb_io_set_timeout, 1);
15863
15864 rb_define_method(rb_cIO, "fsync", rb_io_fsync, 0);
15865 rb_define_method(rb_cIO, "fdatasync", rb_io_fdatasync, 0);
15866 rb_define_method(rb_cIO, "sync", rb_io_sync, 0);
15867 rb_define_method(rb_cIO, "sync=", rb_io_set_sync, 1);
15868
15869 rb_define_method(rb_cIO, "lineno", rb_io_lineno, 0);
15870 rb_define_method(rb_cIO, "lineno=", rb_io_set_lineno, 1);
15871
15872 rb_define_method(rb_cIO, "readlines", rb_io_readlines, -1);
15873
15874 rb_define_method(rb_cIO, "readpartial", io_readpartial, -1);
15875 rb_define_method(rb_cIO, "read", io_read, -1);
15876 rb_define_method(rb_cIO, "write", io_write_m, -1);
15877 rb_define_method(rb_cIO, "gets", rb_io_gets_m, -1);
15878 rb_define_method(rb_cIO, "getc", rb_io_getc, 0);
15879 rb_define_method(rb_cIO, "getbyte", rb_io_getbyte, 0);
15880 rb_define_method(rb_cIO, "readchar", rb_io_readchar, 0);
15881 rb_define_method(rb_cIO, "readbyte", rb_io_readbyte, 0);
15882 rb_define_method(rb_cIO, "ungetbyte",rb_io_ungetbyte, 1);
15883 rb_define_method(rb_cIO, "ungetc",rb_io_ungetc, 1);
15885 rb_define_method(rb_cIO, "flush", rb_io_flush, 0);
15886 rb_define_method(rb_cIO, "tell", rb_io_tell, 0);
15887 rb_define_method(rb_cIO, "seek", rb_io_seek_m, -1);
15888 /* Set I/O position from the beginning */
15889 rb_define_const(rb_cIO, "SEEK_SET", INT2FIX(SEEK_SET));
15890 /* Set I/O position from the current position */
15891 rb_define_const(rb_cIO, "SEEK_CUR", INT2FIX(SEEK_CUR));
15892 /* Set I/O position from the end */
15893 rb_define_const(rb_cIO, "SEEK_END", INT2FIX(SEEK_END));
15894#ifdef SEEK_DATA
15895 /* Set I/O position to the next location containing data */
15896 rb_define_const(rb_cIO, "SEEK_DATA", INT2FIX(SEEK_DATA));
15897#endif
15898#ifdef SEEK_HOLE
15899 /* Set I/O position to the next hole */
15900 rb_define_const(rb_cIO, "SEEK_HOLE", INT2FIX(SEEK_HOLE));
15901#endif
15902 rb_define_method(rb_cIO, "rewind", rb_io_rewind, 0);
15903 rb_define_method(rb_cIO, "pos", rb_io_tell, 0);
15904 rb_define_method(rb_cIO, "pos=", rb_io_set_pos, 1);
15905 rb_define_method(rb_cIO, "eof", rb_io_eof, 0);
15906 rb_define_method(rb_cIO, "eof?", rb_io_eof, 0);
15907
15908 rb_define_method(rb_cIO, "close_on_exec?", rb_io_close_on_exec_p, 0);
15909 rb_define_method(rb_cIO, "close_on_exec=", rb_io_set_close_on_exec, 1);
15910
15911 rb_define_method(rb_cIO, "close", rb_io_close_m, 0);
15912 rb_define_method(rb_cIO, "closed?", rb_io_closed_p, 0);
15913 rb_define_method(rb_cIO, "close_read", rb_io_close_read, 0);
15914 rb_define_method(rb_cIO, "close_write", rb_io_close_write, 0);
15915
15916 rb_define_method(rb_cIO, "isatty", rb_io_isatty, 0);
15917 rb_define_method(rb_cIO, "tty?", rb_io_isatty, 0);
15918 rb_define_method(rb_cIO, "binmode", rb_io_binmode_m, 0);
15919 rb_define_method(rb_cIO, "binmode?", rb_io_binmode_p, 0);
15920 rb_define_method(rb_cIO, "sysseek", rb_io_sysseek, -1);
15921 rb_define_method(rb_cIO, "advise", rb_io_advise, -1);
15922
15923 rb_define_method(rb_cIO, "ioctl", rb_io_ioctl, -1);
15924 rb_define_method(rb_cIO, "fcntl", rb_io_fcntl, -1);
15925 rb_define_method(rb_cIO, "pid", rb_io_pid, 0);
15926
15927 rb_define_method(rb_cIO, "path", rb_io_path, 0);
15928 rb_define_method(rb_cIO, "to_path", rb_io_path, 0);
15929
15930 rb_define_method(rb_cIO, "inspect", rb_io_inspect, 0);
15931
15932 rb_define_method(rb_cIO, "external_encoding", rb_io_external_encoding, 0);
15933 rb_define_method(rb_cIO, "internal_encoding", rb_io_internal_encoding, 0);
15934 rb_define_method(rb_cIO, "set_encoding", rb_io_set_encoding, -1);
15935 rb_define_method(rb_cIO, "set_encoding_by_bom", rb_io_set_encoding_by_bom, 0);
15936
15937 rb_define_method(rb_cIO, "autoclose?", rb_io_autoclose_p, 0);
15938 rb_define_method(rb_cIO, "autoclose=", rb_io_set_autoclose, 1);
15939
15940 rb_define_method(rb_cIO, "wait", io_wait, -1);
15941
15942 rb_define_method(rb_cIO, "wait_readable", io_wait_readable, -1);
15943 rb_define_method(rb_cIO, "wait_writable", io_wait_writable, -1);
15944 rb_define_method(rb_cIO, "wait_priority", io_wait_priority, -1);
15945
15946 rb_define_virtual_variable("$stdin", stdin_getter, stdin_setter);
15947 rb_define_virtual_variable("$stdout", stdout_getter, stdout_setter);
15948 rb_define_virtual_variable("$>", stdout_getter, stdout_setter);
15949 rb_define_virtual_variable("$stderr", stderr_getter, stderr_setter);
15950
15951 rb_gvar_ractor_local("$stdin");
15952 rb_gvar_ractor_local("$stdout");
15953 rb_gvar_ractor_local("$>");
15954 rb_gvar_ractor_local("$stderr");
15955
15957 rb_stdin = rb_io_prep_stdin();
15959 rb_stdout = rb_io_prep_stdout();
15961 rb_stderr = rb_io_prep_stderr();
15962
15963 orig_stdout = rb_stdout;
15964 orig_stderr = rb_stderr;
15965
15966 /* Holds the original stdin */
15968 /* Holds the original stdout */
15970 /* Holds the original stderr */
15972
15973#if 0
15974 /* Hack to get rdoc to regard ARGF as a class: */
15975 rb_cARGF = rb_define_class("ARGF", rb_cObject);
15976#endif
15977
15978 rb_cARGF = rb_class_new(rb_cObject);
15979 rb_set_class_path(rb_cARGF, rb_cObject, "ARGF.class");
15980 rb_define_alloc_func(rb_cARGF, argf_alloc);
15981
15983
15984 rb_define_method(rb_cARGF, "initialize", argf_initialize, -2);
15985 rb_define_method(rb_cARGF, "initialize_copy", argf_initialize_copy, 1);
15986 rb_define_method(rb_cARGF, "to_s", argf_to_s, 0);
15987 rb_define_alias(rb_cARGF, "inspect", "to_s");
15988 rb_define_method(rb_cARGF, "argv", argf_argv, 0);
15989
15990 rb_define_method(rb_cARGF, "fileno", argf_fileno, 0);
15991 rb_define_method(rb_cARGF, "to_i", argf_fileno, 0);
15992 rb_define_method(rb_cARGF, "to_io", argf_to_io, 0);
15993 rb_define_method(rb_cARGF, "to_write_io", argf_write_io, 0);
15994 rb_define_method(rb_cARGF, "each", argf_each_line, -1);
15995 rb_define_method(rb_cARGF, "each_line", argf_each_line, -1);
15996 rb_define_method(rb_cARGF, "each_byte", argf_each_byte, 0);
15997 rb_define_method(rb_cARGF, "each_char", argf_each_char, 0);
15998 rb_define_method(rb_cARGF, "each_codepoint", argf_each_codepoint, 0);
15999
16000 rb_define_method(rb_cARGF, "read", argf_read, -1);
16001 rb_define_method(rb_cARGF, "readpartial", argf_readpartial, -1);
16002 rb_define_method(rb_cARGF, "read_nonblock", argf_read_nonblock, -1);
16003 rb_define_method(rb_cARGF, "readlines", argf_readlines, -1);
16004 rb_define_method(rb_cARGF, "to_a", argf_readlines, -1);
16005 rb_define_method(rb_cARGF, "gets", argf_gets, -1);
16006 rb_define_method(rb_cARGF, "readline", argf_readline, -1);
16007 rb_define_method(rb_cARGF, "getc", argf_getc, 0);
16008 rb_define_method(rb_cARGF, "getbyte", argf_getbyte, 0);
16009 rb_define_method(rb_cARGF, "readchar", argf_readchar, 0);
16010 rb_define_method(rb_cARGF, "readbyte", argf_readbyte, 0);
16011 rb_define_method(rb_cARGF, "tell", argf_tell, 0);
16012 rb_define_method(rb_cARGF, "seek", argf_seek_m, -1);
16013 rb_define_method(rb_cARGF, "rewind", argf_rewind, 0);
16014 rb_define_method(rb_cARGF, "pos", argf_tell, 0);
16015 rb_define_method(rb_cARGF, "pos=", argf_set_pos, 1);
16016 rb_define_method(rb_cARGF, "eof", argf_eof, 0);
16017 rb_define_method(rb_cARGF, "eof?", argf_eof, 0);
16018 rb_define_method(rb_cARGF, "binmode", argf_binmode_m, 0);
16019 rb_define_method(rb_cARGF, "binmode?", argf_binmode_p, 0);
16020
16021 rb_define_method(rb_cARGF, "write", argf_write, -1);
16022 rb_define_method(rb_cARGF, "print", rb_io_print, -1);
16023 rb_define_method(rb_cARGF, "putc", rb_io_putc, 1);
16024 rb_define_method(rb_cARGF, "puts", rb_io_puts, -1);
16025 rb_define_method(rb_cARGF, "printf", rb_io_printf, -1);
16026
16027 rb_define_method(rb_cARGF, "filename", argf_filename, 0);
16028 rb_define_method(rb_cARGF, "path", argf_filename, 0);
16029 rb_define_method(rb_cARGF, "file", argf_file, 0);
16030 rb_define_method(rb_cARGF, "skip", argf_skip, 0);
16031 rb_define_method(rb_cARGF, "close", argf_close_m, 0);
16032 rb_define_method(rb_cARGF, "closed?", argf_closed, 0);
16033
16034 rb_define_method(rb_cARGF, "lineno", argf_lineno, 0);
16035 rb_define_method(rb_cARGF, "lineno=", argf_set_lineno, 1);
16036
16037 rb_define_method(rb_cARGF, "inplace_mode", argf_inplace_mode_get, 0);
16038 rb_define_method(rb_cARGF, "inplace_mode=", argf_inplace_mode_set, 1);
16039
16040 rb_define_method(rb_cARGF, "external_encoding", argf_external_encoding, 0);
16041 rb_define_method(rb_cARGF, "internal_encoding", argf_internal_encoding, 0);
16042 rb_define_method(rb_cARGF, "set_encoding", argf_set_encoding, -1);
16043
16044 argf = rb_class_new_instance(0, 0, rb_cARGF);
16045
16047 /*
16048 * ARGF is a stream designed for use in scripts that process files given
16049 * as command-line arguments or passed in via STDIN.
16050 *
16051 * See ARGF (the class) for more details.
16052 */
16054
16055 rb_define_hooked_variable("$.", &argf, argf_lineno_getter, argf_lineno_setter);
16056 rb_define_hooked_variable("$FILENAME", &argf, argf_filename_getter, rb_gvar_readonly_setter);
16057 ARGF.filename = rb_str_new2("-");
16058
16059 rb_define_hooked_variable("$-i", &argf, opt_i_get, opt_i_set);
16060 rb_gvar_ractor_local("$-i");
16061
16062 rb_define_hooked_variable("$*", &argf, argf_argv_getter, rb_gvar_readonly_setter);
16063
16064#if defined (_WIN32) || defined(__CYGWIN__)
16065 atexit(pipe_atexit);
16066#endif
16067
16068 Init_File();
16069
16070 rb_define_method(rb_cFile, "initialize", rb_file_initialize, -1);
16071
16072 sym_mode = ID2SYM(rb_intern_const("mode"));
16073 sym_perm = ID2SYM(rb_intern_const("perm"));
16074 sym_flags = ID2SYM(rb_intern_const("flags"));
16075 sym_extenc = ID2SYM(rb_intern_const("external_encoding"));
16076 sym_intenc = ID2SYM(rb_intern_const("internal_encoding"));
16077 sym_encoding = ID2SYM(rb_id_encoding());
16078 sym_open_args = ID2SYM(rb_intern_const("open_args"));
16079 sym_textmode = ID2SYM(rb_intern_const("textmode"));
16080 sym_binmode = ID2SYM(rb_intern_const("binmode"));
16081 sym_autoclose = ID2SYM(rb_intern_const("autoclose"));
16082 sym_normal = ID2SYM(rb_intern_const("normal"));
16083 sym_sequential = ID2SYM(rb_intern_const("sequential"));
16084 sym_random = ID2SYM(rb_intern_const("random"));
16085 sym_willneed = ID2SYM(rb_intern_const("willneed"));
16086 sym_dontneed = ID2SYM(rb_intern_const("dontneed"));
16087 sym_noreuse = ID2SYM(rb_intern_const("noreuse"));
16088 sym_SET = ID2SYM(rb_intern_const("SET"));
16089 sym_CUR = ID2SYM(rb_intern_const("CUR"));
16090 sym_END = ID2SYM(rb_intern_const("END"));
16091#ifdef SEEK_DATA
16092 sym_DATA = ID2SYM(rb_intern_const("DATA"));
16093#endif
16094#ifdef SEEK_HOLE
16095 sym_HOLE = ID2SYM(rb_intern_const("HOLE"));
16096#endif
16097 sym_wait_readable = ID2SYM(rb_intern_const("wait_readable"));
16098 sym_wait_writable = ID2SYM(rb_intern_const("wait_writable"));
16099}
16100
16101#include "io.rbinc"
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
std::atomic< unsigned > rb_atomic_t
Type that is eligible for atomic operations.
Definition atomic.h:69
#define STRNCASECMP
@old{st_locale_insensitive_strncasecmp}
Definition ctype.h:103
unsigned long ruby_strtoul(const char *str, char **endptr, int base)
Our own locale-insensitive version of strtoul(3).
Definition util.c:117
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
#define rb_define_global_function(mid, func, arity)
Defines rb_mKernel #mid.
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1695
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:1488
VALUE rb_class_new(VALUE super)
Creates a new, anonymous class.
Definition class.c:856
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition class.c:1519
VALUE rb_define_module_under(VALUE outer, const char *name)
Defines a module under the namespace of outer.
Definition class.c:1624
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:2868
int rb_scan_args_kw(int kw_flag, int argc, const VALUE *argv, const char *fmt,...)
Identical to rb_scan_args(), except it also accepts kw_splat.
Definition class.c:3171
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:3158
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1027
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:2947
#define ECONV_AFTER_OUTPUT
Old name of RUBY_ECONV_AFTER_OUTPUT.
Definition transcode.h:555
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition string.h:1676
#define TYPE(_)
Old name of rb_type.
Definition value_type.h:108
#define RB_INTEGER_TYPE_P
Old name of rb_integer_type_p.
Definition value_type.h:87
#define ENC_CODERANGE_7BIT
Old name of RUBY_ENC_CODERANGE_7BIT.
Definition coderange.h:180
#define T_FILE
Old name of RUBY_T_FILE.
Definition value_type.h:62
#define ENC_CODERANGE_VALID
Old name of RUBY_ENC_CODERANGE_VALID.
Definition coderange.h:181
#define ECONV_UNIVERSAL_NEWLINE_DECORATOR
Old name of RUBY_ECONV_UNIVERSAL_NEWLINE_DECORATOR.
Definition transcode.h:532
#define OBJ_INIT_COPY(obj, orig)
Old name of RB_OBJ_INIT_COPY.
Definition object.h:41
#define ALLOC
Old name of RB_ALLOC.
Definition memory.h:400
#define RFLOAT_VALUE
Old name of rb_float_value.
Definition double.h:28
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define rb_str_cat2
Old name of rb_str_cat_cstr.
Definition string.h:1684
#define T_NIL
Old name of RUBY_T_NIL.
Definition value_type.h:72
#define UNREACHABLE
Old name of RBIMPL_UNREACHABLE.
Definition assume.h:28
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define T_BIGNUM
Old name of RUBY_T_BIGNUM.
Definition value_type.h:57
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:134
#define T_FIXNUM
Old name of RUBY_T_FIXNUM.
Definition value_type.h:63
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define FIX2UINT
Old name of RB_FIX2UINT.
Definition int.h:42
#define SSIZET2NUM
Old name of RB_SSIZE2NUM.
Definition size_t.h:64
#define ZALLOC
Old name of RB_ZALLOC.
Definition memory.h:402
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define rb_ary_new4
Old name of rb_ary_new_from_values.
Definition array.h:659
#define ECONV_NEWLINE_DECORATOR_WRITE_MASK
Old name of RUBY_ECONV_NEWLINE_DECORATOR_WRITE_MASK.
Definition transcode.h:531
#define ENCODING_MAXNAMELEN
Old name of RUBY_ENCODING_MAXNAMELEN.
Definition encoding.h:111
#define MBCLEN_NEEDMORE_LEN(ret)
Old name of ONIGENC_MBCLEN_NEEDMORE_LEN.
Definition encoding.h:520
#define ENCODING_GET(obj)
Old name of RB_ENCODING_GET.
Definition encoding.h:109
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
#define NUM2UINT
Old name of RB_NUM2UINT.
Definition int.h:45
#define ALLOC_N
Old name of RB_ALLOC_N.
Definition memory.h:399
#define MBCLEN_CHARFOUND_LEN(ret)
Old name of ONIGENC_MBCLEN_CHARFOUND_LEN.
Definition encoding.h:517
#define LONG2NUM
Old name of RB_LONG2NUM.
Definition long.h:50
#define rb_exc_new3
Old name of rb_exc_new_str.
Definition error.h:38
#define MBCLEN_INVALID_P(ret)
Old name of ONIGENC_MBCLEN_INVALID_P.
Definition encoding.h:518
#define ECONV_STATEFUL_DECORATOR_MASK
Old name of RUBY_ECONV_STATEFUL_DECORATOR_MASK.
Definition transcode.h:538
#define Qtrue
Old name of RUBY_Qtrue.
#define MBCLEN_NEEDMORE_P(ret)
Old name of ONIGENC_MBCLEN_NEEDMORE_P.
Definition encoding.h:519
#define ECONV_PARTIAL_INPUT
Old name of RUBY_ECONV_PARTIAL_INPUT.
Definition transcode.h:554
#define NUM2INT
Old name of RB_NUM2INT.
Definition int.h:44
#define ECONV_ERROR_HANDLER_MASK
Old name of RUBY_ECONV_ERROR_HANDLER_MASK.
Definition transcode.h:522
#define INT2NUM
Old name of RB_INT2NUM.
Definition int.h:43
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define FIX2LONG
Old name of RB_FIX2LONG.
Definition long.h:46
#define ENC_CODERANGE_BROKEN
Old name of RUBY_ENC_CODERANGE_BROKEN.
Definition coderange.h:182
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define NIL_P
Old name of RB_NIL_P.
#define ALLOCV_N
Old name of RB_ALLOCV_N.
Definition memory.h:405
#define MBCLEN_CHARFOUND_P(ret)
Old name of ONIGENC_MBCLEN_CHARFOUND_P.
Definition encoding.h:516
#define ECONV_NEWLINE_DECORATOR_READ_MASK
Old name of RUBY_ECONV_NEWLINE_DECORATOR_READ_MASK.
Definition transcode.h:530
#define NUM2CHR
Old name of RB_NUM2CHR.
Definition char.h:33
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
#define UINT2NUM
Old name of RB_UINT2NUM.
Definition int.h:46
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define ECONV_NEWLINE_DECORATOR_MASK
Old name of RUBY_ECONV_NEWLINE_DECORATOR_MASK.
Definition transcode.h:529
#define CONST_ID
Old name of RUBY_CONST_ID.
Definition symbol.h:47
#define rb_ary_new2
Old name of rb_ary_new_capa.
Definition array.h:657
#define ENC_CODERANGE_SET(obj, cr)
Old name of RB_ENC_CODERANGE_SET.
Definition coderange.h:186
#define rb_str_new4
Old name of rb_str_new_frozen.
Definition string.h:1678
#define ALLOCV_END
Old name of RB_ALLOCV_END.
Definition memory.h:406
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
#define ECONV_DEFAULT_NEWLINE_DECORATOR
Old name of RUBY_ECONV_DEFAULT_NEWLINE_DECORATOR.
Definition transcode.h:540
void rb_notimplement(void)
Definition error.c:3842
void rb_category_warn(rb_warning_category_t category, const char *fmt,...)
Identical to rb_category_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:476
void rb_category_warning(rb_warning_category_t category, const char *fmt,...)
Identical to rb_warning(), except it takes additional "category" parameter.
Definition error.c:508
VALUE rb_rescue2(VALUE(*b_proc)(VALUE), VALUE data1, VALUE(*r_proc)(VALUE, VALUE), VALUE data2,...)
An equivalent of rescue clause.
Definition eval.c:1056
VALUE rb_eNotImpError
NotImplementedError exception.
Definition error.c:1441
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:664
void rb_syserr_fail(int e, const char *mesg)
Raises appropriate exception that represents a C errno.
Definition error.c:3911
void rb_readwrite_syserr_fail(enum rb_io_wait_readwrite waiting, int err, const char *msg)
Identical to rb_readwrite_sys_fail(), except it does not depend on C global variable errno.
Definition io.c:14779
VALUE rb_eIOError
IOError exception.
Definition io.c:194
VALUE rb_eStandardError
StandardError exception.
Definition error.c:1428
void rb_mod_syserr_fail_str(VALUE mod, int e, VALUE mesg)
Identical to rb_mod_syserr_fail(), except it takes the message in Ruby's String instead of C's.
Definition error.c:4001
void rb_syserr_fail_str(int e, VALUE mesg)
Identical to rb_syserr_fail(), except it takes the message in Ruby's String instead of C's.
Definition error.c:3917
#define ruby_verbose
This variable controls whether the interpreter is in debug mode.
Definition error.h:475
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1431
VALUE rb_eEOFError
EOFError exception.
Definition io.c:193
void rb_readwrite_sys_fail(enum rb_io_wait_readwrite waiting, const char *msg)
Raises appropriate exception using the parameters.
Definition io.c:14773
void rb_iter_break_value(VALUE val)
Identical to rb_iter_break(), except it additionally takes the "value" of this breakage.
Definition vm.c:2312
rb_io_wait_readwrite
for rb_readwrite_sys_fail first argument
Definition error.h:73
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1429
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:466
VALUE rb_ensure(VALUE(*b_proc)(VALUE), VALUE data1, VALUE(*e_proc)(VALUE), VALUE data2)
An equivalent to ensure clause.
Definition eval.c:1178
VALUE rb_eSystemCallError
SystemCallError exception.
Definition error.c:1451
@ RB_WARN_CATEGORY_DEPRECATED
Warning is for deprecated features.
Definition error.h:48
VALUE rb_mKernel
Kernel module.
Definition object.c:60
VALUE rb_check_to_int(VALUE val)
Identical to rb_check_to_integer(), except it uses #to_int for conversion.
Definition object.c:3312
VALUE rb_any_to_s(VALUE obj)
Generates a textual representation of the given object.
Definition object.c:675
VALUE rb_obj_alloc(VALUE klass)
Allocates an instance of the given class.
Definition object.c:2208
VALUE rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
Allocates, then initialises an instance of the given class.
Definition object.c:2249
VALUE rb_cIO
IO class.
Definition io.c:192
VALUE rb_class_new_instance_kw(int argc, const VALUE *argv, VALUE klass, int kw_splat)
Identical to rb_class_new_instance(), except you can specify how to handle the last element of the gi...
Definition object.c:2237
VALUE rb_mEnumerable
Enumerable module.
Definition enum.c:27
VALUE rb_stdin
STDIN constant.
Definition io.c:206
VALUE rb_stderr
STDERR constant.
Definition io.c:206
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:264
VALUE rb_obj_dup(VALUE obj)
Duplicates the given object.
Definition object.c:582
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:686
VALUE rb_mWaitReadable
IO::WaitReadable module.
Definition io.c:196
VALUE rb_mWaitWritable
IO::WaitReadable module.
Definition io.c:197
VALUE rb_obj_freeze(VALUE obj)
Just calls rb_obj_freeze_inline() inside.
Definition object.c:1342
VALUE rb_check_to_integer(VALUE val, const char *mid)
Identical to rb_check_convert_type(), except the return value type is fixed to rb_cInteger.
Definition object.c:3293
VALUE rb_cFile
File class.
Definition file.c:191
VALUE rb_stdout
STDOUT constant.
Definition io.c:206
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
Definition object.c:3306
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:603
VALUE rb_str_conv_enc(VALUE str, rb_encoding *from, rb_encoding *to)
Encoding conversion main routine.
Definition string.c:1359
VALUE rb_enc_uint_chr(unsigned int code, rb_encoding *enc)
Encodes the passed code point into a series of bytes.
Definition numeric.c:3939
int rb_econv_prepare_options(VALUE opthash, VALUE *ecopts, int ecflags)
Identical to rb_econv_prepare_opts(), except it additionally takes the initial value of flags.
Definition transcode.c:2678
VALUE rb_econv_open_exc(const char *senc, const char *denc, int ecflags)
Creates a rb_eConverterNotFoundError exception object (but does not raise).
Definition transcode.c:2125
rb_econv_result_t rb_econv_convert(rb_econv_t *ec, const unsigned char **source_buffer_ptr, const unsigned char *source_buffer_end, unsigned char **destination_buffer_ptr, unsigned char *destination_buffer_end, int flags)
Converts a string from an encoding to another.
Definition transcode.c:1487
rb_econv_result_t
return value of rb_econv_convert()
Definition transcode.h:30
@ econv_incomplete_input
The conversion stopped in middle of reading a character, possibly due to a partial read of a socket e...
Definition transcode.h:69
@ econv_finished
The conversion stopped after converting everything.
Definition transcode.h:57
@ econv_undefined_conversion
The conversion stopped when it found a character in the input which cannot be representable in the ou...
Definition transcode.h:41
@ econv_source_buffer_empty
The conversion stopped because there is no input.
Definition transcode.h:51
@ econv_destination_buffer_full
The conversion stopped because there is no destination.
Definition transcode.h:46
@ econv_invalid_byte_sequence
The conversion stopped when it found an invalid sequence.
Definition transcode.h:35
int rb_econv_putbackable(rb_econv_t *ec)
Queries if rb_econv_putback() makes sense, i.e.
Definition transcode.c:1782
const char * rb_econv_asciicompat_encoding(const char *encname)
Queries the passed encoding's corresponding ASCII compatible encoding.
Definition transcode.c:1826
VALUE rb_econv_str_convert(rb_econv_t *ec, VALUE src, int flags)
Identical to rb_econv_convert(), except it takes Ruby's string instead of C's pointer.
Definition transcode.c:1961
rb_econv_t * rb_econv_open_opts(const char *source_encoding, const char *destination_encoding, int ecflags, VALUE ecopts)
Identical to rb_econv_open(), except it additionally takes a hash of optional strings.
Definition transcode.c:2729
void rb_econv_binmode(rb_econv_t *ec)
This badly named function does not set the destination encoding to binary, but instead just nullifies...
Definition transcode.c:2024
VALUE rb_str_encode(VALUE str, VALUE to, int ecflags, VALUE ecopts)
Converts the contents of the passed string from its encoding to the passed one.
Definition transcode.c:2992
VALUE rb_econv_make_exception(rb_econv_t *ec)
This function makes sense right after rb_econv_convert() returns.
Definition transcode.c:4361
void rb_econv_check_error(rb_econv_t *ec)
This is a rb_econv_make_exception() + rb_exc_raise() combo.
Definition transcode.c:4367
void rb_econv_close(rb_econv_t *ec)
Destructs a converter.
Definition transcode.c:1743
void rb_econv_putback(rb_econv_t *ec, unsigned char *p, int n)
Puts back the bytes.
Definition transcode.c:1793
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1119
VALUE rb_funcallv_kw(VALUE recv, ID mid, int argc, const VALUE *argv, int kw_splat)
Identical to rb_funcallv(), except you can specify how to handle the last element of the given array.
Definition vm_eval.c:1086
VALUE rb_ary_concat(VALUE lhs, VALUE rhs)
Destructively appends the contents of latter into the end of former.
VALUE rb_ary_shift(VALUE ary)
Destructively deletes an element from the beginning of the passed array and returns what was deleted.
VALUE rb_check_array_type(VALUE obj)
Try converting an object to its array representation using its to_ary method, if any.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_ary_entry(VALUE ary, long off)
Queries an element of an array.
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Identical to rb_ary_new_from_values(), except it expects exactly two parameters.
#define RETURN_ENUMERATOR(obj, argc, argv)
Identical to RETURN_SIZED_ENUMERATOR(), except its size is unknown.
Definition enumerator.h:242
VALUE rb_io_printf(int argc, const VALUE *argv, VALUE io)
This is a rb_f_sprintf() + rb_io_write() combo.
Definition io.c:8692
VALUE rb_io_gets(VALUE io)
Reads a "line" from the given IO.
Definition io.c:4400
int rb_cloexec_pipe(int fildes[2])
Opens a pipe with closing on exec.
Definition io.c:514
VALUE rb_io_print(int argc, const VALUE *argv, VALUE io)
Iterates over the passed array to apply rb_io_write() individually.
Definition io.c:8825
VALUE rb_io_addstr(VALUE io, VALUE str)
Identical to rb_io_write(), except it always returns the passed IO.
Definition io.c:2447
void rb_write_error(const char *str)
Writes the given error message to somewhere applicable.
Definition io.c:9254
VALUE rb_io_ungetbyte(VALUE io, VALUE b)
Identical to rb_io_ungetc(), except it doesn't take the encoding of the passed IO into account.
Definition io.c:5265
VALUE rb_io_getbyte(VALUE io)
Reads a byte from the given IO.
Definition io.c:5171
int rb_cloexec_dup2(int oldfd, int newfd)
Identical to rb_cloexec_dup(), except you can specify the destination file descriptor.
Definition io.c:412
VALUE rb_io_fdopen(int fd, int flags, const char *path)
Creates an IO instance whose backend is the given file descriptor.
Definition io.c:9435
void rb_update_max_fd(int fd)
Informs the interpreter that the passed fd can be the max.
Definition io.c:286
int rb_cloexec_open(const char *pathname, int flags, mode_t mode)
Opens a file that closes on exec.
Definition io.c:366
VALUE rb_output_rs
The record separator character for outputs, or the $\\endiskip.
Definition io.c:211
VALUE rb_io_eof(VALUE io)
Queries if the passed IO is at the end of file.
Definition io.c:2789
void rb_write_error2(const char *str, long len)
Identical to rb_write_error(), except it additionally takes the message's length.
Definition io.c:9234
void rb_close_before_exec(int lowfd, int maxhint, VALUE noclose_fds)
Closes everything.
int rb_reserved_fd_p(int fd)
Queries if the given FD is reserved or not.
void rb_fd_fix_cloexec(int fd)
Sets or clears the close-on-exec flag of the passed file descriptor to the desired state.
Definition io.c:336
VALUE rb_io_ascii8bit_binmode(VALUE io)
Forces no conversions be applied to the passed IO.
Definition io.c:6489
VALUE rb_io_binmode(VALUE io)
Sets the binmode.
Definition io.c:6443
VALUE rb_io_ungetc(VALUE io, VALUE c)
"Unget"s a string.
Definition io.c:5329
int rb_pipe(int *pipes)
This is an rb_cloexec_pipe() + rb_update_max_fd() combo.
Definition io.c:7491
VALUE rb_gets(void)
Much like rb_io_gets(), but it reads from the mysterious ARGF object.
Definition io.c:10513
int rb_cloexec_fcntl_dupfd(int fd, int minfd)
Duplicates a file descriptor with closing on exec.
Definition io.c:520
VALUE rb_output_fs
The field separator character for outputs, or the $,.
Definition io.c:209
VALUE rb_file_open_str(VALUE fname, const char *fmode)
Identical to rb_file_open(), except it takes the pathname as a Ruby's string instead of C's.
Definition io.c:7374
int rb_cloexec_dup(int oldfd)
Identical to rb_cloexec_fcntl_dupfd(), except it implies minfd is 3.
Definition io.c:405
VALUE rb_file_open(const char *fname, const char *fmode)
Opens a file located at the given path.
Definition io.c:7381
VALUE rb_io_close(VALUE io)
Closes the IO.
Definition io.c:5847
VALUE rb_default_rs
This is the default value of rb_rs, i.e.
Definition io.c:212
void rb_lastline_set(VALUE str)
Updates $_.
Definition vm.c:2074
VALUE rb_lastline_get(void)
Queries the last line, or the $_.
Definition vm.c:2068
int rb_obj_method_arity(VALUE obj, ID mid)
Identical to rb_mod_method_arity(), except it searches for singleton methods rather than instance met...
Definition proc.c:3123
rb_pid_t rb_waitpid(rb_pid_t pid, int *status, int flags)
Waits for a process, with releasing GVL.
Definition process.c:1171
void rb_last_status_set(int status, rb_pid_t pid)
Sets the "last status", or the $?.
Definition process.c:685
VALUE rb_str_append(VALUE dst, VALUE src)
Identical to rb_str_buf_append(), except it converts the right hand side before concatenating.
Definition string.c:3833
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1499
#define rb_str_buf_cat
Just another name of rb_str_cat.
Definition string.h:1682
#define rb_usascii_str_new(str, len)
Identical to rb_str_new, except it generates a string of "US ASCII" encoding.
Definition string.h:1533
size_t rb_str_capacity(VALUE str)
Queries the capacity of the given string.
Definition string.c:1018
VALUE rb_str_new_frozen(VALUE str)
Creates a frozen copy of the string, if necessary.
Definition string.c:1535
VALUE rb_str_dup(VALUE str)
Duplicates a string.
Definition string.c:2014
VALUE rb_str_cat(VALUE dst, const char *src, long srclen)
Destructively appends the passed contents to the string.
Definition string.c:3599
VALUE rb_str_locktmp(VALUE str)
Obtains a "temporary lock" of the string.
VALUE rb_str_equal(VALUE str1, VALUE str2)
Equality of two strings.
Definition string.c:4312
void rb_str_set_len(VALUE str, long len)
Overwrites the length of the string.
Definition string.c:3418
VALUE rb_str_buf_cat_ascii(VALUE dst, const char *src)
Identical to rb_str_cat_cstr(), except it additionally assumes the source string be a NUL terminated ...
Definition string.c:3773
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition string.c:2981
VALUE rb_str_substr(VALUE str, long beg, long len)
This is the implementation of two-argumented String#slice.
Definition string.c:3281
VALUE rb_str_unlocktmp(VALUE str)
Releases a lock formerly obtained by rb_str_locktmp().
Definition string.c:3400
void rb_str_modify_expand(VALUE str, long capa)
Identical to rb_str_modify(), except it additionally expands the capacity of the receiver.
Definition string.c:2775
VALUE rb_str_buf_new(long capa)
Allocates a "string buffer".
Definition string.c:1735
#define rb_str_new_cstr(str)
Identical to rb_str_new, except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1515
VALUE rb_obj_as_string(VALUE obj)
Try converting an object to its stringised representation using its to_s method, if any.
Definition string.c:1868
int rb_thread_interrupted(VALUE thval)
Checks if the thread's execution was recently interrupted.
Definition thread.c:1483
VALUE rb_mutex_new(void)
Creates a mutex.
int rb_thread_fd_writable(int fd)
Identical to rb_thread_wait_fd(), except it blocks the current thread until the given file descriptor...
Definition io.c:1694
VALUE rb_exec_recursive(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
"Recursion" API entry point.
Definition thread.c:5616
VALUE rb_mutex_synchronize(VALUE mutex, VALUE(*func)(VALUE arg), VALUE arg)
Obtains the lock, runs the passed function, and releases the lock when it completes.
void rb_thread_check_ints(void)
Checks for interrupts.
Definition thread.c:1466
VALUE rb_thread_current(void)
Obtains the "current" thread.
Definition thread.c:3225
int rb_thread_wait_fd(int fd)
Blocks the current thread until the given file descriptor is ready to be read.
Definition io.c:1688
void rb_thread_sleep(int sec)
Blocks for the given period of time.
Definition thread.c:1489
struct timeval rb_time_interval(VALUE num)
Creates a "time interval".
Definition time.c:2950
void rb_set_class_path(VALUE klass, VALUE space, const char *name)
Names a class.
Definition variable.c:441
VALUE rb_ivar_set(VALUE obj, ID name, VALUE val)
Identical to rb_iv_set(), except it accepts the name as an ID instead of a C string.
Definition variable.c:2030
VALUE rb_class_name(VALUE obj)
Queries the name of the given object's class.
Definition variable.c:500
int rb_respond_to(VALUE obj, ID mid)
Queries if the object responds to the method.
Definition vm_method.c:3480
VALUE rb_check_funcall(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcallv(), except it returns RUBY_Qundef instead of raising rb_eNoMethodError.
Definition vm_eval.c:688
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
#define RB_ID2SYM
Just another name of rb_id2sym.
Definition symbol.h:42
void rb_define_global_const(const char *name, VALUE val)
Identical to rb_define_const(), except it defines that of "global", i.e.
Definition variable.c:4092
void rb_define_readonly_variable(const char *name, const VALUE *var)
Identical to rb_define_variable(), except it does not allow Ruby programs to assign values to such gl...
Definition variable.c:855
rb_gvar_setter_t rb_gvar_readonly_setter
This function just raises rb_eNameError.
Definition variable.h:135
#define FMODE_READABLE
The IO is opened for reading.
Definition io.h:162
enum rb_io_mode rb_io_modestr_fmode(const char *modestr)
Maps a file mode string (that rb_file_open() takes) into a mixture of FMODE_ flags.
Definition io.c:6575
VALUE rb_io_get_io(VALUE io)
Identical to rb_io_check_io(), except it raises exceptions on conversion failures.
Definition io.c:870
VALUE rb_io_timeout(VALUE io)
Get the timeout associated with the specified io object.
Definition io.c:916
VALUE rb_io_taint_check(VALUE obj)
Definition io.c:840
void rb_io_read_check(rb_io_t *fptr)
Blocks until there is a pending read in the passed IO.
Definition io.c:1128
int rb_io_modestr_oflags(const char *modestr)
Identical to rb_io_modestr_fmode(), except it returns a mixture of O_ flags.
Definition io.c:6708
#define FMODE_SETENC_BY_BOM
This flag amends the encoding of the IO so that the BOM of the contents of the IO takes effect.
Definition io.h:260
rb_io_event
Type of events that an IO can wait.
Definition io.h:96
@ RUBY_IO_READABLE
IO::READABLE
Definition io.h:97
@ RUBY_IO_PRIORITY
IO::PRIORITY
Definition io.h:99
@ RUBY_IO_WRITABLE
IO::WRITABLE
Definition io.h:98
#define FMODE_READWRITE
The IO is opened for both read/write.
Definition io.h:168
#define FMODE_EXTERNAL
This flag means that an IO object is wrapping an "external" file descriptor, which is owned by someth...
Definition io.h:252
#define GetOpenFile
This is an old name of RB_IO_POINTER.
Definition io.h:442
void rb_io_check_byte_readable(rb_io_t *fptr)
Asserts that an IO is opened for byte-based reading.
Definition io.c:1074
#define FMODE_TTY
The IO is a TTY.
Definition io.h:192
#define FMODE_CREATE
The IO is opened for creating.
Definition io.h:215
void rb_io_check_readable(rb_io_t *fptr)
Just another name of rb_io_check_byte_readable.
Definition io.c:1083
int rb_io_oflags_fmode(int oflags)
Converts an oflags (that rb_io_modestr_oflags() returns) to a fmode (that rb_io_mode_flags() returns)...
Definition io.c:6632
int rb_wait_for_single_fd(int fd, int events, struct timeval *tv)
Blocks until the passed file descriptor is ready for the passed events.
Definition io.c:1680
FILE * rb_fdopen(int fd, const char *modestr)
Identical to rb_io_stdio_file(), except it takes file descriptors instead of Ruby's IO.
Definition io.c:7191
int rb_io_extract_encoding_option(VALUE opt, rb_encoding **enc_p, rb_encoding **enc2_p, enum rb_io_mode *fmode_p)
This function breaks down the option hash that IO#initialize takes into components.
Definition io.c:6857
int rb_io_descriptor(VALUE io)
Returns an integer representing the numeric file descriptor for io.
Definition io.c:2992
#define FMODE_WRITABLE
The IO is opened for writing.
Definition io.h:165
FILE * rb_io_stdio_file(rb_io_t *fptr)
Finds or creates a stdio's file structure from a Ruby's one.
Definition io.c:9481
#define FMODE_APPEND
The IO is opened for appending.
Definition io.h:207
#define MakeOpenFile
This is an old name of RB_IO_OPEN.
Definition io.h:465
#define FMODE_DUPLEX
Ruby eventually detects that the IO is bidirectional.
Definition io.h:200
#define FMODE_BINMODE
The IO is in "binary mode".
Definition io.h:179
int rb_io_maybe_wait_readable(int error, VALUE io, VALUE timeout)
Blocks until the passed IO is ready for reading, if that makes sense for the passed errno.
Definition io.c:1747
int capa
Designed capacity of the buffer.
Definition io.h:11
#define RB_IO_POINTER(obj, fp)
Queries the underlying IO pointer.
Definition io.h:436
VALUE rb_io_maybe_wait(int error, VALUE io, VALUE events, VALUE timeout)
Identical to rb_io_wait() except it additionally takes previous errno.
Definition io.c:1700
VALUE rb_eIOTimeoutError
Indicates that a timeout has occurred while performing an IO operation.
Definition io.c:195
char * ptr
Pointer to the underlying memory region, of at least capa bytes.
Definition io.h:2
#define FMODE_SYNC
The IO is in "sync mode".
Definition io.h:186
int off
Offset inside of ptr.
Definition io.h:5
VALUE rb_io_path(VALUE io)
Returns the path for the given IO.
Definition io.c:3066
void rb_io_extract_modeenc(VALUE *vmode_p, VALUE *vperm_p, VALUE opthash, int *oflags_p, enum rb_io_mode *fmode_p, rb_io_enc_t *convconfig_p)
This function can be seen as an extended version of rb_io_extract_encoding_option() that not only con...
Definition io.c:6982
void rb_io_check_initialized(rb_io_t *fptr)
Asserts that the passed IO is initialised.
Definition io.c:847
#define FMODE_EXCL
This flag amends the effect of FMODE_CREATE, so that if there already is a file at the given path the...
Definition io.h:223
#define FMODE_TEXTMODE
The IO is in "text mode".
Definition io.h:243
int rb_io_fptr_finalize(rb_io_t *fptr)
Destroys the given IO.
Definition io.c:5767
VALUE rb_io_check_io(VALUE io)
Try converting an object to its IO representation using its to_io method, if any.
Definition io.c:876
VALUE rb_io_closed_p(VALUE io)
Returns whether or not the underlying IO is closed.
Definition io.c:5955
struct rb_io_internal_buffer rb_io_buffer_t
Just another name of rb_io_buffer_t.
Definition io.h:125
VALUE rb_io_set_timeout(VALUE io, VALUE timeout)
Set the timeout associated with the specified io object.
Definition io.c:945
ssize_t rb_io_bufwrite(VALUE io, const void *buf, size_t size)
Buffered write to the passed IO.
Definition io.c:2112
void rb_io_check_char_readable(rb_io_t *fptr)
Asserts that an IO is opened for character-based reading.
Definition io.c:1055
#define FMODE_TRUNC
This flag amends the effect of FMODE_CREATE, so that if there already is a file at the given path it ...
Definition io.h:229
int rb_io_read_pending(rb_io_t *fptr)
Queries if the passed IO has any pending reads.
Definition io.c:1119
VALUE rb_io_get_write_io(VALUE io)
Queries the tied IO for writing.
Definition io.c:882
void rb_io_set_nonblock(rb_io_t *fptr)
Instructs the OS to put its internal file structure into "nonblocking mode".
Definition io.c:3519
int rb_io_wait_writable(int fd)
Blocks until the passed file descriptor gets writable.
Definition io.c:1636
VALUE rb_io_open_descriptor(VALUE klass, int descriptor, int mode, VALUE path, VALUE timeout, struct rb_io_encoding *encoding)
Allocate a new IO object, with the given file descriptor.
Definition io.c:9347
VALUE rb_io_set_write_io(VALUE io, VALUE w)
Assigns the tied IO for writing.
Definition io.c:893
void rb_io_check_writable(rb_io_t *fptr)
Asserts that an IO is opened for writing.
Definition io.c:1107
int rb_io_maybe_wait_writable(int error, VALUE io, VALUE timeout)
Blocks until the passed IO is ready for writing, if that makes sense for the passed errno.
Definition io.c:1762
void rb_io_check_closed(rb_io_t *fptr)
This badly named function asserts that the passed IO is open.
Definition io.c:855
void rb_eof_error(void)
Utility function to raise rb_eEOFError.
Definition io.c:834
int rb_io_wait_readable(int fd)
Blocks until the passed file descriptor gets readable.
Definition io.c:1601
void rb_io_synchronized(rb_io_t *fptr)
Sets FMODE_SYNC.
Definition io.c:7478
VALUE rb_io_wait(VALUE io, VALUE events, VALUE timeout)
Blocks until the passed IO is ready for the passed events.
Definition io.c:1541
int len
Length of the buffer.
Definition io.h:8
VALUE rb_ractor_stdin(void)
Queries the standard input of the current Ractor that is calling this function.
Definition ractor.c:1082
void rb_ractor_stderr_set(VALUE io)
Assigns an IO to the standard error of the Ractor that is calling this function.
Definition ractor.c:1142
void rb_ractor_stdout_set(VALUE io)
Assigns an IO to the standard output of the Ractor that is calling this function.
Definition ractor.c:1130
void rb_ractor_stdin_set(VALUE io)
Assigns an IO to the standard input of the Ractor that is calling this function.
Definition ractor.c:1118
void * rb_thread_call_with_gvl(void *(*func)(void *), void *data1)
(Re-)acquires the GVL.
Definition thread.c:2063
#define RB_NUM2INT
Just another name of rb_num2int_inline.
Definition int.h:38
#define RB_INT2NUM
Just another name of rb_int2num_inline.
Definition int.h:37
VALUE rb_f_sprintf(int argc, const VALUE *argv)
Identical to rb_str_format(), except how the arguments are arranged.
Definition sprintf.c:225
#define RB_BLOCK_CALL_FUNC_ARGLIST(yielded_arg, callback_arg)
Shim for block function parameters.
Definition iterator.h:58
VALUE rb_yield_values2(int n, const VALUE *argv)
Identical to rb_yield_values(), except it takes the parameters as a C array instead of variadic argum...
Definition vm_eval.c:1419
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1374
void rb_fd_term(rb_fdset_t *f)
Destroys the rb_fdset_t, releasing any memory and resources it used.
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
Definition memory.h:360
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
#define MEMMOVE(p1, p2, type, n)
Handy macro to call memmove.
Definition memory.h:384
#define NUM2MODET
Converts a C's mode_t into an instance of rb_cInteger.
Definition mode_t.h:28
void rb_define_hooked_variable(const char *q, VALUE *w, type *e, void_type *r)
Define a function-backended global variable.
void rb_define_virtual_variable(const char *q, type *w, void_type *e)
Define a function-backended global variable.
#define PRI_OFFT_PREFIX
A rb_sprintf() format prefix to be used for an off_t parameter.
Definition off_t.h:55
#define OFFT2NUM
Converts a C's off_t into an instance of rb_cInteger.
Definition off_t.h:33
#define NUM2OFFT
Converts an instance of rb_cNumeric into C's off_t.
Definition off_t.h:44
#define PIDT2NUM
Converts a C's pid_t into an instance of rb_cInteger.
Definition pid_t.h:28
#define rb_fd_isset
Queries if the given fd is in the rb_fdset_t.
Definition posix.h:60
#define rb_fd_select
Waits for multiple file descriptors at once.
Definition posix.h:66
#define rb_fd_init
Initialises the :given :rb_fdset_t.
Definition posix.h:63
#define rb_fd_set
Sets the given fd to the rb_fdset_t.
Definition posix.h:54
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
#define RARRAY_AREF(a, i)
Definition rarray.h:403
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition rarray.h:52
#define RFILE(obj)
Convenient casting macro.
Definition rfile.h:50
#define StringValue(v)
Ensures that the parameter object is a String.
Definition rstring.h:66
#define RSTRING_GETMEM(str, ptrvar, lenvar)
Convenient macro to obtain the contents and length at once.
Definition rstring.h:450
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
Definition rstring.h:89
#define RUBY_TYPED_DEFAULT_FREE
This is a value you can set to rb_data_type_struct::dfree.
Definition rtypeddata.h:80
struct rb_data_type_struct rb_data_type_t
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:205
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
Definition rtypeddata.h:508
VALUE rb_get_argv(void)
Queries the arguments passed to the current process that you can access from Ruby as ARGV.
Definition io.c:14739
void rb_p(VALUE obj)
Inspects an object.
Definition io.c:9133
#define FilePathValue(v)
Ensures that the parameter object is a path.
Definition ruby.h:90
#define errno
Ractor-aware version of errno.
Definition ruby.h:388
#define RB_SCAN_ARGS_LAST_HASH_KEYWORDS
Treat a final argument as keywords if it is a hash, and not as keywords otherwise.
Definition scan_args.h:59
#define RB_PASS_CALLED_KEYWORDS
Pass keywords if current method is called with keywords, useful for argument delegation.
Definition scan_args.h:78
Scheduler APIs.
VALUE rb_fiber_scheduler_current(void)
Identical to rb_fiber_scheduler_get(), except it also returns RUBY_Qnil in case of a blocking fiber.
Definition scheduler.c:471
VALUE rb_fiber_scheduler_io_pread_memory(VALUE scheduler, VALUE io, rb_off_t from, void *base, size_t size, size_t length)
Non-blocking pread from the passed IO using a native buffer.
Definition scheduler.c:1006
VALUE rb_fiber_scheduler_make_timeout(struct timeval *timeout)
Converts the passed timeout to an expression that rb_fiber_scheduler_block() etc.
Definition scheduler.c:522
VALUE rb_fiber_scheduler_io_wait_readable(VALUE scheduler, VALUE io)
Non-blocking wait until the passed IO is ready for reading.
Definition scheduler.c:756
VALUE rb_fiber_scheduler_io_read_memory(VALUE scheduler, VALUE io, void *base, size_t size, size_t length)
Non-blocking read from the passed IO using a native buffer.
Definition scheduler.c:982
VALUE rb_fiber_scheduler_io_wait(VALUE scheduler, VALUE io, VALUE events, VALUE timeout)
Non-blocking version of rb_io_wait().
Definition scheduler.c:742
VALUE rb_fiber_scheduler_io_selectv(VALUE scheduler, int argc, VALUE *argv)
Non-blocking version of IO.select, argv variant.
Definition scheduler.c:786
VALUE rb_fiber_scheduler_io_pwrite_memory(VALUE scheduler, VALUE io, rb_off_t from, const void *base, size_t size, size_t length)
Non-blocking pwrite to the passed IO using a native buffer.
Definition scheduler.c:1018
VALUE rb_fiber_scheduler_current_for_thread(VALUE thread)
Identical to rb_fiber_scheduler_current(), except it queries for that of the passed thread value inst...
Definition scheduler.c:479
VALUE rb_fiber_scheduler_io_write_memory(VALUE scheduler, VALUE io, const void *base, size_t size, size_t length)
Non-blocking write to the passed IO using a native buffer.
Definition scheduler.c:994
VALUE rb_fiber_scheduler_current_for_threadptr(struct rb_thread_struct *thread)
Identical to rb_fiber_scheduler_current_for_thread(), except it expects a threadptr instead of a thre...
Definition scheduler.c:484
VALUE rb_fiber_scheduler_io_wait_writable(VALUE scheduler, VALUE io)
Non-blocking wait until the passed IO is ready for writing.
Definition scheduler.c:762
VALUE rb_fiber_scheduler_io_close(VALUE scheduler, VALUE io)
Non-blocking close the given IO.
Definition scheduler.c:1038
int rb_thread_fd_select(int nfds, rb_fdset_t *rfds, rb_fdset_t *wfds, rb_fdset_t *efds, struct timeval *timeout)
Waits for multiple file descriptors at once.
Definition thread.c:4579
@ RUBY_Qfalse
#define RTEST
This is an old name of RB_TEST.
#define _(args)
This was a transition path from K&R to ANSI.
Definition stdarg.h:35
C99 shim for <stdbool.h>.
Ruby's File and IO.
Definition rfile.h:35
Definition io.c:241
Definition win32.h:230
The data structure which wraps the fd_set bitmap used by select(2).
Definition largesize.h:71
Decomposed encoding flags (e.g.
Definition io.h:134
int ecflags
Flags.
Definition io.h:144
VALUE ecopts
Flags as Ruby hash.
Definition io.h:152
rb_encoding * enc2
External encoding.
Definition io.h:138
rb_encoding * enc
Internal encoding.
Definition io.h:136
IO buffers.
Definition io.h:109
char * ptr
Pointer to the underlying memory region, of at least capa bytes.
Definition io.h:112
int off
Offset inside of ptr.
Definition io.h:115
int len
Length of the buffer.
Definition io.h:118
int capa
Designed capacity of the buffer.
Definition io.h:121
Ruby's IO, metadata and buffers.
Definition io.h:295
rb_io_buffer_t wbuf
Write buffer.
Definition io.h:330
enum rb_io_mode mode
mode flags: FMODE_XXXs
Definition io.h:310
rb_econv_t * readconv
Encoding converter used when reading from this IO.
Definition io.h:352
rb_econv_t * writeconv
Encoding converter used when writing to this IO.
Definition io.h:363
struct rb_io_encoding encs
Decomposed encoding flags.
Definition io.h:348
VALUE self
The IO's Ruby level counterpart.
Definition io.h:298
VALUE write_lock
This is a Ruby level mutex.
Definition io.h:400
VALUE timeout
The timeout associated with this IO when performing blocking operations.
Definition io.h:406
FILE * stdio_file
stdio ptr for read/write, if available.
Definition io.h:302
VALUE writeconv_pre_ecopts
Value of rb_io_t::rb_io_enc_t::ecopts stored right before initialising rb_io_t::writeconv.
Definition io.h:390
VALUE tied_io_for_writing
Duplex IO object, if set.
Definition io.h:345
int writeconv_initialized
Whether rb_io_t::writeconv is already set up.
Definition io.h:376
int fd
file descriptor.
Definition io.h:306
rb_io_buffer_t rbuf
(Byte) read buffer.
Definition io.h:337
int lineno
number of lines read
Definition io.h:318
struct ccan_list_head blocking_operations
Threads that are performing a blocking operation without the GVL using this IO.
Definition io.h:131
VALUE writeconv_asciicompat
This is, when set, an instance of rb_cString which holds the "common" encoding.
Definition io.h:372
rb_io_buffer_t cbuf
rb_io_ungetc() destination.
Definition io.h:359
rb_pid_t pid
child's pid (for pipes)
Definition io.h:314
int writeconv_pre_ecflags
Value of rb_io_t::rb_io_enc_t::ecflags stored right before initialising rb_io_t::writeconv.
Definition io.h:383
void(*) finalize(struct rb_io *, int)
finalize proc
Definition io.h:326
VALUE pathv
pathname for file
Definition io.h:322
intptr_t SIGNED_VALUE
A signed integer type that has the same width with VALUE.
Definition value.h:63
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
#define RBIMPL_WARNING_IGNORED(flag)
Suppresses a warning.
#define RBIMPL_WARNING_PUSH()
Pushes compiler warning state.
#define RBIMPL_WARNING_POP()
Pops compiler warning state.