Ruby 4.1.0dev (2026-11-18 revision 9de06831e37534f8a163e598cc0c6903c7687430)
io.c (9de06831e37534f8a163e598cc0c6903c7687430)
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#ifdef __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(__CYGWIN__) || defined(_WIN32)
52# define NO_SAFE_RENAME
53#endif
54
55#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__sun)
56# define USE_SETVBUF
57#endif
58
59#include <sys/types.h>
60#ifdef HAVE_SYS_IOCTL_H
61#include <sys/ioctl.h>
62#endif
63#if defined(HAVE_FCNTL_H)
64#include <fcntl.h>
65#elif defined(HAVE_SYS_FCNTL_H)
66#include <sys/fcntl.h>
67#endif
68
69#ifdef HAVE_SYS_TIME_H
70# include <sys/time.h>
71#endif
72
73#include <sys/stat.h>
74
75#if defined(HAVE_SYS_PARAM_H)
76# include <sys/param.h>
77#endif
78
79#if !defined NOFILE
80# define NOFILE 64
81#endif
82
83#ifdef HAVE_UNISTD_H
84#include <unistd.h>
85#endif
86
87#ifdef HAVE_SYSCALL_H
88#include <syscall.h>
89#elif defined HAVE_SYS_SYSCALL_H
90#include <sys/syscall.h>
91#endif
92
93#ifdef HAVE_SYS_UIO_H
94#include <sys/uio.h>
95#endif
96
97#ifdef HAVE_SYS_WAIT_H
98# include <sys/wait.h> /* for WNOHANG on BSD */
99#endif
100
101#ifdef HAVE_COPYFILE_H
102# include <copyfile.h>
103#endif
104
105#if defined __APPLE__
106# include <AvailabilityMacros.h>
107#endif
108
110#include "ccan/list/list.h"
111#include "dln.h"
112#include "encindex.h"
113#include "id.h"
114#include "internal.h"
115#include "internal/class.h"
116#include "internal/encoding.h"
117#include "internal/error.h"
118#include "internal/inits.h"
119#include "internal/io.h"
120#include "internal/numeric.h"
121#include "internal/object.h"
122#include "internal/process.h"
123#include "internal/string.h"
124#include "internal/thread.h"
125#include "internal/transcode.h"
126#include "internal/variable.h"
127#include "ruby/io.h"
128#include "ruby/io/buffer.h"
129#include "ruby/missing.h"
130#include "ruby/thread.h"
131#include "ruby/util.h"
132#include "ruby_atomic.h"
133#include "ruby/ractor.h"
134
135#if !USE_POLL
136# include "vm_core.h"
137#endif
138
139#include "builtin.h"
140
141#ifndef O_ACCMODE
142#define O_ACCMODE (O_RDONLY | O_WRONLY | O_RDWR)
143#endif
144
145#ifndef PIPE_BUF
146# ifdef _POSIX_PIPE_BUF
147# define PIPE_BUF _POSIX_PIPE_BUF
148# else
149# define PIPE_BUF 512 /* is this ok? */
150# endif
151#endif
152
153#ifndef EWOULDBLOCK
154# define EWOULDBLOCK EAGAIN
155#endif
156
157#if defined(HAVE___SYSCALL) && (defined(__APPLE__) || defined(__OpenBSD__))
158/* Mac OS X and OpenBSD have __syscall but don't define it in headers */
159off_t __syscall(quad_t number, ...);
160#endif
161
162#define IO_RBUF_CAPA_MIN 8192
163#define IO_CBUF_CAPA_MIN (128*1024)
164#define IO_RBUF_CAPA_FOR(fptr) (NEED_READCONV(fptr) ? IO_CBUF_CAPA_MIN : IO_RBUF_CAPA_MIN)
165#define IO_WBUF_CAPA_MIN 8192
166
167#define IO_MAX_BUFFER_GROWTH 8 * 1024 * 1024 // 8MB
168
169/* define system APIs */
170#ifdef _WIN32
171#undef open
172#define open rb_w32_uopen
173#undef rename
174#define rename(f, t) rb_w32_urename((f), (t))
175#include "win32/file.h"
176#endif
177
184
185static VALUE rb_eEAGAINWaitReadable;
186static VALUE rb_eEAGAINWaitWritable;
187#if EAGAIN != EWOULDBLOCK
188static VALUE rb_eEWOULDBLOCKWaitReadable;
189static VALUE rb_eEWOULDBLOCKWaitWritable;
190#endif
191static VALUE rb_eEINPROGRESSWaitWritable;
192static VALUE rb_eEINPROGRESSWaitReadable;
193
195static VALUE orig_stdout, orig_stderr;
196
198VALUE rb_rs;
201
202static VALUE argf;
203
204static ID id_write, id_read, id_flush, id_readpartial, id_set_encoding, id_fileno;
205static VALUE sym_mode, sym_perm, sym_flags, sym_extenc, sym_intenc, sym_encoding, sym_open_args;
206static VALUE sym_textmode, sym_binmode, sym_autoclose;
207static VALUE sym_SET, sym_CUR, sym_END;
208static VALUE sym_wait_readable, sym_wait_writable;
209#ifdef SEEK_DATA
210static VALUE sym_DATA;
211#endif
212#ifdef SEEK_HOLE
213static VALUE sym_HOLE;
214#endif
215
216static VALUE prep_io(int fd, enum rb_io_mode fmode, VALUE klass, const char *path);
217
218VALUE
219rb_io_blocking_region_wait(struct rb_io *io, rb_blocking_function_t *function, void *argument, enum rb_io_event events)
220{
221 return rb_thread_io_blocking_call(io, function, argument, events);
222}
223
224VALUE rb_io_blocking_region(struct rb_io *io, rb_blocking_function_t *function, void *argument)
225{
226 return rb_io_blocking_region_wait(io, function, argument, 0);
227}
228
229struct argf {
230 VALUE filename, current_file;
231 long last_lineno; /* $. */
232 long lineno;
233 VALUE argv;
234 VALUE inplace;
235 struct rb_io_encoding encs;
236 int8_t init_p, next_p, binmode;
237};
238
239
240#if defined(__APPLE__) && \
241 (!defined(MAC_OS_VERSION_27_0) || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_VERSION_27_0))
242
243# if __has_attribute(availability) && __has_warning("-Wunguarded-availability-new")
244
246RBIMPL_WARNING_IGNORED(-Wunguarded-availability-new)
247
248# ifdef HAVE_DUP3
249static inline int (*rb_dup3(void))(int, int, int) {return &dup3;}
250# define dup3 rb_dup3()
251# endif
252
253# ifdef HAVE_PIPE2
254static inline int (*rb_pipe2(void))(int [2], int) {return &pipe2;}
255# define pipe2 rb_pipe2()
256# endif
257
259
260# else /* __API_AVAILABLE macro does nothing on gcc */
261
262# ifdef HAVE_DUP3
263__attribute__((weak)) int dup3(int, int, int);
264# endif
265# ifdef HAVE_PIPE2
266__attribute__((weak)) int pipe2(int [2], int);
267# endif
268
269# endif
270#endif /* __APPLE__ && < MAC_OS_X_VERSION_27_0 */
271
272static rb_atomic_t max_file_descriptor = NOFILE;
273void
275{
276 rb_atomic_t afd = (rb_atomic_t)fd;
277 rb_atomic_t max_fd = max_file_descriptor;
278 int err;
279
280 if (fd < 0 || afd <= max_fd)
281 return;
282
283#if defined(HAVE_FCNTL) && defined(F_GETFL)
284 err = fcntl(fd, F_GETFL) == -1;
285#else
286 {
287 struct stat buf;
288 err = fstat(fd, &buf) != 0;
289 }
290#endif
291 if (err && errno == EBADF) {
292 rb_bug("rb_update_max_fd: invalid fd (%d) given.", fd);
293 }
294
295 while (max_fd < afd) {
296 max_fd = ATOMIC_CAS(max_file_descriptor, max_fd, afd);
297 }
298}
299
300void
301rb_maygvl_fd_fix_cloexec(int fd)
302{
303 /* MinGW don't have F_GETFD and FD_CLOEXEC. [ruby-core:40281] */
304#if defined(HAVE_FCNTL) && defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
305 int flags, flags2, ret;
306 flags = fcntl(fd, F_GETFD); /* should not fail except EBADF. */
307 if (flags == -1) {
308 rb_bug("rb_maygvl_fd_fix_cloexec: fcntl(%d, F_GETFD) failed: %s", fd, strerror(errno));
309 }
310 if (fd <= 2)
311 flags2 = flags & ~FD_CLOEXEC; /* Clear CLOEXEC for standard file descriptors: 0, 1, 2. */
312 else
313 flags2 = flags | FD_CLOEXEC; /* Set CLOEXEC for non-standard file descriptors: 3, 4, 5, ... */
314 if (flags != flags2) {
315 ret = fcntl(fd, F_SETFD, flags2);
316 if (ret != 0) {
317 rb_bug("rb_maygvl_fd_fix_cloexec: fcntl(%d, F_SETFD, %d) failed: %s", fd, flags2, strerror(errno));
318 }
319 }
320#endif
321}
322
323void
325{
326 rb_maygvl_fd_fix_cloexec(fd);
328}
329
330static inline bool
331io_again_p(int e)
332{
333 return (e == EWOULDBLOCK) || (e == EAGAIN);
334}
335
336int
337rb_cloexec_open(const char *pathname, int flags, mode_t mode)
338{
339 int ret;
340
341 static const int retry_interval = 0;
342 static const int retry_max_count = 10000;
343
344 int retry_count = 0;
345
346#ifdef O_CLOEXEC
347 flags |= O_CLOEXEC;
348#elif defined O_NOINHERIT
349 flags |= O_NOINHERIT;
350#endif
351
352 while ((ret = open(pathname, flags, mode)) == -1) {
353 int e = errno;
354 if (!io_again_p(e)) break;
355 if (retry_count++ >= retry_max_count) break;
356
357 sleep(retry_interval);
358 }
359
360 if (ret < 0) return ret;
361#ifdef O_CLOEXEC
362 if (ret > 2) return ret;
363#endif
364 rb_maygvl_fd_fix_cloexec(ret);
365 return ret;
366}
367
368int
370{
371 /* Don't allocate standard file descriptors: 0, 1, 2 */
372 return rb_cloexec_fcntl_dupfd(oldfd, 3);
373}
374
375int
376rb_cloexec_dup2(int oldfd, int newfd)
377{
378 int ret;
379
380 /* When oldfd == newfd, dup2 succeeds but dup3 fails with EINVAL.
381 * rb_cloexec_dup2 succeeds as dup2. */
382 if (oldfd == newfd) {
383 ret = newfd;
384 }
385 else {
386#if defined(HAVE_DUP3) && defined(O_CLOEXEC)
387# if defined(__APPLE__)
388# define try_dup3 (dup3 != NULL)
389# define abandon_dup3() true
390# else
391 static bool try_dup3 = true;
392# define abandon_dup3() (errno != ENOSYS || !!(try_dup3 = false))
393# endif
394 if (newfd <= 2) {
395 /* pass stdin, stdout and stderr to children */
396 }
397 else if (try_dup3) {
398 ret = dup3(oldfd, newfd, O_CLOEXEC);
399 /* dup3 is available since:
400 * - Linux 2.6.27, glibc 2.9
401 * - macOS 27.0
402 */
403 if (ret != -1)
404 return ret;
405 if (abandon_dup3()) return ret;
406 }
407#endif
408 ret = dup2(oldfd, newfd);
409 if (ret < 0) return ret;
410 }
411 rb_maygvl_fd_fix_cloexec(ret);
412 return ret;
413}
414
415static int
416rb_fd_set_nonblock(int fd)
417{
418#ifdef _WIN32
419 return rb_w32_set_nonblock(fd);
420#elif defined(F_GETFL)
421 int oflags = fcntl(fd, F_GETFL);
422
423 if (oflags == -1)
424 return -1;
425 if (oflags & O_NONBLOCK)
426 return 0;
427 oflags |= O_NONBLOCK;
428 return fcntl(fd, F_SETFL, oflags);
429#endif
430 return 0;
431}
432
433static inline int
434cloexec_pipe(int descriptors[2], int flags, bool force_cloexec)
435{
436 int result = -1;
437#ifdef HAVE_PIPE2
438# if defined(__APPLE__)
439# define try_pipe2 (pipe2 != NULL)
440# define abandon_pipe2() true
441# else
442 static bool try_pipe2 = true;
443# define abandon_pipe2() (errno != ENOSYS || !!(try_pipe2 = false))
444# endif
445 if (try_pipe2) {
446 result = pipe2(descriptors, O_CLOEXEC | flags);
447 if (result == 0) return result;
448 if (abandon_pipe2()) return result;
449 }
450#endif
451 if (result < 0 && (result = pipe(descriptors)) < 0)
452 return result;
453
454#ifdef __CYGWIN__
455 if (result == 0 && descriptors[1] == -1) {
456 close(descriptors[0]);
457 descriptors[0] = -1;
458 errno = ENFILE;
459 return -1;
460 }
461#endif
462
463 if (!force_cloexec) return result;
464
465 /* no pipe2 or fallenback to dup */
466 rb_maygvl_fd_fix_cloexec(descriptors[0]);
467 rb_maygvl_fd_fix_cloexec(descriptors[1]);
468
469#ifndef _WIN32
470 rb_fd_set_nonblock(descriptors[0]);
471 rb_fd_set_nonblock(descriptors[1]);
472#endif
473
474 return result;
475}
476
477int
478rb_cloexec_pipe(int descriptors[2])
479{
480 return cloexec_pipe(descriptors, O_NONBLOCK, true);
481}
482
483int
484rb_cloexec_fcntl_dupfd(int fd, int minfd)
485{
486 int ret;
487
488#if defined(HAVE_FCNTL) && defined(F_DUPFD_CLOEXEC)
489 ret = fcntl(fd, F_DUPFD_CLOEXEC, minfd);
490 if (ret > 2) return ret;
491#elif defined(HAVE_FCNTL) && defined(F_DUPFD)
492 ret = fcntl(fd, F_DUPFD, minfd);
493#else
494 ret = dup(fd);
495 if (ret >= 0 && ret < minfd) {
496 const int prev_fd = ret;
497 ret = rb_cloexec_fcntl_dupfd(fd, minfd);
498 close(prev_fd);
499 }
500 return ret;
501#endif
502 if (ret < 0) return ret;
503 rb_maygvl_fd_fix_cloexec(ret);
504 return ret;
505}
506
507#define argf_of(obj) (*(struct argf *)DATA_PTR(obj))
508#define ARGF argf_of(argf)
509#define ARGF_SET(field, value) RB_OBJ_WRITE(argf, &ARGF.field, value)
510
511#define GetWriteIO(io) rb_io_get_write_io(io)
512
513#define READ_DATA_PENDING(fptr) ((fptr)->rbuf.len)
514#define READ_DATA_PENDING_COUNT(fptr) ((fptr)->rbuf.len)
515#define READ_DATA_PENDING_PTR(fptr) ((fptr)->rbuf.ptr+(fptr)->rbuf.off)
516#define READ_DATA_BUFFERED(fptr) READ_DATA_PENDING(fptr)
517
518#define READ_CHAR_PENDING(fptr) ((fptr)->cbuf.len)
519#define READ_CHAR_PENDING_COUNT(fptr) ((fptr)->cbuf.len)
520#define READ_CHAR_PENDING_PTR(fptr) ((fptr)->cbuf.ptr+(fptr)->cbuf.off)
521
522#if defined(_WIN32)
523#define WAIT_FD_IN_WIN32(fptr) \
524 (rb_w32_io_cancelable_p((fptr)->fd) ? Qnil : rb_io_wait(fptr->self, RB_INT2NUM(RUBY_IO_READABLE), RUBY_IO_TIMEOUT_DEFAULT))
525#else
526#define WAIT_FD_IN_WIN32(fptr)
527#endif
528
529#define READ_CHECK(fptr) do {\
530 if (!READ_DATA_PENDING(fptr)) {\
531 WAIT_FD_IN_WIN32(fptr);\
532 rb_io_check_closed(fptr);\
533 }\
534} while(0)
535
536#ifndef S_ISSOCK
537# ifdef _S_ISSOCK
538# define S_ISSOCK(m) _S_ISSOCK(m)
539# else
540# ifdef _S_IFSOCK
541# define S_ISSOCK(m) (((m) & S_IFMT) == _S_IFSOCK)
542# else
543# ifdef S_IFSOCK
544# define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK)
545# endif
546# endif
547# endif
548#endif
549
550static int io_fflush(rb_io_t *);
551static rb_io_t *flush_before_seek(rb_io_t *fptr, bool discard_rbuf);
552static void clear_readconv(rb_io_t *fptr);
553static void clear_codeconv(rb_io_t *fptr);
554
555#define FMODE_SIGNAL_ON_EPIPE (1<<17)
556
557#define fptr_signal_on_epipe(fptr) \
558 (((fptr)->mode & FMODE_SIGNAL_ON_EPIPE) != 0)
559
560#define fptr_set_signal_on_epipe(fptr, flag) \
561 ((flag) ? \
562 (fptr)->mode |= FMODE_SIGNAL_ON_EPIPE : \
563 (fptr)->mode &= ~FMODE_SIGNAL_ON_EPIPE)
564
565extern ID ruby_static_id_signo;
566
567NORETURN(static void rb_sys_fail_on_write(rb_io_t *fptr));
568static void
569rb_sys_fail_on_write(rb_io_t *fptr)
570{
571 int e = errno;
572 VALUE errinfo = rb_syserr_new_path(e, (fptr)->pathv);
573#if defined EPIPE
574 if (fptr_signal_on_epipe(fptr) && (e == EPIPE)) {
575 const VALUE sig =
576# if defined SIGPIPE
577 INT2FIX(SIGPIPE) - INT2FIX(0) +
578# endif
579 INT2FIX(0);
580 rb_ivar_set(errinfo, ruby_static_id_signo, sig);
581 }
582#endif
583 rb_exc_raise(errinfo);
584}
585
586#define NEED_NEWLINE_DECORATOR_ON_READ(fptr) ((fptr)->mode & FMODE_TEXTMODE)
587#define NEED_NEWLINE_DECORATOR_ON_WRITE(fptr) ((fptr)->mode & FMODE_TEXTMODE)
588#if defined(RUBY_TEST_CRLF_ENVIRONMENT) || defined(_WIN32)
589# define RUBY_CRLF_ENVIRONMENT 1
590#else
591# define RUBY_CRLF_ENVIRONMENT 0
592#endif
593
594#if RUBY_CRLF_ENVIRONMENT
595/* Windows */
596# define DEFAULT_TEXTMODE FMODE_TEXTMODE
597# define TEXTMODE_NEWLINE_DECORATOR_ON_WRITE ECONV_CRLF_NEWLINE_DECORATOR
598/*
599 * CRLF newline is set as default newline decorator.
600 * If only CRLF newline conversion is needed, we use binary IO process
601 * with OS's text mode for IO performance improvement.
602 * If encoding conversion is needed or a user sets text mode, we use encoding
603 * conversion IO process and universal newline decorator by default.
604 */
605#define NEED_READCONV(fptr) ((fptr)->encs.enc2 != NULL || (fptr)->encs.ecflags & ~ECONV_CRLF_NEWLINE_DECORATOR)
606#define WRITECONV_MASK ( \
607 (ECONV_DECORATOR_MASK & ~ECONV_CRLF_NEWLINE_DECORATOR)|\
608 ECONV_STATEFUL_DECORATOR_MASK|\
609 0)
610#define NEED_WRITECONV(fptr) ( \
611 ((fptr)->encs.enc != NULL && (fptr)->encs.enc != rb_ascii8bit_encoding()) || \
612 ((fptr)->encs.ecflags & WRITECONV_MASK) || \
613 0)
614#define SET_BINARY_MODE(fptr) setmode((fptr)->fd, O_BINARY)
615
616#define NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr) do {\
617 if (NEED_NEWLINE_DECORATOR_ON_READ(fptr)) {\
618 if (((fptr)->mode & FMODE_READABLE) &&\
619 !((fptr)->encs.ecflags & ECONV_NEWLINE_DECORATOR_MASK)) {\
620 setmode((fptr)->fd, O_BINARY);\
621 }\
622 else {\
623 setmode((fptr)->fd, O_TEXT);\
624 }\
625 }\
626} while(0)
627
628#define SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags) do {\
629 if ((enc2) && ((ecflags) & ECONV_DEFAULT_NEWLINE_DECORATOR)) {\
630 (ecflags) |= ECONV_UNIVERSAL_NEWLINE_DECORATOR;\
631 }\
632} while(0)
633
634/*
635 * IO unread with taking care of removed '\r' in text mode.
636 */
637static void
638io_unread(rb_io_t *fptr, bool discard_rbuf)
639{
640 rb_off_t r, pos;
641 ssize_t read_size;
642 long i;
643 long newlines = 0;
644 long extra_max;
645 char *p;
646 char *buf;
647
648 rb_io_check_closed(fptr);
649 if (fptr->rbuf.len == 0 || fptr->mode & FMODE_DUPLEX) {
650 return;
651 }
652
653 errno = 0;
654 if (!rb_w32_fd_is_text(fptr->fd)) {
655 r = lseek(fptr->fd, -fptr->rbuf.len, SEEK_CUR);
656 if (r < 0 && errno) {
657 if (errno == ESPIPE)
658 fptr->mode |= FMODE_DUPLEX;
659 if (!discard_rbuf) return;
660 }
661
662 goto end;
663 }
664
665 pos = lseek(fptr->fd, 0, SEEK_CUR);
666 if (pos < 0 && errno) {
667 if (errno == ESPIPE)
668 fptr->mode |= FMODE_DUPLEX;
669 if (!discard_rbuf) goto end;
670 }
671
672 /* add extra offset for removed '\r' in rbuf */
673 extra_max = (pos - fptr->rbuf.len < fptr->rbuf.len) ?
674 (long)(pos - fptr->rbuf.len) : fptr->rbuf.len;
675 p = fptr->rbuf.ptr + fptr->rbuf.off;
676
677 for (i = 0; i < fptr->rbuf.len; i++) {
678 if (*p == '\n') newlines++;
679 if (extra_max == newlines) break;
680 p++;
681 }
682
683 /* if the end of rbuf is '\r', rbuf doesn't have '\r' within rbuf.len */
684 if (*(fptr->rbuf.ptr + fptr->rbuf.capa - 1) == '\r' &&
685 newlines < pos - fptr->rbuf.len) {
686 newlines++;
687 }
688
689 buf = ALLOC_N(char, fptr->rbuf.len + newlines);
690 while (newlines >= 0) {
691 r = lseek(fptr->fd, pos - fptr->rbuf.len - newlines, SEEK_SET);
692 if (newlines == 0) break;
693 if (r < 0) {
694 newlines--;
695 continue;
696 }
697 read_size = _read(fptr->fd, buf, fptr->rbuf.len + newlines);
698 if (read_size < 0) {
699 int e = errno;
700 free(buf);
701 rb_syserr_fail_path(e, fptr->pathv);
702 }
703 if (read_size == fptr->rbuf.len) {
704 lseek(fptr->fd, r, SEEK_SET);
705 break;
706 }
707 else {
708 newlines--;
709 }
710 }
711 free(buf);
712 end:
713 fptr->rbuf.off = 0;
714 fptr->rbuf.len = 0;
715 clear_codeconv(fptr);
716 return;
717}
718
719/*
720 * We use io_seek to back cursor position when changing mode from text to binary,
721 * but stdin and pipe cannot seek back. Stdin and pipe read should use encoding
722 * conversion for working properly with mode change.
723 *
724 * Return previous translation mode.
725 */
726static inline int
727set_binary_mode_with_seek_cur(rb_io_t *fptr)
728{
729 if (!rb_w32_fd_is_text(fptr->fd)) return O_BINARY;
730
731 if (fptr->rbuf.len == 0 || fptr->mode & FMODE_DUPLEX) {
732 return setmode(fptr->fd, O_BINARY);
733 }
734 flush_before_seek(fptr, false);
735 return setmode(fptr->fd, O_BINARY);
736}
737#define SET_BINARY_MODE_WITH_SEEK_CUR(fptr) set_binary_mode_with_seek_cur(fptr)
738
739#else
740/* Unix */
741# define DEFAULT_TEXTMODE 0
742#define NEED_READCONV(fptr) ((fptr)->encs.enc2 != NULL || NEED_NEWLINE_DECORATOR_ON_READ(fptr))
743#define NEED_WRITECONV(fptr) ( \
744 ((fptr)->encs.enc != NULL && (fptr)->encs.enc != rb_ascii8bit_encoding()) || \
745 NEED_NEWLINE_DECORATOR_ON_WRITE(fptr) || \
746 ((fptr)->encs.ecflags & (ECONV_DECORATOR_MASK|ECONV_STATEFUL_DECORATOR_MASK)) || \
747 0)
748#define SET_BINARY_MODE(fptr) (void)(fptr)
749#define NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr) (void)(fptr)
750#define SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags) ((void)(enc2), (void)(ecflags))
751#define SET_BINARY_MODE_WITH_SEEK_CUR(fptr) (void)(fptr)
752#endif
753
754#if !defined HAVE_SHUTDOWN && !defined shutdown
755#define shutdown(a,b) 0
756#endif
757
758#if defined(_WIN32)
759#define is_socket(fd, path) rb_w32_is_socket(fd)
760#elif !defined(S_ISSOCK)
761#define is_socket(fd, path) 0
762#else
763static int
764is_socket(int fd, VALUE path)
765{
766 struct stat sbuf;
767 if (fstat(fd, &sbuf) < 0)
768 rb_sys_fail_path(path);
769 return S_ISSOCK(sbuf.st_mode);
770}
771#endif
772
773static const char closed_stream[] = "closed stream";
774
775static void
776io_fd_check_closed(int fd)
777{
778 if (fd < 0) {
779 rb_thread_check_ints(); /* check for ruby_error_stream_closed */
780 rb_raise(rb_eIOError, closed_stream);
781 }
782}
783
784void
786{
787 rb_raise(rb_eEOFError, "end of file reached");
788}
789
790VALUE
792{
793 rb_check_frozen(io);
794 return io;
795}
796
797void
799{
800 if (!fptr) {
801 rb_raise(rb_eIOError, "uninitialized stream");
802 }
803}
804
805void
806rb_io_check_closed(rb_io_t *fptr)
807{
809 io_fd_check_closed(fptr->fd);
810}
811
812static rb_io_t *
813rb_io_get_fptr(VALUE io)
814{
815 rb_io_t *fptr = RFILE(io)->fptr;
817 return fptr;
818}
819
820VALUE
822{
823 return rb_convert_type_with_id(io, T_FILE, "IO", idTo_io);
824}
825
826VALUE
828{
829 return rb_check_convert_type_with_id(io, T_FILE, "IO", idTo_io);
830}
831
832VALUE
834{
835 VALUE write_io;
836 write_io = rb_io_get_fptr(io)->tied_io_for_writing;
837 if (write_io) {
838 return write_io;
839 }
840 return io;
841}
842
843VALUE
845{
846 VALUE write_io;
847 rb_io_t *fptr = rb_io_get_fptr(io);
848 if (!RTEST(w)) {
849 w = 0;
850 }
851 else {
852 GetWriteIO(w);
853 }
854 write_io = fptr->tied_io_for_writing;
855 fptr->tied_io_for_writing = w;
856 return write_io ? write_io : Qnil;
857}
858
859/*
860 * call-seq:
861 * timeout -> duration or nil
862 *
863 * Get the internal timeout duration or nil if it was not set.
864 *
865 */
866VALUE
868{
869 rb_io_t *fptr = rb_io_get_fptr(self);
870
871 return fptr->timeout;
872}
873
874/*
875 * call-seq:
876 * timeout = duration -> duration
877 * timeout = nil -> nil
878 *
879 * Sets the internal timeout to the specified duration or nil. The timeout
880 * applies to all blocking operations where possible.
881 *
882 * When the operation performs longer than the timeout set, IO::TimeoutError
883 * is raised.
884 *
885 * This affects the following methods (but is not limited to): #gets, #puts,
886 * #read, #write, #wait_readable and #wait_writable. This also affects
887 * blocking socket operations like Socket#accept and Socket#connect.
888 *
889 * Some operations like File#open and IO#close are not affected by the
890 * timeout. A timeout during a write operation may leave the IO in an
891 * inconsistent state, e.g. data was partially written. Generally speaking, a
892 * timeout is a last ditch effort to prevent an application from hanging on
893 * slow I/O operations, such as those that occur during a slowloris attack.
894 */
895VALUE
897{
898 // Validate it:
899 if (RTEST(timeout)) {
900 rb_time_interval(timeout);
901 }
902
903 rb_io_t *fptr = rb_io_get_fptr(self);
904
905 RB_OBJ_WRITE(self, &fptr->timeout, timeout);
906
907 return self;
908}
909
910/*
911 * call-seq:
912 * IO.try_convert(object) -> new_io or nil
913 *
914 * Attempts to convert +object+ into an \IO object via method +to_io+;
915 * returns the new \IO object if successful, or +nil+ otherwise:
916 *
917 * IO.try_convert(STDOUT) # => #<IO:<STDOUT>>
918 * IO.try_convert(ARGF) # => #<IO:<STDIN>>
919 * IO.try_convert('STDOUT') # => nil
920 *
921 */
922static VALUE
923rb_io_s_try_convert(VALUE dummy, VALUE io)
924{
925 return rb_io_check_io(io);
926}
927
928#if !RUBY_CRLF_ENVIRONMENT
929static void
930io_unread(rb_io_t *fptr, bool discard_rbuf)
931{
932 rb_off_t r;
933 rb_io_check_closed(fptr);
934 if (fptr->rbuf.len == 0 || fptr->mode & FMODE_DUPLEX)
935 return;
936 /* xxx: target position may be negative if buffer is filled by ungetc */
937 errno = 0;
938 r = lseek(fptr->fd, -fptr->rbuf.len, SEEK_CUR);
939 if (r < 0 && errno) {
940 if (errno == ESPIPE)
941 fptr->mode |= FMODE_DUPLEX;
942 if (!discard_rbuf) return;
943 }
944 fptr->rbuf.off = 0;
945 fptr->rbuf.len = 0;
946 clear_codeconv(fptr);
947 return;
948}
949#endif
950
951static rb_encoding *io_input_encoding(rb_io_t *fptr);
952
953static void
954io_ungetbyte(VALUE str, rb_io_t *fptr)
955{
956 rb_len_t len = RSTRING_LEN(str);
957
958 if (fptr->rbuf.ptr == NULL) {
959 const int min_capa = IO_RBUF_CAPA_FOR(fptr);
960 fptr->rbuf.off = 0;
961 fptr->rbuf.len = 0;
962#if SIZEOF_RB_LEN_T > SIZEOF_INT
963 if (len > INT_MAX)
964 rb_raise(rb_eIOError, "ungetbyte failed");
965#endif
966 if (len > min_capa)
967 fptr->rbuf.capa = (int)len;
968 else
969 fptr->rbuf.capa = min_capa;
970 fptr->rbuf.ptr = ALLOC_N(char, fptr->rbuf.capa);
971 }
972 if (fptr->rbuf.capa < len + fptr->rbuf.len) {
973 rb_raise(rb_eIOError, "ungetbyte failed");
974 }
975 if (fptr->rbuf.off < len) {
976 MEMMOVE(fptr->rbuf.ptr+fptr->rbuf.capa-fptr->rbuf.len,
977 fptr->rbuf.ptr+fptr->rbuf.off,
978 char, fptr->rbuf.len);
979 fptr->rbuf.off = fptr->rbuf.capa-fptr->rbuf.len;
980 }
981 fptr->rbuf.off-=(int)len;
982 fptr->rbuf.len+=(int)len;
983 MEMMOVE(fptr->rbuf.ptr+fptr->rbuf.off, RSTRING_PTR(str), char, len);
984}
985
986static void
987io_restore_read_buffer(VALUE str, rb_io_t *fptr)
988{
989 rb_len_t len = RSTRING_LEN(str);
990
991 if (len > INT_MAX - fptr->rbuf.len) {
992 rb_raise(rb_eIOError, "read buffer too large");
993 }
994 if (fptr->rbuf.ptr == NULL || fptr->rbuf.capa >= len + fptr->rbuf.len) {
995 io_ungetbyte(str, fptr);
996 }
997 else {
998 int pending = fptr->rbuf.len;
999 int capa = (int)len + pending;
1000 char *ptr = ALLOC_N(char, capa);
1001
1002 MEMMOVE(ptr, RSTRING_PTR(str), char, len);
1003 MEMMOVE(ptr + len, fptr->rbuf.ptr + fptr->rbuf.off, char, pending);
1004 ruby_xfree(fptr->rbuf.ptr);
1005 fptr->rbuf.ptr = ptr;
1006 fptr->rbuf.off = 0;
1007 fptr->rbuf.len = capa;
1008 fptr->rbuf.capa = capa;
1009 }
1010}
1011
1012static rb_io_t *
1013flush_before_seek(rb_io_t *fptr, bool discard_rbuf)
1014{
1015 if (io_fflush(fptr) < 0)
1016 rb_sys_fail_on_write(fptr);
1017 io_unread(fptr, discard_rbuf);
1018 errno = 0;
1019 return fptr;
1020}
1021
1022#define io_seek(fptr, ofs, whence) (errno = 0, lseek(flush_before_seek(fptr, true)->fd, (ofs), (whence)))
1023#define io_tell(fptr) lseek(flush_before_seek(fptr, false)->fd, 0, SEEK_CUR)
1024
1025#ifndef SEEK_CUR
1026# define SEEK_SET 0
1027# define SEEK_CUR 1
1028# define SEEK_END 2
1029#endif
1030
1031void
1033{
1034 rb_io_check_closed(fptr);
1035 if (!(fptr->mode & FMODE_READABLE)) {
1036 rb_raise(rb_eIOError, "not opened for reading");
1037 }
1038 if (fptr->wbuf.len) {
1039 if (io_fflush(fptr) < 0)
1040 rb_sys_fail_on_write(fptr);
1041 }
1042 if (fptr->tied_io_for_writing) {
1043 rb_io_t *wfptr;
1044 GetOpenFile(fptr->tied_io_for_writing, wfptr);
1045 if (io_fflush(wfptr) < 0)
1046 rb_sys_fail_on_write(wfptr);
1047 }
1048}
1049
1050void
1052{
1054 if (READ_CHAR_PENDING(fptr)) {
1055 rb_raise(rb_eIOError, "byte oriented read for character buffered IO");
1056 }
1057}
1058
1059void
1061{
1063}
1064
1065static rb_encoding*
1066io_read_encoding(rb_io_t *fptr)
1067{
1068 if (fptr->encs.enc) {
1069 return fptr->encs.enc;
1070 }
1072}
1073
1074static rb_encoding*
1075io_input_encoding(rb_io_t *fptr)
1076{
1077 if (fptr->encs.enc2) {
1078 return fptr->encs.enc2;
1079 }
1080 return io_read_encoding(fptr);
1081}
1082
1083void
1085{
1086 rb_io_check_closed(fptr);
1087 if (!(fptr->mode & FMODE_WRITABLE)) {
1088 rb_raise(rb_eIOError, "not opened for writing");
1089 }
1090 if (fptr->rbuf.len) {
1091 io_unread(fptr, true);
1092 }
1093}
1094
1095int
1097{
1098 /* This function is used for bytes and chars. Confusing. */
1099 if (READ_CHAR_PENDING(fptr))
1100 return 1; /* should raise? */
1101 return READ_DATA_PENDING(fptr);
1102}
1103
1104void
1105rb_io_read_check(rb_io_t *fptr)
1106{
1107 if (!READ_DATA_PENDING(fptr)) {
1108 rb_io_wait(fptr->self, RB_INT2NUM(RUBY_IO_READABLE), RUBY_IO_TIMEOUT_DEFAULT);
1109 }
1110 return;
1111}
1112
1113int
1114rb_gc_for_fd(int err)
1115{
1116 if (err == EMFILE || err == ENFILE || err == ENOMEM) {
1117 rb_gc();
1118 return 1;
1119 }
1120 return 0;
1121}
1122
1123/* try `expr` upto twice while it returns false and `errno`
1124 * is to GC. Each `errno`s are available as `first_errno` and
1125 * `retried_errno` respectively */
1126#define TRY_WITH_GC(expr) \
1127 for (int first_errno, retried_errno = 0, retried = 0; \
1128 (!retried && \
1129 !(expr) && \
1130 (!rb_gc_for_fd(first_errno = errno) || !(expr)) && \
1131 (retried_errno = errno, 1)); \
1132 (void)retried_errno, retried = 1)
1133
1134static int
1135ruby_dup(int orig)
1136{
1137 int fd = -1;
1138
1139 TRY_WITH_GC((fd = rb_cloexec_dup(orig)) >= 0) {
1140 rb_syserr_fail(first_errno, 0);
1141 }
1142 rb_update_max_fd(fd);
1143 return fd;
1144}
1145
1146static VALUE
1147io_alloc(VALUE klass)
1148{
1149 UNPROTECTED_NEWOBJ_OF(io, struct RFile, klass, T_FILE, sizeof(struct RFile));
1150
1151 io->fptr = 0;
1152
1153 return (VALUE)io;
1154}
1155
1156#ifndef S_ISREG
1157# define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
1158#endif
1159
1161 VALUE th;
1162 rb_io_t *fptr;
1163 int nonblock;
1164 int fd;
1165
1166 void *buf;
1167 size_t capa;
1168 struct timeval *timeout;
1169};
1170
1172 VALUE th;
1173 rb_io_t *fptr;
1174 int nonblock;
1175 int fd;
1176
1177 const void *buf;
1178 size_t capa;
1179 struct timeval *timeout;
1180};
1181
1182#ifdef HAVE_WRITEV
1183struct io_internal_writev_struct {
1184 VALUE th;
1185 rb_io_t *fptr;
1186 int nonblock;
1187 int fd;
1188
1189 int iovcnt;
1190 const struct iovec *iov;
1191 struct timeval *timeout;
1192};
1193#endif
1194
1195static int nogvl_wait_for(VALUE th, rb_io_t *fptr, short events, struct timeval *timeout);
1196
1202static inline int
1203io_internal_wait(VALUE thread, rb_io_t *fptr, int error, int events, struct timeval *timeout)
1204{
1205 if (!timeout && rb_thread_mn_schedulable(thread)) {
1206 RUBY_ASSERT(errno == EWOULDBLOCK || errno == EAGAIN);
1207 return -1;
1208 }
1209
1210 int ready = nogvl_wait_for(thread, fptr, events, timeout);
1211
1212 if (ready > 0) {
1213 return ready;
1214 }
1215 else if (ready == 0) {
1216 errno = ETIMEDOUT;
1217 return -1;
1218 }
1219
1220 // If there was an error BEFORE we started waiting, return it:
1221 if (error) {
1222 errno = error;
1223 return -1;
1224 }
1225 else {
1226 // Otherwise, whatever error was generated by `nogvl_wait_for` is the one we want:
1227 return ready;
1228 }
1229}
1230
1231static VALUE
1232internal_read_func(void *ptr)
1233{
1234 struct io_internal_read_struct *iis = ptr;
1235 ssize_t result;
1236
1237 if (iis->timeout && !iis->nonblock) {
1238 if (io_internal_wait(iis->th, iis->fptr, 0, RB_WAITFD_IN, iis->timeout) == -1) {
1239 return -1;
1240 }
1241 }
1242
1243 retry:
1244 result = read(iis->fd, iis->buf, iis->capa);
1245
1246 if (result < 0 && !iis->nonblock) {
1247 if (io_again_p(errno)) {
1248 if (io_internal_wait(iis->th, iis->fptr, errno, RB_WAITFD_IN, iis->timeout) == -1) {
1249 return -1;
1250 }
1251 else {
1252 goto retry;
1253 }
1254 }
1255 }
1256
1257 return result;
1258}
1259
1260#if defined __APPLE__
1261# define do_write_retry(code) do {result = code;} while (result == -1 && errno == EPROTOTYPE)
1262#else
1263# define do_write_retry(code) result = code
1264#endif
1265
1266static VALUE
1267internal_write_func(void *ptr)
1268{
1269 struct io_internal_write_struct *iis = ptr;
1270 ssize_t result;
1271
1272 if (iis->timeout && !iis->nonblock) {
1273 if (io_internal_wait(iis->th, iis->fptr, 0, RB_WAITFD_OUT, iis->timeout) == -1) {
1274 return -1;
1275 }
1276 }
1277
1278 retry:
1279 do_write_retry(write(iis->fd, iis->buf, iis->capa));
1280
1281 if (result < 0 && !iis->nonblock) {
1282 int e = errno;
1283 if (io_again_p(e)) {
1284 if (io_internal_wait(iis->th, iis->fptr, errno, RB_WAITFD_OUT, iis->timeout) == -1) {
1285 return -1;
1286 }
1287 else {
1288 goto retry;
1289 }
1290 }
1291 }
1292
1293 return result;
1294}
1295
1296#ifdef HAVE_WRITEV
1297static VALUE
1298internal_writev_func(void *ptr)
1299{
1300 struct io_internal_writev_struct *iis = ptr;
1301 ssize_t result;
1302
1303 if (iis->timeout && !iis->nonblock) {
1304 if (io_internal_wait(iis->th, iis->fptr, 0, RB_WAITFD_OUT, iis->timeout) == -1) {
1305 return -1;
1306 }
1307 }
1308
1309 retry:
1310 do_write_retry(writev(iis->fd, iis->iov, iis->iovcnt));
1311
1312 if (result < 0 && !iis->nonblock) {
1313 if (io_again_p(errno)) {
1314 if (io_internal_wait(iis->th, iis->fptr, errno, RB_WAITFD_OUT, iis->timeout) == -1) {
1315 return -1;
1316 }
1317 else {
1318 goto retry;
1319 }
1320 }
1321 }
1322
1323 return result;
1324}
1325#endif
1326
1327static ssize_t
1328rb_io_read_memory(rb_io_t *fptr, void *buf, size_t count)
1329{
1330 rb_thread_t *th = GET_THREAD();
1332 if (scheduler != Qnil) {
1333 VALUE result = rb_fiber_scheduler_io_read_memory(scheduler, fptr->self, buf, count);
1334
1335 if (!UNDEF_P(result)) {
1337 }
1338 }
1339
1340 struct io_internal_read_struct iis = {
1341 .th = th->self,
1342 .fptr = fptr,
1343 .nonblock = 0,
1344 .fd = fptr->fd,
1345
1346 .buf = buf,
1347 .capa = count,
1348 .timeout = NULL,
1349 };
1350
1351 struct timeval timeout_storage;
1352
1353 if (fptr->timeout != Qnil) {
1354 timeout_storage = rb_time_interval(fptr->timeout);
1355 iis.timeout = &timeout_storage;
1356 }
1357
1358 return (ssize_t)rb_io_blocking_region_wait(fptr, internal_read_func, &iis, RUBY_IO_READABLE);
1359}
1360
1361static ssize_t
1362rb_io_write_memory(rb_io_t *fptr, const void *buf, size_t count)
1363{
1364 rb_thread_t *th = GET_THREAD();
1366 if (scheduler != Qnil) {
1367 VALUE result = rb_fiber_scheduler_io_write_memory(scheduler, fptr->self, buf, count);
1368
1369 if (!UNDEF_P(result)) {
1371 }
1372 }
1373
1374 struct io_internal_write_struct iis = {
1375 .th = th->self,
1376 .fptr = fptr,
1377 .nonblock = 0,
1378 .fd = fptr->fd,
1379
1380 .buf = buf,
1381 .capa = count,
1382 .timeout = NULL
1383 };
1384
1385 struct timeval timeout_storage;
1386
1387 if (fptr->timeout != Qnil) {
1388 timeout_storage = rb_time_interval(fptr->timeout);
1389 iis.timeout = &timeout_storage;
1390 }
1391
1392 return (ssize_t)rb_io_blocking_region_wait(fptr, internal_write_func, &iis, RUBY_IO_WRITABLE);
1393}
1394
1395#ifdef HAVE_WRITEV
1396static ssize_t
1397rb_writev_internal(rb_io_t *fptr, const struct iovec *iov, int iovcnt)
1398{
1399 if (!iovcnt) return 0;
1400
1401 rb_thread_t *th = GET_THREAD();
1402
1404 if (scheduler != Qnil) {
1405 // This path assumes at least one `iov`:
1406 VALUE result = rb_fiber_scheduler_io_write_memory(scheduler, fptr->self, iov[0].iov_base, iov[0].iov_len);
1407
1408 if (!UNDEF_P(result)) {
1410 }
1411 }
1412
1413 struct io_internal_writev_struct iis = {
1414 .th = th->self,
1415 .fptr = fptr,
1416 .nonblock = 0,
1417 .fd = fptr->fd,
1418
1419 .iov = iov,
1420 .iovcnt = iovcnt,
1421 .timeout = NULL
1422 };
1423
1424 struct timeval timeout_storage;
1425
1426 if (fptr->timeout != Qnil) {
1427 timeout_storage = rb_time_interval(fptr->timeout);
1428 iis.timeout = &timeout_storage;
1429 }
1430
1431 return (ssize_t)rb_io_blocking_region_wait(fptr, internal_writev_func, &iis, RUBY_IO_WRITABLE);
1432}
1433#endif
1434
1435static VALUE
1436io_flush_buffer_sync(void *arg)
1437{
1438 rb_io_t *fptr = arg;
1439 rb_len_t l = fptr->wbuf.len;
1440 ssize_t r = write(fptr->fd, fptr->wbuf.ptr+fptr->wbuf.off, (size_t)l);
1441
1442 if (fptr->wbuf.len <= r) {
1443 fptr->wbuf.off = 0;
1444 fptr->wbuf.len = 0;
1445 return 0;
1446 }
1447
1448 if (0 <= r) {
1449 fptr->wbuf.off += (int)r;
1450 fptr->wbuf.len -= (int)r;
1451 errno = EAGAIN;
1452 }
1453
1454 return (VALUE)-1;
1455}
1456
1457static inline VALUE
1458io_flush_buffer_fiber_scheduler(VALUE scheduler, rb_io_t *fptr)
1459{
1460 VALUE ret = rb_fiber_scheduler_io_write_memory(scheduler, fptr->self, fptr->wbuf.ptr+fptr->wbuf.off, fptr->wbuf.len);
1461 if (!UNDEF_P(ret)) {
1462 ssize_t result = rb_fiber_scheduler_io_result_apply(ret);
1463 if (result > 0) {
1464 fptr->wbuf.off += result;
1465 fptr->wbuf.len -= result;
1466 }
1467 return result >= 0 ? (VALUE)0 : (VALUE)-1;
1468 }
1469 return ret;
1470}
1471
1472static VALUE
1473io_flush_buffer_async(VALUE arg)
1474{
1475 rb_io_t *fptr = (rb_io_t *)arg;
1476
1477 VALUE scheduler = rb_fiber_scheduler_current();
1478 if (scheduler != Qnil) {
1479 VALUE result = io_flush_buffer_fiber_scheduler(scheduler, fptr);
1480 if (!UNDEF_P(result)) {
1481 return result;
1482 }
1483 }
1484
1485 return rb_io_blocking_region_wait(fptr, io_flush_buffer_sync, fptr, RUBY_IO_WRITABLE);
1486}
1487
1488static inline int
1489io_flush_buffer(rb_io_t *fptr)
1490{
1491 if (!NIL_P(fptr->write_lock) && rb_mutex_owned_p(fptr->write_lock)) {
1492 return (int)io_flush_buffer_async((VALUE)fptr);
1493 }
1494 else {
1495 return (int)rb_mutex_synchronize(fptr->write_lock, io_flush_buffer_async, (VALUE)fptr);
1496 }
1497}
1498
1499static int
1500io_fflush(rb_io_t *fptr)
1501{
1502 rb_io_check_closed(fptr);
1503
1504 if (fptr->wbuf.len == 0)
1505 return 0;
1506
1507 while (fptr->wbuf.len > 0 && io_flush_buffer(fptr) != 0) {
1508 if (!rb_io_maybe_wait_writable(errno, fptr->self, RUBY_IO_TIMEOUT_DEFAULT))
1509 return -1;
1510
1511 rb_io_check_closed(fptr);
1512 }
1513
1514 return 0;
1515}
1516
1517VALUE
1518rb_io_wait(VALUE io, VALUE events, VALUE timeout)
1519{
1520 rb_thread_t *th = GET_THREAD();
1522
1523 if (scheduler != Qnil) {
1524 return rb_fiber_scheduler_io_wait(scheduler, io, events, timeout);
1525 }
1526
1527 rb_io_t * fptr = NULL;
1528 RB_IO_POINTER(io, fptr);
1529
1530 struct timeval tv_storage;
1531 struct timeval *tv = NULL;
1532
1533 if (NIL_OR_UNDEF_P(timeout)) {
1534 timeout = fptr->timeout;
1535 }
1536
1537 if (timeout != Qnil) {
1538 tv_storage = rb_time_interval(timeout);
1539 tv = &tv_storage;
1540 }
1541
1542 int ready = rb_thread_io_wait(th, fptr, RB_NUM2INT(events), tv);
1543
1544 if (ready < 0) {
1545 rb_sys_fail(0);
1546 }
1547
1548 // Not sure if this is necessary:
1549 rb_io_check_closed(fptr);
1550
1551 if (ready) {
1552 return RB_INT2NUM(ready);
1553 }
1554 else {
1555 return Qfalse;
1556 }
1557}
1558
1559static VALUE
1560io_from_fd(int fd)
1561{
1562 return prep_io(fd, FMODE_EXTERNAL, rb_cIO, NULL);
1563}
1564
1565static int
1566io_wait_for_single_fd(int fd, int events, struct timeval *timeout, rb_thread_t *th, VALUE scheduler)
1567{
1568 if (scheduler != Qnil) {
1569 return RTEST(
1570 rb_fiber_scheduler_io_wait(scheduler, io_from_fd(fd), RB_INT2NUM(events), rb_fiber_scheduler_make_timeout(timeout))
1571 );
1572 }
1573
1574 return rb_thread_wait_for_single_fd(th, fd, events, timeout);
1575}
1576
1577int
1579{
1580 io_fd_check_closed(f);
1581
1582 rb_thread_t *th = GET_THREAD();
1584
1585 switch (errno) {
1586 case EINTR:
1587#if defined(ERESTART)
1588 case ERESTART:
1589#endif
1591 return TRUE;
1592
1593 case EAGAIN:
1594#if EWOULDBLOCK != EAGAIN
1595 case EWOULDBLOCK:
1596#endif
1597 if (scheduler != Qnil) {
1598 return RTEST(
1599 rb_fiber_scheduler_io_wait_readable(scheduler, io_from_fd(f))
1600 );
1601 }
1602 else {
1603 io_wait_for_single_fd(f, RUBY_IO_READABLE, NULL, th, scheduler);
1604 }
1605 return TRUE;
1606
1607 default:
1608 return FALSE;
1609 }
1610}
1611
1612int
1614{
1615 io_fd_check_closed(f);
1616
1617 rb_thread_t *th = GET_THREAD();
1619
1620 switch (errno) {
1621 case EINTR:
1622#if defined(ERESTART)
1623 case ERESTART:
1624#endif
1625 /*
1626 * In old Linux, several special files under /proc and /sys don't handle
1627 * select properly. Thus we need avoid to call if don't use O_NONBLOCK.
1628 * Otherwise, we face nasty hang up. Sigh.
1629 * e.g. https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=31b07093c44a7a442394d44423e21d783f5523b8
1630 * https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=31b07093c44a7a442394d44423e21d783f5523b8
1631 * In EINTR case, we only need to call RUBY_VM_CHECK_INTS_BLOCKING().
1632 * Then rb_thread_check_ints() is enough.
1633 */
1635 return TRUE;
1636
1637 case EAGAIN:
1638#if EWOULDBLOCK != EAGAIN
1639 case EWOULDBLOCK:
1640#endif
1641 if (scheduler != Qnil) {
1642 return RTEST(
1643 rb_fiber_scheduler_io_wait_writable(scheduler, io_from_fd(f))
1644 );
1645 }
1646 else {
1647 io_wait_for_single_fd(f, RUBY_IO_WRITABLE, NULL, th, scheduler);
1648 }
1649 return TRUE;
1650
1651 default:
1652 return FALSE;
1653 }
1654}
1655
1656int
1657rb_wait_for_single_fd(int fd, int events, struct timeval *timeout)
1658{
1659 rb_thread_t *th = GET_THREAD();
1661 return io_wait_for_single_fd(fd, events, timeout, th, scheduler);
1662}
1663
1664int
1666{
1667 return rb_wait_for_single_fd(fd, RUBY_IO_READABLE, NULL);
1668}
1669
1670int
1672{
1673 return rb_wait_for_single_fd(fd, RUBY_IO_WRITABLE, NULL);
1674}
1675
1676VALUE
1677rb_io_maybe_wait(int error, VALUE io, VALUE events, VALUE timeout)
1678{
1679 // fptr->fd can be set to -1 at any time by another thread when the GVL is
1680 // released. Many code, e.g. `io_bufread` didn't check this correctly and
1681 // instead relies on `read(-1) -> -1` which causes this code path. We then
1682 // check here whether the IO was in fact closed. Probably it's better to
1683 // check that `fptr->fd != -1` before using it in syscall.
1684 rb_io_check_closed(RFILE(io)->fptr);
1685
1686 switch (error) {
1687 // In old Linux, several special files under /proc and /sys don't handle
1688 // select properly. Thus we need avoid to call if don't use O_NONBLOCK.
1689 // Otherwise, we face nasty hang up. Sigh.
1690 // e.g. https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=31b07093c44a7a442394d44423e21d783f5523b8
1691 // https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=31b07093c44a7a442394d44423e21d783f5523b8
1692 // In EINTR case, we only need to call RUBY_VM_CHECK_INTS_BLOCKING().
1693 // Then rb_thread_check_ints() is enough.
1694 case EINTR:
1695#if defined(ERESTART)
1696 case ERESTART:
1697#endif
1698 // We might have pending interrupts since the previous syscall was interrupted:
1700
1701 // The operation was interrupted, so retry it immediately:
1702 return events;
1703
1704 case EAGAIN:
1705#if EWOULDBLOCK != EAGAIN
1706 case EWOULDBLOCK:
1707#endif
1708 {
1709 // The operation would block, so wait for the specified events:
1710 VALUE result = rb_io_wait(io, events, timeout);
1711 // The scheduler may change errno while waiting. Preserve the original
1712 // error in case no events are ready and the caller reports the failure.
1713 errno = error;
1714 return result;
1715 }
1716
1717 default:
1718 // Non-specific error, no event is ready:
1719 return Qnil;
1720 }
1721}
1722
1723int
1725{
1726 VALUE result = rb_io_maybe_wait(error, io, RB_INT2NUM(RUBY_IO_READABLE), timeout);
1727
1728 if (RTEST(result)) {
1729 return RB_NUM2INT(result);
1730 }
1731 else if (result == RUBY_Qfalse) {
1732 rb_raise(rb_eIOTimeoutError, "Timed out waiting for IO to become readable!");
1733 }
1734
1735 return 0;
1736}
1737
1738int
1740{
1741 VALUE result = rb_io_maybe_wait(error, io, RB_INT2NUM(RUBY_IO_WRITABLE), timeout);
1742
1743 if (RTEST(result)) {
1744 return RB_NUM2INT(result);
1745 }
1746 else if (result == RUBY_Qfalse) {
1747 rb_raise(rb_eIOTimeoutError, "Timed out waiting for IO to become writable!");
1748 }
1749
1750 return 0;
1751}
1752
1753static void
1754make_writeconv(rb_io_t *fptr)
1755{
1756 if (!fptr->writeconv_initialized) {
1757 const char *senc, *denc;
1758 rb_encoding *enc;
1759 int ecflags;
1760 VALUE ecopts;
1761
1762 fptr->writeconv_initialized = 1;
1763
1765 ecopts = fptr->encs.ecopts;
1766
1767 if (!fptr->encs.enc || (rb_is_ascii8bit_enc(fptr->encs.enc) && !fptr->encs.enc2)) {
1768 /* no encoding conversion */
1769 fptr->writeconv_pre_ecflags = 0;
1770 fptr->writeconv_pre_ecopts = Qnil;
1771 fptr->writeconv = rb_econv_open_opts("", "", ecflags, ecopts);
1772 if (!fptr->writeconv)
1773 rb_exc_raise(rb_econv_open_exc("", "", ecflags));
1775 }
1776 else {
1777 enc = fptr->encs.enc2 ? fptr->encs.enc2 : fptr->encs.enc;
1778 senc = rb_econv_asciicompat_encoding(rb_enc_name(enc));
1779 if (!senc && !(fptr->encs.ecflags & ECONV_STATEFUL_DECORATOR_MASK)) {
1780 /* single conversion */
1781 fptr->writeconv_pre_ecflags = ecflags;
1782 fptr->writeconv_pre_ecopts = ecopts;
1783 fptr->writeconv = NULL;
1785 }
1786 else {
1787 /* double conversion */
1789 fptr->writeconv_pre_ecopts = ecopts;
1790 if (senc) {
1791 denc = rb_enc_name(enc);
1792 fptr->writeconv_asciicompat = rb_str_new2(senc);
1793 }
1794 else {
1795 senc = denc = "";
1796 fptr->writeconv_asciicompat = rb_str_new2(rb_enc_name(enc));
1797 }
1799 ecopts = fptr->encs.ecopts;
1800 fptr->writeconv = rb_econv_open_opts(senc, denc, ecflags, ecopts);
1801 if (!fptr->writeconv)
1802 rb_exc_raise(rb_econv_open_exc(senc, denc, ecflags));
1803 }
1804 }
1805 }
1806}
1807
1808/* writing functions */
1810 rb_io_t *fptr;
1811 const char *ptr;
1812 rb_len_t length;
1813};
1814
1816 VALUE io;
1817 VALUE str;
1818 int nosync;
1819};
1820
1821#ifdef HAVE_WRITEV
1822static ssize_t
1823io_binwrite_string_internal(rb_io_t *fptr, const char *ptr, rb_len_t length)
1824{
1825 if (fptr->wbuf.len) {
1826 struct iovec iov[2];
1827
1828 iov[0].iov_base = fptr->wbuf.ptr+fptr->wbuf.off;
1829 iov[0].iov_len = fptr->wbuf.len;
1830 iov[1].iov_base = (void*)ptr;
1831 iov[1].iov_len = length;
1832
1833 ssize_t result = rb_writev_internal(fptr, iov, 2);
1834
1835 if (result < 0)
1836 return result;
1837
1838 if (result >= fptr->wbuf.len) {
1839 // We wrote more than the internal buffer:
1840 result -= fptr->wbuf.len;
1841 fptr->wbuf.off = 0;
1842 fptr->wbuf.len = 0;
1843 }
1844 else {
1845 // We only wrote less data than the internal buffer:
1846 fptr->wbuf.off += (int)result;
1847 fptr->wbuf.len -= (int)result;
1848
1849 result = 0;
1850 }
1851
1852 return result;
1853 }
1854 else {
1855 return rb_io_write_memory(fptr, ptr, length);
1856 }
1857}
1858#else
1859static ssize_t
1860io_binwrite_string_internal(rb_io_t *fptr, const char *ptr, rb_len_t length)
1861{
1862 rb_len_t remaining = length;
1863
1864 if (fptr->wbuf.len) {
1865 if (fptr->wbuf.len+length <= fptr->wbuf.capa) {
1866 if (fptr->wbuf.capa < fptr->wbuf.off+fptr->wbuf.len+length) {
1867 MEMMOVE(fptr->wbuf.ptr, fptr->wbuf.ptr+fptr->wbuf.off, char, fptr->wbuf.len);
1868 fptr->wbuf.off = 0;
1869 }
1870
1871 MEMMOVE(fptr->wbuf.ptr+fptr->wbuf.off+fptr->wbuf.len, ptr, char, length);
1872 fptr->wbuf.len += (int)length;
1873
1874 // We copied the entire incoming data to the internal buffer:
1875 remaining = 0;
1876 }
1877
1878 // Flush the internal buffer:
1879 if (io_fflush(fptr) < 0) {
1880 return -1;
1881 }
1882
1883 // If all the data was buffered, we are done:
1884 if (remaining == 0) {
1885 return length;
1886 }
1887 }
1888
1889 // Otherwise, we should write the data directly:
1890 return rb_io_write_memory(fptr, ptr, length);
1891}
1892#endif
1893
1894static VALUE
1895io_binwrite_string(VALUE arg)
1896{
1897 struct binwrite_arg *p = (struct binwrite_arg *)arg;
1898
1899 const char *ptr = p->ptr;
1900 size_t remaining = p->length;
1901
1902 while (remaining) {
1903 // Write as much as possible:
1904 ssize_t result = io_binwrite_string_internal(p->fptr, ptr, remaining);
1905
1906 if (result == 0) {
1907 // If only the internal buffer is written, result will be zero [bytes of given data written]. This means we
1908 // should try again immediately.
1909 }
1910 else if (result > 0) {
1911 if ((size_t)result == remaining) break;
1912 ptr += result;
1913 remaining -= result;
1914 }
1915 // Wait for it to become writable:
1916 else if (rb_io_maybe_wait_writable(errno, p->fptr->self, RUBY_IO_TIMEOUT_DEFAULT)) {
1917 rb_io_check_closed(p->fptr);
1918 }
1919 else {
1920 // The error was unrelated to waiting for it to become writable, so we fail:
1921 return -1;
1922 }
1923 }
1924
1925 return p->length;
1926}
1927
1928inline static void
1929io_allocate_write_buffer(rb_io_t *fptr, int sync)
1930{
1931 if (fptr->wbuf.ptr == NULL && !(sync && (fptr->mode & FMODE_SYNC))) {
1932 fptr->wbuf.off = 0;
1933 fptr->wbuf.len = 0;
1934 fptr->wbuf.capa = IO_WBUF_CAPA_MIN;
1935 fptr->wbuf.ptr = ALLOC_N(char, fptr->wbuf.capa);
1936 }
1937
1938 if (NIL_P(fptr->write_lock)) {
1939 fptr->write_lock = rb_mutex_new();
1940 rb_mutex_allow_trap(fptr->write_lock, 1);
1941 }
1942}
1943
1944static inline int
1945io_binwrite_requires_flush_write(rb_io_t *fptr, rb_len_t len, int nosync)
1946{
1947 // If the requested operation was synchronous and the output mode is synchronous or a TTY:
1948 if (!nosync && (fptr->mode & (FMODE_SYNC|FMODE_TTY)))
1949 return 1;
1950
1951 // If the amount of data we want to write exceeds the internal buffer:
1952 if (fptr->wbuf.ptr && fptr->wbuf.capa <= fptr->wbuf.len + len)
1953 return 1;
1954
1955 // Otherwise, we can append to the internal buffer:
1956 return 0;
1957}
1958
1959static rb_len_t
1960io_binwrite(const char *ptr, rb_len_t len, rb_io_t *fptr, int nosync)
1961{
1962 if (len <= 0) return len;
1963
1964 // Don't write anything if current thread has a pending interrupt:
1966
1967 io_allocate_write_buffer(fptr, !nosync);
1968
1969 if (io_binwrite_requires_flush_write(fptr, len, nosync)) {
1970 struct binwrite_arg arg;
1971
1972 arg.fptr = fptr;
1973 arg.ptr = ptr;
1974 arg.length = len;
1975
1976 if (!NIL_P(fptr->write_lock)) {
1977 return rb_mutex_synchronize(fptr->write_lock, io_binwrite_string, (VALUE)&arg);
1978 }
1979 else {
1980 return io_binwrite_string((VALUE)&arg);
1981 }
1982 }
1983 else {
1984 if (fptr->wbuf.off) {
1985 if (fptr->wbuf.len)
1986 MEMMOVE(fptr->wbuf.ptr, fptr->wbuf.ptr+fptr->wbuf.off, char, fptr->wbuf.len);
1987 fptr->wbuf.off = 0;
1988 }
1989
1990 MEMMOVE(fptr->wbuf.ptr+fptr->wbuf.off+fptr->wbuf.len, ptr, char, len);
1991 fptr->wbuf.len += (int)len;
1992
1993 return len;
1994 }
1995}
1996
1997# define MODE_BTMODE(a,b,c) ((fmode & FMODE_BINMODE) ? (b) : \
1998 (fmode & FMODE_TEXTMODE) ? (c) : (a))
1999
2000#define MODE_BTXMODE(a, b, c, d, e, f) ((fmode & FMODE_EXCL) ? \
2001 MODE_BTMODE(d, e, f) : \
2002 MODE_BTMODE(a, b, c))
2003
2004static VALUE
2005do_writeconv(VALUE str, rb_io_t *fptr, int *converted)
2006{
2007 if (NEED_WRITECONV(fptr)) {
2008 VALUE common_encoding = Qnil;
2009 SET_BINARY_MODE(fptr);
2010
2011 make_writeconv(fptr);
2012
2013 if (fptr->writeconv) {
2014#define fmode (fptr->mode)
2015 if (!NIL_P(fptr->writeconv_asciicompat))
2016 common_encoding = fptr->writeconv_asciicompat;
2017 else if (MODE_BTMODE(DEFAULT_TEXTMODE,0,1) && !rb_enc_asciicompat(rb_enc_get(str))) {
2018 rb_raise(rb_eArgError, "ASCII incompatible string written for text mode IO without encoding conversion: %s",
2019 rb_enc_name(rb_enc_get(str)));
2020 }
2021#undef fmode
2022 }
2023 else {
2024 if (fptr->encs.enc2)
2025 common_encoding = rb_enc_from_encoding(fptr->encs.enc2);
2026 else if (fptr->encs.enc != rb_ascii8bit_encoding())
2027 common_encoding = rb_enc_from_encoding(fptr->encs.enc);
2028 }
2029
2030 if (!NIL_P(common_encoding)) {
2031 str = rb_str_encode(str, common_encoding,
2033 *converted = 1;
2034 }
2035
2036 if (fptr->writeconv) {
2038 *converted = 1;
2039 }
2040 }
2041#if RUBY_CRLF_ENVIRONMENT
2042#define fmode (fptr->mode)
2043 else if (MODE_BTMODE(DEFAULT_TEXTMODE,0,1)) {
2044 if ((fptr->mode & FMODE_READABLE) &&
2046 setmode(fptr->fd, O_BINARY);
2047 }
2048 else {
2049 setmode(fptr->fd, O_TEXT);
2050 }
2051 if (!rb_enc_asciicompat(rb_enc_get(str))) {
2052 rb_raise(rb_eArgError, "ASCII incompatible string written for text mode IO without encoding conversion: %s",
2053 rb_enc_name(rb_enc_get(str)));
2054 }
2055 }
2056#undef fmode
2057#endif
2058 return str;
2059}
2060
2061static rb_len_t
2062io_fwrite(VALUE str, rb_io_t *fptr, int nosync)
2063{
2064 int converted = 0;
2065 VALUE tmp;
2066 rb_len_t n, len;
2067 const char *ptr;
2068
2069#ifdef _WIN32
2070 if (fptr->mode & FMODE_TTY) {
2071 if (rb_w32_write_console(str, fptr->fd) > 0) return RSTRING_LEN(str);
2072 }
2073#endif
2074
2075 str = do_writeconv(str, fptr, &converted);
2076 if (converted)
2077 OBJ_FREEZE(str);
2078
2079 tmp = rb_str_no_gvl_safe_acquire(str);
2080 RSTRING_GETMEM(tmp, ptr, len);
2081 n = io_binwrite(ptr, len, fptr, nosync);
2083
2084 return n;
2085}
2086
2087ssize_t
2088rb_io_bufwrite(VALUE io, const void *buf, size_t size)
2089{
2090 rb_io_t *fptr;
2091
2092 GetOpenFile(io, fptr);
2094 return (ssize_t)io_binwrite(buf, (rb_len_t)size, fptr, 0);
2095}
2096
2097static VALUE
2098io_write(VALUE io, VALUE str, int nosync)
2099{
2100 rb_io_t *fptr;
2101 rb_len_t n;
2102 VALUE tmp;
2103
2104 io = GetWriteIO(io);
2105 str = rb_obj_as_string(str);
2106 tmp = rb_io_check_io(io);
2107
2108 if (NIL_P(tmp)) {
2109 /* port is not IO, call write method for it. */
2110 return rb_funcall(io, id_write, 1, str);
2111 }
2112
2113 io = tmp;
2114 if (RSTRING_LEN(str) == 0) return INT2FIX(0);
2115
2116 GetOpenFile(io, fptr);
2118
2119 n = io_fwrite(str, fptr, nosync);
2120 if (n < 0L) rb_sys_fail_on_write(fptr);
2121
2122 return LEN2NUM(n);
2123}
2124
2125#ifdef HAVE_WRITEV
2126struct binwritev_arg {
2127 rb_io_t *fptr;
2128 struct iovec *iov;
2129 int iovcnt;
2130 size_t total;
2131};
2132
2133static VALUE
2134io_binwritev_internal(VALUE arg)
2135{
2136 struct binwritev_arg *p = (struct binwritev_arg *)arg;
2137
2138 size_t remaining = p->total;
2139 size_t offset = 0;
2140
2141 rb_io_t *fptr = p->fptr;
2142 struct iovec *iov = p->iov;
2143 int iovcnt = p->iovcnt;
2144
2145 while (remaining) {
2146 rb_len_t result = rb_writev_internal(fptr, iov, iovcnt);
2147
2148 if (result >= 0) {
2149 offset += result;
2150 if (fptr->wbuf.ptr && fptr->wbuf.len) {
2151 if (offset < (size_t)fptr->wbuf.len) {
2152 fptr->wbuf.off += result;
2153 fptr->wbuf.len -= result;
2154 }
2155 else {
2156 offset -= (size_t)fptr->wbuf.len;
2157 fptr->wbuf.off = 0;
2158 fptr->wbuf.len = 0;
2159 }
2160 }
2161
2162 if (offset == p->total) {
2163 return p->total;
2164 }
2165
2166 while (result >= (ssize_t)iov->iov_len) {
2167 /* iovcnt > 0 */
2168 result -= iov->iov_len;
2169 iov->iov_len = 0;
2170 iov++;
2171
2172 if (!--iovcnt) {
2173 // I don't believe this code path can ever occur.
2174 return offset;
2175 }
2176 }
2177
2178 iov->iov_base = (char *)iov->iov_base + result;
2179 iov->iov_len -= result;
2180 }
2181 else if (rb_io_maybe_wait_writable(errno, fptr->self, RUBY_IO_TIMEOUT_DEFAULT)) {
2182 rb_io_check_closed(fptr);
2183 }
2184 else {
2185 return -1;
2186 }
2187 }
2188
2189 return offset;
2190}
2191
2192static rb_len_t
2193io_binwritev(struct iovec *iov, int iovcnt, rb_io_t *fptr)
2194{
2195 // Don't write anything if current thread has a pending interrupt:
2197
2198 if (iovcnt == 0) return 0;
2199
2200 size_t total = 0;
2201 for (int i = 1; i < iovcnt; i++) total += iov[i].iov_len;
2202
2203 io_allocate_write_buffer(fptr, 1);
2204
2205 if (fptr->wbuf.ptr && fptr->wbuf.len) {
2206 // The end of the buffered data:
2207 size_t offset = fptr->wbuf.off + fptr->wbuf.len;
2208
2209 if (offset + total <= (size_t)fptr->wbuf.capa) {
2210 for (int i = 1; i < iovcnt; i++) {
2211 memcpy(fptr->wbuf.ptr+offset, iov[i].iov_base, iov[i].iov_len);
2212 offset += iov[i].iov_len;
2213 }
2214
2215 fptr->wbuf.len += total;
2216
2217 /* io_binwritev is only reached in sync/TTY mode (it is called only
2218 * from io_fwritev, which io_writev uses only when FMODE_SYNC or
2219 * FMODE_TTY is set), so the coalesced data must be flushed
2220 * immediately rather than left in the buffer until the next flush
2221 * or close. Otherwise a multi-argument write with many arguments
2222 * would not be observably atomic under sync. */
2223 if (io_fflush(fptr) < 0) return -1;
2224
2225 return total;
2226 }
2227 else {
2228 iov[0].iov_base = fptr->wbuf.ptr + fptr->wbuf.off;
2229 iov[0].iov_len = fptr->wbuf.len;
2230 }
2231 }
2232 else {
2233 // The first iov is reserved for the internal buffer, and it's empty.
2234 iov++;
2235
2236 if (!--iovcnt) {
2237 // If there are no other io vectors we are done.
2238 return 0;
2239 }
2240 }
2241
2242 struct binwritev_arg arg;
2243 arg.fptr = fptr;
2244 arg.iov = iov;
2245 arg.iovcnt = iovcnt;
2246 arg.total = total;
2247
2248 if (!NIL_P(fptr->write_lock)) {
2249 return rb_mutex_synchronize(fptr->write_lock, io_binwritev_internal, (VALUE)&arg);
2250 }
2251 else {
2252 return io_binwritev_internal((VALUE)&arg);
2253 }
2254}
2255
2256static rb_len_t
2257io_fwritev(int argc, const VALUE *argv, rb_io_t *fptr)
2258{
2259 int i, converted, iovcnt = argc + 1;
2260 rb_len_t n;
2261 VALUE v1, v2, str, tmp, *tmp_array;
2262 struct iovec *iov;
2263
2264 iov = ALLOCV_N(struct iovec, v1, iovcnt);
2265 tmp_array = ALLOCV_N(VALUE, v2, argc);
2266
2267 for (i = 0; i < argc; i++) {
2268 str = rb_obj_as_string(argv[i]);
2269 converted = 0;
2270 str = do_writeconv(str, fptr, &converted);
2271
2272 if (converted)
2273 OBJ_FREEZE(str);
2274
2275 tmp = rb_str_tmp_frozen_acquire(str);
2276 tmp_array[i] = tmp;
2277
2278 /* iov[0] is reserved for buffer of fptr */
2279 iov[i+1].iov_base = RSTRING_PTR(tmp);
2280 iov[i+1].iov_len = RSTRING_LEN(tmp);
2281 }
2282
2283 n = io_binwritev(iov, iovcnt, fptr);
2284 if (v1) ALLOCV_END(v1);
2285
2286 for (i = 0; i < argc; i++) {
2287 rb_str_tmp_frozen_release(argv[i], tmp_array[i]);
2288 }
2289
2290 if (v2) ALLOCV_END(v2);
2291
2292 return n;
2293}
2294
2295static int
2296iovcnt_ok(int iovcnt)
2297{
2298#ifdef IOV_MAX
2299 return iovcnt < IOV_MAX;
2300#else /* GNU/Hurd has writev, but no IOV_MAX */
2301 return 1;
2302#endif
2303}
2304#endif /* HAVE_WRITEV */
2305
2306static VALUE
2307io_writev(int argc, const VALUE *argv, VALUE io)
2308{
2309 rb_io_t *fptr;
2310 rb_len_t n;
2311 VALUE tmp, total = INT2FIX(0);
2312 int i, cnt = 1;
2313
2314 io = GetWriteIO(io);
2315 tmp = rb_io_check_io(io);
2316
2317 if (NIL_P(tmp)) {
2318 /* port is not IO, call write method for it. */
2319 return rb_funcallv(io, id_write, argc, argv);
2320 }
2321
2322 io = tmp;
2323
2324 GetOpenFile(io, fptr);
2326
2327 for (i = 0; i < argc; i += cnt) {
2328#ifdef HAVE_WRITEV
2329 if ((fptr->mode & (FMODE_SYNC|FMODE_TTY)) && iovcnt_ok(cnt = argc - i)) {
2330 n = io_fwritev(cnt, &argv[i], fptr);
2331 }
2332 else
2333#endif
2334 {
2335 cnt = 1;
2336 /* sync at last item */
2337 n = io_fwrite(rb_obj_as_string(argv[i]), fptr, (i < argc-1));
2338 }
2339
2340 if (n < 0L)
2341 rb_sys_fail_on_write(fptr);
2342
2343 total = rb_int_plus(LEN2NUM(n), total);
2344 }
2345
2346 return total;
2347}
2348
2349/*
2350 * call-seq:
2351 * write(*objects) -> integer
2352 *
2353 * Writes each of the given +objects+ to +self+,
2354 * which must be opened for writing
2355 * (see {Access Modes}[rdoc-ref:File@Access+Modes]);
2356 * returns the total number bytes written;
2357 * each of +objects+ that is not a string is converted via method +to_s+:
2358 *
2359 * $stdout.write('Hello', ', ', 'World!', "\n") # => 14
2360 * $stdout.write('foo', :bar, 2, "\n") # => 8
2361 *
2362 * Output:
2363 *
2364 * Hello, World!
2365 * foobar2
2366 *
2367 * Related: IO#read.
2368 */
2369
2370static VALUE
2371io_write_m(int argc, VALUE *argv, VALUE io)
2372{
2373 if (argc != 1) {
2374 return io_writev(argc, argv, io);
2375 }
2376 else {
2377 VALUE str = argv[0];
2378 return io_write(io, str, 0);
2379 }
2380}
2381
2382VALUE
2383rb_io_write(VALUE io, VALUE str)
2384{
2385 return rb_funcallv(io, id_write, 1, &str);
2386}
2387
2388static VALUE
2389rb_io_writev(VALUE io, int argc, const VALUE *argv)
2390{
2391 if (argc > 1 && rb_obj_method_arity(io, id_write) == 1) {
2392 if (io != rb_ractor_stderr() && RTEST(ruby_verbose)) {
2393 VALUE klass = CLASS_OF(io);
2394 char sep = RCLASS_SINGLETON_P(klass) ? (klass = io, '.') : '#';
2396 RB_WARN_CATEGORY_DEPRECATED, "%+"PRIsVALUE"%c""write is outdated interface"
2397 " which accepts just one argument",
2398 klass, sep
2399 );
2400 }
2401
2402 do rb_io_write(io, *argv++); while (--argc);
2403
2404 return Qnil;
2405 }
2406
2407 return rb_funcallv(io, id_write, argc, argv);
2408}
2409
2410/*
2411 * call-seq:
2412 * self << object -> self
2413 *
2414 * Writes the given +object+ to +self+,
2415 * which must be opened for writing (see {Access Modes}[rdoc-ref:File@Access+Modes]);
2416 * returns +self+;
2417 * if +object+ is not a string, it is converted via method +to_s+:
2418 *
2419 * $stdout << 'Hello' << ', ' << 'World!' << "\n"
2420 * $stdout << 'foo' << :bar << 2 << "\n"
2421 *
2422 * Output:
2423 *
2424 * Hello, World!
2425 * foobar2
2426 *
2427 */
2428
2429
2430VALUE
2432{
2433 rb_io_write(io, str);
2434 return io;
2435}
2436
2437#ifdef HAVE_FSYNC
2438static VALUE
2439nogvl_fsync(void *ptr)
2440{
2441 rb_io_t *fptr = ptr;
2442
2443#ifdef _WIN32
2444 if (GetFileType((HANDLE)rb_w32_get_osfhandle(fptr->fd)) != FILE_TYPE_DISK)
2445 return 0;
2446#endif
2447 return (VALUE)fsync(fptr->fd);
2448}
2449#endif
2450
2451VALUE
2452rb_io_flush_raw(VALUE io, int sync)
2453{
2454 rb_io_t *fptr;
2455
2456 if (!RB_TYPE_P(io, T_FILE)) {
2457 return rb_funcall(io, id_flush, 0);
2458 }
2459
2460 io = GetWriteIO(io);
2461 GetOpenFile(io, fptr);
2462
2463 if (fptr->mode & FMODE_WRITABLE) {
2464 if (io_fflush(fptr) < 0)
2465 rb_sys_fail_on_write(fptr);
2466 }
2467 if (fptr->mode & FMODE_READABLE) {
2468 io_unread(fptr, true);
2469 }
2470
2471 return io;
2472}
2473
2474/*
2475 * call-seq:
2476 * flush -> self
2477 *
2478 * Flushes data buffered in +self+ to the operating system
2479 * (but does not necessarily flush data buffered in the operating system):
2480 *
2481 * $stdout.print 'no newline' # Not necessarily flushed.
2482 * $stdout.flush # Flushed.
2483 *
2484 */
2485
2486VALUE
2487rb_io_flush(VALUE io)
2488{
2489 return rb_io_flush_raw(io, 1);
2490}
2491
2492/*
2493 * call-seq:
2494 * tell -> integer
2495 *
2496 * Returns the current position (in bytes) in +self+
2497 * (see {Position}[rdoc-ref:IO@Position]):
2498 *
2499 * f = File.open('t.txt')
2500 * f.tell # => 0
2501 * f.gets # => "First line\n"
2502 * f.tell # => 12
2503 * f.close
2504 *
2505 * Related: IO#pos=, IO#seek.
2506 */
2507
2508static VALUE
2509rb_io_tell(VALUE io)
2510{
2511 rb_io_t *fptr;
2512 rb_off_t pos;
2513
2514 GetOpenFile(io, fptr);
2515 pos = io_tell(fptr);
2516 if (pos < 0 && errno) rb_sys_fail_path(fptr->pathv);
2517 pos -= fptr->rbuf.len;
2518 return OFFT2NUM(pos);
2519}
2520
2521static VALUE
2522rb_io_seek(VALUE io, VALUE offset, int whence)
2523{
2524 rb_io_t *fptr;
2525 rb_off_t pos;
2526
2527 pos = NUM2OFFT(offset);
2528 GetOpenFile(io, fptr);
2529 pos = io_seek(fptr, pos, whence);
2530 if (pos < 0 && errno) rb_sys_fail_path(fptr->pathv);
2531 if (fptr->readconv) clear_readconv(fptr);
2532
2533 return INT2FIX(0);
2534}
2535
2536static int
2537interpret_seek_whence(VALUE vwhence)
2538{
2539 if (vwhence == sym_SET)
2540 return SEEK_SET;
2541 if (vwhence == sym_CUR)
2542 return SEEK_CUR;
2543 if (vwhence == sym_END)
2544 return SEEK_END;
2545#ifdef SEEK_DATA
2546 if (vwhence == sym_DATA)
2547 return SEEK_DATA;
2548#endif
2549#ifdef SEEK_HOLE
2550 if (vwhence == sym_HOLE)
2551 return SEEK_HOLE;
2552#endif
2553 return NUM2INT(vwhence);
2554}
2555
2556/*
2557 * call-seq:
2558 * seek(offset, whence = IO::SEEK_SET) -> 0
2559 *
2560 * Seeks to the position given by integer +offset+
2561 * (see {Position}[rdoc-ref:IO@Position])
2562 * and constant +whence+, which is one of:
2563 *
2564 * - +:CUR+ or <tt>IO::SEEK_CUR</tt>:
2565 * Repositions the stream to its current position plus the given +offset+:
2566 *
2567 * f = File.open('t.txt')
2568 * f.tell # => 0
2569 * f.seek(20, :CUR) # => 0
2570 * f.tell # => 20
2571 * f.seek(-10, :CUR) # => 0
2572 * f.tell # => 10
2573 * f.close
2574 *
2575 * - +:END+ or <tt>IO::SEEK_END</tt>:
2576 * Repositions the stream to its end plus the given +offset+:
2577 *
2578 * f = File.open('t.txt')
2579 * f.tell # => 0
2580 * f.seek(0, :END) # => 0 # Repositions to stream end.
2581 * f.tell # => 52
2582 * f.seek(-20, :END) # => 0
2583 * f.tell # => 32
2584 * f.seek(-40, :END) # => 0
2585 * f.tell # => 12
2586 * f.close
2587 *
2588 * - +:SET+ or <tt>IO::SEEK_SET</tt>:
2589 * Repositions the stream to the given +offset+:
2590 *
2591 * f = File.open('t.txt')
2592 * f.tell # => 0
2593 * f.seek(20, :SET) # => 0
2594 * f.tell # => 20
2595 * f.seek(40, :SET) # => 0
2596 * f.tell # => 40
2597 * f.close
2598 *
2599 * Related: IO#pos=, IO#tell.
2600 *
2601 */
2602
2603static VALUE
2604rb_io_seek_m(int argc, VALUE *argv, VALUE io)
2605{
2606 VALUE offset, ptrname;
2607 int whence = SEEK_SET;
2608
2609 if (rb_scan_args(argc, argv, "11", &offset, &ptrname) == 2) {
2610 whence = interpret_seek_whence(ptrname);
2611 }
2612
2613 return rb_io_seek(io, offset, whence);
2614}
2615
2616/*
2617 * call-seq:
2618 * pos = new_position -> new_position
2619 *
2620 * Seeks to the given +new_position+ (in bytes);
2621 * see {Position}[rdoc-ref:IO@Position]:
2622 *
2623 * f = File.open('t.txt')
2624 * f.tell # => 0
2625 * f.pos = 20 # => 20
2626 * f.tell # => 20
2627 * f.close
2628 *
2629 * Related: IO#seek, IO#tell.
2630 *
2631 */
2632
2633static VALUE
2634rb_io_set_pos(VALUE io, VALUE offset)
2635{
2636 rb_io_t *fptr;
2637 rb_off_t pos;
2638
2639 pos = NUM2OFFT(offset);
2640 GetOpenFile(io, fptr);
2641 pos = io_seek(fptr, pos, SEEK_SET);
2642 if (pos < 0 && errno) rb_sys_fail_path(fptr->pathv);
2643 if (fptr->readconv) clear_readconv(fptr);
2644
2645 return OFFT2NUM(pos);
2646}
2647
2648/*
2649 * call-seq:
2650 * rewind -> 0
2651 *
2652 * Repositions the stream to its beginning,
2653 * setting both the position and the line number to zero;
2654 * see {Position}[rdoc-ref:IO@Position]
2655 * and {Line Number}[rdoc-ref:IO@Line+Number]:
2656 *
2657 * f = File.open('t.txt')
2658 * f.tell # => 0
2659 * f.lineno # => 0
2660 * f.gets # => "First line\n"
2661 * f.tell # => 12
2662 * f.lineno # => 1
2663 * f.rewind # => 0
2664 * f.tell # => 0
2665 * f.lineno # => 0
2666 * f.close
2667 *
2668 * Note that this method cannot be used with streams such as pipes, ttys, and sockets.
2669 *
2670 */
2671
2672static VALUE
2673rb_io_rewind(VALUE io)
2674{
2675 rb_io_t *fptr;
2676
2677 GetOpenFile(io, fptr);
2678 if (io_seek(fptr, 0L, 0) < 0 && errno) rb_sys_fail_path(fptr->pathv);
2679 if (io == ARGF.current_file) {
2680 ARGF.lineno -= fptr->lineno;
2681 }
2682 fptr->lineno = 0;
2683 if (fptr->readconv) {
2684 clear_readconv(fptr);
2685 }
2686
2687 return INT2FIX(0);
2688}
2689
2690static int
2691fptr_wait_readable(rb_io_t *fptr)
2692{
2693 int result = rb_io_maybe_wait_readable(errno, fptr->self, RUBY_IO_TIMEOUT_DEFAULT);
2694
2695 if (result)
2696 rb_io_check_closed(fptr);
2697
2698 return result;
2699}
2700
2701static int
2702io_fillbuf(rb_io_t *fptr)
2703{
2704 ssize_t r;
2705
2706 if (fptr->rbuf.ptr == NULL) {
2707 fptr->rbuf.off = 0;
2708 fptr->rbuf.len = 0;
2709 fptr->rbuf.capa = IO_RBUF_CAPA_FOR(fptr);
2710 fptr->rbuf.ptr = ALLOC_N(char, fptr->rbuf.capa);
2711 }
2712 if (fptr->rbuf.len == 0) {
2713 retry:
2714 r = rb_io_read_memory(fptr, fptr->rbuf.ptr, fptr->rbuf.capa);
2715
2716 if (r < 0) {
2717 if (fptr_wait_readable(fptr))
2718 goto retry;
2719
2720 int e = errno;
2721 VALUE path = rb_sprintf("fd:%d ", fptr->fd);
2722 if (!NIL_P(fptr->pathv)) {
2723 rb_str_append(path, fptr->pathv);
2724 }
2725
2726 rb_syserr_fail_path(e, path);
2727 }
2728 if (r > 0) rb_io_check_closed(fptr);
2729 fptr->rbuf.off = 0;
2730 fptr->rbuf.len = (int)r; /* r should be <= rbuf_capa */
2731 if (r == 0)
2732 return -1; /* EOF */
2733 }
2734 return 0;
2735}
2736
2737/*
2738 * call-seq:
2739 * eof -> true or false
2740 *
2741 * Returns +true+ if the stream is positioned at its end, +false+ otherwise;
2742 * see {Position}[rdoc-ref:IO@Position]:
2743 *
2744 * f = File.open('t.txt')
2745 * f.eof # => false
2746 * f.seek(0, :END) # => 0
2747 * f.eof # => true
2748 * f.close
2749 *
2750 * Raises an exception unless the stream is opened for reading;
2751 * see {Mode}[rdoc-ref:File@Access+Modes].
2752 *
2753 * If +self+ is a stream such as pipe or socket, this method
2754 * blocks until the other end sends some data or closes it:
2755 *
2756 * r, w = IO.pipe
2757 * Thread.new { sleep 1; w.close }
2758 * r.eof? # => true # After 1-second wait.
2759 *
2760 * r, w = IO.pipe
2761 * Thread.new { sleep 1; w.puts "a" }
2762 * r.eof? # => false # After 1-second wait.
2763 *
2764 * r, w = IO.pipe
2765 * r.eof? # blocks forever
2766 *
2767 * Note that this method reads data to the input byte buffer. So
2768 * IO#sysread may not behave as you intend with IO#eof?, unless you
2769 * call IO#rewind first (which is not available for some streams).
2770 */
2771
2772VALUE
2774{
2775 rb_io_t *fptr;
2776
2777 GetOpenFile(io, fptr);
2779
2780 if (READ_CHAR_PENDING(fptr)) return Qfalse;
2781 if (READ_DATA_PENDING(fptr)) return Qfalse;
2782 READ_CHECK(fptr);
2783#if RUBY_CRLF_ENVIRONMENT
2784 if (!NEED_READCONV(fptr) && NEED_NEWLINE_DECORATOR_ON_READ(fptr)) {
2785 return RBOOL(eof(fptr->fd));
2786 }
2787#endif
2788 return RBOOL(io_fillbuf(fptr) < 0);
2789}
2790
2791/*
2792 * call-seq:
2793 * sync -> true or false
2794 *
2795 * Returns the current sync mode of the stream.
2796 * When sync mode is true, all output is immediately flushed to the underlying
2797 * operating system and is not buffered by Ruby internally. See also #fsync.
2798 *
2799 * f = File.open('t.tmp', 'w')
2800 * f.sync # => false
2801 * f.sync = true
2802 * f.sync # => true
2803 * f.close
2804 *
2805 */
2806
2807static VALUE
2808rb_io_sync(VALUE io)
2809{
2810 rb_io_t *fptr;
2811
2812 io = GetWriteIO(io);
2813 GetOpenFile(io, fptr);
2814 return RBOOL(fptr->mode & FMODE_SYNC);
2815}
2816
2817#ifdef HAVE_FSYNC
2818
2819/*
2820 * call-seq:
2821 * sync = boolean -> boolean
2822 *
2823 * Sets the _sync_ _mode_ for the stream to the given value;
2824 * returns the given value.
2825 *
2826 * Values for the sync mode:
2827 *
2828 * - +true+: All output is immediately flushed to the
2829 * underlying operating system and is not buffered internally.
2830 * - +false+: Output may be buffered internally.
2831 *
2832 * Example;
2833 *
2834 * f = File.open('t.tmp', 'w')
2835 * f.sync # => false
2836 * f.sync = true
2837 * f.sync # => true
2838 * f.close
2839 *
2840 * Related: IO#fsync.
2841 *
2842 */
2843
2844static VALUE
2845rb_io_set_sync(VALUE io, VALUE sync)
2846{
2847 rb_io_t *fptr;
2848
2849 io = GetWriteIO(io);
2850 GetOpenFile(io, fptr);
2851 if (RTEST(sync)) {
2852 fptr->mode |= FMODE_SYNC;
2853 }
2854 else {
2855 fptr->mode &= ~FMODE_SYNC;
2856 }
2857 return sync;
2858}
2859
2860/*
2861 * call-seq:
2862 * fsync -> 0
2863 *
2864 * Immediately writes to disk all data buffered in the stream,
2865 * via the operating system's <tt>fsync(2)</tt>.
2866
2867 * Note this difference:
2868 *
2869 * - IO#sync=: Ensures that data is flushed from the stream's internal buffers,
2870 * but does not guarantee that the operating system actually writes the data to disk.
2871 * - IO#fsync: Ensures both that data is flushed from internal buffers,
2872 * and that data is written to disk.
2873 *
2874 * Raises an exception if the operating system does not support <tt>fsync(2)</tt>.
2875 *
2876 */
2877
2878static VALUE
2879rb_io_fsync(VALUE io)
2880{
2881 rb_io_t *fptr;
2882
2883 io = GetWriteIO(io);
2884 GetOpenFile(io, fptr);
2885
2886 if (io_fflush(fptr) < 0)
2887 rb_sys_fail_on_write(fptr);
2888
2889 if ((int)rb_io_blocking_region(fptr, nogvl_fsync, fptr))
2890 rb_sys_fail_path(fptr->pathv);
2891
2892 return INT2FIX(0);
2893}
2894#else
2895# define rb_io_fsync rb_f_notimplement
2896# define rb_io_sync rb_f_notimplement
2897static VALUE
2898rb_io_set_sync(VALUE io, VALUE sync)
2899{
2902}
2903#endif
2904
2905#ifdef HAVE_FDATASYNC
2906static VALUE
2907nogvl_fdatasync(void *ptr)
2908{
2909 rb_io_t *fptr = ptr;
2910
2911 return (VALUE)fdatasync(fptr->fd);
2912}
2913
2914/*
2915 * call-seq:
2916 * fdatasync -> 0
2917 *
2918 * Immediately writes to disk all data buffered in the stream,
2919 * via the operating system's: <tt>fdatasync(2)</tt>, if supported,
2920 * otherwise via <tt>fsync(2)</tt>, if supported;
2921 * otherwise raises an exception.
2922 *
2923 */
2924
2925static VALUE
2926rb_io_fdatasync(VALUE io)
2927{
2928 rb_io_t *fptr;
2929
2930 io = GetWriteIO(io);
2931 GetOpenFile(io, fptr);
2932
2933 if (io_fflush(fptr) < 0)
2934 rb_sys_fail_on_write(fptr);
2935
2936 if ((int)rb_io_blocking_region(fptr, nogvl_fdatasync, fptr) == 0)
2937 return INT2FIX(0);
2938
2939 /* fall back */
2940 return rb_io_fsync(io);
2941}
2942#else
2943#define rb_io_fdatasync rb_io_fsync
2944#endif
2945
2946/*
2947 * call-seq:
2948 * fileno -> integer
2949 *
2950 * Returns the integer file descriptor for the stream:
2951 *
2952 * $stdin.fileno # => 0
2953 * $stdout.fileno # => 1
2954 * $stderr.fileno # => 2
2955 * File.open('t.txt').fileno # => 10
2956 * f.close
2957 *
2958 */
2959
2960static VALUE
2961rb_io_fileno(VALUE io)
2962{
2963 rb_io_t *fptr = RFILE(io)->fptr;
2964 int fd;
2965
2966 rb_io_check_closed(fptr);
2967 fd = fptr->fd;
2968 return INT2FIX(fd);
2969}
2970
2971int
2973{
2974 if (RB_TYPE_P(io, T_FILE)) {
2975 rb_io_t *fptr = RFILE(io)->fptr;
2976 rb_io_check_closed(fptr);
2977 return fptr->fd;
2978 }
2979 else {
2980 VALUE fileno = rb_check_funcall(io, id_fileno, 0, NULL);
2981 if (!UNDEF_P(fileno)) {
2982 return RB_NUM2INT(fileno);
2983 }
2984 }
2985
2986 rb_raise(rb_eTypeError, "expected IO or #fileno, %"PRIsVALUE" given", rb_obj_class(io));
2987
2989}
2990
2991int
2992rb_io_mode(VALUE io)
2993{
2994 rb_io_t *fptr;
2995 GetOpenFile(io, fptr);
2996 return fptr->mode;
2997}
2998
2999/*
3000 * call-seq:
3001 * pid -> integer or nil
3002 *
3003 * Returns the process ID of a child process associated with the stream,
3004 * which will have been set by IO#popen, or +nil+ if the stream was not
3005 * created by IO#popen:
3006 *
3007 * pipe = IO.popen("-")
3008 * if pipe
3009 * $stderr.puts "In parent, child pid is #{pipe.pid}"
3010 * else
3011 * $stderr.puts "In child, pid is #{$$}"
3012 * end
3013 *
3014 * Output:
3015 *
3016 * In child, pid is 26209
3017 * In parent, child pid is 26209
3018 *
3019 */
3020
3021static VALUE
3022rb_io_pid(VALUE io)
3023{
3024 rb_io_t *fptr;
3025
3026 GetOpenFile(io, fptr);
3027 if (!fptr->pid)
3028 return Qnil;
3029 return PIDT2NUM(fptr->pid);
3030}
3031
3032/*
3033 * :markup: markdown
3034 *
3035 * call-seq:
3036 * path -> string or nil
3037 *
3038 * Returns the string path associated with `self`,
3039 * or `nil` if there is no associated path:
3040 *
3041 * ```ruby
3042 * path = 'doc/maintainers.md'
3043 * fd = File.open(path).fileno # => 6
3044 * IO.new(fd, path: path).path # => "doc/maintainers.md"
3045 * IO.new(fd).path # => nil
3046 * ```
3047 *
3048 */
3049
3050VALUE
3052{
3053 rb_io_t *fptr = RFILE(io)->fptr;
3054
3055 if (!fptr)
3056 return Qnil;
3057
3058 return rb_obj_dup(fptr->pathv);
3059}
3060
3061/*
3062 * call-seq:
3063 * inspect -> string
3064 *
3065 * Returns a string representation of +self+:
3066 *
3067 * f = File.open('t.txt')
3068 * f.inspect # => "#<File:t.txt>"
3069 * f.close
3070 *
3071 */
3072
3073static VALUE
3074rb_io_inspect(VALUE obj)
3075{
3076 rb_io_t *fptr;
3077 VALUE result;
3078 static const char closed[] = " (closed)";
3079
3080 fptr = RFILE(obj)->fptr;
3081 if (!fptr) return rb_any_to_s(obj);
3082 result = rb_str_new_cstr("#<");
3083 rb_str_append(result, rb_class_name(CLASS_OF(obj)));
3084 rb_str_cat2(result, ":");
3085 if (NIL_P(fptr->pathv)) {
3086 if (fptr->fd < 0) {
3087 rb_str_cat(result, closed+1, strlen(closed)-1);
3088 }
3089 else {
3090 rb_str_catf(result, "fd %d", fptr->fd);
3091 }
3092 }
3093 else {
3094 rb_str_append(result, fptr->pathv);
3095 if (fptr->fd < 0) {
3096 rb_str_cat(result, closed, strlen(closed));
3097 }
3098 }
3099 return rb_str_cat2(result, ">");
3100}
3101
3102/*
3103 * call-seq:
3104 * to_io -> self
3105 *
3106 * Returns +self+.
3107 *
3108 */
3109
3110static VALUE
3111rb_io_to_io(VALUE io)
3112{
3113 return io;
3114}
3115
3116/* reading functions */
3117static rb_len_t
3118read_buffered_data(char *ptr, rb_len_t len, rb_io_t *fptr)
3119{
3120 int n;
3121
3122 n = READ_DATA_PENDING_COUNT(fptr);
3123 if (n <= 0) return 0;
3124 if (n > len) n = (int)len;
3125 MEMMOVE(ptr, fptr->rbuf.ptr+fptr->rbuf.off, char, n);
3126 fptr->rbuf.off += n;
3127 fptr->rbuf.len -= n;
3128 return n;
3129}
3130
3131static rb_len_t
3132io_bufread(char *ptr, rb_len_t len, rb_io_t *fptr, rb_len_t *read_len)
3133{
3134 rb_len_t offset = 0;
3135 rb_len_t n = len;
3136 rb_len_t c;
3137
3138 *read_len = 0;
3139 if (READ_DATA_PENDING(fptr) == 0) {
3140 while (n > 0) {
3141 again:
3142 rb_io_check_closed(fptr);
3143 c = rb_io_read_memory(fptr, ptr+offset, n);
3144 if (c == 0) break;
3145 if (c < 0) {
3146 if (fptr_wait_readable(fptr))
3147 goto again;
3148 return -1;
3149 }
3150 offset += c;
3151 *read_len = offset;
3152 if ((n -= c) <= 0) break;
3153 }
3154 return len - n;
3155 }
3156
3157 while (n > 0) {
3158 c = read_buffered_data(ptr+offset, n, fptr);
3159 if (c > 0) {
3160 offset += c;
3161 *read_len = offset;
3162 if ((n -= c) <= 0) break;
3163 }
3164 rb_io_check_closed(fptr);
3165 if (io_fillbuf(fptr) < 0) {
3166 break;
3167 }
3168 }
3169 return len - n;
3170}
3171
3172static int io_setstrbuf(VALUE *str, rb_len_t len);
3173
3175 char *str_ptr;
3176 rb_len_t offset;
3177 rb_len_t len;
3178 rb_len_t read_len;
3179 rb_io_t *fptr;
3180};
3181
3182static VALUE
3183bufread_body(VALUE arg)
3184{
3185 struct bufread_arg *p = (struct bufread_arg *)arg;
3186 p->len = io_bufread(p->str_ptr + p->offset, p->len, p->fptr, &p->read_len);
3187 return Qundef;
3188}
3189
3190static VALUE
3191bufread_timeout(VALUE arg, VALUE error)
3192{
3193 struct bufread_arg *p = (struct bufread_arg *)arg;
3194
3195 if (p->offset + p->read_len > 0) {
3196 VALUE str = rb_str_new(p->str_ptr, p->offset + p->read_len);
3197 io_restore_read_buffer(str, p->fptr);
3198 }
3199 rb_exc_raise(error);
3201}
3202
3203static VALUE
3204bufread_call(VALUE arg)
3205{
3206 struct bufread_arg *p = (struct bufread_arg *)arg;
3207
3208 if (NIL_P(p->fptr->timeout)) {
3209 return bufread_body(arg);
3210 }
3211 return rb_rescue2(bufread_body, arg, bufread_timeout, arg,
3213}
3214
3215static rb_len_t
3216io_fread(VALUE str, rb_len_t offset, rb_len_t size, rb_io_t *fptr)
3217{
3218 rb_len_t len;
3219 struct bufread_arg arg;
3220
3221 io_setstrbuf(&str, offset + size);
3222 if (!READ_DATA_PENDING(fptr))
3223 rb_str_make_heap(str);
3224 arg.str_ptr = RSTRING_PTR(str);
3225 arg.offset = offset;
3226 arg.len = size;
3227 arg.read_len = 0;
3228 arg.fptr = fptr;
3229 rb_str_locktmp_ensure(str, bufread_call, (VALUE)&arg);
3230 len = arg.len;
3231 if (len < 0) rb_sys_fail_path(fptr->pathv);
3232 return len;
3233}
3234
3235static rb_len_t
3236remain_size(rb_io_t *fptr)
3237{
3238 struct stat st;
3239 rb_off_t siz = READ_DATA_PENDING_COUNT(fptr);
3240 rb_off_t pos;
3241
3242 if (fstat(fptr->fd, &st) == 0 && S_ISREG(st.st_mode)
3243#if defined(__HAIKU__)
3244 && (st.st_dev > 3)
3245#endif
3246 )
3247 {
3248 if (io_fflush(fptr) < 0)
3249 rb_sys_fail_on_write(fptr);
3250 pos = lseek(fptr->fd, 0, SEEK_CUR);
3251 if (st.st_size >= pos && pos >= 0) {
3252 siz += st.st_size - pos;
3253 if (siz > RB_LEN_MAX) {
3254 rb_raise(rb_eIOError, "file too big for single read");
3255 }
3256 }
3257 }
3258 else {
3259 siz += BUFSIZ;
3260 }
3261 return (rb_len_t)siz;
3262}
3263
3264static VALUE
3265io_enc_str(VALUE str, rb_io_t *fptr)
3266{
3267 rb_enc_associate(str, io_read_encoding(fptr));
3268 return str;
3269}
3270
3271static void
3272make_readconv(rb_io_t *fptr, int size)
3273{
3274 if (!fptr->readconv) {
3275 int ecflags;
3276 VALUE ecopts;
3277 const char *sname, *dname;
3279 ecopts = fptr->encs.ecopts;
3280 if (fptr->encs.enc2) {
3281 sname = rb_enc_name(fptr->encs.enc2);
3282 dname = rb_enc_name(io_read_encoding(fptr));
3283 }
3284 else {
3285 sname = dname = "";
3286 }
3287 fptr->readconv = rb_econv_open_opts(sname, dname, ecflags, ecopts);
3288 if (!fptr->readconv)
3289 rb_exc_raise(rb_econv_open_exc(sname, dname, ecflags));
3290 fptr->cbuf.off = 0;
3291 fptr->cbuf.len = 0;
3292 if (size < IO_CBUF_CAPA_MIN) size = IO_CBUF_CAPA_MIN;
3293 fptr->cbuf.capa = size;
3294 fptr->cbuf.ptr = ALLOC_N(char, fptr->cbuf.capa);
3295 }
3296}
3297
3298#define MORE_CHAR_SUSPENDED Qtrue
3299#define MORE_CHAR_FINISHED Qnil
3300static VALUE
3301fill_cbuf(rb_io_t *fptr, int ec_flags)
3302{
3303 const unsigned char *ss, *sp, *se;
3304 unsigned char *ds, *dp, *de;
3306 int putbackable;
3307 int cbuf_len0;
3308 VALUE exc;
3309
3310 ec_flags |= ECONV_PARTIAL_INPUT;
3311
3312 if (fptr->cbuf.len == fptr->cbuf.capa)
3313 return MORE_CHAR_SUSPENDED; /* cbuf full */
3314 if (fptr->cbuf.len == 0)
3315 fptr->cbuf.off = 0;
3316 else if (fptr->cbuf.off + fptr->cbuf.len == fptr->cbuf.capa) {
3317 memmove(fptr->cbuf.ptr, fptr->cbuf.ptr+fptr->cbuf.off, fptr->cbuf.len);
3318 fptr->cbuf.off = 0;
3319 }
3320
3321 cbuf_len0 = fptr->cbuf.len;
3322
3323 while (1) {
3324 ss = sp = (const unsigned char *)fptr->rbuf.ptr + fptr->rbuf.off;
3325 se = sp + fptr->rbuf.len;
3326 ds = dp = (unsigned char *)fptr->cbuf.ptr + fptr->cbuf.off + fptr->cbuf.len;
3327 de = (unsigned char *)fptr->cbuf.ptr + fptr->cbuf.capa;
3328 res = rb_econv_convert(fptr->readconv, &sp, se, &dp, de, ec_flags);
3329 fptr->rbuf.off += (int)(sp - ss);
3330 fptr->rbuf.len -= (int)(sp - ss);
3331 fptr->cbuf.len += (int)(dp - ds);
3332
3333 putbackable = rb_econv_putbackable(fptr->readconv);
3334 /* The converter can hold readagain bytes it received in an earlier
3335 * fill (a character split across reads). Only bytes still in rbuf
3336 * can be put back there; the rest stay in the converter. */
3337 if (putbackable > fptr->rbuf.off)
3338 putbackable = fptr->rbuf.off;
3339 if (putbackable) {
3340 rb_econv_putback(fptr->readconv, (unsigned char *)fptr->rbuf.ptr + fptr->rbuf.off - putbackable, putbackable);
3341 fptr->rbuf.off -= putbackable;
3342 fptr->rbuf.len += putbackable;
3343 }
3344
3345 exc = rb_econv_make_exception(fptr->readconv);
3346 if (!NIL_P(exc))
3347 return exc;
3348
3349 if (cbuf_len0 != fptr->cbuf.len)
3350 return MORE_CHAR_SUSPENDED;
3351
3352 if (res == econv_finished) {
3353 return MORE_CHAR_FINISHED;
3354 }
3355
3356 if (res == econv_source_buffer_empty) {
3357 if (fptr->rbuf.len == 0) {
3358 READ_CHECK(fptr);
3359 if (io_fillbuf(fptr) < 0) {
3360 if (!fptr->readconv) {
3361 return MORE_CHAR_FINISHED;
3362 }
3363 ds = dp = (unsigned char *)fptr->cbuf.ptr + fptr->cbuf.off + fptr->cbuf.len;
3364 de = (unsigned char *)fptr->cbuf.ptr + fptr->cbuf.capa;
3365 res = rb_econv_convert(fptr->readconv, NULL, NULL, &dp, de, 0);
3366 fptr->cbuf.len += (int)(dp - ds);
3368 break;
3369 }
3370 }
3371 }
3372 }
3373 if (cbuf_len0 != fptr->cbuf.len)
3374 return MORE_CHAR_SUSPENDED;
3375
3376 return MORE_CHAR_FINISHED;
3377}
3378
3379static VALUE
3380more_char(rb_io_t *fptr)
3381{
3382 VALUE v;
3383 v = fill_cbuf(fptr, ECONV_AFTER_OUTPUT);
3384 if (v != MORE_CHAR_SUSPENDED && v != MORE_CHAR_FINISHED)
3385 rb_exc_raise(v);
3386 return v;
3387}
3388
3389static VALUE
3390io_shift_cbuf(rb_io_t *fptr, int len, VALUE *strp)
3391{
3392 VALUE str = Qnil;
3393 if (strp) {
3394 str = *strp;
3395 if (NIL_P(str)) {
3396 *strp = str = rb_str_new(fptr->cbuf.ptr+fptr->cbuf.off, len);
3397 }
3398 else {
3399 rb_str_cat(str, fptr->cbuf.ptr+fptr->cbuf.off, len);
3400 }
3401 rb_enc_associate(str, fptr->encs.enc);
3402 }
3403 fptr->cbuf.off += len;
3404 fptr->cbuf.len -= len;
3405 /* xxx: set coderange */
3406 if (fptr->cbuf.len == 0)
3407 fptr->cbuf.off = 0;
3408 else if (fptr->cbuf.capa/2 < fptr->cbuf.off) {
3409 memmove(fptr->cbuf.ptr, fptr->cbuf.ptr+fptr->cbuf.off, fptr->cbuf.len);
3410 fptr->cbuf.off = 0;
3411 }
3412 return str;
3413}
3414
3415static int
3416io_setstrbuf(VALUE *str, rb_len_t len)
3417{
3418 if (NIL_P(*str)) {
3419 *str = rb_str_new(0, len);
3420 return TRUE;
3421 }
3422 else {
3423 VALUE s = StringValue(*str);
3424 rb_str_modify(s);
3425
3426 rb_len_t clen = RSTRING_LEN(s);
3427 if (clen >= len) {
3428 return FALSE;
3429 }
3430 len -= clen;
3431 }
3432 if ((rb_str_capacity(*str) - (size_t)RSTRING_LEN(*str)) < (size_t)len) {
3434 }
3435 return FALSE;
3436}
3437
3438#define MAX_REALLOC_GAP 4096
3439static void
3440io_shrink_read_string(VALUE str, rb_len_t n)
3441{
3442 if (rb_str_capacity(str) - n > MAX_REALLOC_GAP) {
3443 rb_str_resize(str, n);
3444 }
3445}
3446
3447static void
3448io_set_read_length(VALUE str, rb_len_t n, int shrinkable)
3449{
3450 if (RSTRING_LEN(str) != n) {
3451 rb_str_modify(str);
3452 rb_str_set_len(str, n);
3453 if (shrinkable) io_shrink_read_string(str, n);
3454 }
3455}
3456
3457static VALUE
3458read_all(rb_io_t *fptr, rb_len_t siz, VALUE str)
3459{
3460 rb_len_t bytes;
3461 rb_len_t n;
3462 rb_len_t pos;
3463 rb_encoding *enc;
3464 int cr;
3465 int shrinkable;
3466
3467 if (NEED_READCONV(fptr)) {
3468 int first = !NIL_P(str);
3469 SET_BINARY_MODE(fptr);
3470 shrinkable = io_setstrbuf(&str,0);
3471 make_readconv(fptr, 0);
3472 while (1) {
3473 VALUE v;
3474 if (fptr->cbuf.len) {
3475 if (first) rb_str_set_len(str, first = 0);
3476 io_shift_cbuf(fptr, fptr->cbuf.len, &str);
3477 }
3478 v = fill_cbuf(fptr, 0);
3479 if (v != MORE_CHAR_SUSPENDED && v != MORE_CHAR_FINISHED) {
3480 if (fptr->cbuf.len) {
3481 if (first) rb_str_set_len(str, first = 0);
3482 io_shift_cbuf(fptr, fptr->cbuf.len, &str);
3483 }
3484 rb_exc_raise(v);
3485 }
3486 if (v == MORE_CHAR_FINISHED) {
3487 clear_readconv(fptr);
3488 if (first) rb_str_set_len(str, first = 0);
3489 if (shrinkable) io_shrink_read_string(str, RSTRING_LEN(str));
3490 return io_enc_str(str, fptr);
3491 }
3492 }
3493 }
3494
3495 NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr);
3496 bytes = 0;
3497 pos = 0;
3498
3499 enc = io_read_encoding(fptr);
3500 cr = 0;
3501
3502 if (siz == 0) {
3503 siz = BUFSIZ;
3504 }
3505 else {
3506 // If `siz` is set, we got it from `stat(2)`.
3507 // We attempt to read one extra byte because:
3508 // - If the file was appended to since then, we'll continue reading.
3509 // - If the file is still the same length, we won't issue a second `io_fread`.
3510 siz++;
3511 }
3512 shrinkable = io_setstrbuf(&str, siz);
3513 for (;;) {
3514 READ_CHECK(fptr);
3515 n = io_fread(str, bytes, siz - bytes, fptr);
3516 if (n == 0 && bytes == 0) {
3517 rb_str_set_len(str, 0);
3518 break;
3519 }
3520 bytes += n;
3521 rb_str_set_len(str, bytes);
3522 if (cr != ENC_CODERANGE_BROKEN)
3523 pos += rb_str_coderange_scan_restartable(RSTRING_PTR(str) + pos, RSTRING_PTR(str) + bytes, enc, &cr);
3524 if (bytes < siz) break;
3525 siz += BUFSIZ;
3526
3527 size_t capa = rb_str_capacity(str);
3528 if (capa < (size_t)RSTRING_LEN(str) + BUFSIZ) {
3529 if (capa < BUFSIZ) {
3530 capa = BUFSIZ;
3531 }
3532 else if (capa > IO_MAX_BUFFER_GROWTH) {
3533 capa = IO_MAX_BUFFER_GROWTH;
3534 }
3536 }
3537 }
3538 if (shrinkable) io_shrink_read_string(str, RSTRING_LEN(str));
3539 str = io_enc_str(str, fptr);
3540 ENC_CODERANGE_SET(str, cr);
3541 return str;
3542}
3543
3544void
3546{
3547 if (rb_fd_set_nonblock(fptr->fd) != 0) {
3548 rb_sys_fail_path(fptr->pathv);
3549 }
3550}
3551
3552static VALUE
3553io_read_memory_call(VALUE arg)
3554{
3555 struct io_internal_read_struct *iis = (struct io_internal_read_struct *)arg;
3556
3557 VALUE scheduler = rb_fiber_scheduler_current();
3558 if (scheduler != Qnil) {
3559 VALUE result = rb_fiber_scheduler_io_read_memory(scheduler, iis->fptr->self, iis->buf, iis->capa);
3560
3561 if (!UNDEF_P(result)) {
3562 // This is actually returned as a pseudo-VALUE and later cast to a rb_len_t:
3564 }
3565 }
3566
3567 if (iis->nonblock) {
3568 return rb_io_blocking_region(iis->fptr, internal_read_func, iis);
3569 }
3570 else {
3571 return rb_io_blocking_region_wait(iis->fptr, internal_read_func, iis, RUBY_IO_READABLE);
3572 }
3573}
3574
3575static rb_len_t
3576io_read_memory_locktmp(VALUE str, struct io_internal_read_struct *iis)
3577{
3578 return (rb_len_t)rb_str_locktmp_ensure(str, io_read_memory_call, (VALUE)iis);
3579}
3580
3581#define no_exception_p(opts) !rb_opts_exception_p((opts), TRUE)
3582
3583static VALUE
3584io_getpartial(VALUE io, VALUE length, VALUE str, int no_exception, int nonblock)
3585{
3586 rb_io_t *fptr;
3587 rb_len_t n, len;
3588 struct io_internal_read_struct iis;
3589 int shrinkable;
3590
3591 if ((len = NUM2LEN(length)) < 0) {
3592 rb_raise(rb_eArgError, "negative length %"PRIdLEN" given", len);
3593 }
3594
3595 shrinkable = io_setstrbuf(&str, len);
3596
3597 GetOpenFile(io, fptr);
3599
3600 if (len == 0) {
3601 io_set_read_length(str, 0, shrinkable);
3602 return str;
3603 }
3604
3605 if (!nonblock)
3606 READ_CHECK(fptr);
3607 n = read_buffered_data(RSTRING_PTR(str), len, fptr);
3608 if (n <= 0) {
3609 again:
3610 if (nonblock) {
3611 /* NOTE: The result is deliberately ignored */
3612 rb_fd_set_nonblock(fptr->fd);
3613 }
3614 io_setstrbuf(&str, len);
3615 rb_str_make_heap(str);
3616 iis.th = rb_thread_current();
3617 iis.fptr = fptr;
3618 iis.nonblock = nonblock;
3619 iis.fd = fptr->fd;
3620 iis.buf = RSTRING_PTR(str);
3621 iis.capa = len;
3622 iis.timeout = NULL;
3623 n = io_read_memory_locktmp(str, &iis);
3624 if (n < 0) {
3625 int e = errno;
3626 if (!nonblock && fptr_wait_readable(fptr))
3627 goto again;
3628 if (nonblock && (io_again_p(e))) {
3629 if (no_exception)
3630 return sym_wait_readable;
3631 else
3632 rb_readwrite_syserr_fail(RB_IO_WAIT_READABLE,
3633 e, "read would block");
3634 }
3635 rb_syserr_fail_path(e, fptr->pathv);
3636 }
3637 }
3638 io_set_read_length(str, n, shrinkable);
3639
3640 if (n == 0)
3641 return Qnil;
3642 else
3643 return str;
3644}
3645
3646/*
3647 * call-seq:
3648 * readpartial(maxlen) -> string
3649 * readpartial(maxlen, out_string) -> out_string
3650 *
3651 * Reads up to +maxlen+ bytes from the stream;
3652 * returns a string (either a new string or the given +out_string+).
3653 * Its encoding is:
3654 *
3655 * - The unchanged encoding of +out_string+, if +out_string+ is given.
3656 * - ASCII-8BIT, otherwise.
3657 *
3658 * - Contains +maxlen+ bytes from the stream, if available.
3659 * - Otherwise contains all available bytes, if any available.
3660 * - Is an empty string if +maxlen+ is zero.
3661 *
3662 * With the single non-negative integer argument +maxlen+ given,
3663 * returns a new string:
3664 *
3665 * f = File.new('t.txt')
3666 * f.readpartial(20) # => "First line\nSecond l"
3667 * f.readpartial(20) # => "ine\n\nFourth line\n"
3668 * f.readpartial(20) # => "Fifth line\n"
3669 * f.readpartial(20) # Raises EOFError.
3670 * f.close
3671 *
3672 * With both argument +maxlen+ and string argument +out_string+ given,
3673 * returns modified +out_string+:
3674 *
3675 * f = File.new('t.txt')
3676 * s = 'foo'
3677 * f.readpartial(20, s) # => "First line\nSecond l"
3678 * s = 'bar'
3679 * f.readpartial(0, s) # => ""
3680 * f.close
3681 *
3682 * This method is useful for a stream such as a pipe, a socket, or a tty.
3683 * It blocks only when no data is immediately available.
3684 * This means that it blocks only when _all_ of the following are true:
3685 *
3686 * - The byte buffer in the stream is empty.
3687 * - The content of the stream is empty.
3688 * - The stream is not at EOF.
3689 *
3690 * When blocked, the method waits for either more data or EOF on the stream:
3691 *
3692 * - If more data is read, the method returns the data.
3693 * - If EOF is reached, the method raises EOFError.
3694 *
3695 * When not blocked, the method responds immediately:
3696 *
3697 * - Returns data from the buffer if there is any.
3698 * - Otherwise returns data from the stream if there is any.
3699 * - Otherwise raises EOFError if the stream has reached EOF.
3700 *
3701 * Note that this method is similar to sysread. The differences are:
3702 *
3703 * - If the byte buffer is not empty, read from the byte buffer
3704 * instead of "sysread for buffered IO (IOError)".
3705 * - It doesn't cause Errno::EWOULDBLOCK and Errno::EINTR. When
3706 * readpartial meets EWOULDBLOCK and EINTR by read system call,
3707 * readpartial retries the system call.
3708 *
3709 * The latter means that readpartial is non-blocking-flag insensitive.
3710 * It blocks on the situation IO#sysread causes Errno::EWOULDBLOCK as
3711 * if the fd is blocking mode.
3712 *
3713 * Examples:
3714 *
3715 * # # Returned Buffer Content Pipe Content
3716 * r, w = IO.pipe #
3717 * w << 'abc' # "" "abc".
3718 * r.readpartial(4096) # => "abc" "" ""
3719 * r.readpartial(4096) # (Blocks because buffer and pipe are empty.)
3720 *
3721 * # # Returned Buffer Content Pipe Content
3722 * r, w = IO.pipe #
3723 * w << 'abc' # "" "abc"
3724 * w.close # "" "abc" EOF
3725 * r.readpartial(4096) # => "abc" "" EOF
3726 * r.readpartial(4096) # raises EOFError
3727 *
3728 * # # Returned Buffer Content Pipe Content
3729 * r, w = IO.pipe #
3730 * w << "abc\ndef\n" # "" "abc\ndef\n"
3731 * r.gets # => "abc\n" "def\n" ""
3732 * w << "ghi\n" # "def\n" "ghi\n"
3733 * r.readpartial(4096) # => "def\n" "" "ghi\n"
3734 * r.readpartial(4096) # => "ghi\n" "" ""
3735 *
3736 */
3737
3738static VALUE
3739io_readpartial(int argc, VALUE *argv, VALUE io)
3740{
3741 VALUE ret, length, str;
3742
3743 rb_scan_args(argc, argv, "11", &length, &str);
3744 ret = io_getpartial(io, length, str, 0, 0);
3745 if (NIL_P(ret))
3746 rb_eof_error();
3747 return ret;
3748}
3749
3750static VALUE
3751io_nonblock_eof(int no_exception)
3752{
3753 if (!no_exception) {
3754 rb_eof_error();
3755 }
3756 return Qnil;
3757}
3758
3759/* :nodoc: */
3760static VALUE
3761io_read_nonblock(rb_execution_context_t *ec, VALUE io, VALUE length, VALUE str, VALUE ex)
3762{
3763 int no_exception = !rb_bool_expected(ex, "exception", TRUE);
3764 VALUE ret = io_getpartial(io, length, str, no_exception, 1);
3765 if (NIL_P(ret))
3766 io_nonblock_eof(no_exception);
3767
3768 return ret;
3769}
3770
3771/* :nodoc: */
3772static VALUE
3773io_write_nonblock(rb_execution_context_t *ec, VALUE io, VALUE str, VALUE ex)
3774{
3775 rb_io_t *fptr;
3776 rb_len_t n;
3777
3778 if (!RB_TYPE_P(str, T_STRING))
3779 str = rb_obj_as_string(str);
3780 rb_bool_expected(ex, "exception", TRUE);
3781
3782 io = GetWriteIO(io);
3783 GetOpenFile(io, fptr);
3785
3786 if (io_fflush(fptr) < 0)
3787 rb_sys_fail_on_write(fptr);
3788
3789 rb_fd_set_nonblock(fptr->fd);
3790 n = write(fptr->fd, RSTRING_PTR(str), RSTRING_LEN(str));
3791 RB_GC_GUARD(str);
3792
3793 if (n < 0) {
3794 int e = errno;
3795 if (io_again_p(e)) {
3796 if (!ex) {
3797 return sym_wait_writable;
3798 }
3799 else {
3800 rb_readwrite_syserr_fail(RB_IO_WAIT_WRITABLE, e, "write would block");
3801 }
3802 }
3803 rb_syserr_fail_path(e, fptr->pathv);
3804 }
3805
3806 return LEN2NUM(n);
3807}
3808
3809/*
3810 * call-seq:
3811 * read(maxlen = nil, out_string = nil) -> new_string, out_string, or nil
3812 *
3813 * Reads bytes from the stream; the stream must be opened for reading
3814 * (see {Access Modes}[rdoc-ref:File@Access+Modes]):
3815 *
3816 * - If +maxlen+ is +nil+, reads all bytes using the stream's data mode.
3817 * - Otherwise reads up to +maxlen+ bytes in binary mode.
3818 *
3819 * Returns a string (either a new string or the given +out_string+)
3820 * containing the bytes read.
3821 * The encoding of the string depends on both +maxLen+ and +out_string+:
3822 *
3823 * - +maxlen+ is +nil+: uses internal encoding of +self+
3824 * (regardless of whether +out_string+ was given).
3825 * - +maxlen+ not +nil+:
3826 *
3827 * - +out_string+ given: encoding of +out_string+ not modified.
3828 * - +out_string+ not given: ASCII-8BIT is used.
3829 *
3830 * <b>Without Argument +out_string+</b>
3831 *
3832 * When argument +out_string+ is omitted,
3833 * the returned value is a new string:
3834 *
3835 * f = File.new('t.txt')
3836 * f.read
3837 * # => "First line\nSecond line\n\nFourth line\nFifth line\n"
3838 * f.rewind
3839 * f.read(30) # => "First line\r\nSecond line\r\n\r\nFou"
3840 * f.read(30) # => "rth line\r\nFifth line\r\n"
3841 * f.read(30) # => nil
3842 * f.close
3843 *
3844 * If +maxlen+ is zero, returns an empty string.
3845 *
3846 * <b> With Argument +out_string+</b>
3847 *
3848 * When argument +out_string+ is given,
3849 * the returned value is +out_string+, whose content is replaced:
3850 *
3851 * f = File.new('t.txt')
3852 * s = 'foo' # => "foo"
3853 * f.read(nil, s) # => "First line\nSecond line\n\nFourth line\nFifth line\n"
3854 * s # => "First line\nSecond line\n\nFourth line\nFifth line\n"
3855 * f.rewind
3856 * s = 'bar'
3857 * f.read(30, s) # => "First line\r\nSecond line\r\n\r\nFou"
3858 * s # => "First line\r\nSecond line\r\n\r\nFou"
3859 * s = 'baz'
3860 * f.read(30, s) # => "rth line\r\nFifth line\r\n"
3861 * s # => "rth line\r\nFifth line\r\n"
3862 * s = 'bat'
3863 * f.read(30, s) # => nil
3864 * s # => ""
3865 * f.close
3866 *
3867 * Note that this method behaves like the fread() function in C.
3868 * This means it retries to invoke read(2) system calls to read data
3869 * with the specified maxlen (or until EOF).
3870 *
3871 * This behavior is preserved even if the stream is in non-blocking mode.
3872 * (This method is non-blocking-flag insensitive as other methods.)
3873 *
3874 * If you need the behavior like a single read(2) system call,
3875 * consider #readpartial, #read_nonblock, and #sysread.
3876 *
3877 * Related: IO#write.
3878 */
3879
3880static VALUE
3881io_read(int argc, VALUE *argv, VALUE io)
3882{
3883 rb_io_t *fptr;
3884 rb_len_t n, len;
3885 VALUE length, str;
3886 int shrinkable;
3887#if RUBY_CRLF_ENVIRONMENT
3888 int previous_mode;
3889#endif
3890
3891 rb_scan_args(argc, argv, "02", &length, &str);
3892
3893 if (NIL_P(length)) {
3894 GetOpenFile(io, fptr);
3896 return read_all(fptr, remain_size(fptr), str);
3897 }
3898 len = NUM2LEN(length);
3899 if (len < 0) {
3900 rb_raise(rb_eArgError, "negative length %"PRIdLEN" given", len);
3901 }
3902
3903 shrinkable = io_setstrbuf(&str,len);
3904
3905 GetOpenFile(io, fptr);
3907 if (len == 0) {
3908 io_set_read_length(str, 0, shrinkable);
3909 return str;
3910 }
3911
3912 READ_CHECK(fptr);
3913#if RUBY_CRLF_ENVIRONMENT
3914 previous_mode = set_binary_mode_with_seek_cur(fptr);
3915#endif
3916 n = io_fread(str, 0, len, fptr);
3917 io_set_read_length(str, n, shrinkable);
3918#if RUBY_CRLF_ENVIRONMENT
3919 if (previous_mode == O_TEXT) {
3920 setmode(fptr->fd, O_TEXT);
3921 }
3922#endif
3923 if (n == 0) return Qnil;
3924
3925 return str;
3926}
3927
3928static void
3929rscheck(const char *rsptr, rb_len_t rslen, VALUE rs)
3930{
3931 if (!rs) return;
3932 if (RSTRING_PTR(rs) != rsptr && RSTRING_LEN(rs) != rslen)
3933 rb_raise(rb_eRuntimeError, "rs modified");
3934}
3935
3936static const char *
3937search_delim(const char *p, rb_len_t len, int delim, rb_encoding *enc)
3938{
3939 if (delim < 0) return NULL;
3940 if (rb_enc_mbminlen(enc) == 1) {
3941 p = memchr(p, delim, len);
3942 if (p) return p + 1;
3943 }
3944 else {
3945 const char *end = p + len;
3946 while (p < end) {
3947 int r = rb_enc_precise_mbclen(p, end, enc);
3948 if (!MBCLEN_CHARFOUND_P(r)) {
3949 p += rb_enc_mbminlen(enc);
3950 continue;
3951 }
3952 int n = MBCLEN_CHARFOUND_LEN(r);
3953 if (rb_enc_mbc_to_codepoint(p, end, enc) == (unsigned int)delim) {
3954 return p + n;
3955 }
3956 p += n;
3957 }
3958 }
3959 return NULL;
3960}
3961
3962static int
3963read_raw_character(rb_io_t *fptr, rb_encoding *enc, char *buf)
3964{
3965 int n = 0;
3966 int r;
3967
3968 do {
3969 if (!READ_DATA_PENDING(fptr)) {
3970 READ_CHECK(fptr);
3971 if (io_fillbuf(fptr) < 0) break;
3972 }
3973 buf[n++] = *READ_DATA_PENDING_PTR(fptr);
3974 fptr->rbuf.off++;
3975 fptr->rbuf.len--;
3976 r = rb_enc_precise_mbclen(buf, buf + n, enc);
3977 } while (MBCLEN_NEEDMORE_P(r) && n < rb_enc_mbmaxlen(enc));
3978
3979 return n;
3980}
3981
3982static void
3983unread_raw_character(rb_io_t *fptr, const char *buf, int len)
3984{
3985 if (fptr->rbuf.capa - fptr->rbuf.len < len) {
3986 if (fptr->rbuf.capa > INT_MAX - len)
3987 rb_raise(rb_eIOError, "ungetbyte failed");
3988 fptr->rbuf.capa += len;
3989 REALLOC_N(fptr->rbuf.ptr, char, fptr->rbuf.capa);
3990 }
3991 io_ungetbyte(rb_str_new(buf, len), fptr);
3992}
3993
3994static const char *
3995search_wide_delim(const char *p, long len, const char *delim, int width)
3996{
3997 const char *e = p + len;
3998 int index = 0;
3999
4000 while (index < width && delim[index] == 0) index++;
4001 if (index == width) index = 0;
4002
4003 const char *candidate = p + index;
4004 while (candidate < e) {
4005 candidate = memchr(candidate, (unsigned char)delim[index], e - candidate);
4006 if (candidate == NULL) break;
4007 const char *start = candidate - index;
4008 if ((start - p) % width == 0 && start + width <= e &&
4009 memcmp(start, delim, width) == 0) {
4010 return start;
4011 }
4012 candidate++;
4013 }
4014 return NULL;
4015}
4016
4017static int
4018appendline(rb_io_t *fptr, int delim, VALUE *strp, rb_len_t *lp, rb_encoding *enc)
4019{
4020 VALUE str = *strp;
4021 rb_len_t limit = *lp;
4022
4023 if (NEED_READCONV(fptr)) {
4024 SET_BINARY_MODE(fptr);
4025 make_readconv(fptr, 0);
4026 do {
4027 const char *p, *e;
4028 int searchlen = READ_CHAR_PENDING_COUNT(fptr);
4029 if (searchlen) {
4030 p = READ_CHAR_PENDING_PTR(fptr);
4031 if (0 < limit && limit < searchlen)
4032 searchlen = (int)limit;
4033 e = search_delim(p, searchlen, delim, enc);
4034 if (e) {
4035 int len = (int)(e-p);
4036 if (NIL_P(str))
4037 *strp = str = rb_str_new(p, len);
4038 else
4039 rb_str_buf_cat(str, p, len);
4040 fptr->cbuf.off += len;
4041 fptr->cbuf.len -= len;
4042 limit -= len;
4043 *lp = limit;
4044 return delim;
4045 }
4046
4047 if (NIL_P(str))
4048 *strp = str = rb_str_new(p, searchlen);
4049 else
4050 rb_str_buf_cat(str, p, searchlen);
4051 fptr->cbuf.off += searchlen;
4052 fptr->cbuf.len -= searchlen;
4053 limit -= searchlen;
4054
4055 if (limit == 0) {
4056 *lp = limit;
4057 return (unsigned char)RSTRING_PTR(str)[RSTRING_LEN(str)-1];
4058 }
4059 }
4060 } while (more_char(fptr) != MORE_CHAR_FINISHED);
4061 clear_readconv(fptr);
4062 *lp = limit;
4063 return EOF;
4064 }
4065
4066 NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr);
4067 if (rb_enc_mbminlen(enc) != 1) {
4068 char buf[ONIGENC_CODE_TO_MBC_MAXLEN];
4069 int len;
4070
4071 if (limit < 0) {
4072 int width = rb_enc_mbminlen(enc);
4073 int delim_len = rb_enc_codelen(delim, enc);
4074
4075 if (delim_len == width) {
4076 rb_enc_mbcput(delim, buf, enc);
4077 for (;;) {
4078 if (!READ_DATA_PENDING(fptr)) {
4079 READ_CHECK(fptr);
4080 if (io_fillbuf(fptr) < 0) return EOF;
4081 }
4082 long pending = READ_DATA_PENDING_COUNT(fptr);
4083 long complete = pending - pending % width;
4084 const char *p = READ_DATA_PENDING_PTR(fptr);
4085 const char *q = complete ? search_wide_delim(p, complete, buf, width) : NULL;
4086 long take = q ? q - p + width : complete;
4087
4088 if (take > 0) {
4089 if (NIL_P(str))
4090 *strp = str = rb_str_buf_new(0);
4091 rb_str_buf_cat(str, p, take);
4092 fptr->rbuf.off += (int)take;
4093 fptr->rbuf.len -= (int)take;
4094 }
4095 if (q) return delim;
4096 if (complete == pending) continue;
4097
4098 len = read_raw_character(fptr, enc, buf);
4099 if (len == 0) return EOF;
4100 if (NIL_P(str))
4101 *strp = str = rb_str_buf_new(0);
4102 rb_str_buf_cat(str, buf, len);
4103 int r = rb_enc_precise_mbclen(buf, buf + len, enc);
4104 if (MBCLEN_CHARFOUND_P(r) &&
4105 rb_enc_mbc_to_codepoint(buf, buf + len, enc) == (unsigned int)delim)
4106 return delim;
4107 }
4108 }
4109 }
4110
4111 while ((len = read_raw_character(fptr, enc, buf)) > 0) {
4112 if (NIL_P(str))
4113 *strp = str = rb_str_buf_new(0);
4114 rb_str_buf_cat(str, buf, len);
4115 if (limit > 0) {
4116 if (len > limit) {
4117 *lp = 0;
4118 return (unsigned char)buf[len - 1];
4119 }
4120 *lp = limit -= len;
4121 }
4122 int r = rb_enc_precise_mbclen(buf, buf + len, enc);
4123 if (MBCLEN_CHARFOUND_P(r) &&
4124 rb_enc_mbc_to_codepoint(buf, buf + len, enc) == (unsigned int)delim)
4125 return delim;
4126 if (limit == 0)
4127 return (unsigned char)buf[len - 1];
4128 }
4129 *lp = limit;
4130 return EOF;
4131 }
4132 do {
4133 rb_len_t pending = READ_DATA_PENDING_COUNT(fptr);
4134 if (pending > 0) {
4135 const char *p = READ_DATA_PENDING_PTR(fptr);
4136 const char *e;
4137 rb_len_t last;
4138
4139 if (limit > 0 && pending > limit) pending = limit;
4140 e = search_delim(p, pending, delim, enc);
4141 if (e) pending = e - p;
4142 if (!NIL_P(str)) {
4143 last = RSTRING_LEN(str);
4144 rb_str_resize(str, last + pending);
4145 }
4146 else {
4147 last = 0;
4148 *strp = str = rb_str_buf_new(pending);
4149 rb_str_set_len(str, pending);
4150 }
4151 read_buffered_data(RSTRING_PTR(str) + last, pending, fptr); /* must not fail */
4152 limit -= pending;
4153 *lp = limit;
4154 if (e) return delim;
4155 if (limit == 0)
4156 return (unsigned char)RSTRING_PTR(str)[RSTRING_LEN(str)-1];
4157 }
4158 READ_CHECK(fptr);
4159 } while (io_fillbuf(fptr) >= 0);
4160 *lp = limit;
4161 return EOF;
4162}
4163
4164static inline int
4165swallow(rb_io_t *fptr, int term)
4166{
4167 if (NEED_READCONV(fptr)) {
4168 rb_encoding *enc = io_read_encoding(fptr);
4169 int needconv = rb_enc_mbminlen(enc) != 1;
4170 SET_BINARY_MODE(fptr);
4171 make_readconv(fptr, 0);
4172 do {
4173 size_t cnt;
4174 while ((cnt = READ_CHAR_PENDING_COUNT(fptr)) > 0) {
4175 const char *p = READ_CHAR_PENDING_PTR(fptr);
4176 int i;
4177 if (!needconv) {
4178 if (*p != term) return TRUE;
4179 i = (int)cnt;
4180 while (--i && *++p == term);
4181 }
4182 else {
4183 const char *e = p + cnt;
4184 if (rb_enc_ascget(p, e, &i, enc) != term) return TRUE;
4185 while ((p += i) < e && rb_enc_ascget(p, e, &i, enc) == term);
4186 i = (int)(e - p);
4187 }
4188 io_shift_cbuf(fptr, (int)cnt - i, NULL);
4189 }
4190 } while (more_char(fptr) != MORE_CHAR_FINISHED);
4191 return FALSE;
4192 }
4193
4194 NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr);
4195 rb_encoding *enc = io_read_encoding(fptr);
4196 int widechar = rb_enc_mbminlen(enc) != 1;
4197 if (widechar) {
4198 char buf[ONIGENC_CODE_TO_MBC_MAXLEN];
4199 int len;
4200
4201 while ((len = read_raw_character(fptr, enc, buf)) > 0) {
4202 if (rb_enc_ascget(buf, buf + len, NULL, enc) != term) {
4203 unread_raw_character(fptr, buf, len);
4204 return TRUE;
4205 }
4206 }
4207 return FALSE;
4208 }
4209 do {
4210 size_t cnt;
4211 while ((cnt = READ_DATA_PENDING_COUNT(fptr)) > 0) {
4212 char buf[1024];
4213 const char *p = READ_DATA_PENDING_PTR(fptr);
4214 int i;
4215 if (cnt > sizeof buf) cnt = sizeof buf;
4216 if (*p != term) return TRUE;
4217 i = (int)cnt;
4218 while (--i && *++p == term);
4219 if (!read_buffered_data(buf, cnt - i, fptr)) /* must not fail */
4220 rb_sys_fail_path(fptr->pathv);
4221 }
4222 READ_CHECK(fptr);
4223 } while (io_fillbuf(fptr) == 0);
4224 return FALSE;
4225}
4226
4227static VALUE
4228rb_io_getline_fast(rb_io_t *fptr, rb_encoding *enc, int chomp)
4229{
4230 VALUE str = Qnil;
4231 rb_len_t len = 0;
4232 rb_len_t pos = 0;
4233 int cr = 0;
4234
4235 do {
4236 int pending = READ_DATA_PENDING_COUNT(fptr);
4237
4238 if (pending > 0) {
4239 const char *p = READ_DATA_PENDING_PTR(fptr);
4240 const char *e;
4241 int chomplen = 0;
4242
4243 e = memchr(p, '\n', pending);
4244 if (e) {
4245 pending = (int)(e - p + 1);
4246 if (chomp) {
4247 chomplen = (pending > 1 && *(e-1) == '\r') + 1;
4248 }
4249 }
4250 if (NIL_P(str)) {
4251 str = rb_str_new(p, pending - chomplen);
4252 fptr->rbuf.off += pending;
4253 fptr->rbuf.len -= pending;
4254 }
4255 else {
4256 rb_str_resize(str, len + pending - chomplen);
4257 read_buffered_data(RSTRING_PTR(str)+len, pending - chomplen, fptr);
4258 fptr->rbuf.off += chomplen;
4259 fptr->rbuf.len -= chomplen;
4260 if (pending == 1 && chomplen == 1 && len > 0) {
4261 if (RSTRING_PTR(str)[len-1] == '\r') {
4262 rb_str_resize(str, --len);
4263 break;
4264 }
4265 }
4266 }
4267 len += pending - chomplen;
4268 if (cr != ENC_CODERANGE_BROKEN)
4269 pos += rb_str_coderange_scan_restartable(RSTRING_PTR(str) + pos, RSTRING_PTR(str) + len, enc, &cr);
4270 if (e) break;
4271 }
4272 READ_CHECK(fptr);
4273 } while (io_fillbuf(fptr) >= 0);
4274 if (NIL_P(str)) return Qnil;
4275
4276 str = io_enc_str(str, fptr);
4277 ENC_CODERANGE_SET(str, cr);
4278 fptr->lineno++;
4279
4280 return str;
4281}
4282
4284 VALUE io;
4285 VALUE rs;
4286 rb_len_t limit;
4287 unsigned int chomp: 1;
4288};
4289
4290static void
4291extract_getline_opts(VALUE opts, struct getline_arg *args)
4292{
4293 int chomp = FALSE;
4294 if (!NIL_P(opts)) {
4295 static ID kwds[1];
4296 VALUE vchomp;
4297 if (!kwds[0]) {
4298 kwds[0] = rb_intern_const("chomp");
4299 }
4300 rb_get_kwargs(opts, kwds, 0, -2, &vchomp);
4301 chomp = (!UNDEF_P(vchomp)) && RTEST(vchomp);
4302 }
4303 args->chomp = chomp;
4304}
4305
4306static void
4307extract_getline_args(int argc, VALUE *argv, struct getline_arg *args)
4308{
4309 VALUE rs = rb_rs, lim = Qnil;
4310
4311 if (argc == 1) {
4312 VALUE tmp = Qnil;
4313
4314 if (NIL_P(argv[0]) || !NIL_P(tmp = rb_check_string_type(argv[0]))) {
4315 rs = tmp;
4316 }
4317 else {
4318 lim = argv[0];
4319 }
4320 }
4321 else if (2 <= argc) {
4322 rs = argv[0], lim = argv[1];
4323 if (!NIL_P(rs))
4324 StringValue(rs);
4325 }
4326 args->rs = rs;
4327 args->limit = NIL_P(lim) ? -1L : NUM2LEN(lim);
4328}
4329
4330static void
4331check_getline_args(VALUE *rsp, rb_len_t *limit, VALUE io)
4332{
4333 rb_io_t *fptr;
4334 VALUE rs = *rsp;
4335
4336 if (!NIL_P(rs)) {
4337 rb_encoding *enc_rs, *enc_io;
4338
4339 GetOpenFile(io, fptr);
4340 enc_rs = rb_enc_get(rs);
4341 enc_io = io_read_encoding(fptr);
4342 if (enc_io != enc_rs &&
4343 (!is_ascii_string(rs) ||
4344 (RSTRING_LEN(rs) > 0 && !rb_enc_asciicompat(enc_io)))) {
4345 if (rs == rb_default_rs) {
4346 rs = rb_enc_str_new(0, 0, enc_io);
4347 rb_str_buf_cat_ascii(rs, "\n");
4348 *rsp = rs;
4349 }
4350 else {
4351 rb_raise(rb_eArgError, "encoding mismatch: %s IO with %s RS",
4352 rb_enc_name(enc_io),
4353 rb_enc_name(enc_rs));
4354 }
4355 }
4356 }
4357}
4358
4359static void
4360prepare_getline_args(int argc, VALUE *argv, struct getline_arg *args, VALUE io)
4361{
4362 VALUE opts;
4363 argc = rb_scan_args(argc, argv, "02:", NULL, NULL, &opts);
4364 extract_getline_args(argc, argv, args);
4365 extract_getline_opts(opts, args);
4366 check_getline_args(&args->rs, &args->limit, io);
4367}
4368
4369static VALUE
4370rb_io_getline_0(VALUE rs, rb_len_t limit, int chomp, rb_io_t *fptr)
4371{
4372 VALUE str = Qnil;
4373 int nolimit = 0;
4374 rb_encoding *enc;
4375
4377 if (NIL_P(rs) && limit < 0) {
4378 str = read_all(fptr, 0, Qnil);
4379 if (RSTRING_LEN(str) == 0) return Qnil;
4380 }
4381 else if (limit == 0) {
4382 return rb_enc_str_new(0, 0, io_read_encoding(fptr));
4383 }
4384 else if (rs == rb_default_rs && limit < 0 && !NEED_READCONV(fptr) &&
4385 rb_enc_asciicompat(enc = io_read_encoding(fptr))) {
4386 NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr);
4387 return rb_io_getline_fast(fptr, enc, chomp);
4388 }
4389 else {
4390 int c, newline = -1;
4391 const char *rsptr = 0;
4392 rb_len_t rslen = 0;
4393 int rspara = 0;
4394 int extra_limit = 16;
4395 int chomp_cr = chomp;
4396
4397 SET_BINARY_MODE(fptr);
4398 enc = io_read_encoding(fptr);
4399
4400 if (!NIL_P(rs)) {
4401 rslen = RSTRING_LEN(rs);
4402 if (rslen == 0) {
4403 rsptr = "\n\n";
4404 rslen = 2;
4405 rspara = 1;
4406 swallow(fptr, '\n');
4407 rs = 0;
4408 if (!rb_enc_asciicompat(enc)) {
4409 rs = rb_usascii_str_new(rsptr, rslen);
4410 rs = rb_str_conv_enc(rs, 0, enc);
4411 OBJ_FREEZE(rs);
4412 rsptr = RSTRING_PTR(rs);
4413 rslen = RSTRING_LEN(rs);
4414 }
4415 newline = '\n';
4416 }
4417 else if (rb_enc_mbminlen(enc) == 1) {
4418 rsptr = RSTRING_PTR(rs);
4419 newline = (unsigned char)rsptr[rslen - 1];
4420 }
4421 else {
4422 rs = rb_str_conv_enc(rs, 0, enc);
4423 rsptr = RSTRING_PTR(rs);
4424 const char *e = rsptr + rslen;
4425 const char *last = rb_enc_prev_char(rsptr, e, e, enc);
4426 int n;
4427 newline = rb_enc_codepoint_len(last, e, &n, enc);
4428 if (last + n != e) rb_raise(rb_eArgError, "broken separator");
4429 }
4430 chomp_cr = chomp && newline == '\n' && rslen == rb_enc_mbminlen(enc);
4431 }
4432
4433 /* MS - Optimization */
4434 while ((c = appendline(fptr, newline, &str, &limit, enc)) != EOF) {
4435 const char *s, *p, *pp, *e;
4436
4437 if (c == newline && RSTRING_LEN(str) >= rslen) {
4438 s = RSTRING_PTR(str);
4439 e = RSTRING_END(str);
4440 p = e - rslen;
4441 if (at_char_boundary(s, p, e, enc)) {
4442 if (!rspara) rscheck(rsptr, rslen, rs);
4443 if (memcmp(p, rsptr, rslen) == 0) {
4444 if (chomp) {
4445 if (chomp_cr && p > s && *(p-1) == '\r') --p;
4446 rb_str_set_len(str, p - s);
4447 }
4448 break;
4449 }
4450 }
4451 }
4452 if (limit == 0) {
4453 s = RSTRING_PTR(str);
4454 p = RSTRING_END(str);
4455 pp = rb_enc_prev_char(s, p, p, enc);
4456 if (extra_limit && pp &&
4457 MBCLEN_NEEDMORE_P(rb_enc_precise_mbclen(pp, p, enc))) {
4458 /* relax the limit while incomplete character.
4459 * extra_limit limits the relax length */
4460 limit = 1;
4461 extra_limit--;
4462 }
4463 else {
4464 nolimit = 1;
4465 break;
4466 }
4467 }
4468 }
4469
4470 if (rspara && c != EOF)
4471 swallow(fptr, '\n');
4472 if (!NIL_P(str))
4473 str = io_enc_str(str, fptr);
4474 }
4475
4476 if (!NIL_P(str) && !nolimit) {
4477 fptr->lineno++;
4478 }
4479
4480 return str;
4481}
4482
4483static VALUE
4484rb_io_getline_1(VALUE rs, rb_len_t limit, int chomp, VALUE io)
4485{
4486 rb_io_t *fptr;
4487 int old_lineno, new_lineno;
4488 VALUE str;
4489
4490 GetOpenFile(io, fptr);
4491 old_lineno = fptr->lineno;
4492 str = rb_io_getline_0(rs, limit, chomp, fptr);
4493 if (!NIL_P(str) && (new_lineno = fptr->lineno) != old_lineno) {
4494 if (io == ARGF.current_file) {
4495 ARGF.lineno += new_lineno - old_lineno;
4496 ARGF.last_lineno = ARGF.lineno;
4497 }
4498 else {
4499 ARGF.last_lineno = new_lineno;
4500 }
4501 }
4502
4503 return str;
4504}
4505
4506static VALUE
4507rb_io_getline(int argc, VALUE *argv, VALUE io)
4508{
4509 struct getline_arg args;
4510
4511 prepare_getline_args(argc, argv, &args, io);
4512 return rb_io_getline_1(args.rs, args.limit, args.chomp, io);
4513}
4514
4515VALUE
4517{
4518 return rb_io_getline_1(rb_default_rs, -1, FALSE, io);
4519}
4520
4521VALUE
4522rb_io_gets_limit_internal(VALUE io, rb_len_t limit)
4523{
4524 rb_io_t *fptr;
4525 GetOpenFile(io, fptr);
4526 return rb_io_getline_0(rb_default_rs, limit, FALSE, fptr);
4527}
4528
4529VALUE
4530rb_io_gets_internal(VALUE io)
4531{
4532 return rb_io_gets_limit_internal(io, -1);
4533}
4534
4535/*
4536 * call-seq:
4537 * gets(sep = $/, chomp: false) -> string or nil
4538 * gets(limit, chomp: false) -> string or nil
4539 * gets(sep, limit, chomp: false) -> string or nil
4540 *
4541 * Reads and returns a line from the stream;
4542 * assigns the return value to <tt>$_</tt>.
4543 * See {Line IO}[rdoc-ref:IO@Line+IO].
4544 *
4545 * With no arguments given, returns the next line
4546 * as determined by line separator <tt>$/</tt>, or +nil+ if none:
4547 *
4548 * f = File.open('t.txt')
4549 * f.gets # => "First line\n"
4550 * $_ # => "First line\n"
4551 * f.gets # => "\n"
4552 * f.gets # => "Fourth line\n"
4553 * f.gets # => "Fifth line\n"
4554 * f.gets # => nil
4555 * f.close
4556 *
4557 * With only string argument +sep+ given,
4558 * returns the next line as determined by line separator +sep+,
4559 * or +nil+ if none;
4560 * see {Line Separator}[rdoc-ref:IO@Line+Separator]:
4561 *
4562 * f = File.new('t.txt')
4563 * f.gets('l') # => "First l"
4564 * f.gets('li') # => "ine\nSecond li"
4565 * f.gets('lin') # => "ne\n\nFourth lin"
4566 * f.gets # => "e\n"
4567 * f.close
4568 *
4569 * The two special values for +sep+ are honored:
4570 *
4571 * f = File.new('t.txt')
4572 * # Get all.
4573 * f.gets(nil) # => "First line\nSecond line\n\nFourth line\nFifth line\n"
4574 * f.rewind
4575 * # Get paragraph (up to two line separators).
4576 * f.gets('') # => "First line\nSecond line\n\n"
4577 * f.close
4578 *
4579 * With only integer argument +limit+ given,
4580 * limits the number of bytes in the line;
4581 * see {Line Limit}[rdoc-ref:IO@Line+Limit]:
4582 *
4583 * # No more than one line.
4584 * File.open('t.txt') {|f| f.gets(10) } # => "First line"
4585 * File.open('t.txt') {|f| f.gets(11) } # => "First line\n"
4586 * File.open('t.txt') {|f| f.gets(12) } # => "First line\n"
4587 *
4588 * With arguments +sep+ and +limit+ given,
4589 * combines the two behaviors
4590 * (see {Line Separator and Line Limit}[rdoc-ref:IO@Line+Separator+and+Line+Limit]).
4591 *
4592 * Optional keyword argument +chomp+ specifies whether line separators
4593 * are to be omitted:
4594 *
4595 * f = File.open('t.txt')
4596 * # Chomp the lines.
4597 * f.gets(chomp: true) # => "First line"
4598 * f.gets(chomp: true) # => "Second line"
4599 * f.gets(chomp: true) # => ""
4600 * f.gets(chomp: true) # => "Fourth line"
4601 * f.gets(chomp: true) # => "Fifth line"
4602 * f.gets(chomp: true) # => nil
4603 * f.close
4604 *
4605 */
4606
4607static VALUE
4608rb_io_gets_m(int argc, VALUE *argv, VALUE io)
4609{
4610 VALUE str;
4611
4612 str = rb_io_getline(argc, argv, io);
4613 rb_lastline_set(str);
4614
4615 return str;
4616}
4617
4618/*
4619 * call-seq:
4620 * lineno -> integer
4621 *
4622 * Returns the current line number for the stream;
4623 * see {Line Number}[rdoc-ref:IO@Line+Number].
4624 *
4625 */
4626
4627static VALUE
4628rb_io_lineno(VALUE io)
4629{
4630 rb_io_t *fptr;
4631
4632 GetOpenFile(io, fptr);
4634 return INT2NUM(fptr->lineno);
4635}
4636
4637/*
4638 * call-seq:
4639 * lineno = integer -> integer
4640 *
4641 * Sets and returns the line number for the stream;
4642 * see {Line Number}[rdoc-ref:IO@Line+Number].
4643 *
4644 */
4645
4646static VALUE
4647rb_io_set_lineno(VALUE io, VALUE lineno)
4648{
4649 rb_io_t *fptr;
4650
4651 GetOpenFile(io, fptr);
4653 fptr->lineno = NUM2INT(lineno);
4654 return lineno;
4655}
4656
4657/* :nodoc: */
4658static VALUE
4659io_readline(rb_execution_context_t *ec, VALUE io, VALUE sep, VALUE lim, VALUE chomp)
4660{
4661 rb_len_t limit = -1;
4662 if (NIL_P(lim)) {
4663 VALUE tmp = Qnil;
4664 // If sep is specified, but it's not a string and not nil, then assume
4665 // it's the limit (it should be an integer)
4666 if (!NIL_P(sep) && NIL_P(tmp = rb_check_string_type(sep))) {
4667 // If the user has specified a non-nil / non-string value
4668 // for the separator, we assume it's the limit and set the
4669 // separator to default: rb_rs.
4670 lim = sep;
4671 limit = NUM2LEN(lim);
4672 sep = rb_rs;
4673 }
4674 else {
4675 sep = tmp;
4676 }
4677 }
4678 else {
4679 if (!NIL_P(sep)) StringValue(sep);
4680 limit = NUM2LEN(lim);
4681 }
4682
4683 check_getline_args(&sep, &limit, io);
4684
4685 VALUE line = rb_io_getline_1(sep, limit, RTEST(chomp), io);
4686 rb_lastline_set_up(line, 1);
4687
4688 if (NIL_P(line)) {
4689 rb_eof_error();
4690 }
4691 return line;
4692}
4693
4694static VALUE io_readlines(const struct getline_arg *arg, VALUE io);
4695
4696/*
4697 * call-seq:
4698 * readlines(sep = $/, chomp: false) -> array
4699 * readlines(limit, chomp: false) -> array
4700 * readlines(sep, limit, chomp: false) -> array
4701 *
4702 * Reads and returns all remaining line from the stream;
4703 * does not modify <tt>$_</tt>.
4704 * See {Line IO}[rdoc-ref:IO@Line+IO].
4705 *
4706 * With no arguments given, returns lines
4707 * as determined by line separator <tt>$/</tt>, or +nil+ if none:
4708 *
4709 * f = File.new('t.txt')
4710 * f.readlines
4711 * # => ["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"]
4712 * f.readlines # => []
4713 * f.close
4714 *
4715 * With only string argument +sep+ given,
4716 * returns lines as determined by line separator +sep+,
4717 * or +nil+ if none;
4718 * see {Line Separator}[rdoc-ref:IO@Line+Separator]:
4719 *
4720 * f = File.new('t.txt')
4721 * f.readlines('li')
4722 * # => ["First li", "ne\nSecond li", "ne\n\nFourth li", "ne\nFifth li", "ne\n"]
4723 * f.close
4724 *
4725 * The two special values for +sep+ are honored:
4726 *
4727 * f = File.new('t.txt')
4728 * # Get all into one string.
4729 * f.readlines(nil)
4730 * # => ["First line\nSecond line\n\nFourth line\nFifth line\n"]
4731 * # Get paragraphs (up to two line separators).
4732 * f.rewind
4733 * f.readlines('')
4734 * # => ["First line\nSecond line\n\n", "Fourth line\nFifth line\n"]
4735 * f.close
4736 *
4737 * With only integer argument +limit+ given,
4738 * limits the number of bytes in each line;
4739 * see {Line Limit}[rdoc-ref:IO@Line+Limit]:
4740 *
4741 * f = File.new('t.txt')
4742 * f.readlines(8)
4743 * # => ["First li", "ne\n", "Second l", "ine\n", "\n", "Fourth l", "ine\n", "Fifth li", "ne\n"]
4744 * f.close
4745 *
4746 * With arguments +sep+ and +limit+ given,
4747 * combines the two behaviors
4748 * (see {Line Separator and Line Limit}[rdoc-ref:IO@Line+Separator+and+Line+Limit]).
4749 *
4750 * Optional keyword argument +chomp+ specifies whether line separators
4751 * are to be omitted:
4752 *
4753 * f = File.new('t.txt')
4754 * f.readlines(chomp: true)
4755 * # => ["First line", "Second line", "", "Fourth line", "Fifth line"]
4756 * f.close
4757 *
4758 */
4759
4760static VALUE
4761rb_io_readlines(int argc, VALUE *argv, VALUE io)
4762{
4763 struct getline_arg args;
4764
4765 prepare_getline_args(argc, argv, &args, io);
4766 return io_readlines(&args, io);
4767}
4768
4769static VALUE
4770io_readlines(const struct getline_arg *arg, VALUE io)
4771{
4772 VALUE line, ary;
4773
4774 if (arg->limit == 0)
4775 rb_raise(rb_eArgError, "invalid limit: 0 for readlines");
4776 ary = rb_ary_new();
4777 while (!NIL_P(line = rb_io_getline_1(arg->rs, arg->limit, arg->chomp, io))) {
4778 rb_ary_push(ary, line);
4779 }
4780 return ary;
4781}
4782
4783/*
4784 * call-seq:
4785 * each_line(sep = $/, chomp: false) {|line| ... } -> self
4786 * each_line(limit, chomp: false) {|line| ... } -> self
4787 * each_line(sep, limit, chomp: false) {|line| ... } -> self
4788 * each_line -> enumerator
4789 *
4790 * Calls the block with each remaining line read from the stream;
4791 * returns +self+.
4792 * Does nothing if already at end-of-stream;
4793 * See {Line IO}[rdoc-ref:IO@Line+IO].
4794 *
4795 * With no arguments given, reads lines
4796 * as determined by line separator <tt>$/</tt>:
4797 *
4798 * f = File.new('t.txt')
4799 * f.each_line {|line| p line }
4800 * f.each_line {|line| fail 'Cannot happen' }
4801 * f.close
4802 *
4803 * Output:
4804 *
4805 * "First line\n"
4806 * "Second line\n"
4807 * "\n"
4808 * "Fourth line\n"
4809 * "Fifth line\n"
4810 *
4811 * With only string argument +sep+ given,
4812 * reads lines as determined by line separator +sep+;
4813 * see {Line Separator}[rdoc-ref:IO@Line+Separator]:
4814 *
4815 * f = File.new('t.txt')
4816 * f.each_line('li') {|line| p line }
4817 * f.close
4818 *
4819 * Output:
4820 *
4821 * "First li"
4822 * "ne\nSecond li"
4823 * "ne\n\nFourth li"
4824 * "ne\nFifth li"
4825 * "ne\n"
4826 *
4827 * The two special values for +sep+ are honored:
4828 *
4829 * f = File.new('t.txt')
4830 * # Get all into one string.
4831 * f.each_line(nil) {|line| p line }
4832 * f.close
4833 *
4834 * Output:
4835 *
4836 * "First line\nSecond line\n\nFourth line\nFifth line\n"
4837 *
4838 * f.rewind
4839 * # Get paragraphs (up to two line separators).
4840 * f.each_line('') {|line| p line }
4841 *
4842 * Output:
4843 *
4844 * "First line\nSecond line\n\n"
4845 * "Fourth line\nFifth line\n"
4846 *
4847 * With only integer argument +limit+ given,
4848 * limits the number of bytes in each line;
4849 * see {Line Limit}[rdoc-ref:IO@Line+Limit]:
4850 *
4851 * f = File.new('t.txt')
4852 * f.each_line(8) {|line| p line }
4853 * f.close
4854 *
4855 * Output:
4856 *
4857 * "First li"
4858 * "ne\n"
4859 * "Second l"
4860 * "ine\n"
4861 * "\n"
4862 * "Fourth l"
4863 * "ine\n"
4864 * "Fifth li"
4865 * "ne\n"
4866 *
4867 * With arguments +sep+ and +limit+ given,
4868 * combines the two behaviors
4869 * (see {Line Separator and Line Limit}[rdoc-ref:IO@Line+Separator+and+Line+Limit]).
4870 *
4871 * Optional keyword argument +chomp+ specifies whether line separators
4872 * are to be omitted:
4873 *
4874 * f = File.new('t.txt')
4875 * f.each_line(chomp: true) {|line| p line }
4876 * f.close
4877 *
4878 * Output:
4879 *
4880 * "First line"
4881 * "Second line"
4882 * ""
4883 * "Fourth line"
4884 * "Fifth line"
4885 *
4886 * Returns an Enumerator if no block is given.
4887 */
4888
4889static VALUE
4890rb_io_each_line(int argc, VALUE *argv, VALUE io)
4891{
4892 VALUE str;
4893 struct getline_arg args;
4894
4895 RETURN_ENUMERATOR(io, argc, argv);
4896 prepare_getline_args(argc, argv, &args, io);
4897 if (args.limit == 0)
4898 rb_raise(rb_eArgError, "invalid limit: 0 for each_line");
4899 while (!NIL_P(str = rb_io_getline_1(args.rs, args.limit, args.chomp, io))) {
4900 rb_yield(str);
4901 }
4902 return io;
4903}
4904
4905/*
4906 * call-seq:
4907 * each_byte {|byte| ... } -> self
4908 * each_byte -> enumerator
4909 *
4910 * Calls the given block with each byte (0..255) in the stream; returns +self+.
4911 * See {Byte IO}[rdoc-ref:IO@Byte+IO].
4912 *
4913 * File.read('t.ja') # => "こんにちは"
4914 * f = File.new('t.ja')
4915 * a = []
4916 * f.each_byte {|b| a << b }
4917 * a # => [227, 129, 147, 227, 130, 147, 227, 129, 171, 227, 129, 161, 227, 129, 175]
4918 * f.close
4919 *
4920 * Returns an Enumerator if no block is given.
4921 *
4922 * Related: IO#each_char, IO#each_codepoint.
4923 *
4924 */
4925
4926static VALUE
4927rb_io_each_byte(VALUE io)
4928{
4929 rb_io_t *fptr;
4930
4931 RETURN_ENUMERATOR(io, 0, 0);
4932 GetOpenFile(io, fptr);
4933
4934 do {
4935 while (fptr->rbuf.len > 0) {
4936 char *p = fptr->rbuf.ptr + fptr->rbuf.off++;
4937 fptr->rbuf.len--;
4938 rb_yield(INT2FIX(*p & 0xff));
4940 errno = 0;
4941 }
4942 READ_CHECK(fptr);
4943 } while (io_fillbuf(fptr) >= 0);
4944 return io;
4945}
4946
4947static VALUE
4948io_getc(rb_io_t *fptr, rb_encoding *enc)
4949{
4950 int r, n, cr = 0;
4951 VALUE str;
4952
4953 if (NEED_READCONV(fptr)) {
4954 rb_encoding *read_enc = io_read_encoding(fptr);
4955
4956 str = Qnil;
4957 SET_BINARY_MODE(fptr);
4958 make_readconv(fptr, 0);
4959
4960 while (1) {
4961 if (fptr->cbuf.len) {
4962 r = rb_enc_precise_mbclen(fptr->cbuf.ptr+fptr->cbuf.off,
4963 fptr->cbuf.ptr+fptr->cbuf.off+fptr->cbuf.len,
4964 read_enc);
4965 if (!MBCLEN_NEEDMORE_P(r))
4966 break;
4967 if (fptr->cbuf.len == fptr->cbuf.capa) {
4968 rb_raise(rb_eIOError, "too long character");
4969 }
4970 }
4971
4972 if (more_char(fptr) == MORE_CHAR_FINISHED) {
4973 if (fptr->cbuf.len == 0) {
4974 clear_readconv(fptr);
4975 return Qnil;
4976 }
4977 /* return an unit of an incomplete character just before EOF */
4978 str = rb_enc_str_new(fptr->cbuf.ptr+fptr->cbuf.off, 1, read_enc);
4979 fptr->cbuf.off += 1;
4980 fptr->cbuf.len -= 1;
4981 if (fptr->cbuf.len == 0) clear_readconv(fptr);
4983 return str;
4984 }
4985 }
4986 if (MBCLEN_INVALID_P(r)) {
4987 r = rb_enc_mbclen(fptr->cbuf.ptr+fptr->cbuf.off,
4988 fptr->cbuf.ptr+fptr->cbuf.off+fptr->cbuf.len,
4989 read_enc);
4990 io_shift_cbuf(fptr, r, &str);
4992 }
4993 else {
4994 io_shift_cbuf(fptr, MBCLEN_CHARFOUND_LEN(r), &str);
4996 if (MBCLEN_CHARFOUND_LEN(r) == 1 && rb_enc_asciicompat(read_enc) &&
4997 ISASCII(RSTRING_PTR(str)[0])) {
4998 cr = ENC_CODERANGE_7BIT;
4999 }
5000 }
5001 str = io_enc_str(str, fptr);
5002 ENC_CODERANGE_SET(str, cr);
5003 return str;
5004 }
5005
5006 NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr);
5007 if (io_fillbuf(fptr) < 0) {
5008 return Qnil;
5009 }
5010 if (rb_enc_asciicompat(enc) && ISASCII(fptr->rbuf.ptr[fptr->rbuf.off])) {
5011 str = rb_str_new(fptr->rbuf.ptr+fptr->rbuf.off, 1);
5012 fptr->rbuf.off += 1;
5013 fptr->rbuf.len -= 1;
5014 cr = ENC_CODERANGE_7BIT;
5015 }
5016 else {
5017 r = rb_enc_precise_mbclen(fptr->rbuf.ptr+fptr->rbuf.off, fptr->rbuf.ptr+fptr->rbuf.off+fptr->rbuf.len, enc);
5018 if (MBCLEN_CHARFOUND_P(r) &&
5019 (n = MBCLEN_CHARFOUND_LEN(r)) <= fptr->rbuf.len) {
5020 str = rb_str_new(fptr->rbuf.ptr+fptr->rbuf.off, n);
5021 fptr->rbuf.off += n;
5022 fptr->rbuf.len -= n;
5024 }
5025 else if (MBCLEN_NEEDMORE_P(r)) {
5026 str = rb_str_new(fptr->rbuf.ptr+fptr->rbuf.off, fptr->rbuf.len);
5027 fptr->rbuf.len = 0;
5028 getc_needmore:
5029 if (io_fillbuf(fptr) != -1) {
5030 rb_str_cat(str, fptr->rbuf.ptr+fptr->rbuf.off, 1);
5031 fptr->rbuf.off++;
5032 fptr->rbuf.len--;
5033 r = rb_enc_precise_mbclen(RSTRING_PTR(str), RSTRING_PTR(str)+RSTRING_LEN(str), enc);
5034 if (MBCLEN_NEEDMORE_P(r)) {
5035 goto getc_needmore;
5036 }
5037 else if (MBCLEN_CHARFOUND_P(r)) {
5039 }
5040 }
5041 }
5042 else {
5043 str = rb_str_new(fptr->rbuf.ptr+fptr->rbuf.off, 1);
5044 fptr->rbuf.off++;
5045 fptr->rbuf.len--;
5046 }
5047 }
5048 if (!cr) cr = ENC_CODERANGE_BROKEN;
5049 str = io_enc_str(str, fptr);
5050 ENC_CODERANGE_SET(str, cr);
5051 return str;
5052}
5053
5054/*
5055 * call-seq:
5056 * each_char {|c| ... } -> self
5057 * each_char -> enumerator
5058 *
5059 * Calls the given block with each character in the stream; returns +self+.
5060 * See {Character IO}[rdoc-ref:IO@Character+IO].
5061 *
5062 * File.read('t.ja') # => "こんにちは"
5063 * f = File.new('t.ja')
5064 * a = []
5065 * f.each_char {|c| a << c.ord }
5066 * a # => [12371, 12435, 12395, 12385, 12399]
5067 * f.close
5068 *
5069 * Returns an Enumerator if no block is given.
5070 *
5071 * Related: IO#each_byte, IO#each_codepoint.
5072 *
5073 */
5074
5075static VALUE
5076rb_io_each_char(VALUE io)
5077{
5078 rb_io_t *fptr;
5079 rb_encoding *enc;
5080 VALUE c;
5081
5082 RETURN_ENUMERATOR(io, 0, 0);
5083 GetOpenFile(io, fptr);
5085
5086 enc = io_input_encoding(fptr);
5087 READ_CHECK(fptr);
5088 while (!NIL_P(c = io_getc(fptr, enc))) {
5089 rb_yield(c);
5090 }
5091 return io;
5092}
5093
5094/*
5095 * call-seq:
5096 * each_codepoint {|c| ... } -> self
5097 * each_codepoint -> enumerator
5098 *
5099 * Calls the given block with each codepoint in the stream; returns +self+:
5100 *
5101 * File.read('t.ja') # => "こんにちは"
5102 * f = File.new('t.ja')
5103 * a = []
5104 * f.each_codepoint {|c| a << c }
5105 * a # => [12371, 12435, 12395, 12385, 12399]
5106 * f.close
5107 *
5108 * Returns an Enumerator if no block is given.
5109 *
5110 * Related: IO#each_byte, IO#each_char.
5111 *
5112 */
5113
5114static VALUE
5115rb_io_each_codepoint(VALUE io)
5116{
5117 rb_io_t *fptr;
5118 rb_encoding *enc;
5119 unsigned int c;
5120 int r, n;
5121
5122 RETURN_ENUMERATOR(io, 0, 0);
5123 GetOpenFile(io, fptr);
5125
5126 READ_CHECK(fptr);
5127 enc = io_read_encoding(fptr);
5128 if (NEED_READCONV(fptr)) {
5129 SET_BINARY_MODE(fptr);
5130 r = 1; /* no invalid char yet */
5131 for (;;) {
5132 make_readconv(fptr, 0);
5133 for (;;) {
5134 if (fptr->cbuf.len) {
5135 r = rb_enc_precise_mbclen(fptr->cbuf.ptr+fptr->cbuf.off,
5136 fptr->cbuf.ptr+fptr->cbuf.off+fptr->cbuf.len,
5137 enc);
5138 if (!MBCLEN_NEEDMORE_P(r))
5139 break;
5140 if (fptr->cbuf.len == fptr->cbuf.capa) {
5141 rb_raise(rb_eIOError, "too long character");
5142 }
5143 }
5144 if (more_char(fptr) == MORE_CHAR_FINISHED) {
5145 clear_readconv(fptr);
5146 if (!MBCLEN_CHARFOUND_P(r)) {
5147 goto invalid;
5148 }
5149 return io;
5150 }
5151 }
5152 if (MBCLEN_INVALID_P(r)) {
5153 goto invalid;
5154 }
5155 n = MBCLEN_CHARFOUND_LEN(r);
5156 c = rb_enc_codepoint(fptr->cbuf.ptr+fptr->cbuf.off,
5157 fptr->cbuf.ptr+fptr->cbuf.off+fptr->cbuf.len,
5158 enc);
5159 fptr->cbuf.off += n;
5160 fptr->cbuf.len -= n;
5161 rb_yield(UINT2NUM(c));
5163 }
5164 }
5165 NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr);
5166 while (io_fillbuf(fptr) >= 0) {
5167 r = rb_enc_precise_mbclen(fptr->rbuf.ptr+fptr->rbuf.off,
5168 fptr->rbuf.ptr+fptr->rbuf.off+fptr->rbuf.len, enc);
5169 if (MBCLEN_CHARFOUND_P(r) &&
5170 (n = MBCLEN_CHARFOUND_LEN(r)) <= fptr->rbuf.len) {
5171 c = rb_enc_codepoint(fptr->rbuf.ptr+fptr->rbuf.off,
5172 fptr->rbuf.ptr+fptr->rbuf.off+fptr->rbuf.len, enc);
5173 fptr->rbuf.off += n;
5174 fptr->rbuf.len -= n;
5175 rb_yield(UINT2NUM(c));
5176 }
5177 else if (MBCLEN_INVALID_P(r)) {
5178 goto invalid;
5179 }
5180 else if (MBCLEN_NEEDMORE_P(r)) {
5181 char cbuf[8], *p = cbuf;
5182 int more = MBCLEN_NEEDMORE_LEN(r);
5183 if (more > numberof(cbuf)) goto invalid;
5184 more += n = fptr->rbuf.len;
5185 if (more > numberof(cbuf)) goto invalid;
5186 while ((n = (int)read_buffered_data(p, more, fptr)) > 0 &&
5187 (p += n, (more -= n) > 0)) {
5188 if (io_fillbuf(fptr) < 0) goto invalid;
5189 if ((n = fptr->rbuf.len) > more) n = more;
5190 }
5191 r = rb_enc_precise_mbclen(cbuf, p, enc);
5192 if (!MBCLEN_CHARFOUND_P(r)) goto invalid;
5193 c = rb_enc_codepoint(cbuf, p, enc);
5194 rb_yield(UINT2NUM(c));
5195 }
5196 else {
5197 continue;
5198 }
5200 }
5201 return io;
5202
5203 invalid:
5204 rb_raise(rb_eArgError, "invalid byte sequence in %s", rb_enc_name(enc));
5206}
5207
5208/*
5209 * call-seq:
5210 * getc -> character or nil
5211 *
5212 * Reads and returns the next 1-character string from the stream;
5213 * returns +nil+ if already at end-of-stream.
5214 * See {Character IO}[rdoc-ref:IO@Character+IO].
5215 *
5216 * f = File.open('t.txt')
5217 * f.getc # => "F"
5218 * f.close
5219 * File.read('t.ja') # => "こんにちは"
5220 * f = File.open('t.ja')
5221 * f.getc.ord # => 12371
5222 * f.close
5223 *
5224 * Related: IO#readchar (may raise EOFError).
5225 *
5226 */
5227
5228static VALUE
5229rb_io_getc(VALUE io)
5230{
5231 rb_io_t *fptr;
5232 rb_encoding *enc;
5233
5234 GetOpenFile(io, fptr);
5236
5237 enc = io_input_encoding(fptr);
5238 READ_CHECK(fptr);
5239 return io_getc(fptr, enc);
5240}
5241
5242/*
5243 * call-seq:
5244 * readchar -> string
5245 *
5246 * Reads and returns the next 1-character string from the stream;
5247 * raises EOFError if already at end-of-stream.
5248 * See {Character IO}[rdoc-ref:IO@Character+IO].
5249 *
5250 * f = File.open('t.txt')
5251 * f.readchar # => "F"
5252 * f.close
5253 * File.read('t.ja') # => "こんにちは"
5254 * f = File.open('t.ja')
5255 * f.readchar.ord # => 12371
5256 * f.close
5257 *
5258 * Related: IO#getc (will not raise EOFError).
5259 *
5260 */
5261
5262static VALUE
5263rb_io_readchar(VALUE io)
5264{
5265 VALUE c = rb_io_getc(io);
5266
5267 if (NIL_P(c)) {
5268 rb_eof_error();
5269 }
5270 return c;
5271}
5272
5273/*
5274 * call-seq:
5275 * getbyte -> integer or nil
5276 *
5277 * Reads and returns the next byte (in range 0..255) from the stream;
5278 * returns +nil+ if already at end-of-stream.
5279 * See {Byte IO}[rdoc-ref:IO@Byte+IO].
5280 *
5281 * f = File.open('t.txt')
5282 * f.getbyte # => 70
5283 * f.close
5284 * File.read('t.ja') # => "こんにちは"
5285 * f = File.open('t.ja')
5286 * f.getbyte # => 227
5287 * f.close
5288 *
5289 * Related: IO#readbyte (may raise EOFError).
5290 */
5291
5292VALUE
5294{
5295 rb_io_t *fptr;
5296 int c;
5297
5298 GetOpenFile(io, fptr);
5300 READ_CHECK(fptr);
5301 VALUE r_stdout = rb_ractor_stdout();
5302 if (fptr->fd == 0 && (fptr->mode & FMODE_TTY) && RB_TYPE_P(r_stdout, T_FILE)) {
5303 rb_io_t *ofp;
5304 GetOpenFile(r_stdout, ofp);
5305 if (ofp->mode & FMODE_TTY) {
5306 rb_io_flush(r_stdout);
5307 }
5308 }
5309 if (io_fillbuf(fptr) < 0) {
5310 return Qnil;
5311 }
5312 fptr->rbuf.off++;
5313 fptr->rbuf.len--;
5314 c = (unsigned char)fptr->rbuf.ptr[fptr->rbuf.off-1];
5315 return INT2FIX(c & 0xff);
5316}
5317
5318/*
5319 * call-seq:
5320 * readbyte -> integer
5321 *
5322 * Reads and returns the next byte (in range 0..255) from the stream;
5323 * raises EOFError if already at end-of-stream.
5324 * See {Byte IO}[rdoc-ref:IO@Byte+IO].
5325 *
5326 * f = File.open('t.txt')
5327 * f.readbyte # => 70
5328 * f.close
5329 * File.read('t.ja') # => "こんにちは"
5330 * f = File.open('t.ja')
5331 * f.readbyte # => 227
5332 * f.close
5333 *
5334 * Related: IO#getbyte (will not raise EOFError).
5335 *
5336 */
5337
5338static VALUE
5339rb_io_readbyte(VALUE io)
5340{
5341 VALUE c = rb_io_getbyte(io);
5342
5343 if (NIL_P(c)) {
5344 rb_eof_error();
5345 }
5346 return c;
5347}
5348
5349/*
5350 * call-seq:
5351 * ungetbyte(integer) -> nil
5352 * ungetbyte(string) -> nil
5353 *
5354 * Pushes back ("unshifts") the given data onto the stream's buffer,
5355 * placing the data so that it is next to be read; returns +nil+.
5356 * See {Byte IO}[rdoc-ref:IO@Byte+IO].
5357 *
5358 * Note that:
5359 *
5360 * - Calling the method has no effect with unbuffered reads (such as IO#sysread).
5361 * - Calling #rewind on the stream discards the pushed-back data.
5362 *
5363 * When argument +integer+ is given, uses only its low-order byte:
5364 *
5365 * File.write('t.tmp', '012')
5366 * f = File.open('t.tmp')
5367 * f.ungetbyte(0x41) # => nil
5368 * f.read # => "A012"
5369 * f.rewind
5370 * f.ungetbyte(0x4243) # => nil
5371 * f.read # => "C012"
5372 * f.close
5373 *
5374 * When argument +string+ is given, uses all bytes:
5375 *
5376 * File.write('t.tmp', '012')
5377 * f = File.open('t.tmp')
5378 * f.ungetbyte('A') # => nil
5379 * f.read # => "A012"
5380 * f.rewind
5381 * f.ungetbyte('BCDE') # => nil
5382 * f.read # => "BCDE012"
5383 * f.close
5384 *
5385 */
5386
5387VALUE
5389{
5390 rb_io_t *fptr;
5391
5392 GetOpenFile(io, fptr);
5394 switch (TYPE(b)) {
5395 case T_NIL:
5396 return Qnil;
5397 case T_FIXNUM:
5398 case T_BIGNUM: ;
5399 VALUE v = rb_int_modulo(b, INT2FIX(256));
5400 unsigned char c = NUM2INT(v) & 0xFF;
5401 b = rb_str_new((const char *)&c, 1);
5402 break;
5403 default:
5404 StringValue(b);
5405 }
5406 io_ungetbyte(b, fptr);
5407 return Qnil;
5408}
5409
5410/*
5411 * call-seq:
5412 * ungetc(integer) -> nil
5413 * ungetc(string) -> nil
5414 *
5415 * Pushes back ("unshifts") the given data onto the stream's buffer,
5416 * placing the data so that it is next to be read; returns +nil+.
5417 * See {Character IO}[rdoc-ref:IO@Character+IO].
5418 *
5419 * Note that:
5420 *
5421 * - Calling the method has no effect with unbuffered reads (such as IO#sysread).
5422 * - Calling #rewind on the stream discards the pushed-back data.
5423 *
5424 * When argument +integer+ is given, interprets the integer as a character:
5425 *
5426 * File.write('t.tmp', '012')
5427 * f = File.open('t.tmp')
5428 * f.ungetc(0x41) # => nil
5429 * f.read # => "A012"
5430 * f.rewind
5431 * f.ungetc(0x0442) # => nil
5432 * f.getc.ord # => 1090
5433 * f.close
5434 *
5435 * When argument +string+ is given, uses all characters:
5436 *
5437 * File.write('t.tmp', '012')
5438 * f = File.open('t.tmp')
5439 * f.ungetc('A') # => nil
5440 * f.read # => "A012"
5441 * f.rewind
5442 * f.ungetc("\u0442\u0435\u0441\u0442") # => nil
5443 * f.getc.ord # => 1090
5444 * f.getc.ord # => 1077
5445 * f.getc.ord # => 1089
5446 * f.getc.ord # => 1090
5447 * f.close
5448 *
5449 */
5450
5451VALUE
5453{
5454 rb_io_t *fptr;
5455 rb_len_t len;
5456
5457 GetOpenFile(io, fptr);
5459 if (FIXNUM_P(c)) {
5460 c = rb_enc_uint_chr(FIX2UINT(c), io_read_encoding(fptr));
5461 }
5462 else if (RB_BIGNUM_TYPE_P(c)) {
5463 c = rb_enc_uint_chr(NUM2UINT(c), io_read_encoding(fptr));
5464 }
5465 else {
5466 StringValue(c);
5467 }
5468 if (NEED_READCONV(fptr)) {
5469 SET_BINARY_MODE(fptr);
5470 len = RSTRING_LEN(c);
5471#if SIZEOF_RB_LEN_T > SIZEOF_INT
5472 if (len > INT_MAX)
5473 rb_raise(rb_eIOError, "ungetc failed");
5474#endif
5475 make_readconv(fptr, (int)len);
5476 if (fptr->cbuf.capa - fptr->cbuf.len < len)
5477 rb_raise(rb_eIOError, "ungetc failed");
5478 if (fptr->cbuf.off < len) {
5479 MEMMOVE(fptr->cbuf.ptr+fptr->cbuf.capa-fptr->cbuf.len,
5480 fptr->cbuf.ptr+fptr->cbuf.off,
5481 char, fptr->cbuf.len);
5482 fptr->cbuf.off = fptr->cbuf.capa-fptr->cbuf.len;
5483 }
5484 fptr->cbuf.off -= (int)len;
5485 fptr->cbuf.len += (int)len;
5486 MEMMOVE(fptr->cbuf.ptr+fptr->cbuf.off, RSTRING_PTR(c), char, len);
5487 }
5488 else {
5489 NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr);
5490 io_ungetbyte(c, fptr);
5491 }
5492 return Qnil;
5493}
5494
5495/*
5496 * call-seq:
5497 * isatty -> true or false
5498 *
5499 * Returns +true+ if the stream is associated with a terminal device (tty),
5500 * +false+ otherwise:
5501 *
5502 * f = File.new('t.txt').isatty #=> false
5503 * f.close
5504 * f = File.new('/dev/tty').isatty #=> true
5505 * f.close
5506 *
5507 */
5508
5509static VALUE
5510rb_io_isatty(VALUE io)
5511{
5512 rb_io_t *fptr;
5513
5514 GetOpenFile(io, fptr);
5515 return RBOOL(isatty(fptr->fd) != 0);
5516}
5517
5518#if defined(HAVE_FCNTL) && defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
5519/*
5520 * call-seq:
5521 * close_on_exec? -> true or false
5522 *
5523 * Returns +true+ if the stream will be closed on exec, +false+ otherwise:
5524 *
5525 * f = File.open('t.txt')
5526 * f.close_on_exec? # => true
5527 * f.close_on_exec = false
5528 * f.close_on_exec? # => false
5529 * f.close
5530 *
5531 */
5532
5533static VALUE
5534rb_io_close_on_exec_p(VALUE io)
5535{
5536 rb_io_t *fptr;
5537 VALUE write_io;
5538 int fd, ret;
5539
5540 write_io = GetWriteIO(io);
5541 if (io != write_io) {
5542 GetOpenFile(write_io, fptr);
5543 if (fptr && 0 <= (fd = fptr->fd)) {
5544 if ((ret = fcntl(fd, F_GETFD)) == -1) rb_sys_fail_path(fptr->pathv);
5545 if (!(ret & FD_CLOEXEC)) return Qfalse;
5546 }
5547 }
5548
5549 GetOpenFile(io, fptr);
5550 if (fptr && 0 <= (fd = fptr->fd)) {
5551 if ((ret = fcntl(fd, F_GETFD)) == -1) rb_sys_fail_path(fptr->pathv);
5552 if (!(ret & FD_CLOEXEC)) return Qfalse;
5553 }
5554 return Qtrue;
5555}
5556#else
5557#define rb_io_close_on_exec_p rb_f_notimplement
5558#endif
5559
5560#if defined(HAVE_FCNTL) && defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
5561/*
5562 * call-seq:
5563 * self.close_on_exec = bool -> true or false
5564 *
5565 * Sets a close-on-exec flag.
5566 *
5567 * f = File.open(File::NULL)
5568 * f.close_on_exec = true
5569 * system("cat", "/proc/self/fd/#{f.fileno}") # cat: /proc/self/fd/3: No such file or directory
5570 * f.closed? #=> false
5571 *
5572 * Ruby sets close-on-exec flags of all file descriptors by default
5573 * since Ruby 2.0.0.
5574 * So you don't need to set by yourself.
5575 * Also, unsetting a close-on-exec flag can cause file descriptor leak
5576 * if another thread use fork() and exec() (via system() method for example).
5577 * If you really needs file descriptor inheritance to child process,
5578 * use spawn()'s argument such as fd=>fd.
5579 */
5580
5581static VALUE
5582rb_io_set_close_on_exec(VALUE io, VALUE arg)
5583{
5584 int flag = RTEST(arg) ? FD_CLOEXEC : 0;
5585 rb_io_t *fptr;
5586 VALUE write_io;
5587 int fd, ret;
5588
5589 write_io = GetWriteIO(io);
5590 if (io != write_io) {
5591 GetOpenFile(write_io, fptr);
5592 if (fptr && 0 <= (fd = fptr->fd)) {
5593 if ((ret = fcntl(fptr->fd, F_GETFD)) == -1) rb_sys_fail_path(fptr->pathv);
5594 if ((ret & FD_CLOEXEC) != flag) {
5595 ret = (ret & ~FD_CLOEXEC) | flag;
5596 ret = fcntl(fd, F_SETFD, ret);
5597 if (ret != 0) rb_sys_fail_path(fptr->pathv);
5598 }
5599 }
5600
5601 }
5602
5603 GetOpenFile(io, fptr);
5604 if (fptr && 0 <= (fd = fptr->fd)) {
5605 if ((ret = fcntl(fd, F_GETFD)) == -1) rb_sys_fail_path(fptr->pathv);
5606 if ((ret & FD_CLOEXEC) != flag) {
5607 ret = (ret & ~FD_CLOEXEC) | flag;
5608 ret = fcntl(fd, F_SETFD, ret);
5609 if (ret != 0) rb_sys_fail_path(fptr->pathv);
5610 }
5611 }
5612 return Qnil;
5613}
5614#else
5615#define rb_io_set_close_on_exec rb_f_notimplement
5616#endif
5617
5618#define RUBY_IO_EXTERNAL_P(f) ((f)->mode & FMODE_EXTERNAL)
5619#define PREP_STDIO_NAME(f) (RSTRING_PTR((f)->pathv))
5620
5621static VALUE
5622finish_writeconv(rb_io_t *fptr, int noalloc)
5623{
5624 unsigned char *ds, *dp, *de;
5626
5627 if (!fptr->wbuf.ptr) {
5628 unsigned char buf[1024];
5629
5631 while (res == econv_destination_buffer_full) {
5632 ds = dp = buf;
5633 de = buf + sizeof(buf);
5634 res = rb_econv_convert(fptr->writeconv, NULL, NULL, &dp, de, 0);
5635 while (dp-ds) {
5636 size_t remaining = dp-ds;
5637 rb_len_t result = rb_io_write_memory(fptr, ds, remaining);
5638
5639 if (result > 0) {
5640 ds += result;
5641 if ((size_t)result == remaining) break;
5642 }
5643 else if (rb_io_maybe_wait_writable(errno, fptr->self, RUBY_IO_TIMEOUT_DEFAULT)) {
5644 if (fptr->fd < 0)
5645 return noalloc ? Qtrue : rb_exc_new3(rb_eIOError, rb_str_new_cstr(closed_stream));
5646 }
5647 else {
5648 return noalloc ? Qtrue : INT2NUM(errno);
5649 }
5650 }
5651 if (res == econv_invalid_byte_sequence ||
5652 res == econv_incomplete_input ||
5654 return noalloc ? Qtrue : rb_econv_make_exception(fptr->writeconv);
5655 }
5656 }
5657
5658 return Qnil;
5659 }
5660
5662 while (res == econv_destination_buffer_full) {
5663 if (fptr->wbuf.len == fptr->wbuf.capa) {
5664 if (io_fflush(fptr) < 0) {
5665 return noalloc ? Qtrue : INT2NUM(errno);
5666 }
5667 }
5668
5669 ds = dp = (unsigned char *)fptr->wbuf.ptr + fptr->wbuf.off + fptr->wbuf.len;
5670 de = (unsigned char *)fptr->wbuf.ptr + fptr->wbuf.capa;
5671 res = rb_econv_convert(fptr->writeconv, NULL, NULL, &dp, de, 0);
5672 fptr->wbuf.len += (int)(dp - ds);
5673 if (res == econv_invalid_byte_sequence ||
5674 res == econv_incomplete_input ||
5676 return noalloc ? Qtrue : rb_econv_make_exception(fptr->writeconv);
5677 }
5678 }
5679 return Qnil;
5680}
5681
5683 rb_io_t *fptr;
5684 int noalloc;
5685};
5686
5687static VALUE
5688finish_writeconv_sync(VALUE arg)
5689{
5690 struct finish_writeconv_arg *p = (struct finish_writeconv_arg *)arg;
5691 return finish_writeconv(p->fptr, p->noalloc);
5692}
5693
5694static void*
5695nogvl_close(void *ptr)
5696{
5697 int *fd = ptr;
5698
5699 return (void*)(intptr_t)close(*fd);
5700}
5701
5702static int
5703maygvl_close(int fd, int keepgvl)
5704{
5705 if (keepgvl)
5706 return close(fd);
5707
5708 /*
5709 * close() may block for certain file types (NFS, SO_LINGER sockets,
5710 * inotify), so let other threads run.
5711 */
5712 return IO_WITHOUT_GVL_INT(nogvl_close, &fd);
5713}
5714
5715static void*
5716nogvl_fclose(void *ptr)
5717{
5718 FILE *file = ptr;
5719
5720 return (void*)(intptr_t)fclose(file);
5721}
5722
5723static int
5724maygvl_fclose(FILE *file, int keepgvl)
5725{
5726 if (keepgvl)
5727 return fclose(file);
5728
5729 return IO_WITHOUT_GVL_INT(nogvl_fclose, file);
5730}
5731
5732static void free_io_buffer(rb_io_buffer_t *buf);
5733
5734static void
5735fptr_finalize_flush(rb_io_t *fptr, int noraise, int keepgvl)
5736{
5737 VALUE error = Qnil;
5738 int fd = fptr->fd;
5739 FILE *stdio_file = fptr->stdio_file;
5740 int mode = fptr->mode;
5741
5742 if (fptr->writeconv) {
5743 if (!NIL_P(fptr->write_lock) && !noraise) {
5744 struct finish_writeconv_arg arg;
5745 arg.fptr = fptr;
5746 arg.noalloc = noraise;
5747 error = rb_mutex_synchronize(fptr->write_lock, finish_writeconv_sync, (VALUE)&arg);
5748 }
5749 else {
5750 error = finish_writeconv(fptr, noraise);
5751 }
5752 }
5753 /* Do not flush the write buffer on close when the stream is in sync
5754 * mode. In sync mode Ruby's write buffer is not authoritative (writes go
5755 * straight to the OS), so any bytes left in the buffer are the result of
5756 * writes made while sync was disabled. Setting sync = true is therefore a
5757 * way to abandon that pending output rather than replaying it on close,
5758 * which matters after an interrupted write where the amount actually
5759 * written is indeterminate. Call flush before enabling sync if the
5760 * buffered data should still be sent. */
5761 if (fptr->wbuf.len && !(fptr->mode & FMODE_SYNC)) {
5762 if (noraise) {
5763 io_flush_buffer_sync(fptr);
5764 }
5765 else {
5766 if (io_fflush(fptr) < 0 && NIL_P(error)) {
5767 error = INT2NUM(errno);
5768 }
5769 }
5770 }
5771
5772 int done = 0;
5773
5774 if (RUBY_IO_EXTERNAL_P(fptr) || fd <= 2) {
5775 // Need to keep FILE objects of stdin, stdout and stderr, so we are done:
5776 done = 1;
5777 }
5778
5779 fptr->fd = -1;
5780 fptr->stdio_file = 0;
5782
5783 // Wait for blocking operations to ensure they do not hit EBADF:
5784 rb_thread_io_close_wait(fptr);
5785
5786 if (!done && stdio_file) {
5787 // stdio_file is deallocated anyway even if fclose failed.
5788 if ((maygvl_fclose(stdio_file, noraise) < 0) && NIL_P(error)) {
5789 if (!noraise) {
5790 error = INT2NUM(errno);
5791 }
5792 }
5793
5794 done = 1;
5795 }
5796
5797 VALUE scheduler = rb_fiber_scheduler_current();
5798 if (!done && fd >= 0 && scheduler != Qnil) {
5799 VALUE result = rb_fiber_scheduler_io_close(scheduler, RB_INT2NUM(fd));
5800
5801 if (!UNDEF_P(result)) {
5802 done = RTEST(result);
5803 }
5804 }
5805
5806 if (!done && fd >= 0) {
5807 // fptr->fd may be closed even if close fails. POSIX doesn't specify it.
5808 // We assumes it is closed.
5809
5810 keepgvl |= !(mode & FMODE_WRITABLE);
5811 keepgvl |= noraise;
5812 if ((maygvl_close(fd, keepgvl) < 0) && NIL_P(error)) {
5813 if (!noraise) {
5814 error = INT2NUM(errno);
5815 }
5816 }
5817
5818 done = 1;
5819 }
5820
5821 if (!NIL_P(error) && !noraise) {
5822 if (RB_INTEGER_TYPE_P(error))
5823 rb_syserr_fail_path(NUM2INT(error), fptr->pathv);
5824 else
5825 rb_exc_raise(error);
5826 }
5827}
5828
5829static void
5830fptr_finalize(rb_io_t *fptr, int noraise)
5831{
5832 fptr_finalize_flush(fptr, noraise, FALSE);
5833 free_io_buffer(&fptr->rbuf);
5834 free_io_buffer(&fptr->wbuf);
5835 clear_codeconv(fptr);
5836}
5837
5838static void
5839rb_io_fptr_cleanup(rb_io_t *fptr, int noraise)
5840{
5841 if (fptr->finalize) {
5842 (*fptr->finalize)(fptr, noraise);
5843 }
5844 else {
5845 fptr_finalize(fptr, noraise);
5846 }
5847}
5848
5849static void
5850free_io_buffer(rb_io_buffer_t *buf)
5851{
5852 if (buf->ptr) {
5853 ruby_xfree_sized(buf->ptr, (size_t)buf->capa);
5854 buf->ptr = NULL;
5855 }
5856 buf->off = buf->len = buf->capa = 0;
5857}
5858
5859static void
5860clear_readconv(rb_io_t *fptr)
5861{
5862 if (fptr->readconv) {
5863 rb_econv_close(fptr->readconv);
5864 fptr->readconv = NULL;
5865 }
5866 free_io_buffer(&fptr->cbuf);
5867}
5868
5869static void
5870clear_writeconv(rb_io_t *fptr)
5871{
5872 if (fptr->writeconv) {
5874 fptr->writeconv = NULL;
5875 }
5876 fptr->writeconv_initialized = 0;
5877}
5878
5879static void
5880clear_codeconv(rb_io_t *fptr)
5881{
5882 clear_readconv(fptr);
5883 clear_writeconv(fptr);
5884}
5885
5886static void
5887rb_io_fptr_cleanup_all(rb_io_t *fptr)
5888{
5889 fptr->pathv = Qnil;
5890 if (0 <= fptr->fd)
5891 rb_io_fptr_cleanup(fptr, TRUE);
5892 fptr->write_lock = Qnil;
5893 free_io_buffer(&fptr->rbuf);
5894 free_io_buffer(&fptr->wbuf);
5895 clear_codeconv(fptr);
5896}
5897
5898int
5900{
5901 if (!io) return 0;
5902 rb_io_fptr_cleanup_all(io);
5903 free(io);
5904
5905 return 1;
5906}
5907
5908bool
5909rb_io_fptr_finalize_closed(struct rb_io *io)
5910{
5911 if (!io) return true;
5912 if (io->fd >= 0) return false;
5914 return true;
5915}
5916
5917size_t
5918rb_io_memsize(const rb_io_t *io)
5919{
5920 size_t size = sizeof(rb_io_t);
5921 size += io->rbuf.capa;
5922 size += io->wbuf.capa;
5923 size += io->cbuf.capa;
5924 if (io->readconv) size += rb_econv_memsize(io->readconv);
5925 if (io->writeconv) size += rb_econv_memsize(io->writeconv);
5926
5927 struct rb_io_blocking_operation *blocking_operation = 0;
5928
5929 // 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.
5930 rb_serial_t fork_generation = GET_VM()->fork_gen;
5931 if (io->fork_generation == fork_generation) {
5932 ccan_list_for_each(&io->blocking_operations, blocking_operation, list) {
5933 size += sizeof(struct rb_io_blocking_operation);
5934 }
5935 }
5936
5937 return size;
5938}
5939
5940#ifdef _WIN32
5941/* keep GVL while closing to prevent crash on Windows */
5942# define KEEPGVL TRUE
5943#else
5944# define KEEPGVL FALSE
5945#endif
5946
5947static rb_io_t *
5948io_close_fptr(VALUE io)
5949{
5950 rb_io_t *fptr;
5951 VALUE write_io;
5952 rb_io_t *write_fptr;
5953
5954 write_io = GetWriteIO(io);
5955 if (io != write_io) {
5956 write_fptr = RFILE(write_io)->fptr;
5957 if (write_fptr && 0 <= write_fptr->fd) {
5958 rb_io_fptr_cleanup(write_fptr, TRUE);
5959 }
5960 }
5961
5962 fptr = RFILE(io)->fptr;
5963 if (!fptr) return 0;
5964 if (fptr->fd < 0) return 0;
5965
5966 // This guards against multiple threads closing the same IO object:
5967 if (rb_thread_io_close_interrupt(fptr)) {
5968 /* calls close(fptr->fd): */
5969 fptr_finalize_flush(fptr, FALSE, KEEPGVL);
5970 }
5971
5972 rb_io_fptr_cleanup(fptr, FALSE);
5973 return fptr;
5974}
5975
5976static void
5977fptr_waitpid(rb_io_t *fptr, int nohang)
5978{
5979 int status;
5980 if (fptr->pid) {
5981 rb_last_status_clear();
5982 rb_waitpid(fptr->pid, &status, nohang ? WNOHANG : 0);
5983 fptr->pid = 0;
5984 }
5985}
5986
5987VALUE
5989{
5990 rb_io_t *fptr = io_close_fptr(io);
5991 if (fptr) fptr_waitpid(fptr, 0);
5992 return Qnil;
5993}
5994
5995/*
5996 * call-seq:
5997 * close -> nil
5998 *
5999 * Closes the stream for both reading and writing
6000 * if open for either or both; returns +nil+.
6001 * See {Open and Closed Streams}[rdoc-ref:IO@Open+and+Closed+Streams].
6002 *
6003 * If the stream is open for writing, flushes any buffered writes
6004 * to the operating system before closing.
6005 *
6006 * If the stream was opened by IO.popen, sets global variable <tt>$?</tt>
6007 * (child exit status).
6008 *
6009 * It is not an error to close an IO object that has already been closed.
6010 * It just returns nil.
6011 *
6012 * Example:
6013 *
6014 * IO.popen('ruby', 'r+') do |pipe|
6015 * puts pipe.closed?
6016 * pipe.close
6017 * puts $?
6018 * puts pipe.closed?
6019 * end
6020 *
6021 * Output:
6022 *
6023 * false
6024 * pid 13760 exit 0
6025 * true
6026 *
6027 * Related: IO#close_read, IO#close_write, IO#closed?.
6028 */
6029
6030static VALUE
6031rb_io_close_m(VALUE io)
6032{
6033 rb_io_t *fptr = rb_io_get_fptr(io);
6034 if (fptr->fd < 0) {
6035 return Qnil;
6036 }
6037 rb_io_close(io);
6038 return Qnil;
6039}
6040
6041static VALUE
6042io_call_close(VALUE io)
6043{
6044 rb_check_funcall(io, rb_intern("close"), 0, 0);
6045 return io;
6046}
6047
6048static VALUE
6049ignore_closed_stream(VALUE io, VALUE exc)
6050{
6051 enum {mesg_len = sizeof(closed_stream)-1};
6052 VALUE mesg = rb_attr_get(exc, idMesg);
6053 if (!RB_TYPE_P(mesg, T_STRING) ||
6054 RSTRING_LEN(mesg) != mesg_len ||
6055 memcmp(RSTRING_PTR(mesg), closed_stream, mesg_len)) {
6056 rb_exc_raise(exc);
6057 }
6058 return io;
6059}
6060
6061static VALUE
6062io_close(VALUE io)
6063{
6064 VALUE closed = rb_check_funcall(io, rb_intern("closed?"), 0, 0);
6065 if (!UNDEF_P(closed) && RTEST(closed)) return io;
6066 rb_rescue2(io_call_close, io, ignore_closed_stream, io,
6067 rb_eIOError, (VALUE)0);
6068 return io;
6069}
6070
6071/*
6072 * call-seq:
6073 * closed? -> true or false
6074 *
6075 * Returns +true+ if the stream is closed for both reading and writing,
6076 * +false+ otherwise.
6077 * See {Open and Closed Streams}[rdoc-ref:IO@Open+and+Closed+Streams].
6078 *
6079 * IO.popen('ruby', 'r+') do |pipe|
6080 * puts pipe.closed?
6081 * pipe.close_read
6082 * puts pipe.closed?
6083 * pipe.close_write
6084 * puts pipe.closed?
6085 * end
6086 *
6087 * Output:
6088 *
6089 * false
6090 * false
6091 * true
6092 *
6093 * Related: IO#close_read, IO#close_write, IO#close.
6094 */
6095VALUE
6097{
6098 rb_io_t *fptr;
6099 VALUE write_io;
6100 rb_io_t *write_fptr;
6101
6102 write_io = GetWriteIO(io);
6103 if (io != write_io) {
6104 write_fptr = RFILE(write_io)->fptr;
6105 if (write_fptr && 0 <= write_fptr->fd) {
6106 return Qfalse;
6107 }
6108 }
6109
6110 fptr = rb_io_get_fptr(io);
6111 return RBOOL(0 > fptr->fd);
6112}
6113
6114/*
6115 * call-seq:
6116 * close_read -> nil
6117 *
6118 * Closes the stream for reading if open for reading;
6119 * returns +nil+.
6120 * See {Open and Closed Streams}[rdoc-ref:IO@Open+and+Closed+Streams].
6121 *
6122 * If the stream was opened by IO.popen and is also closed for writing,
6123 * sets global variable <tt>$?</tt> (child exit status).
6124 *
6125 * Example:
6126 *
6127 * IO.popen('ruby', 'r+') do |pipe|
6128 * puts pipe.closed?
6129 * pipe.close_write
6130 * puts pipe.closed?
6131 * pipe.close_read
6132 * puts $?
6133 * puts pipe.closed?
6134 * end
6135 *
6136 * Output:
6137 *
6138 * false
6139 * false
6140 * pid 14748 exit 0
6141 * true
6142 *
6143 * Related: IO#close, IO#close_write, IO#closed?.
6144 */
6145
6146static VALUE
6147rb_io_close_read(VALUE io)
6148{
6149 rb_io_t *fptr;
6150 VALUE write_io;
6151
6152 fptr = rb_io_get_fptr(rb_io_taint_check(io));
6153 if (fptr->fd < 0) return Qnil;
6154 if (is_socket(fptr->fd, fptr->pathv)) {
6155#ifndef SHUT_RD
6156# define SHUT_RD 0
6157#endif
6158 if (shutdown(fptr->fd, SHUT_RD) < 0)
6159 rb_sys_fail_path(fptr->pathv);
6160 fptr->mode &= ~FMODE_READABLE;
6161 if (!(fptr->mode & FMODE_WRITABLE))
6162 return rb_io_close(io);
6163 return Qnil;
6164 }
6165
6166 write_io = GetWriteIO(io);
6167 if (io != write_io) {
6168 rb_io_t *wfptr;
6169 wfptr = rb_io_get_fptr(rb_io_taint_check(write_io));
6170 wfptr->pid = fptr->pid;
6171 fptr->pid = 0;
6172 RFILE(io)->fptr = wfptr;
6173 /* bind to write_io temporarily to get rid of memory/fd leak */
6174 fptr->tied_io_for_writing = 0;
6175 RFILE(write_io)->fptr = fptr;
6176 rb_io_fptr_cleanup(fptr, FALSE);
6177 /* should not finalize fptr because another thread may be reading it */
6178 return Qnil;
6179 }
6180
6181 if ((fptr->mode & (FMODE_DUPLEX|FMODE_WRITABLE)) == FMODE_WRITABLE) {
6182 rb_raise(rb_eIOError, "closing non-duplex IO for reading");
6183 }
6184 return rb_io_close(io);
6185}
6186
6187/*
6188 * call-seq:
6189 * close_write -> nil
6190 *
6191 * Closes the stream for writing if open for writing;
6192 * returns +nil+.
6193 * See {Open and Closed Streams}[rdoc-ref:IO@Open+and+Closed+Streams].
6194 *
6195 * Flushes any buffered writes to the operating system before closing.
6196 *
6197 * If the stream was opened by IO.popen and is also closed for reading,
6198 * sets global variable <tt>$?</tt> (child exit status).
6199 *
6200 * IO.popen('ruby', 'r+') do |pipe|
6201 * puts pipe.closed?
6202 * pipe.close_read
6203 * puts pipe.closed?
6204 * pipe.close_write
6205 * puts $?
6206 * puts pipe.closed?
6207 * end
6208 *
6209 * Output:
6210 *
6211 * false
6212 * false
6213 * pid 15044 exit 0
6214 * true
6215 *
6216 * Related: IO#close, IO#close_read, IO#closed?.
6217 */
6218
6219static VALUE
6220rb_io_close_write(VALUE io)
6221{
6222 rb_io_t *fptr;
6223 VALUE write_io;
6224
6225 write_io = GetWriteIO(io);
6226 fptr = rb_io_get_fptr(rb_io_taint_check(write_io));
6227 if (fptr->fd < 0) return Qnil;
6228 if (is_socket(fptr->fd, fptr->pathv)) {
6229#ifndef SHUT_WR
6230# define SHUT_WR 1
6231#endif
6232 /* Flush any buffered data before shutting down the write side.
6233 * Otherwise the buffered bytes are silently dropped here, and a
6234 * subsequent #close would try to flush them into the now
6235 * shutdown(SHUT_WR) socket and fail with EPIPE. This matches the
6236 * behaviour of the non-socket path below, which flushes via
6237 * rb_io_close(). */
6238 if (fptr->mode & FMODE_WRITABLE) {
6239 if (io_fflush(fptr) < 0)
6240 rb_sys_fail_on_write(fptr);
6241 }
6242 if (shutdown(fptr->fd, SHUT_WR) < 0)
6243 rb_sys_fail_path(fptr->pathv);
6244 fptr->mode &= ~FMODE_WRITABLE;
6245 if (!(fptr->mode & FMODE_READABLE))
6246 return rb_io_close(write_io);
6247 return Qnil;
6248 }
6249
6250 if ((fptr->mode & (FMODE_DUPLEX|FMODE_READABLE)) == FMODE_READABLE) {
6251 rb_raise(rb_eIOError, "closing non-duplex IO for writing");
6252 }
6253
6254 if (io != write_io) {
6255 fptr = rb_io_get_fptr(rb_io_taint_check(io));
6256 fptr->tied_io_for_writing = 0;
6257 }
6258 rb_io_close(write_io);
6259 return Qnil;
6260}
6261
6262/*
6263 * call-seq:
6264 * sysseek(offset, whence = IO::SEEK_SET) -> integer
6265 *
6266 * Behaves like IO#seek, except that it:
6267 *
6268 * - Uses low-level system functions.
6269 * - Returns the new position.
6270 *
6271 */
6272
6273static VALUE
6274rb_io_sysseek(int argc, VALUE *argv, VALUE io)
6275{
6276 VALUE offset, ptrname;
6277 int whence = SEEK_SET;
6278 rb_io_t *fptr;
6279 rb_off_t pos;
6280
6281 if (rb_scan_args(argc, argv, "11", &offset, &ptrname) == 2) {
6282 whence = interpret_seek_whence(ptrname);
6283 }
6284 pos = NUM2OFFT(offset);
6285 GetOpenFile(io, fptr);
6286 if ((fptr->mode & FMODE_READABLE) &&
6287 (READ_DATA_BUFFERED(fptr) || READ_CHAR_PENDING(fptr))) {
6288 rb_raise(rb_eIOError, "sysseek for buffered IO");
6289 }
6290 if ((fptr->mode & FMODE_WRITABLE) && fptr->wbuf.len) {
6291 rb_warn("sysseek for buffered IO");
6292 }
6293 errno = 0;
6294 pos = lseek(fptr->fd, pos, whence);
6295 if (pos < 0 && errno) rb_sys_fail_path(fptr->pathv);
6296
6297 return OFFT2NUM(pos);
6298}
6299
6300/*
6301 * call-seq:
6302 * syswrite(object) -> integer
6303 *
6304 * Writes the given +object+ to self, which must be opened for writing (see Modes);
6305 * returns the number bytes written.
6306 * If +object+ is not a string is converted via method to_s:
6307 *
6308 * f = File.new('t.tmp', 'w')
6309 * f.syswrite('foo') # => 3
6310 * f.syswrite(30) # => 2
6311 * f.syswrite(:foo) # => 3
6312 * f.close
6313 *
6314 * This methods should not be used with other stream-writer methods.
6315 *
6316 */
6317
6318static VALUE
6319rb_io_syswrite(VALUE io, VALUE str)
6320{
6321 VALUE tmp;
6322 rb_io_t *fptr;
6323 rb_len_t n, len;
6324 const char *ptr;
6325
6326 if (!RB_TYPE_P(str, T_STRING))
6327 str = rb_obj_as_string(str);
6328
6329 io = GetWriteIO(io);
6330 GetOpenFile(io, fptr);
6332
6333 if (fptr->wbuf.len) {
6334 rb_warn("syswrite for buffered IO");
6335 }
6336
6337 tmp = rb_str_tmp_frozen_acquire(str);
6338 RSTRING_GETMEM(tmp, ptr, len);
6339 n = rb_io_write_memory(fptr, ptr, len);
6340 if (n < 0) rb_sys_fail_path(fptr->pathv);
6341 rb_str_tmp_frozen_release(str, tmp);
6342
6343 return LEN2NUM(n);
6344}
6345
6346/*
6347 * call-seq:
6348 * sysread(maxlen) -> string
6349 * sysread(maxlen, out_string) -> string
6350 *
6351 * Behaves like IO#readpartial, except that it uses low-level system functions.
6352 *
6353 * This method should not be used with other stream-reader methods.
6354 *
6355 */
6356
6357static VALUE
6358rb_io_sysread(int argc, VALUE *argv, VALUE io)
6359{
6360 VALUE len, str;
6361 rb_io_t *fptr;
6362 rb_len_t n, ilen;
6363 struct io_internal_read_struct iis;
6364 int shrinkable;
6365
6366 rb_scan_args(argc, argv, "11", &len, &str);
6367 ilen = NUM2LEN(len);
6368 if (ilen < 0) {
6369 rb_raise(rb_eArgError, "negative length %"PRIdLEN" given", ilen);
6370 }
6371 shrinkable = io_setstrbuf(&str, ilen);
6372
6373 GetOpenFile(io, fptr);
6375
6376 if (READ_DATA_BUFFERED(fptr)) {
6377 rb_raise(rb_eIOError, "sysread for buffered IO");
6378 }
6379
6380 if (ilen == 0) {
6381 io_set_read_length(str, 0, shrinkable);
6382 return str;
6383 }
6384
6385 rb_io_check_closed(fptr);
6386
6387 io_setstrbuf(&str, ilen);
6388 rb_str_make_heap(str);
6389 iis.th = rb_thread_current();
6390 iis.fptr = fptr;
6391 iis.nonblock = 0;
6392 iis.fd = fptr->fd;
6393 iis.buf = RSTRING_PTR(str);
6394 iis.capa = ilen;
6395 iis.timeout = NULL;
6396 n = io_read_memory_locktmp(str, &iis);
6397
6398 if (n < 0) {
6399 rb_sys_fail_path(fptr->pathv);
6400 }
6401
6402 io_set_read_length(str, n, shrinkable);
6403
6404 if (n == 0) {
6405 rb_eof_error();
6406 }
6407
6408 return str;
6409}
6410
6412 struct rb_io *io;
6413 int fd;
6414 void *buf;
6415 size_t count;
6416 rb_off_t offset;
6417};
6418
6419static VALUE
6420internal_pread_func(void *_arg)
6421{
6422 struct prdwr_internal_arg *arg = _arg;
6423
6424 return (VALUE)pread(arg->fd, arg->buf, arg->count, arg->offset);
6425}
6426
6427static VALUE
6428pread_internal_call(VALUE _arg)
6429{
6430 struct prdwr_internal_arg *arg = (struct prdwr_internal_arg *)_arg;
6431
6432 VALUE scheduler = rb_fiber_scheduler_current();
6433 if (scheduler != Qnil) {
6434 VALUE result = rb_fiber_scheduler_io_pread_memory(scheduler, arg->io->self, arg->offset, arg->buf, arg->count);
6435
6436 if (!UNDEF_P(result)) {
6438 }
6439 }
6440
6441 return rb_io_blocking_region_wait(arg->io, internal_pread_func, arg, RUBY_IO_READABLE);
6442}
6443
6444/*
6445 * call-seq:
6446 * pread(maxlen, offset) -> string
6447 * pread(maxlen, offset, out_string) -> string
6448 *
6449 * Behaves like IO#readpartial, except that it:
6450 *
6451 * - Reads at the given +offset+ (in bytes).
6452 * - Disregards, and does not modify, the stream's position
6453 * (see {Position}[rdoc-ref:IO@Position]).
6454 * - Bypasses any user space buffering in the stream.
6455 *
6456 * Because this method does not disturb the stream's state
6457 * (its position, in particular), +pread+ allows multiple threads and processes
6458 * to use the same \IO object for reading at various offsets.
6459 *
6460 * f = File.open('t.txt')
6461 * f.read # => "First line\nSecond line\n\nFourth line\nFifth line\n"
6462 * f.pos # => 52
6463 * # Read 12 bytes at offset 0.
6464 * f.pread(12, 0) # => "First line\n"
6465 * # Read 9 bytes at offset 8.
6466 * f.pread(9, 8) # => "ne\nSecon"
6467 * f.close
6468 *
6469 * Not available on some platforms.
6470 *
6471 */
6472static VALUE
6473rb_io_pread(int argc, VALUE *argv, VALUE io)
6474{
6475 VALUE len, offset, str;
6476 rb_len_t ilen;
6477 rb_io_t *fptr;
6478 ssize_t n;
6479 struct prdwr_internal_arg arg;
6480 int shrinkable;
6481
6482 rb_scan_args(argc, argv, "21", &len, &offset, &str);
6483 ilen = NUM2LEN(len);
6484 if (ilen < 0) {
6485 rb_raise(rb_eArgError, "negative length %"PRIdLEN" given", ilen);
6486 }
6487 arg.offset = NUM2OFFT(offset);
6488
6489 shrinkable = io_setstrbuf(&str, ilen);
6490
6491 GetOpenFile(io, fptr);
6493
6494 if (ilen == 0) {
6495 io_set_read_length(str, 0, shrinkable);
6496 return str;
6497 }
6498
6499 io_setstrbuf(&str, ilen);
6500 rb_str_make_heap(str);
6501 arg.io = fptr;
6502 arg.fd = fptr->fd;
6503 arg.buf = RSTRING_PTR(str);
6504 arg.count = (size_t)ilen;
6505 rb_io_check_closed(fptr);
6506
6507 rb_str_locktmp(str);
6508 n = (ssize_t)rb_ensure(pread_internal_call, (VALUE)&arg, rb_str_unlocktmp, str);
6509
6510 if (n < 0) {
6511 rb_sys_fail_path(fptr->pathv);
6512 }
6513 io_set_read_length(str, n, shrinkable);
6514 if (n == 0) {
6515 rb_eof_error();
6516 }
6517
6518 return str;
6519}
6520
6521static VALUE
6522internal_pwrite_func(void *_arg)
6523{
6524 struct prdwr_internal_arg *arg = _arg;
6525
6526 return (VALUE)pwrite(arg->fd, arg->buf, arg->count, arg->offset);
6527}
6528
6529static VALUE
6530pwrite_internal_call(VALUE _arg)
6531{
6532 struct prdwr_internal_arg *arg = (struct prdwr_internal_arg *)_arg;
6533
6534 VALUE scheduler = rb_fiber_scheduler_current();
6535 if (scheduler != Qnil) {
6536 VALUE result = rb_fiber_scheduler_io_pwrite_memory(scheduler, arg->io->self, arg->offset, arg->buf, arg->count);
6537
6538 if (!UNDEF_P(result)) {
6540 }
6541 }
6542
6543 return rb_io_blocking_region_wait(arg->io, internal_pwrite_func, arg, RUBY_IO_WRITABLE);
6544}
6545
6546/*
6547 * call-seq:
6548 * pwrite(object, offset) -> integer
6549 *
6550 * Behaves like IO#write, except that it:
6551 *
6552 * - Writes at the given +offset+ (in bytes).
6553 * - Disregards, and does not modify, the stream's position
6554 * (see {Position}[rdoc-ref:IO@Position]).
6555 * - Bypasses any user space buffering in the stream.
6556 *
6557 * Because this method does not disturb the stream's state
6558 * (its position, in particular), +pwrite+ allows multiple threads and processes
6559 * to use the same \IO object for writing at various offsets.
6560 *
6561 * f = File.open('t.tmp', 'w+')
6562 * # Write 6 bytes at offset 3.
6563 * f.pwrite('ABCDEF', 3) # => 6
6564 * f.rewind
6565 * f.read # => "\u0000\u0000\u0000ABCDEF"
6566 * f.close
6567 *
6568 * Not available on some platforms.
6569 *
6570 */
6571static VALUE
6572rb_io_pwrite(VALUE io, VALUE str, VALUE offset)
6573{
6574 rb_io_t *fptr;
6575 ssize_t n;
6576 struct prdwr_internal_arg arg;
6577 VALUE tmp;
6578
6579 if (!RB_TYPE_P(str, T_STRING))
6580 str = rb_obj_as_string(str);
6581
6582 arg.offset = NUM2OFFT(offset);
6583
6584 io = GetWriteIO(io);
6585 GetOpenFile(io, fptr);
6587
6588 arg.io = fptr;
6589 arg.fd = fptr->fd;
6590
6591 tmp = rb_str_tmp_frozen_acquire(str);
6592 arg.buf = RSTRING_PTR(tmp);
6593 arg.count = (size_t)RSTRING_LEN(tmp);
6594
6595 n = (ssize_t)pwrite_internal_call((VALUE)&arg);
6596 if (n < 0) rb_sys_fail_path(fptr->pathv);
6597 rb_str_tmp_frozen_release(str, tmp);
6598
6599 return SSIZET2NUM(n);
6600}
6601
6602VALUE
6604{
6605 rb_io_t *fptr;
6606
6607 GetOpenFile(io, fptr);
6608 if (fptr->readconv)
6610 if (fptr->writeconv)
6612 fptr->mode |= FMODE_BINMODE;
6613 fptr->mode &= ~FMODE_TEXTMODE;
6615#ifdef O_BINARY
6616 if (!fptr->readconv) {
6617 SET_BINARY_MODE_WITH_SEEK_CUR(fptr);
6618 }
6619 else {
6620 setmode(fptr->fd, O_BINARY);
6621 }
6622#endif
6623 return io;
6624}
6625
6626static void
6627io_ascii8bit_binmode(rb_io_t *fptr)
6628{
6629 if (fptr->readconv) {
6630 rb_econv_close(fptr->readconv);
6631 fptr->readconv = NULL;
6632 }
6633 if (fptr->writeconv) {
6635 fptr->writeconv = NULL;
6636 }
6637 fptr->mode |= FMODE_BINMODE;
6638 fptr->mode &= ~FMODE_TEXTMODE;
6639 SET_BINARY_MODE_WITH_SEEK_CUR(fptr);
6640
6641 fptr->encs.enc = rb_ascii8bit_encoding();
6642 fptr->encs.enc2 = NULL;
6643 fptr->encs.ecflags = 0;
6644 fptr->encs.ecopts = Qnil;
6645 clear_codeconv(fptr);
6646}
6647
6648VALUE
6650{
6651 rb_io_t *fptr;
6652
6653 GetOpenFile(io, fptr);
6654 io_ascii8bit_binmode(fptr);
6655
6656 return io;
6657}
6658
6659/*
6660 * call-seq:
6661 * binmode -> self
6662 *
6663 * Sets the stream's data mode as binary
6664 * (see {Data Mode}[rdoc-ref:File@Data+Mode]).
6665 *
6666 * A stream's data mode may not be changed from binary to text.
6667 *
6668 */
6669
6670static VALUE
6671rb_io_binmode_m(VALUE io)
6672{
6673 VALUE write_io;
6674
6676
6677 write_io = GetWriteIO(io);
6678 if (write_io != io)
6679 rb_io_ascii8bit_binmode(write_io);
6680 return io;
6681}
6682
6683/*
6684 * call-seq:
6685 * binmode? -> true or false
6686 *
6687 * Returns +true+ if the stream is on binary mode, +false+ otherwise.
6688 * See {Data Mode}[rdoc-ref:File@Data+Mode].
6689 *
6690 */
6691static VALUE
6692rb_io_binmode_p(VALUE io)
6693{
6694 rb_io_t *fptr;
6695 GetOpenFile(io, fptr);
6696 return RBOOL(fptr->mode & FMODE_BINMODE);
6697}
6698
6699static const char*
6700rb_io_fmode_modestr(enum rb_io_mode fmode)
6701{
6702 if (fmode & FMODE_APPEND) {
6703 if ((fmode & FMODE_READWRITE) == FMODE_READWRITE) {
6704 return MODE_BTMODE("a+", "ab+", "at+");
6705 }
6706 return MODE_BTMODE("a", "ab", "at");
6707 }
6708 switch (fmode & FMODE_READWRITE) {
6709 default:
6710 rb_raise(rb_eArgError, "invalid access fmode 0x%x", fmode);
6711 case FMODE_READABLE:
6712 return MODE_BTMODE("r", "rb", "rt");
6713 case FMODE_WRITABLE:
6714 return MODE_BTXMODE("w", "wb", "wt", "wx", "wbx", "wtx");
6715 case FMODE_READWRITE:
6716 if (fmode & FMODE_CREATE) {
6717 return MODE_BTXMODE("w+", "wb+", "wt+", "w+x", "wb+x", "wt+x");
6718 }
6719 return MODE_BTMODE("r+", "rb+", "rt+");
6720 }
6721}
6722
6723static const char bom_prefix[] = "bom|";
6724static const char utf_prefix[] = "utf-";
6725enum {bom_prefix_len = (int)sizeof(bom_prefix) - 1};
6726enum {utf_prefix_len = (int)sizeof(utf_prefix) - 1};
6727
6728static int
6729io_encname_bom_p(const char *name, rb_len_t len)
6730{
6731 return len > bom_prefix_len && STRNCASECMP(name, bom_prefix, bom_prefix_len) == 0;
6732}
6733
6734enum rb_io_mode
6735rb_io_modestr_fmode(const char *modestr)
6736{
6737 enum rb_io_mode fmode = 0;
6738 const char *m = modestr, *p = NULL;
6739
6740 switch (*m++) {
6741 case 'r':
6742 fmode |= FMODE_READABLE;
6743 break;
6744 case 'w':
6746 break;
6747 case 'a':
6749 break;
6750 default:
6751 goto error;
6752 }
6753
6754 while (*m) {
6755 switch (*m++) {
6756 case 'b':
6757 fmode |= FMODE_BINMODE;
6758 break;
6759 case 't':
6760 fmode |= FMODE_TEXTMODE;
6761 break;
6762 case '+':
6763 fmode |= FMODE_READWRITE;
6764 break;
6765 case 'x':
6766 if (modestr[0] != 'w')
6767 goto error;
6768 fmode |= FMODE_EXCL;
6769 break;
6770 default:
6771 goto error;
6772 case ':':
6773 p = strchr(m, ':');
6774 if (io_encname_bom_p(m, p ? (rb_len_t)(p - m) : (rb_len_t)strlen(m)))
6775 fmode |= FMODE_SETENC_BY_BOM;
6776 goto finished;
6777 }
6778 }
6779
6780 finished:
6781 if ((fmode & FMODE_BINMODE) && (fmode & FMODE_TEXTMODE))
6782 goto error;
6783
6784 return fmode;
6785
6786 error:
6787 rb_raise(rb_eArgError, "invalid access mode %s", modestr);
6789}
6790
6791int
6793{
6794 enum rb_io_mode fmode = 0;
6795
6796 switch (oflags & O_ACCMODE) {
6797 case O_RDONLY:
6798 fmode = FMODE_READABLE;
6799 break;
6800 case O_WRONLY:
6801 fmode = FMODE_WRITABLE;
6802 break;
6803 case O_RDWR:
6804 fmode = FMODE_READWRITE;
6805 break;
6806 }
6807
6808 if (oflags & O_APPEND) {
6809 fmode |= FMODE_APPEND;
6810 }
6811 if (oflags & O_TRUNC) {
6812 fmode |= FMODE_TRUNC;
6813 }
6814 if (oflags & O_CREAT) {
6815 fmode |= FMODE_CREATE;
6816 }
6817 if (oflags & O_EXCL) {
6818 fmode |= FMODE_EXCL;
6819 }
6820#ifdef O_BINARY
6821 if (oflags & O_BINARY) {
6822 fmode |= FMODE_BINMODE;
6823 }
6824#endif
6825
6826 return fmode;
6827}
6828
6829static int
6830rb_io_fmode_oflags(enum rb_io_mode fmode)
6831{
6832 int oflags = 0;
6833
6834 switch (fmode & FMODE_READWRITE) {
6835 case FMODE_READABLE:
6836 oflags |= O_RDONLY;
6837 break;
6838 case FMODE_WRITABLE:
6839 oflags |= O_WRONLY;
6840 break;
6841 case FMODE_READWRITE:
6842 oflags |= O_RDWR;
6843 break;
6844 }
6845
6846 if (fmode & FMODE_APPEND) {
6847 oflags |= O_APPEND;
6848 }
6849 if (fmode & FMODE_TRUNC) {
6850 oflags |= O_TRUNC;
6851 }
6852 if (fmode & FMODE_CREATE) {
6853 oflags |= O_CREAT;
6854 }
6855 if (fmode & FMODE_EXCL) {
6856 oflags |= O_EXCL;
6857 }
6858#ifdef O_BINARY
6859 if (fmode & FMODE_BINMODE) {
6860 oflags |= O_BINARY;
6861 }
6862#endif
6863
6864 return oflags;
6865}
6866
6867int
6868rb_io_modestr_oflags(const char *modestr)
6869{
6870 return rb_io_fmode_oflags(rb_io_modestr_fmode(modestr));
6871}
6872
6873static const char*
6874rb_io_oflags_modestr(int oflags)
6875{
6876#ifdef O_BINARY
6877# define MODE_BINARY(a,b) ((oflags & O_BINARY) ? (b) : (a))
6878#else
6879# define MODE_BINARY(a,b) (a)
6880#endif
6881 int accmode;
6882 if (oflags & O_EXCL) {
6883 rb_raise(rb_eArgError, "exclusive access mode is not supported");
6884 }
6885 accmode = oflags & (O_RDONLY|O_WRONLY|O_RDWR);
6886 if (oflags & O_APPEND) {
6887 if (accmode == O_WRONLY) {
6888 return MODE_BINARY("a", "ab");
6889 }
6890 if (accmode == O_RDWR) {
6891 return MODE_BINARY("a+", "ab+");
6892 }
6893 }
6894 switch (accmode) {
6895 default:
6896 rb_raise(rb_eArgError, "invalid access oflags 0x%x", oflags);
6897 case O_RDONLY:
6898 return MODE_BINARY("r", "rb");
6899 case O_WRONLY:
6900 return MODE_BINARY("w", "wb");
6901 case O_RDWR:
6902 if (oflags & O_TRUNC) {
6903 return MODE_BINARY("w+", "wb+");
6904 }
6905 return MODE_BINARY("r+", "rb+");
6906 }
6907}
6908
6909/*
6910 * Convert external/internal encodings to enc/enc2
6911 * NULL => use default encoding
6912 * Qnil => no encoding specified (internal only)
6913 */
6914static void
6915rb_io_ext_int_to_encs(rb_encoding *ext, rb_encoding *intern, rb_encoding **enc, rb_encoding **enc2, enum rb_io_mode fmode)
6916{
6917 int default_ext = 0;
6918
6919 if (ext == NULL) {
6921 default_ext = 1;
6922 }
6923 if (rb_is_ascii8bit_enc(ext)) {
6924 /* If external is ASCII-8BIT, no transcoding */
6925 intern = NULL;
6926 }
6927 else if (intern == NULL) {
6929 }
6930 if (intern == NULL || intern == (rb_encoding *)Qnil ||
6931 (!(fmode & FMODE_SETENC_BY_BOM) && (intern == ext))) {
6932 /* No internal encoding => use external + no transcoding */
6933 *enc = (default_ext && intern != ext) ? NULL : ext;
6934 *enc2 = NULL;
6935 }
6936 else {
6937 *enc = intern;
6938 *enc2 = ext;
6939 }
6940}
6941
6942static void
6943unsupported_encoding(const char *name, rb_encoding *enc)
6944{
6945 rb_enc_warn(enc, "Unsupported encoding %s ignored", name);
6946}
6947
6948static void
6949parse_mode_enc(const char *estr, rb_encoding *estr_enc,
6950 rb_encoding **enc_p, rb_encoding **enc2_p, enum rb_io_mode *fmode_p)
6951{
6952 const char *p;
6953 char encname[ENCODING_MAXNAMELEN+1];
6954 int idx, idx2;
6955 enum rb_io_mode fmode = fmode_p ? *fmode_p : 0;
6956 rb_encoding *ext_enc, *int_enc;
6957 rb_len_t len;
6958
6959 /* parse estr as "enc" or "enc2:enc" or "enc:-" */
6960
6961 p = strrchr(estr, ':');
6962 len = p ? (p++ - estr) : (rb_len_t)strlen(estr);
6963 if ((fmode & FMODE_SETENC_BY_BOM) || io_encname_bom_p(estr, len)) {
6964 estr += bom_prefix_len;
6965 len -= bom_prefix_len;
6966 if (!STRNCASECMP(estr, utf_prefix, utf_prefix_len)) {
6967 fmode |= FMODE_SETENC_BY_BOM;
6968 }
6969 else {
6970 rb_enc_warn(estr_enc, "BOM with non-UTF encoding %s is nonsense", estr);
6971 fmode &= ~FMODE_SETENC_BY_BOM;
6972 }
6973 }
6974 if (len == 0 || len > ENCODING_MAXNAMELEN) {
6975 idx = -1;
6976 }
6977 else {
6978 if (p) {
6979 memcpy(encname, estr, len);
6980 encname[len] = '\0';
6981 estr = encname;
6982 }
6983 idx = rb_enc_find_index(estr);
6984 }
6985 if (fmode_p) *fmode_p = fmode;
6986
6987 if (idx >= 0)
6988 ext_enc = rb_enc_from_index(idx);
6989 else {
6990 if (idx != -2)
6991 unsupported_encoding(estr, estr_enc);
6992 ext_enc = NULL;
6993 }
6994
6995 int_enc = NULL;
6996 if (p) {
6997 if (*p == '-' && *(p+1) == '\0') {
6998 /* Special case - "-" => no transcoding */
6999 int_enc = (rb_encoding *)Qnil;
7000 }
7001 else {
7002 idx2 = rb_enc_find_index(p);
7003 if (idx2 < 0)
7004 unsupported_encoding(p, estr_enc);
7005 else if (!(fmode & FMODE_SETENC_BY_BOM) && (idx2 == idx)) {
7006 int_enc = (rb_encoding *)Qnil;
7007 }
7008 else
7009 int_enc = rb_enc_from_index(idx2);
7010 }
7011 }
7012
7013 rb_io_ext_int_to_encs(ext_enc, int_enc, enc_p, enc2_p, fmode);
7014}
7015
7016int
7017rb_io_extract_encoding_option(VALUE opt, rb_encoding **enc_p, rb_encoding **enc2_p, enum rb_io_mode *fmode_p)
7018{
7019 VALUE encoding=Qnil, extenc=Qundef, intenc=Qundef, tmp;
7020 int extracted = 0;
7021 rb_encoding *extencoding = NULL;
7022 rb_encoding *intencoding = NULL;
7023
7024 if (!NIL_P(opt)) {
7025 VALUE v;
7026 v = rb_hash_lookup2(opt, sym_encoding, Qnil);
7027 if (v != Qnil) encoding = v;
7028 v = rb_hash_lookup2(opt, sym_extenc, Qundef);
7029 if (v != Qnil) extenc = v;
7030 v = rb_hash_lookup2(opt, sym_intenc, Qundef);
7031 if (!UNDEF_P(v)) intenc = v;
7032 }
7033 if ((!UNDEF_P(extenc) || !UNDEF_P(intenc)) && !NIL_P(encoding)) {
7034 if (!NIL_P(ruby_verbose)) {
7035 int idx = rb_to_encoding_index(encoding);
7036 if (idx >= 0) encoding = rb_enc_from_encoding(rb_enc_from_index(idx));
7037 rb_warn("Ignoring encoding parameter '%"PRIsVALUE"': %s_encoding is used",
7038 encoding, UNDEF_P(extenc) ? "internal" : "external");
7039 }
7040 encoding = Qnil;
7041 }
7042 if (!NIL_OR_UNDEF_P(extenc)) {
7043 extencoding = rb_to_encoding(extenc);
7044 }
7045 if (!UNDEF_P(intenc)) {
7046 if (NIL_P(intenc)) {
7047 /* internal_encoding: nil => no transcoding */
7048 intencoding = (rb_encoding *)Qnil;
7049 }
7050 else if (!NIL_P(tmp = rb_check_string_type(intenc))) {
7051 char *p = StringValueCStr(tmp);
7052
7053 if (*p == '-' && *(p+1) == '\0') {
7054 /* Special case - "-" => no transcoding */
7055 intencoding = (rb_encoding *)Qnil;
7056 }
7057 else {
7058 intencoding = rb_to_encoding(intenc);
7059 }
7060 }
7061 else {
7062 intencoding = rb_to_encoding(intenc);
7063 }
7064 if (extencoding == intencoding) {
7065 intencoding = (rb_encoding *)Qnil;
7066 }
7067 }
7068 if (!NIL_P(encoding)) {
7069 extracted = 1;
7070 if (!NIL_P(tmp = rb_check_string_type(encoding))) {
7071 parse_mode_enc(StringValueCStr(tmp), rb_enc_get(tmp),
7072 enc_p, enc2_p, fmode_p);
7073 }
7074 else {
7075 rb_io_ext_int_to_encs(rb_to_encoding(encoding), NULL, enc_p, enc2_p, 0);
7076 }
7077 }
7078 else if (!UNDEF_P(extenc) || !UNDEF_P(intenc)) {
7079 extracted = 1;
7080 rb_io_ext_int_to_encs(extencoding, intencoding, enc_p, enc2_p, 0);
7081 }
7082 return extracted;
7083}
7084
7085static void
7086validate_enc_binmode(enum rb_io_mode *fmode_p, int ecflags, rb_encoding *enc, rb_encoding *enc2)
7087{
7088 enum rb_io_mode fmode = *fmode_p;
7089
7090 if ((fmode & FMODE_READABLE) &&
7091 !enc2 &&
7092 !(fmode & FMODE_BINMODE) &&
7093 !rb_enc_asciicompat(enc ? enc : rb_default_external_encoding()))
7094 rb_raise(rb_eArgError, "ASCII incompatible encoding needs binmode");
7095
7096 if ((fmode & FMODE_BINMODE) && (ecflags & ECONV_NEWLINE_DECORATOR_MASK)) {
7097 rb_raise(rb_eArgError, "newline decorator with binary mode");
7098 }
7099 if (!(fmode & FMODE_BINMODE) &&
7100 (DEFAULT_TEXTMODE || (ecflags & ECONV_NEWLINE_DECORATOR_MASK))) {
7101 fmode |= FMODE_TEXTMODE;
7102 *fmode_p = fmode;
7103 }
7104#if !DEFAULT_TEXTMODE
7105 else if (!(ecflags & ECONV_NEWLINE_DECORATOR_MASK)) {
7106 fmode &= ~FMODE_TEXTMODE;
7107 *fmode_p = fmode;
7108 }
7109#endif
7110}
7111
7112static void
7113extract_binmode(VALUE opthash, enum rb_io_mode *fmode)
7114{
7115 if (!NIL_P(opthash)) {
7116 VALUE v;
7117 v = rb_hash_aref(opthash, sym_textmode);
7118 if (!NIL_P(v)) {
7119 if (*fmode & FMODE_TEXTMODE)
7120 rb_raise(rb_eArgError, "textmode specified twice");
7121 if (*fmode & FMODE_BINMODE)
7122 rb_raise(rb_eArgError, "both textmode and binmode specified");
7123 if (RTEST(v))
7124 *fmode |= FMODE_TEXTMODE;
7125 }
7126 v = rb_hash_aref(opthash, sym_binmode);
7127 if (!NIL_P(v)) {
7128 if (*fmode & FMODE_BINMODE)
7129 rb_raise(rb_eArgError, "binmode specified twice");
7130 if (*fmode & FMODE_TEXTMODE)
7131 rb_raise(rb_eArgError, "both textmode and binmode specified");
7132 if (RTEST(v))
7133 *fmode |= FMODE_BINMODE;
7134 }
7135
7136 if ((*fmode & FMODE_BINMODE) && (*fmode & FMODE_TEXTMODE))
7137 rb_raise(rb_eArgError, "both textmode and binmode specified");
7138 }
7139}
7140
7141void
7142rb_io_extract_modeenc(VALUE *vmode_p, VALUE *vperm_p, VALUE opthash,
7143 int *oflags_p, enum rb_io_mode *fmode_p, struct rb_io_encoding *convconfig_p)
7144{
7145 VALUE vmode;
7146 int oflags;
7147 enum rb_io_mode fmode;
7148 rb_encoding *enc, *enc2;
7149 int ecflags;
7150 VALUE ecopts;
7151 int has_enc = 0, has_vmode = 0;
7152 VALUE intmode;
7153
7154 vmode = *vmode_p;
7155
7156 /* Set to defaults */
7157 rb_io_ext_int_to_encs(NULL, NULL, &enc, &enc2, 0);
7158
7159 vmode_handle:
7160 if (NIL_P(vmode)) {
7161 fmode = FMODE_READABLE;
7162 oflags = O_RDONLY;
7163 }
7164 else if (!NIL_P(intmode = rb_check_to_integer(vmode, "to_int"))) {
7165 vmode = intmode;
7166 oflags = NUM2INT(intmode);
7167 fmode = rb_io_oflags_fmode(oflags);
7168 }
7169 else {
7170 const char *p;
7171
7172 StringValue(vmode);
7173 p = StringValueCStr(vmode);
7174 fmode = rb_io_modestr_fmode(p);
7175 oflags = rb_io_fmode_oflags(fmode);
7176 p = strchr(p, ':');
7177 if (p) {
7178 has_enc = 1;
7179 parse_mode_enc(p+1, rb_enc_get(vmode), &enc, &enc2, &fmode);
7180 }
7181 else {
7182 rb_encoding *e;
7183
7184 e = (fmode & FMODE_BINMODE) ? rb_ascii8bit_encoding() : NULL;
7185 rb_io_ext_int_to_encs(e, NULL, &enc, &enc2, fmode);
7186 }
7187 }
7188
7189 if (NIL_P(opthash)) {
7190 ecflags = (fmode & FMODE_READABLE) ?
7193#ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE
7194 ecflags |= (fmode & FMODE_WRITABLE) ?
7195 MODE_BTMODE(TEXTMODE_NEWLINE_DECORATOR_ON_WRITE,
7196 0, TEXTMODE_NEWLINE_DECORATOR_ON_WRITE) : 0;
7197#endif
7198 SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags);
7199 ecopts = Qnil;
7200 if (fmode & FMODE_BINMODE) {
7201#ifdef O_BINARY
7202 oflags |= O_BINARY;
7203#endif
7204 if (!has_enc)
7205 rb_io_ext_int_to_encs(rb_ascii8bit_encoding(), NULL, &enc, &enc2, fmode);
7206 }
7207#if DEFAULT_TEXTMODE
7208 else if (NIL_P(vmode)) {
7209 fmode |= DEFAULT_TEXTMODE;
7210 }
7211#endif
7212 }
7213 else {
7214 VALUE v;
7215 if (!has_vmode) {
7216 v = rb_hash_aref(opthash, sym_mode);
7217 if (!NIL_P(v)) {
7218 if (!NIL_P(vmode)) {
7219 rb_raise(rb_eArgError, "mode specified twice");
7220 }
7221 has_vmode = 1;
7222 vmode = v;
7223 goto vmode_handle;
7224 }
7225 }
7226 v = rb_hash_aref(opthash, sym_flags);
7227 if (!NIL_P(v)) {
7228 v = rb_to_int(v);
7229 oflags |= NUM2INT(v);
7230 vmode = INT2NUM(oflags);
7231 fmode = rb_io_oflags_fmode(oflags);
7232 }
7233 extract_binmode(opthash, &fmode);
7234 if (fmode & FMODE_BINMODE) {
7235#ifdef O_BINARY
7236 oflags |= O_BINARY;
7237#endif
7238 if (!has_enc)
7239 rb_io_ext_int_to_encs(rb_ascii8bit_encoding(), NULL, &enc, &enc2, fmode);
7240 }
7241#if DEFAULT_TEXTMODE
7242 else if (NIL_P(vmode)) {
7243 fmode |= DEFAULT_TEXTMODE;
7244 }
7245#endif
7246 v = rb_hash_aref(opthash, sym_perm);
7247 if (!NIL_P(v)) {
7248 if (vperm_p) {
7249 if (!NIL_P(*vperm_p)) {
7250 rb_raise(rb_eArgError, "perm specified twice");
7251 }
7252 *vperm_p = v;
7253 }
7254 else {
7255 /* perm no use, just ignore */
7256 }
7257 }
7258 ecflags = (fmode & FMODE_READABLE) ?
7261#ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE
7262 ecflags |= (fmode & FMODE_WRITABLE) ?
7263 MODE_BTMODE(TEXTMODE_NEWLINE_DECORATOR_ON_WRITE,
7264 0, TEXTMODE_NEWLINE_DECORATOR_ON_WRITE) : 0;
7265#endif
7266
7267 if (rb_io_extract_encoding_option(opthash, &enc, &enc2, &fmode)) {
7268 if (has_enc) {
7269 rb_raise(rb_eArgError, "encoding specified twice");
7270 }
7271 }
7272 SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags);
7273 ecflags = rb_econv_prepare_options(opthash, &ecopts, ecflags);
7274 }
7275
7276 validate_enc_binmode(&fmode, ecflags, enc, enc2);
7277
7278 *vmode_p = vmode;
7279
7280 *oflags_p = oflags;
7281 *fmode_p = fmode;
7282 convconfig_p->enc = enc;
7283 convconfig_p->enc2 = enc2;
7284 convconfig_p->ecflags = ecflags;
7285 convconfig_p->ecopts = ecopts;
7286}
7287
7289 VALUE fname;
7290 int oflags;
7291 mode_t perm;
7292};
7293
7294static void *
7295sysopen_func(void *ptr)
7296{
7297 const struct sysopen_struct *data = ptr;
7298 const char *fname = RSTRING_PTR(data->fname);
7299 return (void *)(VALUE)rb_cloexec_open(fname, data->oflags, data->perm);
7300}
7301
7302static inline int
7303rb_sysopen_internal(struct sysopen_struct *data)
7304{
7305 int fd;
7306 do {
7307 fd = IO_WITHOUT_GVL_INT(sysopen_func, data);
7308 } while (fd < 0 && errno == EINTR);
7309 if (0 <= fd)
7310 rb_update_max_fd(fd);
7311 return fd;
7312}
7313
7314static int
7315rb_sysopen(VALUE fname, int oflags, mode_t perm)
7316{
7317 int fd = -1;
7318 struct sysopen_struct data;
7319
7320 data.fname = rb_str_encode_ospath(fname);
7321 StringValueCStr(data.fname);
7322 data.oflags = oflags;
7323 data.perm = perm;
7324
7325 TRY_WITH_GC((fd = rb_sysopen_internal(&data)) >= 0) {
7326 rb_syserr_fail_path(first_errno, fname);
7327 }
7328 return fd;
7329}
7330
7331static inline FILE *
7332fdopen_internal(int fd, const char *modestr)
7333{
7334 FILE *file;
7335
7336#if defined(__sun)
7337 errno = 0;
7338#endif
7339 file = fdopen(fd, modestr);
7340 if (!file) {
7341#ifdef _WIN32
7342 if (errno == 0) errno = EINVAL;
7343#elif defined(__sun)
7344 if (errno == 0) errno = EMFILE;
7345#endif
7346 }
7347 return file;
7348}
7349
7350FILE *
7351rb_fdopen(int fd, const char *modestr)
7352{
7353 FILE *file = 0;
7354
7355 TRY_WITH_GC((file = fdopen_internal(fd, modestr)) != 0) {
7356 rb_syserr_fail(first_errno, 0);
7357 }
7358
7359 /* xxx: should be _IONBF? A buffer in FILE may have trouble. */
7360#ifdef USE_SETVBUF
7361 if (setvbuf(file, NULL, _IOFBF, 0) != 0)
7362 rb_warn("setvbuf() can't be honoured (fd=%d)", fd);
7363#endif
7364 return file;
7365}
7366
7367static int
7368io_check_tty(rb_io_t *fptr)
7369{
7370 int t = isatty(fptr->fd);
7371 if (t)
7372 fptr->mode |= FMODE_TTY|FMODE_DUPLEX;
7373 return t;
7374}
7375
7376static VALUE rb_io_internal_encoding(VALUE);
7377static void io_encoding_set(rb_io_t *, VALUE, VALUE, VALUE);
7378
7379static int
7380io_strip_bom(VALUE io)
7381{
7382 VALUE b1, b2, b3, b4;
7383 rb_io_t *fptr;
7384
7385 GetOpenFile(io, fptr);
7386 if (!(fptr->mode & FMODE_READABLE)) return 0;
7387 if (NIL_P(b1 = rb_io_getbyte(io))) return 0;
7388 switch (b1) {
7389 case INT2FIX(0xEF):
7390 if (NIL_P(b2 = rb_io_getbyte(io))) break;
7391 if (b2 == INT2FIX(0xBB) && !NIL_P(b3 = rb_io_getbyte(io))) {
7392 if (b3 == INT2FIX(0xBF)) {
7393 return rb_utf8_encindex();
7394 }
7395 rb_io_ungetbyte(io, b3);
7396 }
7397 rb_io_ungetbyte(io, b2);
7398 break;
7399
7400 case INT2FIX(0xFE):
7401 if (NIL_P(b2 = rb_io_getbyte(io))) break;
7402 if (b2 == INT2FIX(0xFF)) {
7403 return ENCINDEX_UTF_16BE;
7404 }
7405 rb_io_ungetbyte(io, b2);
7406 break;
7407
7408 case INT2FIX(0xFF):
7409 if (NIL_P(b2 = rb_io_getbyte(io))) break;
7410 if (b2 == INT2FIX(0xFE)) {
7411 b3 = rb_io_getbyte(io);
7412 if (b3 == INT2FIX(0) && !NIL_P(b4 = rb_io_getbyte(io))) {
7413 if (b4 == INT2FIX(0)) {
7414 return ENCINDEX_UTF_32LE;
7415 }
7416 rb_io_ungetbyte(io, b4);
7417 }
7418 rb_io_ungetbyte(io, b3);
7419 return ENCINDEX_UTF_16LE;
7420 }
7421 rb_io_ungetbyte(io, b2);
7422 break;
7423
7424 case INT2FIX(0):
7425 if (NIL_P(b2 = rb_io_getbyte(io))) break;
7426 if (b2 == INT2FIX(0) && !NIL_P(b3 = rb_io_getbyte(io))) {
7427 if (b3 == INT2FIX(0xFE) && !NIL_P(b4 = rb_io_getbyte(io))) {
7428 if (b4 == INT2FIX(0xFF)) {
7429 return ENCINDEX_UTF_32BE;
7430 }
7431 rb_io_ungetbyte(io, b4);
7432 }
7433 rb_io_ungetbyte(io, b3);
7434 }
7435 rb_io_ungetbyte(io, b2);
7436 break;
7437 }
7438 rb_io_ungetbyte(io, b1);
7439 return 0;
7440}
7441
7442static rb_encoding *
7443io_set_encoding_by_bom(VALUE io)
7444{
7445 int idx = io_strip_bom(io);
7446 rb_io_t *fptr;
7447 rb_encoding *extenc = NULL;
7448
7449 GetOpenFile(io, fptr);
7450 if (idx) {
7451 extenc = rb_enc_from_index(idx);
7452 io_encoding_set(fptr, rb_enc_from_encoding(extenc),
7453 rb_io_internal_encoding(io), Qnil);
7454 }
7455 else {
7456 fptr->encs.enc2 = NULL;
7457 }
7458 return extenc;
7459}
7460
7461static VALUE
7462rb_file_open_generic(VALUE io, VALUE filename, int oflags, enum rb_io_mode fmode,
7463 const struct rb_io_encoding *convconfig, mode_t perm)
7464{
7465 VALUE pathv;
7466 rb_io_t *fptr;
7467 struct rb_io_encoding cc;
7468 if (!convconfig) {
7469 /* Set to default encodings */
7470 rb_io_ext_int_to_encs(NULL, NULL, &cc.enc, &cc.enc2, fmode);
7471 cc.ecflags = 0;
7472 cc.ecopts = Qnil;
7473 convconfig = &cc;
7474 }
7475 validate_enc_binmode(&fmode, convconfig->ecflags,
7476 convconfig->enc, convconfig->enc2);
7477
7478 MakeOpenFile(io, fptr);
7479 fptr->mode = fmode;
7480 fptr->encs = *convconfig;
7481 pathv = rb_str_new_frozen(filename);
7482#ifdef O_TMPFILE
7483 if (!(oflags & O_TMPFILE)) {
7484 fptr->pathv = pathv;
7485 }
7486#else
7487 fptr->pathv = pathv;
7488#endif
7489 fptr->fd = rb_sysopen(pathv, oflags, perm);
7490 io_check_tty(fptr);
7491 if (fmode & FMODE_SETENC_BY_BOM) io_set_encoding_by_bom(io);
7492
7493 return io;
7494}
7495
7496static VALUE
7497rb_file_open_internal(VALUE io, VALUE filename, const char *modestr)
7498{
7499 enum rb_io_mode fmode = rb_io_modestr_fmode(modestr);
7500 const char *p = strchr(modestr, ':');
7501 struct rb_io_encoding convconfig;
7502
7503 if (p) {
7504 parse_mode_enc(p+1, rb_usascii_encoding(),
7505 &convconfig.enc, &convconfig.enc2, &fmode);
7506 }
7507 else {
7508 rb_encoding *e;
7509 /* Set to default encodings */
7510
7511 e = (fmode & FMODE_BINMODE) ? rb_ascii8bit_encoding() : NULL;
7512 rb_io_ext_int_to_encs(e, NULL, &convconfig.enc, &convconfig.enc2, fmode);
7513 }
7514
7515 convconfig.ecflags = (fmode & FMODE_READABLE) ?
7518#ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE
7519 convconfig.ecflags |= (fmode & FMODE_WRITABLE) ?
7520 MODE_BTMODE(TEXTMODE_NEWLINE_DECORATOR_ON_WRITE,
7521 0, TEXTMODE_NEWLINE_DECORATOR_ON_WRITE) : 0;
7522#endif
7523 SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(convconfig.enc2, convconfig.ecflags);
7524 convconfig.ecopts = Qnil;
7525
7526 return rb_file_open_generic(io, filename,
7527 rb_io_fmode_oflags(fmode),
7528 fmode,
7529 &convconfig,
7530 0666);
7531}
7532
7533VALUE
7534rb_file_open_str(VALUE fname, const char *modestr)
7535{
7536 FilePathValue(fname);
7537 return rb_file_open_internal(io_alloc(rb_cFile), fname, modestr);
7538}
7539
7540VALUE
7541rb_file_open(const char *fname, const char *modestr)
7542{
7543 return rb_file_open_internal(io_alloc(rb_cFile), rb_str_new_cstr(fname), modestr);
7544}
7545
7546#if defined(__CYGWIN__) || !defined(HAVE_WORKING_FORK)
7547static struct pipe_list {
7548 rb_io_t *fptr;
7549 struct pipe_list *next;
7550} *pipe_list;
7551
7552static void
7553pipe_add_fptr(rb_io_t *fptr)
7554{
7555 struct pipe_list *list;
7556
7557 list = ALLOC(struct pipe_list);
7558 list->fptr = fptr;
7559 list->next = pipe_list;
7560 pipe_list = list;
7561}
7562
7563static void
7564pipe_del_fptr(rb_io_t *fptr)
7565{
7566 struct pipe_list **prev = &pipe_list;
7567 struct pipe_list *tmp;
7568
7569 while ((tmp = *prev) != 0) {
7570 if (tmp->fptr == fptr) {
7571 *prev = tmp->next;
7572 free(tmp);
7573 return;
7574 }
7575 prev = &tmp->next;
7576 }
7577}
7578
7579#if defined (_WIN32) || defined(__CYGWIN__)
7580static void
7581pipe_atexit(void)
7582{
7583 struct pipe_list *list = pipe_list;
7584 struct pipe_list *tmp;
7585
7586 /* The CRT calls this on whichever thread calls ExitProcess, which can be
7587 * one Ruby does not know, e.g. the console control handler on Ctrl+Break. */
7588 if (!rb_current_execution_context(false)) return;
7589
7590 while (list) {
7591 tmp = list->next;
7592 rb_io_fptr_finalize(list->fptr);
7593 list = tmp;
7594 }
7595}
7596#endif
7597
7598static void
7599pipe_finalize(rb_io_t *fptr, int noraise)
7600{
7601#if !defined(HAVE_WORKING_FORK) && !defined(_WIN32)
7602 int status = 0;
7603 if (fptr->stdio_file) {
7604 status = pclose(fptr->stdio_file);
7605 }
7606 fptr->fd = -1;
7607 fptr->stdio_file = 0;
7608 rb_last_status_set(status, fptr->pid);
7609#else
7610 fptr_finalize(fptr, noraise);
7611#endif
7612 pipe_del_fptr(fptr);
7613}
7614#endif
7615
7616static void
7617fptr_copy_finalizer(rb_io_t *fptr, const rb_io_t *orig)
7618{
7619#if defined(__CYGWIN__) || !defined(HAVE_WORKING_FORK)
7620 void (*const old_finalize)(struct rb_io*,int) = fptr->finalize;
7621
7622 if (old_finalize == orig->finalize) return;
7623#endif
7624
7625 fptr->finalize = orig->finalize;
7626
7627#if defined(__CYGWIN__) || !defined(HAVE_WORKING_FORK)
7628 if (old_finalize != pipe_finalize) {
7629 struct pipe_list *list;
7630 for (list = pipe_list; list; list = list->next) {
7631 if (list->fptr == fptr) break;
7632 }
7633 if (!list) pipe_add_fptr(fptr);
7634 }
7635 else {
7636 pipe_del_fptr(fptr);
7637 }
7638#endif
7639}
7640
7641void
7643{
7645 fptr->mode |= FMODE_SYNC;
7646}
7647
7648
7649int
7650rb_pipe(int *pipes)
7651{
7652 int ret;
7653 TRY_WITH_GC((ret = rb_cloexec_pipe(pipes)) >= 0);
7654 if (ret == 0) {
7655 rb_update_max_fd(pipes[0]);
7656 rb_update_max_fd(pipes[1]);
7657 }
7658 return ret;
7659}
7660
7661#ifdef _WIN32
7662#define spawnv(mode, cmd, args) rb_w32_uaspawn((mode), (cmd), (args))
7663#define spawn(mode, cmd) rb_w32_uspawn((mode), (cmd), 0)
7664#endif
7665
7666#if defined(HAVE_WORKING_FORK) || defined(HAVE_SPAWNV)
7667struct popen_arg {
7668 VALUE execarg_obj;
7669 struct rb_execarg *eargp;
7670 int modef;
7671 int pair[2];
7672 int write_pair[2];
7673};
7674#endif
7675
7676#ifdef HAVE_WORKING_FORK
7677# ifndef __EMSCRIPTEN__
7678static void
7679popen_redirect(struct popen_arg *p)
7680{
7681 if ((p->modef & FMODE_READABLE) && (p->modef & FMODE_WRITABLE)) {
7682 close(p->write_pair[1]);
7683 if (p->write_pair[0] != 0) {
7684 dup2(p->write_pair[0], 0);
7685 close(p->write_pair[0]);
7686 }
7687 close(p->pair[0]);
7688 if (p->pair[1] != 1) {
7689 dup2(p->pair[1], 1);
7690 close(p->pair[1]);
7691 }
7692 }
7693 else if (p->modef & FMODE_READABLE) {
7694 close(p->pair[0]);
7695 if (p->pair[1] != 1) {
7696 dup2(p->pair[1], 1);
7697 close(p->pair[1]);
7698 }
7699 }
7700 else {
7701 close(p->pair[1]);
7702 if (p->pair[0] != 0) {
7703 dup2(p->pair[0], 0);
7704 close(p->pair[0]);
7705 }
7706 }
7707}
7708# endif
7709
7710#if defined(__linux__)
7711/* Linux /proc/self/status contains a line: "FDSize:\t<nnn>\n"
7712 * Since /proc may not be available, linux_get_maxfd is just a hint.
7713 * This function, linux_get_maxfd, must be async-signal-safe.
7714 * I.e. opendir() is not usable.
7715 *
7716 * Note that memchr() and memcmp is *not* async-signal-safe in POSIX.
7717 * However they are easy to re-implement in async-signal-safe manner.
7718 * (Also note that there is missing/memcmp.c.)
7719 */
7720static int
7721linux_get_maxfd(void)
7722{
7723 int fd;
7724 char buf[4096], *p, *np, *e;
7725 ssize_t ss;
7726 fd = rb_cloexec_open("/proc/self/status", O_RDONLY|O_NOCTTY, 0);
7727 if (fd < 0) return fd;
7728 ss = read(fd, buf, sizeof(buf));
7729 if (ss < 0) goto err;
7730 p = buf;
7731 e = buf + ss;
7732 while ((int)sizeof("FDSize:\t0\n")-1 <= e-p &&
7733 (np = memchr(p, '\n', e-p)) != NULL) {
7734 if (memcmp(p, "FDSize:", sizeof("FDSize:")-1) == 0) {
7735 int fdsize;
7736 p += sizeof("FDSize:")-1;
7737 *np = '\0';
7738 fdsize = (int)ruby_strtoul(p, (char **)NULL, 10);
7739 close(fd);
7740 return fdsize;
7741 }
7742 p = np+1;
7743 }
7744 /* fall through */
7745
7746 err:
7747 close(fd);
7748 return (int)ss;
7749}
7750#endif
7751
7752/* This function should be async-signal-safe. */
7753void
7754rb_close_before_exec(int lowfd, int maxhint, VALUE noclose_fds)
7755{
7756#if defined(HAVE_FCNTL) && defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
7757 int fd, ret;
7758 int max = (int)max_file_descriptor;
7759# ifdef F_MAXFD
7760 /* F_MAXFD is available since NetBSD 2.0. */
7761 ret = fcntl(0, F_MAXFD); /* async-signal-safe */
7762 if (ret != -1)
7763 maxhint = max = ret;
7764# elif defined(__linux__)
7765 ret = linux_get_maxfd();
7766 if (maxhint < ret)
7767 maxhint = ret;
7768 /* maxhint = max = ret; if (ret == -1) abort(); // test */
7769# endif
7770 if (max < maxhint)
7771 max = maxhint;
7772 for (fd = lowfd; fd <= max; fd++) {
7773 if (!NIL_P(noclose_fds) &&
7774 RTEST(rb_hash_lookup(noclose_fds, INT2FIX(fd)))) /* async-signal-safe */
7775 continue;
7776 ret = fcntl(fd, F_GETFD); /* async-signal-safe */
7777 if (ret != -1 && !(ret & FD_CLOEXEC)) {
7778 fcntl(fd, F_SETFD, ret|FD_CLOEXEC); /* async-signal-safe */
7779 }
7780# define CONTIGUOUS_CLOSED_FDS 20
7781 if (ret != -1) {
7782 if (max < fd + CONTIGUOUS_CLOSED_FDS)
7783 max = fd + CONTIGUOUS_CLOSED_FDS;
7784 }
7785 }
7786#endif
7787}
7788
7789# ifndef __EMSCRIPTEN__
7790static int
7791popen_exec(void *pp, char *errmsg, size_t errmsg_len)
7792{
7793 struct popen_arg *p = (struct popen_arg*)pp;
7794
7795 return rb_exec_async_signal_safe(p->eargp, errmsg, errmsg_len);
7796}
7797# endif
7798#endif
7799
7800#if (defined(HAVE_WORKING_FORK) || defined(HAVE_SPAWNV)) && !defined __EMSCRIPTEN__
7801static VALUE
7802rb_execarg_fixup_v(VALUE execarg_obj)
7803{
7804 rb_execarg_parent_start(execarg_obj);
7805 return Qnil;
7806}
7807#else
7808char *rb_execarg_commandline(const struct rb_execarg *eargp, VALUE *prog);
7809#endif
7810
7811#ifndef __EMSCRIPTEN__
7812static VALUE
7813pipe_open(VALUE execarg_obj, const char *modestr, enum rb_io_mode fmode,
7814 const struct rb_io_encoding *convconfig)
7815{
7816 struct rb_execarg *eargp = NIL_P(execarg_obj) ? NULL : rb_execarg_get(execarg_obj);
7817 VALUE prog = eargp ? (eargp->use_shell ? eargp->invoke.sh.shell_script : eargp->invoke.cmd.command_name) : Qfalse ;
7818 rb_pid_t pid = 0;
7819 rb_io_t *fptr;
7820 VALUE port;
7821 rb_io_t *write_fptr;
7822 VALUE write_port;
7823#if defined(HAVE_WORKING_FORK)
7824 int status;
7825 char errmsg[80] = { '\0' };
7826#endif
7827#if defined(HAVE_WORKING_FORK) || defined(HAVE_SPAWNV)
7828 int state;
7829 struct popen_arg arg;
7830#endif
7831 int e = 0;
7832#if defined(HAVE_SPAWNV)
7833# define DO_SPAWN(cmd, args) ((args) ? \
7834 spawnv(P_NOWAIT, (cmd), (args)) : \
7835 spawn(P_NOWAIT, (cmd)))
7836# if !defined(HAVE_WORKING_FORK)
7837 char **args = NULL;
7838# endif
7839#endif
7840#if !defined(HAVE_WORKING_FORK)
7841 struct rb_execarg sarg, *sargp = &sarg;
7842#endif
7843 FILE *fp = 0;
7844 int fd = -1;
7845 int write_fd = -1;
7846#if !defined(HAVE_WORKING_FORK)
7847 const char *cmd = 0;
7848
7849 if (prog)
7850 cmd = StringValueCStr(prog);
7851#endif
7852
7853#if defined(HAVE_WORKING_FORK) || defined(HAVE_SPAWNV)
7854 arg.execarg_obj = execarg_obj;
7855 arg.eargp = eargp;
7856 arg.modef = fmode;
7857 arg.pair[0] = arg.pair[1] = -1;
7858 arg.write_pair[0] = arg.write_pair[1] = -1;
7859# if !defined(HAVE_WORKING_FORK)
7860 if (eargp && !eargp->use_shell) {
7861 args = ARGVSTR2ARGV(eargp->invoke.cmd.argv_str);
7862 }
7863# endif
7864 switch (fmode & (FMODE_READABLE|FMODE_WRITABLE)) {
7866 if (rb_pipe(arg.write_pair) < 0)
7867 rb_sys_fail_str(prog);
7868 if (rb_pipe(arg.pair) < 0) {
7869 e = errno;
7870 close(arg.write_pair[0]);
7871 close(arg.write_pair[1]);
7872 rb_syserr_fail_str(e, prog);
7873 }
7874 if (eargp) {
7875 rb_execarg_addopt(execarg_obj, INT2FIX(0), INT2FIX(arg.write_pair[0]));
7876 rb_execarg_addopt(execarg_obj, INT2FIX(1), INT2FIX(arg.pair[1]));
7877 }
7878 break;
7879 case FMODE_READABLE:
7880 if (rb_pipe(arg.pair) < 0)
7881 rb_sys_fail_str(prog);
7882 if (eargp)
7883 rb_execarg_addopt(execarg_obj, INT2FIX(1), INT2FIX(arg.pair[1]));
7884 break;
7885 case FMODE_WRITABLE:
7886 if (rb_pipe(arg.pair) < 0)
7887 rb_sys_fail_str(prog);
7888 if (eargp)
7889 rb_execarg_addopt(execarg_obj, INT2FIX(0), INT2FIX(arg.pair[0]));
7890 break;
7891 default:
7892 rb_sys_fail_str(prog);
7893 }
7894 if (!NIL_P(execarg_obj)) {
7895 rb_protect(rb_execarg_fixup_v, execarg_obj, &state);
7896 if (state) {
7897 if (0 <= arg.write_pair[0]) close(arg.write_pair[0]);
7898 if (0 <= arg.write_pair[1]) close(arg.write_pair[1]);
7899 if (0 <= arg.pair[0]) close(arg.pair[0]);
7900 if (0 <= arg.pair[1]) close(arg.pair[1]);
7901 rb_execarg_parent_end(execarg_obj);
7902 rb_jump_tag(state);
7903 }
7904
7905# if defined(HAVE_WORKING_FORK)
7906 pid = rb_fork_async_signal_safe(&status, popen_exec, &arg, arg.eargp->redirect_fds, errmsg, sizeof(errmsg));
7907# else
7908 rb_execarg_run_options(eargp, sargp, NULL, 0);
7909 while ((pid = DO_SPAWN(cmd, args)) < 0) {
7910 /* exec failed */
7911 switch (e = errno) {
7912 case EAGAIN:
7913# if EWOULDBLOCK != EAGAIN
7914 case EWOULDBLOCK:
7915# endif
7916 rb_thread_sleep(1);
7917 continue;
7918 }
7919 break;
7920 }
7921 if (eargp)
7922 rb_execarg_run_options(sargp, NULL, NULL, 0);
7923# endif
7924 rb_execarg_parent_end(execarg_obj);
7925 }
7926 else {
7927# if defined(HAVE_WORKING_FORK)
7928 pid = rb_call_proc__fork();
7929 if (pid == 0) { /* child */
7930 popen_redirect(&arg);
7931 rb_io_synchronized(RFILE(orig_stdout)->fptr);
7932 rb_io_synchronized(RFILE(orig_stderr)->fptr);
7933 return Qnil;
7934 }
7935# else
7937# endif
7938 }
7939
7940 /* parent */
7941 if (pid < 0) {
7942# if defined(HAVE_WORKING_FORK)
7943 e = errno;
7944# endif
7945 close(arg.pair[0]);
7946 close(arg.pair[1]);
7948 close(arg.write_pair[0]);
7949 close(arg.write_pair[1]);
7950 }
7951# if defined(HAVE_WORKING_FORK)
7952 if (errmsg[0])
7953 rb_syserr_fail(e, errmsg);
7954# endif
7955 rb_syserr_fail_str(e, prog);
7956 }
7957 if ((fmode & FMODE_READABLE) && (fmode & FMODE_WRITABLE)) {
7958 close(arg.pair[1]);
7959 fd = arg.pair[0];
7960 close(arg.write_pair[0]);
7961 write_fd = arg.write_pair[1];
7962 }
7963 else if (fmode & FMODE_READABLE) {
7964 close(arg.pair[1]);
7965 fd = arg.pair[0];
7966 }
7967 else {
7968 close(arg.pair[0]);
7969 fd = arg.pair[1];
7970 }
7971#else
7972 cmd = rb_execarg_commandline(eargp, &prog);
7973 if (!NIL_P(execarg_obj)) {
7974 rb_execarg_parent_start(execarg_obj);
7975 rb_execarg_run_options(eargp, sargp, NULL, 0);
7976 }
7977 fp = popen(cmd, modestr);
7978 e = errno;
7979 if (eargp) {
7980 rb_execarg_parent_end(execarg_obj);
7981 rb_execarg_run_options(sargp, NULL, NULL, 0);
7982 }
7983 if (!fp) rb_syserr_fail_path(e, prog);
7984 fd = fileno(fp);
7985#endif
7986
7987 port = io_alloc(rb_cIO);
7988 MakeOpenFile(port, fptr);
7989 fptr->fd = fd;
7990 fptr->stdio_file = fp;
7991 fptr->mode = fmode | FMODE_SYNC|FMODE_DUPLEX;
7992 if (convconfig) {
7993 fptr->encs = *convconfig;
7994#if RUBY_CRLF_ENVIRONMENT
7997 }
7998#endif
7999 }
8000 else {
8001 if (NEED_NEWLINE_DECORATOR_ON_READ(fptr)) {
8003 }
8004#ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE
8005 if (NEED_NEWLINE_DECORATOR_ON_WRITE(fptr)) {
8006 fptr->encs.ecflags |= TEXTMODE_NEWLINE_DECORATOR_ON_WRITE;
8007 }
8008#endif
8009 }
8010 fptr->pid = pid;
8011
8012 if (0 <= write_fd) {
8013 write_port = io_alloc(rb_cIO);
8014 MakeOpenFile(write_port, write_fptr);
8015 write_fptr->fd = write_fd;
8016 write_fptr->mode = (fmode & ~FMODE_READABLE)| FMODE_SYNC|FMODE_DUPLEX;
8017 fptr->mode &= ~FMODE_WRITABLE;
8018 fptr->tied_io_for_writing = write_port;
8019 rb_ivar_set(port, rb_intern("@tied_io_for_writing"), write_port);
8020 }
8021
8022#if defined (__CYGWIN__) || !defined(HAVE_WORKING_FORK)
8023 fptr->finalize = pipe_finalize;
8024 pipe_add_fptr(fptr);
8025#endif
8026 return port;
8027}
8028#else
8029static VALUE
8030pipe_open(VALUE execarg_obj, const char *modestr, enum rb_io_mode fmode,
8031 const struct rb_io_encoding *convconfig)
8032{
8033 rb_raise(rb_eNotImpError, "popen() is not available");
8034}
8035#endif
8036
8037static int
8038is_popen_fork(VALUE prog)
8039{
8040 if (RSTRING_LEN(prog) == 1 && RSTRING_PTR(prog)[0] == '-') {
8041#if !defined(HAVE_WORKING_FORK)
8042 rb_raise(rb_eNotImpError,
8043 "fork() function is unimplemented on this machine");
8044#else
8045 return TRUE;
8046#endif
8047 }
8048 return FALSE;
8049}
8050
8051static VALUE
8052pipe_open_s(VALUE prog, const char *modestr, enum rb_io_mode fmode,
8053 const struct rb_io_encoding *convconfig)
8054{
8055 int argc = 1;
8056 VALUE *argv = &prog;
8057 VALUE execarg_obj = Qnil;
8058
8059 if (!is_popen_fork(prog))
8060 execarg_obj = rb_execarg_new(argc, argv, TRUE, FALSE);
8061 return pipe_open(execarg_obj, modestr, fmode, convconfig);
8062}
8063
8064static VALUE
8065pipe_close(VALUE io)
8066{
8067 rb_io_t *fptr = io_close_fptr(io);
8068 if (fptr) {
8069 fptr_waitpid(fptr, rb_thread_to_be_killed(rb_thread_current()));
8070 }
8071 return Qnil;
8072}
8073
8074static VALUE popen_finish(VALUE port, VALUE klass);
8075
8076/*
8077 * call-seq:
8078 * IO.popen(env = {}, cmd, mode = 'r', **opts) -> io
8079 * IO.popen(env = {}, cmd, mode = 'r', **opts) {|io| ... } -> object
8080 *
8081 * Executes the given command +cmd+ as a subprocess
8082 * whose $stdin and $stdout are connected to a new stream +io+.
8083 *
8084 * This method has potential security vulnerabilities if called with untrusted input;
8085 * see {Command Injection}[rdoc-ref:security/command_injection.rdoc].
8086 *
8087 * If no block is given, returns the new stream,
8088 * which depending on given +mode+ may be open for reading, writing, or both.
8089 * The stream should be explicitly closed (eventually) to avoid resource leaks.
8090 *
8091 * If a block is given, the stream is passed to the block
8092 * (again, open for reading, writing, or both);
8093 * when the block exits, the stream is closed,
8094 * the block's value is returned,
8095 * and the global variable <tt>$?</tt> is set to the child's exit status.
8096 *
8097 * Optional argument +mode+ may be any valid \IO mode.
8098 * See {Access Modes}[rdoc-ref:File@Access+Modes].
8099 *
8100 * Required argument +cmd+ determines which of the following occurs:
8101 *
8102 * - The process forks.
8103 * - A specified program runs in a shell.
8104 * - A specified program runs with specified arguments.
8105 * - A specified program runs with specified arguments and a specified +argv0+.
8106 *
8107 * Each of these is detailed below.
8108 *
8109 * The optional hash argument +env+ specifies name/value pairs that are to be added
8110 * to the environment variables for the subprocess:
8111 *
8112 * IO.popen({'FOO' => 'bar'}, 'ruby', 'r+') do |pipe|
8113 * pipe.puts 'puts ENV["FOO"]'
8114 * pipe.close_write
8115 * pipe.gets
8116 * end => "bar\n"
8117 *
8118 * Optional keyword arguments +opts+ specify:
8119 *
8120 * - {Open options}[rdoc-ref:IO@Open+Options].
8121 * - {Encoding options}[rdoc-ref:encodings.rdoc@Encoding+Options].
8122 * - Options for Kernel#spawn.
8123 *
8124 * <b>Forked Process</b>
8125 *
8126 * When argument +cmd+ is the 1-character string <tt>'-'</tt>, causes the process to fork:
8127 * IO.popen('-') do |pipe|
8128 * if pipe
8129 * $stderr.puts "In parent, child pid is #{pipe.pid}\n"
8130 * else
8131 * $stderr.puts "In child, pid is #{$$}\n"
8132 * end
8133 * end
8134 *
8135 * Output:
8136 *
8137 * In parent, child pid is 26253
8138 * In child, pid is 26253
8139 *
8140 * Note that this is not supported on all platforms.
8141 *
8142 * <b>Shell Subprocess</b>
8143 *
8144 * When argument +cmd+ is a single string (but not <tt>'-'</tt>),
8145 * the program named +cmd+ is run as a shell command:
8146 *
8147 * IO.popen('uname') do |pipe|
8148 * pipe.readlines
8149 * end
8150 *
8151 * Output:
8152 *
8153 * ["Linux\n"]
8154 *
8155 * Another example:
8156 *
8157 * IO.popen('/bin/sh', 'r+') do |pipe|
8158 * pipe.puts('ls')
8159 * pipe.close_write
8160 * $stderr.puts pipe.readlines.size
8161 * end
8162 *
8163 * Output:
8164 *
8165 * 213
8166 *
8167 * <b>Program Subprocess</b>
8168 *
8169 * When argument +cmd+ is an array of strings,
8170 * the program named <tt>cmd[0]</tt> is run with all elements of +cmd+ as its arguments:
8171 *
8172 * IO.popen(['du', '..', '.']) do |pipe|
8173 * $stderr.puts pipe.readlines.size
8174 * end
8175 *
8176 * Output:
8177 *
8178 * 1111
8179 *
8180 * <b>Program Subprocess with <tt>argv0</tt></b>
8181 *
8182 * When argument +cmd+ is an array whose first element is a 2-element string array
8183 * and whose remaining elements (if any) are strings:
8184 *
8185 * - <tt>cmd[0][0]</tt> (the first string in the nested array) is the name of a program that is run.
8186 * - <tt>cmd[0][1]</tt> (the second string in the nested array) is set as the program's <tt>argv[0]</tt>.
8187 * - <tt>cmd[1..-1]</tt> (the strings in the outer array) are the program's arguments.
8188 *
8189 * Example (sets <tt>$0</tt> to 'foo'):
8190 *
8191 * IO.popen([['/bin/sh', 'foo'], '-c', 'echo $0']).read # => "foo\n"
8192 *
8193 * <b>Some Special Examples</b>
8194 *
8195 * # Set IO encoding.
8196 * IO.popen("nkf -e filename", :external_encoding=>"EUC-JP") {|nkf_io|
8197 * euc_jp_string = nkf_io.read
8198 * }
8199 *
8200 * # Merge standard output and standard error using Kernel#spawn option. See Kernel#spawn.
8201 * IO.popen(["ls", "/", :err=>[:child, :out]]) do |io|
8202 * ls_result_with_error = io.read
8203 * end
8204 *
8205 * # Use mixture of spawn options and IO options.
8206 * IO.popen(["ls", "/"], :err=>[:child, :out]) do |io|
8207 * ls_result_with_error = io.read
8208 * end
8209 *
8210 * f = IO.popen("uname")
8211 * p f.readlines
8212 * f.close
8213 * puts "Parent is #{Process.pid}"
8214 * IO.popen("date") {|f| puts f.gets }
8215 * IO.popen("-") {|f| $stderr.puts "#{Process.pid} is here, f is #{f.inspect}"}
8216 * p $?
8217 * IO.popen(%w"sed -e s|^|<foo>| -e s&$&;zot;&", "r+") {|f|
8218 * f.puts "bar"; f.close_write; puts f.gets
8219 * }
8220 *
8221 * Output (from last section):
8222 *
8223 * ["Linux\n"]
8224 * Parent is 21346
8225 * Thu Jan 15 22:41:19 JST 2009
8226 * 21346 is here, f is #<IO:fd 3>
8227 * 21352 is here, f is nil
8228 * #<Process::Status: pid 21352 exit 0>
8229 * <foo>bar;zot;
8230 *
8231 * Raises exceptions that IO.pipe and Kernel.spawn raise.
8232 *
8233 */
8234
8235static VALUE
8236rb_io_s_popen(int argc, VALUE *argv, VALUE klass)
8237{
8238 VALUE pname, pmode = Qnil, opt = Qnil, env = Qnil;
8239
8240 if (argc > 1 && !NIL_P(opt = rb_check_hash_type(argv[argc-1]))) --argc;
8241 if (argc > 1 && !NIL_P(env = rb_check_hash_type(argv[0]))) --argc, ++argv;
8242 switch (argc) {
8243 case 2:
8244 pmode = argv[1];
8245 case 1:
8246 pname = argv[0];
8247 break;
8248 default:
8249 {
8250 int ex = !NIL_P(opt);
8251 rb_error_arity(argc + ex, 1 + ex, 2 + ex);
8252 }
8253 }
8254 return popen_finish(rb_io_popen(pname, pmode, env, opt), klass);
8255}
8256
8257VALUE
8258rb_io_popen(VALUE pname, VALUE pmode, VALUE env, VALUE opt)
8259{
8260 const char *modestr;
8261 VALUE tmp, execarg_obj = Qnil;
8262 int oflags;
8263 enum rb_io_mode fmode;
8264 struct rb_io_encoding convconfig;
8265
8266 tmp = rb_check_array_type(pname);
8267 if (!NIL_P(tmp)) {
8268 rb_len_t len = RARRAY_LEN(tmp);
8269#if SIZEOF_RB_LEN_T > SIZEOF_INT
8270 if (len > INT_MAX) {
8271 rb_raise(rb_eArgError, "too many arguments");
8272 }
8273#endif
8274 execarg_obj = rb_execarg_new((int)len, RARRAY_CONST_PTR(tmp), FALSE, FALSE);
8275 RB_GC_GUARD(tmp);
8276 }
8277 else {
8278 StringValue(pname);
8279 execarg_obj = Qnil;
8280 if (!is_popen_fork(pname))
8281 execarg_obj = rb_execarg_new(1, &pname, TRUE, FALSE);
8282 }
8283 if (!NIL_P(execarg_obj)) {
8284 if (!NIL_P(opt))
8285 opt = rb_execarg_extract_options(execarg_obj, opt);
8286 if (!NIL_P(env))
8287 rb_execarg_setenv(execarg_obj, env);
8288 }
8289 rb_io_extract_modeenc(&pmode, 0, opt, &oflags, &fmode, &convconfig);
8290 modestr = rb_io_oflags_modestr(oflags);
8291
8292 return pipe_open(execarg_obj, modestr, fmode, &convconfig);
8293}
8294
8295static VALUE
8296popen_finish(VALUE port, VALUE klass)
8297{
8298 if (NIL_P(port)) {
8299 /* child */
8300 if (rb_block_given_p()) {
8301 rb_protect(rb_yield, Qnil, NULL);
8302 rb_io_flush(rb_ractor_stdout());
8303 rb_io_flush(rb_ractor_stderr());
8304 _exit(EXIT_SUCCESS);
8305 }
8306 return Qnil;
8307 }
8308 RBASIC_SET_CLASS(port, klass);
8309 if (rb_block_given_p()) {
8310 return rb_ensure(rb_yield, port, pipe_close, port);
8311 }
8312 return port;
8313}
8314
8315#if defined(HAVE_WORKING_FORK) && !defined(__EMSCRIPTEN__)
8316struct popen_writer_arg {
8317 char *const *argv;
8318 struct popen_arg popen;
8319};
8320
8321static int
8322exec_popen_writer(void *arg, char *errmsg, size_t buflen)
8323{
8324 struct popen_writer_arg *pw = arg;
8325 pw->popen.modef = FMODE_WRITABLE;
8326 popen_redirect(&pw->popen);
8327 execv(pw->argv[0], pw->argv);
8328 strlcpy(errmsg, strerror(errno), buflen);
8329 return -1;
8330}
8331#endif
8332
8333FILE *
8334ruby_popen_writer(char *const *argv, rb_pid_t *pid)
8335{
8336#if (defined(HAVE_WORKING_FORK) && !defined(__EMSCRIPTEN__)) || defined(_WIN32)
8337# ifdef HAVE_WORKING_FORK
8338 struct popen_writer_arg pw;
8339 int *const write_pair = pw.popen.pair;
8340# else
8341 int write_pair[2];
8342# endif
8343
8344 *pid = -1;
8345 if (cloexec_pipe(write_pair, 0, false) == 0) {
8346# ifdef HAVE_WORKING_FORK
8347 pw.argv = argv;
8348 int status;
8349 char errmsg[80] = {'\0'};
8350 *pid = rb_fork_async_signal_safe(&status, exec_popen_writer, &pw, Qnil, errmsg, sizeof(errmsg));
8351# else
8352 *pid = rb_w32_uspawn_process(P_NOWAIT, argv[0], argv, write_pair[0], -1, -1, 0);
8353 const char *errmsg = (*pid < 0) ? strerror(errno) : NULL;
8354# endif
8355 close(write_pair[0]);
8356 if (*pid < 0) {
8357 close(write_pair[1]);
8358 fprintf(stderr, "ruby_popen_writer(%s): %s\n", argv[0], errmsg);
8359 }
8360 else {
8361 return fdopen(write_pair[1], "w");
8362 }
8363 }
8364#endif
8365 return NULL;
8366}
8367
8368static VALUE
8369rb_open_file(VALUE io, VALUE fname, VALUE vmode, VALUE vperm, VALUE opt)
8370{
8371 int oflags;
8372 enum rb_io_mode fmode;
8373 struct rb_io_encoding convconfig;
8374 mode_t perm;
8375
8376 FilePathValue(fname);
8377
8378 rb_io_extract_modeenc(&vmode, &vperm, opt, &oflags, &fmode, &convconfig);
8379 perm = NIL_P(vperm) ? 0666 : NUM2MODET(vperm);
8380
8381 rb_file_open_generic(io, fname, oflags, fmode, &convconfig, perm);
8382
8383 return io;
8384}
8385
8386/*
8387 * Document-method: File::open
8388 *
8389 * :markup: markdown
8390 *
8391 * call-seq:
8392 * File.open(path, mode = 'r', permissions = 0666, **options) -> file
8393 * File.open(path, mode = 'r', permissions = 0666, **options) {|file| ... } -> object
8394 *
8395 * Creates a new \File object via File.new with the given arguments.
8396 *
8397 * With no block given, returns the \File object.
8398 *
8399 * With a block given, calls the block with the \File object,
8400 * closes the \File object, and returns the block's value:
8401 *
8402 * ```ruby
8403 * File.open('doc/maintainers.md') {|file| file.size } # => 14900
8404 * ```
8405 *
8406 * Note that the \File object is automatically closed
8407 * even if the block raises an exception.
8408 */
8409
8410/*
8411 * Document-method: IO::open
8412 *
8413 * :markup: markdown
8414 *
8415 * call-seq:
8416 * IO.open(fd, mode = 'r', **options) -> io
8417 * IO.open(fd, mode = 'r', **options) {|io| ... } -> object
8418 *
8419 * Creates a new \IO object via IO.new with the given arguments.
8420 *
8421 * With no block given, returns the \IO object.
8422 *
8423 * With a block given, calls the block with the \IO object,
8424 * closes the \IO object, and returns the block’s value:
8425 *
8426 * ```ruby
8427 * fd = File.sysopen('doc/maintainers.md') # => 6
8428 * IO.open(fd) {|io| io.read.size } # => 14897
8429 * ```
8430 */
8431
8432static VALUE
8433rb_io_s_open(int argc, VALUE *argv, VALUE klass)
8434{
8436
8437 if (rb_block_given_p()) {
8438 return rb_ensure(rb_yield, io, io_close, io);
8439 }
8440
8441 return io;
8442}
8443
8444/*
8445 * call-seq:
8446 * IO.sysopen(path, mode = 'r', perm = 0666) -> integer
8447 *
8448 * Opens the file at the given path with the given mode and permissions;
8449 * returns the integer file descriptor.
8450 *
8451 * If the file is to be readable, it must exist;
8452 * if the file is to be writable and does not exist,
8453 * it is created with the given permissions:
8454 *
8455 * File.write('t.tmp', '') # => 0
8456 * IO.sysopen('t.tmp') # => 8
8457 * IO.sysopen('t.tmp', 'w') # => 9
8458 *
8459 *
8460 */
8461
8462static VALUE
8463rb_io_s_sysopen(int argc, VALUE *argv, VALUE _)
8464{
8465 VALUE fname, vmode, vperm;
8466 VALUE intmode;
8467 int oflags, fd;
8468 mode_t perm;
8469
8470 rb_scan_args(argc, argv, "12", &fname, &vmode, &vperm);
8471 FilePathValue(fname);
8472
8473 if (NIL_P(vmode))
8474 oflags = O_RDONLY;
8475 else if (!NIL_P(intmode = rb_check_to_integer(vmode, "to_int")))
8476 oflags = NUM2INT(intmode);
8477 else {
8478 StringValue(vmode);
8479 oflags = rb_io_modestr_oflags(StringValueCStr(vmode));
8480 }
8481 if (NIL_P(vperm)) perm = 0666;
8482 else perm = NUM2MODET(vperm);
8483
8484 RB_GC_GUARD(fname) = rb_str_new4(fname);
8485 fd = rb_sysopen(fname, oflags, perm);
8486 return INT2NUM(fd);
8487}
8488
8489/*
8490 * call-seq:
8491 * open(path, mode = 'r', perm = 0666, **opts) -> io or nil
8492 * open(path, mode = 'r', perm = 0666, **opts) {|io| ... } -> obj
8493 *
8494 * Creates an IO object connected to the given file.
8495 *
8496 * With no block given, file stream is returned:
8497 *
8498 * open('t.txt') # => #<File:t.txt>
8499 *
8500 * With a block given, calls the block with the open file stream,
8501 * then closes the stream:
8502 *
8503 * open('t.txt') {|f| p f } # => #<File:t.txt (closed)>
8504 *
8505 * Output:
8506 *
8507 * #<File:t.txt>
8508 *
8509 * See File.open for details.
8510 *
8511 */
8512
8513static VALUE
8514rb_f_open(int argc, VALUE *argv, VALUE _)
8515{
8516 ID to_open = 0;
8517 int redirect = FALSE;
8518
8519 if (argc >= 1) {
8520 CONST_ID(to_open, "to_open");
8521 if (rb_respond_to(argv[0], to_open)) {
8522 redirect = TRUE;
8523 }
8524 else {
8525 VALUE tmp = argv[0];
8526 FilePathValue(tmp);
8527 if (NIL_P(tmp)) {
8528 redirect = TRUE;
8529 }
8530 else {
8531 argv[0] = tmp;
8532 }
8533 }
8534 }
8535 if (redirect) {
8536 VALUE io = rb_funcallv_kw(argv[0], to_open, argc-1, argv+1, RB_PASS_CALLED_KEYWORDS);
8537
8538 if (rb_block_given_p()) {
8539 return rb_ensure(rb_yield, io, io_close, io);
8540 }
8541 return io;
8542 }
8543 return rb_io_s_open(argc, argv, rb_cFile);
8544}
8545
8546static VALUE
8547rb_io_open_generic(VALUE klass, VALUE filename, int oflags, enum rb_io_mode fmode,
8548 const struct rb_io_encoding *convconfig, mode_t perm)
8549{
8550 return rb_file_open_generic(io_alloc(klass), filename,
8551 oflags, fmode, convconfig, perm);
8552}
8553
8554static VALUE
8555rb_io_open(VALUE io, VALUE filename, VALUE vmode, VALUE vperm, VALUE opt)
8556{
8557 int oflags;
8558 enum rb_io_mode fmode;
8559 struct rb_io_encoding convconfig;
8560 mode_t perm;
8561
8562 rb_io_extract_modeenc(&vmode, &vperm, opt, &oflags, &fmode, &convconfig);
8563 perm = NIL_P(vperm) ? 0666 : NUM2MODET(vperm);
8564 return rb_io_open_generic(io, filename, oflags, fmode, &convconfig, perm);
8565}
8566
8567static VALUE
8568io_reopen(VALUE io, VALUE nfile)
8569{
8570 rb_io_t *fptr, *orig;
8571 int fd, fd2;
8572 rb_off_t pos = 0;
8573
8574 nfile = rb_io_get_io(nfile);
8575 GetOpenFile(io, fptr);
8576 GetOpenFile(nfile, orig);
8577
8578 if (fptr == orig) return io;
8579 if (RUBY_IO_EXTERNAL_P(fptr)) {
8580 if ((fptr->stdio_file == stdin && !(orig->mode & FMODE_READABLE)) ||
8581 (fptr->stdio_file == stdout && !(orig->mode & FMODE_WRITABLE)) ||
8582 (fptr->stdio_file == stderr && !(orig->mode & FMODE_WRITABLE))) {
8583 rb_raise(rb_eArgError,
8584 "%s can't change access mode from \"%s\" to \"%s\"",
8585 PREP_STDIO_NAME(fptr), rb_io_fmode_modestr(fptr->mode),
8586 rb_io_fmode_modestr(orig->mode));
8587 }
8588 }
8589 flush_before_seek(fptr, true);
8590 /* in flush_before_seek, clear_codeconv called only if rbuf is filled */
8591 clear_codeconv(fptr);
8592 if (orig->mode & FMODE_READABLE) {
8593 pos = io_tell(orig);
8594 }
8595 if (orig->mode & FMODE_WRITABLE) {
8596 if (io_fflush(orig) < 0)
8597 rb_sys_fail_on_write(fptr);
8598 }
8599
8600 /* copy rb_io_t structure */
8601 fptr->mode = orig->mode | (fptr->mode & FMODE_EXTERNAL);
8602 fptr->encs = orig->encs;
8603 fptr->pid = orig->pid;
8604 fptr->lineno = orig->lineno;
8605 if (RTEST(orig->pathv)) fptr->pathv = orig->pathv;
8606 else if (!RUBY_IO_EXTERNAL_P(fptr)) fptr->pathv = Qnil;
8607 fptr_copy_finalizer(fptr, orig);
8608
8609 fd = fptr->fd;
8610 fd2 = orig->fd;
8611 if (fd != fd2) {
8612 // Interrupt all usage of the old file descriptor:
8613 rb_thread_io_close_interrupt(fptr);
8614 rb_thread_io_close_wait(fptr);
8615
8616 if (RUBY_IO_EXTERNAL_P(fptr) || fd <= 2 || !fptr->stdio_file) {
8617 /* need to keep FILE objects of stdin, stdout and stderr */
8618 if (rb_cloexec_dup2(fd2, fd) < 0)
8619 rb_sys_fail_path(orig->pathv);
8620 rb_update_max_fd(fd);
8621 }
8622 else {
8623 fclose(fptr->stdio_file);
8624 fptr->stdio_file = 0;
8625 fptr->fd = -1;
8626 if (rb_cloexec_dup2(fd2, fd) < 0)
8627 rb_sys_fail_path(orig->pathv);
8628 rb_update_max_fd(fd);
8629 fptr->fd = fd;
8630 }
8631
8632 if ((orig->mode & FMODE_READABLE) && pos >= 0) {
8633 if (io_seek(fptr, pos, SEEK_SET) < 0 && errno) {
8634 rb_sys_fail_path(fptr->pathv);
8635 }
8636 if (io_seek(orig, pos, SEEK_SET) < 0 && errno) {
8637 rb_sys_fail_path(orig->pathv);
8638 }
8639 }
8640 }
8641
8642 if (fptr->mode & FMODE_BINMODE) {
8643 rb_io_binmode(io);
8644 }
8645
8646 RBASIC_SET_CLASS(io, rb_obj_class(nfile));
8647 return io;
8648}
8649
8650#ifdef _WIN32
8651int rb_freopen(VALUE fname, const char *mode, FILE *fp);
8652#else
8653static int
8654rb_freopen(VALUE fname, const char *mode, FILE *fp)
8655{
8656 if (!freopen(RSTRING_PTR(fname), mode, fp)) {
8657 RB_GC_GUARD(fname);
8658 return errno;
8659 }
8660 return 0;
8661}
8662#endif
8663
8664/*
8665 * call-seq:
8666 * reopen(other_io) -> self
8667 * reopen(path, mode = 'r', **opts) -> self
8668 *
8669 * Reassociates the stream with another stream,
8670 * which may be of a different class.
8671 * This method may be used to redirect an existing stream
8672 * to a new destination.
8673 *
8674 * With argument +other_io+ given, reassociates with that stream:
8675 *
8676 * # Redirect $stdin from a file.
8677 * f = File.open('t.txt')
8678 * $stdin.reopen(f)
8679 * f.close
8680 *
8681 * # Redirect $stdout to a file.
8682 * f = File.open('t.tmp', 'w')
8683 * $stdout.reopen(f)
8684 * f.close
8685 *
8686 * With argument +path+ given, reassociates with a new stream to that file path:
8687 *
8688 * $stdin.reopen('t.txt')
8689 * $stdout.reopen('t.tmp', 'w')
8690 *
8691 * Optional keyword arguments +opts+ specify:
8692 *
8693 * - {Open Options}[rdoc-ref:IO@Open+Options].
8694 * - {Encoding options}[rdoc-ref:encodings.rdoc@Encoding+Options].
8695 *
8696 */
8697
8698static VALUE
8699rb_io_reopen(int argc, VALUE *argv, VALUE file)
8700{
8701 VALUE fname, nmode, opt;
8702 int oflags;
8703 rb_io_t *fptr;
8704
8705 if (rb_scan_args(argc, argv, "11:", &fname, &nmode, &opt) == 1) {
8706 VALUE tmp = rb_io_check_io(fname);
8707 if (!NIL_P(tmp)) {
8708 return io_reopen(file, tmp);
8709 }
8710 }
8711
8712 FilePathValue(fname);
8713 rb_io_taint_check(file);
8714 fptr = RFILE(file)->fptr;
8716
8717 if (!NIL_P(nmode) || !NIL_P(opt)) {
8718 enum rb_io_mode fmode;
8719 struct rb_io_encoding convconfig;
8720
8721 rb_io_extract_modeenc(&nmode, 0, opt, &oflags, &fmode, &convconfig);
8722 if (RUBY_IO_EXTERNAL_P(fptr) &&
8723 ((fptr->mode & FMODE_READWRITE) & (fmode & FMODE_READWRITE)) !=
8724 (fptr->mode & FMODE_READWRITE)) {
8725 rb_raise(rb_eArgError,
8726 "%s can't change access mode from \"%s\" to \"%s\"",
8727 PREP_STDIO_NAME(fptr), rb_io_fmode_modestr(fptr->mode),
8728 rb_io_fmode_modestr(fmode));
8729 }
8730 fptr->mode = fmode;
8731 fptr->encs = convconfig;
8732 }
8733 else {
8734 oflags = rb_io_fmode_oflags(fptr->mode);
8735 }
8736
8737 fptr->pathv = fname;
8738 if (fptr->fd < 0) {
8739 fptr->fd = rb_sysopen(fptr->pathv, oflags, 0666);
8740 fptr->stdio_file = 0;
8741 return file;
8742 }
8743
8744 if (fptr->mode & FMODE_WRITABLE) {
8745 if (io_fflush(fptr) < 0)
8746 rb_sys_fail_on_write(fptr);
8747 }
8748 fptr->rbuf.off = fptr->rbuf.len = 0;
8749 clear_codeconv(fptr);
8750
8751 if (fptr->stdio_file) {
8752 int e = rb_freopen(rb_str_encode_ospath(fptr->pathv),
8753 rb_io_oflags_modestr(oflags),
8754 fptr->stdio_file);
8755 if (e) rb_syserr_fail_path(e, fptr->pathv);
8756 fptr->fd = fileno(fptr->stdio_file);
8757 rb_fd_fix_cloexec(fptr->fd);
8758#ifdef USE_SETVBUF
8759 if (setvbuf(fptr->stdio_file, NULL, _IOFBF, 0) != 0)
8760 rb_warn("setvbuf() can't be honoured for %"PRIsVALUE, fptr->pathv);
8761#endif
8762 if (fptr->stdio_file == stderr) {
8763 if (setvbuf(fptr->stdio_file, NULL, _IONBF, BUFSIZ) != 0)
8764 rb_warn("setvbuf() can't be honoured for %"PRIsVALUE, fptr->pathv);
8765 }
8766 else if (fptr->stdio_file == stdout && isatty(fptr->fd)) {
8767 if (setvbuf(fptr->stdio_file, NULL, _IOLBF, BUFSIZ) != 0)
8768 rb_warn("setvbuf() can't be honoured for %"PRIsVALUE, fptr->pathv);
8769 }
8770 }
8771 else {
8772 int tmpfd = rb_sysopen(fptr->pathv, oflags, 0666);
8773 int err = 0;
8774 if (rb_cloexec_dup2(tmpfd, fptr->fd) < 0)
8775 err = errno;
8776 (void)close(tmpfd);
8777 if (err) {
8778 rb_syserr_fail_path(err, fptr->pathv);
8779 }
8780 }
8781
8782 return file;
8783}
8784
8785/* :nodoc: */
8786static VALUE
8787rb_io_init_copy(VALUE dest, VALUE io)
8788{
8789 rb_io_t *fptr, *orig;
8790 int fd;
8791 VALUE write_io;
8792 rb_off_t pos;
8793
8794 io = rb_io_get_io(io);
8795 if (!OBJ_INIT_COPY(dest, io)) return dest;
8796 GetOpenFile(io, orig);
8797 MakeOpenFile(dest, fptr);
8798
8799 rb_io_flush(io);
8800
8801 /* copy rb_io_t structure */
8802 fptr->mode = orig->mode & ~FMODE_EXTERNAL;
8803 fptr->encs = orig->encs;
8804 fptr->pid = orig->pid;
8805 fptr->lineno = orig->lineno;
8806 fptr->timeout = orig->timeout;
8807
8808 ccan_list_head_init(&fptr->blocking_operations);
8809 fptr->closing_ec = NULL;
8810 fptr->wakeup_mutex = Qnil;
8811 fptr->fork_generation = GET_VM()->fork_gen;
8812
8813 if (!NIL_P(orig->pathv)) fptr->pathv = orig->pathv;
8814 fptr_copy_finalizer(fptr, orig);
8815
8816 fd = ruby_dup(orig->fd);
8817 fptr->fd = fd;
8818 pos = io_tell(orig);
8819 if (0 <= pos)
8820 io_seek(fptr, pos, SEEK_SET);
8821 if (fptr->mode & FMODE_BINMODE) {
8822 rb_io_binmode(dest);
8823 }
8824
8825 write_io = GetWriteIO(io);
8826 if (io != write_io) {
8827 write_io = rb_obj_dup(write_io);
8828 fptr->tied_io_for_writing = write_io;
8829 rb_ivar_set(dest, rb_intern("@tied_io_for_writing"), write_io);
8830 }
8831
8832 return dest;
8833}
8834
8835/*
8836 * call-seq:
8837 * printf(format_string, *objects) -> nil
8838 *
8839 * Formats and writes +objects+ to the stream.
8840 *
8841 * For details on +format_string+, see
8842 * {Format Specifications}[rdoc-ref:language/format_specifications.rdoc].
8843 *
8844 */
8845
8846VALUE
8847rb_io_printf(int argc, const VALUE *argv, VALUE out)
8848{
8849 rb_io_write(out, rb_f_sprintf(argc, argv));
8850 return Qnil;
8851}
8852
8853/*
8854 * call-seq:
8855 * printf(format_string, *objects) -> nil
8856 * printf(io, format_string, *objects) -> nil
8857 *
8858 * Equivalent to:
8859 *
8860 * io.write(sprintf(format_string, *objects))
8861 *
8862 * For details on +format_string+, see
8863 * {Format Specifications}[rdoc-ref:language/format_specifications.rdoc].
8864 *
8865 * With the single argument +format_string+, formats +objects+ into the string,
8866 * then writes the formatted string to $stdout:
8867 *
8868 * printf('%4.4d %10s %2.2f', 24, 24, 24.0)
8869 *
8870 * Output (on $stdout):
8871 *
8872 * 0024 24 24.00#
8873 *
8874 * With arguments +io+ and +format_string+, formats +objects+ into the string,
8875 * then writes the formatted string to +io+:
8876 *
8877 * printf($stderr, '%4.4d %10s %2.2f', 24, 24, 24.0)
8878 *
8879 * Output (on $stderr):
8880 *
8881 * 0024 24 24.00# => nil
8882 *
8883 * With no arguments, does nothing.
8884 *
8885 */
8886
8887static VALUE
8888rb_f_printf(int argc, VALUE *argv, VALUE _)
8889{
8890 VALUE out;
8891
8892 if (argc == 0) return Qnil;
8893 if (RB_TYPE_P(argv[0], T_STRING)) {
8894 out = rb_ractor_stdout();
8895 }
8896 else {
8897 out = argv[0];
8898 argv++;
8899 argc--;
8900 }
8901 rb_io_write(out, rb_f_sprintf(argc, argv));
8902
8903 return Qnil;
8904}
8905
8906extern void rb_deprecated_str_setter(VALUE val, ID id, VALUE *var);
8907
8908static void
8909deprecated_rs_setter(VALUE val, ID id, VALUE *var)
8910{
8911 rb_deprecated_str_setter(val, id, &val);
8912 if (!NIL_P(val)) {
8913 if (rb_str_equal(val, rb_default_rs)) {
8914 val = rb_default_rs;
8915 }
8916 else {
8917 val = rb_str_frozen_bare_string(val);
8918 }
8919 }
8920 *var = val;
8921}
8922
8923/*
8924 * call-seq:
8925 * print(*objects) -> nil
8926 *
8927 * Writes the given objects to the stream; returns +nil+.
8928 * Appends the output record separator <tt>$OUTPUT_RECORD_SEPARATOR</tt>
8929 * (<tt>$\</tt>), if it is not +nil+.
8930 * See {Line IO}[rdoc-ref:IO@Line+IO].
8931 *
8932 * With argument +objects+ given, for each object:
8933 *
8934 * - Converts via its method +to_s+ if not a string.
8935 * - Writes to the stream.
8936 * - If not the last object, writes the output field separator
8937 * <tt>$OUTPUT_FIELD_SEPARATOR</tt> (<tt>$,</tt>) if it is not +nil+.
8938 *
8939 * With default separators:
8940 *
8941 * f = File.open('t.tmp', 'w+')
8942 * objects = [0, 0.0, Rational(0, 1), Complex(0, 0), :zero, 'zero']
8943 * p $OUTPUT_RECORD_SEPARATOR
8944 * p $OUTPUT_FIELD_SEPARATOR
8945 * f.print(*objects)
8946 * f.rewind
8947 * p f.read
8948 * f.close
8949 *
8950 * Output:
8951 *
8952 * nil
8953 * nil
8954 * "00.00/10+0izerozero"
8955 *
8956 * With specified separators:
8957 *
8958 * $\ = "\n"
8959 * $, = ','
8960 * f.rewind
8961 * f.print(*objects)
8962 * f.rewind
8963 * p f.read
8964 *
8965 * Output:
8966 *
8967 * "0,0.0,0/1,0+0i,zero,zero\n"
8968 *
8969 * With no argument given, writes the content of <tt>$_</tt>
8970 * (which is usually the most recent user input):
8971 *
8972 * f = File.open('t.tmp', 'w+')
8973 * gets # Sets $_ to the most recent user input.
8974 * f.print
8975 * f.close
8976 *
8977 */
8978
8979VALUE
8980rb_io_print(int argc, const VALUE *argv, VALUE out)
8981{
8982 int i;
8983 VALUE line;
8984
8985 /* if no argument given, print `$_' */
8986 if (argc == 0) {
8987 argc = 1;
8988 line = rb_lastline_get();
8989 argv = &line;
8990 }
8991 if (argc > 1 && !NIL_P(rb_output_fs)) {
8992 rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "$, is set to non-nil value");
8993 }
8994 for (i=0; i<argc; i++) {
8995 if (!NIL_P(rb_output_fs) && i>0) {
8996 rb_io_write(out, rb_output_fs);
8997 }
8998 rb_io_write(out, argv[i]);
8999 }
9000 if (argc > 0 && !NIL_P(rb_output_rs)) {
9001 rb_io_write(out, rb_output_rs);
9002 }
9003
9004 return Qnil;
9005}
9006
9007/*
9008 * call-seq:
9009 * print(*objects) -> nil
9010 *
9011 * Equivalent to <tt>$stdout.print(*objects)</tt>,
9012 * this method is the straightforward way to write to <tt>$stdout</tt>.
9013 *
9014 * Writes the given objects to <tt>$stdout</tt>; returns +nil+.
9015 * Appends the output record separator <tt>$OUTPUT_RECORD_SEPARATOR</tt>
9016 * (<tt>$\</tt>), if it is not +nil+.
9017 *
9018 * With argument +objects+ given, for each object:
9019 *
9020 * - Converts via its method +to_s+ if not a string.
9021 * - Writes to <tt>stdout</tt>.
9022 * - If not the last object, writes the output field separator
9023 * <tt>$OUTPUT_FIELD_SEPARATOR</tt> (<tt>$,</tt>) if it is not +nil+.
9024 *
9025 * With default separators:
9026 *
9027 * objects = [0, 0.0, Rational(0, 1), Complex(0, 0), :zero, 'zero']
9028 * $OUTPUT_RECORD_SEPARATOR
9029 * $OUTPUT_FIELD_SEPARATOR
9030 * print(*objects)
9031 *
9032 * Output:
9033 *
9034 * nil
9035 * nil
9036 * 00.00/10+0izerozero
9037 *
9038 * With specified separators:
9039 *
9040 * $OUTPUT_RECORD_SEPARATOR = "\n"
9041 * $OUTPUT_FIELD_SEPARATOR = ','
9042 * print(*objects)
9043 *
9044 * Output:
9045 *
9046 * 0,0.0,0/1,0+0i,zero,zero
9047 *
9048 * With no argument given, writes the content of <tt>$_</tt>
9049 * (which is usually the most recent user input):
9050 *
9051 * gets # Sets $_ to the most recent user input.
9052 * print # Prints $_.
9053 *
9054 */
9055
9056static VALUE
9057rb_f_print(int argc, const VALUE *argv, VALUE _)
9058{
9059 rb_io_print(argc, argv, rb_ractor_stdout());
9060 return Qnil;
9061}
9062
9063/*
9064 * call-seq:
9065 * putc(object) -> object
9066 *
9067 * Writes a character to the stream.
9068 * See {Character IO}[rdoc-ref:IO@Character+IO].
9069 *
9070 * If +object+ is numeric, converts to integer if necessary,
9071 * then writes the character whose code is the
9072 * least significant byte;
9073 * if +object+ is a string, writes the first character:
9074 *
9075 * $stdout.putc "A"
9076 * $stdout.putc 65
9077 *
9078 * Output:
9079 *
9080 * AA
9081 *
9082 */
9083
9084static VALUE
9085rb_io_putc(VALUE io, VALUE ch)
9086{
9087 VALUE str;
9088 if (RB_TYPE_P(ch, T_STRING)) {
9089 str = rb_str_substr(ch, 0, 1);
9090 }
9091 else {
9092 char c = NUM2CHR(ch);
9093 str = rb_str_new(&c, 1);
9094 }
9095 rb_io_write(io, str);
9096 return ch;
9097}
9098
9099#define forward(obj, id, argc, argv) \
9100 rb_funcallv_kw(obj, id, argc, argv, RB_PASS_CALLED_KEYWORDS)
9101#define forward_public(obj, id, argc, argv) \
9102 rb_funcallv_public_kw(obj, id, argc, argv, RB_PASS_CALLED_KEYWORDS)
9103#define forward_current(id, argc, argv) \
9104 forward_public(ARGF.current_file, id, argc, argv)
9105
9106/*
9107 * call-seq:
9108 * putc(int) -> int
9109 *
9110 * Equivalent to:
9111 *
9112 * $stdout.putc(int)
9113 *
9114 * See IO#putc for important information regarding multi-byte characters.
9115 *
9116 */
9117
9118static VALUE
9119rb_f_putc(VALUE recv, VALUE ch)
9120{
9121 VALUE r_stdout = rb_ractor_stdout();
9122 if (recv == r_stdout) {
9123 return rb_io_putc(recv, ch);
9124 }
9125 return forward(r_stdout, rb_intern("putc"), 1, &ch);
9126}
9127
9128
9129int
9130rb_str_end_with_asciichar(VALUE str, int c)
9131{
9132 rb_len_t len = RSTRING_LEN(str);
9133 const char *ptr = RSTRING_PTR(str);
9134 rb_encoding *enc = rb_enc_from_index(ENCODING_GET(str));
9135 int n;
9136
9137 if (len == 0) return 0;
9138 if ((n = rb_enc_mbminlen(enc)) == 1) {
9139 return ptr[len - 1] == c;
9140 }
9141 return rb_enc_ascget(ptr + ((len - 1) / n) * n, ptr + len, &n, enc) == c;
9142}
9143
9144static VALUE
9145io_puts_ary(VALUE ary, VALUE out, int recur)
9146{
9147 VALUE tmp;
9148 rb_len_t i;
9149
9150 if (recur) {
9151 tmp = rb_str_new2("[...]");
9152 rb_io_puts(1, &tmp, out);
9153 return Qtrue;
9154 }
9155 ary = rb_check_array_type(ary);
9156 if (NIL_P(ary)) return Qfalse;
9157 for (i=0; i<RARRAY_LEN(ary); i++) {
9158 tmp = RARRAY_AREF(ary, i);
9159 rb_io_puts(1, &tmp, out);
9160 }
9161 return Qtrue;
9162}
9163
9164/*
9165 * call-seq:
9166 * puts(*objects) -> nil
9167 *
9168 * Writes the given +objects+ to the stream, which must be open for writing;
9169 * returns +nil+.\
9170 * Writes a newline after each that does not already end with a newline sequence.
9171 * If called without arguments, writes a newline.
9172 * See {Line IO}[rdoc-ref:IO@Line+IO].
9173 *
9174 * Note that each added newline is the character <tt>"\n"</tt>,
9175 * not the output record separator (<tt>$\</tt>).
9176 *
9177 * Treatment for each object:
9178 *
9179 * - String: writes the string.
9180 * - Neither string nor array: writes <tt>object.to_s</tt>.
9181 * - Array: writes each element of the array; arrays may be nested.
9182 *
9183 * To keep these examples brief, we define this helper method:
9184 *
9185 * def show(*objects)
9186 * # Puts objects to file.
9187 * f = File.new('t.tmp', 'w+')
9188 * f.puts(objects)
9189 * # Return file content.
9190 * f.rewind
9191 * p f.read
9192 * f.close
9193 * end
9194 *
9195 * # Strings without newlines.
9196 * show('foo', 'bar', 'baz') # => "foo\nbar\nbaz\n"
9197 * # Strings, some with newlines.
9198 * show("foo\n", 'bar', "baz\n") # => "foo\nbar\nbaz\n"
9199 *
9200 * # Neither strings nor arrays:
9201 * show(0, 0.0, Rational(0, 1), Complex(9, 0), :zero)
9202 * # => "0\n0.0\n0/1\n9+0i\nzero\n"
9203 *
9204 * # Array of strings.
9205 * show(['foo', "bar\n", 'baz']) # => "foo\nbar\nbaz\n"
9206 * # Nested arrays.
9207 * show([[[0, 1], 2, 3], 4, 5]) # => "0\n1\n2\n3\n4\n5\n"
9208 *
9209 */
9210
9211VALUE
9212rb_io_puts(int argc, const VALUE *argv, VALUE out)
9213{
9214 VALUE line, args[2];
9215
9216 /* if no argument given, print newline. */
9217 if (argc == 0) {
9218 rb_io_write(out, rb_default_rs);
9219 return Qnil;
9220 }
9221 for (int i = 0; i < argc; i++) {
9222 // Convert the argument to a string:
9223 if (RB_TYPE_P(argv[i], T_STRING)) {
9224 line = argv[i];
9225 }
9226 else if (rb_exec_recursive(io_puts_ary, argv[i], out)) {
9227 continue;
9228 }
9229 else {
9230 line = rb_obj_as_string(argv[i]);
9231 }
9232
9233 // Write the line:
9234 int n = 0;
9235 if (RSTRING_LEN(line) == 0) {
9236 args[n++] = rb_default_rs;
9237 }
9238 else {
9239 args[n++] = line;
9240 if (!rb_str_end_with_asciichar(line, '\n')) {
9241 args[n++] = rb_default_rs;
9242 }
9243 }
9244
9245 rb_io_writev(out, n, args);
9246 }
9247
9248 return Qnil;
9249}
9250
9251/*
9252 * call-seq:
9253 * puts(*objects) -> nil
9254 *
9255 * Equivalent to
9256 *
9257 * $stdout.puts(objects)
9258 */
9259
9260static VALUE
9261rb_f_puts(int argc, VALUE *argv, VALUE recv)
9262{
9263 VALUE r_stdout = rb_ractor_stdout();
9264 if (recv == r_stdout) {
9265 return rb_io_puts(argc, argv, recv);
9266 }
9267 return forward(r_stdout, rb_intern("puts"), argc, argv);
9268}
9269
9270static VALUE
9271rb_p_write(VALUE str)
9272{
9273 VALUE args[2];
9274 args[0] = str;
9275 args[1] = rb_default_rs;
9276 VALUE r_stdout = rb_ractor_stdout();
9277 if (RB_TYPE_P(r_stdout, T_FILE) &&
9278 rb_method_basic_definition_p(CLASS_OF(r_stdout), id_write)) {
9279 io_writev(2, args, r_stdout);
9280 }
9281 else {
9282 rb_io_writev(r_stdout, 2, args);
9283 }
9284 return Qnil;
9285}
9286
9287void
9288rb_p(VALUE obj) /* for debug print within C code */
9289{
9290 rb_p_write(rb_obj_as_string(rb_inspect(obj)));
9291}
9292
9293static VALUE
9294rb_p_result(int argc, const VALUE *argv)
9295{
9296 VALUE ret = Qnil;
9297
9298 if (argc == 1) {
9299 ret = argv[0];
9300 }
9301 else if (argc > 1) {
9302 ret = rb_ary_new4(argc, argv);
9303 }
9304 VALUE r_stdout = rb_ractor_stdout();
9305 if (RB_TYPE_P(r_stdout, T_FILE)) {
9306 rb_uninterruptible(rb_io_flush, r_stdout);
9307 }
9308 return ret;
9309}
9310
9311/*
9312 * call-seq:
9313 * p(object) -> obj
9314 * p(*objects) -> array of objects
9315 * p -> nil
9316 *
9317 * For each object +obj+, executes:
9318 *
9319 * $stdout.write(obj.inspect, "\n")
9320 *
9321 * With one object given, returns the object;
9322 * with multiple objects given, returns an array containing the objects;
9323 * with no object given, returns +nil+.
9324 *
9325 * Examples:
9326 *
9327 * r = Range.new(0, 4)
9328 * p r # => 0..4
9329 * p [r, r, r] # => [0..4, 0..4, 0..4]
9330 * p # => nil
9331 *
9332 * Output:
9333 *
9334 * 0..4
9335 * [0..4, 0..4, 0..4]
9336 *
9337 * Kernel#p is designed for debugging purposes.
9338 * Ruby implementations may define Kernel#p to be uninterruptible
9339 * in whole or in part.
9340 * On CRuby, Kernel#p's writing of data is uninterruptible.
9341 */
9342
9343static VALUE
9344rb_f_p(int argc, VALUE *argv, VALUE self)
9345{
9346 int i;
9347 for (i=0; i<argc; i++) {
9348 VALUE inspected = rb_obj_as_string(rb_inspect(argv[i]));
9349 rb_uninterruptible(rb_p_write, inspected);
9350 }
9351 return rb_p_result(argc, argv);
9352}
9353
9354/*
9355 * call-seq:
9356 * display(port = $>) -> nil
9357 *
9358 * Writes +self+ on the given port:
9359 *
9360 * 1.display
9361 * "cat".display
9362 * [ 4, 5, 6 ].display
9363 * puts
9364 *
9365 * Output:
9366 *
9367 * 1cat[4, 5, 6]
9368 *
9369 */
9370
9371static VALUE
9372rb_obj_display(int argc, VALUE *argv, VALUE self)
9373{
9374 VALUE out;
9375
9376 out = (!rb_check_arity(argc, 0, 1) ? rb_ractor_stdout() : argv[0]);
9377 rb_io_write(out, self);
9378
9379 return Qnil;
9380}
9381
9382static int
9383rb_stderr_to_original_p(VALUE err)
9384{
9385 return (err == orig_stderr || RFILE(orig_stderr)->fptr->fd < 0);
9386}
9387
9388void
9389rb_write_error2(const char *mesg, rb_len_t len)
9390{
9391 VALUE out = rb_ractor_stderr();
9392 if (rb_stderr_to_original_p(out)) {
9393#ifdef _WIN32
9394 if (isatty(fileno(stderr))) {
9395 if (rb_w32_write_console(rb_str_new(mesg, len), fileno(stderr)) > 0) return;
9396 }
9397#endif
9398 if (fwrite(mesg, sizeof(char), (size_t)len, stderr) < (size_t)len) {
9399 /* failed to write to stderr, what can we do? */
9400 return;
9401 }
9402 }
9403 else {
9404 rb_io_write(out, rb_str_new(mesg, len));
9405 }
9406}
9407
9408void
9409rb_write_error(const char *mesg)
9410{
9411 rb_write_error2(mesg, strlen(mesg));
9412}
9413
9414void
9415rb_write_error_str(VALUE mesg)
9416{
9417 VALUE out = rb_ractor_stderr();
9418 /* a stopgap measure for the time being */
9419 if (rb_stderr_to_original_p(out)) {
9420 size_t len = (size_t)RSTRING_LEN(mesg);
9421#ifdef _WIN32
9422 if (isatty(fileno(stderr))) {
9423 if (rb_w32_write_console(mesg, fileno(stderr)) > 0) return;
9424 }
9425#endif
9426 if (fwrite(RSTRING_PTR(mesg), sizeof(char), len, stderr) < len) {
9427 RB_GC_GUARD(mesg);
9428 return;
9429 }
9430 }
9431 else {
9432 /* may unlock GVL, and */
9433 rb_io_write(out, mesg);
9434 }
9435}
9436
9437int
9438rb_stderr_tty_p(void)
9439{
9440 if (rb_stderr_to_original_p(rb_ractor_stderr()))
9441 return isatty(fileno(stderr));
9442 return 0;
9443}
9444
9445static void
9446must_respond_to(ID mid, VALUE val, ID id)
9447{
9448 if (!rb_respond_to(val, mid)) {
9449 rb_raise(rb_eTypeError, "%"PRIsVALUE" must have %"PRIsVALUE" method, %"PRIsVALUE" given",
9450 rb_id2str(id), rb_id2str(mid),
9451 rb_obj_class(val));
9452 }
9453}
9454
9455static void
9456stdin_setter(VALUE val, ID id, VALUE *ptr)
9457{
9459}
9460
9461static VALUE
9462stdin_getter(ID id, VALUE *ptr)
9463{
9464 return rb_ractor_stdin();
9465}
9466
9467static void
9468stdout_setter(VALUE val, ID id, VALUE *ptr)
9469{
9470 must_respond_to(id_write, val, id);
9472}
9473
9474static VALUE
9475stdout_getter(ID id, VALUE *ptr)
9476{
9477 return rb_ractor_stdout();
9478}
9479
9480static void
9481stderr_setter(VALUE val, ID id, VALUE *ptr)
9482{
9483 must_respond_to(id_write, val, id);
9485}
9486
9487static VALUE
9488stderr_getter(ID id, VALUE *ptr)
9489{
9490 return rb_ractor_stderr();
9491}
9492
9493static VALUE
9494allocate_and_open_new_file(VALUE klass)
9495{
9496 VALUE self = io_alloc(klass);
9497 rb_io_make_open_file(self);
9498 return self;
9499}
9500
9501VALUE
9502rb_io_open_descriptor(VALUE klass, int descriptor, int mode, VALUE path, VALUE timeout, struct rb_io_encoding *encoding)
9503{
9504 int state;
9505 VALUE self = rb_protect(allocate_and_open_new_file, klass, &state);
9506 if (state) {
9507 /* if we raised an exception allocating an IO object, but the caller
9508 intended to transfer ownership of this FD to us, close the fd before
9509 raising the exception. Otherwise, we would leak a FD - the caller
9510 expects GC to close the file, but we never got around to assigning
9511 it to a rb_io. */
9512 if (!(mode & FMODE_EXTERNAL)) {
9513 maygvl_close(descriptor, 0);
9514 }
9515 rb_jump_tag(state);
9516 }
9517
9518
9519 rb_io_t *io = RFILE(self)->fptr;
9520 io->self = self;
9521 io->fd = descriptor;
9522 io->mode = mode;
9523
9524 /* At this point, Ruby fully owns the descriptor, and will close it when
9525 the IO gets GC'd (unless FMODE_EXTERNAL was set), no matter what happens
9526 in the rest of this method. */
9527
9528 if (NIL_P(path)) {
9529 io->pathv = Qnil;
9530 }
9531 else {
9532 StringValue(path);
9533 io->pathv = rb_str_new_frozen(path);
9534 }
9535
9536 io->timeout = timeout;
9537
9538 ccan_list_head_init(&io->blocking_operations);
9539 io->closing_ec = NULL;
9540 io->wakeup_mutex = Qnil;
9541 io->fork_generation = GET_VM()->fork_gen;
9542
9543 if (encoding) {
9544 io->encs = *encoding;
9545 }
9546
9547 rb_update_max_fd(descriptor);
9548
9549 return self;
9550}
9551
9552static VALUE
9553prep_io(int fd, enum rb_io_mode fmode, VALUE klass, const char *path)
9554{
9555 VALUE path_value = Qnil;
9556 rb_encoding *e;
9557 struct rb_io_encoding convconfig;
9558
9559 if (path) {
9560 path_value = rb_obj_freeze(rb_str_new_cstr(path));
9561 }
9562
9563 e = (fmode & FMODE_BINMODE) ? rb_ascii8bit_encoding() : NULL;
9564 rb_io_ext_int_to_encs(e, NULL, &convconfig.enc, &convconfig.enc2, fmode);
9565 convconfig.ecflags = (fmode & FMODE_READABLE) ?
9568#ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE
9569 convconfig.ecflags |= (fmode & FMODE_WRITABLE) ?
9570 MODE_BTMODE(TEXTMODE_NEWLINE_DECORATOR_ON_WRITE,
9571 0, TEXTMODE_NEWLINE_DECORATOR_ON_WRITE) : 0;
9572#endif
9573 SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(convconfig.enc2, convconfig.ecflags);
9574 convconfig.ecopts = Qnil;
9575
9576 VALUE self = rb_io_open_descriptor(klass, fd, fmode, path_value, Qnil, &convconfig);
9577 rb_io_t*io = RFILE(self)->fptr;
9578
9579 if (!io_check_tty(io)) {
9580#ifdef __CYGWIN__
9581 io->mode |= FMODE_BINMODE;
9582 setmode(fd, O_BINARY);
9583#endif
9584 }
9585
9586 return self;
9587}
9588
9589VALUE
9590rb_io_fdopen(int fd, int oflags, const char *path)
9591{
9592 VALUE klass = rb_cIO;
9593
9594 if (path && strcmp(path, "-")) klass = rb_cFile;
9595 return prep_io(fd, rb_io_oflags_fmode(oflags), klass, path);
9596}
9597
9598static VALUE
9599prep_stdio(FILE *f, enum rb_io_mode fmode, VALUE klass, const char *path)
9600{
9601 rb_io_t *fptr;
9602 VALUE io = prep_io(fileno(f), fmode|FMODE_EXTERNAL|DEFAULT_TEXTMODE, klass, path);
9603
9604 GetOpenFile(io, fptr);
9606#ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE
9607 fptr->encs.ecflags |= TEXTMODE_NEWLINE_DECORATOR_ON_WRITE;
9608 if (fmode & FMODE_READABLE) {
9610 }
9611#endif
9612 fptr->stdio_file = f;
9613
9614 return io;
9615}
9616
9617VALUE
9618rb_io_prep_stdin(void)
9619{
9620 return prep_stdio(stdin, FMODE_READABLE, rb_cIO, "<STDIN>");
9621}
9622
9623VALUE
9624rb_io_prep_stdout(void)
9625{
9626 return prep_stdio(stdout, FMODE_WRITABLE|FMODE_SIGNAL_ON_EPIPE, rb_cIO, "<STDOUT>");
9627}
9628
9629VALUE
9630rb_io_prep_stderr(void)
9631{
9632 return prep_stdio(stderr, FMODE_WRITABLE|FMODE_SYNC, rb_cIO, "<STDERR>");
9633}
9634
9635FILE *
9636rb_io_stdio_file(rb_io_t *fptr)
9637{
9638 if (!fptr->stdio_file) {
9639 int oflags = rb_io_fmode_oflags(fptr->mode) & ~O_EXCL;
9640 fptr->stdio_file = rb_fdopen(fptr->fd, rb_io_oflags_modestr(oflags));
9641 }
9642 return fptr->stdio_file;
9643}
9644
9645static inline void
9646rb_io_buffer_init(struct rb_io_internal_buffer *buf)
9647{
9648 buf->ptr = NULL;
9649 buf->off = 0;
9650 buf->len = 0;
9651 buf->capa = 0;
9652}
9653
9654static inline rb_io_t *
9655rb_io_fptr_new(void)
9656{
9657 rb_io_t *fp = ALLOC(rb_io_t);
9658 fp->self = Qnil;
9659 fp->fd = -1;
9660 fp->stdio_file = NULL;
9661 fp->mode = 0;
9662 fp->pid = 0;
9663 fp->lineno = 0;
9664 fp->pathv = Qnil;
9665 fp->finalize = 0;
9666 rb_io_buffer_init(&fp->wbuf);
9667 rb_io_buffer_init(&fp->rbuf);
9668 rb_io_buffer_init(&fp->cbuf);
9669 fp->readconv = NULL;
9670 fp->writeconv = NULL;
9672 fp->writeconv_pre_ecflags = 0;
9674 fp->writeconv_initialized = 0;
9675 fp->tied_io_for_writing = 0;
9676 fp->encs.enc = NULL;
9677 fp->encs.enc2 = NULL;
9678 fp->encs.ecflags = 0;
9679 fp->encs.ecopts = Qnil;
9680 fp->write_lock = Qnil;
9681 fp->timeout = Qnil;
9682 ccan_list_head_init(&fp->blocking_operations);
9683 fp->closing_ec = NULL;
9684 fp->wakeup_mutex = Qnil;
9685 fp->fork_generation = GET_VM()->fork_gen;
9686 return fp;
9687}
9688
9689rb_io_t *
9690rb_io_make_open_file(VALUE obj)
9691{
9692 rb_io_t *fp = 0;
9693
9694 Check_Type(obj, T_FILE);
9695 if (RFILE(obj)->fptr) {
9696 rb_io_close(obj);
9697 rb_io_fptr_finalize(RFILE(obj)->fptr);
9698 RFILE(obj)->fptr = 0;
9699 }
9700 fp = rb_io_fptr_new();
9701 fp->self = obj;
9702 RFILE(obj)->fptr = fp;
9703 return fp;
9704}
9705
9706static VALUE io_initialize(VALUE io, VALUE fnum, VALUE vmode, VALUE opt);
9707
9708/*
9709 * call-seq:
9710 * IO.new(fd, mode = 'r', **opts) -> io
9711 *
9712 * Creates and returns a new \IO object (file stream) from a file descriptor.
9713 *
9714 * \IO.new may be useful for interaction with low-level libraries.
9715 * For higher-level interactions, it may be simpler to create
9716 * the file stream using File.open.
9717 *
9718 * Argument +fd+ must be a valid file descriptor (integer):
9719 *
9720 * path = 't.tmp'
9721 * fd = IO.sysopen(path) # => 3
9722 * IO.new(fd) # => #<IO:fd 3>
9723 *
9724 * The new \IO object does not inherit encoding
9725 * (because the integer file descriptor does not have an encoding):
9726 *
9727 * File.read('t.ja') # => "こんにちは"
9728 * fd = IO.sysopen('t.ja', 'rb')
9729 * io = IO.new(fd)
9730 * io.external_encoding # => #<Encoding:UTF-8> # Not ASCII-8BIT.
9731 *
9732 * Optional argument +mode+ (defaults to 'r') must specify a valid mode;
9733 * see {Access Modes}[rdoc-ref:File@Access+Modes]:
9734 *
9735 * IO.new(fd, 'w') # => #<IO:fd 3>
9736 * IO.new(fd, File::WRONLY) # => #<IO:fd 3>
9737 *
9738 * Optional keyword arguments +opts+ specify:
9739 *
9740 * - {Open Options}[rdoc-ref:IO@Open+Options].
9741 * - {Encoding options}[rdoc-ref:encodings.rdoc@Encoding+Options].
9742 *
9743 * Examples:
9744 *
9745 * IO.new(fd, internal_encoding: nil) # => #<IO:fd 3>
9746 * IO.new(fd, autoclose: true) # => #<IO:fd 3>
9747 *
9748 */
9749
9750static VALUE
9751rb_io_initialize(int argc, VALUE *argv, VALUE io)
9752{
9753 VALUE fnum, vmode;
9754 VALUE opt;
9755
9756 rb_scan_args(argc, argv, "11:", &fnum, &vmode, &opt);
9757 return io_initialize(io, fnum, vmode, opt);
9758}
9759
9760static VALUE
9761io_initialize(VALUE io, VALUE fnum, VALUE vmode, VALUE opt)
9762{
9763 rb_io_t *fp;
9764 int fd, oflags = O_RDONLY;
9765 enum rb_io_mode fmode;
9766 struct rb_io_encoding convconfig;
9767#if defined(HAVE_FCNTL) && defined(F_GETFL)
9768 int ofmode;
9769#else
9770 struct stat st;
9771#endif
9772
9773 rb_io_extract_modeenc(&vmode, 0, opt, &oflags, &fmode, &convconfig);
9774
9775 fd = NUM2INT(fnum);
9776 if (rb_reserved_fd_p(fd)) {
9777 rb_raise(rb_eArgError, "The given fd is not accessible because RubyVM reserves it");
9778 }
9779#if defined(HAVE_FCNTL) && defined(F_GETFL)
9780 oflags = fcntl(fd, F_GETFL);
9781 if (oflags == -1) rb_sys_fail(0);
9782#else
9783 if (fstat(fd, &st) < 0) rb_sys_fail(0);
9784#endif
9785 rb_update_max_fd(fd);
9786#if defined(HAVE_FCNTL) && defined(F_GETFL)
9787 ofmode = rb_io_oflags_fmode(oflags);
9788 if (NIL_P(vmode)) {
9789 fmode = ofmode;
9790 }
9791 else if ((~ofmode & fmode) & FMODE_READWRITE) {
9792 VALUE error = INT2FIX(EINVAL);
9794 }
9795#endif
9796 VALUE path = Qnil;
9797
9798 if (!NIL_P(opt)) {
9799 if (rb_hash_aref(opt, sym_autoclose) == Qfalse) {
9800 fmode |= FMODE_EXTERNAL;
9801 }
9802
9803 path = rb_hash_aref(opt, RB_ID2SYM(idPath));
9804 if (!NIL_P(path)) {
9805 StringValue(path);
9806 path = rb_str_new_frozen(path);
9807 }
9808 }
9809
9810 MakeOpenFile(io, fp);
9811 fp->self = io;
9812 fp->fd = fd;
9813 fp->mode = fmode;
9814 fp->encs = convconfig;
9815 fp->pathv = path;
9816 fp->timeout = Qnil;
9817 ccan_list_head_init(&fp->blocking_operations);
9818 fp->closing_ec = NULL;
9819 fp->wakeup_mutex = Qnil;
9820 fp->fork_generation = GET_VM()->fork_gen;
9821 clear_codeconv(fp);
9822 io_check_tty(fp);
9823 if (fileno(stdin) == fd)
9824 fp->stdio_file = stdin;
9825 else if (fileno(stdout) == fd)
9826 fp->stdio_file = stdout;
9827 else if (fileno(stderr) == fd)
9828 fp->stdio_file = stderr;
9829
9830 if (fmode & FMODE_SETENC_BY_BOM) io_set_encoding_by_bom(io);
9831 return io;
9832}
9833
9834/*
9835 * call-seq:
9836 * set_encoding_by_bom -> encoding or nil
9837 *
9838 * If the stream begins with a BOM
9839 * ({byte order marker}[https://en.wikipedia.org/wiki/Byte_order_mark]),
9840 * consumes the BOM and sets the external encoding accordingly;
9841 * returns the result encoding if found, or +nil+ otherwise:
9842 *
9843 * File.write('t.tmp', "\u{FEFF}abc")
9844 * io = File.open('t.tmp', 'rb')
9845 * io.set_encoding_by_bom # => #<Encoding:UTF-8>
9846 * io.close
9847 *
9848 * File.write('t.tmp', 'abc')
9849 * io = File.open('t.tmp', 'rb')
9850 * io.set_encoding_by_bom # => nil
9851 * io.close
9852 *
9853 * Raises an exception if the stream is not binmode
9854 * or its encoding has already been set.
9855 *
9856 */
9857
9858static VALUE
9859rb_io_set_encoding_by_bom(VALUE io)
9860{
9861 rb_io_t *fptr;
9862
9863 GetOpenFile(io, fptr);
9864 if (!(fptr->mode & FMODE_BINMODE)) {
9865 rb_raise(rb_eArgError, "ASCII incompatible encoding needs binmode");
9866 }
9867 if (fptr->encs.enc2) {
9868 rb_raise(rb_eArgError, "encoding conversion is set");
9869 }
9870 else if (fptr->encs.enc && fptr->encs.enc != rb_ascii8bit_encoding()) {
9871 rb_raise(rb_eArgError, "encoding is set to %s already",
9872 rb_enc_name(fptr->encs.enc));
9873 }
9874 if (!io_set_encoding_by_bom(io)) return Qnil;
9875 return rb_enc_from_encoding(fptr->encs.enc);
9876}
9877
9878/*
9879 * :markup: markdown
9880 *
9881 * call-seq:
9882 * File.new(path, mode = 'r', permissions = 0666, **options) -> file
9883 *
9884 * Opens the file as specified by the given arguments.
9885 * Creates and returns a new open \File object for that file;
9886 * the opened file is in non-synchronous mode.
9887 *
9888 * Argument `path` must the string path to an existing filesystem entry:
9889 *
9890 * ```ruby
9891 * file = File.new('doc/maintainers.md') # => #<File:doc/maintainers.md>
9892 * file.close # Clean up.
9893 * tty = File.new('/dev/tty') # => #<File:/dev/tty>
9894 * tty.close # Clean up.
9895 * ```
9896 *
9897 * Note that the caller is responsible for closing the file;
9898 * see File.open for automatic closing.
9899 *
9900 * Optional argument `mode` (defaults to `'r'`) must specify a valid mode;
9901 * see [Access Modes](rdoc-ref:File@Access+Modes):
9902 *
9903 * ```ruby
9904 * file = File.new('t.tmp', 'w') # => #<File:t.tmp>
9905 * file.close # Clean up.
9906 * file = File.new('t.tmp', File::RDONLY) # => #<File:t.tmp>
9907 * file.close # Clean up.
9908 * ```
9909 *
9910 * Optional argument `permissions` (defaults to `0666`) must specify valid permissions;
9911 * see [File Permissions](rdoc-ref:File@File+Permissions):
9912 *
9913 * ```ruby
9914 * file = File.new('t.tmp', 'w', 0644) # => #<File:t.tmp>
9915 * file.close # Clean up.
9916 * file = File.new('t.tmp', 'w', 0444) # => #<File:t.tmp>
9917 * file.close # Clean up.
9918 * ```
9919 *
9920 * Optional keyword arguments `options` specify:
9921 *
9922 * - [Open Options](rdoc-ref:IO@Open+Options).
9923 * - [Encoding options](rdoc-ref:encodings.rdoc@Encoding+Options).
9924 *
9925 */
9926
9927static VALUE
9928rb_file_initialize(int argc, VALUE *argv, VALUE io)
9929{
9930 if (RFILE(io)->fptr) {
9931 rb_raise(rb_eRuntimeError, "reinitializing File");
9932 }
9933 VALUE fname, vmode, vperm, opt;
9934 int posargc = rb_scan_args(argc, argv, "12:", &fname, &vmode, &vperm, &opt);
9935 if (posargc < 3) { /* perm is File only */
9936 VALUE fd = rb_check_to_int(fname);
9937
9938 if (!NIL_P(fd)) {
9939 return io_initialize(io, fd, vmode, opt);
9940 }
9941 }
9942 return rb_open_file(io, fname, vmode, vperm, opt);
9943}
9944
9945/* :nodoc: */
9946static VALUE
9947rb_io_s_new(int argc, VALUE *argv, VALUE klass)
9948{
9949 if (rb_block_given_p()) {
9950 VALUE cname = rb_obj_as_string(klass);
9951
9952 rb_warn("%"PRIsVALUE"::new() does not take block; use %"PRIsVALUE"::open() instead",
9953 cname, cname);
9954 }
9955 return rb_class_new_instance_kw(argc, argv, klass, RB_PASS_CALLED_KEYWORDS);
9956}
9957
9958
9959/*
9960 * call-seq:
9961 * IO.for_fd(fd, mode = 'r', **opts) -> io
9962 *
9963 * Synonym for IO.new.
9964 *
9965 */
9966
9967static VALUE
9968rb_io_s_for_fd(int argc, VALUE *argv, VALUE klass)
9969{
9970 VALUE io = rb_obj_alloc(klass);
9971 rb_io_initialize(argc, argv, io);
9972 return io;
9973}
9974
9975/*
9976 * call-seq:
9977 * ios.autoclose? -> true or false
9978 *
9979 * Returns +true+ if the underlying file descriptor of _ios_ will be
9980 * closed at its finalization or at calling #close, otherwise +false+.
9981 */
9982
9983static VALUE
9984rb_io_autoclose_p(VALUE io)
9985{
9986 rb_io_t *fptr = RFILE(io)->fptr;
9987 rb_io_check_closed(fptr);
9988 return RBOOL(!(fptr->mode & FMODE_EXTERNAL));
9989}
9990
9991/*
9992 * call-seq:
9993 * io.autoclose = bool -> true or false
9994 *
9995 * Sets auto-close flag.
9996 *
9997 * f = File.open(File::NULL)
9998 * IO.for_fd(f.fileno).close
9999 * f.gets # raises Errno::EBADF
10000 *
10001 * f = File.open(File::NULL)
10002 * g = IO.for_fd(f.fileno)
10003 * g.autoclose = false
10004 * g.close
10005 * f.gets # won't cause Errno::EBADF
10006 */
10007
10008static VALUE
10009rb_io_set_autoclose(VALUE io, VALUE autoclose)
10010{
10011 rb_io_t *fptr;
10012 GetOpenFile(io, fptr);
10013 if (!RTEST(autoclose))
10014 fptr->mode |= FMODE_EXTERNAL;
10015 else
10016 fptr->mode &= ~FMODE_EXTERNAL;
10017 return autoclose;
10018}
10019
10020static VALUE
10021io_wait_event(VALUE io, int event, VALUE timeout, int return_io)
10022{
10023 VALUE result = rb_io_wait(io, RB_INT2NUM(event), timeout);
10024
10025 if (!RB_TEST(result)) {
10026 return Qnil;
10027 }
10028
10029 int mask = RB_NUM2INT(result);
10030
10031 if (mask & event) {
10032 if (return_io)
10033 return io;
10034 else
10035 return result;
10036 }
10037 else {
10038 return Qfalse;
10039 }
10040}
10041
10042/*
10043 * call-seq:
10044 * io.wait_readable -> truthy or falsy
10045 * io.wait_readable(timeout) -> truthy or falsy
10046 *
10047 * Waits until IO is readable and returns a truthy value, or a falsy
10048 * value when times out. Returns a truthy value immediately when
10049 * buffered data is available.
10050 */
10051
10052static VALUE
10053io_wait_readable(int argc, VALUE *argv, VALUE io)
10054{
10055 rb_io_t *fptr;
10056
10057 RB_IO_POINTER(io, fptr);
10059
10060 if (rb_io_read_pending(fptr)) return Qtrue;
10061
10062 rb_check_arity(argc, 0, 1);
10063 VALUE timeout = (argc == 1 ? argv[0] : Qnil);
10064
10065 return io_wait_event(io, RUBY_IO_READABLE, timeout, 1);
10066}
10067
10068/*
10069 * call-seq:
10070 * io.wait_writable -> truthy or falsy
10071 * io.wait_writable(timeout) -> truthy or falsy
10072 *
10073 * Waits until IO is writable and returns a truthy value or a falsy
10074 * value when times out.
10075 */
10076static VALUE
10077io_wait_writable(int argc, VALUE *argv, VALUE io)
10078{
10079 rb_io_t *fptr;
10080
10081 RB_IO_POINTER(io, fptr);
10083
10084 rb_check_arity(argc, 0, 1);
10085 VALUE timeout = (argc == 1 ? argv[0] : Qnil);
10086
10087 return io_wait_event(io, RUBY_IO_WRITABLE, timeout, 1);
10088}
10089
10090/*
10091 * call-seq:
10092 * io.wait_priority -> truthy or falsy
10093 * io.wait_priority(timeout) -> truthy or falsy
10094 *
10095 * Waits until IO is priority and returns a truthy value or a falsy
10096 * value when times out. Priority data is sent and received using
10097 * the Socket::MSG_OOB flag and is typically limited to streams.
10098 */
10099static VALUE
10100io_wait_priority(int argc, VALUE *argv, VALUE io)
10101{
10102 rb_io_t *fptr = NULL;
10103
10104 RB_IO_POINTER(io, fptr);
10106
10107 if (rb_io_read_pending(fptr)) return Qtrue;
10108
10109 rb_check_arity(argc, 0, 1);
10110 VALUE timeout = argc == 1 ? argv[0] : Qnil;
10111
10112 return io_wait_event(io, RUBY_IO_PRIORITY, timeout, 1);
10113}
10114
10115static int
10116wait_mode_sym(VALUE mode)
10117{
10118 if (mode == ID2SYM(rb_intern("r"))) {
10119 return RB_WAITFD_IN;
10120 }
10121 if (mode == ID2SYM(rb_intern("read"))) {
10122 return RB_WAITFD_IN;
10123 }
10124 if (mode == ID2SYM(rb_intern("readable"))) {
10125 return RB_WAITFD_IN;
10126 }
10127 if (mode == ID2SYM(rb_intern("w"))) {
10128 return RB_WAITFD_OUT;
10129 }
10130 if (mode == ID2SYM(rb_intern("write"))) {
10131 return RB_WAITFD_OUT;
10132 }
10133 if (mode == ID2SYM(rb_intern("writable"))) {
10134 return RB_WAITFD_OUT;
10135 }
10136 if (mode == ID2SYM(rb_intern("rw"))) {
10137 return RB_WAITFD_IN|RB_WAITFD_OUT;
10138 }
10139 if (mode == ID2SYM(rb_intern("read_write"))) {
10140 return RB_WAITFD_IN|RB_WAITFD_OUT;
10141 }
10142 if (mode == ID2SYM(rb_intern("readable_writable"))) {
10143 return RB_WAITFD_IN|RB_WAITFD_OUT;
10144 }
10145
10146 rb_raise(rb_eArgError, "unsupported mode: %"PRIsVALUE, mode);
10147}
10148
10149static inline enum rb_io_event
10150io_event_from_value(VALUE value)
10151{
10152 int events = RB_NUM2INT(value);
10153
10154 if (events <= 0) rb_raise(rb_eArgError, "Events must be positive integer!");
10155
10156 return events;
10157}
10158
10159/*
10160 * call-seq:
10161 * io.wait(events, timeout) -> event mask, false or nil
10162 * io.wait(*event_symbols[, timeout]) -> self, true, or false
10163 *
10164 * Waits until the IO becomes ready for the specified events and returns the
10165 * subset of events that become ready, or a falsy value when times out.
10166 *
10167 * The events can be a bit mask of +IO::READABLE+, +IO::WRITABLE+ or
10168 * +IO::PRIORITY+.
10169 *
10170 * Returns an event mask (truthy value) immediately when buffered data is
10171 * available.
10172 *
10173 * The second form: if one or more event symbols (+:read+, +:write+, or
10174 * +:read_write+) are passed, the event mask is the bit OR of the bitmask
10175 * corresponding to those symbols. In this form, +timeout+ is optional, the
10176 * order of the arguments is arbitrary, and returns +io+ if any of the
10177 * events is ready.
10178 */
10179
10180static VALUE
10181io_wait(int argc, VALUE *argv, VALUE io)
10182{
10183 VALUE timeout = Qundef;
10184 enum rb_io_event events = 0;
10185 int return_io = 0;
10186
10187 if (argc != 2 || (RB_SYMBOL_P(argv[0]) || RB_SYMBOL_P(argv[1]))) {
10188 // We'd prefer to return the actual mask, but this form would return the io itself:
10189 return_io = 1;
10190
10191 // Slow/messy path:
10192 for (int i = 0; i < argc; i += 1) {
10193 if (RB_SYMBOL_P(argv[i])) {
10194 events |= wait_mode_sym(argv[i]);
10195 }
10196 else if (UNDEF_P(timeout)) {
10197 rb_time_interval(timeout = argv[i]);
10198 }
10199 else {
10200 rb_raise(rb_eArgError, "timeout given more than once");
10201 }
10202 }
10203
10204 if (UNDEF_P(timeout)) timeout = Qnil;
10205
10206 if (events == 0) {
10207 events = RUBY_IO_READABLE;
10208 }
10209 }
10210 else /* argc == 2 and neither are symbols */ {
10211 // This is the fast path:
10212 events = io_event_from_value(argv[0]);
10213 timeout = argv[1];
10214 }
10215
10216 if (events & RUBY_IO_READABLE) {
10217 rb_io_t *fptr = NULL;
10218 RB_IO_POINTER(io, fptr);
10219
10220 if (rb_io_read_pending(fptr)) {
10221 // This was the original behaviour:
10222 if (return_io) return Qtrue;
10223 // New behaviour always returns an event mask:
10224 else return RB_INT2NUM(RUBY_IO_READABLE);
10225 }
10226 }
10227
10228 return io_wait_event(io, events, timeout, return_io);
10229}
10230
10231static void
10232argf_mark_and_move(void *ptr)
10233{
10234 struct argf *p = ptr;
10235 rb_gc_mark_and_move(&p->filename);
10236 rb_gc_mark_and_move(&p->current_file);
10237 rb_gc_mark_and_move(&p->argv);
10238 rb_gc_mark_and_move(&p->inplace);
10239 rb_gc_mark_and_move(&p->encs.ecopts);
10240}
10241
10242static size_t
10243argf_memsize(const void *ptr)
10244{
10245 const struct argf *p = ptr;
10246 size_t size = sizeof(*p);
10247 return size;
10248}
10249
10250static const rb_data_type_t argf_type = {
10251 "ARGF",
10252 {argf_mark_and_move, RUBY_TYPED_DEFAULT_FREE, argf_memsize, argf_mark_and_move},
10253 0, 0, RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_WB_PROTECTED
10254};
10255
10256static inline void
10257argf_init(VALUE argf, struct argf *p, VALUE v)
10258{
10259 p->filename = Qnil;
10260 p->current_file = Qnil;
10261 p->lineno = 0;
10262 RB_OBJ_WRITE(argf, &p->argv, v);
10263}
10264
10265static VALUE
10266argf_alloc(VALUE klass)
10267{
10268 struct argf *p;
10269 VALUE argf = TypedData_Make_Struct(klass, struct argf, &argf_type, p);
10270
10271 argf_init(argf, p, Qnil);
10272 return argf;
10273}
10274
10275#undef rb_argv
10276
10277/* :nodoc: */
10278static VALUE
10279argf_initialize(VALUE argf, VALUE argv)
10280{
10281 memset(&ARGF, 0, sizeof(ARGF));
10282 argf_init(argf, &ARGF, argv);
10283
10284 return argf;
10285}
10286
10287/* :nodoc: */
10288static VALUE
10289argf_initialize_copy(VALUE argf, VALUE orig)
10290{
10291 if (!OBJ_INIT_COPY(argf, orig)) return argf;
10292 ARGF = argf_of(orig);
10293 rb_gc_writebarrier_remember(argf);
10294 ARGF_SET(argv, rb_obj_dup(ARGF.argv));
10295 return argf;
10296}
10297
10298/*
10299 * call-seq:
10300 * ARGF.lineno = integer -> integer
10301 *
10302 * Sets the line number of ARGF as a whole to the given Integer.
10303 *
10304 * ARGF sets the line number automatically as you read data, so normally
10305 * you will not need to set it explicitly. To access the current line number
10306 * use ARGF.lineno.
10307 *
10308 * For example:
10309 *
10310 * ARGF.lineno #=> 0
10311 * ARGF.readline #=> "This is line 1\n"
10312 * ARGF.lineno #=> 1
10313 * ARGF.lineno = 0 #=> 0
10314 * ARGF.lineno #=> 0
10315 */
10316static VALUE
10317argf_set_lineno(VALUE argf, VALUE val)
10318{
10319 ARGF.lineno = NUM2INT(val);
10320 ARGF.last_lineno = ARGF.lineno;
10321 return val;
10322}
10323
10324/*
10325 * call-seq:
10326 * ARGF.lineno -> integer
10327 *
10328 * Returns the current line number of ARGF as a whole. This value
10329 * can be set manually with ARGF.lineno=.
10330 *
10331 * For example:
10332 *
10333 * ARGF.lineno #=> 0
10334 * ARGF.readline #=> "This is line 1\n"
10335 * ARGF.lineno #=> 1
10336 */
10337static VALUE
10338argf_lineno(VALUE argf)
10339{
10340 return INT2FIX(ARGF.lineno);
10341}
10342
10343static VALUE
10344argf_forward(int argc, VALUE *argv, VALUE argf)
10345{
10346 return forward_current(rb_frame_this_func(), argc, argv);
10347}
10348
10349#define next_argv() argf_next_argv(argf)
10350#define ARGF_GENERIC_INPUT_P() \
10351 (ARGF.current_file == rb_stdin && !RB_TYPE_P(ARGF.current_file, T_FILE))
10352#define ARGF_FORWARD(argc, argv) do {\
10353 if (ARGF_GENERIC_INPUT_P())\
10354 return argf_forward((argc), (argv), argf);\
10355} while (0)
10356#define NEXT_ARGF_FORWARD(argc, argv) do {\
10357 if (!next_argv()) return Qnil;\
10358 ARGF_FORWARD((argc), (argv));\
10359} while (0)
10360
10361static void
10362argf_close(VALUE argf)
10363{
10364 VALUE file = ARGF.current_file;
10365 if (file == rb_stdin) return;
10366 if (RB_TYPE_P(file, T_FILE)) {
10367 rb_io_set_write_io(file, Qnil);
10368 }
10369 io_close(file);
10370 ARGF.init_p = -1;
10371}
10372
10373static int
10374argf_next_argv(VALUE argf)
10375{
10376 char *fn;
10377 rb_io_t *fptr;
10378 int stdout_binmode = 0;
10379 enum rb_io_mode fmode;
10380
10381 VALUE r_stdout = rb_ractor_stdout();
10382
10383 if (RB_TYPE_P(r_stdout, T_FILE)) {
10384 GetOpenFile(r_stdout, fptr);
10385 if (fptr->mode & FMODE_BINMODE)
10386 stdout_binmode = 1;
10387 }
10388
10389 if (ARGF.init_p == 0) {
10390 if (!NIL_P(ARGF.argv) && RARRAY_LEN(ARGF.argv) > 0) {
10391 ARGF.next_p = 1;
10392 }
10393 else {
10394 ARGF.next_p = -1;
10395 }
10396 ARGF.init_p = 1;
10397 }
10398 else {
10399 if (NIL_P(ARGF.argv)) {
10400 ARGF.next_p = -1;
10401 }
10402 else if (ARGF.next_p == -1 && RARRAY_LEN(ARGF.argv) > 0) {
10403 ARGF.next_p = 1;
10404 }
10405 }
10406
10407 if (ARGF.next_p == 1) {
10408 if (ARGF.init_p == 1) argf_close(argf);
10409 retry:
10410 if (RARRAY_LEN(ARGF.argv) > 0) {
10411 VALUE filename = rb_ary_shift(ARGF.argv);
10412 FilePathValue(filename);
10413 ARGF_SET(filename, filename);
10414 filename = rb_str_encode_ospath(filename);
10415 fn = StringValueCStr(filename);
10416 if (RSTRING_LEN(filename) == 1 && fn[0] == '-') {
10417 ARGF_SET(current_file, rb_stdin);
10418 if (ARGF.inplace) {
10419 rb_warn("Can't do inplace edit for stdio; skipping");
10420 goto retry;
10421 }
10422 }
10423 else {
10424 VALUE write_io = Qnil;
10425 int fr = rb_sysopen(filename, O_RDONLY, 0);
10426
10427 if (ARGF.inplace) {
10428 struct stat st;
10429#ifndef NO_SAFE_RENAME
10430 struct stat st2;
10431#endif
10432 VALUE str;
10433 int fw;
10434
10435 if (RB_TYPE_P(r_stdout, T_FILE) && r_stdout != orig_stdout) {
10436 rb_io_close(r_stdout);
10437 }
10438 fstat(fr, &st);
10439 str = filename;
10440 if (!NIL_P(ARGF.inplace)) {
10441 VALUE suffix = ARGF.inplace;
10442 str = rb_str_dup(str);
10443 if (NIL_P(rb_str_cat_conv_enc_opts(str, RSTRING_LEN(str),
10444 RSTRING_PTR(suffix), RSTRING_LEN(suffix),
10445 rb_enc_get(suffix), 0, Qnil))) {
10446 rb_str_append(str, suffix);
10447 }
10448#ifdef NO_SAFE_RENAME
10449 (void)close(fr);
10450 (void)unlink(RSTRING_PTR(str));
10451 if (rename(fn, RSTRING_PTR(str)) < 0) {
10452 rb_warn("Can't rename %"PRIsVALUE" to %"PRIsVALUE": %s, skipping file",
10453 filename, str, strerror(errno));
10454 goto retry;
10455 }
10456 fr = rb_sysopen(str, O_RDONLY, 0);
10457#else
10458 if (rename(fn, RSTRING_PTR(str)) < 0) {
10459 rb_warn("Can't rename %"PRIsVALUE" to %"PRIsVALUE": %s, skipping file",
10460 filename, str, strerror(errno));
10461 close(fr);
10462 goto retry;
10463 }
10464#endif
10465 }
10466 else {
10467#ifdef NO_SAFE_RENAME
10468 rb_fatal("Can't do inplace edit without backup");
10469#else
10470 if (unlink(fn) < 0) {
10471 rb_warn("Can't remove %"PRIsVALUE": %s, skipping file",
10472 filename, strerror(errno));
10473 close(fr);
10474 goto retry;
10475 }
10476#endif
10477 }
10478 fw = rb_sysopen(filename, O_WRONLY|O_CREAT|O_TRUNC, 0666);
10479#ifndef NO_SAFE_RENAME
10480 fstat(fw, &st2);
10481#ifdef HAVE_FCHMOD
10482 fchmod(fw, st.st_mode);
10483#else
10484 chmod(fn, st.st_mode);
10485#endif
10486 if (st.st_uid!=st2.st_uid || st.st_gid!=st2.st_gid) {
10487 int err;
10488#ifdef HAVE_FCHOWN
10489 err = fchown(fw, st.st_uid, st.st_gid);
10490#else
10491 err = chown(fn, st.st_uid, st.st_gid);
10492#endif
10493 if (err && getuid() == 0 && st2.st_uid == 0) {
10494 const char *wkfn = RSTRING_PTR(filename);
10495 rb_warn("Can't set owner/group of %"PRIsVALUE" to same as %"PRIsVALUE": %s, skipping file",
10496 filename, str, strerror(errno));
10497 (void)close(fr);
10498 (void)close(fw);
10499 (void)unlink(wkfn);
10500 goto retry;
10501 }
10502 }
10503#endif
10504 write_io = prep_io(fw, FMODE_WRITABLE, rb_cFile, fn);
10505 rb_ractor_stdout_set(write_io);
10506 if (stdout_binmode) rb_io_binmode(rb_stdout);
10507 }
10508 fmode = FMODE_READABLE;
10509 if (!ARGF.binmode) {
10510 fmode |= DEFAULT_TEXTMODE;
10511 }
10512 ARGF_SET(current_file, prep_io(fr, fmode, rb_cFile, fn));
10513 if (!NIL_P(write_io)) {
10514 rb_io_set_write_io(ARGF.current_file, write_io);
10515 }
10516 RB_GC_GUARD(filename);
10517 }
10518 if (ARGF.binmode) rb_io_ascii8bit_binmode(ARGF.current_file);
10519 GetOpenFile(ARGF.current_file, fptr);
10520 if (ARGF.encs.enc) {
10521 fptr->encs = ARGF.encs;
10522 clear_codeconv(fptr);
10523 }
10524 else {
10526 if (!ARGF.binmode) {
10528#ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE
10529 fptr->encs.ecflags |= TEXTMODE_NEWLINE_DECORATOR_ON_WRITE;
10530#endif
10531 }
10532 }
10533 ARGF.next_p = 0;
10534 }
10535 else {
10536 ARGF.next_p = 1;
10537 return FALSE;
10538 }
10539 }
10540 else if (ARGF.next_p == -1) {
10541 ARGF_SET(current_file, rb_stdin);
10542 ARGF_SET(filename, rb_str_new2("-"));
10543 if (ARGF.inplace) {
10544 rb_warn("Can't do inplace edit for stdio");
10545 rb_ractor_stdout_set(orig_stdout);
10546 }
10547 }
10548 if (ARGF.init_p == -1) ARGF.init_p = 1;
10549 return TRUE;
10550}
10551
10552static VALUE
10553argf_getline(int argc, VALUE *argv, VALUE argf)
10554{
10555 VALUE line;
10556 long lineno = ARGF.lineno;
10557
10558 retry:
10559 if (!next_argv()) return Qnil;
10560 if (ARGF_GENERIC_INPUT_P()) {
10561 line = forward_current(idGets, argc, argv);
10562 }
10563 else {
10564 if (argc == 0 && rb_rs == rb_default_rs) {
10565 line = rb_io_gets(ARGF.current_file);
10566 }
10567 else {
10568 line = rb_io_getline(argc, argv, ARGF.current_file);
10569 }
10570 if (NIL_P(line) && ARGF.next_p != -1) {
10571 argf_close(argf);
10572 ARGF.next_p = 1;
10573 goto retry;
10574 }
10575 }
10576 if (!NIL_P(line)) {
10577 ARGF.lineno = ++lineno;
10578 ARGF.last_lineno = ARGF.lineno;
10579 }
10580 return line;
10581}
10582
10583static VALUE
10584argf_lineno_getter(ID id, VALUE *var)
10585{
10586 VALUE argf = *var;
10587 return INT2FIX(ARGF.last_lineno);
10588}
10589
10590static void
10591argf_lineno_setter(VALUE val, ID id, VALUE *var)
10592{
10593 VALUE argf = *var;
10594 int n = NUM2INT(val);
10595 ARGF.last_lineno = ARGF.lineno = n;
10596}
10597
10598void
10599rb_reset_argf_lineno(long n)
10600{
10601 ARGF.last_lineno = ARGF.lineno = n;
10602}
10603
10604static VALUE argf_gets(int, VALUE *, VALUE);
10605
10606/*
10607 * call-seq:
10608 * gets(sep=$/ [, getline_args]) -> string or nil
10609 * gets(limit [, getline_args]) -> string or nil
10610 * gets(sep, limit [, getline_args]) -> string or nil
10611 *
10612 * Returns (and assigns to <code>$_</code>) the next line from the list
10613 * of files in +ARGV+ (or <code>$*</code>), or from standard input if
10614 * no files are present on the command line. Returns +nil+ at end of
10615 * file. The optional argument specifies the record separator. The
10616 * separator is included with the contents of each record. A separator
10617 * of +nil+ reads the entire contents, and a zero-length separator
10618 * reads the input one paragraph at a time, where paragraphs are
10619 * divided by two consecutive newlines. If the first argument is an
10620 * integer, or optional second argument is given, the returning string
10621 * would not be longer than the given value in bytes. If multiple
10622 * filenames are present in +ARGV+, <code>gets(nil)</code> will read
10623 * the contents one file at a time.
10624 *
10625 * ARGV << "testfile"
10626 * print while gets
10627 *
10628 * <em>produces:</em>
10629 *
10630 * This is line one
10631 * This is line two
10632 * This is line three
10633 * And so on...
10634 *
10635 * The style of programming using <code>$_</code> as an implicit
10636 * parameter is gradually losing favor in the Ruby community.
10637 */
10638
10639static VALUE
10640rb_f_gets(int argc, VALUE *argv, VALUE recv)
10641{
10642 if (recv == argf) {
10643 return argf_gets(argc, argv, argf);
10644 }
10645 return forward(argf, idGets, argc, argv);
10646}
10647
10648/*
10649 * call-seq:
10650 * ARGF.gets(sep=$/ [, getline_args]) -> string or nil
10651 * ARGF.gets(limit [, getline_args]) -> string or nil
10652 * ARGF.gets(sep, limit [, getline_args]) -> string or nil
10653 *
10654 * Returns the next line from the current file in ARGF.
10655 *
10656 * By default lines are assumed to be separated by <code>$/</code>;
10657 * to use a different character as a separator, supply it as a String
10658 * for the _sep_ argument.
10659 *
10660 * The optional _limit_ argument specifies how many characters of each line
10661 * to return. By default all characters are returned.
10662 *
10663 * See IO.readlines for details about getline_args.
10664 *
10665 */
10666static VALUE
10667argf_gets(int argc, VALUE *argv, VALUE argf)
10668{
10669 VALUE line;
10670
10671 line = argf_getline(argc, argv, argf);
10672 rb_lastline_set(line);
10673
10674 return line;
10675}
10676
10677VALUE
10679{
10680 VALUE line;
10681
10682 if (rb_rs != rb_default_rs) {
10683 return rb_f_gets(0, 0, argf);
10684 }
10685
10686 retry:
10687 if (!next_argv()) return Qnil;
10688 line = rb_io_gets(ARGF.current_file);
10689 if (NIL_P(line) && ARGF.next_p != -1) {
10690 rb_io_close(ARGF.current_file);
10691 ARGF.next_p = 1;
10692 goto retry;
10693 }
10694 rb_lastline_set(line);
10695 if (!NIL_P(line)) {
10696 ARGF.lineno++;
10697 ARGF.last_lineno = ARGF.lineno;
10698 }
10699
10700 return line;
10701}
10702
10703static VALUE argf_readline(int, VALUE *, VALUE);
10704
10705/*
10706 * call-seq:
10707 * readline(sep = $/, chomp: false) -> string
10708 * readline(limit, chomp: false) -> string
10709 * readline(sep, limit, chomp: false) -> string
10710 *
10711 * Equivalent to method Kernel#gets, except that it raises an exception
10712 * if called at end-of-stream:
10713 *
10714 * $ cat t.txt | ruby -e "p readlines; readline"
10715 * ["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"]
10716 * in `readline': end of file reached (EOFError)
10717 *
10718 * Optional keyword argument +chomp+ specifies whether line separators
10719 * are to be omitted.
10720 */
10721
10722static VALUE
10723rb_f_readline(int argc, VALUE *argv, VALUE recv)
10724{
10725 if (recv == argf) {
10726 return argf_readline(argc, argv, argf);
10727 }
10728 return forward(argf, rb_intern("readline"), argc, argv);
10729}
10730
10731
10732/*
10733 * call-seq:
10734 * ARGF.readline(sep=$/) -> string
10735 * ARGF.readline(limit) -> string
10736 * ARGF.readline(sep, limit) -> string
10737 *
10738 * Returns the next line from the current file in ARGF.
10739 *
10740 * By default lines are assumed to be separated by <code>$/</code>;
10741 * to use a different character as a separator, supply it as a String
10742 * for the _sep_ argument.
10743 *
10744 * The optional _limit_ argument specifies how many characters of each line
10745 * to return. By default all characters are returned.
10746 *
10747 * An EOFError is raised at the end of the file.
10748 */
10749static VALUE
10750argf_readline(int argc, VALUE *argv, VALUE argf)
10751{
10752 VALUE line;
10753
10754 if (!next_argv()) rb_eof_error();
10755 ARGF_FORWARD(argc, argv);
10756 line = argf_gets(argc, argv, argf);
10757 if (NIL_P(line)) {
10758 rb_eof_error();
10759 }
10760
10761 return line;
10762}
10763
10764static VALUE argf_readlines(int, VALUE *, VALUE);
10765
10766/*
10767 * call-seq:
10768 * readlines(sep = $/, chomp: false, **enc_opts) -> array
10769 * readlines(limit, chomp: false, **enc_opts) -> array
10770 * readlines(sep, limit, chomp: false, **enc_opts) -> array
10771 *
10772 * Returns an array containing the lines returned by calling
10773 * Kernel#gets until the end-of-stream is reached;
10774 * (see {Line IO}[rdoc-ref:IO@Line+IO]).
10775 *
10776 * With only string argument +sep+ given,
10777 * returns the remaining lines as determined by line separator +sep+,
10778 * or +nil+ if none;
10779 * see {Line Separator}[rdoc-ref:IO@Line+Separator]:
10780 *
10781 * # Default separator.
10782 * $ cat t.txt | ruby -e "p readlines"
10783 * ["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"]
10784 *
10785 * # Specified separator.
10786 * $ cat t.txt | ruby -e "p readlines 'li'"
10787 * ["First li", "ne\nSecond li", "ne\n\nFourth li", "ne\nFifth li", "ne\n"]
10788 *
10789 * # Get-all separator.
10790 * $ cat t.txt | ruby -e "p readlines nil"
10791 * ["First line\nSecond line\n\nFourth line\nFifth line\n"]
10792 *
10793 * # Get-paragraph separator.
10794 * $ cat t.txt | ruby -e "p readlines ''"
10795 * ["First line\nSecond line\n\n", "Fourth line\nFifth line\n"]
10796 *
10797 * With only integer argument +limit+ given,
10798 * limits the number of bytes in the line;
10799 * see {Line Limit}[rdoc-ref:IO@Line+Limit]:
10800 *
10801 * $cat t.txt | ruby -e "p readlines 10"
10802 * ["First line", "\n", "Second lin", "e\n", "\n", "Fourth lin", "e\n", "Fifth line", "\n"]
10803 *
10804 * $cat t.txt | ruby -e "p readlines 11"
10805 * ["First line\n", "Second line", "\n", "\n", "Fourth line", "\n", "Fifth line\n"]
10806 *
10807 * $cat t.txt | ruby -e "p readlines 12"
10808 * ["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"]
10809 *
10810 * With arguments +sep+ and +limit+ given,
10811 * combines the two behaviors
10812 * (see {Line Separator and Line Limit}[rdoc-ref:IO@Line+Separator+and+Line+Limit]).
10813 *
10814 * Optional keyword argument +chomp+ specifies whether line separators
10815 * are to be omitted:
10816 *
10817 * $ cat t.txt | ruby -e "p readlines(chomp: true)"
10818 * ["First line", "Second line", "", "Fourth line", "Fifth line"]
10819 *
10820 * Optional keyword arguments +enc_opts+ specify encoding options;
10821 * see {Encoding options}[rdoc-ref:encodings.rdoc@Encoding+Options].
10822 *
10823 */
10824
10825static VALUE
10826rb_f_readlines(int argc, VALUE *argv, VALUE recv)
10827{
10828 if (recv == argf) {
10829 return argf_readlines(argc, argv, argf);
10830 }
10831 return forward(argf, rb_intern("readlines"), argc, argv);
10832}
10833
10834/*
10835 * call-seq:
10836 * ARGF.readlines(sep = $/, chomp: false) -> array
10837 * ARGF.readlines(limit, chomp: false) -> array
10838 * ARGF.readlines(sep, limit, chomp: false) -> array
10839 *
10840 * ARGF.to_a(sep = $/, chomp: false) -> array
10841 * ARGF.to_a(limit, chomp: false) -> array
10842 * ARGF.to_a(sep, limit, chomp: false) -> array
10843 *
10844 * Reads each file in ARGF in its entirety, returning an Array containing
10845 * lines from the files. Lines are assumed to be separated by _sep_.
10846 *
10847 * lines = ARGF.readlines
10848 * lines[0] #=> "This is line one\n"
10849 *
10850 * See +IO.readlines+ for a full description of all options.
10851 */
10852static VALUE
10853argf_readlines(int argc, VALUE *argv, VALUE argf)
10854{
10855 long lineno = ARGF.lineno;
10856 VALUE lines, ary;
10857
10858 ary = rb_ary_new();
10859 while (next_argv()) {
10860 if (ARGF_GENERIC_INPUT_P()) {
10861 lines = forward_current(rb_intern("readlines"), argc, argv);
10862 }
10863 else {
10864 lines = rb_io_readlines(argc, argv, ARGF.current_file);
10865 argf_close(argf);
10866 }
10867 ARGF.next_p = 1;
10868 rb_ary_concat(ary, lines);
10869 ARGF.lineno = lineno + RARRAY_LEN(ary);
10870 ARGF.last_lineno = ARGF.lineno;
10871 }
10872 ARGF.init_p = 0;
10873 return ary;
10874}
10875
10876/*
10877 * call-seq:
10878 * `command` -> string
10879 *
10880 * Returns the <tt>$stdout</tt> output from running +command+ in a subshell;
10881 * sets global variable <tt>$?</tt> to the process status.
10882 *
10883 * This method has potential security vulnerabilities if called with untrusted input;
10884 * see {Command Injection}[rdoc-ref:security/command_injection.rdoc].
10885 *
10886 * Examples:
10887 *
10888 * $ `date` # => "Wed Apr 9 08:56:30 CDT 2003\n"
10889 * $ `echo oops && exit 99` # => "oops\n"
10890 * $ $? # => #<Process::Status: pid 17088 exit 99>
10891 * $ $?.exitstatus # => 99
10892 *
10893 * The built-in syntax <tt>%x{...}</tt> uses this method.
10894 *
10895 */
10896
10897static VALUE
10898rb_f_backquote(VALUE obj, VALUE str)
10899{
10900 VALUE port;
10901 VALUE result;
10902 rb_io_t *fptr;
10903
10904 StringValue(str);
10905 rb_last_status_clear();
10906 port = pipe_open_s(str, "r", FMODE_READABLE|DEFAULT_TEXTMODE, NULL);
10907 if (NIL_P(port)) return rb_str_new(0,0);
10908
10909 GetOpenFile(port, fptr);
10910 result = read_all(fptr, remain_size(fptr), Qnil);
10911 rb_io_close(port);
10912 rb_io_fptr_cleanup_all(fptr);
10913 RB_GC_GUARD(port);
10914
10915 return result;
10916}
10917
10918#ifdef HAVE_SYS_SELECT_H
10919#include <sys/select.h>
10920#endif
10921
10922static VALUE
10923select_internal(VALUE read, VALUE write, VALUE except, struct timeval *tp, rb_fdset_t *fds)
10924{
10925 VALUE res, list;
10926 rb_fdset_t *rp, *wp, *ep;
10927 rb_io_t *fptr;
10928 rb_len_t i;
10929 int max = 0, n;
10930 int pending = 0;
10931 struct timeval timerec;
10932
10933 if (!NIL_P(read)) {
10934 Check_Type(read, T_ARRAY);
10935 for (i=0; i<RARRAY_LEN(read); i++) {
10936 GetOpenFile(rb_io_get_io(RARRAY_AREF(read, i)), fptr);
10937 rb_fd_set(fptr->fd, &fds[0]);
10938 if (READ_DATA_PENDING(fptr) || READ_CHAR_PENDING(fptr)) { /* check for buffered data */
10939 pending++;
10940 rb_fd_set(fptr->fd, &fds[3]);
10941 }
10942 if (max < fptr->fd) max = fptr->fd;
10943 }
10944 if (pending) { /* no blocking if there's buffered data */
10945 timerec.tv_sec = timerec.tv_usec = 0;
10946 tp = &timerec;
10947 }
10948 rp = &fds[0];
10949 }
10950 else
10951 rp = 0;
10952
10953 if (!NIL_P(write)) {
10954 Check_Type(write, T_ARRAY);
10955 for (i=0; i<RARRAY_LEN(write); i++) {
10956 VALUE write_io = GetWriteIO(rb_io_get_io(RARRAY_AREF(write, i)));
10957 GetOpenFile(write_io, fptr);
10958 rb_fd_set(fptr->fd, &fds[1]);
10959 if (max < fptr->fd) max = fptr->fd;
10960 }
10961 wp = &fds[1];
10962 }
10963 else
10964 wp = 0;
10965
10966 if (!NIL_P(except)) {
10967 Check_Type(except, T_ARRAY);
10968 for (i=0; i<RARRAY_LEN(except); i++) {
10969 VALUE io = rb_io_get_io(RARRAY_AREF(except, i));
10970 VALUE write_io = GetWriteIO(io);
10971 GetOpenFile(io, fptr);
10972 rb_fd_set(fptr->fd, &fds[2]);
10973 if (max < fptr->fd) max = fptr->fd;
10974 if (io != write_io) {
10975 GetOpenFile(write_io, fptr);
10976 rb_fd_set(fptr->fd, &fds[2]);
10977 if (max < fptr->fd) max = fptr->fd;
10978 }
10979 }
10980 ep = &fds[2];
10981 }
10982 else {
10983 ep = 0;
10984 }
10985
10986 max++;
10987
10988 n = rb_thread_fd_select(max, rp, wp, ep, tp);
10989 if (n < 0) {
10990 rb_sys_fail(0);
10991 }
10992 if (!pending && n == 0) return Qnil; /* returns nil on timeout */
10993
10994 res = rb_ary_new2(3);
10995 rb_ary_push(res, rp ? rb_ary_new_capa(RARRAY_LEN(read)) : rb_ary_new());
10996 rb_ary_push(res, wp ? rb_ary_new_capa(RARRAY_LEN(write)) : rb_ary_new());
10997 rb_ary_push(res, ep ? rb_ary_new_capa(RARRAY_LEN(except)) : rb_ary_new());
10998
10999 if (rp) {
11000 list = RARRAY_AREF(res, 0);
11001 for (i=0; i< RARRAY_LEN(read); i++) {
11002 VALUE obj = rb_ary_entry(read, i);
11003 VALUE io = rb_io_get_io(obj);
11004 GetOpenFile(io, fptr);
11005 if (rb_fd_isset(fptr->fd, &fds[0]) ||
11006 rb_fd_isset(fptr->fd, &fds[3])) {
11007 rb_ary_push(list, obj);
11008 }
11009 }
11010 }
11011
11012 if (wp) {
11013 list = RARRAY_AREF(res, 1);
11014 for (i=0; i< RARRAY_LEN(write); i++) {
11015 VALUE obj = rb_ary_entry(write, i);
11016 VALUE io = rb_io_get_io(obj);
11017 VALUE write_io = GetWriteIO(io);
11018 GetOpenFile(write_io, fptr);
11019 if (rb_fd_isset(fptr->fd, &fds[1])) {
11020 rb_ary_push(list, obj);
11021 }
11022 }
11023 }
11024
11025 if (ep) {
11026 list = RARRAY_AREF(res, 2);
11027 for (i=0; i< RARRAY_LEN(except); i++) {
11028 VALUE obj = rb_ary_entry(except, i);
11029 VALUE io = rb_io_get_io(obj);
11030 VALUE write_io = GetWriteIO(io);
11031 GetOpenFile(io, fptr);
11032 if (rb_fd_isset(fptr->fd, &fds[2])) {
11033 rb_ary_push(list, obj);
11034 }
11035 else if (io != write_io) {
11036 GetOpenFile(write_io, fptr);
11037 if (rb_fd_isset(fptr->fd, &fds[2])) {
11038 rb_ary_push(list, obj);
11039 }
11040 }
11041 }
11042 }
11043
11044 return res; /* returns an empty array on interrupt */
11045}
11046
11048 VALUE read, write, except;
11049 struct timeval *timeout;
11050 rb_fdset_t fdsets[4];
11051};
11052
11053static VALUE
11054select_call(VALUE arg)
11055{
11056 struct select_args *p = (struct select_args *)arg;
11057
11058 return select_internal(p->read, p->write, p->except, p->timeout, p->fdsets);
11059}
11060
11061static VALUE
11062select_end(VALUE arg)
11063{
11064 struct select_args *p = (struct select_args *)arg;
11065 int i;
11066
11067 for (i = 0; i < numberof(p->fdsets); ++i)
11068 rb_fd_term(&p->fdsets[i]);
11069 return Qnil;
11070}
11071
11072static VALUE sym_normal, sym_sequential, sym_random,
11073 sym_willneed, sym_dontneed, sym_noreuse;
11074
11075#ifdef HAVE_POSIX_FADVISE
11076struct io_advise_struct {
11077 int fd;
11078 int advice;
11079 rb_off_t offset;
11080 rb_off_t len;
11081};
11082
11083static VALUE
11084io_advise_internal(void *arg)
11085{
11086 struct io_advise_struct *ptr = arg;
11087 return posix_fadvise(ptr->fd, ptr->offset, ptr->len, ptr->advice);
11088}
11089
11090static VALUE
11091io_advise_sym_to_const(VALUE sym)
11092{
11093#ifdef POSIX_FADV_NORMAL
11094 if (sym == sym_normal)
11095 return INT2NUM(POSIX_FADV_NORMAL);
11096#endif
11097
11098#ifdef POSIX_FADV_RANDOM
11099 if (sym == sym_random)
11100 return INT2NUM(POSIX_FADV_RANDOM);
11101#endif
11102
11103#ifdef POSIX_FADV_SEQUENTIAL
11104 if (sym == sym_sequential)
11105 return INT2NUM(POSIX_FADV_SEQUENTIAL);
11106#endif
11107
11108#ifdef POSIX_FADV_WILLNEED
11109 if (sym == sym_willneed)
11110 return INT2NUM(POSIX_FADV_WILLNEED);
11111#endif
11112
11113#ifdef POSIX_FADV_DONTNEED
11114 if (sym == sym_dontneed)
11115 return INT2NUM(POSIX_FADV_DONTNEED);
11116#endif
11117
11118#ifdef POSIX_FADV_NOREUSE
11119 if (sym == sym_noreuse)
11120 return INT2NUM(POSIX_FADV_NOREUSE);
11121#endif
11122
11123 return Qnil;
11124}
11125
11126static VALUE
11127do_io_advise(rb_io_t *fptr, VALUE advice, rb_off_t offset, rb_off_t len)
11128{
11129 int rv;
11130 struct io_advise_struct ias;
11131 VALUE num_adv;
11132
11133 num_adv = io_advise_sym_to_const(advice);
11134
11135 /*
11136 * The platform doesn't support this hint. We don't raise exception, instead
11137 * silently ignore it. Because IO::advise is only hint.
11138 */
11139 if (NIL_P(num_adv))
11140 return Qnil;
11141
11142 ias.fd = fptr->fd;
11143 ias.advice = NUM2INT(num_adv);
11144 ias.offset = offset;
11145 ias.len = len;
11146
11147 rv = (int)rb_io_blocking_region(fptr, io_advise_internal, &ias);
11148 if (rv && rv != ENOSYS) {
11149 /* posix_fadvise(2) doesn't set errno. On success it returns 0; otherwise
11150 it returns the error code. */
11151 VALUE message = rb_sprintf("%"PRIsVALUE" "
11152 "(%"PRI_OFFT_PREFIX"d, "
11153 "%"PRI_OFFT_PREFIX"d, "
11154 "%"PRIsVALUE")",
11155 fptr->pathv, offset, len, advice);
11156 rb_syserr_fail_str(rv, message);
11157 }
11158
11159 return Qnil;
11160}
11161
11162#endif /* HAVE_POSIX_FADVISE */
11163
11164static void
11165advice_arg_check(VALUE advice)
11166{
11167 if (!SYMBOL_P(advice))
11168 rb_raise(rb_eTypeError, "advice must be a Symbol");
11169
11170 if (advice != sym_normal &&
11171 advice != sym_sequential &&
11172 advice != sym_random &&
11173 advice != sym_willneed &&
11174 advice != sym_dontneed &&
11175 advice != sym_noreuse) {
11176 rb_raise(rb_eNotImpError, "Unsupported advice: %+"PRIsVALUE, advice);
11177 }
11178}
11179
11180/*
11181 * call-seq:
11182 * advise(advice, offset = 0, len = 0) -> nil
11183 *
11184 * Invokes Posix system call
11185 * {posix_fadvise(2)}[https://man7.org/linux/man-pages/man2/posix_fadvise.2.html],
11186 * which announces an intention to access data from the current file
11187 * in a particular manner.
11188 *
11189 * The arguments and results are platform-dependent.
11190 *
11191 * The relevant data is specified by:
11192 *
11193 * - +offset+: The offset of the first byte of data.
11194 * - +len+: The number of bytes to be accessed;
11195 * if +len+ is zero, or is larger than the number of bytes remaining,
11196 * all remaining bytes will be accessed.
11197 *
11198 * Argument +advice+ is one of the following symbols:
11199 *
11200 * - +:normal+: The application has no advice to give
11201 * about its access pattern for the specified data.
11202 * If no advice is given for an open file, this is the default assumption.
11203 * - +:sequential+: The application expects to access the specified data sequentially
11204 * (with lower offsets read before higher ones).
11205 * - +:random+: The specified data will be accessed in random order.
11206 * - +:noreuse+: The specified data will be accessed only once.
11207 * - +:willneed+: The specified data will be accessed in the near future.
11208 * - +:dontneed+: The specified data will not be accessed in the near future.
11209 *
11210 * Not implemented on all platforms.
11211 *
11212 */
11213static VALUE
11214rb_io_advise(int argc, VALUE *argv, VALUE io)
11215{
11216 VALUE advice, offset, len;
11217 rb_off_t off, l;
11218 rb_io_t *fptr;
11219
11220 rb_scan_args(argc, argv, "12", &advice, &offset, &len);
11221 advice_arg_check(advice);
11222
11223 io = GetWriteIO(io);
11224 GetOpenFile(io, fptr);
11225
11226 off = NIL_P(offset) ? 0 : NUM2OFFT(offset);
11227 l = NIL_P(len) ? 0 : NUM2OFFT(len);
11228
11229#ifdef HAVE_POSIX_FADVISE
11230 return do_io_advise(fptr, advice, off, l);
11231#else
11232 ((void)off, (void)l); /* Ignore all hint */
11233 return Qnil;
11234#endif
11235}
11236
11237static int
11238is_pos_inf(VALUE x)
11239{
11240 double f;
11241 if (!RB_FLOAT_TYPE_P(x))
11242 return 0;
11243 f = RFLOAT_VALUE(x);
11244 return isinf(f) && 0 < f;
11245}
11246
11247/*
11248 * call-seq:
11249 * IO.select(read_ios, write_ios = [], error_ios = [], timeout = nil) -> array or nil
11250 *
11251 * Invokes system call {select(2)}[https://man7.org/linux/man-pages/man2/select.2.html],
11252 * which monitors multiple file descriptors,
11253 * waiting until one or more of the file descriptors
11254 * becomes ready for some class of I/O operation.
11255 *
11256 * Not implemented on all platforms.
11257 *
11258 * Each of the arguments +read_ios+, +write_ios+, and +error_ios+
11259 * is an array of IO objects.
11260 *
11261 * Argument +timeout+ is a numeric value (such as integer or float) timeout
11262 * interval in seconds.
11263 * +timeout+ can also be +nil+ or +Float::INFINITY+.
11264 * +nil+ and +Float::INFINITY+ means no timeout.
11265 *
11266 * The method monitors the \IO objects given in all three arrays,
11267 * waiting for some to be ready;
11268 * returns a 3-element array whose elements are:
11269 *
11270 * - An array of the objects in +read_ios+ that are ready for reading.
11271 * - An array of the objects in +write_ios+ that are ready for writing.
11272 * - An array of the objects in +error_ios+ have pending exceptions.
11273 *
11274 * If no object becomes ready within the given +timeout+, +nil+ is returned.
11275 *
11276 * \IO.select peeks the buffer of \IO objects for testing readability.
11277 * If the \IO buffer is not empty, \IO.select immediately notifies
11278 * readability. This "peek" only happens for \IO objects. It does not
11279 * happen for IO-like objects such as OpenSSL::SSL::SSLSocket.
11280 *
11281 * The best way to use \IO.select is invoking it after non-blocking
11282 * methods such as #read_nonblock, #write_nonblock, etc. The methods
11283 * raise an exception which is extended by IO::WaitReadable or
11284 * IO::WaitWritable. The modules notify how the caller should wait
11285 * with \IO.select. If IO::WaitReadable is raised, the caller should
11286 * wait for reading. If IO::WaitWritable is raised, the caller should
11287 * wait for writing.
11288 *
11289 * So, blocking read (#readpartial) can be emulated using
11290 * #read_nonblock and \IO.select as follows:
11291 *
11292 * begin
11293 * result = io_like.read_nonblock(maxlen)
11294 * rescue IO::WaitReadable
11295 * IO.select([io_like])
11296 * retry
11297 * rescue IO::WaitWritable
11298 * IO.select(nil, [io_like])
11299 * retry
11300 * end
11301 *
11302 * Especially, the combination of non-blocking methods and \IO.select is
11303 * preferred for IO like objects such as OpenSSL::SSL::SSLSocket. It
11304 * has #to_io method to return underlying IO object. IO.select calls
11305 * #to_io to obtain the file descriptor to wait.
11306 *
11307 * This means that readability notified by \IO.select doesn't mean
11308 * readability from OpenSSL::SSL::SSLSocket object.
11309 *
11310 * The most likely situation is that OpenSSL::SSL::SSLSocket buffers
11311 * some data. \IO.select doesn't see the buffer. So \IO.select can
11312 * block when OpenSSL::SSL::SSLSocket#readpartial doesn't block.
11313 *
11314 * However, several more complicated situations exist.
11315 *
11316 * SSL is a protocol which is sequence of records.
11317 * The record consists of multiple bytes.
11318 * So, the remote side of SSL sends a partial record, IO.select
11319 * notifies readability but OpenSSL::SSL::SSLSocket cannot decrypt a
11320 * byte and OpenSSL::SSL::SSLSocket#readpartial will block.
11321 *
11322 * Also, the remote side can request SSL renegotiation which forces
11323 * the local SSL engine to write some data.
11324 * This means OpenSSL::SSL::SSLSocket#readpartial may invoke #write
11325 * system call and it can block.
11326 * In such a situation, OpenSSL::SSL::SSLSocket#read_nonblock raises
11327 * IO::WaitWritable instead of blocking.
11328 * So, the caller should wait for ready for writability as above
11329 * example.
11330 *
11331 * The combination of non-blocking methods and \IO.select is also useful
11332 * for streams such as tty, pipe socket socket when multiple processes
11333 * read from a stream.
11334 *
11335 * Finally, Linux kernel developers don't guarantee that
11336 * readability of select(2) means readability of following read(2) even
11337 * for a single process;
11338 * see {select(2)}[https://man7.org/linux/man-pages/man2/select.2.html]
11339 *
11340 * Invoking \IO.select before IO#readpartial works well as usual.
11341 * However it is not the best way to use \IO.select.
11342 *
11343 * The writability notified by select(2) doesn't show
11344 * how many bytes are writable.
11345 * IO#write method blocks until given whole string is written.
11346 * So, <tt>IO#write(two or more bytes)</tt> can block after
11347 * writability is notified by \IO.select. IO#write_nonblock is required
11348 * to avoid the blocking.
11349 *
11350 * Blocking write (#write) can be emulated using #write_nonblock and
11351 * IO.select as follows: IO::WaitReadable should also be rescued for
11352 * SSL renegotiation in OpenSSL::SSL::SSLSocket.
11353 *
11354 * while 0 < string.bytesize
11355 * begin
11356 * written = io_like.write_nonblock(string)
11357 * rescue IO::WaitReadable
11358 * IO.select([io_like])
11359 * retry
11360 * rescue IO::WaitWritable
11361 * IO.select(nil, [io_like])
11362 * retry
11363 * end
11364 * string = string.byteslice(written..-1)
11365 * end
11366 *
11367 * Example:
11368 *
11369 * rp, wp = IO.pipe
11370 * mesg = "ping "
11371 * 100.times {
11372 * # IO.select follows IO#read. Not the best way to use IO.select.
11373 * rs, ws, = IO.select([rp], [wp])
11374 * if r = rs[0]
11375 * ret = r.read(5)
11376 * print ret
11377 * case ret
11378 * when /ping/
11379 * mesg = "pong\n"
11380 * when /pong/
11381 * mesg = "ping "
11382 * end
11383 * end
11384 * if w = ws[0]
11385 * w.write(mesg)
11386 * end
11387 * }
11388 *
11389 * Output:
11390 *
11391 * ping pong
11392 * ping pong
11393 * ping pong
11394 * (snipped)
11395 * ping
11396 *
11397 */
11398
11399static VALUE
11400rb_f_select(int argc, VALUE *argv, VALUE obj)
11401{
11402 VALUE scheduler = rb_fiber_scheduler_current();
11403 if (scheduler != Qnil) {
11404 // It's optionally supported.
11405 VALUE result = rb_fiber_scheduler_io_selectv(scheduler, argc, argv);
11406 if (!UNDEF_P(result)) return result;
11407 }
11408
11409 VALUE timeout;
11410 struct select_args args;
11411 struct timeval timerec;
11412 int i;
11413
11414 rb_scan_args(argc, argv, "13", &args.read, &args.write, &args.except, &timeout);
11415 if (NIL_P(timeout) || is_pos_inf(timeout)) {
11416 args.timeout = 0;
11417 }
11418 else {
11419 timerec = rb_time_interval(timeout);
11420 args.timeout = &timerec;
11421 }
11422
11423 for (i = 0; i < numberof(args.fdsets); ++i)
11424 rb_fd_init(&args.fdsets[i]);
11425
11426 return rb_ensure(select_call, (VALUE)&args, select_end, (VALUE)&args);
11427}
11428
11429#ifdef IOCTL_REQ_TYPE
11430 typedef IOCTL_REQ_TYPE ioctl_req_t;
11431#else
11432 typedef int ioctl_req_t;
11433# define NUM2IOCTLREQ(num) ((int)NUM2LONG(num))
11434#endif
11435
11436#ifdef HAVE_IOCTL
11437struct ioctl_arg {
11438 int fd;
11439 ioctl_req_t cmd;
11440 long narg;
11441};
11442
11443static VALUE
11444nogvl_ioctl(void *ptr)
11445{
11446 struct ioctl_arg *arg = ptr;
11447
11448 return (VALUE)ioctl(arg->fd, arg->cmd, arg->narg);
11449}
11450
11451static int
11452do_ioctl(struct rb_io *io, ioctl_req_t cmd, long narg)
11453{
11454 int retval;
11455 struct ioctl_arg arg;
11456
11457 arg.fd = io->fd;
11458 arg.cmd = cmd;
11459 arg.narg = narg;
11460
11461 retval = (int)rb_io_blocking_region(io, nogvl_ioctl, &arg);
11462
11463 return retval;
11464}
11465#endif
11466
11467#define DEFAULT_IOCTL_NARG_LEN (256)
11468
11469#if defined(__linux__) && defined(_IOC_SIZE)
11470static long
11471linux_iocparm_len(ioctl_req_t cmd)
11472{
11473 long len;
11474
11475 if ((cmd & 0xFFFF0000) == 0) {
11476 /* legacy and unstructured ioctl number. */
11477 return DEFAULT_IOCTL_NARG_LEN;
11478 }
11479
11480 len = _IOC_SIZE(cmd);
11481
11482 /* paranoia check for silly drivers which don't keep ioctl convention */
11483 if (len < DEFAULT_IOCTL_NARG_LEN)
11484 len = DEFAULT_IOCTL_NARG_LEN;
11485
11486 return len;
11487}
11488#endif
11489
11490#ifdef HAVE_IOCTL
11491static long
11492ioctl_narg_len(ioctl_req_t cmd)
11493{
11494 long len;
11495
11496#ifdef IOCPARM_MASK
11497#ifndef IOCPARM_LEN
11498#define IOCPARM_LEN(x) (((x) >> 16) & IOCPARM_MASK)
11499#endif
11500#endif
11501#ifdef IOCPARM_LEN
11502 len = IOCPARM_LEN(cmd); /* on BSDish systems we're safe */
11503#elif defined(__linux__) && defined(_IOC_SIZE)
11504 len = linux_iocparm_len(cmd);
11505#else
11506 /* otherwise guess at what's safe */
11507 len = DEFAULT_IOCTL_NARG_LEN;
11508#endif
11509
11510 return len;
11511}
11512#endif
11513
11514#ifdef HAVE_FCNTL
11515#ifdef __linux__
11516typedef long fcntl_arg_t;
11517#else
11518/* posix */
11519typedef int fcntl_arg_t;
11520#endif
11521
11522static long
11523fcntl_narg_len(ioctl_req_t cmd)
11524{
11525 long len;
11526
11527 switch (cmd) {
11528#ifdef F_DUPFD
11529 case F_DUPFD:
11530 len = sizeof(fcntl_arg_t);
11531 break;
11532#endif
11533#ifdef F_DUP2FD /* bsd specific */
11534 case F_DUP2FD:
11535 len = sizeof(int);
11536 break;
11537#endif
11538#ifdef F_DUPFD_CLOEXEC /* linux specific */
11539 case F_DUPFD_CLOEXEC:
11540 len = sizeof(fcntl_arg_t);
11541 break;
11542#endif
11543#ifdef F_GETFD
11544 case F_GETFD:
11545 len = 1;
11546 break;
11547#endif
11548#ifdef F_SETFD
11549 case F_SETFD:
11550 len = sizeof(fcntl_arg_t);
11551 break;
11552#endif
11553#ifdef F_GETFL
11554 case F_GETFL:
11555 len = 1;
11556 break;
11557#endif
11558#ifdef F_SETFL
11559 case F_SETFL:
11560 len = sizeof(fcntl_arg_t);
11561 break;
11562#endif
11563#ifdef F_GETOWN
11564 case F_GETOWN:
11565 len = 1;
11566 break;
11567#endif
11568#ifdef F_SETOWN
11569 case F_SETOWN:
11570 len = sizeof(fcntl_arg_t);
11571 break;
11572#endif
11573#ifdef F_GETOWN_EX /* linux specific */
11574 case F_GETOWN_EX:
11575 len = sizeof(struct f_owner_ex);
11576 break;
11577#endif
11578#ifdef F_SETOWN_EX /* linux specific */
11579 case F_SETOWN_EX:
11580 len = sizeof(struct f_owner_ex);
11581 break;
11582#endif
11583#ifdef F_GETLK
11584 case F_GETLK:
11585 len = sizeof(struct flock);
11586 break;
11587#endif
11588#ifdef F_SETLK
11589 case F_SETLK:
11590 len = sizeof(struct flock);
11591 break;
11592#endif
11593#ifdef F_SETLKW
11594 case F_SETLKW:
11595 len = sizeof(struct flock);
11596 break;
11597#endif
11598#ifdef F_READAHEAD /* bsd specific */
11599 case F_READAHEAD:
11600 len = sizeof(int);
11601 break;
11602#endif
11603#ifdef F_RDAHEAD /* Darwin specific */
11604 case F_RDAHEAD:
11605 len = sizeof(int);
11606 break;
11607#endif
11608#ifdef F_GETSIG /* linux specific */
11609 case F_GETSIG:
11610 len = 1;
11611 break;
11612#endif
11613#ifdef F_SETSIG /* linux specific */
11614 case F_SETSIG:
11615 len = sizeof(fcntl_arg_t);
11616 break;
11617#endif
11618#ifdef F_GETLEASE /* linux specific */
11619 case F_GETLEASE:
11620 len = 1;
11621 break;
11622#endif
11623#ifdef F_SETLEASE /* linux specific */
11624 case F_SETLEASE:
11625 len = sizeof(fcntl_arg_t);
11626 break;
11627#endif
11628#ifdef F_NOTIFY /* linux specific */
11629 case F_NOTIFY:
11630 len = sizeof(fcntl_arg_t);
11631 break;
11632#endif
11633
11634 default:
11635 len = 256;
11636 break;
11637 }
11638
11639 return len;
11640}
11641#else /* HAVE_FCNTL */
11642static long
11643fcntl_narg_len(ioctl_req_t cmd)
11644{
11645 return 0;
11646}
11647#endif /* HAVE_FCNTL */
11648
11649#define NARG_SENTINEL 17
11650
11651static long
11652setup_narg(ioctl_req_t cmd, VALUE *argp, long (*narg_len)(ioctl_req_t))
11653{
11654 long narg = 0;
11655 VALUE arg = *argp;
11656
11657 if (!RTEST(arg)) {
11658 narg = 0;
11659 }
11660 else if (FIXNUM_P(arg)) {
11661 narg = FIX2LONG(arg);
11662 }
11663 else if (arg == Qtrue) {
11664 narg = 1;
11665 }
11666 else {
11667 VALUE tmp = rb_check_string_type(arg);
11668
11669 if (NIL_P(tmp)) {
11670 narg = NUM2LONG(arg);
11671 }
11672 else {
11673 char *ptr;
11674 long req_len;
11675 rb_len_t slen;
11676
11677 *argp = arg = tmp;
11678 req_len = narg_len(cmd);
11679 rb_str_modify(arg);
11680
11681 slen = RSTRING_LEN(arg);
11682 /* expand for data + sentinel. */
11683 if (slen < req_len+1) {
11684 rb_str_resize(arg, req_len+1);
11685 MEMZERO(RSTRING_PTR(arg)+slen, char, req_len-slen);
11686 slen = req_len+1;
11687 }
11688 /* a little sanity check here */
11689 ptr = RSTRING_PTR(arg);
11690 ptr[slen - 1] = NARG_SENTINEL;
11691 narg = (long)(SIGNED_VALUE)ptr;
11692 }
11693 }
11694
11695 return narg;
11696}
11697
11698static VALUE
11699finish_narg(int retval, VALUE arg, const rb_io_t *fptr)
11700{
11701 if (retval < 0) rb_sys_fail_path(fptr->pathv);
11702 if (RB_TYPE_P(arg, T_STRING)) {
11703 char *ptr;
11704 rb_len_t slen;
11705 RSTRING_GETMEM(arg, ptr, slen);
11706 if (ptr[slen-1] != NARG_SENTINEL)
11707 rb_raise(rb_eArgError, "return value overflowed string");
11708 ptr[slen-1] = '\0';
11709 }
11710
11711 return INT2NUM(retval);
11712}
11713
11714#ifdef HAVE_IOCTL
11715static VALUE
11716rb_ioctl(VALUE io, VALUE req, VALUE arg)
11717{
11718 ioctl_req_t cmd = NUM2IOCTLREQ(req);
11719 rb_io_t *fptr;
11720 long narg;
11721 int retval;
11722
11723 narg = setup_narg(cmd, &arg, ioctl_narg_len);
11724 GetOpenFile(io, fptr);
11725 retval = do_ioctl(fptr, cmd, narg);
11726 return finish_narg(retval, arg, fptr);
11727}
11728
11729/*
11730 * call-seq:
11731 * ioctl(integer_cmd, argument) -> integer
11732 *
11733 * Invokes Posix system call {ioctl(2)}[https://man7.org/linux/man-pages/man2/ioctl.2.html],
11734 * which issues a low-level command to an I/O device.
11735 *
11736 * Issues a low-level command to an I/O device.
11737 * The arguments and returned value are platform-dependent.
11738 * The effect of the call is platform-dependent.
11739 *
11740 * If argument +argument+ is an integer, it is passed directly;
11741 * if it is a string, it is interpreted as a binary sequence of bytes.
11742 *
11743 * Not implemented on all platforms.
11744 *
11745 */
11746
11747static VALUE
11748rb_io_ioctl(int argc, VALUE *argv, VALUE io)
11749{
11750 VALUE req, arg;
11751
11752 rb_scan_args(argc, argv, "11", &req, &arg);
11753 return rb_ioctl(io, req, arg);
11754}
11755#else
11756#define rb_io_ioctl rb_f_notimplement
11757#endif
11758
11759#ifdef HAVE_FCNTL
11760struct fcntl_arg {
11761 int fd;
11762 int cmd;
11763 long narg;
11764};
11765
11766static VALUE
11767nogvl_fcntl(void *ptr)
11768{
11769 struct fcntl_arg *arg = ptr;
11770
11771#if defined(F_DUPFD)
11772 if (arg->cmd == F_DUPFD)
11773 return (VALUE)rb_cloexec_fcntl_dupfd(arg->fd, (int)arg->narg);
11774#endif
11775 return (VALUE)fcntl(arg->fd, arg->cmd, arg->narg);
11776}
11777
11778static int
11779do_fcntl(struct rb_io *io, int cmd, long narg)
11780{
11781 int retval;
11782 struct fcntl_arg arg;
11783
11784 arg.fd = io->fd;
11785 arg.cmd = cmd;
11786 arg.narg = narg;
11787
11788 retval = (int)rb_io_blocking_region(io, nogvl_fcntl, &arg);
11789 if (retval != -1) {
11790 switch (cmd) {
11791#if defined(F_DUPFD)
11792 case F_DUPFD:
11793#endif
11794#if defined(F_DUPFD_CLOEXEC)
11795 case F_DUPFD_CLOEXEC:
11796#endif
11797 rb_update_max_fd(retval);
11798 }
11799 }
11800
11801 return retval;
11802}
11803
11804static VALUE
11805rb_fcntl(VALUE io, VALUE req, VALUE arg)
11806{
11807 int cmd = NUM2INT(req);
11808 rb_io_t *fptr;
11809 long narg;
11810 int retval;
11811
11812 narg = setup_narg(cmd, &arg, fcntl_narg_len);
11813 GetOpenFile(io, fptr);
11814 retval = do_fcntl(fptr, cmd, narg);
11815 return finish_narg(retval, arg, fptr);
11816}
11817
11818/*
11819 * call-seq:
11820 * fcntl(integer_cmd, argument) -> integer
11821 *
11822 * Invokes Posix system call {fcntl(2)}[https://man7.org/linux/man-pages/man2/fcntl.2.html],
11823 * which provides a mechanism for issuing low-level commands to control or query
11824 * a file-oriented I/O stream. Arguments and results are platform
11825 * dependent.
11826 *
11827 * If +argument+ is a number, its value is passed directly;
11828 * if it is a string, it is interpreted as a binary sequence of bytes.
11829 * (Array#pack might be a useful way to build this string.)
11830 *
11831 * Not implemented on all platforms.
11832 *
11833 */
11834
11835static VALUE
11836rb_io_fcntl(int argc, VALUE *argv, VALUE io)
11837{
11838 VALUE req, arg;
11839
11840 rb_scan_args(argc, argv, "11", &req, &arg);
11841 return rb_fcntl(io, req, arg);
11842}
11843#else
11844#define rb_io_fcntl rb_f_notimplement
11845#endif
11846
11847#if defined(HAVE_SYSCALL) || defined(HAVE___SYSCALL)
11848/*
11849 * call-seq:
11850 * syscall(integer_callno, *arguments) -> integer
11851 *
11852 * Invokes Posix system call {syscall(2)}[https://man7.org/linux/man-pages/man2/syscall.2.html],
11853 * which calls a specified function.
11854 *
11855 * Calls the operating system function identified by +integer_callno+;
11856 * returns the result of the function or raises SystemCallError if it failed.
11857 * The effect of the call is platform-dependent.
11858 * The arguments and returned value are platform-dependent.
11859 *
11860 * For each of +arguments+: if it is an integer, it is passed directly;
11861 * if it is a string, it is interpreted as a binary sequence of bytes.
11862 * There may be as many as nine such arguments.
11863 *
11864 * Arguments +integer_callno+ and +argument+, as well as the returned value,
11865 * are platform-dependent.
11866 *
11867 * Note: Method +syscall+ is essentially unsafe and unportable.
11868 * The DL (Fiddle) library is preferred for safer and a bit
11869 * more portable programming.
11870 *
11871 * Not implemented on all platforms.
11872 *
11873 */
11874
11875static VALUE
11876rb_f_syscall(int argc, VALUE *argv, VALUE _)
11877{
11878 VALUE arg[8];
11879#if SIZEOF_VOIDP == 8 && defined(HAVE___SYSCALL) && SIZEOF_INT != 8 /* mainly *BSD */
11880# define SYSCALL __syscall
11881# define NUM2SYSCALLID(x) NUM2LONG(x)
11882# define RETVAL2NUM(x) LONG2NUM(x)
11883# if SIZEOF_LONG == 8
11884 long num, retval = -1;
11885# elif SIZEOF_LONG_LONG == 8
11886 long long num, retval = -1;
11887# else
11888# error ---->> it is asserted that __syscall takes the first argument and returns retval in 64bit signed integer. <<----
11889# endif
11890#elif defined(__linux__)
11891# define SYSCALL syscall
11892# define NUM2SYSCALLID(x) NUM2LONG(x)
11893# define RETVAL2NUM(x) LONG2NUM(x)
11894 /*
11895 * Linux man page says, syscall(2) function prototype is below.
11896 *
11897 * int syscall(int number, ...);
11898 *
11899 * But, it's incorrect. Actual one takes and returned long. (see unistd.h)
11900 */
11901 long num, retval = -1;
11902#else
11903# define SYSCALL syscall
11904# define NUM2SYSCALLID(x) NUM2INT(x)
11905# define RETVAL2NUM(x) INT2NUM(x)
11906 int num, retval = -1;
11907#endif
11908 int i;
11909
11910 if (RTEST(ruby_verbose)) {
11912 "We plan to remove a syscall function at future release. DL(Fiddle) provides safer alternative.");
11913 }
11914
11915 if (argc == 0)
11916 rb_raise(rb_eArgError, "too few arguments for syscall");
11917 if (argc > numberof(arg))
11918 rb_raise(rb_eArgError, "too many arguments for syscall");
11919 num = NUM2SYSCALLID(argv[0]); ++argv;
11920 for (i = argc - 1; i--; ) {
11921 VALUE v = rb_check_string_type(argv[i]);
11922
11923 if (!NIL_P(v)) {
11924 StringValue(v);
11925 rb_str_modify(v);
11926 arg[i] = (VALUE)StringValueCStr(v);
11927 }
11928 else {
11929 arg[i] = (VALUE)NUM2LONG(argv[i]);
11930 }
11931 }
11932
11933 switch (argc) {
11934 case 1:
11935 retval = SYSCALL(num);
11936 break;
11937 case 2:
11938 retval = SYSCALL(num, arg[0]);
11939 break;
11940 case 3:
11941 retval = SYSCALL(num, arg[0],arg[1]);
11942 break;
11943 case 4:
11944 retval = SYSCALL(num, arg[0],arg[1],arg[2]);
11945 break;
11946 case 5:
11947 retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3]);
11948 break;
11949 case 6:
11950 retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3],arg[4]);
11951 break;
11952 case 7:
11953 retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3],arg[4],arg[5]);
11954 break;
11955 case 8:
11956 retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6]);
11957 break;
11958 }
11959
11960 if (retval == -1)
11961 rb_sys_fail(0);
11962 return RETVAL2NUM(retval);
11963#undef SYSCALL
11964#undef NUM2SYSCALLID
11965#undef RETVAL2NUM
11966}
11967#else
11968#define rb_f_syscall rb_f_notimplement
11969#endif
11970
11971static VALUE
11972io_new_instance(VALUE args)
11973{
11974 return rb_class_new_instance(2, (VALUE*)args+1, *(VALUE*)args);
11975}
11976
11977static rb_encoding *
11978find_encoding(VALUE v)
11979{
11980 rb_encoding *enc = rb_find_encoding(v);
11981 if (!enc) rb_warn("Unsupported encoding %"PRIsVALUE" ignored", v);
11982 return enc;
11983}
11984
11985static void
11986io_encoding_set(rb_io_t *fptr, VALUE v1, VALUE v2, VALUE opt)
11987{
11988 rb_encoding *enc, *enc2;
11989 int ecflags = fptr->encs.ecflags;
11990 VALUE ecopts, tmp;
11991
11992 if (!NIL_P(v2)) {
11993 enc2 = find_encoding(v1);
11994 tmp = rb_check_string_type(v2);
11995 if (!NIL_P(tmp)) {
11996 if (RSTRING_LEN(tmp) == 1 && RSTRING_PTR(tmp)[0] == '-') {
11997 /* Special case - "-" => no transcoding */
11998 enc = enc2;
11999 enc2 = NULL;
12000 }
12001 else
12002 enc = find_encoding(v2);
12003 if (enc == enc2) {
12004 /* Special case - "-" => no transcoding */
12005 enc2 = NULL;
12006 }
12007 }
12008 else {
12009 enc = find_encoding(v2);
12010 if (enc == enc2) {
12011 /* Special case - "-" => no transcoding */
12012 enc2 = NULL;
12013 }
12014 }
12015 if (enc2 == rb_ascii8bit_encoding()) {
12016 /* If external is ASCII-8BIT, no transcoding */
12017 enc = enc2;
12018 enc2 = NULL;
12019 }
12020 SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags);
12021 ecflags = rb_econv_prepare_options(opt, &ecopts, ecflags);
12022 }
12023 else {
12024 if (NIL_P(v1)) {
12025 /* Set to default encodings */
12026 rb_io_ext_int_to_encs(NULL, NULL, &enc, &enc2, 0);
12027 SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags);
12028 ecopts = Qnil;
12029 }
12030 else {
12031 tmp = rb_check_string_type(v1);
12032 if (!NIL_P(tmp) && rb_enc_asciicompat(enc = rb_enc_get(tmp))) {
12033 parse_mode_enc(RSTRING_PTR(tmp), enc, &enc, &enc2, NULL);
12034 SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags);
12035 }
12036 else {
12037 rb_io_ext_int_to_encs(find_encoding(v1), NULL, &enc, &enc2, 0);
12038 SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags);
12039 }
12040 ecflags = rb_econv_prepare_options(opt, &ecopts, ecflags);
12041 }
12042 }
12043 validate_enc_binmode(&fptr->mode, ecflags, enc, enc2);
12044 fptr->encs.enc = enc;
12045 fptr->encs.enc2 = enc2;
12046 fptr->encs.ecflags = ecflags;
12047 fptr->encs.ecopts = ecopts;
12048 clear_codeconv(fptr);
12049
12050}
12051
12053 rb_io_t *fptr;
12054 VALUE v1;
12055 VALUE v2;
12056 VALUE opt;
12057};
12058
12059static VALUE
12060io_encoding_set_v(VALUE v)
12061{
12062 struct io_encoding_set_args *arg = (struct io_encoding_set_args *)v;
12063 io_encoding_set(arg->fptr, arg->v1, arg->v2, arg->opt);
12064 return Qnil;
12065}
12066
12067static VALUE
12068pipe_pair_close(VALUE rw)
12069{
12070 VALUE *rwp = (VALUE *)rw;
12071 return rb_ensure(io_close, rwp[0], io_close, rwp[1]);
12072}
12073
12074/*
12075 * call-seq:
12076 * IO.pipe(**opts) -> [read_io, write_io]
12077 * IO.pipe(enc, **opts) -> [read_io, write_io]
12078 * IO.pipe(ext_enc, int_enc, **opts) -> [read_io, write_io]
12079 * IO.pipe(**opts) {|read_io, write_io| ...} -> object
12080 * IO.pipe(enc, **opts) {|read_io, write_io| ...} -> object
12081 * IO.pipe(ext_enc, int_enc, **opts) {|read_io, write_io| ...} -> object
12082 *
12083 * Creates a pair of pipe endpoints, +read_io+ and +write_io+,
12084 * connected to each other.
12085 *
12086 * If argument +enc_string+ is given, it must be a string containing one of:
12087 *
12088 * - The name of the encoding to be used as the external encoding.
12089 * - The colon-separated names of two encodings to be used as the external
12090 * and internal encodings.
12091 *
12092 * If argument +int_enc+ is given, it must be an Encoding object
12093 * or encoding name string that specifies the internal encoding to be used;
12094 * if argument +ext_enc+ is also given, it must be an Encoding object
12095 * or encoding name string that specifies the external encoding to be used.
12096 *
12097 * The string read from +read_io+ is tagged with the external encoding;
12098 * if an internal encoding is also specified, the string is converted
12099 * to, and tagged with, that encoding.
12100 *
12101 * If any encoding is specified,
12102 * optional hash arguments specify the conversion option.
12103 *
12104 * Optional keyword arguments +opts+ specify:
12105 *
12106 * - {Open Options}[rdoc-ref:IO@Open+Options].
12107 * - {Encoding Options}[rdoc-ref:encodings.rdoc@Encoding+Options].
12108 *
12109 * With no block given, returns the two endpoints in an array:
12110 *
12111 * IO.pipe # => [#<IO:fd 4>, #<IO:fd 5>]
12112 *
12113 * With a block given, calls the block with the two endpoints;
12114 * closes both endpoints and returns the value of the block:
12115 *
12116 * IO.pipe {|read_io, write_io| p read_io; p write_io }
12117 *
12118 * Output:
12119 *
12120 * #<IO:fd 6>
12121 * #<IO:fd 7>
12122 *
12123 * Not available on all platforms.
12124 *
12125 * In the example below, the two processes close the ends of the pipe
12126 * that they are not using. This is not just a cosmetic nicety. The
12127 * read end of a pipe will not generate an end of file condition if
12128 * there are any writers with the pipe still open. In the case of the
12129 * parent process, the <tt>rd.read</tt> will never return if it
12130 * does not first issue a <tt>wr.close</tt>:
12131 *
12132 * rd, wr = IO.pipe
12133 *
12134 * if fork
12135 * wr.close
12136 * puts "Parent got: <#{rd.read}>"
12137 * rd.close
12138 * Process.wait
12139 * else
12140 * rd.close
12141 * puts 'Sending message to parent'
12142 * wr.write "Hi Dad"
12143 * wr.close
12144 * end
12145 *
12146 * <em>produces:</em>
12147 *
12148 * Sending message to parent
12149 * Parent got: <Hi Dad>
12150 *
12151 */
12152
12153static VALUE
12154rb_io_s_pipe(int argc, VALUE *argv, VALUE klass)
12155{
12156 int pipes[2], state;
12157 VALUE r, w, args[3], v1, v2;
12158 VALUE opt;
12159 rb_io_t *fptr, *fptr2;
12160 struct io_encoding_set_args ies_args;
12161 enum rb_io_mode fmode = 0;
12162 VALUE ret;
12163
12164 argc = rb_scan_args(argc, argv, "02:", &v1, &v2, &opt);
12165 if (rb_pipe(pipes) < 0)
12166 rb_sys_fail(0);
12167
12168 args[0] = klass;
12169 args[1] = INT2NUM(pipes[0]);
12170 args[2] = INT2FIX(O_RDONLY);
12171 r = rb_protect(io_new_instance, (VALUE)args, &state);
12172 if (state) {
12173 close(pipes[0]);
12174 close(pipes[1]);
12175 rb_jump_tag(state);
12176 }
12177 GetOpenFile(r, fptr);
12178
12179 ies_args.fptr = fptr;
12180 ies_args.v1 = v1;
12181 ies_args.v2 = v2;
12182 ies_args.opt = opt;
12183 rb_protect(io_encoding_set_v, (VALUE)&ies_args, &state);
12184 if (state) {
12185 close(pipes[1]);
12186 io_close(r);
12187 rb_jump_tag(state);
12188 }
12189
12190 args[1] = INT2NUM(pipes[1]);
12191 args[2] = INT2FIX(O_WRONLY);
12192 w = rb_protect(io_new_instance, (VALUE)args, &state);
12193 if (state) {
12194 close(pipes[1]);
12195 if (!NIL_P(r)) rb_io_close(r);
12196 rb_jump_tag(state);
12197 }
12198 GetOpenFile(w, fptr2);
12199 rb_io_synchronized(fptr2);
12200
12201 extract_binmode(opt, &fmode);
12202
12203 if ((fmode & FMODE_BINMODE) && NIL_P(v1)) {
12206 }
12207
12208#if DEFAULT_TEXTMODE
12209 if ((fptr->mode & FMODE_TEXTMODE) && (fmode & FMODE_BINMODE)) {
12210 fptr->mode &= ~FMODE_TEXTMODE;
12211 setmode(fptr->fd, O_BINARY);
12212 }
12213#if RUBY_CRLF_ENVIRONMENT
12216 }
12217#endif
12218#endif
12219 fptr->mode |= fmode;
12220#if DEFAULT_TEXTMODE
12221 if ((fptr2->mode & FMODE_TEXTMODE) && (fmode & FMODE_BINMODE)) {
12222 fptr2->mode &= ~FMODE_TEXTMODE;
12223 setmode(fptr2->fd, O_BINARY);
12224 }
12225#endif
12226 fptr2->mode |= fmode;
12227
12228 ret = rb_assoc_new(r, w);
12229 if (rb_block_given_p()) {
12230 VALUE rw[2];
12231 rw[0] = r;
12232 rw[1] = w;
12233 return rb_ensure(rb_yield, ret, pipe_pair_close, (VALUE)rw);
12234 }
12235 return ret;
12236}
12237
12239 int argc;
12240 VALUE *argv;
12241 VALUE io;
12242};
12243
12244static void
12245open_key_args(VALUE klass, int argc, VALUE *argv, VALUE opt, struct foreach_arg *arg)
12246{
12247 VALUE path, v;
12248 VALUE vmode = Qnil, vperm = Qnil;
12249
12250 path = *argv++;
12251 argc--;
12252 FilePathValue(path);
12253 arg->io = 0;
12254 arg->argc = argc;
12255 arg->argv = argv;
12256 if (NIL_P(opt)) {
12257 vmode = INT2NUM(O_RDONLY);
12258 vperm = INT2FIX(0666);
12259 }
12260 else if (!NIL_P(v = rb_hash_aref(opt, sym_open_args))) {
12261 int n;
12262
12263 v = rb_to_array_type(v);
12264 n = RARRAY_LENINT(v);
12265 rb_check_arity(n, 0, 3); /* rb_io_open */
12266 rb_scan_args_kw(RB_SCAN_ARGS_LAST_HASH_KEYWORDS, n, RARRAY_CONST_PTR(v), "02:", &vmode, &vperm, &opt);
12267 }
12268 arg->io = rb_io_open(klass, path, vmode, vperm, opt);
12269}
12270
12271static VALUE
12272io_s_foreach(VALUE v)
12273{
12274 struct getline_arg *arg = (void *)v;
12275 VALUE str;
12276
12277 if (arg->limit == 0)
12278 rb_raise(rb_eArgError, "invalid limit: 0 for foreach");
12279 while (!NIL_P(str = rb_io_getline_1(arg->rs, arg->limit, arg->chomp, arg->io))) {
12280 rb_lastline_set(str);
12281 rb_yield(str);
12282 }
12284 return Qnil;
12285}
12286
12287/*
12288 * call-seq:
12289 * IO.foreach(path, sep = $/, **opts) {|line| block } -> nil
12290 * IO.foreach(path, limit, **opts) {|line| block } -> nil
12291 * IO.foreach(path, sep, limit, **opts) {|line| block } -> nil
12292 * IO.foreach(...) -> an_enumerator
12293 *
12294 * Calls the block with each successive line read from the stream.
12295 *
12296 * The first argument must be a string that is the path to a file.
12297 *
12298 * With only argument +path+ given, parses lines from the file at the given +path+,
12299 * as determined by the default line separator,
12300 * and calls the block with each successive line:
12301 *
12302 * File.foreach('t.txt') {|line| p line }
12303 *
12304 * Output: the same as above.
12305 *
12306 * For both forms, command and path, the remaining arguments are the same.
12307 *
12308 * With argument +sep+ given, parses lines as determined by that line separator
12309 * (see {Line Separator}[rdoc-ref:IO@Line+Separator]):
12310 *
12311 * File.foreach('t.txt', 'li') {|line| p line }
12312 *
12313 * Output:
12314 *
12315 * "First li"
12316 * "ne\nSecond li"
12317 * "ne\n\nThird li"
12318 * "ne\nFourth li"
12319 * "ne\n"
12320 *
12321 * Each paragraph:
12322 *
12323 * File.foreach('t.txt', '') {|paragraph| p paragraph }
12324 *
12325 * Output:
12326 *
12327 * "First line\nSecond line\n\n"
12328 * "Third line\nFourth line\n"
12329 *
12330 * With argument +limit+ given, parses lines as determined by the default
12331 * line separator and the given line-length limit
12332 * (see {Line Separator}[rdoc-ref:IO@Line+Separator] and {Line Limit}[rdoc-ref:IO@Line+Limit]):
12333 *
12334 * File.foreach('t.txt', 7) {|line| p line }
12335 *
12336 * Output:
12337 *
12338 * "First l"
12339 * "ine\n"
12340 * "Second "
12341 * "line\n"
12342 * "\n"
12343 * "Third l"
12344 * "ine\n"
12345 * "Fourth l"
12346 * "line\n"
12347 *
12348 * With arguments +sep+ and +limit+ given,
12349 * combines the two behaviors
12350 * (see {Line Separator and Line Limit}[rdoc-ref:IO@Line+Separator+and+Line+Limit]).
12351 *
12352 * Optional keyword arguments +opts+ specify:
12353 *
12354 * - {Open Options}[rdoc-ref:IO@Open+Options].
12355 * - {Encoding options}[rdoc-ref:encodings.rdoc@Encoding+Options].
12356 * - {Line Input Options}[rdoc-ref:IO@Line+Input+Options].
12357 *
12358 * Returns an Enumerator if no block is given.
12359 *
12360 */
12361
12362static VALUE
12363rb_io_s_foreach(int argc, VALUE *argv, VALUE self)
12364{
12365 VALUE opt;
12366 int orig_argc = argc;
12367 struct foreach_arg arg;
12368 struct getline_arg garg;
12369
12370 argc = rb_scan_args(argc, argv, "12:", NULL, NULL, NULL, &opt);
12371 RETURN_ENUMERATOR(self, orig_argc, argv);
12372 extract_getline_args(argc-1, argv+1, &garg);
12373 open_key_args(self, argc, argv, opt, &arg);
12374 if (NIL_P(arg.io)) return Qnil;
12375 extract_getline_opts(opt, &garg);
12376 check_getline_args(&garg.rs, &garg.limit, garg.io = arg.io);
12377 return rb_ensure(io_s_foreach, (VALUE)&garg, rb_io_close, arg.io);
12378}
12379
12380static VALUE
12381io_s_readlines(VALUE v)
12382{
12383 struct getline_arg *arg = (void *)v;
12384 return io_readlines(arg, arg->io);
12385}
12386
12387/*
12388 * call-seq:
12389 * IO.readlines(path, sep = $/, **opts) -> array
12390 * IO.readlines(path, limit, **opts) -> array
12391 * IO.readlines(path, sep, limit, **opts) -> array
12392 *
12393 * Returns an array of all lines read from the stream.
12394 *
12395 * The first argument must be a string that is the path to a file.
12396 *
12397 * With only argument +path+ given, parses lines from the file at the given +path+,
12398 * as determined by the default line separator,
12399 * and returns those lines in an array:
12400 *
12401 * IO.readlines('t.txt')
12402 * # => ["First line\n", "Second line\n", "\n", "Third line\n", "Fourth line\n"]
12403 *
12404 * With argument +sep+ given, parses lines as determined by that line separator
12405 * (see {Line Separator}[rdoc-ref:IO@Line+Separator]):
12406 *
12407 * # Ordinary separator.
12408 * IO.readlines('t.txt', 'li')
12409 * # =>["First li", "ne\nSecond li", "ne\n\nThird li", "ne\nFourth li", "ne\n"]
12410 * # Get-paragraphs separator.
12411 * IO.readlines('t.txt', '')
12412 * # => ["First line\nSecond line\n\n", "Third line\nFourth line\n"]
12413 * # Get-all separator.
12414 * IO.readlines('t.txt', nil)
12415 * # => ["First line\nSecond line\n\nThird line\nFourth line\n"]
12416 *
12417 * With argument +limit+ given, parses lines as determined by the default
12418 * line separator and the given line-length limit
12419 * (see {Line Separator}[rdoc-ref:IO@Line+Separator] and {Line Limit}[rdoc-ref:IO@Line+Limit]:
12420 *
12421 * IO.readlines('t.txt', 7)
12422 * # => ["First l", "ine\n", "Second ", "line\n", "\n", "Third l", "ine\n", "Fourth ", "line\n"]
12423 *
12424 * With arguments +sep+ and +limit+ given,
12425 * combines the two behaviors
12426 * (see {Line Separator and Line Limit}[rdoc-ref:IO@Line+Separator+and+Line+Limit]).
12427 *
12428 * Optional keyword arguments +opts+ specify:
12429 *
12430 * - {Open Options}[rdoc-ref:IO@Open+Options].
12431 * - {Encoding options}[rdoc-ref:encodings.rdoc@Encoding+Options].
12432 * - {Line Input Options}[rdoc-ref:IO@Line+Input+Options].
12433 *
12434 */
12435
12436static VALUE
12437rb_io_s_readlines(int argc, VALUE *argv, VALUE io)
12438{
12439 VALUE opt;
12440 struct foreach_arg arg;
12441 struct getline_arg garg;
12442
12443 argc = rb_scan_args(argc, argv, "12:", NULL, NULL, NULL, &opt);
12444 extract_getline_args(argc-1, argv+1, &garg);
12445 open_key_args(io, argc, argv, opt, &arg);
12446 if (NIL_P(arg.io)) return Qnil;
12447 extract_getline_opts(opt, &garg);
12448 check_getline_args(&garg.rs, &garg.limit, garg.io = arg.io);
12449 return rb_ensure(io_s_readlines, (VALUE)&garg, rb_io_close, arg.io);
12450}
12451
12452static VALUE
12453io_s_read(VALUE v)
12454{
12455 struct foreach_arg *arg = (void *)v;
12456 return io_read(arg->argc, arg->argv, arg->io);
12457}
12458
12459struct seek_arg {
12460 VALUE io;
12461 VALUE offset;
12462 int mode;
12463};
12464
12465static VALUE
12466seek_before_access(VALUE argp)
12467{
12468 struct seek_arg *arg = (struct seek_arg *)argp;
12469 rb_io_binmode(arg->io);
12470 return rb_io_seek(arg->io, arg->offset, arg->mode);
12471}
12472
12473/*
12474 * call-seq:
12475 * IO.read(path, length = nil, offset = 0, **opts) -> string or nil
12476 *
12477 * Opens the stream, reads and returns some or all of its content,
12478 * and closes the stream; returns +nil+ if no bytes were read.
12479 *
12480 * The first argument must be a string that is the path to a file.
12481 *
12482 * With only argument +path+ given, reads in text mode and returns the entire content
12483 * of the file at the given path:
12484 *
12485 * File.read('t.txt')
12486 * # => "First line\nSecond line\n\nFourth line\nFifth line\n"
12487 * File.read('t.ja')
12488 * # => "こんにちは"
12489 * File.read('t.dat')
12490 * # => "\xFE\xFF\x99\x90\x99\x91\x99\x92\x99\x93\x99\x94"
12491 *
12492 * On Windows, text mode can terminate reading and leave bytes in the file
12493 * unread when encountering certain special bytes. Consider using
12494 * IO.binread if all bytes in the file should be read.
12495 *
12496 * With argument +length+, returns +length+ bytes if available:
12497 *
12498 * File.read('t.txt', 7)
12499 * # => "First l"
12500 * File.read('t.ja', 7)
12501 * # => "\xE3\x81\x93\xE3\x82\x93\xE3"
12502 * File.read('t.dat', 7)
12503 * # => "\xFE\xFF\x99\x90\x99\x91\x99"
12504 *
12505 * Returns all bytes if +length+ is larger than the files size:
12506 *
12507 * File.read('t.txt', 700)
12508 * # => "First line\r\nSecond line\r\n\r\nFourth line\r\nFifth line\r\n"
12509 * File.read('t.ja', 700)
12510 * # => "\xE3\x81\x93\xE3\x82\x93\xE3\x81\xAB\xE3\x81\xA1\xE3\x81\xAF"
12511 * File.read('t.dat', 700)
12512 * # => "\xFE\xFF\x99\x90\x99\x91\x99\x92\x99\x93\x99\x94"
12513 *
12514 * With arguments +length+ and +offset+, returns +length+ bytes
12515 * if available, beginning at the given +offset+:
12516 *
12517 * File.read('t.txt', 10, 2)
12518 * # => "rst line\r\n"
12519 * File.read('t.ja', 10, 2)
12520 * # => "\x93\xE3\x82\x93\xE3\x81\xAB\xE3\x81\xA1"
12521 * File.read('t.dat', 10, 2)
12522 * # => "\x99\x90\x99\x91\x99\x92\x99\x93\x99\x94"
12523 *
12524 * Returns +nil+ if +offset+ is past the end of the stream:
12525 *
12526 * File.read('t.txt', 10, 200)
12527 * # => nil
12528 *
12529 * Optional keyword arguments +opts+ specify:
12530 *
12531 * - {Open Options}[rdoc-ref:IO@Open+Options].
12532 * - {Encoding options}[rdoc-ref:encodings.rdoc@Encoding+Options].
12533 *
12534 */
12535
12536static VALUE
12537rb_io_s_read(int argc, VALUE *argv, VALUE io)
12538{
12539 VALUE opt, offset;
12540 rb_len_t off;
12541 struct foreach_arg arg;
12542
12543 argc = rb_scan_args(argc, argv, "13:", NULL, NULL, &offset, NULL, &opt);
12544 if (!NIL_P(offset) && (off = NUM2LEN(offset)) < 0) {
12545 rb_raise(rb_eArgError, "negative offset %"PRIdLEN" given", off);
12546 }
12547 open_key_args(io, argc, argv, opt, &arg);
12548 if (NIL_P(arg.io)) return Qnil;
12549 if (!NIL_P(offset)) {
12550 struct seek_arg sarg;
12551 int state = 0;
12552 sarg.io = arg.io;
12553 sarg.offset = offset;
12554 sarg.mode = SEEK_SET;
12555 rb_protect(seek_before_access, (VALUE)&sarg, &state);
12556 if (state) {
12557 rb_io_close(arg.io);
12558 rb_jump_tag(state);
12559 }
12560 if (arg.argc == 2) arg.argc = 1;
12561 }
12562 return rb_ensure(io_s_read, (VALUE)&arg, rb_io_close, arg.io);
12563}
12564
12565/*
12566 * call-seq:
12567 * IO.binread(path, length = nil, offset = 0) -> string or nil
12568 *
12569 * Behaves like IO.read, except that the stream is opened in binary mode
12570 * with ASCII-8BIT encoding.
12571 *
12572 */
12573
12574static VALUE
12575rb_io_s_binread(int argc, VALUE *argv, VALUE io)
12576{
12577 VALUE offset;
12578 struct foreach_arg arg;
12579 enum rb_io_mode fmode = FMODE_READABLE|FMODE_BINMODE;
12580 enum {
12581 oflags = O_RDONLY
12582#ifdef O_BINARY
12583 |O_BINARY
12584#endif
12585 };
12586 struct rb_io_encoding convconfig = {NULL, NULL, 0, Qnil};
12587
12588 rb_scan_args(argc, argv, "12", NULL, NULL, &offset);
12589 FilePathValue(argv[0]);
12590 convconfig.enc = rb_ascii8bit_encoding();
12591 arg.io = rb_io_open_generic(io, argv[0], oflags, fmode, &convconfig, 0);
12592 if (NIL_P(arg.io)) return Qnil;
12593 arg.argv = argv+1;
12594 arg.argc = (argc > 1) ? 1 : 0;
12595 if (!NIL_P(offset)) {
12596 struct seek_arg sarg;
12597 int state = 0;
12598 sarg.io = arg.io;
12599 sarg.offset = offset;
12600 sarg.mode = SEEK_SET;
12601 rb_protect(seek_before_access, (VALUE)&sarg, &state);
12602 if (state) {
12603 rb_io_close(arg.io);
12604 rb_jump_tag(state);
12605 }
12606 }
12607 return rb_ensure(io_s_read, (VALUE)&arg, rb_io_close, arg.io);
12608}
12609
12610static VALUE
12611io_s_write0(VALUE v)
12612{
12613 struct write_arg *arg = (void *)v;
12614 return io_write(arg->io,arg->str,arg->nosync);
12615}
12616
12617static VALUE
12618io_s_write(int argc, VALUE *argv, VALUE klass, int binary)
12619{
12620 VALUE string, offset, opt;
12621 struct foreach_arg arg;
12622 struct write_arg warg;
12623
12624 rb_scan_args(argc, argv, "21:", NULL, &string, &offset, &opt);
12625
12626 if (NIL_P(opt)) opt = rb_hash_new();
12627 else opt = rb_hash_dup(opt);
12628
12629
12630 if (NIL_P(rb_hash_aref(opt,sym_mode))) {
12631 int mode = O_WRONLY|O_CREAT;
12632#ifdef O_BINARY
12633 if (binary) mode |= O_BINARY;
12634#endif
12635 if (NIL_P(offset)) mode |= O_TRUNC;
12636 rb_hash_aset(opt,sym_mode,INT2NUM(mode));
12637 }
12638 open_key_args(klass, argc, argv, opt, &arg);
12639
12640#ifndef O_BINARY
12641 if (binary) rb_io_binmode_m(arg.io);
12642#endif
12643
12644 if (NIL_P(arg.io)) return Qnil;
12645 if (!NIL_P(offset)) {
12646 struct seek_arg sarg;
12647 int state = 0;
12648 sarg.io = arg.io;
12649 sarg.offset = offset;
12650 sarg.mode = SEEK_SET;
12651 rb_protect(seek_before_access, (VALUE)&sarg, &state);
12652 if (state) {
12653 rb_io_close(arg.io);
12654 rb_jump_tag(state);
12655 }
12656 }
12657
12658 warg.io = arg.io;
12659 warg.str = string;
12660 warg.nosync = 0;
12661
12662 return rb_ensure(io_s_write0, (VALUE)&warg, rb_io_close, arg.io);
12663}
12664
12665/*
12666 * call-seq:
12667 * IO.write(path, data, offset = 0, **opts) -> nonnegative_integer
12668 *
12669 * Opens the stream, writes the given +data+ to it,
12670 * and closes the stream; returns the number of bytes written.
12671 *
12672 * The first argument must be a string that is the path to a file.
12673 *
12674 * With only arguments +path+ and +data+ given,
12675 * writes the given data to the file at that path:
12676 *
12677 * path = 't.tmp'
12678 * File.write(path, "First line\nSecond line\n\nFourth line\nFifth line\n") # => 47
12679 * File.write(path, 'こんにちは') # => 15
12680 * File.write(path, "\xFE\xFF\x99\x90\x99\x91\x99\x92\x99\x93\x99\x94") # => 12
12681 *
12682 * When +offset+ is zero (the default), the entire file content is overwritten:
12683 *
12684 * File.read(path) # => "\xFE\xFF\x99\x90\x99\x91\x99\x92\x99\x93\x99\x94"
12685 * File.write(path, 'foo')
12686 * File.read(path) # => "foo"
12687 *
12688 * When +offset+ in within the file content, the file content is partly overwritten,
12689 * beginning at byte +offset+:
12690 *
12691 * File.write(path, "First line\nSecond line\n\nFourth line\nFifth line\n")
12692 * File.write(path, 'LINE', 6)
12693 * File.read(path) # => "First LINE\nSecond line\n\nFourth line\nFifth line\n"
12694 *
12695 * When the file contains multi-byte characters,
12696 * the effect of writing may disturb some characters:
12697 *
12698 * File.write(path, "こんにちは")
12699 * File.write(path, 'FOO', 3) # Replace one 3-byte character.
12700 * File.read(path) # => "こFOOにちは"
12701 * File.write(path, 'BAR', 7) # Replace bytes in two different 3-byte characters.
12702 * File.read(path) # => "こFOO\xE3BAR\x81\xA1は"
12703 *
12704 * If +offset+ is outside the file content,
12705 * the file is padded with null characters <tt>"\u0000"</tt>:
12706 *
12707 * File.write(path, "First line\nSecond line\n\nFourth line\nFifth line\n")
12708 * File.write(path, 'FOO', 55)
12709 * File.read(path)
12710 * # => "First line\nSecond line\n\nFourth line\nFifth line\n\u0000\u0000\u0000FOO"
12711 *
12712 * Optional keyword arguments +opts+ specify:
12713 *
12714 * - {Open Options}[rdoc-ref:IO@Open+Options].
12715 * - {Encoding options}[rdoc-ref:encodings.rdoc@Encoding+Options].
12716 *
12717 */
12718
12719static VALUE
12720rb_io_s_write(int argc, VALUE *argv, VALUE io)
12721{
12722 return io_s_write(argc, argv, io, 0);
12723}
12724
12725/*
12726 * call-seq:
12727 * IO.binwrite(path, string, offset = 0, **opts) -> integer
12728 *
12729 * Behaves like IO.write, except that the stream is opened in binary mode
12730 * with ASCII-8BIT encoding.
12731 *
12732 */
12733
12734static VALUE
12735rb_io_s_binwrite(int argc, VALUE *argv, VALUE io)
12736{
12737 return io_s_write(argc, argv, io, 1);
12738}
12739
12741 VALUE src;
12742 VALUE dst;
12743 rb_off_t copy_length; /* (rb_off_t)-1 if not specified */
12744 rb_off_t src_offset; /* (rb_off_t)-1 if not specified */
12745
12746 rb_io_t *src_fptr;
12747 rb_io_t *dst_fptr;
12748 unsigned close_src : 1;
12749 unsigned close_dst : 1;
12750 int error_no;
12751 rb_off_t total;
12752 const char *syserr;
12753 const char *notimp;
12754 VALUE th;
12755 struct stat src_stat;
12756 struct stat dst_stat;
12757#ifdef HAVE_FCOPYFILE
12758 copyfile_state_t copyfile_state;
12759#endif
12760};
12761
12762static void *
12763exec_interrupts(void *arg)
12764{
12765 VALUE th = (VALUE)arg;
12766 rb_thread_execute_interrupts(th);
12767 return NULL;
12768}
12769
12770/*
12771 * returns TRUE if the preceding system call was interrupted
12772 * so we can continue. If the thread was interrupted, we
12773 * reacquire the GVL to execute interrupts before continuing.
12774 */
12775static int
12776maygvl_copy_stream_continue_p(int has_gvl, struct copy_stream_struct *stp)
12777{
12778 switch (errno) {
12779 case EINTR:
12780#if defined(ERESTART)
12781 case ERESTART:
12782#endif
12783 if (rb_thread_interrupted(stp->th)) {
12784 if (has_gvl)
12785 rb_thread_execute_interrupts(stp->th);
12786 else
12787 rb_thread_call_with_gvl(exec_interrupts, (void *)stp->th);
12788 }
12789 return TRUE;
12790 }
12791 return FALSE;
12792}
12793
12795 VALUE scheduler;
12796
12797 rb_io_t *fptr;
12798 short events;
12799
12800 VALUE result;
12801};
12802
12803static void *
12804fiber_scheduler_wait_for(void * _arguments)
12805{
12806 struct fiber_scheduler_wait_for_arguments *arguments = (struct fiber_scheduler_wait_for_arguments *)_arguments;
12807
12808 arguments->result = rb_fiber_scheduler_io_wait(arguments->scheduler, arguments->fptr->self, INT2NUM(arguments->events), RUBY_IO_TIMEOUT_DEFAULT);
12809
12810 return NULL;
12811}
12812
12813#if USE_POLL
12814# define IOWAIT_SYSCALL "poll"
12815STATIC_ASSERT(pollin_expected, POLLIN == RB_WAITFD_IN);
12816STATIC_ASSERT(pollout_expected, POLLOUT == RB_WAITFD_OUT);
12817static int
12818nogvl_wait_for(VALUE th, rb_io_t *fptr, short events, struct timeval *timeout)
12819{
12821 if (scheduler != Qnil) {
12822 struct fiber_scheduler_wait_for_arguments args = {.scheduler = scheduler, .fptr = fptr, .events = events};
12823 rb_thread_call_with_gvl(fiber_scheduler_wait_for, &args);
12824 return RTEST(args.result);
12825 }
12826
12827 int fd = fptr->fd;
12828 if (fd == -1) return 0;
12829
12830 struct pollfd fds;
12831
12832 fds.fd = fd;
12833 fds.events = events;
12834
12835 int timeout_milliseconds = -1;
12836
12837 if (timeout) {
12838 timeout_milliseconds = (int)(timeout->tv_sec * 1000) + (int)(timeout->tv_usec / 1000);
12839 }
12840
12841 return poll(&fds, 1, timeout_milliseconds);
12842}
12843#else /* !USE_POLL */
12844# define IOWAIT_SYSCALL "select"
12845static int
12846nogvl_wait_for(VALUE th, rb_io_t *fptr, short events, struct timeval *timeout)
12847{
12849 if (scheduler != Qnil) {
12850 struct fiber_scheduler_wait_for_arguments args = {.scheduler = scheduler, .fptr = fptr, .events = events};
12851 rb_thread_call_with_gvl(fiber_scheduler_wait_for, &args);
12852 return RTEST(args.result);
12853 }
12854
12855 int fd = fptr->fd;
12856
12857 if (fd == -1) {
12858 errno = EBADF;
12859 return -1;
12860 }
12861
12862 rb_fdset_t fds;
12863 int ret;
12864
12865 rb_fd_init(&fds);
12866 rb_fd_set(fd, &fds);
12867
12868 switch (events) {
12869 case RB_WAITFD_IN:
12870 ret = rb_fd_select(fd + 1, &fds, 0, 0, timeout);
12871 break;
12872 case RB_WAITFD_OUT:
12873 ret = rb_fd_select(fd + 1, 0, &fds, 0, timeout);
12874 break;
12875 default:
12876 VM_UNREACHABLE(nogvl_wait_for);
12877 }
12878
12879 rb_fd_term(&fds);
12880
12881 // On timeout, this returns 0.
12882 return ret;
12883}
12884#endif /* !USE_POLL */
12885
12886static int
12887maygvl_copy_stream_wait_read(int has_gvl, struct copy_stream_struct *stp)
12888{
12889 int ret;
12890
12891 do {
12892 if (has_gvl) {
12894 }
12895 else {
12896 ret = nogvl_wait_for(stp->th, stp->src_fptr, RB_WAITFD_IN, NULL);
12897 }
12898 } while (ret < 0 && maygvl_copy_stream_continue_p(has_gvl, stp));
12899
12900 if (ret < 0) {
12901 stp->syserr = IOWAIT_SYSCALL;
12902 stp->error_no = errno;
12903 return ret;
12904 }
12905 return 0;
12906}
12907
12908static int
12909nogvl_copy_stream_wait_write(struct copy_stream_struct *stp)
12910{
12911 int ret;
12912
12913 do {
12914 ret = nogvl_wait_for(stp->th, stp->dst_fptr, RB_WAITFD_OUT, NULL);
12915 } while (ret < 0 && maygvl_copy_stream_continue_p(0, stp));
12916
12917 if (ret < 0) {
12918 stp->syserr = IOWAIT_SYSCALL;
12919 stp->error_no = errno;
12920 return ret;
12921 }
12922 return 0;
12923}
12924
12925#ifdef USE_COPY_FILE_RANGE
12926
12927static ssize_t
12928simple_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)
12929{
12930#ifdef HAVE_COPY_FILE_RANGE
12931 return copy_file_range(in_fd, in_offset, out_fd, out_offset, count, flags);
12932#else
12933 return syscall(__NR_copy_file_range, in_fd, in_offset, out_fd, out_offset, count, flags);
12934#endif
12935}
12936
12937static int
12938nogvl_copy_file_range(struct copy_stream_struct *stp)
12939{
12940 ssize_t ss;
12941 rb_off_t src_size;
12942 rb_off_t copy_length, src_offset, *src_offset_ptr;
12943
12944 if (!S_ISREG(stp->src_stat.st_mode))
12945 return 0;
12946
12947 src_size = stp->src_stat.st_size;
12948 src_offset = stp->src_offset;
12949 if (src_offset >= (rb_off_t)0) {
12950 src_offset_ptr = &src_offset;
12951 }
12952 else {
12953 src_offset_ptr = NULL; /* if src_offset_ptr is NULL, then bytes are read from in_fd starting from the file offset */
12954 }
12955
12956 copy_length = stp->copy_length;
12957 if (copy_length < (rb_off_t)0) {
12958 if (src_offset < (rb_off_t)0) {
12959 rb_off_t current_offset;
12960 errno = 0;
12961 current_offset = lseek(stp->src_fptr->fd, 0, SEEK_CUR);
12962 if (current_offset < (rb_off_t)0 && errno) {
12963 stp->syserr = "lseek";
12964 stp->error_no = errno;
12965 return (int)current_offset;
12966 }
12967 copy_length = src_size - current_offset;
12968 }
12969 else {
12970 copy_length = src_size - src_offset;
12971 }
12972 }
12973
12974 retry_copy_file_range:
12975# if SIZEOF_OFF_T > SIZEOF_SIZE_T
12976 /* we are limited by the 32-bit ssize_t return value on 32-bit */
12977 ss = (copy_length > (rb_off_t)SSIZE_MAX) ? SSIZE_MAX : (ssize_t)copy_length;
12978# else
12979 ss = (ssize_t)copy_length;
12980# endif
12981 ss = simple_copy_file_range(stp->src_fptr->fd, src_offset_ptr, stp->dst_fptr->fd, NULL, ss, 0);
12982 if (0 < ss) {
12983 stp->total += ss;
12984 copy_length -= ss;
12985 if (0 < copy_length) {
12986 goto retry_copy_file_range;
12987 }
12988 }
12989 if (ss < 0) {
12990 if (maygvl_copy_stream_continue_p(0, stp)) {
12991 goto retry_copy_file_range;
12992 }
12993 switch (errno) {
12994 case EINVAL:
12995 case EPERM: /* copy_file_range(2) doesn't exist (may happen in
12996 docker container) */
12997#ifdef ENOSYS
12998 case ENOSYS:
12999#endif
13000#ifdef EXDEV
13001 case EXDEV: /* in_fd and out_fd are not on the same filesystem */
13002#endif
13003 return 0;
13004 case EAGAIN:
13005#if EWOULDBLOCK != EAGAIN
13006 case EWOULDBLOCK:
13007#endif
13008 {
13009 int ret = nogvl_copy_stream_wait_write(stp);
13010 if (ret < 0) return ret;
13011 }
13012 goto retry_copy_file_range;
13013 case EBADF:
13014 {
13015 int e = errno;
13016 int flags = fcntl(stp->dst_fptr->fd, F_GETFL);
13017
13018 if (flags != -1 && flags & O_APPEND) {
13019 return 0;
13020 }
13021 errno = e;
13022 }
13023 }
13024 stp->syserr = "copy_file_range";
13025 stp->error_no = errno;
13026 return (int)ss;
13027 }
13028 return 1;
13029}
13030#endif
13031
13032#ifdef HAVE_FCOPYFILE
13033static int
13034nogvl_fcopyfile(struct copy_stream_struct *stp)
13035{
13036 rb_off_t cur, ss = 0;
13037 const rb_off_t src_offset = stp->src_offset;
13038 int ret;
13039
13040 if (stp->copy_length >= (rb_off_t)0) {
13041 /* copy_length can't be specified in fcopyfile(3) */
13042 return 0;
13043 }
13044
13045 if (!S_ISREG(stp->src_stat.st_mode))
13046 return 0;
13047
13048 if (!S_ISREG(stp->dst_stat.st_mode))
13049 return 0;
13050 if (lseek(stp->dst_fptr->fd, 0, SEEK_CUR) > (rb_off_t)0) /* if dst IO was already written */
13051 return 0;
13052 if (fcntl(stp->dst_fptr->fd, F_GETFL) & O_APPEND) {
13053 /* fcopyfile(3) appends src IO to dst IO and then truncates
13054 * dst IO to src IO's original size. */
13055 rb_off_t end = lseek(stp->dst_fptr->fd, 0, SEEK_END);
13056 lseek(stp->dst_fptr->fd, 0, SEEK_SET);
13057 if (end > (rb_off_t)0) return 0;
13058 }
13059
13060 if (src_offset > (rb_off_t)0) {
13061 rb_off_t r;
13062
13063 /* get current offset */
13064 errno = 0;
13065 cur = lseek(stp->src_fptr->fd, 0, SEEK_CUR);
13066 if (cur < (rb_off_t)0 && errno) {
13067 stp->error_no = errno;
13068 return 1;
13069 }
13070
13071 errno = 0;
13072 r = lseek(stp->src_fptr->fd, src_offset, SEEK_SET);
13073 if (r < (rb_off_t)0 && errno) {
13074 stp->error_no = errno;
13075 return 1;
13076 }
13077 }
13078
13079 stp->copyfile_state = copyfile_state_alloc(); /* this will be freed by copy_stream_finalize() */
13080 ret = fcopyfile(stp->src_fptr->fd, stp->dst_fptr->fd, stp->copyfile_state, COPYFILE_DATA);
13081 copyfile_state_get(stp->copyfile_state, COPYFILE_STATE_COPIED, &ss); /* get copied bytes */
13082
13083 if (ret == 0) { /* success */
13084 stp->total = ss;
13085 if (src_offset > (rb_off_t)0) {
13086 rb_off_t r;
13087 errno = 0;
13088 /* reset offset */
13089 r = lseek(stp->src_fptr->fd, cur, SEEK_SET);
13090 if (r < (rb_off_t)0 && errno) {
13091 stp->error_no = errno;
13092 return 1;
13093 }
13094 }
13095 }
13096 else {
13097 switch (errno) {
13098 case ENOTSUP:
13099 case EPERM:
13100 case EINVAL:
13101 return 0;
13102 }
13103 stp->syserr = "fcopyfile";
13104 stp->error_no = errno;
13105 return (int)ret;
13106 }
13107 return 1;
13108}
13109#endif
13110
13111#ifdef HAVE_SENDFILE
13112
13113# ifdef __linux__
13114# define USE_SENDFILE
13115
13116# ifdef HAVE_SYS_SENDFILE_H
13117# include <sys/sendfile.h>
13118# endif
13119
13120static ssize_t
13121simple_sendfile(int out_fd, int in_fd, rb_off_t *offset, rb_off_t count)
13122{
13123 return sendfile(out_fd, in_fd, offset, (size_t)count);
13124}
13125
13126# elif 0 /* defined(__FreeBSD__) || defined(__DragonFly__) */ || defined(__APPLE__)
13127/* This runs on FreeBSD8.1 r30210, but sendfiles blocks its execution
13128 * without cpuset -l 0.
13129 */
13130# define USE_SENDFILE
13131
13132static ssize_t
13133simple_sendfile(int out_fd, int in_fd, rb_off_t *offset, rb_off_t count)
13134{
13135 int r;
13136 rb_off_t pos = offset ? *offset : lseek(in_fd, 0, SEEK_CUR);
13137 rb_off_t sbytes;
13138# ifdef __APPLE__
13139 r = sendfile(in_fd, out_fd, pos, &count, NULL, 0);
13140 sbytes = count;
13141# else
13142 r = sendfile(in_fd, out_fd, pos, (size_t)count, NULL, &sbytes, 0);
13143# endif
13144 if (r != 0 && sbytes == 0) return r;
13145 if (offset) {
13146 *offset += sbytes;
13147 }
13148 else {
13149 lseek(in_fd, sbytes, SEEK_CUR);
13150 }
13151 return (ssize_t)sbytes;
13152}
13153
13154# endif
13155
13156#endif
13157
13158#ifdef USE_SENDFILE
13159static int
13160nogvl_copy_stream_sendfile(struct copy_stream_struct *stp)
13161{
13162 ssize_t ss;
13163 rb_off_t src_size;
13164 rb_off_t copy_length;
13165 rb_off_t src_offset;
13166 int use_pread;
13167
13168 if (!S_ISREG(stp->src_stat.st_mode))
13169 return 0;
13170
13171 src_size = stp->src_stat.st_size;
13172#ifndef __linux__
13173 if ((stp->dst_stat.st_mode & S_IFMT) != S_IFSOCK)
13174 return 0;
13175#endif
13176
13177 src_offset = stp->src_offset;
13178 use_pread = src_offset >= (rb_off_t)0;
13179
13180 copy_length = stp->copy_length;
13181 if (copy_length < (rb_off_t)0) {
13182 if (use_pread)
13183 copy_length = src_size - src_offset;
13184 else {
13185 rb_off_t cur;
13186 errno = 0;
13187 cur = lseek(stp->src_fptr->fd, 0, SEEK_CUR);
13188 if (cur < (rb_off_t)0 && errno) {
13189 stp->syserr = "lseek";
13190 stp->error_no = errno;
13191 return (int)cur;
13192 }
13193 copy_length = src_size - cur;
13194 }
13195 }
13196
13197 retry_sendfile:
13198# if SIZEOF_OFF_T > SIZEOF_SIZE_T
13199 /* we are limited by the 32-bit ssize_t return value on 32-bit */
13200 ss = (copy_length > (rb_off_t)SSIZE_MAX) ? SSIZE_MAX : (ssize_t)copy_length;
13201# else
13202 ss = (ssize_t)copy_length;
13203# endif
13204 if (use_pread) {
13205 ss = simple_sendfile(stp->dst_fptr->fd, stp->src_fptr->fd, &src_offset, ss);
13206 }
13207 else {
13208 ss = simple_sendfile(stp->dst_fptr->fd, stp->src_fptr->fd, NULL, ss);
13209 }
13210 if (0 < ss) {
13211 stp->total += ss;
13212 copy_length -= ss;
13213 if (0 < copy_length) {
13214 goto retry_sendfile;
13215 }
13216 }
13217 if (ss < 0) {
13218 if (maygvl_copy_stream_continue_p(0, stp))
13219 goto retry_sendfile;
13220 switch (errno) {
13221 case EINVAL:
13222#ifdef ENOSYS
13223 case ENOSYS:
13224#endif
13225#ifdef EOPNOTSUP
13226 /* some RedHat kernels may return EOPNOTSUP on an NFS mount.
13227 see also: [Feature #16965] */
13228 case EOPNOTSUP:
13229#endif
13230 return 0;
13231 case EAGAIN:
13232#if EWOULDBLOCK != EAGAIN
13233 case EWOULDBLOCK:
13234#endif
13235 {
13236 int ret;
13237#ifndef __linux__
13238 /*
13239 * Linux requires stp->src_fptr->fd to be a mmap-able (regular) file,
13240 * select() reports regular files to always be "ready", so
13241 * there is no need to select() on it.
13242 * Other OSes may have the same limitation for sendfile() which
13243 * allow us to bypass maygvl_copy_stream_wait_read()...
13244 */
13245 ret = maygvl_copy_stream_wait_read(0, stp);
13246 if (ret < 0) return ret;
13247#endif
13248 ret = nogvl_copy_stream_wait_write(stp);
13249 if (ret < 0) return ret;
13250 }
13251 goto retry_sendfile;
13252 }
13253 stp->syserr = "sendfile";
13254 stp->error_no = errno;
13255 return (int)ss;
13256 }
13257 return 1;
13258}
13259#endif
13260
13261static ssize_t
13262maygvl_read(int has_gvl, rb_io_t *fptr, void *buf, size_t count)
13263{
13264 if (has_gvl)
13265 return rb_io_read_memory(fptr, buf, count);
13266 else
13267 return read(fptr->fd, buf, count);
13268}
13269
13270static ssize_t
13271maygvl_copy_stream_read(int has_gvl, struct copy_stream_struct *stp, char *buf, size_t len, rb_off_t offset)
13272{
13273 ssize_t ss;
13274 retry_read:
13275 if (offset < (rb_off_t)0) {
13276 ss = maygvl_read(has_gvl, stp->src_fptr, buf, len);
13277 }
13278 else {
13279 ss = pread(stp->src_fptr->fd, buf, len, offset);
13280 }
13281 if (ss == 0) {
13282 return 0;
13283 }
13284 if (ss < 0) {
13285 if (maygvl_copy_stream_continue_p(has_gvl, stp))
13286 goto retry_read;
13287 switch (errno) {
13288 case EAGAIN:
13289#if EWOULDBLOCK != EAGAIN
13290 case EWOULDBLOCK:
13291#endif
13292 {
13293 int ret = maygvl_copy_stream_wait_read(has_gvl, stp);
13294 if (ret < 0) return ret;
13295 }
13296 goto retry_read;
13297#ifdef ENOSYS
13298 case ENOSYS:
13299 stp->notimp = "pread";
13300 return ss;
13301#endif
13302 }
13303 stp->syserr = offset < (rb_off_t)0 ? "read" : "pread";
13304 stp->error_no = errno;
13305 }
13306 return ss;
13307}
13308
13309static int
13310nogvl_copy_stream_write(struct copy_stream_struct *stp, char *buf, size_t len)
13311{
13312 ssize_t ss;
13313 int off = 0;
13314 while (len) {
13315 ss = write(stp->dst_fptr->fd, buf+off, len);
13316 if (ss < 0) {
13317 if (maygvl_copy_stream_continue_p(0, stp))
13318 continue;
13319 if (io_again_p(errno)) {
13320 int ret = nogvl_copy_stream_wait_write(stp);
13321 if (ret < 0) return ret;
13322 continue;
13323 }
13324 stp->syserr = "write";
13325 stp->error_no = errno;
13326 return (int)ss;
13327 }
13328 off += (int)ss;
13329 len -= (int)ss;
13330 stp->total += ss;
13331 }
13332 return 0;
13333}
13334
13335static void
13336nogvl_copy_stream_read_write(struct copy_stream_struct *stp)
13337{
13338 char buf[1024*16];
13339 size_t len;
13340 ssize_t ss;
13341 int ret;
13342 rb_off_t copy_length;
13343 rb_off_t src_offset;
13344 int use_eof;
13345 int use_pread;
13346
13347 copy_length = stp->copy_length;
13348 use_eof = copy_length < (rb_off_t)0;
13349 src_offset = stp->src_offset;
13350 use_pread = src_offset >= (rb_off_t)0;
13351
13352 if (use_pread && stp->close_src) {
13353 rb_off_t r;
13354 errno = 0;
13355 r = lseek(stp->src_fptr->fd, src_offset, SEEK_SET);
13356 if (r < (rb_off_t)0 && errno) {
13357 stp->syserr = "lseek";
13358 stp->error_no = errno;
13359 return;
13360 }
13361 src_offset = (rb_off_t)-1;
13362 use_pread = 0;
13363 }
13364
13365 while (use_eof || 0 < copy_length) {
13366 if (!use_eof && copy_length < (rb_off_t)sizeof(buf)) {
13367 len = (size_t)copy_length;
13368 }
13369 else {
13370 len = sizeof(buf);
13371 }
13372 if (use_pread) {
13373 ss = maygvl_copy_stream_read(0, stp, buf, len, src_offset);
13374 if (0 < ss)
13375 src_offset += ss;
13376 }
13377 else {
13378 ss = maygvl_copy_stream_read(0, stp, buf, len, (rb_off_t)-1);
13379 }
13380 if (ss <= 0) /* EOF or error */
13381 return;
13382
13383 ret = nogvl_copy_stream_write(stp, buf, ss);
13384 if (ret < 0)
13385 return;
13386
13387 if (!use_eof)
13388 copy_length -= ss;
13389 }
13390}
13391
13392static void *
13393nogvl_copy_stream_func(void *arg)
13394{
13395 struct copy_stream_struct *stp = (struct copy_stream_struct *)arg;
13396#if defined(USE_SENDFILE) || defined(USE_COPY_FILE_RANGE) || defined(HAVE_FCOPYFILE)
13397 int ret;
13398#endif
13399
13400#ifdef USE_COPY_FILE_RANGE
13401 ret = nogvl_copy_file_range(stp);
13402 if (ret != 0)
13403 goto finish; /* error or success */
13404#endif
13405
13406#ifdef HAVE_FCOPYFILE
13407 ret = nogvl_fcopyfile(stp);
13408 if (ret != 0)
13409 goto finish; /* error or success */
13410#endif
13411
13412#ifdef USE_SENDFILE
13413 ret = nogvl_copy_stream_sendfile(stp);
13414 if (ret != 0)
13415 goto finish; /* error or success */
13416#endif
13417
13418 nogvl_copy_stream_read_write(stp);
13419
13420#if defined(USE_SENDFILE) || defined(USE_COPY_FILE_RANGE) || defined(HAVE_FCOPYFILE)
13421 finish:
13422#endif
13423 return 0;
13424}
13425
13427 struct copy_stream_struct *stp;
13428 VALUE buf;
13429 rb_len_t len;
13430 rb_off_t offset;
13431};
13432
13433static VALUE
13434copy_stream_fallback_read(VALUE arg)
13435{
13436 struct copy_stream_fallback_read_arg *p = (void *)arg;
13437 return (VALUE)maygvl_copy_stream_read(1, p->stp, RSTRING_PTR(p->buf),
13438 p->len, p->offset);
13439}
13440
13441static VALUE
13442copy_stream_fallback_body(VALUE arg)
13443{
13444 struct copy_stream_struct *stp = (struct copy_stream_struct *)arg;
13445 const int buflen = 16*1024;
13446 VALUE n;
13447 VALUE buf = rb_str_buf_new(buflen);
13448 rb_off_t rest = stp->copy_length;
13449 rb_off_t off = stp->src_offset;
13450 ID read_method = id_readpartial;
13451
13452 if (!stp->src_fptr) {
13453 if (!rb_respond_to(stp->src, read_method)) {
13454 read_method = id_read;
13455 }
13456 }
13457
13458 while (1) {
13459 rb_len_t numwrote;
13460 rb_len_t l;
13461 rb_str_make_independent(buf);
13462 if (stp->copy_length < (rb_off_t)0) {
13463 l = buflen;
13464 }
13465 else {
13466 if (rest == 0) {
13467 rb_str_resize(buf, 0);
13468 break;
13469 }
13470 l = buflen < rest ? buflen : (rb_len_t)rest;
13471 }
13472 if (!stp->src_fptr) {
13473 VALUE rc = rb_funcall(stp->src, read_method, 2, INT2FIX(l), buf);
13474
13475 if (read_method == id_read && NIL_P(rc))
13476 break;
13477 }
13478 else {
13479 rb_str_resize(buf, buflen);
13480 struct copy_stream_fallback_read_arg read_arg = {stp, buf, l, off};
13481 ssize_t ss =
13482 (ssize_t)rb_str_locktmp_ensure(buf, copy_stream_fallback_read,
13483 (VALUE)&read_arg);
13484 rb_str_resize(buf, ss > 0 ? ss : 0);
13485 if (ss < 0)
13486 return Qnil;
13487 if (ss == 0)
13488 rb_eof_error();
13489 if (off >= (rb_off_t)0)
13490 off += ss;
13491 }
13492 n = rb_io_write(stp->dst, buf);
13493 numwrote = NUM2LEN(n);
13494 stp->total += numwrote;
13495 rest -= numwrote;
13496 if (read_method == id_read && RSTRING_LEN(buf) == 0) {
13497 break;
13498 }
13499 }
13500
13501 return Qnil;
13502}
13503
13504static VALUE
13505copy_stream_fallback(struct copy_stream_struct *stp)
13506{
13507 if (!stp->src_fptr && stp->src_offset >= (rb_off_t)0) {
13508 rb_raise(rb_eArgError, "cannot specify src_offset for non-IO");
13509 }
13510 rb_rescue2(copy_stream_fallback_body, (VALUE)stp,
13511 (VALUE (*) (VALUE, VALUE))0, (VALUE)0,
13512 rb_eEOFError, (VALUE)0);
13513 return Qnil;
13514}
13515
13516static VALUE
13517copy_stream_body(VALUE arg)
13518{
13519 struct copy_stream_struct *stp = (struct copy_stream_struct *)arg;
13520 VALUE src_io = stp->src, dst_io = stp->dst;
13521 const int common_oflags = 0
13522#ifdef O_NOCTTY
13523 | O_NOCTTY
13524#endif
13525 ;
13526
13527 stp->th = rb_thread_current();
13528
13529 stp->total = 0;
13530
13531 if (src_io == argf ||
13532 !(RB_TYPE_P(src_io, T_FILE) ||
13533 RB_TYPE_P(src_io, T_STRING) ||
13534 rb_respond_to(src_io, rb_intern("to_path")))) {
13535 stp->src_fptr = NULL;
13536 }
13537 else {
13538 int stat_ret;
13539 VALUE tmp_io = rb_io_check_io(src_io);
13540 if (!NIL_P(tmp_io)) {
13541 src_io = tmp_io;
13542 }
13543 else if (!RB_TYPE_P(src_io, T_FILE)) {
13544 VALUE args[2];
13545 FilePathValue(src_io);
13546 args[0] = src_io;
13547 args[1] = INT2NUM(O_RDONLY|common_oflags);
13548 src_io = rb_class_new_instance(2, args, rb_cFile);
13549 stp->src = src_io;
13550 stp->close_src = 1;
13551 }
13552 RB_IO_POINTER(src_io, stp->src_fptr);
13553 rb_io_check_byte_readable(stp->src_fptr);
13554
13555 stat_ret = fstat(stp->src_fptr->fd, &stp->src_stat);
13556 if (stat_ret < 0) {
13557 stp->syserr = "fstat";
13558 stp->error_no = errno;
13559 return Qnil;
13560 }
13561 }
13562
13563 if (dst_io == argf ||
13564 !(RB_TYPE_P(dst_io, T_FILE) ||
13565 RB_TYPE_P(dst_io, T_STRING) ||
13566 rb_respond_to(dst_io, rb_intern("to_path")))) {
13567 stp->dst_fptr = NULL;
13568 }
13569 else {
13570 int stat_ret;
13571 VALUE tmp_io = rb_io_check_io(dst_io);
13572 if (!NIL_P(tmp_io)) {
13573 dst_io = GetWriteIO(tmp_io);
13574 }
13575 else if (!RB_TYPE_P(dst_io, T_FILE)) {
13576 VALUE args[3];
13577 FilePathValue(dst_io);
13578 args[0] = dst_io;
13579 args[1] = INT2NUM(O_WRONLY|O_CREAT|O_TRUNC|common_oflags);
13580 args[2] = INT2FIX(0666);
13581 dst_io = rb_class_new_instance(3, args, rb_cFile);
13582 stp->dst = dst_io;
13583 stp->close_dst = 1;
13584 }
13585 else {
13586 dst_io = GetWriteIO(dst_io);
13587 stp->dst = dst_io;
13588 }
13589 RB_IO_POINTER(dst_io, stp->dst_fptr);
13590 rb_io_check_writable(stp->dst_fptr);
13591
13592 stat_ret = fstat(stp->dst_fptr->fd, &stp->dst_stat);
13593 if (stat_ret < 0) {
13594 stp->syserr = "fstat";
13595 stp->error_no = errno;
13596 return Qnil;
13597 }
13598 }
13599
13600#ifdef O_BINARY
13601 if (stp->src_fptr)
13602 SET_BINARY_MODE_WITH_SEEK_CUR(stp->src_fptr);
13603#endif
13604 if (stp->dst_fptr)
13605 io_ascii8bit_binmode(stp->dst_fptr);
13606
13607 if (stp->src_offset < (rb_off_t)0 && stp->src_fptr && stp->src_fptr->rbuf.len) {
13608 size_t len = stp->src_fptr->rbuf.len;
13609 VALUE str;
13610 if (stp->copy_length >= (rb_off_t)0 && stp->copy_length < (rb_off_t)len) {
13611 len = (size_t)stp->copy_length;
13612 }
13613 str = rb_str_buf_new(len);
13614 rb_str_resize(str,len);
13615 read_buffered_data(RSTRING_PTR(str), len, stp->src_fptr);
13616 if (stp->dst_fptr) { /* IO or filename */
13617 if (io_binwrite(RSTRING_PTR(str), RSTRING_LEN(str), stp->dst_fptr, 0) < 0)
13618 rb_sys_fail_on_write(stp->dst_fptr);
13619 }
13620 else /* others such as StringIO */
13621 rb_io_write(dst_io, str);
13622 rb_str_resize(str, 0);
13623 stp->total += len;
13624 if (stp->copy_length >= (rb_off_t)0)
13625 stp->copy_length -= len;
13626 }
13627
13628 if (stp->dst_fptr && io_fflush(stp->dst_fptr) < 0) {
13629 rb_raise(rb_eIOError, "flush failed");
13630 }
13631
13632 if (stp->copy_length == 0)
13633 return Qnil;
13634
13635 if (stp->src_fptr == NULL || stp->dst_fptr == NULL) {
13636 return copy_stream_fallback(stp);
13637 }
13638
13639 IO_WITHOUT_GVL(nogvl_copy_stream_func, stp);
13640 return Qnil;
13641}
13642
13643static VALUE
13644copy_stream_finalize(VALUE arg)
13645{
13646 struct copy_stream_struct *stp = (struct copy_stream_struct *)arg;
13647
13648#ifdef HAVE_FCOPYFILE
13649 if (stp->copyfile_state) {
13650 copyfile_state_free(stp->copyfile_state);
13651 }
13652#endif
13653
13654 if (stp->close_src) {
13655 rb_io_close_m(stp->src);
13656 }
13657 if (stp->close_dst) {
13658 rb_io_close_m(stp->dst);
13659 }
13660 if (stp->syserr) {
13661 rb_syserr_fail(stp->error_no, stp->syserr);
13662 }
13663 if (stp->notimp) {
13664 rb_raise(rb_eNotImpError, "%s() not implemented", stp->notimp);
13665 }
13666 return Qnil;
13667}
13668
13669/*
13670 * call-seq:
13671 * IO.copy_stream(src, dst, src_length = nil, src_offset = 0) -> integer
13672 *
13673 * Copies from the given +src+ to the given +dst+,
13674 * returning the number of bytes copied.
13675 *
13676 * - The given +src+ must be one of the following:
13677 *
13678 * - The path to a readable file, from which source data is to be read.
13679 * - An \IO-like object, opened for reading and capable of responding
13680 * to method +:readpartial+ or method +:read+.
13681 *
13682 * - The given +dst+ must be one of the following:
13683 *
13684 * - The path to a writable file, to which data is to be written.
13685 * - An \IO-like object, opened for writing and capable of responding
13686 * to method +:write+.
13687 *
13688 * The examples here use file <tt>t.txt</tt> as source:
13689 *
13690 * File.read('t.txt')
13691 * # => "First line\nSecond line\n\nThird line\nFourth line\n"
13692 * File.read('t.txt').size # => 47
13693 *
13694 * If only arguments +src+ and +dst+ are given,
13695 * the entire source stream is copied:
13696 *
13697 * # Paths.
13698 * IO.copy_stream('t.txt', 't.tmp') # => 47
13699 *
13700 * # IOs (recall that a File is also an IO).
13701 * src_io = File.open('t.txt', 'r') # => #<File:t.txt>
13702 * dst_io = File.open('t.tmp', 'w') # => #<File:t.tmp>
13703 * IO.copy_stream(src_io, dst_io) # => 47
13704 * src_io.close
13705 * dst_io.close
13706 *
13707 * With argument +src_length+ a non-negative integer,
13708 * no more than that many bytes are copied:
13709 *
13710 * IO.copy_stream('t.txt', 't.tmp', 10) # => 10
13711 * File.read('t.tmp') # => "First line"
13712 *
13713 * With argument +src_offset+ also given,
13714 * the source stream is read beginning at that offset:
13715 *
13716 * IO.copy_stream('t.txt', 't.tmp', 11, 11) # => 11
13717 * IO.read('t.tmp') # => "Second line"
13718 *
13719 */
13720static VALUE
13721rb_io_s_copy_stream(int argc, VALUE *argv, VALUE io)
13722{
13723 VALUE src, dst, length, src_offset;
13724 struct copy_stream_struct st;
13725
13726 MEMZERO(&st, struct copy_stream_struct, 1);
13727
13728 rb_scan_args(argc, argv, "22", &src, &dst, &length, &src_offset);
13729
13730 st.src = src;
13731 st.dst = dst;
13732
13733 st.src_fptr = NULL;
13734 st.dst_fptr = NULL;
13735
13736 if (NIL_P(length))
13737 st.copy_length = (rb_off_t)-1;
13738 else
13739 st.copy_length = NUM2OFFT(length);
13740
13741 if (NIL_P(src_offset))
13742 st.src_offset = (rb_off_t)-1;
13743 else
13744 st.src_offset = NUM2OFFT(src_offset);
13745
13746 rb_ensure(copy_stream_body, (VALUE)&st, copy_stream_finalize, (VALUE)&st);
13747
13748 return OFFT2NUM(st.total);
13749}
13750
13751/*
13752 * call-seq:
13753 * external_encoding -> encoding or nil
13754 *
13755 * Returns the Encoding object that represents the encoding of the stream,
13756 * or +nil+ if the stream is in write mode and no encoding is specified.
13757 *
13758 * See {Encodings}[rdoc-ref:File@Encodings].
13759 *
13760 */
13761
13762static VALUE
13763rb_io_external_encoding(VALUE io)
13764{
13765 rb_io_t *fptr = rb_io_get_fptr(rb_io_taint_check(io));
13766
13767 if (fptr->encs.enc2) {
13768 return rb_enc_from_encoding(fptr->encs.enc2);
13769 }
13770 if (fptr->mode & FMODE_WRITABLE) {
13771 if (fptr->encs.enc)
13772 return rb_enc_from_encoding(fptr->encs.enc);
13773 return Qnil;
13774 }
13775 return rb_enc_from_encoding(io_read_encoding(fptr));
13776}
13777
13778/*
13779 * call-seq:
13780 * internal_encoding -> encoding or nil
13781 *
13782 * Returns the Encoding object that represents the encoding of the internal string,
13783 * if conversion is specified,
13784 * or +nil+ otherwise.
13785 *
13786 * See {Encodings}[rdoc-ref:File@Encodings].
13787 *
13788 */
13789
13790static VALUE
13791rb_io_internal_encoding(VALUE io)
13792{
13793 rb_io_t *fptr = rb_io_get_fptr(rb_io_taint_check(io));
13794
13795 if (!fptr->encs.enc2) return Qnil;
13796 return rb_enc_from_encoding(io_read_encoding(fptr));
13797}
13798
13799/*
13800 * call-seq:
13801 * set_encoding(ext_enc) -> self
13802 * set_encoding(ext_enc, int_enc, **enc_opts) -> self
13803 * set_encoding('ext_enc:int_enc', **enc_opts) -> self
13804 *
13805 * See {Encodings}[rdoc-ref:File@Encodings].
13806 *
13807 * Argument +ext_enc+, if given, must be an Encoding object
13808 * or a String with the encoding name;
13809 * it is assigned as the encoding for the stream.
13810 *
13811 * Argument +int_enc+, if given, must be an Encoding object
13812 * or a String with the encoding name;
13813 * it is assigned as the encoding for the internal string.
13814 *
13815 * Argument <tt>'ext_enc:int_enc'</tt>, if given, is a string
13816 * containing two colon-separated encoding names;
13817 * corresponding Encoding objects are assigned as the external
13818 * and internal encodings for the stream.
13819 *
13820 * If the external encoding of a string is binary/ASCII-8BIT,
13821 * the internal encoding of the string is set to nil, since no
13822 * transcoding is needed.
13823 *
13824 * Optional keyword arguments +enc_opts+ specify
13825 * {Encoding options}[rdoc-ref:encodings.rdoc@Encoding+Options].
13826 *
13827 */
13828
13829static VALUE
13830rb_io_set_encoding(int argc, VALUE *argv, VALUE io)
13831{
13832 rb_io_t *fptr;
13833 VALUE v1, v2, opt;
13834
13835 if (!RB_TYPE_P(io, T_FILE)) {
13836 return forward(io, id_set_encoding, argc, argv);
13837 }
13838
13839 argc = rb_scan_args(argc, argv, "11:", &v1, &v2, &opt);
13840 GetOpenFile(io, fptr);
13841 io_encoding_set(fptr, v1, v2, opt);
13842 return io;
13843}
13844
13845void
13846rb_stdio_set_default_encoding(void)
13847{
13848 VALUE val = Qnil;
13849
13850#ifdef _WIN32
13851 if (isatty(fileno(stdin))) {
13852 rb_encoding *external = rb_locale_encoding();
13853 rb_encoding *internal = rb_default_internal_encoding();
13854 if (!internal) internal = rb_default_external_encoding();
13855 io_encoding_set(RFILE(rb_stdin)->fptr,
13856 rb_enc_from_encoding(external),
13857 rb_enc_from_encoding(internal),
13858 Qnil);
13859 }
13860 else
13861#endif
13862 rb_io_set_encoding(1, &val, rb_stdin);
13863 rb_io_set_encoding(1, &val, rb_stdout);
13864 rb_io_set_encoding(1, &val, rb_stderr);
13865}
13866
13867static inline int
13868global_argf_p(VALUE arg)
13869{
13870 return arg == argf;
13871}
13872
13873typedef VALUE (*argf_encoding_func)(VALUE io);
13874
13875static VALUE
13876argf_encoding(VALUE argf, argf_encoding_func func)
13877{
13878 if (!RTEST(ARGF.current_file)) {
13879 return rb_enc_default_external();
13880 }
13881 return func(rb_io_check_io(ARGF.current_file));
13882}
13883
13884/*
13885 * call-seq:
13886 * ARGF.external_encoding -> encoding
13887 *
13888 * Returns the external encoding for files read from ARGF as an Encoding
13889 * object. The external encoding is the encoding of the text as stored in a
13890 * file. Contrast with ARGF.internal_encoding, which is the encoding used to
13891 * represent this text within Ruby.
13892 *
13893 * To set the external encoding use ARGF.set_encoding.
13894 *
13895 * For example:
13896 *
13897 * ARGF.external_encoding #=> #<Encoding:UTF-8>
13898 *
13899 */
13900static VALUE
13901argf_external_encoding(VALUE argf)
13902{
13903 return argf_encoding(argf, rb_io_external_encoding);
13904}
13905
13906/*
13907 * call-seq:
13908 * ARGF.internal_encoding -> encoding
13909 *
13910 * Returns the internal encoding for strings read from ARGF as an
13911 * Encoding object.
13912 *
13913 * If ARGF.set_encoding has been called with two encoding names, the second
13914 * is returned. Otherwise, if +Encoding.default_external+ has been set, that
13915 * value is returned. Failing that, if a default external encoding was
13916 * specified on the command-line, that value is used. If the encoding is
13917 * unknown, +nil+ is returned.
13918 */
13919static VALUE
13920argf_internal_encoding(VALUE argf)
13921{
13922 return argf_encoding(argf, rb_io_internal_encoding);
13923}
13924
13925/*
13926 * call-seq:
13927 * ARGF.set_encoding(ext_enc) -> ARGF
13928 * ARGF.set_encoding("ext_enc:int_enc") -> ARGF
13929 * ARGF.set_encoding(ext_enc, int_enc) -> ARGF
13930 * ARGF.set_encoding("ext_enc:int_enc", opt) -> ARGF
13931 * ARGF.set_encoding(ext_enc, int_enc, opt) -> ARGF
13932 *
13933 * If single argument is specified, strings read from ARGF are tagged with
13934 * the encoding specified.
13935 *
13936 * If two encoding names separated by a colon are given, e.g. "ascii:utf-8",
13937 * the read string is converted from the first encoding (external encoding)
13938 * to the second encoding (internal encoding), then tagged with the second
13939 * encoding.
13940 *
13941 * If two arguments are specified, they must be encoding objects or encoding
13942 * names. Again, the first specifies the external encoding; the second
13943 * specifies the internal encoding.
13944 *
13945 * If the external encoding and the internal encoding are specified, the
13946 * optional Hash argument can be used to adjust the conversion process. The
13947 * structure of this hash is explained in the String#encode documentation.
13948 *
13949 * For example:
13950 *
13951 * ARGF.set_encoding('ascii') # Tag the input as US-ASCII text
13952 * ARGF.set_encoding(Encoding::UTF_8) # Tag the input as UTF-8 text
13953 * ARGF.set_encoding('utf-8','ascii') # Transcode the input from US-ASCII
13954 * # to UTF-8.
13955 */
13956static VALUE
13957argf_set_encoding(int argc, VALUE *argv, VALUE argf)
13958{
13959 rb_io_t *fptr;
13960
13961 if (!next_argv()) {
13962 rb_raise(rb_eArgError, "no stream to set encoding");
13963 }
13964 rb_io_set_encoding(argc, argv, ARGF.current_file);
13965 GetOpenFile(ARGF.current_file, fptr);
13966 ARGF.encs = fptr->encs;
13967 RB_OBJ_WRITTEN(argf, Qundef, ARGF.encs.ecopts);
13968 return argf;
13969}
13970
13971/*
13972 * call-seq:
13973 * ARGF.tell -> Integer
13974 * ARGF.pos -> Integer
13975 *
13976 * Returns the current offset (in bytes) of the current file in ARGF.
13977 *
13978 * ARGF.pos #=> 0
13979 * ARGF.gets #=> "This is line one\n"
13980 * ARGF.pos #=> 17
13981 *
13982 */
13983static VALUE
13984argf_tell(VALUE argf)
13985{
13986 if (!next_argv()) {
13987 rb_raise(rb_eArgError, "no stream to tell");
13988 }
13989 ARGF_FORWARD(0, 0);
13990 return rb_io_tell(ARGF.current_file);
13991}
13992
13993/*
13994 * call-seq:
13995 * ARGF.seek(amount, whence=IO::SEEK_SET) -> 0
13996 *
13997 * Seeks to offset _amount_ (an Integer) in the ARGF stream according to
13998 * the value of _whence_. See IO#seek for further details.
13999 */
14000static VALUE
14001argf_seek_m(int argc, VALUE *argv, VALUE argf)
14002{
14003 if (!next_argv()) {
14004 rb_raise(rb_eArgError, "no stream to seek");
14005 }
14006 ARGF_FORWARD(argc, argv);
14007 return rb_io_seek_m(argc, argv, ARGF.current_file);
14008}
14009
14010/*
14011 * call-seq:
14012 * ARGF.pos = position -> Integer
14013 *
14014 * Seeks to the position given by _position_ (in bytes) in ARGF.
14015 *
14016 * For example:
14017 *
14018 * ARGF.pos = 17
14019 * ARGF.gets #=> "This is line two\n"
14020 */
14021static VALUE
14022argf_set_pos(VALUE argf, VALUE offset)
14023{
14024 if (!next_argv()) {
14025 rb_raise(rb_eArgError, "no stream to set position");
14026 }
14027 ARGF_FORWARD(1, &offset);
14028 return rb_io_set_pos(ARGF.current_file, offset);
14029}
14030
14031/*
14032 * call-seq:
14033 * ARGF.rewind -> 0
14034 *
14035 * Positions the current file to the beginning of input, resetting
14036 * ARGF.lineno to zero.
14037 *
14038 * ARGF.readline #=> "This is line one\n"
14039 * ARGF.rewind #=> 0
14040 * ARGF.lineno #=> 0
14041 * ARGF.readline #=> "This is line one\n"
14042 */
14043static VALUE
14044argf_rewind(VALUE argf)
14045{
14046 VALUE ret;
14047 int old_lineno;
14048
14049 if (!next_argv()) {
14050 rb_raise(rb_eArgError, "no stream to rewind");
14051 }
14052 ARGF_FORWARD(0, 0);
14053 old_lineno = RFILE(ARGF.current_file)->fptr->lineno;
14054 ret = rb_io_rewind(ARGF.current_file);
14055 if (!global_argf_p(argf)) {
14056 ARGF.last_lineno = ARGF.lineno -= old_lineno;
14057 }
14058 return ret;
14059}
14060
14061/*
14062 * call-seq:
14063 * ARGF.fileno -> integer
14064 * ARGF.to_i -> integer
14065 *
14066 * Returns an integer representing the numeric file descriptor for
14067 * the current file. Raises an ArgumentError if there isn't a current file.
14068 *
14069 * ARGF.fileno #=> 3
14070 */
14071static VALUE
14072argf_fileno(VALUE argf)
14073{
14074 if (!next_argv()) {
14075 rb_raise(rb_eArgError, "no stream");
14076 }
14077 ARGF_FORWARD(0, 0);
14078 return rb_io_fileno(ARGF.current_file);
14079}
14080
14081/*
14082 * call-seq:
14083 * ARGF.to_io -> IO
14084 *
14085 * Returns an IO object representing the current file. This will be a
14086 * File object unless the current file is a stream such as STDIN.
14087 *
14088 * For example:
14089 *
14090 * ARGF.to_io #=> #<File:glark.txt>
14091 * ARGF.to_io #=> #<IO:<STDIN>>
14092 */
14093static VALUE
14094argf_to_io(VALUE argf)
14095{
14096 next_argv();
14097 ARGF_FORWARD(0, 0);
14098 return ARGF.current_file;
14099}
14100
14101/*
14102 * call-seq:
14103 * ARGF.eof? -> true or false
14104 * ARGF.eof -> true or false
14105 *
14106 * Returns true if the current file in ARGF is at end of file, i.e. it has
14107 * no data to read. The stream must be opened for reading or an IOError
14108 * will be raised.
14109 *
14110 * $ echo "eof" | ruby argf.rb
14111 *
14112 * ARGF.eof? #=> false
14113 * 3.times { ARGF.readchar }
14114 * ARGF.eof? #=> false
14115 * ARGF.readchar #=> "\n"
14116 * ARGF.eof? #=> true
14117 */
14118
14119static VALUE
14120argf_eof(VALUE argf)
14121{
14122 next_argv();
14123 if (RTEST(ARGF.current_file)) {
14124 if (ARGF.init_p == 0) return Qtrue;
14125 next_argv();
14126 ARGF_FORWARD(0, 0);
14127 if (rb_io_eof(ARGF.current_file)) {
14128 return Qtrue;
14129 }
14130 }
14131 return Qfalse;
14132}
14133
14134/*
14135 * call-seq:
14136 * ARGF.read([length [, outbuf]]) -> string, outbuf, or nil
14137 *
14138 * Reads _length_ bytes from ARGF. The files named on the command line
14139 * are concatenated and treated as a single file by this method, so when
14140 * called without arguments the contents of this pseudo file are returned in
14141 * their entirety.
14142 *
14143 * _length_ must be a non-negative integer or +nil+.
14144 *
14145 * If _length_ is a positive integer, +read+ tries to read
14146 * _length_ bytes without any conversion (binary mode).
14147 * It returns +nil+ if an EOF is encountered before anything can be read.
14148 * Fewer than _length_ bytes are returned if an EOF is encountered during
14149 * the read.
14150 * In the case of an integer _length_, the resulting string is always
14151 * in ASCII-8BIT encoding.
14152 *
14153 * If _length_ is omitted or is +nil+, it reads until EOF
14154 * and the encoding conversion is applied, if applicable.
14155 * A string is returned even if EOF is encountered before any data is read.
14156 *
14157 * If _length_ is zero, it returns an empty string (<code>""</code>).
14158 *
14159 * If the optional _outbuf_ argument is present,
14160 * it must reference a String, which will receive the data.
14161 * The _outbuf_ will contain only the received data after the method call
14162 * even if it is not empty at the beginning.
14163 *
14164 * For example:
14165 *
14166 * $ echo "small" > small.txt
14167 * $ echo "large" > large.txt
14168 * $ ./glark.rb small.txt large.txt
14169 *
14170 * ARGF.read #=> "small\nlarge"
14171 * ARGF.read(200) #=> "small\nlarge"
14172 * ARGF.read(2) #=> "sm"
14173 * ARGF.read(0) #=> ""
14174 *
14175 * Note that this method behaves like the fread() function in C.
14176 * This means it retries to invoke read(2) system calls to read data
14177 * with the specified length.
14178 * If you need the behavior like a single read(2) system call,
14179 * consider ARGF#readpartial or ARGF#read_nonblock.
14180 */
14181
14182static VALUE
14183argf_read(int argc, VALUE *argv, VALUE argf)
14184{
14185 VALUE tmp, str, length;
14186 rb_len_t len = 0;
14187
14188 rb_scan_args(argc, argv, "02", &length, &str);
14189 if (!NIL_P(length)) {
14190 len = NUM2LEN(argv[0]);
14191 }
14192 if (!NIL_P(str)) {
14193 StringValue(str);
14194 rb_str_resize(str,0);
14195 argv[1] = Qnil;
14196 }
14197
14198 retry:
14199 if (!next_argv()) {
14200 return str;
14201 }
14202 if (ARGF_GENERIC_INPUT_P()) {
14203 tmp = argf_forward(argc, argv, argf);
14204 }
14205 else {
14206 tmp = io_read(argc, argv, ARGF.current_file);
14207 }
14208 if (NIL_P(str)) str = tmp;
14209 else if (!NIL_P(tmp)) rb_str_append(str, tmp);
14210 if (NIL_P(tmp) || NIL_P(length)) {
14211 if (ARGF.next_p != -1) {
14212 argf_close(argf);
14213 ARGF.next_p = 1;
14214 goto retry;
14215 }
14216 }
14217 else if (argc >= 1) {
14218 rb_len_t slen = RSTRING_LEN(str);
14219 if (slen < len) {
14220 argv[0] = LEN2NUM(len - slen);
14221 goto retry;
14222 }
14223 }
14224 return str;
14225}
14226
14228 int argc;
14229 VALUE *argv;
14230 VALUE argf;
14231};
14232
14233static VALUE
14234argf_forward_call(VALUE arg)
14235{
14236 struct argf_call_arg *p = (struct argf_call_arg *)arg;
14237 argf_forward(p->argc, p->argv, p->argf);
14238 return Qnil;
14239}
14240
14241static VALUE argf_getpartial(int argc, VALUE *argv, VALUE argf, VALUE opts,
14242 int nonblock);
14243
14244/*
14245 * call-seq:
14246 * ARGF.readpartial(maxlen) -> string
14247 * ARGF.readpartial(maxlen, outbuf) -> outbuf
14248 *
14249 * Reads at most _maxlen_ bytes from the ARGF stream.
14250 *
14251 * If the optional _outbuf_ argument is present,
14252 * it must reference a String, which will receive the data.
14253 * The _outbuf_ will contain only the received data after the method call
14254 * even if it is not empty at the beginning.
14255 *
14256 * It raises EOFError on end of ARGF stream.
14257 * Since ARGF stream is a concatenation of multiple files,
14258 * internally EOF is occur for each file.
14259 * ARGF.readpartial returns empty strings for EOFs except the last one and
14260 * raises EOFError for the last one.
14261 *
14262 */
14263
14264static VALUE
14265argf_readpartial(int argc, VALUE *argv, VALUE argf)
14266{
14267 return argf_getpartial(argc, argv, argf, Qnil, 0);
14268}
14269
14270/*
14271 * call-seq:
14272 * ARGF.read_nonblock(maxlen[, options]) -> string
14273 * ARGF.read_nonblock(maxlen, outbuf[, options]) -> outbuf
14274 *
14275 * Reads at most _maxlen_ bytes from the ARGF stream in non-blocking mode.
14276 */
14277
14278static VALUE
14279argf_read_nonblock(int argc, VALUE *argv, VALUE argf)
14280{
14281 VALUE opts;
14282
14283 rb_scan_args(argc, argv, "11:", NULL, NULL, &opts);
14284
14285 if (!NIL_P(opts))
14286 argc--;
14287
14288 return argf_getpartial(argc, argv, argf, opts, 1);
14289}
14290
14291static VALUE
14292argf_getpartial(int argc, VALUE *argv, VALUE argf, VALUE opts, int nonblock)
14293{
14294 VALUE tmp, str, length;
14295 int no_exception;
14296
14297 rb_scan_args(argc, argv, "11", &length, &str);
14298 if (!NIL_P(str)) {
14299 StringValue(str);
14300 argv[1] = str;
14301 }
14302 no_exception = no_exception_p(opts);
14303
14304 if (!next_argv()) {
14305 if (!NIL_P(str)) {
14306 rb_str_resize(str, 0);
14307 }
14308 rb_eof_error();
14309 }
14310 if (ARGF_GENERIC_INPUT_P()) {
14311 VALUE (*const rescue_does_nothing)(VALUE, VALUE) = 0;
14312 struct argf_call_arg arg;
14313 arg.argc = argc;
14314 arg.argv = argv;
14315 arg.argf = argf;
14316 tmp = rb_rescue2(argf_forward_call, (VALUE)&arg,
14317 rescue_does_nothing, Qnil, rb_eEOFError, (VALUE)0);
14318 }
14319 else {
14320 tmp = io_getpartial(ARGF.current_file, length, str, no_exception, nonblock);
14321 }
14322 if (NIL_P(tmp)) {
14323 if (ARGF.next_p == -1) {
14324 return io_nonblock_eof(no_exception);
14325 }
14326 argf_close(argf);
14327 ARGF.next_p = 1;
14328 if (RARRAY_LEN(ARGF.argv) == 0) {
14329 return io_nonblock_eof(no_exception);
14330 }
14331 if (NIL_P(str))
14332 str = rb_str_new(NULL, 0);
14333 return str;
14334 }
14335 return tmp;
14336}
14337
14338/*
14339 * call-seq:
14340 * ARGF.getc -> String or nil
14341 *
14342 * Reads the next character from ARGF and returns it as a String. Returns
14343 * +nil+ at the end of the stream.
14344 *
14345 * ARGF treats the files named on the command line as a single file created
14346 * by concatenating their contents. After returning the last character of the
14347 * first file, it returns the first character of the second file, and so on.
14348 *
14349 * For example:
14350 *
14351 * $ echo "foo" > file
14352 * $ ruby argf.rb file
14353 *
14354 * ARGF.getc #=> "f"
14355 * ARGF.getc #=> "o"
14356 * ARGF.getc #=> "o"
14357 * ARGF.getc #=> "\n"
14358 * ARGF.getc #=> nil
14359 * ARGF.getc #=> nil
14360 */
14361static VALUE
14362argf_getc(VALUE argf)
14363{
14364 VALUE ch;
14365
14366 retry:
14367 if (!next_argv()) return Qnil;
14368 if (ARGF_GENERIC_INPUT_P()) {
14369 ch = forward_current(rb_intern("getc"), 0, 0);
14370 }
14371 else {
14372 ch = rb_io_getc(ARGF.current_file);
14373 }
14374 if (NIL_P(ch) && ARGF.next_p != -1) {
14375 argf_close(argf);
14376 ARGF.next_p = 1;
14377 goto retry;
14378 }
14379
14380 return ch;
14381}
14382
14383/*
14384 * call-seq:
14385 * ARGF.getbyte -> Integer or nil
14386 *
14387 * Gets the next 8-bit byte (0..255) from ARGF. Returns +nil+ if called at
14388 * the end of the stream.
14389 *
14390 * For example:
14391 *
14392 * $ echo "foo" > file
14393 * $ ruby argf.rb file
14394 *
14395 * ARGF.getbyte #=> 102
14396 * ARGF.getbyte #=> 111
14397 * ARGF.getbyte #=> 111
14398 * ARGF.getbyte #=> 10
14399 * ARGF.getbyte #=> nil
14400 */
14401static VALUE
14402argf_getbyte(VALUE argf)
14403{
14404 VALUE ch;
14405
14406 retry:
14407 if (!next_argv()) return Qnil;
14408 if (!RB_TYPE_P(ARGF.current_file, T_FILE)) {
14409 ch = forward_current(rb_intern("getbyte"), 0, 0);
14410 }
14411 else {
14412 ch = rb_io_getbyte(ARGF.current_file);
14413 }
14414 if (NIL_P(ch) && ARGF.next_p != -1) {
14415 argf_close(argf);
14416 ARGF.next_p = 1;
14417 goto retry;
14418 }
14419
14420 return ch;
14421}
14422
14423/*
14424 * call-seq:
14425 * ARGF.readchar -> String or nil
14426 *
14427 * Reads the next character from ARGF and returns it as a String. Raises
14428 * an EOFError after the last character of the last file has been read.
14429 *
14430 * For example:
14431 *
14432 * $ echo "foo" > file
14433 * $ ruby argf.rb file
14434 *
14435 * ARGF.readchar #=> "f"
14436 * ARGF.readchar #=> "o"
14437 * ARGF.readchar #=> "o"
14438 * ARGF.readchar #=> "\n"
14439 * ARGF.readchar #=> end of file reached (EOFError)
14440 */
14441static VALUE
14442argf_readchar(VALUE argf)
14443{
14444 VALUE ch;
14445
14446 retry:
14447 if (!next_argv()) rb_eof_error();
14448 if (!RB_TYPE_P(ARGF.current_file, T_FILE)) {
14449 ch = forward_current(rb_intern("getc"), 0, 0);
14450 }
14451 else {
14452 ch = rb_io_getc(ARGF.current_file);
14453 }
14454 if (NIL_P(ch) && ARGF.next_p != -1) {
14455 argf_close(argf);
14456 ARGF.next_p = 1;
14457 goto retry;
14458 }
14459
14460 return ch;
14461}
14462
14463/*
14464 * call-seq:
14465 * ARGF.readbyte -> Integer
14466 *
14467 * Reads the next 8-bit byte from ARGF and returns it as an Integer. Raises
14468 * an EOFError after the last byte of the last file has been read.
14469 *
14470 * For example:
14471 *
14472 * $ echo "foo" > file
14473 * $ ruby argf.rb file
14474 *
14475 * ARGF.readbyte #=> 102
14476 * ARGF.readbyte #=> 111
14477 * ARGF.readbyte #=> 111
14478 * ARGF.readbyte #=> 10
14479 * ARGF.readbyte #=> end of file reached (EOFError)
14480 */
14481static VALUE
14482argf_readbyte(VALUE argf)
14483{
14484 VALUE c;
14485
14486 NEXT_ARGF_FORWARD(0, 0);
14487 c = argf_getbyte(argf);
14488 if (NIL_P(c)) {
14489 rb_eof_error();
14490 }
14491 return c;
14492}
14493
14494#define FOREACH_ARGF() while (next_argv())
14495
14496static VALUE
14497argf_block_call_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, argf))
14498{
14499 const VALUE current = ARGF.current_file;
14500 rb_yield_values2(argc, argv);
14501 if (ARGF.init_p == -1 || current != ARGF.current_file) {
14503 }
14504 return Qnil;
14505}
14506
14507#define ARGF_block_call(mid, argc, argv, func, argf) \
14508 rb_block_call_kw(ARGF.current_file, mid, argc, argv, \
14509 func, argf, rb_keyword_given_p())
14510
14511static void
14512argf_block_call(ID mid, int argc, VALUE *argv, VALUE argf)
14513{
14514 VALUE ret = ARGF_block_call(mid, argc, argv, argf_block_call_i, argf);
14515 if (!UNDEF_P(ret)) ARGF.next_p = 1;
14516}
14517
14518static VALUE
14519argf_block_call_line_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, argf))
14520{
14521 if (!global_argf_p(argf)) {
14522 ARGF.last_lineno = ++ARGF.lineno;
14523 }
14524 return argf_block_call_i(i, argf, argc, argv, blockarg);
14525}
14526
14527static void
14528argf_block_call_line(ID mid, int argc, VALUE *argv, VALUE argf)
14529{
14530 VALUE ret = ARGF_block_call(mid, argc, argv, argf_block_call_line_i, argf);
14531 if (!UNDEF_P(ret)) ARGF.next_p = 1;
14532}
14533
14534/*
14535 * call-seq:
14536 * ARGF.each(sep=$/) {|line| block } -> ARGF
14537 * ARGF.each(sep=$/, limit) {|line| block } -> ARGF
14538 * ARGF.each(...) -> an_enumerator
14539 *
14540 * ARGF.each_line(sep=$/) {|line| block } -> ARGF
14541 * ARGF.each_line(sep=$/, limit) {|line| block } -> ARGF
14542 * ARGF.each_line(...) -> an_enumerator
14543 *
14544 * Returns an enumerator which iterates over each line (separated by _sep_,
14545 * which defaults to your platform's newline character) of each file in
14546 * +ARGV+. If a block is supplied, each line in turn will be yielded to the
14547 * block, otherwise an enumerator is returned.
14548 * The optional _limit_ argument is an Integer specifying the maximum
14549 * length of each line; longer lines will be split according to this limit.
14550 *
14551 * This method allows you to treat the files supplied on the command line as
14552 * a single file consisting of the concatenation of each named file. After
14553 * the last line of the first file has been returned, the first line of the
14554 * second file is returned. The ARGF.filename and ARGF.lineno methods can be
14555 * used to determine the filename of the current line and line number of the
14556 * whole input, respectively.
14557 *
14558 * For example, the following code prints out each line of each named file
14559 * prefixed with its line number, displaying the filename once per file:
14560 *
14561 * ARGF.each_line do |line|
14562 * puts ARGF.filename if ARGF.file.lineno == 1
14563 * puts "#{ARGF.file.lineno}: #{line}"
14564 * end
14565 *
14566 * While the following code prints only the first file's name at first, and
14567 * the contents with line number counted through all named files.
14568 *
14569 * ARGF.each_line do |line|
14570 * puts ARGF.filename if ARGF.lineno == 1
14571 * puts "#{ARGF.lineno}: #{line}"
14572 * end
14573 */
14574static VALUE
14575argf_each_line(int argc, VALUE *argv, VALUE argf)
14576{
14577 RETURN_ENUMERATOR(argf, argc, argv);
14578 FOREACH_ARGF() {
14579 argf_block_call_line(rb_intern("each_line"), argc, argv, argf);
14580 }
14581 return argf;
14582}
14583
14584/*
14585 * call-seq:
14586 * ARGF.each_byte {|byte| block } -> ARGF
14587 * ARGF.each_byte -> an_enumerator
14588 *
14589 * Iterates over each byte of each file in +ARGV+.
14590 * A byte is returned as an Integer in the range 0..255.
14591 *
14592 * This method allows you to treat the files supplied on the command line as
14593 * a single file consisting of the concatenation of each named file. After
14594 * the last byte of the first file has been returned, the first byte of the
14595 * second file is returned. The ARGF.filename method can be used to
14596 * determine the filename of the current byte.
14597 *
14598 * If no block is given, an enumerator is returned instead.
14599 *
14600 * For example:
14601 *
14602 * ARGF.bytes.to_a #=> [35, 32, ... 95, 10]
14603 *
14604 */
14605static VALUE
14606argf_each_byte(VALUE argf)
14607{
14608 RETURN_ENUMERATOR(argf, 0, 0);
14609 FOREACH_ARGF() {
14610 argf_block_call(rb_intern("each_byte"), 0, 0, argf);
14611 }
14612 return argf;
14613}
14614
14615/*
14616 * call-seq:
14617 * ARGF.each_char {|char| block } -> ARGF
14618 * ARGF.each_char -> an_enumerator
14619 *
14620 * Iterates over each character of each file in ARGF.
14621 *
14622 * This method allows you to treat the files supplied on the command line as
14623 * a single file consisting of the concatenation of each named file. After
14624 * the last character of the first file has been returned, the first
14625 * character of the second file is returned. The ARGF.filename method can
14626 * be used to determine the name of the file in which the current character
14627 * appears.
14628 *
14629 * If no block is given, an enumerator is returned instead.
14630 */
14631static VALUE
14632argf_each_char(VALUE argf)
14633{
14634 RETURN_ENUMERATOR(argf, 0, 0);
14635 FOREACH_ARGF() {
14636 argf_block_call(rb_intern("each_char"), 0, 0, argf);
14637 }
14638 return argf;
14639}
14640
14641/*
14642 * call-seq:
14643 * ARGF.each_codepoint {|codepoint| block } -> ARGF
14644 * ARGF.each_codepoint -> an_enumerator
14645 *
14646 * Iterates over each codepoint of each file in ARGF.
14647 *
14648 * This method allows you to treat the files supplied on the command line as
14649 * a single file consisting of the concatenation of each named file. After
14650 * the last codepoint of the first file has been returned, the first
14651 * codepoint of the second file is returned. The ARGF.filename method can
14652 * be used to determine the name of the file in which the current codepoint
14653 * appears.
14654 *
14655 * If no block is given, an enumerator is returned instead.
14656 */
14657static VALUE
14658argf_each_codepoint(VALUE argf)
14659{
14660 RETURN_ENUMERATOR(argf, 0, 0);
14661 FOREACH_ARGF() {
14662 argf_block_call(rb_intern("each_codepoint"), 0, 0, argf);
14663 }
14664 return argf;
14665}
14666
14667/*
14668 * call-seq:
14669 * ARGF.filename -> String
14670 * ARGF.path -> String
14671 *
14672 * Returns the current filename. "-" is returned when the current file is
14673 * STDIN.
14674 *
14675 * For example:
14676 *
14677 * $ echo "foo" > foo
14678 * $ echo "bar" > bar
14679 * $ echo "glark" > glark
14680 *
14681 * $ ruby argf.rb foo bar glark
14682 *
14683 * ARGF.filename #=> "foo"
14684 * ARGF.read(5) #=> "foo\nb"
14685 * ARGF.filename #=> "bar"
14686 * ARGF.skip
14687 * ARGF.filename #=> "glark"
14688 */
14689static VALUE
14690argf_filename(VALUE argf)
14691{
14692 next_argv();
14693 return ARGF.filename;
14694}
14695
14696static VALUE
14697argf_filename_getter(ID id, VALUE *var)
14698{
14699 return argf_filename(*var);
14700}
14701
14702/*
14703 * call-seq:
14704 * ARGF.file -> IO or File object
14705 *
14706 * Returns the current file as an IO or File object.
14707 * <code>$stdin</code> is returned when the current file is STDIN.
14708 *
14709 * For example:
14710 *
14711 * $ echo "foo" > foo
14712 * $ echo "bar" > bar
14713 *
14714 * $ ruby argf.rb foo bar
14715 *
14716 * ARGF.file #=> #<File:foo>
14717 * ARGF.read(5) #=> "foo\nb"
14718 * ARGF.file #=> #<File:bar>
14719 */
14720static VALUE
14721argf_file(VALUE argf)
14722{
14723 next_argv();
14724 return ARGF.current_file;
14725}
14726
14727/*
14728 * call-seq:
14729 * ARGF.binmode -> ARGF
14730 *
14731 * Puts ARGF into binary mode. Once a stream is in binary mode, it cannot
14732 * be reset to non-binary mode. This option has the following effects:
14733 *
14734 * * Newline conversion is disabled.
14735 * * Encoding conversion is disabled.
14736 * * Content is treated as ASCII-8BIT.
14737 */
14738static VALUE
14739argf_binmode_m(VALUE argf)
14740{
14741 ARGF.binmode = 1;
14742 next_argv();
14743 ARGF_FORWARD(0, 0);
14744 rb_io_ascii8bit_binmode(ARGF.current_file);
14745 return argf;
14746}
14747
14748/*
14749 * call-seq:
14750 * ARGF.binmode? -> true or false
14751 *
14752 * Returns true if ARGF is being read in binary mode; false otherwise.
14753 * To enable binary mode use ARGF.binmode.
14754 *
14755 * For example:
14756 *
14757 * ARGF.binmode? #=> false
14758 * ARGF.binmode
14759 * ARGF.binmode? #=> true
14760 */
14761static VALUE
14762argf_binmode_p(VALUE argf)
14763{
14764 return RBOOL(ARGF.binmode);
14765}
14766
14767/*
14768 * call-seq:
14769 * ARGF.skip -> ARGF
14770 *
14771 * Sets the current file to the next file in ARGV. If there aren't any more
14772 * files it has no effect.
14773 *
14774 * For example:
14775 *
14776 * $ ruby argf.rb foo bar
14777 * ARGF.filename #=> "foo"
14778 * ARGF.skip
14779 * ARGF.filename #=> "bar"
14780 */
14781static VALUE
14782argf_skip(VALUE argf)
14783{
14784 if (ARGF.init_p && ARGF.next_p == 0) {
14785 argf_close(argf);
14786 ARGF.next_p = 1;
14787 }
14788 return argf;
14789}
14790
14791/*
14792 * call-seq:
14793 * ARGF.close -> ARGF
14794 *
14795 * Closes the current file and skips to the next file in ARGV. If there are
14796 * no more files to open, just closes the current file. STDIN will not be
14797 * closed.
14798 *
14799 * For example:
14800 *
14801 * $ ruby argf.rb foo bar
14802 *
14803 * ARGF.filename #=> "foo"
14804 * ARGF.close
14805 * ARGF.filename #=> "bar"
14806 * ARGF.close
14807 */
14808static VALUE
14809argf_close_m(VALUE argf)
14810{
14811 next_argv();
14812 argf_close(argf);
14813 if (ARGF.next_p != -1) {
14814 ARGF.next_p = 1;
14815 }
14816 ARGF.lineno = 0;
14817 return argf;
14818}
14819
14820/*
14821 * call-seq:
14822 * ARGF.closed? -> true or false
14823 *
14824 * Returns _true_ if the current file has been closed; _false_ otherwise. Use
14825 * ARGF.close to actually close the current file.
14826 */
14827static VALUE
14828argf_closed(VALUE argf)
14829{
14830 next_argv();
14831 ARGF_FORWARD(0, 0);
14832 return rb_io_closed_p(ARGF.current_file);
14833}
14834
14835/*
14836 * call-seq:
14837 * ARGF.to_s -> String
14838 *
14839 * Returns "ARGF".
14840 */
14841static VALUE
14842argf_to_s(VALUE argf)
14843{
14844 return rb_str_new2("ARGF");
14845}
14846
14847/*
14848 * call-seq:
14849 * ARGF.inplace_mode -> String
14850 *
14851 * Returns the file extension appended to the names of backup copies of
14852 * modified files under in-place edit mode. This value can be set using
14853 * ARGF.inplace_mode= or passing the +-i+ switch to the Ruby binary.
14854 */
14855static VALUE
14856argf_inplace_mode_get(VALUE argf)
14857{
14858 if (!ARGF.inplace) return Qnil;
14859 if (NIL_P(ARGF.inplace)) return rb_str_new(0, 0);
14860 return rb_str_dup(ARGF.inplace);
14861}
14862
14863static VALUE
14864opt_i_get(ID id, VALUE *var)
14865{
14866 return argf_inplace_mode_get(*var);
14867}
14868
14869/*
14870 * call-seq:
14871 * ARGF.inplace_mode = ext -> ARGF
14872 *
14873 * Sets the filename extension for in-place editing mode to the given String.
14874 * The backup copy of each file being edited has this value appended to its
14875 * filename.
14876 *
14877 * For example:
14878 *
14879 * $ ruby argf.rb file.txt
14880 *
14881 * ARGF.inplace_mode = '.bak'
14882 * ARGF.each_line do |line|
14883 * print line.sub("foo","bar")
14884 * end
14885 *
14886 * First, _file.txt.bak_ is created as a backup copy of _file.txt_.
14887 * Then, each line of _file.txt_ has the first occurrence of "foo" replaced with
14888 * "bar".
14889 */
14890static VALUE
14891argf_inplace_mode_set(VALUE argf, VALUE val)
14892{
14893 if (!RTEST(val)) {
14894 ARGF.inplace = Qfalse;
14895 }
14896 else if (StringValueCStr(val), !RSTRING_LEN(val)) {
14897 ARGF.inplace = Qnil;
14898 }
14899 else {
14900 ARGF_SET(inplace, rb_str_new_frozen(val));
14901 }
14902 return argf;
14903}
14904
14905static void
14906opt_i_set(VALUE val, ID id, VALUE *var)
14907{
14908 argf_inplace_mode_set(*var, val);
14909}
14910
14911void
14912ruby_set_inplace_mode(const char *suffix)
14913{
14914 ARGF_SET(inplace, !suffix ? Qfalse : !*suffix ? Qnil : rb_str_new(suffix, strlen(suffix)));
14915}
14916
14917/*
14918 * call-seq:
14919 * ARGF.argv -> ARGV
14920 *
14921 * Returns the +ARGV+ array, which contains the arguments passed to your
14922 * script, one per element.
14923 *
14924 * For example:
14925 *
14926 * $ ruby argf.rb -v glark.txt
14927 *
14928 * ARGF.argv #=> ["-v", "glark.txt"]
14929 *
14930 */
14931static VALUE
14932argf_argv(VALUE argf)
14933{
14934 return ARGF.argv;
14935}
14936
14937static VALUE
14938argf_argv_getter(ID id, VALUE *var)
14939{
14940 return argf_argv(*var);
14941}
14942
14943VALUE
14945{
14946 return ARGF.argv;
14947}
14948
14949/*
14950 * call-seq:
14951 * ARGF.to_write_io -> io
14952 *
14953 * Returns IO instance tied to _ARGF_ for writing if inplace mode is
14954 * enabled.
14955 */
14956static VALUE
14957argf_write_io(VALUE argf)
14958{
14959 if (!RTEST(ARGF.current_file)) {
14960 rb_raise(rb_eIOError, "not opened for writing");
14961 }
14962 return GetWriteIO(ARGF.current_file);
14963}
14964
14965/*
14966 * call-seq:
14967 * ARGF.write(*objects) -> integer
14968 *
14969 * Writes each of the given +objects+ if inplace mode.
14970 */
14971static VALUE
14972argf_write(int argc, VALUE *argv, VALUE argf)
14973{
14974 return rb_io_writev(argf_write_io(argf), argc, argv);
14975}
14976
14977void
14978rb_readwrite_sys_fail(enum rb_io_wait_readwrite waiting, const char *mesg)
14979{
14980 rb_readwrite_syserr_fail(waiting, errno, mesg);
14981}
14982
14983void
14984rb_readwrite_syserr_fail(enum rb_io_wait_readwrite waiting, int n, const char *mesg)
14985{
14986 VALUE arg, c = Qnil;
14987 arg = mesg ? rb_str_new2(mesg) : Qnil;
14988 switch (waiting) {
14989 case RB_IO_WAIT_WRITABLE:
14990 switch (n) {
14991 case EAGAIN:
14992 c = rb_eEAGAINWaitWritable;
14993 break;
14994#if EAGAIN != EWOULDBLOCK
14995 case EWOULDBLOCK:
14996 c = rb_eEWOULDBLOCKWaitWritable;
14997 break;
14998#endif
14999 case EINPROGRESS:
15000 c = rb_eEINPROGRESSWaitWritable;
15001 break;
15002 default:
15004 }
15005 break;
15006 case RB_IO_WAIT_READABLE:
15007 switch (n) {
15008 case EAGAIN:
15009 c = rb_eEAGAINWaitReadable;
15010 break;
15011#if EAGAIN != EWOULDBLOCK
15012 case EWOULDBLOCK:
15013 c = rb_eEWOULDBLOCKWaitReadable;
15014 break;
15015#endif
15016 case EINPROGRESS:
15017 c = rb_eEINPROGRESSWaitReadable;
15018 break;
15019 default:
15021 }
15022 break;
15023 default:
15024 rb_bug("invalid read/write type passed to rb_readwrite_sys_fail: %d", waiting);
15025 }
15027}
15028
15029static VALUE
15030get_LAST_READ_LINE(ID _x, VALUE *_y)
15031{
15032 return rb_lastline_get();
15033}
15034
15035static void
15036set_LAST_READ_LINE(VALUE val, ID _x, VALUE *_y)
15037{
15038 rb_lastline_set(val);
15039}
15040
15041/*
15042 * Document-class: IOError
15043 *
15044 * Raised when an IO operation fails.
15045 *
15046 * File.open("/etc/hosts") {|f| f << "example"}
15047 * #=> IOError: not opened for writing
15048 *
15049 * File.open("/etc/hosts") {|f| f.close; f.read }
15050 * #=> IOError: closed stream
15051 *
15052 * Note that some IO failures raise <code>SystemCallError</code>s
15053 * and these are not subclasses of IOError:
15054 *
15055 * File.open("does/not/exist")
15056 * #=> Errno::ENOENT: No such file or directory - does/not/exist
15057 */
15058
15059/*
15060 * Document-class: EOFError
15061 *
15062 * Raised by some IO operations when reaching the end of file. Many IO
15063 * methods exist in two forms,
15064 *
15065 * one that returns +nil+ when the end of file is reached, the other
15066 * raises EOFError.
15067 *
15068 * EOFError is a subclass of IOError.
15069 *
15070 * file = File.open("/etc/hosts")
15071 * file.read
15072 * file.gets #=> nil
15073 * file.readline #=> EOFError: end of file reached
15074 * file.close
15075 */
15076
15077/*
15078 * Document-class: ARGF
15079 *
15080 * == \ARGF and +ARGV+
15081 *
15082 * The \ARGF object works with the array at global variable +ARGV+
15083 * to make <tt>$stdin</tt> and file streams available in the Ruby program:
15084 *
15085 * - **ARGV** may be thought of as the <b>argument vector</b> array.
15086 *
15087 * Initially, it contains the command-line arguments and options
15088 * that are passed to the Ruby program;
15089 * the program can modify that array as it likes.
15090 *
15091 * - **ARGF** may be thought of as the <b>argument files</b> object.
15092 *
15093 * It can access file streams and/or the <tt>$stdin</tt> stream,
15094 * based on what it finds in +ARGV+.
15095 * This provides a convenient way for the command line
15096 * to specify streams for a Ruby program to read.
15097 *
15098 * == Reading
15099 *
15100 * \ARGF may read from _source_ streams,
15101 * which at any particular time are determined by the content of +ARGV+.
15102 *
15103 * === Simplest Case
15104 *
15105 * When the <i>very first</i> \ARGF read occurs with an empty +ARGV+ (<tt>[]</tt>),
15106 * the source is <tt>$stdin</tt>:
15107 *
15108 * - \File +t.rb+:
15109 *
15110 * p ['ARGV', ARGV]
15111 * p ['ARGF.read', ARGF.read]
15112 *
15113 * - Commands and outputs
15114 * (see below for the content of files +foo.txt+ and +bar.txt+):
15115 *
15116 * $ echo "Open the pod bay doors, Hal." | ruby t.rb
15117 * ["ARGV", []]
15118 * ["ARGF.read", "Open the pod bay doors, Hal.\n"]
15119 *
15120 * $ cat foo.txt bar.txt | ruby t.rb
15121 * ["ARGV", []]
15122 * ["ARGF.read", "Foo 0\nFoo 1\nBar 0\nBar 1\nBar 2\nBar 3\n"]
15123 *
15124 * === About the Examples
15125 *
15126 * Many examples here assume the existence of files +foo.txt+ and +bar.txt+:
15127 *
15128 * $ cat foo.txt
15129 * Foo 0
15130 * Foo 1
15131 * $ cat bar.txt
15132 * Bar 0
15133 * Bar 1
15134 * Bar 2
15135 * Bar 3
15136 *
15137 * === Sources in +ARGV+
15138 *
15139 * For any \ARGF read _except_ the {simplest case}[rdoc-ref:ARGF@Simplest+Case]
15140 * (that is, _except_ for the <i>very first</i> \ARGF read with an empty +ARGV+),
15141 * the sources are found in +ARGV+.
15142 *
15143 * \ARGF assumes that each element in array +ARGV+ is a potential source,
15144 * and is one of:
15145 *
15146 * - The string path to a file that may be opened as a stream.
15147 * - The character <tt>'-'</tt>, meaning stream <tt>$stdin</tt>.
15148 *
15149 * Each element that is _not_ one of these
15150 * should be removed from +ARGV+ before \ARGF accesses that source.
15151 *
15152 * In the following example:
15153 *
15154 * - Filepaths +foo.txt+ and +bar.txt+ may be retained as potential sources.
15155 * - Options <tt>--xyzzy</tt> and <tt>--mojo</tt> should be removed.
15156 *
15157 * Example:
15158 *
15159 * - \File +t.rb+:
15160 *
15161 * # Print arguments (and options, if any) found on command line.
15162 * p ['ARGV', ARGV]
15163 *
15164 * - Command and output:
15165 *
15166 * $ ruby t.rb --xyzzy --mojo foo.txt bar.txt
15167 * ["ARGV", ["--xyzzy", "--mojo", "foo.txt", "bar.txt"]]
15168 *
15169 * \ARGF's stream access considers the elements of +ARGV+, left to right:
15170 *
15171 * - \File +t.rb+:
15172 *
15173 * p "ARGV: #{ARGV}"
15174 * p "Read: #{ARGF.read}" # Read everything from all specified streams.
15175 *
15176 * - Command and output:
15177 *
15178 * $ ruby t.rb foo.txt bar.txt
15179 * "ARGV: [\"foo.txt\", \"bar.txt\"]"
15180 * "Read: Foo 0\nFoo 1\nBar 0\nBar 1\nBar 2\nBar 3\n"
15181 *
15182 * Because the value at +ARGV+ is an ordinary array,
15183 * you can manipulate it to control which sources \ARGF considers:
15184 *
15185 * - If you remove an element from +ARGV+, \ARGF will not consider the corresponding source.
15186 * - If you add an element to +ARGV+, \ARGF will consider the corresponding source.
15187 *
15188 * Each element in +ARGV+ is removed when its corresponding source is accessed;
15189 * when all sources have been accessed, the array is empty:
15190 *
15191 * - \File +t.rb+:
15192 *
15193 * until ARGV.empty? && ARGF.eof?
15194 * p "ARGV: #{ARGV}"
15195 * p "Line: #{ARGF.readline}" # Read each line from each specified stream.
15196 * end
15197 *
15198 * - Command and output:
15199 *
15200 * $ ruby t.rb foo.txt bar.txt
15201 * "ARGV: [\"foo.txt\", \"bar.txt\"]"
15202 * "Line: Foo 0\n"
15203 * "ARGV: [\"bar.txt\"]"
15204 * "Line: Foo 1\n"
15205 * "ARGV: [\"bar.txt\"]"
15206 * "Line: Bar 0\n"
15207 * "ARGV: []"
15208 * "Line: Bar 1\n"
15209 * "ARGV: []"
15210 * "Line: Bar 2\n"
15211 * "ARGV: []"
15212 * "Line: Bar 3\n"
15213 *
15214 * ==== Filepaths in +ARGV+
15215 *
15216 * The +ARGV+ array may contain filepaths the specify sources for \ARGF reading.
15217 *
15218 * This program prints what it reads from files at the paths specified
15219 * on the command line:
15220 *
15221 * - \File +t.rb+:
15222 *
15223 * p ['ARGV', ARGV]
15224 * # Read and print all content from the specified sources.
15225 * p ['ARGF.read', ARGF.read]
15226 *
15227 * - Command and output:
15228 *
15229 * $ ruby t.rb foo.txt bar.txt
15230 * ["ARGV", [foo.txt, bar.txt]
15231 * ["ARGF.read", "Foo 0\nFoo 1\nBar 0\nBar 1\nBar 2\nBar 3\n"]
15232 *
15233 * ==== Specifying <tt>$stdin</tt> in +ARGV+
15234 *
15235 * To specify stream <tt>$stdin</tt> in +ARGV+, us the character <tt>'-'</tt>:
15236 *
15237 * - \File +t.rb+:
15238 *
15239 * p ['ARGV', ARGV]
15240 * p ['ARGF.read', ARGF.read]
15241 *
15242 * - Command and output:
15243 *
15244 * $ echo "Open the pod bay doors, Hal." | ruby t.rb -
15245 * ["ARGV", ["-"]]
15246 * ["ARGF.read", "Open the pod bay doors, Hal.\n"]
15247 *
15248 * When no character <tt>'-'</tt> is given, stream <tt>$stdin</tt> is ignored.
15249 *
15250 * - Command and output:
15251 *
15252 * $ echo "Open the pod bay doors, Hal." | ruby t.rb foo.txt bar.txt
15253 * "ARGV: [\"foo.txt\", \"bar.txt\"]"
15254 * "Read: Foo 0\nFoo 1\nBar 0\nBar 1\nBar 2\nBar 3\n"
15255 *
15256 * ==== Mixtures and Repetitions in +ARGV+
15257 *
15258 * For an \ARGF reader, +ARGV+ may contain any mixture of filepaths
15259 * and character <tt>'-'</tt>, including repetitions.
15260 *
15261 * ==== Modifications to +ARGV+
15262 *
15263 * The running Ruby program may make any modifications to the +ARGV+ array;
15264 * the current value of +ARGV+ affects \ARGF reading.
15265 *
15266 * ==== Empty +ARGV+
15267 *
15268 * For an empty +ARGV+, an \ARGF read method either returns +nil+
15269 * or raises an exception, depending on the specific method.
15270 *
15271 * === More Read Methods
15272 *
15273 * As seen above, method ARGF#read reads the content of all sources
15274 * into a single string.
15275 * Other \ARGF methods provide other ways to access that content;
15276 * these include:
15277 *
15278 * - Byte access: #each_byte, #getbyte, #readbyte.
15279 * - Character access: #each_char, #getc, #readchar.
15280 * - Codepoint access: #each_codepoint.
15281 * - Line access: #each_line, #gets, #readline, #readlines.
15282 * - Source access: #read, #read_nonblock, #readpartial.
15283 *
15284 * === About \Enumerable
15285 *
15286 * \ARGF includes module Enumerable.
15287 * Virtually all methods in \Enumerable call method <tt>#each</tt> in the including class.
15288 *
15289 * <b>Note well</b>: In \ARGF, method #each returns data from the _sources_,
15290 * _not_ from +ARGV+;
15291 * therefore, for example, <tt>ARGF#entries</tt> returns an array of lines from the sources,
15292 * not an array of the strings from +ARGV+:
15293 *
15294 * - \File +t.rb+:
15295 *
15296 * p ['ARGV', ARGV]
15297 * p ['ARGF.entries', ARGF.entries]
15298 *
15299 * - Command and output:
15300 *
15301 * $ ruby t.rb foo.txt bar.txt
15302 * ["ARGV", ["foo.txt", "bar.txt"]]
15303 * ["ARGF.entries", ["Foo 0\n", "Foo 1\n", "Bar 0\n", "Bar 1\n", "Bar 2\n", "Bar 3\n"]]
15304 *
15305 * == Writing
15306 *
15307 * If <i>inplace mode</i> is in effect,
15308 * \ARGF may write to target streams,
15309 * which at any particular time are determined by the content of ARGV.
15310 *
15311 * Methods about inplace mode:
15312 *
15313 * - #inplace_mode
15314 * - #inplace_mode=
15315 * - #to_write_io
15316 *
15317 * Methods for writing:
15318 *
15319 * - #print
15320 * - #printf
15321 * - #putc
15322 * - #puts
15323 * - #write
15324 *
15325 */
15326
15327/*
15328 * An instance of class \IO (commonly called a _stream_)
15329 * represents an input/output stream in the underlying operating system.
15330 * Class \IO is the basis for input and output in Ruby.
15331 *
15332 * Class File is the only class in the Ruby core that is a subclass of \IO.
15333 * Some classes in the Ruby standard library are also subclasses of \IO;
15334 * these include TCPSocket and UDPSocket.
15335 *
15336 * The global constant ARGF (also accessible as <tt>$<</tt>)
15337 * provides an IO-like stream that allows access to all file paths
15338 * found in ARGV (or found in STDIN if ARGV is empty).
15339 * ARGF is not itself a subclass of \IO.
15340 *
15341 * Class StringIO provides an IO-like stream that handles a String.
15342 * StringIO is not itself a subclass of \IO.
15343 *
15344 * Important objects based on \IO include:
15345 *
15346 * - $stdin.
15347 * - $stdout.
15348 * - $stderr.
15349 * - Instances of class File.
15350 *
15351 * An instance of \IO may be created using:
15352 *
15353 * - IO.new: returns a new \IO object for the given integer file descriptor.
15354 * - IO.open: passes a new \IO object to the given block.
15355 * - IO.popen: returns a new \IO object that is connected to the $stdin and $stdout
15356 * of a newly-launched subprocess.
15357 * - Kernel#open: Returns a new \IO object connected to a given source:
15358 * stream, file, or subprocess.
15359 *
15360 * Like a File stream, an \IO stream has:
15361 *
15362 * - A read/write mode, which may be read-only, write-only, or read/write;
15363 * see {Read/Write Mode}[rdoc-ref:File@ReadWrite+Mode].
15364 * - A data mode, which may be text-only or binary;
15365 * see {Data Mode}[rdoc-ref:File@Data+Mode].
15366 * - Internal and external encodings;
15367 * see {Encodings}[rdoc-ref:File@Encodings].
15368 *
15369 * And like other \IO streams, it has:
15370 *
15371 * - A position, which determines where in the stream the next
15372 * read or write is to occur;
15373 * see {Position}[rdoc-ref:IO@Position].
15374 * - A line number, which is a special, line-oriented, "position"
15375 * (different from the position mentioned above);
15376 * see {Line Number}[rdoc-ref:IO@Line+Number].
15377 *
15378 * == Extension <tt>io/console</tt>
15379 *
15380 * Extension <tt>io/console</tt> provides numerous methods
15381 * for interacting with the console;
15382 * requiring it adds numerous methods to class \IO.
15383 *
15384 * == Example Files
15385 *
15386 * Many examples here use these variables:
15387 *
15388 * :include: doc/examples/files.rdoc
15389 *
15390 * == Open Options
15391 *
15392 * A number of \IO methods accept optional keyword arguments
15393 * that determine how a new stream is to be opened:
15394 *
15395 * - +:mode+: Stream mode.
15396 * - +:flags+: Integer file open flags;
15397 * If +mode+ is also given, the two are bitwise-ORed.
15398 * - +:external_encoding+: External encoding for the stream.
15399 * - +:internal_encoding+: Internal encoding for the stream.
15400 * <tt>'-'</tt> is a synonym for the default internal encoding.
15401 * If the value is +nil+ no conversion occurs.
15402 * - +:encoding+: Specifies external and internal encodings as <tt>'extern:intern'</tt>.
15403 * - +:textmode+: If a truthy value, specifies the mode as text-only, binary otherwise.
15404 * - +:binmode+: If a truthy value, specifies the mode as binary, text-only otherwise.
15405 * - +:autoclose+: If a truthy value, specifies that the +fd+ will close
15406 * when the stream closes; otherwise it remains open.
15407 * - +:path+: If a string value is provided, it is used in #inspect and is available as
15408 * #path method.
15409 *
15410 * Also available are the options offered in String#encode,
15411 * which may control conversion between external and internal encoding.
15412 *
15413 * == Basic \IO
15414 *
15415 * You can perform basic stream \IO with these methods,
15416 * which typically operate on multi-byte strings:
15417 *
15418 * - IO#read: Reads and returns some or all of the remaining bytes from the stream.
15419 * - IO#write: Writes zero or more strings to the stream;
15420 * each given object that is not already a string is converted via +to_s+.
15421 *
15422 * === Position
15423 *
15424 * An \IO stream has a nonnegative integer _position_,
15425 * which is the byte offset at which the next read or write is to occur.
15426 * A new stream has position zero (and line number zero);
15427 * method +rewind+ resets the position (and line number) to zero.
15428 *
15429 * These methods discard {buffers}[rdoc-ref:IO@Buffering] and the
15430 * Encoding::Converter instances used for that \IO.
15431 *
15432 * The relevant methods:
15433 *
15434 * - IO#tell (aliased as +#pos+): Returns the current position (in bytes) in the stream.
15435 * - IO#pos=: Sets the position of the stream to a given integer +new_position+ (in bytes).
15436 * - IO#seek: Sets the position of the stream to a given integer +offset+ (in bytes),
15437 * relative to a given position +whence+
15438 * (indicating the beginning, end, or current position).
15439 * - IO#rewind: Positions the stream at the beginning (also resetting the line number).
15440 *
15441 * === Open and Closed Streams
15442 *
15443 * A new \IO stream may be open for reading, open for writing, or both.
15444 *
15445 * A stream is automatically closed when claimed by the garbage collector.
15446 *
15447 * Attempted reading or writing on a closed stream raises an exception.
15448 *
15449 * The relevant methods:
15450 *
15451 * - IO#close: Closes the stream for both reading and writing.
15452 * - IO#close_read: Closes the stream for reading.
15453 * - IO#close_write: Closes the stream for writing.
15454 * - IO#closed?: Returns whether the stream is closed.
15455 *
15456 * === End-of-Stream
15457 *
15458 * You can query whether a stream is positioned at its end:
15459 *
15460 * - IO#eof? (also aliased as +#eof+): Returns whether the stream is at end-of-stream.
15461 *
15462 * You can reposition to end-of-stream by using method IO#seek:
15463 *
15464 * f = File.new('t.txt')
15465 * f.eof? # => false
15466 * f.seek(0, :END)
15467 * f.eof? # => true
15468 * f.close
15469 *
15470 * Or by reading all stream content (which is slower than using IO#seek):
15471 *
15472 * f.rewind
15473 * f.eof? # => false
15474 * f.read # => "First line\nSecond line\n\nFourth line\nFifth line\n"
15475 * f.eof? # => true
15476 *
15477 * == Line \IO
15478 *
15479 * Class \IO supports line-oriented
15480 * {input}[rdoc-ref:IO@Line+Input] and {output}[rdoc-ref:IO@Line+Output]
15481 *
15482 * === Line Input
15483 *
15484 * Class \IO supports line-oriented input for
15485 * {files}[rdoc-ref:IO@File+Line+Input] and {IO streams}[rdoc-ref:IO@Stream+Line+Input].
15486 *
15487 * ==== Line Input Options
15488 *
15489 * Optional keyword argument +chomp+ (default: +false+)
15490 * specifies whether line separators are to be excluded from the result of a read.
15491 *
15492 * ==== \File Line Input
15493 *
15494 * You can read lines from a file using these methods:
15495 *
15496 * - IO.foreach: Reads each line and passes it to the given block.
15497 * - IO.readlines: Reads and returns all lines in an array.
15498 *
15499 * For each of these methods:
15500 *
15501 * - You can specify {open options}[rdoc-ref:IO@Open+Options].
15502 * - Line parsing depends on the effective <i>line separator</i>;
15503 * see {Line Separator}[rdoc-ref:IO@Line+Separator].
15504 * - The length of each returned line depends on the effective <i>line limit</i>;
15505 * see {Line Limit}[rdoc-ref:IO@Line+Limit].
15506 *
15507 * ==== Stream Line Input
15508 *
15509 * You can read lines from an \IO stream using these methods:
15510 *
15511 * - IO#each_line: Reads each remaining line, passing it to the given block.
15512 * - IO#gets: Returns the next line.
15513 * - IO#readline: Like #gets, but raises an exception at end-of-stream.
15514 * - IO#readlines: Returns all remaining lines in an array.
15515 *
15516 * For each of these methods:
15517 *
15518 * - Reading may begin mid-line,
15519 * depending on the stream's _position_;
15520 * see {Position}[rdoc-ref:IO@Position].
15521 * - Line parsing depends on the effective <i>line separator</i>;
15522 * see {Line Separator}[rdoc-ref:IO@Line+Separator].
15523 * - The length of each returned line depends on the effective <i>line limit</i>;
15524 * see {Line Limit}[rdoc-ref:IO@Line+Limit].
15525 *
15526 * ===== Line Separator
15527 *
15528 * Each of the {line input methods}[rdoc-ref:IO@Line+Input] uses a <i>line separator</i>:
15529 * the string that determines what is considered a line;
15530 * it is sometimes called the <i>input record separator</i>.
15531 *
15532 * The default line separator is taken from global variable <tt>$/</tt>,
15533 * whose initial value is <tt>"\n"</tt>.
15534 *
15535 * Generally, the line to be read next is all data
15536 * from the current {position}[rdoc-ref:IO@Position]
15537 * to the next line separator
15538 * (but see {Special Line Separator Values}[rdoc-ref:IO@Special+Line+Separator+Values]):
15539 *
15540 * f = File.new('t.txt')
15541 * # Method gets with no sep argument returns the next line, according to $/.
15542 * f.gets # => "First line\n"
15543 * f.gets # => "Second line\n"
15544 * f.gets # => "\n"
15545 * f.gets # => "Fourth line\n"
15546 * f.gets # => "Fifth line\n"
15547 * f.close
15548 *
15549 * You can use a different line separator by passing argument +sep+:
15550 *
15551 * f = File.new('t.txt')
15552 * f.gets('l') # => "First l"
15553 * f.gets('li') # => "ine\nSecond li"
15554 * f.gets('lin') # => "ne\n\nFourth lin"
15555 * f.gets # => "e\n"
15556 * f.close
15557 *
15558 * Or by setting global variable <tt>$/</tt>:
15559 *
15560 * f = File.new('t.txt')
15561 * $/ = 'l'
15562 * f.gets # => "First l"
15563 * f.gets # => "ine\nSecond l"
15564 * f.gets # => "ine\n\nFourth l"
15565 * f.close
15566 *
15567 * ===== Special Line Separator Values
15568 *
15569 * Each of the {line input methods}[rdoc-ref:IO@Line+Input]
15570 * accepts two special values for parameter +sep+:
15571 *
15572 * - +nil+: The entire stream is to be read ("slurped") into a single string:
15573 *
15574 * f = File.new('t.txt')
15575 * f.gets(nil) # => "First line\nSecond line\n\nFourth line\nFifth line\n"
15576 * f.close
15577 *
15578 * - <tt>''</tt> (the empty string): The next "paragraph" is to be read
15579 * (paragraphs being separated by two consecutive line separators):
15580 *
15581 * f = File.new('t.txt')
15582 * f.gets('') # => "First line\nSecond line\n\n"
15583 * f.gets('') # => "Fourth line\nFifth line\n"
15584 * f.close
15585 *
15586 * ===== Line Limit
15587 *
15588 * Each of the {line input methods}[rdoc-ref:IO@Line+Input]
15589 * uses an integer <i>line limit</i>,
15590 * which restricts the number of bytes that may be returned.
15591 * (A multi-byte character will not be split, and so a returned line may be slightly longer
15592 * than the limit).
15593 *
15594 * The default limit value is <tt>-1</tt>;
15595 * any negative limit value means that there is no limit.
15596 *
15597 * If there is no limit, the line is determined only by +sep+.
15598 *
15599 * # Text with 1-byte characters.
15600 * File.open('t.txt') {|f| f.gets(1) } # => "F"
15601 * File.open('t.txt') {|f| f.gets(2) } # => "Fi"
15602 * File.open('t.txt') {|f| f.gets(3) } # => "Fir"
15603 * File.open('t.txt') {|f| f.gets(4) } # => "Firs"
15604 * # No more than one line.
15605 * File.open('t.txt') {|f| f.gets(10) } # => "First line"
15606 * File.open('t.txt') {|f| f.gets(11) } # => "First line\n"
15607 * File.open('t.txt') {|f| f.gets(12) } # => "First line\n"
15608 *
15609 * # Text with 3-byte characters, which will not be split.
15610 * File.read('t.ja') # => "こんにちは"
15611 * File.open('t.ja') {|f| f.gets(1).size } # => 1
15612 * File.open('t.ja') {|f| f.gets(2).size } # => 1
15613 * File.open('t.ja') {|f| f.gets(3).size } # => 1
15614 * File.open('t.ja') {|f| f.gets(4).size } # => 2
15615 * File.open('t.ja') {|f| f.gets(5).size } # => 2
15616 *
15617 * ===== Line Separator and Line Limit
15618 *
15619 * With arguments +sep+ and +limit+ given, combines the two behaviors:
15620 *
15621 * - Returns the next line as determined by line separator +sep+.
15622 * - But returns no more bytes than are allowed by the limit +limit+.
15623 *
15624 * Example:
15625 *
15626 * File.open('t.txt') {|f| f.gets('li', 20) } # => "First li"
15627 * File.open('t.txt') {|f| f.gets('li', 2) } # => "Fi"
15628 *
15629 * ===== Line Number
15630 *
15631 * A readable \IO stream has a non-negative integer <i>line number</i>:
15632 *
15633 * - IO#lineno: Returns the line number.
15634 * - IO#lineno=: Resets and returns the line number.
15635 *
15636 * Unless modified by a call to method IO#lineno=,
15637 * the line number is the number of lines read
15638 * by certain line-oriented methods,
15639 * according to the effective {line separator}[rdoc-ref:IO@Line+Separator]:
15640 *
15641 * - IO.foreach: Increments the line number on each call to the block.
15642 * - IO#each_line: Increments the line number on each call to the block.
15643 * - IO#gets: Increments the line number.
15644 * - IO#readline: Increments the line number.
15645 * - IO#readlines: Increments the line number for each line read.
15646 *
15647 * A new stream is initially has line number zero (and position zero);
15648 * method +rewind+ resets the line number (and position) to zero:
15649 *
15650 * f = File.new('t.txt')
15651 * f.lineno # => 0
15652 * f.gets # => "First line\n"
15653 * f.lineno # => 1
15654 * f.rewind
15655 * f.lineno # => 0
15656 * f.close
15657 *
15658 * Reading lines from a stream usually changes its line number:
15659 *
15660 * f = File.new('t.txt', 'r')
15661 * f.lineno # => 0
15662 * f.readline # => "This is line one.\n"
15663 * f.lineno # => 1
15664 * f.readline # => "This is the second line.\n"
15665 * f.lineno # => 2
15666 * f.readline # => "Here's the third line.\n"
15667 * f.lineno # => 3
15668 * f.eof? # => true
15669 * f.close
15670 *
15671 * Iterating over lines in a stream usually changes its line number:
15672 *
15673 * File.open('t.txt') do |f|
15674 * f.each_line do |line|
15675 * p "position=#{f.pos} eof?=#{f.eof?} lineno=#{f.lineno}"
15676 * end
15677 * end
15678 *
15679 * Output:
15680 *
15681 * "position=11 eof?=false lineno=1"
15682 * "position=23 eof?=false lineno=2"
15683 * "position=24 eof?=false lineno=3"
15684 * "position=36 eof?=false lineno=4"
15685 * "position=47 eof?=true lineno=5"
15686 *
15687 * Unlike the stream's {position}[rdoc-ref:IO@Position],
15688 * the line number does not affect where the next read or write will occur:
15689 *
15690 * f = File.new('t.txt')
15691 * f.lineno = 1000
15692 * f.lineno # => 1000
15693 * f.gets # => "First line\n"
15694 * f.lineno # => 1001
15695 * f.close
15696 *
15697 * Associated with the line number is the global variable <tt>$.</tt>:
15698 *
15699 * - When a stream is opened, <tt>$.</tt> is not set;
15700 * its value is left over from previous activity in the process:
15701 *
15702 * $. = 41
15703 * f = File.new('t.txt')
15704 * $. = 41
15705 * # => 41
15706 * f.close
15707 *
15708 * - When a stream is read, <tt>$.</tt> is set to the line number for that stream:
15709 *
15710 * f0 = File.new('t.txt')
15711 * f1 = File.new('t.dat')
15712 * f0.readlines # => ["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"]
15713 * $. # => 5
15714 * f1.readlines # => ["\xFE\xFF\x99\x90\x99\x91\x99\x92\x99\x93\x99\x94"]
15715 * $. # => 1
15716 * f0.close
15717 * f1.close
15718 *
15719 * - Methods IO#rewind and IO#seek do not affect <tt>$.</tt>:
15720 *
15721 * f = File.new('t.txt')
15722 * f.readlines # => ["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"]
15723 * $. # => 5
15724 * f.rewind
15725 * f.seek(0, :SET)
15726 * $. # => 5
15727 * f.close
15728 *
15729 * === Line Output
15730 *
15731 * You can write to an \IO stream line-by-line using this method:
15732 *
15733 * - IO#puts: Writes objects to the stream.
15734 *
15735 * == Character \IO
15736 *
15737 * You can process an \IO stream character-by-character using these methods:
15738 *
15739 * - IO#getc: Reads and returns the next character from the stream.
15740 * - IO#readchar: Like #getc, but raises an exception at end-of-stream.
15741 * - IO#ungetc: Pushes back ("unshifts") a character or integer onto the stream.
15742 * - IO#putc: Writes a character to the stream.
15743 * - IO#each_char: Reads each remaining character in the stream,
15744 * passing the character to the given block.
15745 *
15746 * == Byte \IO
15747 *
15748 * You can process an \IO stream byte-by-byte using these methods:
15749 *
15750 * - IO#getbyte: Returns the next 8-bit byte as an integer in range 0..255.
15751 * - IO#readbyte: Like #getbyte, but raises an exception if at end-of-stream.
15752 * - IO#ungetbyte: Pushes back ("unshifts") a byte back onto the stream.
15753 * - IO#each_byte: Reads each remaining byte in the stream,
15754 * passing the byte to the given block.
15755 *
15756 * == Codepoint \IO
15757 *
15758 * You can process an \IO stream codepoint-by-codepoint:
15759 *
15760 * - IO#each_codepoint: Reads each remaining codepoint, passing it to the given block.
15761 *
15762 * == What's Here
15763 *
15764 * First, what's elsewhere. Class \IO:
15765 *
15766 * - Inherits from {class Object}[rdoc-ref:Object@Whats+Here].
15767 * - Includes {module Enumerable}[rdoc-ref:Enumerable@Whats+Here],
15768 * which provides dozens of additional methods.
15769 *
15770 * Here, class \IO provides methods that are useful for:
15771 *
15772 * - {Creating}[rdoc-ref:IO@Creating]
15773 * - {Reading}[rdoc-ref:IO@Reading]
15774 * - {Writing}[rdoc-ref:IO@Writing]
15775 * - {Positioning}[rdoc-ref:IO@Positioning]
15776 * - {Iterating}[rdoc-ref:IO@Iterating]
15777 * - {Settings}[rdoc-ref:IO@Settings]
15778 * - {Querying}[rdoc-ref:IO@Querying]
15779 * - {Buffering}[rdoc-ref:IO@Buffering]
15780 * - {Low-Level Access}[rdoc-ref:IO@Low-Level+Access]
15781 * - {Other}[rdoc-ref:IO@Other]
15782 *
15783 * === Creating
15784 *
15785 * - ::new (aliased as ::for_fd): Creates and returns a new \IO object for the given
15786 * integer file descriptor.
15787 * - ::open: Creates a new \IO object.
15788 * - ::pipe: Creates a connected pair of reader and writer \IO objects.
15789 * - ::popen: Creates an \IO object to interact with a subprocess.
15790 * - ::select: Selects which given \IO instances are ready for reading,
15791 * writing, or have pending exceptions.
15792 *
15793 * === Reading
15794 *
15795 * - ::binread: Returns a binary string with all or a subset of bytes
15796 * from the given file.
15797 * - ::read: Returns a string with all or a subset of bytes from the given file.
15798 * - ::readlines: Returns an array of strings, which are the lines from the given file.
15799 * - #getbyte: Returns the next 8-bit byte read from +self+ as an integer.
15800 * - #getc: Returns the next character read from +self+ as a string.
15801 * - #gets: Returns the line read from +self+.
15802 * - #pread: Returns all or the next _n_ bytes read from +self+,
15803 * not updating the receiver's offset.
15804 * - #read: Returns all remaining or the next _n_ bytes read from +self+
15805 * for a given _n_.
15806 * - #read_nonblock: the next _n_ bytes read from +self+ for a given _n_,
15807 * in non-block mode.
15808 * - #readbyte: Returns the next byte read from +self+;
15809 * same as #getbyte, but raises an exception on end-of-stream.
15810 * - #readchar: Returns the next character read from +self+;
15811 * same as #getc, but raises an exception on end-of-stream.
15812 * - #readline: Returns the next line read from +self+;
15813 * same as #getline, but raises an exception of end-of-stream.
15814 * - #readlines: Returns an array of all lines read read from +self+.
15815 * - #readpartial: Returns up to the given number of bytes from +self+.
15816 *
15817 * === Writing
15818 *
15819 * - ::binwrite: Writes the given string to the file at the given filepath,
15820 * in binary mode.
15821 * - ::write: Writes the given string to +self+.
15822 * - #<<: Appends the given string to +self+.
15823 * - #print: Prints last read line or given objects to +self+.
15824 * - #printf: Writes to +self+ based on the given format string and objects.
15825 * - #putc: Writes a character to +self+.
15826 * - #puts: Writes lines to +self+, making sure line ends with a newline.
15827 * - #pwrite: Writes the given string at the given offset,
15828 * not updating the receiver's offset.
15829 * - #write: Writes one or more given strings to +self+.
15830 * - #write_nonblock: Writes one or more given strings to +self+ in non-blocking mode.
15831 *
15832 * === Positioning
15833 *
15834 * - #lineno: Returns the current line number in +self+.
15835 * - #lineno=: Sets the line number is +self+.
15836 * - #pos (aliased as #tell): Returns the current byte offset in +self+.
15837 * - #pos=: Sets the byte offset in +self+.
15838 * - #reopen: Reassociates +self+ with a new or existing \IO stream.
15839 * - #rewind: Positions +self+ to the beginning of input.
15840 * - #seek: Sets the offset for +self+ relative to given position.
15841 *
15842 * === Iterating
15843 *
15844 * - ::foreach: Yields each line of given file to the block.
15845 * - #each (aliased as #each_line): Calls the given block
15846 * with each successive line in +self+.
15847 * - #each_byte: Calls the given block with each successive byte in +self+
15848 * as an integer.
15849 * - #each_char: Calls the given block with each successive character in +self+
15850 * as a string.
15851 * - #each_codepoint: Calls the given block with each successive codepoint in +self+
15852 * as an integer.
15853 *
15854 * === Settings
15855 *
15856 * - #autoclose=: Sets whether +self+ auto-closes.
15857 * - #binmode: Sets +self+ to binary mode.
15858 * - #close: Closes +self+.
15859 * - #close_on_exec=: Sets the close-on-exec flag.
15860 * - #close_read: Closes +self+ for reading.
15861 * - #close_write: Closes +self+ for writing.
15862 * - #set_encoding: Sets the encoding for +self+.
15863 * - #set_encoding_by_bom: Sets the encoding for +self+, based on its
15864 * Unicode byte-order-mark.
15865 * - #sync=: Sets the sync-mode to the given value.
15866 *
15867 * === Querying
15868 *
15869 * - #autoclose?: Returns whether +self+ auto-closes.
15870 * - #binmode?: Returns whether +self+ is in binary mode.
15871 * - #close_on_exec?: Returns the close-on-exec flag for +self+.
15872 * - #closed?: Returns whether +self+ is closed.
15873 * - #eof? (aliased as #eof): Returns whether +self+ is at end-of-stream.
15874 * - #external_encoding: Returns the external encoding object for +self+.
15875 * - #fileno (aliased as #to_i): Returns the integer file descriptor for +self+
15876 * - #internal_encoding: Returns the internal encoding object for +self+.
15877 * - #pid: Returns the process ID of a child process associated with +self+,
15878 * if +self+ was created by ::popen.
15879 * - #stat: Returns the File::Stat object containing status information for +self+.
15880 * - #sync: Returns whether +self+ is in sync-mode.
15881 * - #tty? (aliased as #isatty): Returns whether +self+ is a terminal.
15882 *
15883 * === Buffering
15884 *
15885 * - #fdatasync: Immediately writes all buffered data in +self+ to disk.
15886 * - #flush: Flushes any buffered data within +self+ to the underlying
15887 * operating system.
15888 * - #fsync: Immediately writes all buffered data and attributes in +self+ to disk.
15889 * - #ungetbyte: Prepends buffer for +self+ with given integer byte or string.
15890 * - #ungetc: Prepends buffer for +self+ with given string.
15891 *
15892 * === Low-Level Access
15893 *
15894 * - ::sysopen: Opens the file given by its path,
15895 * returning the integer file descriptor.
15896 * - #advise: Announces the intention to access data from +self+ in a specific way.
15897 * - #fcntl: Passes a low-level command to the file specified
15898 * by the given file descriptor.
15899 * - #ioctl: Passes a low-level command to the device specified
15900 * by the given file descriptor.
15901 * - #sysread: Returns up to the next _n_ bytes read from self using a low-level read.
15902 * - #sysseek: Sets the offset for +self+.
15903 * - #syswrite: Writes the given string to +self+ using a low-level write.
15904 *
15905 * === Other
15906 *
15907 * - ::copy_stream: Copies data from a source to a destination,
15908 * each of which is a filepath or an \IO-like object.
15909 * - ::try_convert: Returns a new \IO object resulting from converting
15910 * the given object.
15911 * - #inspect: Returns the string representation of +self+.
15912 *
15913 */
15914
15915void
15916Init_IO(void)
15917{
15918 VALUE rb_cARGF;
15919#ifdef __CYGWIN__
15920#include <sys/cygwin.h>
15921 static struct __cygwin_perfile pf[] =
15922 {
15923 {"", O_RDONLY | O_BINARY},
15924 {"", O_WRONLY | O_BINARY},
15925 {"", O_RDWR | O_BINARY},
15926 {"", O_APPEND | O_BINARY},
15927 {NULL, 0}
15928 };
15929 cygwin_internal(CW_PERFILE, pf);
15930#endif
15931
15932 rb_eIOError = rb_define_class("IOError", rb_eStandardError);
15933 rb_eEOFError = rb_define_class("EOFError", rb_eIOError);
15934
15935 id_write = rb_intern_const("write");
15936 id_read = rb_intern_const("read");
15937 id_flush = rb_intern_const("flush");
15938 id_readpartial = rb_intern_const("readpartial");
15939 id_set_encoding = rb_intern_const("set_encoding");
15940 id_fileno = rb_intern_const("fileno");
15941
15942 rb_define_global_function("syscall", rb_f_syscall, -1);
15943
15944 rb_define_global_function("open", rb_f_open, -1);
15945 rb_define_global_function("printf", rb_f_printf, -1);
15946 rb_define_global_function("print", rb_f_print, -1);
15947 rb_define_global_function("putc", rb_f_putc, 1);
15948 rb_define_global_function("puts", rb_f_puts, -1);
15949 rb_define_global_function("gets", rb_f_gets, -1);
15950 rb_define_global_function("readline", rb_f_readline, -1);
15951 rb_define_global_function("select", rb_f_select, -1);
15952
15953 rb_define_global_function("readlines", rb_f_readlines, -1);
15954
15955 rb_define_global_function("`", rb_f_backquote, 1);
15956
15957 rb_define_global_function("p", rb_f_p, -1);
15958 rb_define_method(rb_mKernel, "display", rb_obj_display, -1);
15959
15960 rb_cIO = rb_define_class("IO", rb_cObject);
15962
15963 /* Can be raised by IO operations when IO#timeout= is set. */
15964 rb_eIOTimeoutError = rb_define_class_under(rb_cIO, "TimeoutError", rb_eIOError);
15965
15966 /* Readable event mask for IO#wait. */
15967 rb_define_const(rb_cIO, "READABLE", INT2NUM(RUBY_IO_READABLE));
15968 /* Writable event mask for IO#wait. */
15969 rb_define_const(rb_cIO, "WRITABLE", INT2NUM(RUBY_IO_WRITABLE));
15970 /* Priority event mask for IO#wait. */
15971 rb_define_const(rb_cIO, "PRIORITY", INT2NUM(RUBY_IO_PRIORITY));
15972
15973 /* exception to wait for reading. see IO.select. */
15974 rb_mWaitReadable = rb_define_module_under(rb_cIO, "WaitReadable");
15975 /* exception to wait for writing. see IO.select. */
15976 rb_mWaitWritable = rb_define_module_under(rb_cIO, "WaitWritable");
15977 /* exception to wait for reading by EAGAIN. see IO.select. */
15978 rb_eEAGAINWaitReadable = rb_define_class_under(rb_cIO, "EAGAINWaitReadable", rb_eEAGAIN);
15979 rb_include_module(rb_eEAGAINWaitReadable, rb_mWaitReadable);
15980 /* exception to wait for writing by EAGAIN. see IO.select. */
15981 rb_eEAGAINWaitWritable = rb_define_class_under(rb_cIO, "EAGAINWaitWritable", rb_eEAGAIN);
15982 rb_include_module(rb_eEAGAINWaitWritable, rb_mWaitWritable);
15983#if EAGAIN == EWOULDBLOCK
15984 /* same as IO::EAGAINWaitReadable */
15985 rb_define_const(rb_cIO, "EWOULDBLOCKWaitReadable", rb_eEAGAINWaitReadable);
15986 /* same as IO::EAGAINWaitWritable */
15987 rb_define_const(rb_cIO, "EWOULDBLOCKWaitWritable", rb_eEAGAINWaitWritable);
15988#else
15989 /* exception to wait for reading by EWOULDBLOCK. see IO.select. */
15990 rb_eEWOULDBLOCKWaitReadable = rb_define_class_under(rb_cIO, "EWOULDBLOCKWaitReadable", rb_eEWOULDBLOCK);
15991 rb_include_module(rb_eEWOULDBLOCKWaitReadable, rb_mWaitReadable);
15992 /* exception to wait for writing by EWOULDBLOCK. see IO.select. */
15993 rb_eEWOULDBLOCKWaitWritable = rb_define_class_under(rb_cIO, "EWOULDBLOCKWaitWritable", rb_eEWOULDBLOCK);
15994 rb_include_module(rb_eEWOULDBLOCKWaitWritable, rb_mWaitWritable);
15995#endif
15996 /* exception to wait for reading by EINPROGRESS. see IO.select. */
15997 rb_eEINPROGRESSWaitReadable = rb_define_class_under(rb_cIO, "EINPROGRESSWaitReadable", rb_eEINPROGRESS);
15998 rb_include_module(rb_eEINPROGRESSWaitReadable, rb_mWaitReadable);
15999 /* exception to wait for writing by EINPROGRESS. see IO.select. */
16000 rb_eEINPROGRESSWaitWritable = rb_define_class_under(rb_cIO, "EINPROGRESSWaitWritable", rb_eEINPROGRESS);
16001 rb_include_module(rb_eEINPROGRESSWaitWritable, rb_mWaitWritable);
16002
16003#if 0
16004 /* This is necessary only for forcing rdoc handle File::open */
16005 rb_define_singleton_method(rb_cFile, "open", rb_io_s_open, -1);
16006#endif
16007
16008 rb_define_alloc_func(rb_cIO, io_alloc);
16009 rb_define_singleton_method(rb_cIO, "new", rb_io_s_new, -1);
16010 rb_define_singleton_method(rb_cIO, "open", rb_io_s_open, -1);
16011 rb_define_singleton_method(rb_cIO, "sysopen", rb_io_s_sysopen, -1);
16012 rb_define_singleton_method(rb_cIO, "for_fd", rb_io_s_for_fd, -1);
16013 rb_define_singleton_method(rb_cIO, "popen", rb_io_s_popen, -1);
16014 rb_define_singleton_method(rb_cIO, "foreach", rb_io_s_foreach, -1);
16015 rb_define_singleton_method(rb_cIO, "readlines", rb_io_s_readlines, -1);
16016 rb_define_singleton_method(rb_cIO, "read", rb_io_s_read, -1);
16017 rb_define_singleton_method(rb_cIO, "binread", rb_io_s_binread, -1);
16018 rb_define_singleton_method(rb_cIO, "write", rb_io_s_write, -1);
16019 rb_define_singleton_method(rb_cIO, "binwrite", rb_io_s_binwrite, -1);
16020 rb_define_singleton_method(rb_cIO, "select", rb_f_select, -1);
16021 rb_define_singleton_method(rb_cIO, "pipe", rb_io_s_pipe, -1);
16022 rb_define_singleton_method(rb_cIO, "try_convert", rb_io_s_try_convert, 1);
16023 rb_define_singleton_method(rb_cIO, "copy_stream", rb_io_s_copy_stream, -1);
16024
16025 rb_define_method(rb_cIO, "initialize", rb_io_initialize, -1);
16026
16028 rb_define_hooked_variable("$,", &rb_output_fs, 0, rb_deprecated_str_setter);
16029
16030 rb_default_rs = rb_fstring_lit("\n"); /* avoid modifying RS_default */
16031 rb_vm_register_global_object(rb_default_rs);
16032 rb_rs = rb_default_rs;
16034 rb_define_hooked_variable("$/", &rb_rs, 0, deprecated_rs_setter);
16035 rb_gvar_ractor_local("$/"); // not local but ractor safe
16036 rb_define_hooked_variable("$-0", &rb_rs, 0, deprecated_rs_setter);
16037 rb_gvar_ractor_local("$-0"); // not local but ractor safe
16038 rb_define_hooked_variable("$\\", &rb_output_rs, 0, rb_deprecated_str_setter);
16039
16040 rb_define_virtual_variable("$_", get_LAST_READ_LINE, set_LAST_READ_LINE);
16041 rb_gvar_ractor_local("$_");
16042 rb_gvar_box_dynamic("$_");
16043
16044 rb_define_method(rb_cIO, "initialize_copy", rb_io_init_copy, 1);
16045 rb_define_method(rb_cIO, "reopen", rb_io_reopen, -1);
16046
16047 rb_define_method(rb_cIO, "print", rb_io_print, -1);
16048 rb_define_method(rb_cIO, "putc", rb_io_putc, 1);
16049 rb_define_method(rb_cIO, "puts", rb_io_puts, -1);
16050 rb_define_method(rb_cIO, "printf", rb_io_printf, -1);
16051
16052 rb_define_method(rb_cIO, "each", rb_io_each_line, -1);
16053 rb_define_method(rb_cIO, "each_line", rb_io_each_line, -1);
16054 rb_define_method(rb_cIO, "each_byte", rb_io_each_byte, 0);
16055 rb_define_method(rb_cIO, "each_char", rb_io_each_char, 0);
16056 rb_define_method(rb_cIO, "each_codepoint", rb_io_each_codepoint, 0);
16057
16058 rb_define_method(rb_cIO, "syswrite", rb_io_syswrite, 1);
16059 rb_define_method(rb_cIO, "sysread", rb_io_sysread, -1);
16060
16061 rb_define_method(rb_cIO, "pread", rb_io_pread, -1);
16062 rb_define_method(rb_cIO, "pwrite", rb_io_pwrite, 2);
16063
16064 rb_define_method(rb_cIO, "fileno", rb_io_fileno, 0);
16065 rb_define_alias(rb_cIO, "to_i", "fileno");
16066 rb_define_method(rb_cIO, "to_io", rb_io_to_io, 0);
16067
16068 rb_define_method(rb_cIO, "timeout", rb_io_timeout, 0);
16069 rb_define_method(rb_cIO, "timeout=", rb_io_set_timeout, 1);
16070
16071 rb_define_method(rb_cIO, "fsync", rb_io_fsync, 0);
16072 rb_define_method(rb_cIO, "fdatasync", rb_io_fdatasync, 0);
16073 rb_define_method(rb_cIO, "sync", rb_io_sync, 0);
16074 rb_define_method(rb_cIO, "sync=", rb_io_set_sync, 1);
16075
16076 rb_define_method(rb_cIO, "lineno", rb_io_lineno, 0);
16077 rb_define_method(rb_cIO, "lineno=", rb_io_set_lineno, 1);
16078
16079 rb_define_method(rb_cIO, "readlines", rb_io_readlines, -1);
16080
16081 rb_define_method(rb_cIO, "readpartial", io_readpartial, -1);
16082 rb_define_method(rb_cIO, "read", io_read, -1);
16083 rb_define_method(rb_cIO, "write", io_write_m, -1);
16084 rb_define_method(rb_cIO, "gets", rb_io_gets_m, -1);
16085 rb_define_method(rb_cIO, "getc", rb_io_getc, 0);
16086 rb_define_method(rb_cIO, "getbyte", rb_io_getbyte, 0);
16087 rb_define_method(rb_cIO, "readchar", rb_io_readchar, 0);
16088 rb_define_method(rb_cIO, "readbyte", rb_io_readbyte, 0);
16089 rb_define_method(rb_cIO, "ungetbyte",rb_io_ungetbyte, 1);
16090 rb_define_method(rb_cIO, "ungetc",rb_io_ungetc, 1);
16092 rb_define_method(rb_cIO, "flush", rb_io_flush, 0);
16093 rb_define_method(rb_cIO, "tell", rb_io_tell, 0);
16094 rb_define_method(rb_cIO, "seek", rb_io_seek_m, -1);
16095 /* Set I/O position from the beginning */
16096 rb_define_const(rb_cIO, "SEEK_SET", INT2FIX(SEEK_SET));
16097 /* Set I/O position from the current position */
16098 rb_define_const(rb_cIO, "SEEK_CUR", INT2FIX(SEEK_CUR));
16099 /* Set I/O position from the end */
16100 rb_define_const(rb_cIO, "SEEK_END", INT2FIX(SEEK_END));
16101#ifdef SEEK_DATA
16102 /* Set I/O position to the next location containing data */
16103 rb_define_const(rb_cIO, "SEEK_DATA", INT2FIX(SEEK_DATA));
16104#endif
16105#ifdef SEEK_HOLE
16106 /* Set I/O position to the next hole */
16107 rb_define_const(rb_cIO, "SEEK_HOLE", INT2FIX(SEEK_HOLE));
16108#endif
16109 rb_define_method(rb_cIO, "rewind", rb_io_rewind, 0);
16110 rb_define_method(rb_cIO, "pos", rb_io_tell, 0);
16111 rb_define_method(rb_cIO, "pos=", rb_io_set_pos, 1);
16112 rb_define_method(rb_cIO, "eof", rb_io_eof, 0);
16113 rb_define_method(rb_cIO, "eof?", rb_io_eof, 0);
16114
16115 rb_define_method(rb_cIO, "close_on_exec?", rb_io_close_on_exec_p, 0);
16116 rb_define_method(rb_cIO, "close_on_exec=", rb_io_set_close_on_exec, 1);
16117
16118 rb_define_method(rb_cIO, "close", rb_io_close_m, 0);
16119 rb_define_method(rb_cIO, "closed?", rb_io_closed_p, 0);
16120 rb_define_method(rb_cIO, "close_read", rb_io_close_read, 0);
16121 rb_define_method(rb_cIO, "close_write", rb_io_close_write, 0);
16122
16123 rb_define_method(rb_cIO, "isatty", rb_io_isatty, 0);
16124 rb_define_method(rb_cIO, "tty?", rb_io_isatty, 0);
16125 rb_define_method(rb_cIO, "binmode", rb_io_binmode_m, 0);
16126 rb_define_method(rb_cIO, "binmode?", rb_io_binmode_p, 0);
16127 rb_define_method(rb_cIO, "sysseek", rb_io_sysseek, -1);
16128 rb_define_method(rb_cIO, "advise", rb_io_advise, -1);
16129
16130 rb_define_method(rb_cIO, "ioctl", rb_io_ioctl, -1);
16131 rb_define_method(rb_cIO, "fcntl", rb_io_fcntl, -1);
16132 rb_define_method(rb_cIO, "pid", rb_io_pid, 0);
16133
16134 rb_define_method(rb_cIO, "path", rb_io_path, 0);
16135 rb_define_method(rb_cIO, "to_path", rb_io_path, 0);
16136
16137 rb_define_method(rb_cIO, "inspect", rb_io_inspect, 0);
16138
16139 rb_define_method(rb_cIO, "external_encoding", rb_io_external_encoding, 0);
16140 rb_define_method(rb_cIO, "internal_encoding", rb_io_internal_encoding, 0);
16141 rb_define_method(rb_cIO, "set_encoding", rb_io_set_encoding, -1);
16142 rb_define_method(rb_cIO, "set_encoding_by_bom", rb_io_set_encoding_by_bom, 0);
16143
16144 rb_define_method(rb_cIO, "autoclose?", rb_io_autoclose_p, 0);
16145 rb_define_method(rb_cIO, "autoclose=", rb_io_set_autoclose, 1);
16146
16147 rb_define_method(rb_cIO, "wait", io_wait, -1);
16148
16149 rb_define_method(rb_cIO, "wait_readable", io_wait_readable, -1);
16150 rb_define_method(rb_cIO, "wait_writable", io_wait_writable, -1);
16151 rb_define_method(rb_cIO, "wait_priority", io_wait_priority, -1);
16152
16153 rb_define_virtual_variable("$stdin", stdin_getter, stdin_setter);
16154 rb_define_virtual_variable("$stdout", stdout_getter, stdout_setter);
16155 rb_define_virtual_variable("$>", stdout_getter, stdout_setter);
16156 rb_define_virtual_variable("$stderr", stderr_getter, stderr_setter);
16157
16158 rb_gvar_ractor_local("$stdin");
16159 rb_gvar_ractor_local("$stdout");
16160 rb_gvar_ractor_local("$>");
16161 rb_gvar_ractor_local("$stderr");
16162
16163 rb_gvar_box_dynamic("$stdin");
16164 rb_gvar_box_dynamic("$stdout");
16165 rb_gvar_box_dynamic("$>");
16166 rb_gvar_box_dynamic("$stderr");
16167
16169 rb_stdin = rb_io_prep_stdin();
16171 rb_stdout = rb_io_prep_stdout();
16173 rb_stderr = rb_io_prep_stderr();
16174
16175 orig_stdout = rb_stdout;
16176 orig_stderr = rb_stderr;
16177
16178 /* Holds the original stdin */
16180 /* Holds the original stdout */
16182 /* Holds the original stderr */
16184
16185#if 0
16186 /* Hack to get rdoc to regard ARGF as a class: */
16187 rb_cARGF = rb_define_class("ARGF", rb_cObject);
16188#endif
16189
16190 rb_cARGF = rb_class_new(rb_cObject);
16191 rb_set_class_path(rb_cARGF, rb_cObject, "ARGF.class");
16192 rb_define_alloc_func(rb_cARGF, argf_alloc);
16193
16195
16196 rb_define_method(rb_cARGF, "initialize", argf_initialize, -2);
16197 rb_define_method(rb_cARGF, "initialize_copy", argf_initialize_copy, 1);
16198 rb_define_method(rb_cARGF, "to_s", argf_to_s, 0);
16199 rb_define_alias(rb_cARGF, "inspect", "to_s");
16200 rb_define_method(rb_cARGF, "argv", argf_argv, 0);
16201
16202 rb_define_method(rb_cARGF, "fileno", argf_fileno, 0);
16203 rb_define_method(rb_cARGF, "to_i", argf_fileno, 0);
16204 rb_define_method(rb_cARGF, "to_io", argf_to_io, 0);
16205 rb_define_method(rb_cARGF, "to_write_io", argf_write_io, 0);
16206 rb_define_method(rb_cARGF, "each", argf_each_line, -1);
16207 rb_define_method(rb_cARGF, "each_line", argf_each_line, -1);
16208 rb_define_method(rb_cARGF, "each_byte", argf_each_byte, 0);
16209 rb_define_method(rb_cARGF, "each_char", argf_each_char, 0);
16210 rb_define_method(rb_cARGF, "each_codepoint", argf_each_codepoint, 0);
16211
16212 rb_define_method(rb_cARGF, "read", argf_read, -1);
16213 rb_define_method(rb_cARGF, "readpartial", argf_readpartial, -1);
16214 rb_define_method(rb_cARGF, "read_nonblock", argf_read_nonblock, -1);
16215 rb_define_method(rb_cARGF, "readlines", argf_readlines, -1);
16216 rb_define_method(rb_cARGF, "to_a", argf_readlines, -1);
16217 rb_define_method(rb_cARGF, "gets", argf_gets, -1);
16218 rb_define_method(rb_cARGF, "readline", argf_readline, -1);
16219 rb_define_method(rb_cARGF, "getc", argf_getc, 0);
16220 rb_define_method(rb_cARGF, "getbyte", argf_getbyte, 0);
16221 rb_define_method(rb_cARGF, "readchar", argf_readchar, 0);
16222 rb_define_method(rb_cARGF, "readbyte", argf_readbyte, 0);
16223 rb_define_method(rb_cARGF, "tell", argf_tell, 0);
16224 rb_define_method(rb_cARGF, "seek", argf_seek_m, -1);
16225 rb_define_method(rb_cARGF, "rewind", argf_rewind, 0);
16226 rb_define_method(rb_cARGF, "pos", argf_tell, 0);
16227 rb_define_method(rb_cARGF, "pos=", argf_set_pos, 1);
16228 rb_define_method(rb_cARGF, "eof", argf_eof, 0);
16229 rb_define_method(rb_cARGF, "eof?", argf_eof, 0);
16230 rb_define_method(rb_cARGF, "binmode", argf_binmode_m, 0);
16231 rb_define_method(rb_cARGF, "binmode?", argf_binmode_p, 0);
16232
16233 rb_define_method(rb_cARGF, "write", argf_write, -1);
16234 rb_define_method(rb_cARGF, "print", rb_io_print, -1);
16235 rb_define_method(rb_cARGF, "putc", rb_io_putc, 1);
16236 rb_define_method(rb_cARGF, "puts", rb_io_puts, -1);
16237 rb_define_method(rb_cARGF, "printf", rb_io_printf, -1);
16238
16239 rb_define_method(rb_cARGF, "filename", argf_filename, 0);
16240 rb_define_method(rb_cARGF, "path", argf_filename, 0);
16241 rb_define_method(rb_cARGF, "file", argf_file, 0);
16242 rb_define_method(rb_cARGF, "skip", argf_skip, 0);
16243 rb_define_method(rb_cARGF, "close", argf_close_m, 0);
16244 rb_define_method(rb_cARGF, "closed?", argf_closed, 0);
16245
16246 rb_define_method(rb_cARGF, "lineno", argf_lineno, 0);
16247 rb_define_method(rb_cARGF, "lineno=", argf_set_lineno, 1);
16248
16249 rb_define_method(rb_cARGF, "inplace_mode", argf_inplace_mode_get, 0);
16250 rb_define_method(rb_cARGF, "inplace_mode=", argf_inplace_mode_set, 1);
16251
16252 rb_define_method(rb_cARGF, "external_encoding", argf_external_encoding, 0);
16253 rb_define_method(rb_cARGF, "internal_encoding", argf_internal_encoding, 0);
16254 rb_define_method(rb_cARGF, "set_encoding", argf_set_encoding, -1);
16255
16256 argf = rb_class_new_instance(0, 0, rb_cARGF);
16257
16259 /*
16260 * ARGF is a stream designed for use in scripts that process files given
16261 * as command-line arguments or passed in via STDIN.
16262 *
16263 * See ARGF (the class) for more details.
16264 */
16266
16267 rb_define_hooked_variable("$.", &argf, argf_lineno_getter, argf_lineno_setter);
16268 rb_define_hooked_variable("$FILENAME", &argf, argf_filename_getter, rb_gvar_readonly_setter);
16269 ARGF_SET(filename, rb_str_new2("-"));
16270
16271 rb_define_hooked_variable("$-i", &argf, opt_i_get, opt_i_set);
16272 rb_gvar_ractor_local("$-i");
16273
16274 rb_define_hooked_variable("$*", &argf, argf_argv_getter, rb_gvar_readonly_setter);
16275
16276#if defined (_WIN32) || defined(__CYGWIN__)
16277 atexit(pipe_atexit);
16278#endif
16279
16280 Init_File();
16281
16282 rb_define_method(rb_cFile, "initialize", rb_file_initialize, -1);
16283
16284 sym_mode = ID2SYM(rb_intern_const("mode"));
16285 sym_perm = ID2SYM(rb_intern_const("perm"));
16286 sym_flags = ID2SYM(rb_intern_const("flags"));
16287 sym_extenc = ID2SYM(rb_intern_const("external_encoding"));
16288 sym_intenc = ID2SYM(rb_intern_const("internal_encoding"));
16289 sym_encoding = ID2SYM(rb_id_encoding());
16290 sym_open_args = ID2SYM(rb_intern_const("open_args"));
16291 sym_textmode = ID2SYM(rb_intern_const("textmode"));
16292 sym_binmode = ID2SYM(rb_intern_const("binmode"));
16293 sym_autoclose = ID2SYM(rb_intern_const("autoclose"));
16294 sym_normal = ID2SYM(rb_intern_const("normal"));
16295 sym_sequential = ID2SYM(rb_intern_const("sequential"));
16296 sym_random = ID2SYM(rb_intern_const("random"));
16297 sym_willneed = ID2SYM(rb_intern_const("willneed"));
16298 sym_dontneed = ID2SYM(rb_intern_const("dontneed"));
16299 sym_noreuse = ID2SYM(rb_intern_const("noreuse"));
16300 sym_SET = ID2SYM(rb_intern_const("SET"));
16301 sym_CUR = ID2SYM(rb_intern_const("CUR"));
16302 sym_END = ID2SYM(rb_intern_const("END"));
16303#ifdef SEEK_DATA
16304 sym_DATA = ID2SYM(rb_intern_const("DATA"));
16305#endif
16306#ifdef SEEK_HOLE
16307 sym_HOLE = ID2SYM(rb_intern_const("HOLE"));
16308#endif
16309 sym_wait_readable = ID2SYM(rb_intern_const("wait_readable"));
16310 sym_wait_writable = ID2SYM(rb_intern_const("wait_writable"));
16311}
16312
16313static void init_builtin_io(void);
16314#define Init_builtin_io init_builtin_io
16315#include "io.rbinc"
16316#undef Init_builtin_io
16317
16318void
16319Init_builtin_io(void)
16320{
16321 init_builtin_io();
16322
16323 /* Init_IO is called earlier than `loaded_features` is initialized */
16324 rb_provide("io/wait.rb");
16325 rb_provide("io/wait.so");
16326}
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:113
#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:1737
VALUE rb_class_new(VALUE super)
Creates a new, anonymous class.
Definition class.c:854
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:3068
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:3371
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:3358
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1041
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:3147
#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:1700
#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 REALLOC_N
Old name of RB_REALLOC_N.
Definition memory.h:406
#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:403
#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 LEN2NUM
Old name of RB_LEN2NUM.
Definition len_t.h:33
#define rb_str_cat2
Old name of rb_str_cat_cstr.
Definition string.h:1708
#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:131
#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 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 NUM2UINT
Old name of RB_NUM2UINT.
Definition int.h:45
#define ALLOC_N
Old name of RB_ALLOC_N.
Definition memory.h:402
#define MBCLEN_CHARFOUND_LEN(ret)
Old name of ONIGENC_MBCLEN_CHARFOUND_LEN.
Definition encoding.h:517
#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:408
#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 NUM2LEN
Old name of RB_NUM2LEN.
Definition len_t.h:34
#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:1702
#define ALLOCV_END
Old name of RB_ALLOCV_END.
Definition memory.h:409
#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_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:474
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:506
VALUE rb_eNotImpError
NotImplementedError exception.
Definition error.c:1467
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:678
void rb_syserr_fail(int e, const char *mesg)
Raises appropriate exception that represents a C errno.
Definition error.c:4053
void rb_readwrite_syserr_fail(enum rb_io_wait_readwrite waiting, int n, const char *mesg)
Identical to rb_readwrite_sys_fail(), except it does not depend on C global variable errno.
Definition io.c:14984
VALUE rb_eIOError
IOError exception.
Definition io.c:180
VALUE rb_eStandardError
StandardError exception.
Definition error.c:1454
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:4143
#define rb_notimplement()
Definition flock.c:3
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:4059
#define ruby_verbose
This variable controls whether the interpreter is in debug mode.
Definition error.h:476
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1457
VALUE rb_eEOFError
EOFError exception.
Definition io.c:179
void rb_readwrite_sys_fail(enum rb_io_wait_readwrite waiting, const char *mesg)
Raises appropriate exception using the parameters.
Definition io.c:14978
void rb_iter_break_value(VALUE val)
Identical to rb_iter_break(), except it additionally takes the "value" of this breakage.
Definition vm.c:2399
rb_io_wait_readwrite
for rb_readwrite_sys_fail first argument
Definition error.h:73
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1455
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:464
VALUE rb_eSystemCallError
SystemCallError exception.
Definition error.c:1477
@ RB_WARN_CATEGORY_DEPRECATED
Warning is for deprecated features.
Definition error.h:48
VALUE rb_mKernel
Kernel module.
Definition object.c:59
VALUE rb_check_to_int(VALUE val)
Identical to rb_check_to_integer(), except it uses #to_int for conversion.
Definition object.c:3343
VALUE rb_cObject
Object class.
Definition object.c:60
VALUE rb_any_to_s(VALUE obj)
Generates a textual representation of the given object.
Definition object.c:654
VALUE rb_obj_alloc(VALUE klass)
Allocates an instance of the given class.
Definition object.c:2264
VALUE rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
Allocates, then initialises an instance of the given class.
Definition object.c:2305
VALUE rb_cIO
IO class.
Definition io.c:178
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:2293
VALUE rb_mEnumerable
Enumerable module.
Definition enum.c:28
VALUE rb_stdin
STDIN constant.
Definition io.c:194
VALUE rb_stderr
STDERR constant.
Definition io.c:194
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:230
VALUE rb_obj_dup(VALUE obj)
Duplicates the given object.
Definition object.c:552
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:665
VALUE rb_mWaitReadable
IO::WaitReadable module.
Definition io.c:182
VALUE rb_mWaitWritable
IO::WaitReadable module.
Definition io.c:183
VALUE rb_obj_freeze(VALUE obj)
Same as RB_OBJ_FREEZE(), but returns the given object.
Definition object.c:1305
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:3324
VALUE rb_cFile
File class.
Definition file.c:175
VALUE rb_stdout
STDOUT constant.
Definition io.c:194
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
Definition object.c:3337
#define RB_OBJ_WRITTEN(old, oldv, young)
Identical to RB_OBJ_WRITE(), except it doesn't write any values, but only a WB declaration.
Definition gc.h:504
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:492
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
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:581
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:632
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:866
VALUE rb_fiber_scheduler_io_wait(VALUE scheduler, VALUE io, VALUE events, VALUE timeout)
Non-blocking version of rb_io_wait().
Definition scheduler.c:856
static ssize_t rb_fiber_scheduler_io_result_apply(VALUE result)
Apply an io result to the local thread, returning the value of the original system call that created ...
Definition scheduler.h:74
VALUE rb_fiber_scheduler_io_pread_memory(VALUE scheduler, VALUE io, rb_off_t from, void *base, size_t size)
Non-blocking pread from the passed IO using a native buffer.
Definition scheduler.c:1127
VALUE rb_fiber_scheduler_io_selectv(VALUE scheduler, int argc, VALUE *argv)
Non-blocking version of IO.select, argv variant.
Definition scheduler.c:896
VALUE rb_fiber_scheduler_io_read_memory(VALUE scheduler, VALUE io, void *base, size_t size)
Non-blocking read from the passed IO using a native buffer.
Definition scheduler.c:1079
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:589
VALUE rb_fiber_scheduler_io_pwrite_memory(VALUE scheduler, VALUE io, rb_off_t from, const void *base, size_t size)
Non-blocking pwrite to the passed IO using a native buffer.
Definition scheduler.c:1152
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:594
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:872
VALUE rb_fiber_scheduler_io_close(VALUE scheduler, VALUE io)
Non-blocking close the given IO.
Definition scheduler.c:1177
VALUE rb_fiber_scheduler_io_write_memory(VALUE scheduler, VALUE io, const void *base, size_t size)
Non-blocking write to the passed IO using a native buffer.
Definition scheduler.c:1103
rb_encoding * rb_ascii8bit_encoding(void)
Queries the encoding that represents ASCII-8BIT a.k.a.
Definition encoding.c:1566
rb_encoding * rb_default_internal_encoding(void)
Queries the "default internal" encoding.
Definition encoding.c:1787
int rb_utf8_encindex(void)
Identical to rb_utf8_encoding(), except it returns the encoding's index instead of the encoding itsel...
Definition encoding.c:1584
VALUE rb_enc_default_external(void)
Identical to rb_default_external_encoding(), except it returns the Ruby-level counterpart instance of...
Definition encoding.c:1714
static unsigned int rb_enc_codepoint(const char *p, const char *e, rb_encoding *enc)
Queries the code point of character pointed by the passed pointer.
Definition encoding.h:571
rb_encoding * rb_default_external_encoding(void)
Queries the "default external" encoding.
Definition encoding.c:1700
static int rb_enc_mbmaxlen(rb_encoding *enc)
Queries the maximum number of bytes that the passed encoding needs to represent a character.
Definition encoding.h:447
rb_encoding * rb_locale_encoding(void)
Queries the encoding that represents the current locale.
Definition encoding.c:1630
rb_encoding * rb_usascii_encoding(void)
Queries the encoding that represents US-ASCII.
Definition encoding.c:1590
VALUE rb_str_conv_enc(VALUE str, rb_encoding *from, rb_encoding *to)
Encoding conversion main routine.
Definition string.c:1393
rb_len_t rb_str_coderange_scan_restartable(const char *str, const char *end, rb_encoding *enc, int *cr)
Scans the passed string until it finds something odd.
Definition string.c:855
VALUE rb_enc_uint_chr(unsigned int code, rb_encoding *enc)
Encodes the passed code point into a series of bytes.
Definition numeric.c:3953
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:2681
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:2126
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:1783
const char * rb_econv_asciicompat_encoding(const char *encname)
Queries the passed encoding's corresponding ASCII compatible encoding.
Definition transcode.c:1827
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:1962
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:2732
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:2025
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:3044
VALUE rb_econv_make_exception(rb_econv_t *ec)
This function makes sense right after rb_econv_convert() returns.
Definition transcode.c:4413
void rb_econv_check_error(rb_econv_t *ec)
This is a rb_econv_make_exception() + rb_exc_raise() combo.
Definition transcode.c:4419
void rb_econv_close(rb_econv_t *ec)
Destructs a converter.
Definition transcode.c:1744
void rb_econv_putback(rb_econv_t *ec, unsigned char *p, int n)
Puts back the bytes.
Definition transcode.c:1794
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1149
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:1116
VALUE rb_funcallv(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcall(), except it takes the method arguments as a C array.
Definition vm_eval.c:1107
void rb_gc(void)
Triggers a GC process.
Definition gc.c:5695
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_ary_entry(VALUE ary, rb_len_t off)
Queries an element of an array.
VALUE rb_ary_new_capa(rb_len_t capa)
Identical to rb_ary_new(), except it additionally specifies how many rooms of objects it should alloc...
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_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
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition error.h:284
ID rb_frame_this_func(void)
Queries the name of the Ruby level method that is calling this function.
Definition eval.c:1230
VALUE rb_hash_new(void)
Creates a new, empty hash object.
Definition hash.c:1646
VALUE rb_io_printf(int argc, const VALUE *argv, VALUE io)
This is a rb_f_sprintf() + rb_io_write() combo.
Definition io.c:8847
VALUE rb_io_gets(VALUE io)
Reads a "line" from the given IO.
Definition io.c:4516
int rb_cloexec_pipe(int fildes[2])
Opens a pipe with closing on exec.
Definition io.c:478
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:8980
VALUE rb_io_addstr(VALUE io, VALUE str)
Identical to rb_io_write(), except it always returns the passed IO.
Definition io.c:2431
void rb_write_error2(const char *str, rb_len_t len)
Identical to rb_write_error(), except it additionally takes the message's length.
Definition io.c:9389
void rb_write_error(const char *str)
Writes the given error message to somewhere applicable.
Definition io.c:9409
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:5388
VALUE rb_io_getbyte(VALUE io)
Reads a byte from the given IO.
Definition io.c:5293
int rb_cloexec_dup2(int oldfd, int newfd)
Identical to rb_cloexec_dup(), except you can specify the destination file descriptor.
Definition io.c:376
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:9590
void rb_update_max_fd(int fd)
Informs the interpreter that the passed fd can be the max.
Definition io.c:274
int rb_cloexec_open(const char *pathname, int flags, mode_t mode)
Opens a file that closes on exec.
Definition io.c:337
VALUE rb_output_rs
The record separator character for outputs, or the $\\endiskip.
Definition io.c:199
VALUE rb_io_eof(VALUE io)
Queries if the passed IO is at the end of file.
Definition io.c:2773
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:324
VALUE rb_io_ascii8bit_binmode(VALUE io)
Forces no conversions be applied to the passed IO.
Definition io.c:6649
VALUE rb_io_binmode(VALUE io)
Sets the binmode.
Definition io.c:6603
VALUE rb_io_ungetc(VALUE io, VALUE c)
"Unget"s a string.
Definition io.c:5452
int rb_pipe(int *pipes)
This is an rb_cloexec_pipe() + rb_update_max_fd() combo.
Definition io.c:7650
VALUE rb_gets(void)
Much like rb_io_gets(), but it reads from the mysterious ARGF object.
Definition io.c:10678
int rb_cloexec_fcntl_dupfd(int fd, int minfd)
Duplicates a file descriptor with closing on exec.
Definition io.c:484
VALUE rb_output_fs
The field separator character for outputs, or the $,.
Definition io.c:197
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:7534
int rb_cloexec_dup(int oldfd)
Identical to rb_cloexec_fcntl_dupfd(), except it implies minfd is 3.
Definition io.c:369
VALUE rb_file_open(const char *fname, const char *fmode)
Opens a file located at the given path.
Definition io.c:7541
VALUE rb_io_close(VALUE io)
Closes the IO.
Definition io.c:5988
VALUE rb_default_rs
This is the default value of rb_rs, i.e.
Definition io.c:200
void rb_provide(const char *feature)
Declares that the given feature is already provided by someone else.
Definition load.c:963
void rb_lastline_set(VALUE str)
Updates $_.
Definition vm.c:2161
VALUE rb_lastline_get(void)
Queries the last line, or the $_.
Definition vm.c:2155
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:3843
rb_pid_t rb_waitpid(rb_pid_t pid, int *status, int flags)
Waits for a process, with releasing GVL.
Definition process.c:1161
void rb_last_status_set(int status, rb_pid_t pid)
Sets the "last status", or the $?.
Definition process.c:676
void rb_str_modify_expand(VALUE str, rb_len_t capa)
Identical to rb_str_modify(), except it additionally expands the capacity of the receiver.
Definition string.c:2838
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:3940
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1523
#define rb_str_buf_cat
Just another name of rb_str_cat.
Definition string.h:1706
#define rb_usascii_str_new(str, len)
Identical to rb_str_new, except it generates a string of "US ASCII" encoding.
Definition string.h:1557
size_t rb_str_capacity(VALUE str)
Queries the capacity of the given string.
Definition string.c:1037
VALUE rb_str_new_frozen(VALUE str)
Creates a frozen copy of the string, if necessary.
Definition string.c:1569
void rb_str_set_len(VALUE str, rb_len_t len)
Overwrites the length of the string.
Definition string.c:3522
VALUE rb_str_dup(VALUE str)
Duplicates a string.
Definition string.c:2052
VALUE rb_str_cat(VALUE dst, const char *src, rb_len_t srclen)
Destructively appends the passed contents to the string.
Definition string.c:3706
VALUE rb_str_locktmp(VALUE str)
Obtains a "temporary lock" of the string.
VALUE rb_str_no_gvl_safe_acquire(VALUE orig)
Creates a frozen copy of orig that guarantees the RSTRING_PTR is safe to use in operations that relea...
Definition string.c:1598
VALUE rb_str_equal(VALUE str1, VALUE str2)
Equality of two strings.
Definition string.c:4446
void rb_str_no_gvl_safe_release(VALUE orig, VALUE tmp)
Releases a string created from rb_str_no_gvl_safe_acquire.
Definition string.c:1641
VALUE rb_str_substr(VALUE str, rb_len_t beg, rb_len_t len)
This is the implementation of two-argumented String#slice.
Definition string.c:3385
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:3880
VALUE rb_str_buf_new(rb_len_t capa)
Allocates a "string buffer".
Definition string.c:1783
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition string.c:3069
VALUE rb_str_unlocktmp(VALUE str)
Releases a lock formerly obtained by rb_str_locktmp().
Definition string.c:3504
#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:1539
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:1916
int rb_thread_interrupted(VALUE thval)
Checks if the thread's execution was recently interrupted.
Definition thread.c:1663
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:1671
VALUE rb_exec_recursive(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
"Recursion" API entry point.
Definition thread.c:5959
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:1646
VALUE rb_thread_current(void)
Obtains the "current" thread.
Definition thread.c:3492
int rb_thread_wait_fd(int fd)
Blocks the current thread until the given file descriptor is ready to be read.
Definition io.c:1665
void rb_thread_sleep(int sec)
Blocks for the given period of time.
Definition thread.c:1669
struct timeval rb_time_interval(VALUE num)
Creates a "time interval".
Definition time.c:2984
void rb_set_class_path(VALUE klass, VALUE space, const char *name)
Names a class.
Definition variable.c:458
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:2168
VALUE rb_class_name(VALUE obj)
Queries the name of the given object's class.
Definition variable.c:517
int rb_respond_to(VALUE obj, ID mid)
Queries if the object responds to the method.
Definition vm_method.c:3743
int rb_method_basic_definition_p(VALUE klass, ID mid)
Well... Let us hesitate from describing what a "basic definition" is.
Definition vm_method.c:3621
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:716
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:285
#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:4124
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:889
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:6735
VALUE rb_io_get_io(VALUE io)
Identical to rb_io_check_io(), except it raises exceptions on conversion failures.
Definition io.c:821
VALUE rb_io_timeout(VALUE io)
Get the timeout associated with the specified io object.
Definition io.c:867
VALUE rb_io_taint_check(VALUE obj)
Definition io.c:791
void rb_io_read_check(rb_io_t *fptr)
Blocks until there is a pending read in the passed IO.
Definition io.c:1105
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:6868
#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:1051
#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:1060
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:6792
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:1657
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:7351
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:7017
int rb_io_descriptor(VALUE io)
Returns an integer representing the numeric file descriptor for io.
Definition io.c:2972
#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:9636
#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:1724
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:1677
VALUE rb_eIOTimeoutError
Indicates that a timeout has occurred while performing an IO operation.
Definition io.c:181
#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:3051
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:7142
void rb_io_check_initialized(rb_io_t *fptr)
Asserts that the passed IO is initialised.
Definition io.c:798
#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:5899
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:827
VALUE rb_io_closed_p(VALUE io)
Returns whether or not the underlying IO is closed.
Definition io.c:6096
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:896
ssize_t rb_io_bufwrite(VALUE io, const void *buf, size_t size)
Buffered write to the passed IO.
Definition io.c:2088
void rb_io_check_char_readable(rb_io_t *fptr)
Asserts that an IO is opened for character-based reading.
Definition io.c:1032
#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:1096
VALUE rb_io_get_write_io(VALUE io)
Queries the tied IO for writing.
Definition io.c:833
void rb_io_set_nonblock(rb_io_t *fptr)
Instructs the OS to put its internal file structure into "nonblocking mode".
Definition io.c:3545
int rb_io_wait_writable(int fd)
Blocks until the passed file descriptor gets writable.
Definition io.c:1613
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:9502
VALUE rb_io_set_write_io(VALUE io, VALUE w)
Assigns the tied IO for writing.
Definition io.c:844
void rb_io_check_writable(rb_io_t *fptr)
Asserts that an IO is opened for writing.
Definition io.c:1084
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:1739
void rb_io_check_closed(rb_io_t *fptr)
This badly named function asserts that the passed IO is open.
Definition io.c:806
void rb_eof_error(void)
Utility function to raise rb_eEOFError.
Definition io.c:785
int rb_io_wait_readable(int fd)
Blocks until the passed file descriptor gets readable.
Definition io.c:1578
void rb_io_synchronized(rb_io_t *fptr)
Sets FMODE_SYNC.
Definition io.c:7642
VALUE rb_io_wait(VALUE io, VALUE events, VALUE timeout)
Blocks until the passed IO is ready for the passed events.
Definition io.c:1518
int len
Length of the buffer.
Definition io.h:8
VALUE rb_ractor_stderr(void)
Queries the standard error of the current Ractor that is calling this function.
Definition ractor.c:1520
VALUE rb_ractor_stdin(void)
Queries the standard input of the current Ractor that is calling this function.
Definition ractor.c:1490
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:1559
VALUE rb_ractor_stdout(void)
Queries the standard output of the current Ractor that is calling this function.
Definition ractor.c:1505
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:1547
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:1535
void * rb_thread_call_with_gvl(void *(*func)(void *), void *data1)
(Re-)acquires the GVL.
Definition thread.c:2323
#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:232
#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:1449
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1404
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:363
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:170
#define MEMMOVE(p1, p2, type, n)
Handy macro to call memmove.
Definition memory.h:387
#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.
VALUE rb_rescue2(type *q, VALUE w, type *e, VALUE r,...)
An equivalent of rescue clause.
VALUE rb_ensure(type *q, VALUE w, type *e, VALUE r)
An equivalent of ensure clause.
#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:50
static int RARRAY_LENINT(VALUE ary)
Identical to rb_array_len(), except it differs for the return type.
Definition rarray.h:280
#define RARRAY_AREF(a, i)
References an object in an array.
Definition rarray.h:422
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition rarray.h:51
#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
static char * RSTRING_END(VALUE str)
Queries the end of the contents pointer of the string.
Definition rstring.h:409
#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:81
struct rb_data_type_struct rb_data_type_t
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:239
#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:604
VALUE rb_get_argv(void)
Queries the arguments passed to the current process that you can access from Ruby as ARGV.
Definition io.c:14944
void rb_p(VALUE obj)
Inspects an object.
Definition io.c:9288
#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
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:4868
static bool RB_TEST(VALUE obj)
Emulates Ruby's "if" statement.
@ 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:229
Definition win32.h:196
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
void(* finalize)(struct rb_io *, int)
finalize proc
Definition io.h:326
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:134
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
VALUE pathv
pathname for file
Definition io.h:322
long rb_len_t
A signed integer type for lengths and indices of objects such as String and Array.
Definition value.h:142
#define RB_LEN_MAX
Maximum possible value that a rb_len_t can take.
Definition value.h:156
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
static bool RB_FLOAT_TYPE_P(VALUE obj)
Queries if the object is an instance of rb_cFloat.
Definition value_type.h:264
static bool RB_SYMBOL_P(VALUE obj)
Queries if the object is an instance of rb_cSymbol.
Definition value_type.h:307
static void Check_Type(VALUE v, enum ruby_value_type t)
Identical to RB_TYPE_P(), except it raises exceptions on predication failure.
Definition value_type.h:425
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:376
#define RBIMPL_WARNING_IGNORED(flag)
Suppresses a warning.
#define RBIMPL_WARNING_PUSH()
Pushes compiler warning state.
#define RBIMPL_WARNING_POP()
Pops compiler warning state.