Ruby  2.4.2p198(2017-09-14revision59899)
io.c
Go to the documentation of this file.
1 /**********************************************************************
2 
3  io.c -
4 
5  $Author: nagachika $
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 "internal.h"
15 #include "ruby/io.h"
16 #include "ruby/thread.h"
17 #include "dln.h"
18 #include "encindex.h"
19 #include "id.h"
20 #include <ctype.h>
21 #include <errno.h>
22 #include "ruby_atomic.h"
23 
24 #undef free
25 #define free(x) xfree(x)
26 
27 #if defined(DOSISH) || defined(__CYGWIN__)
28 #include <io.h>
29 #endif
30 
31 #include <sys/types.h>
32 #if defined HAVE_NET_SOCKET_H
33 # include <net/socket.h>
34 #elif defined HAVE_SYS_SOCKET_H
35 # include <sys/socket.h>
36 #endif
37 
38 #if defined(__BOW__) || defined(__CYGWIN__) || defined(_WIN32)
39 # define NO_SAFE_RENAME
40 #endif
41 
42 #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__sun) || defined(_nec_ews)
43 # define USE_SETVBUF
44 #endif
45 
46 #ifdef __QNXNTO__
47 #include "unix.h"
48 #endif
49 
50 #include <sys/types.h>
51 #if defined(HAVE_SYS_IOCTL_H) && !defined(_WIN32)
52 #include <sys/ioctl.h>
53 #endif
54 #if defined(HAVE_FCNTL_H) || defined(_WIN32)
55 #include <fcntl.h>
56 #elif defined(HAVE_SYS_FCNTL_H)
57 #include <sys/fcntl.h>
58 #endif
59 
60 #if !HAVE_OFF_T && !defined(off_t)
61 # define off_t long
62 #endif
63 
64 #ifdef HAVE_SYS_TIME_H
65 # include <sys/time.h>
66 #endif
67 
68 #include <sys/stat.h>
69 
70 #if defined(HAVE_SYS_PARAM_H) || defined(__HIUX_MPP__)
71 # include <sys/param.h>
72 #endif
73 
74 #if !defined NOFILE
75 # define NOFILE 64
76 #endif
77 
78 #ifdef HAVE_UNISTD_H
79 #include <unistd.h>
80 #endif
81 
82 #ifdef HAVE_SYSCALL_H
83 #include <syscall.h>
84 #elif defined HAVE_SYS_SYSCALL_H
85 #include <sys/syscall.h>
86 #endif
87 
88 #ifdef HAVE_SYS_UIO_H
89 #include <sys/uio.h>
90 #endif
91 
92 #ifdef HAVE_SYS_WAIT_H
93 # include <sys/wait.h> /* for WNOHANG on BSD */
94 #endif
95 
96 #include "ruby/util.h"
97 
98 #ifndef O_ACCMODE
99 #define O_ACCMODE (O_RDONLY | O_WRONLY | O_RDWR)
100 #endif
101 
102 #if SIZEOF_OFF_T > SIZEOF_LONG && !defined(HAVE_LONG_LONG)
103 # error off_t is bigger than long, but you have no long long...
104 #endif
105 
106 #ifndef PIPE_BUF
107 # ifdef _POSIX_PIPE_BUF
108 # define PIPE_BUF _POSIX_PIPE_BUF
109 # else
110 # define PIPE_BUF 512 /* is this ok? */
111 # endif
112 #endif
113 
114 #ifndef EWOULDBLOCK
115 # define EWOULDBLOCK EAGAIN
116 #endif
117 
118 #if defined(HAVE___SYSCALL) && (defined(__APPLE__) || defined(__OpenBSD__))
119 /* Mac OS X and OpenBSD have __syscall but don't define it in headers */
120 off_t __syscall(quad_t number, ...);
121 #endif
122 
123 #ifdef __native_client__
124 # undef F_GETFD
125 # ifdef NACL_NEWLIB
126 # undef HAVE_IOCTL
127 # endif
128 #endif
129 
130 #define IO_RBUF_CAPA_MIN 8192
131 #define IO_CBUF_CAPA_MIN (128*1024)
132 #define IO_RBUF_CAPA_FOR(fptr) (NEED_READCONV(fptr) ? IO_CBUF_CAPA_MIN : IO_RBUF_CAPA_MIN)
133 #define IO_WBUF_CAPA_MIN 8192
134 
135 /* define system APIs */
136 #ifdef _WIN32
137 #undef open
138 #define open rb_w32_uopen
139 #endif
140 
146 
153 
156 
161 
162 static VALUE argf;
163 
164 #define id_exception idException
170 #ifdef SEEK_DATA
171 static VALUE sym_DATA;
172 #endif
173 #ifdef SEEK_HOLE
174 static VALUE sym_HOLE;
175 #endif
176 
177 struct argf {
179  long last_lineno; /* $. */
180  long lineno;
182  char *inplace;
183  struct rb_io_enc_t encs;
185 };
186 
188 void
190 {
191  struct stat buf;
194 
195  if (afd <= max_fd)
196  return;
197 
198  if (fstat(fd, &buf) != 0 && errno == EBADF) {
199  rb_bug("rb_update_max_fd: invalid fd (%d) given.", fd);
200  }
201 
202  while (max_fd < afd) {
203  max_fd = ATOMIC_CAS(max_file_descriptor, max_fd, afd);
204  }
205 }
206 
207 void
209 {
210  /* MinGW don't have F_GETFD and FD_CLOEXEC. [ruby-core:40281] */
211 #if defined(HAVE_FCNTL) && defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
212  int flags, flags2, ret;
213  flags = fcntl(fd, F_GETFD); /* should not fail except EBADF. */
214  if (flags == -1) {
215  rb_bug("rb_maygvl_fd_fix_cloexec: fcntl(%d, F_GETFD) failed: %s", fd, strerror(errno));
216  }
217  if (fd <= 2)
218  flags2 = flags & ~FD_CLOEXEC; /* Clear CLOEXEC for standard file descriptors: 0, 1, 2. */
219  else
220  flags2 = flags | FD_CLOEXEC; /* Set CLOEXEC for non-standard file descriptors: 3, 4, 5, ... */
221  if (flags != flags2) {
222  ret = fcntl(fd, F_SETFD, flags2);
223  if (ret == -1) {
224  rb_bug("rb_maygvl_fd_fix_cloexec: fcntl(%d, F_SETFD, %d) failed: %s", fd, flags2, strerror(errno));
225  }
226  }
227 #endif
228 }
229 
230 void
232 {
234  rb_update_max_fd(fd);
235 }
236 
237 /* this is only called once */
238 static int
240 {
241 #if defined(O_CLOEXEC) && defined(F_GETFD)
242  int flags = fcntl(fd, F_GETFD);
243 
244  if (flags == -1)
245  rb_bug("rb_fix_detect_o_cloexec: fcntl(%d, F_GETFD) failed: %s", fd, strerror(errno));
246 
247  if (flags & FD_CLOEXEC)
248  return 1;
249 #endif /* fall through if O_CLOEXEC does not work: */
251  return 0;
252 }
253 
254 int
255 rb_cloexec_open(const char *pathname, int flags, mode_t mode)
256 {
257  int ret;
258  static int o_cloexec_state = -1; /* <0: unknown, 0: ignored, >0: working */
259 
260 #ifdef O_CLOEXEC
261  /* O_CLOEXEC is available since Linux 2.6.23. Linux 2.6.18 silently ignore it. */
262  flags |= O_CLOEXEC;
263 #elif defined O_NOINHERIT
264  flags |= O_NOINHERIT;
265 #endif
266  ret = open(pathname, flags, mode);
267  if (ret == -1) return -1;
268  if (ret <= 2 || o_cloexec_state == 0) {
270  }
271  else if (o_cloexec_state > 0) {
272  return ret;
273  }
274  else {
275  o_cloexec_state = rb_fix_detect_o_cloexec(ret);
276  }
277  return ret;
278 }
279 
280 int
281 rb_cloexec_dup(int oldfd)
282 {
283  /* Don't allocate standard file descriptors: 0, 1, 2 */
284  return rb_cloexec_fcntl_dupfd(oldfd, 3);
285 }
286 
287 int
288 rb_cloexec_dup2(int oldfd, int newfd)
289 {
290  int ret;
291 
292  /* When oldfd == newfd, dup2 succeeds but dup3 fails with EINVAL.
293  * rb_cloexec_dup2 succeeds as dup2. */
294  if (oldfd == newfd) {
295  ret = newfd;
296  }
297  else {
298 #if defined(HAVE_DUP3) && defined(O_CLOEXEC)
299  static int try_dup3 = 1;
300  if (2 < newfd && try_dup3) {
301  ret = dup3(oldfd, newfd, O_CLOEXEC);
302  if (ret != -1)
303  return ret;
304  /* dup3 is available since Linux 2.6.27, glibc 2.9. */
305  if (errno == ENOSYS) {
306  try_dup3 = 0;
307  ret = dup2(oldfd, newfd);
308  }
309  }
310  else {
311  ret = dup2(oldfd, newfd);
312  }
313 #else
314  ret = dup2(oldfd, newfd);
315 #endif
316  if (ret == -1) return -1;
317  }
319  return ret;
320 }
321 
322 int
323 rb_cloexec_pipe(int fildes[2])
324 {
325  int ret;
326 
327 #if defined(HAVE_PIPE2)
328  static int try_pipe2 = 1;
329  if (try_pipe2) {
330  ret = pipe2(fildes, O_CLOEXEC);
331  if (ret != -1)
332  return ret;
333  /* pipe2 is available since Linux 2.6.27, glibc 2.9. */
334  if (errno == ENOSYS) {
335  try_pipe2 = 0;
336  ret = pipe(fildes);
337  }
338  }
339  else {
340  ret = pipe(fildes);
341  }
342 #else
343  ret = pipe(fildes);
344 #endif
345  if (ret == -1) return -1;
346 #ifdef __CYGWIN__
347  if (ret == 0 && fildes[1] == -1) {
348  close(fildes[0]);
349  fildes[0] = -1;
350  errno = ENFILE;
351  return -1;
352  }
353 #endif
354  rb_maygvl_fd_fix_cloexec(fildes[0]);
355  rb_maygvl_fd_fix_cloexec(fildes[1]);
356  return ret;
357 }
358 
359 int
360 rb_cloexec_fcntl_dupfd(int fd, int minfd)
361 {
362  int ret;
363 
364 #if defined(HAVE_FCNTL) && defined(F_DUPFD_CLOEXEC) && defined(F_DUPFD)
365  static int try_dupfd_cloexec = 1;
366  if (try_dupfd_cloexec) {
367  ret = fcntl(fd, F_DUPFD_CLOEXEC, minfd);
368  if (ret != -1) {
369  if (ret <= 2)
371  return ret;
372  }
373  /* F_DUPFD_CLOEXEC is available since Linux 2.6.24. Linux 2.6.18 fails with EINVAL */
374  if (errno == EINVAL) {
375  ret = fcntl(fd, F_DUPFD, minfd);
376  if (ret != -1) {
377  try_dupfd_cloexec = 0;
378  }
379  }
380  }
381  else {
382  ret = fcntl(fd, F_DUPFD, minfd);
383  }
384 #elif defined(HAVE_FCNTL) && defined(F_DUPFD)
385  ret = fcntl(fd, F_DUPFD, minfd);
386 #elif defined(HAVE_DUP)
387  ret = dup(fd);
388  if (ret != -1 && ret < minfd) {
389  const int prev_fd = ret;
390  ret = rb_cloexec_fcntl_dupfd(fd, minfd);
391  close(prev_fd);
392  }
393  return ret;
394 #else
395 # error "dup() or fcntl(F_DUPFD) must be supported."
396 #endif
397  if (ret == -1) return -1;
399  return ret;
400 }
401 
402 #define argf_of(obj) (*(struct argf *)DATA_PTR(obj))
403 #define ARGF argf_of(argf)
404 
405 #define GetWriteIO(io) rb_io_get_write_io(io)
406 
407 #define READ_DATA_PENDING(fptr) ((fptr)->rbuf.len)
408 #define READ_DATA_PENDING_COUNT(fptr) ((fptr)->rbuf.len)
409 #define READ_DATA_PENDING_PTR(fptr) ((fptr)->rbuf.ptr+(fptr)->rbuf.off)
410 #define READ_DATA_BUFFERED(fptr) READ_DATA_PENDING(fptr)
411 
412 #define READ_CHAR_PENDING(fptr) ((fptr)->cbuf.len)
413 #define READ_CHAR_PENDING_COUNT(fptr) ((fptr)->cbuf.len)
414 #define READ_CHAR_PENDING_PTR(fptr) ((fptr)->cbuf.ptr+(fptr)->cbuf.off)
415 
416 #if defined(_WIN32)
417 #define WAIT_FD_IN_WIN32(fptr) \
418  (rb_w32_io_cancelable_p((fptr)->fd) ? 0 : rb_thread_wait_fd((fptr)->fd))
419 #else
420 #define WAIT_FD_IN_WIN32(fptr)
421 #endif
422 
423 #define READ_CHECK(fptr) do {\
424  if (!READ_DATA_PENDING(fptr)) {\
425  WAIT_FD_IN_WIN32(fptr);\
426  rb_io_check_closed(fptr);\
427  }\
428 } while(0)
429 
430 #ifndef S_ISSOCK
431 # ifdef _S_ISSOCK
432 # define S_ISSOCK(m) _S_ISSOCK(m)
433 # else
434 # ifdef _S_IFSOCK
435 # define S_ISSOCK(m) (((m) & S_IFMT) == _S_IFSOCK)
436 # else
437 # ifdef S_IFSOCK
438 # define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK)
439 # endif
440 # endif
441 # endif
442 #endif
443 
444 static int io_fflush(rb_io_t *);
445 static rb_io_t *flush_before_seek(rb_io_t *fptr);
446 
447 #define NEED_NEWLINE_DECORATOR_ON_READ(fptr) ((fptr)->mode & FMODE_TEXTMODE)
448 #define NEED_NEWLINE_DECORATOR_ON_WRITE(fptr) ((fptr)->mode & FMODE_TEXTMODE)
449 #if defined(RUBY_TEST_CRLF_ENVIRONMENT) || defined(_WIN32)
450 /* Windows */
451 # define DEFAULT_TEXTMODE FMODE_TEXTMODE
452 # define TEXTMODE_NEWLINE_DECORATOR_ON_WRITE ECONV_CRLF_NEWLINE_DECORATOR
453 /*
454  * CRLF newline is set as default newline decorator.
455  * If only CRLF newline conversion is needed, we use binary IO process
456  * with OS's text mode for IO performance improvement.
457  * If encoding conversion is needed or a user sets text mode, we use encoding
458  * conversion IO process and universal newline decorator by default.
459  */
460 #define NEED_READCONV(fptr) ((fptr)->encs.enc2 != NULL || (fptr)->encs.ecflags & ~ECONV_CRLF_NEWLINE_DECORATOR)
461 #define NEED_WRITECONV(fptr) (((fptr)->encs.enc != NULL && (fptr)->encs.enc != rb_ascii8bit_encoding()) || ((fptr)->encs.ecflags & ((ECONV_DECORATOR_MASK & ~ECONV_CRLF_NEWLINE_DECORATOR)|ECONV_STATEFUL_DECORATOR_MASK)))
462 #define SET_BINARY_MODE(fptr) setmode((fptr)->fd, O_BINARY)
463 
464 #define NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr) do {\
465  if (NEED_NEWLINE_DECORATOR_ON_READ(fptr)) {\
466  if (((fptr)->mode & FMODE_READABLE) &&\
467  !((fptr)->encs.ecflags & ECONV_NEWLINE_DECORATOR_MASK)) {\
468  setmode((fptr)->fd, O_BINARY);\
469  }\
470  else {\
471  setmode((fptr)->fd, O_TEXT);\
472  }\
473  }\
474 } while(0)
475 
476 #define SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags) do {\
477  if ((enc2) && ((ecflags) & ECONV_DEFAULT_NEWLINE_DECORATOR)) {\
478  (ecflags) |= ECONV_UNIVERSAL_NEWLINE_DECORATOR;\
479  }\
480 } while(0)
481 
482 /*
483  * IO unread with taking care of removed '\r' in text mode.
484  */
485 static void
486 io_unread(rb_io_t *fptr)
487 {
488  off_t r, pos;
489  ssize_t read_size;
490  long i;
491  long newlines = 0;
492  long extra_max;
493  char *p;
494  char *buf;
495 
496  rb_io_check_closed(fptr);
497  if (fptr->rbuf.len == 0 || fptr->mode & FMODE_DUPLEX) {
498  return;
499  }
500 
501  errno = 0;
502  if (!rb_w32_fd_is_text(fptr->fd)) {
503  r = lseek(fptr->fd, -fptr->rbuf.len, SEEK_CUR);
504  if (r < 0 && errno) {
505  if (errno == ESPIPE)
506  fptr->mode |= FMODE_DUPLEX;
507  return;
508  }
509 
510  fptr->rbuf.off = 0;
511  fptr->rbuf.len = 0;
512  return;
513  }
514 
515  pos = lseek(fptr->fd, 0, SEEK_CUR);
516  if (pos < 0 && errno) {
517  if (errno == ESPIPE)
518  fptr->mode |= FMODE_DUPLEX;
519  return;
520  }
521 
522  /* add extra offset for removed '\r' in rbuf */
523  extra_max = (long)(pos - fptr->rbuf.len);
524  p = fptr->rbuf.ptr + fptr->rbuf.off;
525 
526  /* if the end of rbuf is '\r', rbuf doesn't have '\r' within rbuf.len */
527  if (*(fptr->rbuf.ptr + fptr->rbuf.capa - 1) == '\r') {
528  newlines++;
529  }
530 
531  for (i = 0; i < fptr->rbuf.len; i++) {
532  if (*p == '\n') newlines++;
533  if (extra_max == newlines) break;
534  p++;
535  }
536 
537  buf = ALLOC_N(char, fptr->rbuf.len + newlines);
538  while (newlines >= 0) {
539  r = lseek(fptr->fd, pos - fptr->rbuf.len - newlines, SEEK_SET);
540  if (newlines == 0) break;
541  if (r < 0) {
542  newlines--;
543  continue;
544  }
545  read_size = _read(fptr->fd, buf, fptr->rbuf.len + newlines);
546  if (read_size < 0) {
547  int e = errno;
548  free(buf);
549  rb_syserr_fail_path(e, fptr->pathv);
550  }
551  if (read_size == fptr->rbuf.len) {
552  lseek(fptr->fd, r, SEEK_SET);
553  break;
554  }
555  else {
556  newlines--;
557  }
558  }
559  free(buf);
560  fptr->rbuf.off = 0;
561  fptr->rbuf.len = 0;
562  return;
563 }
564 
565 /*
566  * We use io_seek to back cursor position when changing mode from text to binary,
567  * but stdin and pipe cannot seek back. Stdin and pipe read should use encoding
568  * conversion for working properly with mode change.
569  *
570  * Return previous translation mode.
571  */
572 static inline int
573 set_binary_mode_with_seek_cur(rb_io_t *fptr)
574 {
575  if (!rb_w32_fd_is_text(fptr->fd)) return O_BINARY;
576 
577  if (fptr->rbuf.len == 0 || fptr->mode & FMODE_DUPLEX) {
578  return setmode(fptr->fd, O_BINARY);
579  }
580  flush_before_seek(fptr);
581  return setmode(fptr->fd, O_BINARY);
582 }
583 #define SET_BINARY_MODE_WITH_SEEK_CUR(fptr) set_binary_mode_with_seek_cur(fptr)
584 
585 #else
586 /* Unix */
587 # define DEFAULT_TEXTMODE 0
588 #define NEED_READCONV(fptr) ((fptr)->encs.enc2 != NULL || NEED_NEWLINE_DECORATOR_ON_READ(fptr))
589 #define NEED_WRITECONV(fptr) (((fptr)->encs.enc != NULL && (fptr)->encs.enc != rb_ascii8bit_encoding()) || NEED_NEWLINE_DECORATOR_ON_WRITE(fptr) || ((fptr)->encs.ecflags & (ECONV_DECORATOR_MASK|ECONV_STATEFUL_DECORATOR_MASK)))
590 #define SET_BINARY_MODE(fptr) (void)(fptr)
591 #define NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr) (void)(fptr)
592 #define SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags) ((void)(enc2), (void)(ecflags))
593 #define SET_BINARY_MODE_WITH_SEEK_CUR(fptr) (void)(fptr)
594 #endif
595 
596 #if !defined HAVE_SHUTDOWN && !defined shutdown
597 #define shutdown(a,b) 0
598 #endif
599 
600 #if defined(_WIN32)
601 #define is_socket(fd, path) rb_w32_is_socket(fd)
602 #elif !defined(S_ISSOCK)
603 #define is_socket(fd, path) 0
604 #else
605 static int
606 is_socket(int fd, VALUE path)
607 {
608  struct stat sbuf;
609  if (fstat(fd, &sbuf) < 0)
610  rb_sys_fail_path(path);
611  return S_ISSOCK(sbuf.st_mode);
612 }
613 #endif
614 
615 static const char closed_stream[] = "closed stream";
616 
617 void
619 {
620  rb_raise(rb_eEOFError, "end of file reached");
621 }
622 
623 VALUE
625 {
626  rb_check_frozen(io);
627  return io;
628 }
629 
630 void
632 {
633  if (!fptr) {
634  rb_raise(rb_eIOError, "uninitialized stream");
635  }
636 }
637 
638 void
640 {
642  if (fptr->fd < 0) {
644  }
645 }
646 
647 static rb_io_t *
649 {
650  rb_io_t *fptr = RFILE(io)->fptr;
652  return fptr;
653 }
654 
655 VALUE
657 {
658  return rb_convert_type(io, T_FILE, "IO", "to_io");
659 }
660 
661 VALUE
663 {
664  return rb_check_convert_type(io, T_FILE, "IO", "to_io");
665 }
666 
667 VALUE
669 {
670  VALUE write_io;
671  write_io = rb_io_get_fptr(io)->tied_io_for_writing;
672  if (write_io) {
673  return write_io;
674  }
675  return io;
676 }
677 
678 VALUE
680 {
681  VALUE write_io;
682  rb_io_t *fptr = rb_io_get_fptr(io);
683  if (!RTEST(w)) {
684  w = 0;
685  }
686  else {
687  GetWriteIO(w);
688  }
689  write_io = fptr->tied_io_for_writing;
690  fptr->tied_io_for_writing = w;
691  return write_io ? write_io : Qnil;
692 }
693 
694 /*
695  * call-seq:
696  * IO.try_convert(obj) -> io or nil
697  *
698  * Try to convert <i>obj</i> into an IO, using to_io method.
699  * Returns converted IO or +nil+ if <i>obj</i> cannot be converted
700  * for any reason.
701  *
702  * IO.try_convert(STDOUT) #=> STDOUT
703  * IO.try_convert("STDOUT") #=> nil
704  *
705  * require 'zlib'
706  * f = open("/tmp/zz.gz") #=> #<File:/tmp/zz.gz>
707  * z = Zlib::GzipReader.open(f) #=> #<Zlib::GzipReader:0x81d8744>
708  * IO.try_convert(z) #=> #<File:/tmp/zz.gz>
709  *
710  */
711 static VALUE
713 {
714  return rb_io_check_io(io);
715 }
716 
717 #if !(defined(RUBY_TEST_CRLF_ENVIRONMENT) || defined(_WIN32))
718 static void
720 {
721  off_t r;
722  rb_io_check_closed(fptr);
723  if (fptr->rbuf.len == 0 || fptr->mode & FMODE_DUPLEX)
724  return;
725  /* xxx: target position may be negative if buffer is filled by ungetc */
726  errno = 0;
727  r = lseek(fptr->fd, -fptr->rbuf.len, SEEK_CUR);
728  if (r < 0 && errno) {
729  if (errno == ESPIPE)
730  fptr->mode |= FMODE_DUPLEX;
731  return;
732  }
733  fptr->rbuf.off = 0;
734  fptr->rbuf.len = 0;
735  return;
736 }
737 #endif
738 
739 static rb_encoding *io_input_encoding(rb_io_t *fptr);
740 
741 static void
743 {
744  long len = RSTRING_LEN(str);
745 
746  if (fptr->rbuf.ptr == NULL) {
747  const int min_capa = IO_RBUF_CAPA_FOR(fptr);
748  fptr->rbuf.off = 0;
749  fptr->rbuf.len = 0;
750 #if SIZEOF_LONG > SIZEOF_INT
751  if (len > INT_MAX)
752  rb_raise(rb_eIOError, "ungetbyte failed");
753 #endif
754  if (len > min_capa)
755  fptr->rbuf.capa = (int)len;
756  else
757  fptr->rbuf.capa = min_capa;
758  fptr->rbuf.ptr = ALLOC_N(char, fptr->rbuf.capa);
759  }
760  if (fptr->rbuf.capa < len + fptr->rbuf.len) {
761  rb_raise(rb_eIOError, "ungetbyte failed");
762  }
763  if (fptr->rbuf.off < len) {
764  MEMMOVE(fptr->rbuf.ptr+fptr->rbuf.capa-fptr->rbuf.len,
765  fptr->rbuf.ptr+fptr->rbuf.off,
766  char, fptr->rbuf.len);
767  fptr->rbuf.off = fptr->rbuf.capa-fptr->rbuf.len;
768  }
769  fptr->rbuf.off-=(int)len;
770  fptr->rbuf.len+=(int)len;
771  MEMMOVE(fptr->rbuf.ptr+fptr->rbuf.off, RSTRING_PTR(str), char, len);
772 }
773 
774 static rb_io_t *
776 {
777  if (io_fflush(fptr) < 0)
778  rb_sys_fail(0);
779  io_unread(fptr);
780  errno = 0;
781  return fptr;
782 }
783 
784 #define io_seek(fptr, ofs, whence) (errno = 0, lseek(flush_before_seek(fptr)->fd, (ofs), (whence)))
785 #define io_tell(fptr) lseek(flush_before_seek(fptr)->fd, 0, SEEK_CUR)
786 
787 #ifndef SEEK_CUR
788 # define SEEK_SET 0
789 # define SEEK_CUR 1
790 # define SEEK_END 2
791 #endif
792 
793 void
795 {
796  rb_io_check_closed(fptr);
797  if (!(fptr->mode & FMODE_READABLE)) {
798  rb_raise(rb_eIOError, "not opened for reading");
799  }
800  if (fptr->wbuf.len) {
801  if (io_fflush(fptr) < 0)
802  rb_sys_fail(0);
803  }
804  if (fptr->tied_io_for_writing) {
805  rb_io_t *wfptr;
806  GetOpenFile(fptr->tied_io_for_writing, wfptr);
807  if (io_fflush(wfptr) < 0)
808  rb_sys_fail(0);
809  }
810 }
811 
812 void
814 {
816  if (READ_CHAR_PENDING(fptr)) {
817  rb_raise(rb_eIOError, "byte oriented read for character buffered IO");
818  }
819 }
820 
821 void
823 {
825 }
826 
827 static rb_encoding*
829 {
830  if (fptr->encs.enc) {
831  return fptr->encs.enc;
832  }
834 }
835 
836 static rb_encoding*
838 {
839  if (fptr->encs.enc2) {
840  return fptr->encs.enc2;
841  }
842  return io_read_encoding(fptr);
843 }
844 
845 void
847 {
848  rb_io_check_closed(fptr);
849  if (!(fptr->mode & FMODE_WRITABLE)) {
850  rb_raise(rb_eIOError, "not opened for writing");
851  }
852  if (fptr->rbuf.len) {
853  io_unread(fptr);
854  }
855 }
856 
857 int
859 {
860  /* This function is used for bytes and chars. Confusing. */
861  if (READ_CHAR_PENDING(fptr))
862  return 1; /* should raise? */
863  return READ_DATA_PENDING(fptr);
864 }
865 
866 void
868 {
869  if (!READ_DATA_PENDING(fptr)) {
870  rb_thread_wait_fd(fptr->fd);
871  }
872  return;
873 }
874 
875 int
877 {
878  if (err == EMFILE || err == ENFILE || err == ENOMEM) {
879  rb_gc();
880  return 1;
881  }
882  return 0;
883 }
884 
885 static int
886 ruby_dup(int orig)
887 {
888  int fd;
889 
890  fd = rb_cloexec_dup(orig);
891  if (fd < 0) {
892  int e = errno;
893  if (rb_gc_for_fd(e)) {
894  fd = rb_cloexec_dup(orig);
895  }
896  if (fd < 0) {
897  rb_syserr_fail(e, 0);
898  }
899  }
900  rb_update_max_fd(fd);
901  return fd;
902 }
903 
904 static VALUE
906 {
907  NEWOBJ_OF(io, struct RFile, klass, T_FILE);
908 
909  io->fptr = 0;
910 
911  return (VALUE)io;
912 }
913 
914 #ifndef S_ISREG
915 # define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
916 #endif
917 
919  int fd;
920  void *buf;
921  size_t capa;
922 };
923 
925  int fd;
926  const void *buf;
927  size_t capa;
928 };
929 
930 #ifdef HAVE_WRITEV
931 struct io_internal_writev_struct {
932  int fd;
933  int iovcnt;
934  const struct iovec *iov;
935 };
936 #endif
937 
938 static VALUE
940 {
941  struct io_internal_read_struct *iis = ptr;
942  return read(iis->fd, iis->buf, iis->capa);
943 }
944 
945 static VALUE
947 {
948  struct io_internal_write_struct *iis = ptr;
949  return write(iis->fd, iis->buf, iis->capa);
950 }
951 
952 static void*
954 {
955  struct io_internal_write_struct *iis = ptr;
956  return (void*)(intptr_t)write(iis->fd, iis->buf, iis->capa);
957 }
958 
959 #ifdef HAVE_WRITEV
960 static VALUE
961 internal_writev_func(void *ptr)
962 {
963  struct io_internal_writev_struct *iis = ptr;
964  return writev(iis->fd, iis->iov, iis->iovcnt);
965 }
966 #endif
967 
968 static ssize_t
969 rb_read_internal(int fd, void *buf, size_t count)
970 {
971  struct io_internal_read_struct iis;
972  iis.fd = fd;
973  iis.buf = buf;
974  iis.capa = count;
975 
976  return (ssize_t)rb_thread_io_blocking_region(internal_read_func, &iis, fd);
977 }
978 
979 static ssize_t
980 rb_write_internal(int fd, const void *buf, size_t count)
981 {
982  struct io_internal_write_struct iis;
983  iis.fd = fd;
984  iis.buf = buf;
985  iis.capa = count;
986 
987  return (ssize_t)rb_thread_io_blocking_region(internal_write_func, &iis, fd);
988 }
989 
990 static ssize_t
991 rb_write_internal2(int fd, const void *buf, size_t count)
992 {
993  struct io_internal_write_struct iis;
994  iis.fd = fd;
995  iis.buf = buf;
996  iis.capa = count;
997 
999  RUBY_UBF_IO, NULL);
1000 }
1001 
1002 #ifdef HAVE_WRITEV
1003 static ssize_t
1004 rb_writev_internal(int fd, const struct iovec *iov, int iovcnt)
1005 {
1006  struct io_internal_writev_struct iis;
1007  iis.fd = fd;
1008  iis.iov = iov;
1009  iis.iovcnt = iovcnt;
1010 
1011  return (ssize_t)rb_thread_io_blocking_region(internal_writev_func, &iis, fd);
1012 }
1013 #endif
1014 
1015 static VALUE
1017 {
1018  rb_io_t *fptr = arg;
1019  long l = fptr->wbuf.len;
1020  ssize_t r = write(fptr->fd, fptr->wbuf.ptr+fptr->wbuf.off, (size_t)l);
1021 
1022  if (fptr->wbuf.len <= r) {
1023  fptr->wbuf.off = 0;
1024  fptr->wbuf.len = 0;
1025  return 0;
1026  }
1027  if (0 <= r) {
1028  fptr->wbuf.off += (int)r;
1029  fptr->wbuf.len -= (int)r;
1030  errno = EAGAIN;
1031  }
1032  return (VALUE)-1;
1033 }
1034 
1035 static void*
1037 {
1039 
1040  /*
1041  * rb_thread_call_without_gvl2 uses 0 as interrupted.
1042  * So, we need to avoid to use 0.
1043  */
1044  return !result ? (void*)1 : (void*)result;
1045 }
1046 
1047 static VALUE
1049 {
1050  rb_io_t *fptr = (rb_io_t *)arg;
1052 }
1053 
1054 static VALUE
1056 {
1057  rb_io_t *fptr = (rb_io_t *)arg;
1058  VALUE ret;
1059 
1061  RUBY_UBF_IO, NULL);
1062 
1063  if (!ret) {
1064  /* pending async interrupt is there. */
1065  errno = EAGAIN;
1066  return -1;
1067  }
1068  else if (ret == 1) {
1069  return 0;
1070  }
1071  return ret;
1072 }
1073 
1074 static inline int
1076 {
1077  if (fptr->write_lock) {
1078  if (rb_mutex_owned_p(fptr->write_lock))
1079  return (int)io_flush_buffer_async2((VALUE)fptr);
1080  else
1081  return (int)rb_mutex_synchronize(fptr->write_lock, io_flush_buffer_async2, (VALUE)fptr);
1082  }
1083  else {
1084  return (int)io_flush_buffer_async((VALUE)fptr);
1085  }
1086 }
1087 
1088 static int
1090 {
1091  rb_io_check_closed(fptr);
1092  if (fptr->wbuf.len == 0)
1093  return 0;
1094  rb_io_check_closed(fptr);
1095  while (fptr->wbuf.len > 0 && io_flush_buffer(fptr) != 0) {
1096  if (!rb_io_wait_writable(fptr->fd))
1097  return -1;
1098  rb_io_check_closed(fptr);
1099  }
1100  return 0;
1101 }
1102 
1103 int
1105 {
1106  if (f < 0) {
1108  }
1109  switch (errno) {
1110  case EINTR:
1111 #if defined(ERESTART)
1112  case ERESTART:
1113 #endif
1115  return TRUE;
1116 
1117  case EAGAIN:
1118 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
1119  case EWOULDBLOCK:
1120 #endif
1121  rb_thread_wait_fd(f);
1122  return TRUE;
1123 
1124  default:
1125  return FALSE;
1126  }
1127 }
1128 
1129 int
1131 {
1132  if (f < 0) {
1134  }
1135  switch (errno) {
1136  case EINTR:
1137 #if defined(ERESTART)
1138  case ERESTART:
1139 #endif
1140  /*
1141  * In old Linux, several special files under /proc and /sys don't handle
1142  * select properly. Thus we need avoid to call if don't use O_NONBLOCK.
1143  * Otherwise, we face nasty hang up. Sigh.
1144  * e.g. http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=commit;h=31b07093c44a7a442394d44423e21d783f5523b8
1145  * http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=commit;h=31b07093c44a7a442394d44423e21d783f5523b8
1146  * In EINTR case, we only need to call RUBY_VM_CHECK_INTS_BLOCKING().
1147  * Then rb_thread_check_ints() is enough.
1148  */
1150  return TRUE;
1151 
1152  case EAGAIN:
1153 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
1154  case EWOULDBLOCK:
1155 #endif
1157  return TRUE;
1158 
1159  default:
1160  return FALSE;
1161  }
1162 }
1163 
1164 static void
1166 {
1167  if (!fptr->writeconv_initialized) {
1168  const char *senc, *denc;
1169  rb_encoding *enc;
1170  int ecflags;
1171  VALUE ecopts;
1172 
1173  fptr->writeconv_initialized = 1;
1174 
1175  ecflags = fptr->encs.ecflags & ~ECONV_NEWLINE_DECORATOR_READ_MASK;
1176  ecopts = fptr->encs.ecopts;
1177 
1178  if (!fptr->encs.enc || (fptr->encs.enc == rb_ascii8bit_encoding() && !fptr->encs.enc2)) {
1179  /* no encoding conversion */
1180  fptr->writeconv_pre_ecflags = 0;
1181  fptr->writeconv_pre_ecopts = Qnil;
1182  fptr->writeconv = rb_econv_open_opts("", "", ecflags, ecopts);
1183  if (!fptr->writeconv)
1184  rb_exc_raise(rb_econv_open_exc("", "", ecflags));
1185  fptr->writeconv_asciicompat = Qnil;
1186  }
1187  else {
1188  enc = fptr->encs.enc2 ? fptr->encs.enc2 : fptr->encs.enc;
1190  if (!senc && !(fptr->encs.ecflags & ECONV_STATEFUL_DECORATOR_MASK)) {
1191  /* single conversion */
1192  fptr->writeconv_pre_ecflags = ecflags;
1193  fptr->writeconv_pre_ecopts = ecopts;
1194  fptr->writeconv = NULL;
1195  fptr->writeconv_asciicompat = Qnil;
1196  }
1197  else {
1198  /* double conversion */
1200  fptr->writeconv_pre_ecopts = ecopts;
1201  if (senc) {
1202  denc = rb_enc_name(enc);
1203  fptr->writeconv_asciicompat = rb_str_new2(senc);
1204  }
1205  else {
1206  senc = denc = "";
1208  }
1210  ecopts = fptr->encs.ecopts;
1211  fptr->writeconv = rb_econv_open_opts(senc, denc, ecflags, ecopts);
1212  if (!fptr->writeconv)
1213  rb_exc_raise(rb_econv_open_exc(senc, denc, ecflags));
1214  }
1215  }
1216  }
1217 }
1218 
1219 /* writing functions */
1223  const char *ptr;
1224  long length;
1225 };
1226 
1227 struct write_arg {
1230  int nosync;
1231 };
1232 
1233 #ifdef HAVE_WRITEV
1234 static VALUE
1236 {
1237  struct binwrite_arg *p = (struct binwrite_arg *)arg;
1238  rb_io_t *fptr = p->fptr;
1239  long r;
1240 
1241  if (fptr->wbuf.len) {
1242  struct iovec iov[2];
1243 
1244  iov[0].iov_base = fptr->wbuf.ptr+fptr->wbuf.off;
1245  iov[0].iov_len = fptr->wbuf.len;
1246  iov[1].iov_base = (char *)p->ptr;
1247  iov[1].iov_len = p->length;
1248 
1249  r = rb_writev_internal(fptr->fd, iov, 2);
1250 
1251  if (r == -1)
1252  return -1;
1253 
1254  if (fptr->wbuf.len <= r) {
1255  r -= fptr->wbuf.len;
1256  fptr->wbuf.off = 0;
1257  fptr->wbuf.len = 0;
1258  }
1259  else {
1260  fptr->wbuf.off += (int)r;
1261  fptr->wbuf.len -= (int)r;
1262  r = 0L;
1263  }
1264  }
1265  else {
1266  r = rb_write_internal(fptr->fd, p->ptr, p->length);
1267  }
1268 
1269  return r;
1270 }
1271 #else
1272 static VALUE
1274 {
1275  struct binwrite_arg *p = (struct binwrite_arg *)arg;
1276  rb_io_t *fptr = p->fptr;
1277  long l, len;
1278 
1279  l = len = p->length;
1280 
1281  if (fptr->wbuf.len) {
1282  if (fptr->wbuf.len+len <= fptr->wbuf.capa) {
1283  if (fptr->wbuf.capa < fptr->wbuf.off+fptr->wbuf.len+len) {
1284  MEMMOVE(fptr->wbuf.ptr, fptr->wbuf.ptr+fptr->wbuf.off, char, fptr->wbuf.len);
1285  fptr->wbuf.off = 0;
1286  }
1287  MEMMOVE(fptr->wbuf.ptr+fptr->wbuf.off+fptr->wbuf.len, p->ptr, char, len);
1288  fptr->wbuf.len += (int)len;
1289  l = 0;
1290  }
1291  if (io_fflush(fptr) < 0)
1292  return -2L; /* fail in fflush */
1293  if (l == 0)
1294  return len;
1295  }
1296 
1297  if (fptr->stdio_file != stderr && !rb_thread_fd_writable(fptr->fd))
1298  rb_io_check_closed(fptr);
1299 
1300  return rb_write_internal(p->fptr->fd, p->ptr, p->length);
1301 }
1302 #endif
1303 
1304 static long
1305 io_binwrite(VALUE str, const char *ptr, long len, rb_io_t *fptr, int nosync)
1306 {
1307  long n, r, offset = 0;
1308 
1309  /* don't write anything if current thread has a pending interrupt. */
1311 
1312  if ((n = len) <= 0) return n;
1313  if (fptr->wbuf.ptr == NULL && !(!nosync && (fptr->mode & FMODE_SYNC))) {
1314  fptr->wbuf.off = 0;
1315  fptr->wbuf.len = 0;
1316  fptr->wbuf.capa = IO_WBUF_CAPA_MIN;
1317  fptr->wbuf.ptr = ALLOC_N(char, fptr->wbuf.capa);
1318  fptr->write_lock = rb_mutex_new();
1319  rb_mutex_allow_trap(fptr->write_lock, 1);
1320  }
1321  if ((!nosync && (fptr->mode & (FMODE_SYNC|FMODE_TTY))) ||
1322  (fptr->wbuf.ptr && fptr->wbuf.capa <= fptr->wbuf.len + len)) {
1323  struct binwrite_arg arg;
1324 
1325  arg.fptr = fptr;
1326  arg.str = str;
1327  retry:
1328  arg.ptr = ptr + offset;
1329  arg.length = n;
1330  if (fptr->write_lock) {
1332  }
1333  else {
1334  r = io_binwrite_string((VALUE)&arg);
1335  }
1336  /* xxx: other threads may modify given string. */
1337  if (r == n) return len;
1338  if (0 <= r) {
1339  offset += r;
1340  n -= r;
1341  errno = EAGAIN;
1342  }
1343  if (r == -2L)
1344  return -1L;
1345  if (rb_io_wait_writable(fptr->fd)) {
1346  rb_io_check_closed(fptr);
1347  if (offset < len)
1348  goto retry;
1349  }
1350  return -1L;
1351  }
1352 
1353  if (fptr->wbuf.off) {
1354  if (fptr->wbuf.len)
1355  MEMMOVE(fptr->wbuf.ptr, fptr->wbuf.ptr+fptr->wbuf.off, char, fptr->wbuf.len);
1356  fptr->wbuf.off = 0;
1357  }
1358  MEMMOVE(fptr->wbuf.ptr+fptr->wbuf.off+fptr->wbuf.len, ptr+offset, char, len);
1359  fptr->wbuf.len += (int)len;
1360  return len;
1361 }
1362 
1363 # define MODE_BTMODE(a,b,c) ((fmode & FMODE_BINMODE) ? (b) : \
1364  (fmode & FMODE_TEXTMODE) ? (c) : (a))
1365 static VALUE
1366 do_writeconv(VALUE str, rb_io_t *fptr, int *converted)
1367 {
1368  if (NEED_WRITECONV(fptr)) {
1369  VALUE common_encoding = Qnil;
1370  SET_BINARY_MODE(fptr);
1371 
1372  make_writeconv(fptr);
1373 
1374  if (fptr->writeconv) {
1375 #define fmode (fptr->mode)
1376  if (!NIL_P(fptr->writeconv_asciicompat))
1377  common_encoding = fptr->writeconv_asciicompat;
1378  else if (MODE_BTMODE(DEFAULT_TEXTMODE,0,1) && !rb_enc_asciicompat(rb_enc_get(str))) {
1379  rb_raise(rb_eArgError, "ASCII incompatible string written for text mode IO without encoding conversion: %s",
1380  rb_enc_name(rb_enc_get(str)));
1381  }
1382 #undef fmode
1383  }
1384  else {
1385  if (fptr->encs.enc2)
1386  common_encoding = rb_enc_from_encoding(fptr->encs.enc2);
1387  else if (fptr->encs.enc != rb_ascii8bit_encoding())
1388  common_encoding = rb_enc_from_encoding(fptr->encs.enc);
1389  }
1390 
1391  if (!NIL_P(common_encoding)) {
1392  str = rb_str_encode(str, common_encoding,
1394  *converted = 1;
1395  }
1396 
1397  if (fptr->writeconv) {
1399  *converted = 1;
1400  }
1401  }
1402 #if defined(RUBY_TEST_CRLF_ENVIRONMENT) || defined(_WIN32)
1403 #define fmode (fptr->mode)
1404  else if (MODE_BTMODE(DEFAULT_TEXTMODE,0,1)) {
1405  if ((fptr->mode & FMODE_READABLE) &&
1407  setmode(fptr->fd, O_BINARY);
1408  }
1409  else {
1410  setmode(fptr->fd, O_TEXT);
1411  }
1412  if (!rb_enc_asciicompat(rb_enc_get(str))) {
1413  rb_raise(rb_eArgError, "ASCII incompatible string written for text mode IO without encoding conversion: %s",
1414  rb_enc_name(rb_enc_get(str)));
1415  }
1416  }
1417 #undef fmode
1418 #endif
1419  return str;
1420 }
1421 
1422 static long
1423 io_fwrite(VALUE str, rb_io_t *fptr, int nosync)
1424 {
1425  int converted = 0;
1426  VALUE tmp;
1427  long n, len;
1428  const char *ptr;
1429 #ifdef _WIN32
1430  if (fptr->mode & FMODE_TTY) {
1431  long len = rb_w32_write_console(str, fptr->fd);
1432  if (len > 0) return len;
1433  }
1434 #endif
1435  str = do_writeconv(str, fptr, &converted);
1436  if (converted)
1437  OBJ_FREEZE(str);
1438 
1439  tmp = rb_str_tmp_frozen_acquire(str);
1440  RSTRING_GETMEM(tmp, ptr, len);
1441  n = io_binwrite(tmp, ptr, len, fptr, nosync);
1442  rb_str_tmp_frozen_release(str, tmp);
1443 
1444  return n;
1445 }
1446 
1447 ssize_t
1448 rb_io_bufwrite(VALUE io, const void *buf, size_t size)
1449 {
1450  rb_io_t *fptr;
1451 
1452  GetOpenFile(io, fptr);
1453  rb_io_check_writable(fptr);
1454  return (ssize_t)io_binwrite(0, buf, (long)size, fptr, 0);
1455 }
1456 
1457 static VALUE
1458 io_write(VALUE io, VALUE str, int nosync)
1459 {
1460  rb_io_t *fptr;
1461  long n;
1462  VALUE tmp;
1463 
1464  io = GetWriteIO(io);
1465  str = rb_obj_as_string(str);
1466  tmp = rb_io_check_io(io);
1467  if (NIL_P(tmp)) {
1468  /* port is not IO, call write method for it. */
1469  return rb_funcall(io, id_write, 1, str);
1470  }
1471  io = tmp;
1472  if (RSTRING_LEN(str) == 0) return INT2FIX(0);
1473 
1474  GetOpenFile(io, fptr);
1475  rb_io_check_writable(fptr);
1476 
1477  n = io_fwrite(str, fptr, nosync);
1478  if (n == -1L) rb_sys_fail_path(fptr->pathv);
1479 
1480  return LONG2FIX(n);
1481 }
1482 
1483 /*
1484  * call-seq:
1485  * ios.write(string) -> integer
1486  *
1487  * Writes the given string to <em>ios</em>. The stream must be opened
1488  * for writing. If the argument is not a string, it will be converted
1489  * to a string using <code>to_s</code>. Returns the number of bytes
1490  * written.
1491  *
1492  * count = $stdout.write("This is a test\n")
1493  * puts "That was #{count} bytes of data"
1494  *
1495  * <em>produces:</em>
1496  *
1497  * This is a test
1498  * That was 15 bytes of data
1499  */
1500 
1501 static VALUE
1503 {
1504  return io_write(io, str, 0);
1505 }
1506 
1507 VALUE
1509 {
1510  return rb_funcallv(io, id_write, 1, &str);
1511 }
1512 
1513 /*
1514  * call-seq:
1515  * ios << obj -> ios
1516  *
1517  * String Output---Writes <i>obj</i> to <em>ios</em>.
1518  * <i>obj</i> will be converted to a string using
1519  * <code>to_s</code>.
1520  *
1521  * $stdout << "Hello " << "world!\n"
1522  *
1523  * <em>produces:</em>
1524  *
1525  * Hello world!
1526  */
1527 
1528 
1529 VALUE
1531 {
1532  rb_io_write(io, str);
1533  return io;
1534 }
1535 
1536 #ifdef HAVE_FSYNC
1537 static VALUE
1538 nogvl_fsync(void *ptr)
1539 {
1540  rb_io_t *fptr = ptr;
1541 
1542 #ifdef _WIN32
1543  if (GetFileType((HANDLE)rb_w32_get_osfhandle(fptr->fd)) != FILE_TYPE_DISK)
1544  return 0;
1545 #endif
1546  return (VALUE)fsync(fptr->fd);
1547 }
1548 #endif
1549 
1550 VALUE
1551 rb_io_flush_raw(VALUE io, int sync)
1552 {
1553  rb_io_t *fptr;
1554 
1555  if (!RB_TYPE_P(io, T_FILE)) {
1556  return rb_funcall(io, id_flush, 0);
1557  }
1558 
1559  io = GetWriteIO(io);
1560  GetOpenFile(io, fptr);
1561 
1562  if (fptr->mode & FMODE_WRITABLE) {
1563  if (io_fflush(fptr) < 0)
1564  rb_sys_fail(0);
1565  }
1566  if (fptr->mode & FMODE_READABLE) {
1567  io_unread(fptr);
1568  }
1569 
1570  return io;
1571 }
1572 
1573 /*
1574  * call-seq:
1575  * ios.flush -> ios
1576  *
1577  * Flushes any buffered data within <em>ios</em> to the underlying
1578  * operating system (note that this is Ruby internal buffering only;
1579  * the OS may buffer the data as well).
1580  *
1581  * $stdout.print "no newline"
1582  * $stdout.flush
1583  *
1584  * <em>produces:</em>
1585  *
1586  * no newline
1587  */
1588 
1589 VALUE
1591 {
1592  return rb_io_flush_raw(io, 1);
1593 }
1594 
1595 /*
1596  * call-seq:
1597  * ios.pos -> integer
1598  * ios.tell -> integer
1599  *
1600  * Returns the current offset (in bytes) of <em>ios</em>.
1601  *
1602  * f = File.new("testfile")
1603  * f.pos #=> 0
1604  * f.gets #=> "This is line one\n"
1605  * f.pos #=> 17
1606  */
1607 
1608 static VALUE
1610 {
1611  rb_io_t *fptr;
1612  off_t pos;
1613 
1614  GetOpenFile(io, fptr);
1615  pos = io_tell(fptr);
1616  if (pos < 0 && errno) rb_sys_fail_path(fptr->pathv);
1617  pos -= fptr->rbuf.len;
1618  return OFFT2NUM(pos);
1619 }
1620 
1621 static VALUE
1622 rb_io_seek(VALUE io, VALUE offset, int whence)
1623 {
1624  rb_io_t *fptr;
1625  off_t pos;
1626 
1627  pos = NUM2OFFT(offset);
1628  GetOpenFile(io, fptr);
1629  pos = io_seek(fptr, pos, whence);
1630  if (pos < 0 && errno) rb_sys_fail_path(fptr->pathv);
1631 
1632  return INT2FIX(0);
1633 }
1634 
1635 static int
1637 {
1638  if (vwhence == sym_SET)
1639  return SEEK_SET;
1640  if (vwhence == sym_CUR)
1641  return SEEK_CUR;
1642  if (vwhence == sym_END)
1643  return SEEK_END;
1644 #ifdef SEEK_DATA
1645  if (vwhence == sym_DATA)
1646  return SEEK_DATA;
1647 #endif
1648 #ifdef SEEK_HOLE
1649  if (vwhence == sym_HOLE)
1650  return SEEK_HOLE;
1651 #endif
1652  return NUM2INT(vwhence);
1653 }
1654 
1655 /*
1656  * call-seq:
1657  * ios.seek(amount, whence=IO::SEEK_SET) -> 0
1658  *
1659  * Seeks to a given offset <i>anInteger</i> in the stream according to
1660  * the value of <i>whence</i>:
1661  *
1662  * :CUR or IO::SEEK_CUR | Seeks to _amount_ plus current position
1663  * ----------------------+--------------------------------------------------
1664  * :END or IO::SEEK_END | Seeks to _amount_ plus end of stream (you
1665  * | probably want a negative value for _amount_)
1666  * ----------------------+--------------------------------------------------
1667  * :SET or IO::SEEK_SET | Seeks to the absolute location given by _amount_
1668  *
1669  * Example:
1670  *
1671  * f = File.new("testfile")
1672  * f.seek(-13, IO::SEEK_END) #=> 0
1673  * f.readline #=> "And so on...\n"
1674  */
1675 
1676 static VALUE
1678 {
1679  VALUE offset, ptrname;
1680  int whence = SEEK_SET;
1681 
1682  if (rb_scan_args(argc, argv, "11", &offset, &ptrname) == 2) {
1683  whence = interpret_seek_whence(ptrname);
1684  }
1685 
1686  return rb_io_seek(io, offset, whence);
1687 }
1688 
1689 /*
1690  * call-seq:
1691  * ios.pos = integer -> integer
1692  *
1693  * Seeks to the given position (in bytes) in <em>ios</em>.
1694  * It is not guaranteed that seeking to the right position when <em>ios</em>
1695  * is textmode.
1696  *
1697  * f = File.new("testfile")
1698  * f.pos = 17
1699  * f.gets #=> "This is line two\n"
1700  */
1701 
1702 static VALUE
1704 {
1705  rb_io_t *fptr;
1706  off_t pos;
1707 
1708  pos = NUM2OFFT(offset);
1709  GetOpenFile(io, fptr);
1710  pos = io_seek(fptr, pos, SEEK_SET);
1711  if (pos < 0 && errno) rb_sys_fail_path(fptr->pathv);
1712 
1713  return OFFT2NUM(pos);
1714 }
1715 
1716 static void clear_readconv(rb_io_t *fptr);
1717 
1718 /*
1719  * call-seq:
1720  * ios.rewind -> 0
1721  *
1722  * Positions <em>ios</em> to the beginning of input, resetting
1723  * <code>lineno</code> to zero.
1724  *
1725  * f = File.new("testfile")
1726  * f.readline #=> "This is line one\n"
1727  * f.rewind #=> 0
1728  * f.lineno #=> 0
1729  * f.readline #=> "This is line one\n"
1730  *
1731  * Note that it cannot be used with streams such as pipes, ttys, and sockets.
1732  */
1733 
1734 static VALUE
1736 {
1737  rb_io_t *fptr;
1738 
1739  GetOpenFile(io, fptr);
1740  if (io_seek(fptr, 0L, 0) < 0 && errno) rb_sys_fail_path(fptr->pathv);
1741  if (io == ARGF.current_file) {
1742  ARGF.lineno -= fptr->lineno;
1743  }
1744  fptr->lineno = 0;
1745  if (fptr->readconv) {
1746  clear_readconv(fptr);
1747  }
1748 
1749  return INT2FIX(0);
1750 }
1751 
1752 static int
1754 {
1755  ssize_t r;
1756 
1757  if (fptr->rbuf.ptr == NULL) {
1758  fptr->rbuf.off = 0;
1759  fptr->rbuf.len = 0;
1760  fptr->rbuf.capa = IO_RBUF_CAPA_FOR(fptr);
1761  fptr->rbuf.ptr = ALLOC_N(char, fptr->rbuf.capa);
1762 #ifdef _WIN32
1763  fptr->rbuf.capa--;
1764 #endif
1765  }
1766  if (fptr->rbuf.len == 0) {
1767  retry:
1768  {
1769  r = rb_read_internal(fptr->fd, fptr->rbuf.ptr, fptr->rbuf.capa);
1770  }
1771  if (r < 0) {
1772  if (rb_io_wait_readable(fptr->fd))
1773  goto retry;
1774  {
1775  int e = errno;
1776  VALUE path = rb_sprintf("fd:%d ", fptr->fd);
1777  if (!NIL_P(fptr->pathv)) {
1778  rb_str_append(path, fptr->pathv);
1779  }
1780  rb_syserr_fail_path(e, path);
1781  }
1782  }
1783  if (r > 0) rb_io_check_closed(fptr);
1784  fptr->rbuf.off = 0;
1785  fptr->rbuf.len = (int)r; /* r should be <= rbuf_capa */
1786  if (r == 0)
1787  return -1; /* EOF */
1788  }
1789  return 0;
1790 }
1791 
1792 /*
1793  * call-seq:
1794  * ios.eof -> true or false
1795  * ios.eof? -> true or false
1796  *
1797  * Returns true if <em>ios</em> is at end of file that means
1798  * there are no more data to read.
1799  * The stream must be opened for reading or an <code>IOError</code> will be
1800  * raised.
1801  *
1802  * f = File.new("testfile")
1803  * dummy = f.readlines
1804  * f.eof #=> true
1805  *
1806  * If <em>ios</em> is a stream such as pipe or socket, <code>IO#eof?</code>
1807  * blocks until the other end sends some data or closes it.
1808  *
1809  * r, w = IO.pipe
1810  * Thread.new { sleep 1; w.close }
1811  * r.eof? #=> true after 1 second blocking
1812  *
1813  * r, w = IO.pipe
1814  * Thread.new { sleep 1; w.puts "a" }
1815  * r.eof? #=> false after 1 second blocking
1816  *
1817  * r, w = IO.pipe
1818  * r.eof? # blocks forever
1819  *
1820  * Note that <code>IO#eof?</code> reads data to the input byte buffer.
1821  * So <code>IO#sysread</code> may not behave as you intend with
1822  * <code>IO#eof?</code>, unless you call <code>IO#rewind</code>
1823  * first (which is not available for some streams).
1824  */
1825 
1826 VALUE
1828 {
1829  rb_io_t *fptr;
1830 
1831  GetOpenFile(io, fptr);
1833 
1834  if (READ_CHAR_PENDING(fptr)) return Qfalse;
1835  if (READ_DATA_PENDING(fptr)) return Qfalse;
1836  READ_CHECK(fptr);
1837 #if defined(RUBY_TEST_CRLF_ENVIRONMENT) || defined(_WIN32)
1838  if (!NEED_READCONV(fptr) && NEED_NEWLINE_DECORATOR_ON_READ(fptr)) {
1839  return eof(fptr->fd) ? Qtrue : Qfalse;
1840  }
1841 #endif
1842  if (io_fillbuf(fptr) < 0) {
1843  return Qtrue;
1844  }
1845  return Qfalse;
1846 }
1847 
1848 /*
1849  * call-seq:
1850  * ios.sync -> true or false
1851  *
1852  * Returns the current ``sync mode'' of <em>ios</em>. When sync mode is
1853  * true, all output is immediately flushed to the underlying operating
1854  * system and is not buffered by Ruby internally. See also
1855  * <code>IO#fsync</code>.
1856  *
1857  * f = File.new("testfile")
1858  * f.sync #=> false
1859  */
1860 
1861 static VALUE
1863 {
1864  rb_io_t *fptr;
1865 
1866  io = GetWriteIO(io);
1867  GetOpenFile(io, fptr);
1868  return (fptr->mode & FMODE_SYNC) ? Qtrue : Qfalse;
1869 }
1870 
1871 #ifdef HAVE_FSYNC
1872 
1873 /*
1874  * call-seq:
1875  * ios.sync = boolean -> boolean
1876  *
1877  * Sets the ``sync mode'' to <code>true</code> or <code>false</code>.
1878  * When sync mode is true, all output is immediately flushed to the
1879  * underlying operating system and is not buffered internally. Returns
1880  * the new state. See also <code>IO#fsync</code>.
1881  *
1882  * f = File.new("testfile")
1883  * f.sync = true
1884  */
1885 
1886 static VALUE
1887 rb_io_set_sync(VALUE io, VALUE sync)
1888 {
1889  rb_io_t *fptr;
1890 
1891  io = GetWriteIO(io);
1892  GetOpenFile(io, fptr);
1893  if (RTEST(sync)) {
1894  fptr->mode |= FMODE_SYNC;
1895  }
1896  else {
1897  fptr->mode &= ~FMODE_SYNC;
1898  }
1899  return sync;
1900 }
1901 
1902 /*
1903  * call-seq:
1904  * ios.fsync -> 0 or nil
1905  *
1906  * Immediately writes all buffered data in <em>ios</em> to disk.
1907  * Note that <code>fsync</code> differs from
1908  * using <code>IO#sync=</code>. The latter ensures that data is flushed
1909  * from Ruby's buffers, but does not guarantee that the underlying
1910  * operating system actually writes it to disk.
1911  *
1912  * <code>NotImplementedError</code> is raised
1913  * if the underlying operating system does not support <em>fsync(2)</em>.
1914  */
1915 
1916 static VALUE
1917 rb_io_fsync(VALUE io)
1918 {
1919  rb_io_t *fptr;
1920 
1921  io = GetWriteIO(io);
1922  GetOpenFile(io, fptr);
1923 
1924  if (io_fflush(fptr) < 0)
1925  rb_sys_fail(0);
1926  if ((int)rb_thread_io_blocking_region(nogvl_fsync, fptr, fptr->fd) < 0)
1927  rb_sys_fail_path(fptr->pathv);
1928  return INT2FIX(0);
1929 }
1930 #else
1931 # define rb_io_fsync rb_f_notimplement
1932 # define rb_io_sync rb_f_notimplement
1933 static VALUE
1935 {
1936  rb_notimplement();
1937  UNREACHABLE;
1938 }
1939 #endif
1940 
1941 #ifdef HAVE_FDATASYNC
1942 static VALUE
1943 nogvl_fdatasync(void *ptr)
1944 {
1945  rb_io_t *fptr = ptr;
1946 
1947 #ifdef _WIN32
1948  if (GetFileType((HANDLE)rb_w32_get_osfhandle(fptr->fd)) != FILE_TYPE_DISK)
1949  return 0;
1950 #endif
1951  return (VALUE)fdatasync(fptr->fd);
1952 }
1953 
1954 /*
1955  * call-seq:
1956  * ios.fdatasync -> 0 or nil
1957  *
1958  * Immediately writes all buffered data in <em>ios</em> to disk.
1959  *
1960  * If the underlying operating system does not support <em>fdatasync(2)</em>,
1961  * <code>IO#fsync</code> is called instead (which might raise a
1962  * <code>NotImplementedError</code>).
1963  */
1964 
1965 static VALUE
1967 {
1968  rb_io_t *fptr;
1969 
1970  io = GetWriteIO(io);
1971  GetOpenFile(io, fptr);
1972 
1973  if (io_fflush(fptr) < 0)
1974  rb_sys_fail(0);
1975 
1976  if ((int)rb_thread_io_blocking_region(nogvl_fdatasync, fptr, fptr->fd) == 0)
1977  return INT2FIX(0);
1978 
1979  /* fall back */
1980  return rb_io_fsync(io);
1981 }
1982 #else
1983 #define rb_io_fdatasync rb_io_fsync
1984 #endif
1985 
1986 /*
1987  * call-seq:
1988  * ios.fileno -> integer
1989  * ios.to_i -> integer
1990  *
1991  * Returns an integer representing the numeric file descriptor for
1992  * <em>ios</em>.
1993  *
1994  * $stdin.fileno #=> 0
1995  * $stdout.fileno #=> 1
1996  */
1997 
1998 static VALUE
2000 {
2001  rb_io_t *fptr = RFILE(io)->fptr;
2002  int fd;
2003 
2004  rb_io_check_closed(fptr);
2005  fd = fptr->fd;
2006  return INT2FIX(fd);
2007 }
2008 
2009 
2010 /*
2011  * call-seq:
2012  * ios.pid -> integer
2013  *
2014  * Returns the process ID of a child process associated with
2015  * <em>ios</em>. This will be set by <code>IO.popen</code>.
2016  *
2017  * pipe = IO.popen("-")
2018  * if pipe
2019  * $stderr.puts "In parent, child pid is #{pipe.pid}"
2020  * else
2021  * $stderr.puts "In child, pid is #{$$}"
2022  * end
2023  *
2024  * <em>produces:</em>
2025  *
2026  * In child, pid is 26209
2027  * In parent, child pid is 26209
2028  */
2029 
2030 static VALUE
2032 {
2033  rb_io_t *fptr;
2034 
2035  GetOpenFile(io, fptr);
2036  if (!fptr->pid)
2037  return Qnil;
2038  return PIDT2NUM(fptr->pid);
2039 }
2040 
2041 
2042 /*
2043  * call-seq:
2044  * ios.inspect -> string
2045  *
2046  * Return a string describing this IO object.
2047  */
2048 
2049 static VALUE
2051 {
2052  rb_io_t *fptr;
2053  VALUE result;
2054  static const char closed[] = " (closed)";
2055 
2056  fptr = RFILE(obj)->fptr;
2057  if (!fptr) return rb_any_to_s(obj);
2058  result = rb_str_new_cstr("#<");
2059  rb_str_append(result, rb_class_name(CLASS_OF(obj)));
2060  rb_str_cat2(result, ":");
2061  if (NIL_P(fptr->pathv)) {
2062  if (fptr->fd < 0) {
2063  rb_str_cat(result, closed+1, strlen(closed)-1);
2064  }
2065  else {
2066  rb_str_catf(result, "fd %d", fptr->fd);
2067  }
2068  }
2069  else {
2070  rb_str_append(result, fptr->pathv);
2071  if (fptr->fd < 0) {
2072  rb_str_cat(result, closed, strlen(closed));
2073  }
2074  }
2075  return rb_str_cat2(result, ">");
2076 }
2077 
2078 /*
2079  * call-seq:
2080  * ios.to_io -> ios
2081  *
2082  * Returns <em>ios</em>.
2083  */
2084 
2085 static VALUE
2087 {
2088  return io;
2089 }
2090 
2091 /* reading functions */
2092 static long
2093 read_buffered_data(char *ptr, long len, rb_io_t *fptr)
2094 {
2095  int n;
2096 
2097  n = READ_DATA_PENDING_COUNT(fptr);
2098  if (n <= 0) return 0;
2099  if (n > len) n = (int)len;
2100  MEMMOVE(ptr, fptr->rbuf.ptr+fptr->rbuf.off, char, n);
2101  fptr->rbuf.off += n;
2102  fptr->rbuf.len -= n;
2103  return n;
2104 }
2105 
2106 static long
2107 io_bufread(char *ptr, long len, rb_io_t *fptr)
2108 {
2109  long offset = 0;
2110  long n = len;
2111  long c;
2112 
2113  if (READ_DATA_PENDING(fptr) == 0) {
2114  while (n > 0) {
2115  again:
2116  c = rb_read_internal(fptr->fd, ptr+offset, n);
2117  if (c == 0) break;
2118  if (c < 0) {
2119  if (rb_io_wait_readable(fptr->fd))
2120  goto again;
2121  return -1;
2122  }
2123  offset += c;
2124  if ((n -= c) <= 0) break;
2125  }
2126  return len - n;
2127  }
2128 
2129  while (n > 0) {
2130  c = read_buffered_data(ptr+offset, n, fptr);
2131  if (c > 0) {
2132  offset += c;
2133  if ((n -= c) <= 0) break;
2134  }
2135  rb_io_check_closed(fptr);
2136  if (io_fillbuf(fptr) < 0) {
2137  break;
2138  }
2139  }
2140  return len - n;
2141 }
2142 
2143 static void io_setstrbuf(VALUE *str, long len);
2144 
2145 struct bufread_arg {
2146  char *str_ptr;
2147  long len;
2149 };
2150 
2151 static VALUE
2153 {
2154  struct bufread_arg *p = (struct bufread_arg *)arg;
2155  p->len = io_bufread(p->str_ptr, p->len, p->fptr);
2156  return Qundef;
2157 }
2158 
2159 static long
2160 io_fread(VALUE str, long offset, long size, rb_io_t *fptr)
2161 {
2162  long len;
2163  struct bufread_arg arg;
2164 
2165  io_setstrbuf(&str, offset + size);
2166  arg.str_ptr = RSTRING_PTR(str) + offset;
2167  arg.len = size;
2168  arg.fptr = fptr;
2170  len = arg.len;
2171  if (len < 0) rb_sys_fail_path(fptr->pathv);
2172  return len;
2173 }
2174 
2175 ssize_t
2176 rb_io_bufread(VALUE io, void *buf, size_t size)
2177 {
2178  rb_io_t *fptr;
2179 
2180  GetOpenFile(io, fptr);
2181  rb_io_check_readable(fptr);
2182  return (ssize_t)io_bufread(buf, (long)size, fptr);
2183 }
2184 
2185 static long
2187 {
2188  struct stat st;
2189  off_t siz = READ_DATA_PENDING_COUNT(fptr);
2190  off_t pos;
2191 
2192  if (fstat(fptr->fd, &st) == 0 && S_ISREG(st.st_mode)
2193 #if defined(__HAIKU__)
2194  && (st.st_dev > 3)
2195 #endif
2196  )
2197  {
2198  if (io_fflush(fptr) < 0)
2199  rb_sys_fail(0);
2200  pos = lseek(fptr->fd, 0, SEEK_CUR);
2201  if (st.st_size >= pos && pos >= 0) {
2202  siz += st.st_size - pos;
2203  if (siz > LONG_MAX) {
2204  rb_raise(rb_eIOError, "file too big for single read");
2205  }
2206  }
2207  }
2208  else {
2209  siz += BUFSIZ;
2210  }
2211  return (long)siz;
2212 }
2213 
2214 static VALUE
2216 {
2217  OBJ_TAINT(str);
2218  rb_enc_associate(str, io_read_encoding(fptr));
2219  return str;
2220 }
2221 
2222 static void
2224 {
2225  if (!fptr->readconv) {
2226  int ecflags;
2227  VALUE ecopts;
2228  const char *sname, *dname;
2229  ecflags = fptr->encs.ecflags & ~ECONV_NEWLINE_DECORATOR_WRITE_MASK;
2230  ecopts = fptr->encs.ecopts;
2231  if (fptr->encs.enc2) {
2232  sname = rb_enc_name(fptr->encs.enc2);
2233  dname = rb_enc_name(fptr->encs.enc);
2234  }
2235  else {
2236  sname = dname = "";
2237  }
2238  fptr->readconv = rb_econv_open_opts(sname, dname, ecflags, ecopts);
2239  if (!fptr->readconv)
2240  rb_exc_raise(rb_econv_open_exc(sname, dname, ecflags));
2241  fptr->cbuf.off = 0;
2242  fptr->cbuf.len = 0;
2243  if (size < IO_CBUF_CAPA_MIN) size = IO_CBUF_CAPA_MIN;
2244  fptr->cbuf.capa = size;
2245  fptr->cbuf.ptr = ALLOC_N(char, fptr->cbuf.capa);
2246  }
2247 }
2248 
2249 #define MORE_CHAR_SUSPENDED Qtrue
2250 #define MORE_CHAR_FINISHED Qnil
2251 static VALUE
2252 fill_cbuf(rb_io_t *fptr, int ec_flags)
2253 {
2254  const unsigned char *ss, *sp, *se;
2255  unsigned char *ds, *dp, *de;
2256  rb_econv_result_t res;
2257  int putbackable;
2258  int cbuf_len0;
2259  VALUE exc;
2260 
2261  ec_flags |= ECONV_PARTIAL_INPUT;
2262 
2263  if (fptr->cbuf.len == fptr->cbuf.capa)
2264  return MORE_CHAR_SUSPENDED; /* cbuf full */
2265  if (fptr->cbuf.len == 0)
2266  fptr->cbuf.off = 0;
2267  else if (fptr->cbuf.off + fptr->cbuf.len == fptr->cbuf.capa) {
2268  memmove(fptr->cbuf.ptr, fptr->cbuf.ptr+fptr->cbuf.off, fptr->cbuf.len);
2269  fptr->cbuf.off = 0;
2270  }
2271 
2272  cbuf_len0 = fptr->cbuf.len;
2273 
2274  while (1) {
2275  ss = sp = (const unsigned char *)fptr->rbuf.ptr + fptr->rbuf.off;
2276  se = sp + fptr->rbuf.len;
2277  ds = dp = (unsigned char *)fptr->cbuf.ptr + fptr->cbuf.off + fptr->cbuf.len;
2278  de = (unsigned char *)fptr->cbuf.ptr + fptr->cbuf.capa;
2279  res = rb_econv_convert(fptr->readconv, &sp, se, &dp, de, ec_flags);
2280  fptr->rbuf.off += (int)(sp - ss);
2281  fptr->rbuf.len -= (int)(sp - ss);
2282  fptr->cbuf.len += (int)(dp - ds);
2283 
2284  putbackable = rb_econv_putbackable(fptr->readconv);
2285  if (putbackable) {
2286  rb_econv_putback(fptr->readconv, (unsigned char *)fptr->rbuf.ptr + fptr->rbuf.off - putbackable, putbackable);
2287  fptr->rbuf.off -= putbackable;
2288  fptr->rbuf.len += putbackable;
2289  }
2290 
2291  exc = rb_econv_make_exception(fptr->readconv);
2292  if (!NIL_P(exc))
2293  return exc;
2294 
2295  if (cbuf_len0 != fptr->cbuf.len)
2296  return MORE_CHAR_SUSPENDED;
2297 
2298  if (res == econv_finished) {
2299  return MORE_CHAR_FINISHED;
2300  }
2301 
2302  if (res == econv_source_buffer_empty) {
2303  if (fptr->rbuf.len == 0) {
2304  READ_CHECK(fptr);
2305  if (io_fillbuf(fptr) == -1) {
2306  if (!fptr->readconv) {
2307  return MORE_CHAR_FINISHED;
2308  }
2309  ds = dp = (unsigned char *)fptr->cbuf.ptr + fptr->cbuf.off + fptr->cbuf.len;
2310  de = (unsigned char *)fptr->cbuf.ptr + fptr->cbuf.capa;
2311  res = rb_econv_convert(fptr->readconv, NULL, NULL, &dp, de, 0);
2312  fptr->cbuf.len += (int)(dp - ds);
2314  break;
2315  }
2316  }
2317  }
2318  }
2319  if (cbuf_len0 != fptr->cbuf.len)
2320  return MORE_CHAR_SUSPENDED;
2321 
2322  return MORE_CHAR_FINISHED;
2323 }
2324 
2325 static VALUE
2327 {
2328  VALUE v;
2329  v = fill_cbuf(fptr, ECONV_AFTER_OUTPUT);
2330  if (v != MORE_CHAR_SUSPENDED && v != MORE_CHAR_FINISHED)
2331  rb_exc_raise(v);
2332  return v;
2333 }
2334 
2335 static VALUE
2336 io_shift_cbuf(rb_io_t *fptr, int len, VALUE *strp)
2337 {
2338  VALUE str = Qnil;
2339  if (strp) {
2340  str = *strp;
2341  if (NIL_P(str)) {
2342  *strp = str = rb_str_new(fptr->cbuf.ptr+fptr->cbuf.off, len);
2343  }
2344  else {
2345  rb_str_cat(str, fptr->cbuf.ptr+fptr->cbuf.off, len);
2346  }
2347  OBJ_TAINT(str);
2348  rb_enc_associate(str, fptr->encs.enc);
2349  }
2350  fptr->cbuf.off += len;
2351  fptr->cbuf.len -= len;
2352  /* xxx: set coderange */
2353  if (fptr->cbuf.len == 0)
2354  fptr->cbuf.off = 0;
2355  else if (fptr->cbuf.capa/2 < fptr->cbuf.off) {
2356  memmove(fptr->cbuf.ptr, fptr->cbuf.ptr+fptr->cbuf.off, fptr->cbuf.len);
2357  fptr->cbuf.off = 0;
2358  }
2359  return str;
2360 }
2361 
2362 static void
2364 {
2365 #ifdef _WIN32
2366  len = (len + 1) & ~1L; /* round up for wide char */
2367 #endif
2368  if (NIL_P(*str)) {
2369  *str = rb_str_new(0, 0);
2370  }
2371  else {
2372  VALUE s = StringValue(*str);
2373  long clen = RSTRING_LEN(s);
2374  if (clen >= len) {
2375  rb_str_modify(s);
2376  return;
2377  }
2378  len -= clen;
2379  }
2380  rb_str_modify_expand(*str, len);
2381 }
2382 
2383 static void
2385 {
2386  if (RSTRING_LEN(str) != n) {
2387  rb_str_modify(str);
2388  rb_str_set_len(str, n);
2389  }
2390 }
2391 
2392 static VALUE
2393 read_all(rb_io_t *fptr, long siz, VALUE str)
2394 {
2395  long bytes;
2396  long n;
2397  long pos;
2398  rb_encoding *enc;
2399  int cr;
2400 
2401  if (NEED_READCONV(fptr)) {
2402  int first = !NIL_P(str);
2403  SET_BINARY_MODE(fptr);
2404  io_setstrbuf(&str,0);
2405  make_readconv(fptr, 0);
2406  while (1) {
2407  VALUE v;
2408  if (fptr->cbuf.len) {
2409  if (first) rb_str_set_len(str, first = 0);
2410  io_shift_cbuf(fptr, fptr->cbuf.len, &str);
2411  }
2412  v = fill_cbuf(fptr, 0);
2413  if (v != MORE_CHAR_SUSPENDED && v != MORE_CHAR_FINISHED) {
2414  if (fptr->cbuf.len) {
2415  if (first) rb_str_set_len(str, first = 0);
2416  io_shift_cbuf(fptr, fptr->cbuf.len, &str);
2417  }
2418  rb_exc_raise(v);
2419  }
2420  if (v == MORE_CHAR_FINISHED) {
2421  clear_readconv(fptr);
2422  if (first) rb_str_set_len(str, first = 0);
2423  return io_enc_str(str, fptr);
2424  }
2425  }
2426  }
2427 
2429  bytes = 0;
2430  pos = 0;
2431 
2432  enc = io_read_encoding(fptr);
2433  cr = 0;
2434 
2435  if (siz == 0) siz = BUFSIZ;
2436  io_setstrbuf(&str,siz);
2437  for (;;) {
2438  READ_CHECK(fptr);
2439  n = io_fread(str, bytes, siz - bytes, fptr);
2440  if (n == 0 && bytes == 0) {
2441  rb_str_set_len(str, 0);
2442  break;
2443  }
2444  bytes += n;
2445  rb_str_set_len(str, bytes);
2446  if (cr != ENC_CODERANGE_BROKEN)
2447  pos += rb_str_coderange_scan_restartable(RSTRING_PTR(str) + pos, RSTRING_PTR(str) + bytes, enc, &cr);
2448  if (bytes < siz) break;
2449  siz += BUFSIZ;
2450  rb_str_modify_expand(str, BUFSIZ);
2451  }
2452  str = io_enc_str(str, fptr);
2453  ENC_CODERANGE_SET(str, cr);
2454  return str;
2455 }
2456 
2457 void
2459 {
2460 #ifdef _WIN32
2461  if (rb_w32_set_nonblock(fptr->fd) != 0) {
2462  rb_sys_fail_path(fptr->pathv);
2463  }
2464 #else
2465  int oflags;
2466 #ifdef F_GETFL
2467  oflags = fcntl(fptr->fd, F_GETFL);
2468  if (oflags == -1) {
2469  rb_sys_fail_path(fptr->pathv);
2470  }
2471 #else
2472  oflags = 0;
2473 #endif
2474  if ((oflags & O_NONBLOCK) == 0) {
2475  oflags |= O_NONBLOCK;
2476  if (fcntl(fptr->fd, F_SETFL, oflags) == -1) {
2477  rb_sys_fail_path(fptr->pathv);
2478  }
2479  }
2480 #endif
2481 }
2482 
2484  int fd;
2485  char *str_ptr;
2486  long len;
2487 };
2488 
2489 static VALUE
2491 {
2492  struct read_internal_arg *p = (struct read_internal_arg *)arg;
2493  p->len = rb_read_internal(p->fd, p->str_ptr, p->len);
2494  return Qundef;
2495 }
2496 
2497 static int
2499 {
2500  VALUE except;
2501  ID id = id_exception;
2502 
2503  rb_get_kwargs(opts, &id, 0, 1, &except);
2504  return except == Qfalse;
2505 }
2506 
2507 static VALUE
2508 io_getpartial(int argc, VALUE *argv, VALUE io, VALUE opts, int nonblock)
2509 {
2510  rb_io_t *fptr;
2511  VALUE length, str;
2512  long n, len;
2513  struct read_internal_arg arg;
2514 
2515  rb_scan_args(argc, argv, "11", &length, &str);
2516 
2517  if ((len = NUM2LONG(length)) < 0) {
2518  rb_raise(rb_eArgError, "negative length %ld given", len);
2519  }
2520 
2521  io_setstrbuf(&str,len);
2522  OBJ_TAINT(str);
2523 
2524  GetOpenFile(io, fptr);
2526 
2527  if (len == 0)
2528  return str;
2529 
2530  if (!nonblock)
2531  READ_CHECK(fptr);
2532  n = read_buffered_data(RSTRING_PTR(str), len, fptr);
2533  if (n <= 0) {
2534  again:
2535  if (nonblock) {
2536  rb_io_set_nonblock(fptr);
2537  }
2538  io_setstrbuf(&str, len);
2539  arg.fd = fptr->fd;
2540  arg.str_ptr = RSTRING_PTR(str);
2541  arg.len = len;
2543  n = arg.len;
2544  if (n < 0) {
2545  int e = errno;
2546  if (!nonblock && rb_io_wait_readable(fptr->fd))
2547  goto again;
2548  if (nonblock && (e == EWOULDBLOCK || e == EAGAIN)) {
2549  if (no_exception_p(opts))
2550  return sym_wait_readable;
2551  else
2553  e, "read would block");
2554  }
2555  rb_syserr_fail_path(e, fptr->pathv);
2556  }
2557  }
2558  io_set_read_length(str, n);
2559 
2560  if (n == 0)
2561  return Qnil;
2562  else
2563  return str;
2564 }
2565 
2566 /*
2567  * call-seq:
2568  * ios.readpartial(maxlen) -> string
2569  * ios.readpartial(maxlen, outbuf) -> outbuf
2570  *
2571  * Reads at most <i>maxlen</i> bytes from the I/O stream.
2572  * It blocks only if <em>ios</em> has no data immediately available.
2573  * It doesn't block if some data available.
2574  *
2575  * If the optional _outbuf_ argument is present,
2576  * it must reference a String, which will receive the data.
2577  * The _outbuf_ will contain only the received data after the method call
2578  * even if it is not empty at the beginning.
2579  *
2580  * It raises <code>EOFError</code> on end of file.
2581  *
2582  * readpartial is designed for streams such as pipe, socket, tty, etc.
2583  * It blocks only when no data immediately available.
2584  * This means that it blocks only when following all conditions hold.
2585  * * the byte buffer in the IO object is empty.
2586  * * the content of the stream is empty.
2587  * * the stream is not reached to EOF.
2588  *
2589  * When readpartial blocks, it waits data or EOF on the stream.
2590  * If some data is reached, readpartial returns with the data.
2591  * If EOF is reached, readpartial raises EOFError.
2592  *
2593  * When readpartial doesn't blocks, it returns or raises immediately.
2594  * If the byte buffer is not empty, it returns the data in the buffer.
2595  * Otherwise if the stream has some content,
2596  * it returns the data in the stream.
2597  * Otherwise if the stream is reached to EOF, it raises EOFError.
2598  *
2599  * r, w = IO.pipe # buffer pipe content
2600  * w << "abc" # "" "abc".
2601  * r.readpartial(4096) #=> "abc" "" ""
2602  * r.readpartial(4096) # blocks because buffer and pipe is empty.
2603  *
2604  * r, w = IO.pipe # buffer pipe content
2605  * w << "abc" # "" "abc"
2606  * w.close # "" "abc" EOF
2607  * r.readpartial(4096) #=> "abc" "" EOF
2608  * r.readpartial(4096) # raises EOFError
2609  *
2610  * r, w = IO.pipe # buffer pipe content
2611  * w << "abc\ndef\n" # "" "abc\ndef\n"
2612  * r.gets #=> "abc\n" "def\n" ""
2613  * w << "ghi\n" # "def\n" "ghi\n"
2614  * r.readpartial(4096) #=> "def\n" "" "ghi\n"
2615  * r.readpartial(4096) #=> "ghi\n" "" ""
2616  *
2617  * Note that readpartial behaves similar to sysread.
2618  * The differences are:
2619  * * If the byte buffer is not empty, read from the byte buffer instead of "sysread for buffered IO (IOError)".
2620  * * It doesn't cause Errno::EWOULDBLOCK and Errno::EINTR. When readpartial meets EWOULDBLOCK and EINTR by read system call, readpartial retry the system call.
2621  *
2622  * The latter means that readpartial is nonblocking-flag insensitive.
2623  * It blocks on the situation IO#sysread causes Errno::EWOULDBLOCK as if the fd is blocking mode.
2624  *
2625  */
2626 
2627 static VALUE
2629 {
2630  VALUE ret;
2631 
2632  ret = io_getpartial(argc, argv, io, Qnil, 0);
2633  if (NIL_P(ret))
2634  rb_eof_error();
2635  return ret;
2636 }
2637 
2638 static VALUE
2640 {
2641  if (!no_exception_p(opts)) {
2642  rb_eof_error();
2643  }
2644  return Qnil;
2645 }
2646 
2647 /* :nodoc: */
2648 static VALUE
2650 {
2651  rb_io_t *fptr;
2652  long n, len;
2653  struct read_internal_arg arg;
2654 
2655  if ((len = NUM2LONG(length)) < 0) {
2656  rb_raise(rb_eArgError, "negative length %ld given", len);
2657  }
2658 
2659  io_setstrbuf(&str,len);
2660  OBJ_TAINT(str);
2661  GetOpenFile(io, fptr);
2663 
2664  if (len == 0)
2665  return str;
2666 
2667  n = read_buffered_data(RSTRING_PTR(str), len, fptr);
2668  if (n <= 0) {
2669  rb_io_set_nonblock(fptr);
2670  io_setstrbuf(&str, len);
2671  arg.fd = fptr->fd;
2672  arg.str_ptr = RSTRING_PTR(str);
2673  arg.len = len;
2675  n = arg.len;
2676  if (n < 0) {
2677  int e = errno;
2678  if ((e == EWOULDBLOCK || e == EAGAIN)) {
2679  if (ex == Qfalse) return sym_wait_readable;
2681  e, "read would block");
2682  }
2683  rb_syserr_fail_path(e, fptr->pathv);
2684  }
2685  }
2686  io_set_read_length(str, n);
2687 
2688  if (n == 0) {
2689  if (ex == Qfalse) return Qnil;
2690  rb_eof_error();
2691  }
2692 
2693  return str;
2694 }
2695 
2696 /* :nodoc: */
2697 static VALUE
2699 {
2700  rb_io_t *fptr;
2701  long n;
2702 
2703  if (!RB_TYPE_P(str, T_STRING))
2704  str = rb_obj_as_string(str);
2705 
2706  io = GetWriteIO(io);
2707  GetOpenFile(io, fptr);
2708  rb_io_check_writable(fptr);
2709 
2710  if (io_fflush(fptr) < 0)
2711  rb_sys_fail(0);
2712 
2713  rb_io_set_nonblock(fptr);
2714  n = write(fptr->fd, RSTRING_PTR(str), RSTRING_LEN(str));
2715 
2716  if (n == -1) {
2717  int e = errno;
2718  if (e == EWOULDBLOCK || e == EAGAIN) {
2719  if (ex == Qfalse) {
2720  return sym_wait_writable;
2721  }
2722  else {
2723  rb_readwrite_syserr_fail(RB_IO_WAIT_WRITABLE, e, "write would block");
2724  }
2725  }
2726  rb_syserr_fail_path(e, fptr->pathv);
2727  }
2728 
2729  return LONG2FIX(n);
2730 }
2731 
2732 /*
2733  * call-seq:
2734  * ios.read([length [, outbuf]]) -> string, outbuf, or nil
2735  *
2736  * Reads _length_ bytes from the I/O stream.
2737  *
2738  * _length_ must be a non-negative integer or +nil+.
2739  *
2740  * If _length_ is a positive integer, +read+ tries to read
2741  * _length_ bytes without any conversion (binary mode).
2742  * It returns +nil+ if an EOF is encountered before anything can be read.
2743  * Fewer than _length_ bytes are returned if an EOF is encountered during
2744  * the read.
2745  * In the case of an integer _length_, the resulting string is always
2746  * in ASCII-8BIT encoding.
2747  *
2748  * If _length_ is omitted or is +nil+, it reads until EOF
2749  * and the encoding conversion is applied, if applicable.
2750  * A string is returned even if EOF is encountered before any data is read.
2751  *
2752  * If _length_ is zero, it returns an empty string (<code>""</code>).
2753  *
2754  * If the optional _outbuf_ argument is present,
2755  * it must reference a String, which will receive the data.
2756  * The _outbuf_ will contain only the received data after the method call
2757  * even if it is not empty at the beginning.
2758  *
2759  * When this method is called at end of file, it returns +nil+
2760  * or <code>""</code>, depending on _length_:
2761  * +read+, <code>read(nil)</code>, and <code>read(0)</code> return
2762  * <code>""</code>,
2763  * <code>read(<i>positive_integer</i>)</code> returns +nil+.
2764  *
2765  * f = File.new("testfile")
2766  * f.read(16) #=> "This is line one"
2767  *
2768  * # read whole file
2769  * open("file") do |f|
2770  * data = f.read # This returns a string even if the file is empty.
2771  * # ...
2772  * end
2773  *
2774  * # iterate over fixed length records
2775  * open("fixed-record-file") do |f|
2776  * while record = f.read(256)
2777  * # ...
2778  * end
2779  * end
2780  *
2781  * # iterate over variable length records,
2782  * # each record is prefixed by its 32-bit length
2783  * open("variable-record-file") do |f|
2784  * while len = f.read(4)
2785  * len = len.unpack("N")[0] # 32-bit length
2786  * record = f.read(len) # This returns a string even if len is 0.
2787  * end
2788  * end
2789  *
2790  * Note that this method behaves like the fread() function in C.
2791  * This means it retries to invoke read(2) system calls to read data
2792  * with the specified length (or until EOF).
2793  * This behavior is preserved even if <i>ios</i> is in non-blocking mode.
2794  * (This method is non-blocking flag insensitive as other methods.)
2795  * If you need the behavior like a single read(2) system call,
2796  * consider #readpartial, #read_nonblock, and #sysread.
2797  */
2798 
2799 static VALUE
2801 {
2802  rb_io_t *fptr;
2803  long n, len;
2804  VALUE length, str;
2805 #if defined(RUBY_TEST_CRLF_ENVIRONMENT) || defined(_WIN32)
2806  int previous_mode;
2807 #endif
2808 
2809  rb_scan_args(argc, argv, "02", &length, &str);
2810 
2811  if (NIL_P(length)) {
2812  GetOpenFile(io, fptr);
2814  return read_all(fptr, remain_size(fptr), str);
2815  }
2816  len = NUM2LONG(length);
2817  if (len < 0) {
2818  rb_raise(rb_eArgError, "negative length %ld given", len);
2819  }
2820 
2821  io_setstrbuf(&str,len);
2822 
2823  GetOpenFile(io, fptr);
2825  if (len == 0) {
2826  io_set_read_length(str, 0);
2827  return str;
2828  }
2829 
2830  READ_CHECK(fptr);
2831 #if defined(RUBY_TEST_CRLF_ENVIRONMENT) || defined(_WIN32)
2832  previous_mode = set_binary_mode_with_seek_cur(fptr);
2833 #endif
2834  n = io_fread(str, 0, len, fptr);
2835  io_set_read_length(str, n);
2836 #if defined(RUBY_TEST_CRLF_ENVIRONMENT) || defined(_WIN32)
2837  if (previous_mode == O_TEXT) {
2838  setmode(fptr->fd, O_TEXT);
2839  }
2840 #endif
2841  if (n == 0) return Qnil;
2842  OBJ_TAINT(str);
2843 
2844  return str;
2845 }
2846 
2847 static void
2848 rscheck(const char *rsptr, long rslen, VALUE rs)
2849 {
2850  if (!rs) return;
2851  if (RSTRING_PTR(rs) != rsptr && RSTRING_LEN(rs) != rslen)
2852  rb_raise(rb_eRuntimeError, "rs modified");
2853 }
2854 
2855 static int
2856 appendline(rb_io_t *fptr, int delim, VALUE *strp, long *lp)
2857 {
2858  VALUE str = *strp;
2859  long limit = *lp;
2860 
2861  if (NEED_READCONV(fptr)) {
2862  SET_BINARY_MODE(fptr);
2863  make_readconv(fptr, 0);
2864  do {
2865  const char *p, *e;
2866  int searchlen = READ_CHAR_PENDING_COUNT(fptr);
2867  if (searchlen) {
2868  p = READ_CHAR_PENDING_PTR(fptr);
2869  if (0 < limit && limit < searchlen)
2870  searchlen = (int)limit;
2871  e = memchr(p, delim, searchlen);
2872  if (e) {
2873  int len = (int)(e-p+1);
2874  if (NIL_P(str))
2875  *strp = str = rb_str_new(p, len);
2876  else
2877  rb_str_buf_cat(str, p, len);
2878  fptr->cbuf.off += len;
2879  fptr->cbuf.len -= len;
2880  limit -= len;
2881  *lp = limit;
2882  return delim;
2883  }
2884 
2885  if (NIL_P(str))
2886  *strp = str = rb_str_new(p, searchlen);
2887  else
2888  rb_str_buf_cat(str, p, searchlen);
2889  fptr->cbuf.off += searchlen;
2890  fptr->cbuf.len -= searchlen;
2891  limit -= searchlen;
2892 
2893  if (limit == 0) {
2894  *lp = limit;
2895  return (unsigned char)RSTRING_PTR(str)[RSTRING_LEN(str)-1];
2896  }
2897  }
2898  } while (more_char(fptr) != MORE_CHAR_FINISHED);
2899  clear_readconv(fptr);
2900  *lp = limit;
2901  return EOF;
2902  }
2903 
2905  do {
2906  long pending = READ_DATA_PENDING_COUNT(fptr);
2907  if (pending > 0) {
2908  const char *p = READ_DATA_PENDING_PTR(fptr);
2909  const char *e;
2910  long last;
2911 
2912  if (limit > 0 && pending > limit) pending = limit;
2913  e = memchr(p, delim, pending);
2914  if (e) pending = e - p + 1;
2915  if (!NIL_P(str)) {
2916  last = RSTRING_LEN(str);
2917  rb_str_resize(str, last + pending);
2918  }
2919  else {
2920  last = 0;
2921  *strp = str = rb_str_buf_new(pending);
2922  rb_str_set_len(str, pending);
2923  }
2924  read_buffered_data(RSTRING_PTR(str) + last, pending, fptr); /* must not fail */
2925  limit -= pending;
2926  *lp = limit;
2927  if (e) return delim;
2928  if (limit == 0)
2929  return (unsigned char)RSTRING_PTR(str)[RSTRING_LEN(str)-1];
2930  }
2931  READ_CHECK(fptr);
2932  } while (io_fillbuf(fptr) >= 0);
2933  *lp = limit;
2934  return EOF;
2935 }
2936 
2937 static inline int
2938 swallow(rb_io_t *fptr, int term)
2939 {
2940  if (NEED_READCONV(fptr)) {
2941  rb_encoding *enc = io_read_encoding(fptr);
2942  int needconv = rb_enc_mbminlen(enc) != 1;
2943  SET_BINARY_MODE(fptr);
2944  make_readconv(fptr, 0);
2945  do {
2946  size_t cnt;
2947  while ((cnt = READ_CHAR_PENDING_COUNT(fptr)) > 0) {
2948  const char *p = READ_CHAR_PENDING_PTR(fptr);
2949  int i;
2950  if (!needconv) {
2951  if (*p != term) return TRUE;
2952  i = (int)cnt;
2953  while (--i && *++p == term);
2954  }
2955  else {
2956  const char *e = p + cnt;
2957  if (rb_enc_ascget(p, e, &i, enc) != term) return TRUE;
2958  while ((p += i) < e && rb_enc_ascget(p, e, &i, enc) == term);
2959  i = (int)(e - p);
2960  }
2961  io_shift_cbuf(fptr, (int)cnt - i, NULL);
2962  }
2963  } while (more_char(fptr) != MORE_CHAR_FINISHED);
2964  return FALSE;
2965  }
2966 
2968  do {
2969  size_t cnt;
2970  while ((cnt = READ_DATA_PENDING_COUNT(fptr)) > 0) {
2971  char buf[1024];
2972  const char *p = READ_DATA_PENDING_PTR(fptr);
2973  int i;
2974  if (cnt > sizeof buf) cnt = sizeof buf;
2975  if (*p != term) return TRUE;
2976  i = (int)cnt;
2977  while (--i && *++p == term);
2978  if (!read_buffered_data(buf, cnt - i, fptr)) /* must not fail */
2979  rb_sys_fail_path(fptr->pathv);
2980  }
2981  READ_CHECK(fptr);
2982  } while (io_fillbuf(fptr) == 0);
2983  return FALSE;
2984 }
2985 
2986 static VALUE
2987 rb_io_getline_fast(rb_io_t *fptr, rb_encoding *enc, int chomp)
2988 {
2989  VALUE str = Qnil;
2990  int len = 0;
2991  long pos = 0;
2992  int cr = 0;
2993 
2994  do {
2995  int pending = READ_DATA_PENDING_COUNT(fptr);
2996 
2997  if (pending > 0) {
2998  const char *p = READ_DATA_PENDING_PTR(fptr);
2999  const char *e;
3000  int chomplen = 0;
3001 
3002  e = memchr(p, '\n', pending);
3003  if (e) {
3004  pending = (int)(e - p + 1);
3005  if (chomp) {
3006  chomplen = (pending > 1 && *(e-1) == '\r') + 1;
3007  }
3008  }
3009  if (NIL_P(str)) {
3010  str = rb_str_new(p, pending - chomplen);
3011  fptr->rbuf.off += pending;
3012  fptr->rbuf.len -= pending;
3013  }
3014  else {
3015  rb_str_resize(str, len + pending - chomplen);
3016  read_buffered_data(RSTRING_PTR(str)+len, pending - chomplen, fptr);
3017  fptr->rbuf.off += chomplen;
3018  fptr->rbuf.len -= chomplen;
3019  }
3020  len += pending - chomplen;
3021  if (cr != ENC_CODERANGE_BROKEN)
3022  pos += rb_str_coderange_scan_restartable(RSTRING_PTR(str) + pos, RSTRING_PTR(str) + len, enc, &cr);
3023  if (e) break;
3024  }
3025  READ_CHECK(fptr);
3026  } while (io_fillbuf(fptr) >= 0);
3027  if (NIL_P(str)) return Qnil;
3028 
3029  str = io_enc_str(str, fptr);
3030  ENC_CODERANGE_SET(str, cr);
3031  fptr->lineno++;
3032 
3033  return str;
3034 }
3035 
3036 struct getline_arg {
3038  VALUE rs;
3039  long limit;
3040  unsigned int chomp: 1;
3041 };
3042 
3043 static void
3045 {
3046  int chomp = FALSE;
3047  if (!NIL_P(opts)) {
3048  static ID kwds[1];
3049  VALUE vchomp;
3050  if (!kwds[0]) {
3051  kwds[0] = rb_intern_const("chomp");
3052  }
3053  rb_get_kwargs(opts, kwds, 0, -2, &vchomp);
3054  chomp = (vchomp != Qundef) && RTEST(vchomp);
3055  }
3056  args->chomp = chomp;
3057 }
3058 
3059 static void
3061 {
3062  VALUE rs = rb_rs, lim = Qnil;
3063 
3064  if (argc == 1) {
3065  VALUE tmp = Qnil;
3066 
3067  if (NIL_P(argv[0]) || !NIL_P(tmp = rb_check_string_type(argv[0]))) {
3068  rs = tmp;
3069  }
3070  else {
3071  lim = argv[0];
3072  }
3073  }
3074  else if (2 <= argc) {
3075  rs = argv[0], lim = argv[1];
3076  if (!NIL_P(rs))
3077  StringValue(rs);
3078  }
3079  args->rs = rs;
3080  args->limit = NIL_P(lim) ? -1L : NUM2LONG(lim);
3081 }
3082 
3083 static void
3084 check_getline_args(VALUE *rsp, long *limit, VALUE io)
3085 {
3086  rb_io_t *fptr;
3087  VALUE rs = *rsp;
3088 
3089  if (!NIL_P(rs)) {
3090  rb_encoding *enc_rs, *enc_io;
3091 
3092  GetOpenFile(io, fptr);
3093  enc_rs = rb_enc_get(rs);
3094  enc_io = io_read_encoding(fptr);
3095  if (enc_io != enc_rs &&
3097  (RSTRING_LEN(rs) > 0 && !rb_enc_asciicompat(enc_io)))) {
3098  if (rs == rb_default_rs) {
3099  rs = rb_enc_str_new(0, 0, enc_io);
3100  rb_str_buf_cat_ascii(rs, "\n");
3101  *rsp = rs;
3102  }
3103  else {
3104  rb_raise(rb_eArgError, "encoding mismatch: %s IO with %s RS",
3105  rb_enc_name(enc_io),
3106  rb_enc_name(enc_rs));
3107  }
3108  }
3109  }
3110 }
3111 
3112 static void
3114 {
3115  VALUE opts;
3116  argc = rb_scan_args(argc, argv, "02:", NULL, NULL, &opts);
3117  extract_getline_args(argc, argv, args);
3118  extract_getline_opts(opts, args);
3119  check_getline_args(&args->rs, &args->limit, io);
3120 }
3121 
3122 static VALUE
3123 rb_io_getline_0(VALUE rs, long limit, int chomp, rb_io_t *fptr)
3124 {
3125  VALUE str = Qnil;
3126  int nolimit = 0;
3127  rb_encoding *enc;
3128 
3130  if (NIL_P(rs) && limit < 0) {
3131  str = read_all(fptr, 0, Qnil);
3132  if (RSTRING_LEN(str) == 0) return Qnil;
3133  if (chomp) rb_str_chomp_string(str, rb_default_rs);
3134  }
3135  else if (limit == 0) {
3136  return rb_enc_str_new(0, 0, io_read_encoding(fptr));
3137  }
3138  else if (rs == rb_default_rs && limit < 0 && !NEED_READCONV(fptr) &&
3139  rb_enc_asciicompat(enc = io_read_encoding(fptr))) {
3141  return rb_io_getline_fast(fptr, enc, chomp);
3142  }
3143  else {
3144  int c, newline = -1;
3145  const char *rsptr = 0;
3146  long rslen = 0;
3147  int rspara = 0;
3148  int extra_limit = 16;
3149  int chomp_cr = chomp;
3150 
3151  SET_BINARY_MODE(fptr);
3152  enc = io_read_encoding(fptr);
3153 
3154  if (!NIL_P(rs)) {
3155  rslen = RSTRING_LEN(rs);
3156  if (rslen == 0) {
3157  rsptr = "\n\n";
3158  rslen = 2;
3159  rspara = 1;
3160  swallow(fptr, '\n');
3161  rs = 0;
3162  if (!rb_enc_asciicompat(enc)) {
3163  rs = rb_usascii_str_new(rsptr, rslen);
3164  rs = rb_str_encode(rs, rb_enc_from_encoding(enc), 0, Qnil);
3165  OBJ_FREEZE(rs);
3166  rsptr = RSTRING_PTR(rs);
3167  rslen = RSTRING_LEN(rs);
3168  }
3169  }
3170  else {
3171  rsptr = RSTRING_PTR(rs);
3172  }
3173  newline = (unsigned char)rsptr[rslen - 1];
3174  chomp_cr = chomp && rslen == 1 && newline == '\n';
3175  }
3176 
3177  /* MS - Optimization */
3178  while ((c = appendline(fptr, newline, &str, &limit)) != EOF) {
3179  const char *s, *p, *pp, *e;
3180 
3181  if (c == newline) {
3182  if (RSTRING_LEN(str) < rslen) continue;
3183  s = RSTRING_PTR(str);
3184  e = RSTRING_END(str);
3185  p = e - rslen;
3186  pp = rb_enc_left_char_head(s, p, e, enc);
3187  if (pp != p) continue;
3188  if (!rspara) rscheck(rsptr, rslen, rs);
3189  if (memcmp(p, rsptr, rslen) == 0) {
3190  if (chomp) {
3191  if (chomp_cr && p > s && *(p-1) == '\r') --p;
3192  rb_str_set_len(str, p - s);
3193  }
3194  break;
3195  }
3196  }
3197  if (limit == 0) {
3198  s = RSTRING_PTR(str);
3199  p = RSTRING_END(str);
3200  pp = rb_enc_left_char_head(s, p-1, p, enc);
3201  if (extra_limit &&
3203  /* relax the limit while incomplete character.
3204  * extra_limit limits the relax length */
3205  limit = 1;
3206  extra_limit--;
3207  }
3208  else {
3209  nolimit = 1;
3210  break;
3211  }
3212  }
3213  }
3214 
3215  if (rspara && c != EOF)
3216  swallow(fptr, '\n');
3217  if (!NIL_P(str))
3218  str = io_enc_str(str, fptr);
3219  }
3220 
3221  if (!NIL_P(str) && !nolimit) {
3222  fptr->lineno++;
3223  }
3224 
3225  return str;
3226 }
3227 
3228 static VALUE
3229 rb_io_getline_1(VALUE rs, long limit, int chomp, VALUE io)
3230 {
3231  rb_io_t *fptr;
3232  int old_lineno, new_lineno;
3233  VALUE str;
3234 
3235  GetOpenFile(io, fptr);
3236  old_lineno = fptr->lineno;
3237  str = rb_io_getline_0(rs, limit, chomp, fptr);
3238  if (!NIL_P(str) && (new_lineno = fptr->lineno) != old_lineno) {
3239  if (io == ARGF.current_file) {
3240  ARGF.lineno += new_lineno - old_lineno;
3241  ARGF.last_lineno = ARGF.lineno;
3242  }
3243  else {
3244  ARGF.last_lineno = new_lineno;
3245  }
3246  }
3247 
3248  return str;
3249 }
3250 
3251 static VALUE
3253 {
3254  struct getline_arg args;
3255 
3256  prepare_getline_args(argc, argv, &args, io);
3257  return rb_io_getline_1(args.rs, args.limit, args.chomp, io);
3258 }
3259 
3260 VALUE
3262 {
3263  return rb_io_getline_1(rb_default_rs, -1, FALSE, io);
3264 }
3265 
3266 VALUE
3268 {
3269  rb_io_t *fptr;
3270  GetOpenFile(io, fptr);
3271  return rb_io_getline_0(rb_default_rs, -1, FALSE, fptr);
3272 }
3273 
3274 /*
3275  * call-seq:
3276  * ios.gets(sep=$/) -> string or nil
3277  * ios.gets(limit) -> string or nil
3278  * ios.gets(sep, limit) -> string or nil
3279  *
3280  * Reads the next ``line'' from the I/O stream; lines are separated by
3281  * <i>sep</i>. A separator of +nil+ reads the entire
3282  * contents, and a zero-length separator reads the input a paragraph at
3283  * a time (two successive newlines in the input separate paragraphs).
3284  * The stream must be opened for reading or an <code>IOError</code>
3285  * will be raised. The line read in will be returned and also assigned
3286  * to <code>$_</code>. Returns +nil+ if called at end of
3287  * file. If the first argument is an integer, or optional second
3288  * argument is given, the returning string would not be longer than the
3289  * given value in bytes.
3290  *
3291  * File.new("testfile").gets #=> "This is line one\n"
3292  * $_ #=> "This is line one\n"
3293  *
3294  * File.new("testfile").gets(4)#=> "This"
3295  *
3296  * If IO contains multibyte characters byte then <code>gets(1)</code>
3297  * returns character entirely:
3298  *
3299  * # Russian characters take 2 bytes
3300  * File.write("testfile", "\u{442 435 441 442}")
3301  * File.open("testfile") {|f|f.gets(1)} #=> "\u0442"
3302  * File.open("testfile") {|f|f.gets(2)} #=> "\u0442"
3303  * File.open("testfile") {|f|f.gets(3)} #=> "\u0442\u0435"
3304  * File.open("testfile") {|f|f.gets(4)} #=> "\u0442\u0435"
3305  */
3306 
3307 static VALUE
3309 {
3310  VALUE str;
3311 
3312  str = rb_io_getline(argc, argv, io);
3313  rb_lastline_set(str);
3314 
3315  return str;
3316 }
3317 
3318 /*
3319  * call-seq:
3320  * ios.lineno -> integer
3321  *
3322  * Returns the current line number in <em>ios</em>. The stream must be
3323  * opened for reading. <code>lineno</code> counts the number of times
3324  * #gets is called rather than the number of newlines encountered. The two
3325  * values will differ if #gets is called with a separator other than newline.
3326  *
3327  * Methods that use <code>$/</code> like #each, #lines and #readline will
3328  * also increment <code>lineno</code>.
3329  *
3330  * See also the <code>$.</code> variable.
3331  *
3332  * f = File.new("testfile")
3333  * f.lineno #=> 0
3334  * f.gets #=> "This is line one\n"
3335  * f.lineno #=> 1
3336  * f.gets #=> "This is line two\n"
3337  * f.lineno #=> 2
3338  */
3339 
3340 static VALUE
3342 {
3343  rb_io_t *fptr;
3344 
3345  GetOpenFile(io, fptr);
3347  return INT2NUM(fptr->lineno);
3348 }
3349 
3350 /*
3351  * call-seq:
3352  * ios.lineno = integer -> integer
3353  *
3354  * Manually sets the current line number to the given value.
3355  * <code>$.</code> is updated only on the next read.
3356  *
3357  * f = File.new("testfile")
3358  * f.gets #=> "This is line one\n"
3359  * $. #=> 1
3360  * f.lineno = 1000
3361  * f.lineno #=> 1000
3362  * $. #=> 1 # lineno of last read
3363  * f.gets #=> "This is line two\n"
3364  * $. #=> 1001 # lineno of last read
3365  */
3366 
3367 static VALUE
3369 {
3370  rb_io_t *fptr;
3371 
3372  GetOpenFile(io, fptr);
3374  fptr->lineno = NUM2INT(lineno);
3375  return lineno;
3376 }
3377 
3378 /*
3379  * call-seq:
3380  * ios.readline(sep=$/) -> string
3381  * ios.readline(limit) -> string
3382  * ios.readline(sep, limit) -> string
3383  *
3384  * Reads a line as with <code>IO#gets</code>, but raises an
3385  * <code>EOFError</code> on end of file.
3386  */
3387 
3388 static VALUE
3390 {
3391  VALUE line = rb_io_gets_m(argc, argv, io);
3392 
3393  if (NIL_P(line)) {
3394  rb_eof_error();
3395  }
3396  return line;
3397 }
3398 
3399 static VALUE io_readlines(const struct getline_arg *arg, VALUE io);
3400 
3401 /*
3402  * call-seq:
3403  * ios.readlines(sep=$/) -> array
3404  * ios.readlines(limit) -> array
3405  * ios.readlines(sep, limit) -> array
3406  *
3407  * Reads all of the lines in <em>ios</em>, and returns them in
3408  * <i>anArray</i>. Lines are separated by the optional <i>sep</i>. If
3409  * <i>sep</i> is +nil+, the rest of the stream is returned
3410  * as a single record. If the first argument is an integer, or
3411  * optional second argument is given, the returning string would not be
3412  * longer than the given value in bytes. The stream must be opened for
3413  * reading or an <code>IOError</code> will be raised.
3414  *
3415  * f = File.new("testfile")
3416  * f.readlines[0] #=> "This is line one\n"
3417  */
3418 
3419 static VALUE
3421 {
3422  struct getline_arg args;
3423 
3424  prepare_getline_args(argc, argv, &args, io);
3425  return io_readlines(&args, io);
3426 }
3427 
3428 static VALUE
3429 io_readlines(const struct getline_arg *arg, VALUE io)
3430 {
3431  VALUE line, ary;
3432 
3433  if (arg->limit == 0)
3434  rb_raise(rb_eArgError, "invalid limit: 0 for readlines");
3435  ary = rb_ary_new();
3436  while (!NIL_P(line = rb_io_getline_1(arg->rs, arg->limit, arg->chomp, io))) {
3437  rb_ary_push(ary, line);
3438  }
3439  return ary;
3440 }
3441 
3442 /*
3443  * call-seq:
3444  * ios.each(sep=$/) {|line| block } -> ios
3445  * ios.each(limit) {|line| block } -> ios
3446  * ios.each(sep, limit) {|line| block } -> ios
3447  * ios.each(...) -> an_enumerator
3448  *
3449  * ios.each_line(sep=$/) {|line| block } -> ios
3450  * ios.each_line(limit) {|line| block } -> ios
3451  * ios.each_line(sep, limit) {|line| block } -> ios
3452  * ios.each_line(...) -> an_enumerator
3453  *
3454  * Executes the block for every line in <em>ios</em>, where lines are
3455  * separated by <i>sep</i>. <em>ios</em> must be opened for
3456  * reading or an <code>IOError</code> will be raised.
3457  *
3458  * If no block is given, an enumerator is returned instead.
3459  *
3460  * f = File.new("testfile")
3461  * f.each {|line| puts "#{f.lineno}: #{line}" }
3462  *
3463  * <em>produces:</em>
3464  *
3465  * 1: This is line one
3466  * 2: This is line two
3467  * 3: This is line three
3468  * 4: And so on...
3469  */
3470 
3471 static VALUE
3473 {
3474  VALUE str;
3475  struct getline_arg args;
3476 
3477  RETURN_ENUMERATOR(io, argc, argv);
3478  prepare_getline_args(argc, argv, &args, io);
3479  if (args.limit == 0)
3480  rb_raise(rb_eArgError, "invalid limit: 0 for each_line");
3481  while (!NIL_P(str = rb_io_getline_1(args.rs, args.limit, args.chomp, io))) {
3482  rb_yield(str);
3483  }
3484  return io;
3485 }
3486 
3487 /*
3488  * This is a deprecated alias for <code>each_line</code>.
3489  */
3490 
3491 static VALUE
3493 {
3494  rb_warn("IO#lines is deprecated; use #each_line instead");
3495  if (!rb_block_given_p())
3496  return rb_enumeratorize(io, ID2SYM(rb_intern("each_line")), argc, argv);
3497  return rb_io_each_line(argc, argv, io);
3498 }
3499 
3500 /*
3501  * call-seq:
3502  * ios.each_byte {|byte| block } -> ios
3503  * ios.each_byte -> an_enumerator
3504  *
3505  * Calls the given block once for each byte (0..255) in <em>ios</em>,
3506  * passing the byte as an argument. The stream must be opened for
3507  * reading or an <code>IOError</code> will be raised.
3508  *
3509  * If no block is given, an enumerator is returned instead.
3510  *
3511  * f = File.new("testfile")
3512  * checksum = 0
3513  * f.each_byte {|x| checksum ^= x } #=> #<File:testfile>
3514  * checksum #=> 12
3515  */
3516 
3517 static VALUE
3519 {
3520  rb_io_t *fptr;
3521 
3522  RETURN_ENUMERATOR(io, 0, 0);
3523  GetOpenFile(io, fptr);
3524 
3525  do {
3526  while (fptr->rbuf.len > 0) {
3527  char *p = fptr->rbuf.ptr + fptr->rbuf.off++;
3528  fptr->rbuf.len--;
3529  rb_yield(INT2FIX(*p & 0xff));
3530  errno = 0;
3531  }
3533  READ_CHECK(fptr);
3534  } while (io_fillbuf(fptr) >= 0);
3535  return io;
3536 }
3537 
3538 /*
3539  * This is a deprecated alias for <code>each_byte</code>.
3540  */
3541 
3542 static VALUE
3544 {
3545  rb_warn("IO#bytes is deprecated; use #each_byte instead");
3546  if (!rb_block_given_p())
3547  return rb_enumeratorize(io, ID2SYM(rb_intern("each_byte")), 0, 0);
3548  return rb_io_each_byte(io);
3549 }
3550 
3551 static VALUE
3553 {
3554  int r, n, cr = 0;
3555  VALUE str;
3556 
3557  if (NEED_READCONV(fptr)) {
3558  VALUE str = Qnil;
3559  rb_encoding *read_enc = io_read_encoding(fptr);
3560 
3561  SET_BINARY_MODE(fptr);
3562  make_readconv(fptr, 0);
3563 
3564  while (1) {
3565  if (fptr->cbuf.len) {
3566  r = rb_enc_precise_mbclen(fptr->cbuf.ptr+fptr->cbuf.off,
3567  fptr->cbuf.ptr+fptr->cbuf.off+fptr->cbuf.len,
3568  read_enc);
3569  if (!MBCLEN_NEEDMORE_P(r))
3570  break;
3571  if (fptr->cbuf.len == fptr->cbuf.capa) {
3572  rb_raise(rb_eIOError, "too long character");
3573  }
3574  }
3575 
3576  if (more_char(fptr) == MORE_CHAR_FINISHED) {
3577  if (fptr->cbuf.len == 0) {
3578  clear_readconv(fptr);
3579  return Qnil;
3580  }
3581  /* return an unit of an incomplete character just before EOF */
3582  str = rb_enc_str_new(fptr->cbuf.ptr+fptr->cbuf.off, 1, read_enc);
3583  fptr->cbuf.off += 1;
3584  fptr->cbuf.len -= 1;
3585  if (fptr->cbuf.len == 0) clear_readconv(fptr);
3587  return str;
3588  }
3589  }
3590  if (MBCLEN_INVALID_P(r)) {
3591  r = rb_enc_mbclen(fptr->cbuf.ptr+fptr->cbuf.off,
3592  fptr->cbuf.ptr+fptr->cbuf.off+fptr->cbuf.len,
3593  read_enc);
3594  io_shift_cbuf(fptr, r, &str);
3595  cr = ENC_CODERANGE_BROKEN;
3596  }
3597  else {
3598  io_shift_cbuf(fptr, MBCLEN_CHARFOUND_LEN(r), &str);
3599  cr = ENC_CODERANGE_VALID;
3600  if (MBCLEN_CHARFOUND_LEN(r) == 1 && rb_enc_asciicompat(read_enc) &&
3601  ISASCII(RSTRING_PTR(str)[0])) {
3602  cr = ENC_CODERANGE_7BIT;
3603  }
3604  }
3605  str = io_enc_str(str, fptr);
3606  ENC_CODERANGE_SET(str, cr);
3607  return str;
3608  }
3609 
3611  if (io_fillbuf(fptr) < 0) {
3612  return Qnil;
3613  }
3614  if (rb_enc_asciicompat(enc) && ISASCII(fptr->rbuf.ptr[fptr->rbuf.off])) {
3615  str = rb_str_new(fptr->rbuf.ptr+fptr->rbuf.off, 1);
3616  fptr->rbuf.off += 1;
3617  fptr->rbuf.len -= 1;
3618  cr = ENC_CODERANGE_7BIT;
3619  }
3620  else {
3621  r = rb_enc_precise_mbclen(fptr->rbuf.ptr+fptr->rbuf.off, fptr->rbuf.ptr+fptr->rbuf.off+fptr->rbuf.len, enc);
3622  if (MBCLEN_CHARFOUND_P(r) &&
3623  (n = MBCLEN_CHARFOUND_LEN(r)) <= fptr->rbuf.len) {
3624  str = rb_str_new(fptr->rbuf.ptr+fptr->rbuf.off, n);
3625  fptr->rbuf.off += n;
3626  fptr->rbuf.len -= n;
3627  cr = ENC_CODERANGE_VALID;
3628  }
3629  else if (MBCLEN_NEEDMORE_P(r)) {
3630  str = rb_str_new(fptr->rbuf.ptr+fptr->rbuf.off, fptr->rbuf.len);
3631  fptr->rbuf.len = 0;
3632  getc_needmore:
3633  if (io_fillbuf(fptr) != -1) {
3634  rb_str_cat(str, fptr->rbuf.ptr+fptr->rbuf.off, 1);
3635  fptr->rbuf.off++;
3636  fptr->rbuf.len--;
3637  r = rb_enc_precise_mbclen(RSTRING_PTR(str), RSTRING_PTR(str)+RSTRING_LEN(str), enc);
3638  if (MBCLEN_NEEDMORE_P(r)) {
3639  goto getc_needmore;
3640  }
3641  else if (MBCLEN_CHARFOUND_P(r)) {
3642  cr = ENC_CODERANGE_VALID;
3643  }
3644  }
3645  }
3646  else {
3647  str = rb_str_new(fptr->rbuf.ptr+fptr->rbuf.off, 1);
3648  fptr->rbuf.off++;
3649  fptr->rbuf.len--;
3650  }
3651  }
3652  if (!cr) cr = ENC_CODERANGE_BROKEN;
3653  str = io_enc_str(str, fptr);
3654  ENC_CODERANGE_SET(str, cr);
3655  return str;
3656 }
3657 
3658 /*
3659  * call-seq:
3660  * ios.each_char {|c| block } -> ios
3661  * ios.each_char -> an_enumerator
3662  *
3663  * Calls the given block once for each character in <em>ios</em>,
3664  * passing the character as an argument. The stream must be opened for
3665  * reading or an <code>IOError</code> will be raised.
3666  *
3667  * If no block is given, an enumerator is returned instead.
3668  *
3669  * f = File.new("testfile")
3670  * f.each_char {|c| print c, ' ' } #=> #<File:testfile>
3671  */
3672 
3673 static VALUE
3675 {
3676  rb_io_t *fptr;
3677  rb_encoding *enc;
3678  VALUE c;
3679 
3680  RETURN_ENUMERATOR(io, 0, 0);
3681  GetOpenFile(io, fptr);
3683 
3684  enc = io_input_encoding(fptr);
3685  READ_CHECK(fptr);
3686  while (!NIL_P(c = io_getc(fptr, enc))) {
3687  rb_yield(c);
3688  }
3689  return io;
3690 }
3691 
3692 /*
3693  * This is a deprecated alias for <code>each_char</code>.
3694  */
3695 
3696 static VALUE
3698 {
3699  rb_warn("IO#chars is deprecated; use #each_char instead");
3700  if (!rb_block_given_p())
3701  return rb_enumeratorize(io, ID2SYM(rb_intern("each_char")), 0, 0);
3702  return rb_io_each_char(io);
3703 }
3704 
3705 
3706 /*
3707  * call-seq:
3708  * ios.each_codepoint {|c| block } -> ios
3709  * ios.codepoints {|c| block } -> ios
3710  * ios.each_codepoint -> an_enumerator
3711  * ios.codepoints -> an_enumerator
3712  *
3713  * Passes the <code>Integer</code> ordinal of each character in <i>ios</i>,
3714  * passing the codepoint as an argument. The stream must be opened for
3715  * reading or an <code>IOError</code> will be raised.
3716  *
3717  * If no block is given, an enumerator is returned instead.
3718  *
3719  */
3720 
3721 static VALUE
3723 {
3724  rb_io_t *fptr;
3725  rb_encoding *enc;
3726  unsigned int c;
3727  int r, n;
3728 
3729  RETURN_ENUMERATOR(io, 0, 0);
3730  GetOpenFile(io, fptr);
3732 
3733  READ_CHECK(fptr);
3734  if (NEED_READCONV(fptr)) {
3735  SET_BINARY_MODE(fptr);
3736  r = 1; /* no invalid char yet */
3737  for (;;) {
3738  make_readconv(fptr, 0);
3739  for (;;) {
3740  if (fptr->cbuf.len) {
3741  if (fptr->encs.enc)
3742  r = rb_enc_precise_mbclen(fptr->cbuf.ptr+fptr->cbuf.off,
3743  fptr->cbuf.ptr+fptr->cbuf.off+fptr->cbuf.len,
3744  fptr->encs.enc);
3745  else
3747  if (!MBCLEN_NEEDMORE_P(r))
3748  break;
3749  if (fptr->cbuf.len == fptr->cbuf.capa) {
3750  rb_raise(rb_eIOError, "too long character");
3751  }
3752  }
3753  if (more_char(fptr) == MORE_CHAR_FINISHED) {
3754  clear_readconv(fptr);
3755  if (!MBCLEN_CHARFOUND_P(r)) {
3756  enc = fptr->encs.enc;
3757  goto invalid;
3758  }
3759  return io;
3760  }
3761  }
3762  if (MBCLEN_INVALID_P(r)) {
3763  enc = fptr->encs.enc;
3764  goto invalid;
3765  }
3766  n = MBCLEN_CHARFOUND_LEN(r);
3767  if (fptr->encs.enc) {
3768  c = rb_enc_codepoint(fptr->cbuf.ptr+fptr->cbuf.off,
3769  fptr->cbuf.ptr+fptr->cbuf.off+fptr->cbuf.len,
3770  fptr->encs.enc);
3771  }
3772  else {
3773  c = (unsigned char)fptr->cbuf.ptr[fptr->cbuf.off];
3774  }
3775  fptr->cbuf.off += n;
3776  fptr->cbuf.len -= n;
3777  rb_yield(UINT2NUM(c));
3778  }
3779  }
3781  enc = io_input_encoding(fptr);
3782  while (io_fillbuf(fptr) >= 0) {
3783  r = rb_enc_precise_mbclen(fptr->rbuf.ptr+fptr->rbuf.off,
3784  fptr->rbuf.ptr+fptr->rbuf.off+fptr->rbuf.len, enc);
3785  if (MBCLEN_CHARFOUND_P(r) &&
3786  (n = MBCLEN_CHARFOUND_LEN(r)) <= fptr->rbuf.len) {
3787  c = rb_enc_codepoint(fptr->rbuf.ptr+fptr->rbuf.off,
3788  fptr->rbuf.ptr+fptr->rbuf.off+fptr->rbuf.len, enc);
3789  fptr->rbuf.off += n;
3790  fptr->rbuf.len -= n;
3791  rb_yield(UINT2NUM(c));
3792  }
3793  else if (MBCLEN_INVALID_P(r)) {
3794  invalid:
3795  rb_raise(rb_eArgError, "invalid byte sequence in %s", rb_enc_name(enc));
3796  }
3797  else if (MBCLEN_NEEDMORE_P(r)) {
3798  char cbuf[8], *p = cbuf;
3799  int more = MBCLEN_NEEDMORE_LEN(r);
3800  if (more > numberof(cbuf)) goto invalid;
3801  more += n = fptr->rbuf.len;
3802  if (more > numberof(cbuf)) goto invalid;
3803  while ((n = (int)read_buffered_data(p, more, fptr)) > 0 &&
3804  (p += n, (more -= n) > 0)) {
3805  if (io_fillbuf(fptr) < 0) goto invalid;
3806  if ((n = fptr->rbuf.len) > more) n = more;
3807  }
3808  r = rb_enc_precise_mbclen(cbuf, p, enc);
3809  if (!MBCLEN_CHARFOUND_P(r)) goto invalid;
3810  c = rb_enc_codepoint(cbuf, p, enc);
3811  rb_yield(UINT2NUM(c));
3812  }
3813  else {
3814  continue;
3815  }
3816  }
3817  return io;
3818 }
3819 
3820 /*
3821  * This is a deprecated alias for <code>each_codepoint</code>.
3822  */
3823 
3824 static VALUE
3826 {
3827  rb_warn("IO#codepoints is deprecated; use #each_codepoint instead");
3828  if (!rb_block_given_p())
3829  return rb_enumeratorize(io, ID2SYM(rb_intern("each_codepoint")), 0, 0);
3830  return rb_io_each_codepoint(io);
3831 }
3832 
3833 
3834 /*
3835  * call-seq:
3836  * ios.getc -> string or nil
3837  *
3838  * Reads a one-character string from <em>ios</em>. Returns
3839  * +nil+ if called at end of file.
3840  *
3841  * f = File.new("testfile")
3842  * f.getc #=> "h"
3843  * f.getc #=> "e"
3844  */
3845 
3846 static VALUE
3848 {
3849  rb_io_t *fptr;
3850  rb_encoding *enc;
3851 
3852  GetOpenFile(io, fptr);
3854 
3855  enc = io_input_encoding(fptr);
3856  READ_CHECK(fptr);
3857  return io_getc(fptr, enc);
3858 }
3859 
3860 /*
3861  * call-seq:
3862  * ios.readchar -> string
3863  *
3864  * Reads a one-character string from <em>ios</em>. Raises an
3865  * <code>EOFError</code> on end of file.
3866  *
3867  * f = File.new("testfile")
3868  * f.readchar #=> "h"
3869  * f.readchar #=> "e"
3870  */
3871 
3872 static VALUE
3874 {
3875  VALUE c = rb_io_getc(io);
3876 
3877  if (NIL_P(c)) {
3878  rb_eof_error();
3879  }
3880  return c;
3881 }
3882 
3883 /*
3884  * call-seq:
3885  * ios.getbyte -> integer or nil
3886  *
3887  * Gets the next 8-bit byte (0..255) from <em>ios</em>. Returns
3888  * +nil+ if called at end of file.
3889  *
3890  * f = File.new("testfile")
3891  * f.getbyte #=> 84
3892  * f.getbyte #=> 104
3893  */
3894 
3895 VALUE
3897 {
3898  rb_io_t *fptr;
3899  int c;
3900 
3901  GetOpenFile(io, fptr);
3903  READ_CHECK(fptr);
3904  if (fptr->fd == 0 && (fptr->mode & FMODE_TTY) && RB_TYPE_P(rb_stdout, T_FILE)) {
3905  rb_io_t *ofp;
3906  GetOpenFile(rb_stdout, ofp);
3907  if (ofp->mode & FMODE_TTY) {
3909  }
3910  }
3911  if (io_fillbuf(fptr) < 0) {
3912  return Qnil;
3913  }
3914  fptr->rbuf.off++;
3915  fptr->rbuf.len--;
3916  c = (unsigned char)fptr->rbuf.ptr[fptr->rbuf.off-1];
3917  return INT2FIX(c & 0xff);
3918 }
3919 
3920 /*
3921  * call-seq:
3922  * ios.readbyte -> integer
3923  *
3924  * Reads a byte as with <code>IO#getbyte</code>, but raises an
3925  * <code>EOFError</code> on end of file.
3926  */
3927 
3928 static VALUE
3930 {
3931  VALUE c = rb_io_getbyte(io);
3932 
3933  if (NIL_P(c)) {
3934  rb_eof_error();
3935  }
3936  return c;
3937 }
3938 
3939 /*
3940  * call-seq:
3941  * ios.ungetbyte(string) -> nil
3942  * ios.ungetbyte(integer) -> nil
3943  *
3944  * Pushes back bytes (passed as a parameter) onto <em>ios</em>,
3945  * such that a subsequent buffered read will return it. Only one byte
3946  * may be pushed back before a subsequent read operation (that is,
3947  * you will be able to read only the last of several bytes that have been pushed
3948  * back). Has no effect with unbuffered reads (such as <code>IO#sysread</code>).
3949  *
3950  * f = File.new("testfile") #=> #<File:testfile>
3951  * b = f.getbyte #=> 0x38
3952  * f.ungetbyte(b) #=> nil
3953  * f.getbyte #=> 0x38
3954  */
3955 
3956 VALUE
3958 {
3959  rb_io_t *fptr;
3960 
3961  GetOpenFile(io, fptr);
3963  if (NIL_P(b)) return Qnil;
3964  if (FIXNUM_P(b)) {
3965  char cc = FIX2INT(b);
3966  b = rb_str_new(&cc, 1);
3967  }
3968  else {
3969  SafeStringValue(b);
3970  }
3971  io_ungetbyte(b, fptr);
3972  return Qnil;
3973 }
3974 
3975 /*
3976  * call-seq:
3977  * ios.ungetc(string) -> nil
3978  *
3979  * Pushes back one character (passed as a parameter) onto <em>ios</em>,
3980  * such that a subsequent buffered character read will return it. Only one character
3981  * may be pushed back before a subsequent read operation (that is,
3982  * you will be able to read only the last of several characters that have been pushed
3983  * back). Has no effect with unbuffered reads (such as <code>IO#sysread</code>).
3984  *
3985  * f = File.new("testfile") #=> #<File:testfile>
3986  * c = f.getc #=> "8"
3987  * f.ungetc(c) #=> nil
3988  * f.getc #=> "8"
3989  */
3990 
3991 VALUE
3993 {
3994  rb_io_t *fptr;
3995  long len;
3996 
3997  GetOpenFile(io, fptr);
3999  if (NIL_P(c)) return Qnil;
4000  if (FIXNUM_P(c)) {
4001  c = rb_enc_uint_chr(FIX2UINT(c), io_read_encoding(fptr));
4002  }
4003  else if (RB_TYPE_P(c, T_BIGNUM)) {
4004  c = rb_enc_uint_chr(NUM2UINT(c), io_read_encoding(fptr));
4005  }
4006  else {
4007  SafeStringValue(c);
4008  }
4009  if (NEED_READCONV(fptr)) {
4010  SET_BINARY_MODE(fptr);
4011  len = RSTRING_LEN(c);
4012 #if SIZEOF_LONG > SIZEOF_INT
4013  if (len > INT_MAX)
4014  rb_raise(rb_eIOError, "ungetc failed");
4015 #endif
4016  make_readconv(fptr, (int)len);
4017  if (fptr->cbuf.capa - fptr->cbuf.len < len)
4018  rb_raise(rb_eIOError, "ungetc failed");
4019  if (fptr->cbuf.off < len) {
4020  MEMMOVE(fptr->cbuf.ptr+fptr->cbuf.capa-fptr->cbuf.len,
4021  fptr->cbuf.ptr+fptr->cbuf.off,
4022  char, fptr->cbuf.len);
4023  fptr->cbuf.off = fptr->cbuf.capa-fptr->cbuf.len;
4024  }
4025  fptr->cbuf.off -= (int)len;
4026  fptr->cbuf.len += (int)len;
4027  MEMMOVE(fptr->cbuf.ptr+fptr->cbuf.off, RSTRING_PTR(c), char, len);
4028  }
4029  else {
4031  io_ungetbyte(c, fptr);
4032  }
4033  return Qnil;
4034 }
4035 
4036 /*
4037  * call-seq:
4038  * ios.isatty -> true or false
4039  * ios.tty? -> true or false
4040  *
4041  * Returns <code>true</code> if <em>ios</em> is associated with a
4042  * terminal device (tty), <code>false</code> otherwise.
4043  *
4044  * File.new("testfile").isatty #=> false
4045  * File.new("/dev/tty").isatty #=> true
4046  */
4047 
4048 static VALUE
4050 {
4051  rb_io_t *fptr;
4052 
4053  GetOpenFile(io, fptr);
4054  if (isatty(fptr->fd) == 0)
4055  return Qfalse;
4056  return Qtrue;
4057 }
4058 
4059 #if defined(HAVE_FCNTL) && defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
4060 /*
4061  * call-seq:
4062  * ios.close_on_exec? -> true or false
4063  *
4064  * Returns <code>true</code> if <em>ios</em> will be closed on exec.
4065  *
4066  * f = open("/dev/null")
4067  * f.close_on_exec? #=> false
4068  * f.close_on_exec = true
4069  * f.close_on_exec? #=> true
4070  * f.close_on_exec = false
4071  * f.close_on_exec? #=> false
4072  */
4073 
4074 static VALUE
4076 {
4077  rb_io_t *fptr;
4078  VALUE write_io;
4079  int fd, ret;
4080 
4081  write_io = GetWriteIO(io);
4082  if (io != write_io) {
4083  GetOpenFile(write_io, fptr);
4084  if (fptr && 0 <= (fd = fptr->fd)) {
4085  if ((ret = fcntl(fd, F_GETFD)) == -1) rb_sys_fail_path(fptr->pathv);
4086  if (!(ret & FD_CLOEXEC)) return Qfalse;
4087  }
4088  }
4089 
4090  GetOpenFile(io, fptr);
4091  if (fptr && 0 <= (fd = fptr->fd)) {
4092  if ((ret = fcntl(fd, F_GETFD)) == -1) rb_sys_fail_path(fptr->pathv);
4093  if (!(ret & FD_CLOEXEC)) return Qfalse;
4094  }
4095  return Qtrue;
4096 }
4097 #else
4098 #define rb_io_close_on_exec_p rb_f_notimplement
4099 #endif
4100 
4101 #if defined(HAVE_FCNTL) && defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
4102 /*
4103  * call-seq:
4104  * ios.close_on_exec = bool -> true or false
4105  *
4106  * Sets a close-on-exec flag.
4107  *
4108  * f = open("/dev/null")
4109  * f.close_on_exec = true
4110  * system("cat", "/proc/self/fd/#{f.fileno}") # cat: /proc/self/fd/3: No such file or directory
4111  * f.closed? #=> false
4112  *
4113  * Ruby sets close-on-exec flags of all file descriptors by default
4114  * since Ruby 2.0.0.
4115  * So you don't need to set by yourself.
4116  * Also, unsetting a close-on-exec flag can cause file descriptor leak
4117  * if another thread use fork() and exec() (via system() method for example).
4118  * If you really needs file descriptor inheritance to child process,
4119  * use spawn()'s argument such as fd=>fd.
4120  */
4121 
4122 static VALUE
4124 {
4125  int flag = RTEST(arg) ? FD_CLOEXEC : 0;
4126  rb_io_t *fptr;
4127  VALUE write_io;
4128  int fd, ret;
4129 
4130  write_io = GetWriteIO(io);
4131  if (io != write_io) {
4132  GetOpenFile(write_io, fptr);
4133  if (fptr && 0 <= (fd = fptr->fd)) {
4134  if ((ret = fcntl(fptr->fd, F_GETFD)) == -1) rb_sys_fail_path(fptr->pathv);
4135  if ((ret & FD_CLOEXEC) != flag) {
4136  ret = (ret & ~FD_CLOEXEC) | flag;
4137  ret = fcntl(fd, F_SETFD, ret);
4138  if (ret == -1) rb_sys_fail_path(fptr->pathv);
4139  }
4140  }
4141 
4142  }
4143 
4144  GetOpenFile(io, fptr);
4145  if (fptr && 0 <= (fd = fptr->fd)) {
4146  if ((ret = fcntl(fd, F_GETFD)) == -1) rb_sys_fail_path(fptr->pathv);
4147  if ((ret & FD_CLOEXEC) != flag) {
4148  ret = (ret & ~FD_CLOEXEC) | flag;
4149  ret = fcntl(fd, F_SETFD, ret);
4150  if (ret == -1) rb_sys_fail_path(fptr->pathv);
4151  }
4152  }
4153  return Qnil;
4154 }
4155 #else
4156 #define rb_io_set_close_on_exec rb_f_notimplement
4157 #endif
4158 
4159 #define FMODE_PREP (1<<16)
4160 #define IS_PREP_STDIO(f) ((f)->mode & FMODE_PREP)
4161 #define PREP_STDIO_NAME(f) (RSTRING_PTR((f)->pathv))
4162 
4163 static VALUE
4164 finish_writeconv(rb_io_t *fptr, int noalloc)
4165 {
4166  unsigned char *ds, *dp, *de;
4167  rb_econv_result_t res;
4168 
4169  if (!fptr->wbuf.ptr) {
4170  unsigned char buf[1024];
4171  long r;
4172 
4174  while (res == econv_destination_buffer_full) {
4175  ds = dp = buf;
4176  de = buf + sizeof(buf);
4177  res = rb_econv_convert(fptr->writeconv, NULL, NULL, &dp, de, 0);
4178  while (dp-ds) {
4179  retry:
4180  if (fptr->write_lock && rb_mutex_owned_p(fptr->write_lock))
4181  r = rb_write_internal2(fptr->fd, ds, dp-ds);
4182  else
4183  r = rb_write_internal(fptr->fd, ds, dp-ds);
4184  if (r == dp-ds)
4185  break;
4186  if (0 <= r) {
4187  ds += r;
4188  }
4189  if (rb_io_wait_writable(fptr->fd)) {
4190  if (fptr->fd < 0)
4192  goto retry;
4193  }
4194  return noalloc ? Qtrue : INT2NUM(errno);
4195  }
4196  if (res == econv_invalid_byte_sequence ||
4197  res == econv_incomplete_input ||
4198  res == econv_undefined_conversion) {
4199  return noalloc ? Qtrue : rb_econv_make_exception(fptr->writeconv);
4200  }
4201  }
4202 
4203  return Qnil;
4204  }
4205 
4207  while (res == econv_destination_buffer_full) {
4208  if (fptr->wbuf.len == fptr->wbuf.capa) {
4209  if (io_fflush(fptr) < 0)
4210  return noalloc ? Qtrue : INT2NUM(errno);
4211  }
4212 
4213  ds = dp = (unsigned char *)fptr->wbuf.ptr + fptr->wbuf.off + fptr->wbuf.len;
4214  de = (unsigned char *)fptr->wbuf.ptr + fptr->wbuf.capa;
4215  res = rb_econv_convert(fptr->writeconv, NULL, NULL, &dp, de, 0);
4216  fptr->wbuf.len += (int)(dp - ds);
4217  if (res == econv_invalid_byte_sequence ||
4218  res == econv_incomplete_input ||
4219  res == econv_undefined_conversion) {
4220  return noalloc ? Qtrue : rb_econv_make_exception(fptr->writeconv);
4221  }
4222  }
4223  return Qnil;
4224 }
4225 
4228  int noalloc;
4229 };
4230 
4231 static VALUE
4233 {
4234  struct finish_writeconv_arg *p = (struct finish_writeconv_arg *)arg;
4235  return finish_writeconv(p->fptr, p->noalloc);
4236 }
4237 
4238 static void*
4239 nogvl_close(void *ptr)
4240 {
4241  int *fd = ptr;
4242 
4243  return (void*)(intptr_t)close(*fd);
4244 }
4245 
4246 static int
4247 maygvl_close(int fd, int keepgvl)
4248 {
4249  if (keepgvl)
4250  return close(fd);
4251 
4252  /*
4253  * close() may block for certain file types (NFS, SO_LINGER sockets,
4254  * inotify), so let other threads run.
4255  */
4257 }
4258 
4259 static void*
4260 nogvl_fclose(void *ptr)
4261 {
4262  FILE *file = ptr;
4263 
4264  return (void*)(intptr_t)fclose(file);
4265 }
4266 
4267 static int
4268 maygvl_fclose(FILE *file, int keepgvl)
4269 {
4270  if (keepgvl)
4271  return fclose(file);
4272 
4274 }
4275 
4276 static void free_io_buffer(rb_io_buffer_t *buf);
4277 static void clear_codeconv(rb_io_t *fptr);
4278 
4279 static void
4280 fptr_finalize_flush(rb_io_t *fptr, int noraise)
4281 {
4282  VALUE err = Qnil;
4283  int fd = fptr->fd;
4284  FILE *stdio_file = fptr->stdio_file;
4285  int mode = fptr->mode;
4286 
4287  if (fptr->writeconv) {
4288  if (fptr->write_lock && !noraise) {
4289  struct finish_writeconv_arg arg;
4290  arg.fptr = fptr;
4291  arg.noalloc = noraise;
4293  }
4294  else {
4295  err = finish_writeconv(fptr, noraise);
4296  }
4297  }
4298  if (fptr->wbuf.len) {
4299  if (noraise) {
4300  if ((int)io_flush_buffer_sync(fptr) < 0 && NIL_P(err))
4301  err = Qtrue;
4302  }
4303  else {
4304  if (io_fflush(fptr) < 0 && NIL_P(err))
4305  err = INT2NUM(errno);
4306  }
4307  }
4308 
4309  fptr->fd = -1;
4310  fptr->stdio_file = 0;
4311  fptr->mode &= ~(FMODE_READABLE|FMODE_WRITABLE);
4312 
4313  if (IS_PREP_STDIO(fptr) || fd <= 2) {
4314  /* need to keep FILE objects of stdin, stdout and stderr */
4315  }
4316  else if (stdio_file) {
4317  /* stdio_file is deallocated anyway
4318  * even if fclose failed. */
4319  if ((maygvl_fclose(stdio_file, noraise) < 0) && NIL_P(err))
4320  err = noraise ? Qtrue : INT2NUM(errno);
4321  }
4322  else if (0 <= fd) {
4323  /* fptr->fd may be closed even if close fails.
4324  * POSIX doesn't specify it.
4325  * We assumes it is closed. */
4326 
4327 
4328  int keepgvl = !(mode & FMODE_WRITABLE);
4329  keepgvl |= noraise;
4330  if ((maygvl_close(fd, keepgvl) < 0) && NIL_P(err))
4331  err = noraise ? Qtrue : INT2NUM(errno);
4332  }
4333 
4334  if (!NIL_P(err) && !noraise) {
4335  if (RB_INTEGER_TYPE_P(err))
4336  rb_syserr_fail_path(NUM2INT(err), fptr->pathv);
4337  else
4338  rb_exc_raise(err);
4339  }
4340 }
4341 
4342 static void
4343 fptr_finalize(rb_io_t *fptr, int noraise)
4344 {
4345  fptr_finalize_flush(fptr, noraise);
4346  free_io_buffer(&fptr->rbuf);
4347  free_io_buffer(&fptr->wbuf);
4348  clear_codeconv(fptr);
4349 }
4350 
4351 static void
4352 rb_io_fptr_cleanup(rb_io_t *fptr, int noraise)
4353 {
4354  if (fptr->finalize) {
4355  (*fptr->finalize)(fptr, noraise);
4356  }
4357  else {
4358  fptr_finalize(fptr, noraise);
4359  }
4360 }
4361 
4362 static void
4364 {
4365  if (buf->ptr) {
4366  ruby_sized_xfree(buf->ptr, (size_t)buf->capa);
4367  buf->ptr = NULL;
4368  }
4369 }
4370 
4371 static void
4373 {
4374  if (fptr->readconv) {
4375  rb_econv_close(fptr->readconv);
4376  fptr->readconv = NULL;
4377  }
4378  free_io_buffer(&fptr->cbuf);
4379 }
4380 
4381 static void
4383 {
4384  if (fptr->writeconv) {
4385  rb_econv_close(fptr->writeconv);
4386  fptr->writeconv = NULL;
4387  }
4388  fptr->writeconv_initialized = 0;
4389 }
4390 
4391 static void
4393 {
4394  clear_readconv(fptr);
4395  clear_writeconv(fptr);
4396 }
4397 
4398 int
4400 {
4401  if (!fptr) return 0;
4402  fptr->pathv = Qnil;
4403  if (0 <= fptr->fd)
4404  rb_io_fptr_cleanup(fptr, TRUE);
4405  fptr->write_lock = 0;
4406  free_io_buffer(&fptr->rbuf);
4407  free_io_buffer(&fptr->wbuf);
4408  clear_codeconv(fptr);
4409  free(fptr);
4410  return 1;
4411 }
4412 
4413 RUBY_FUNC_EXPORTED size_t
4415 {
4416  size_t size = sizeof(rb_io_t);
4417  size += fptr->rbuf.capa;
4418  size += fptr->wbuf.capa;
4419  size += fptr->cbuf.capa;
4420  if (fptr->readconv) size += rb_econv_memsize(fptr->readconv);
4421  if (fptr->writeconv) size += rb_econv_memsize(fptr->writeconv);
4422  return size;
4423 }
4424 
4425 int rb_notify_fd_close(int fd);
4426 static rb_io_t *
4428 {
4429  rb_io_t *fptr;
4430  int fd;
4431  VALUE write_io;
4432  rb_io_t *write_fptr;
4433  int busy;
4434 
4435  write_io = GetWriteIO(io);
4436  if (io != write_io) {
4437  write_fptr = RFILE(write_io)->fptr;
4438  if (write_fptr && 0 <= write_fptr->fd) {
4439  rb_io_fptr_cleanup(write_fptr, TRUE);
4440  }
4441  }
4442 
4443  fptr = RFILE(io)->fptr;
4444  if (!fptr) return 0;
4445  if (fptr->fd < 0) return 0;
4446 
4447  fd = fptr->fd;
4448  busy = rb_notify_fd_close(fd);
4449  fptr_finalize_flush(fptr, FALSE);
4450  if (busy) {
4451  do rb_thread_schedule(); while (rb_notify_fd_close(fd));
4452  }
4453  rb_io_fptr_cleanup(fptr, FALSE);
4454  return fptr;
4455 }
4456 
4457 static void
4458 fptr_waitpid(rb_io_t *fptr, int nohang)
4459 {
4460  int status;
4461  if (fptr->pid) {
4463  rb_waitpid(fptr->pid, &status, nohang ? WNOHANG : 0);
4464  fptr->pid = 0;
4465  }
4466 }
4467 
4468 VALUE
4470 {
4471  rb_io_t *fptr = io_close_fptr(io);
4472  if (fptr) fptr_waitpid(fptr, 0);
4473  return Qnil;
4474 }
4475 
4476 /*
4477  * call-seq:
4478  * ios.close -> nil
4479  *
4480  * Closes <em>ios</em> and flushes any pending writes to the operating
4481  * system. The stream is unavailable for any further data operations;
4482  * an <code>IOError</code> is raised if such an attempt is made. I/O
4483  * streams are automatically closed when they are claimed by the
4484  * garbage collector.
4485  *
4486  * If <em>ios</em> is opened by <code>IO.popen</code>,
4487  * <code>close</code> sets <code>$?</code>.
4488  *
4489  * Calling this method on closed IO object is just ignored since Ruby 2.3.
4490  */
4491 
4492 static VALUE
4494 {
4495  rb_io_t *fptr = rb_io_get_fptr(io);
4496  if (fptr->fd < 0) {
4497  return Qnil;
4498  }
4499  rb_io_close(io);
4500  return Qnil;
4501 }
4502 
4503 static VALUE
4505 {
4506  rb_check_funcall(io, rb_intern("close"), 0, 0);
4507  return io;
4508 }
4509 
4510 static VALUE
4512 {
4513  enum {mesg_len = sizeof(closed_stream)-1};
4514  VALUE mesg = rb_attr_get(exc, rb_intern("mesg"));
4515  if (!RB_TYPE_P(mesg, T_STRING) ||
4516  RSTRING_LEN(mesg) != mesg_len ||
4517  memcmp(RSTRING_PTR(mesg), closed_stream, mesg_len)) {
4518  rb_exc_raise(exc);
4519  }
4520  return io;
4521 }
4522 
4523 static VALUE
4525 {
4526  VALUE closed = rb_check_funcall(io, rb_intern("closed?"), 0, 0);
4527  if (closed != Qundef && RTEST(closed)) return io;
4529  rb_eIOError, (VALUE)0);
4530  return io;
4531 }
4532 
4533 /*
4534  * call-seq:
4535  * ios.closed? -> true or false
4536  *
4537  * Returns <code>true</code> if <em>ios</em> is completely closed (for
4538  * duplex streams, both reader and writer), <code>false</code>
4539  * otherwise.
4540  *
4541  * f = File.new("testfile")
4542  * f.close #=> nil
4543  * f.closed? #=> true
4544  * f = IO.popen("/bin/sh","r+")
4545  * f.close_write #=> nil
4546  * f.closed? #=> false
4547  * f.close_read #=> nil
4548  * f.closed? #=> true
4549  */
4550 
4551 
4552 static VALUE
4554 {
4555  rb_io_t *fptr;
4556  VALUE write_io;
4557  rb_io_t *write_fptr;
4558 
4559  write_io = GetWriteIO(io);
4560  if (io != write_io) {
4561  write_fptr = RFILE(write_io)->fptr;
4562  if (write_fptr && 0 <= write_fptr->fd) {
4563  return Qfalse;
4564  }
4565  }
4566 
4567  fptr = rb_io_get_fptr(io);
4568  return 0 <= fptr->fd ? Qfalse : Qtrue;
4569 }
4570 
4571 /*
4572  * call-seq:
4573  * ios.close_read -> nil
4574  *
4575  * Closes the read end of a duplex I/O stream (i.e., one that contains
4576  * both a read and a write stream, such as a pipe). Will raise an
4577  * <code>IOError</code> if the stream is not duplexed.
4578  *
4579  * f = IO.popen("/bin/sh","r+")
4580  * f.close_read
4581  * f.readlines
4582  *
4583  * <em>produces:</em>
4584  *
4585  * prog.rb:3:in `readlines': not opened for reading (IOError)
4586  * from prog.rb:3
4587  */
4588 
4589 static VALUE
4591 {
4592  rb_io_t *fptr;
4593  VALUE write_io;
4594 
4595  fptr = rb_io_get_fptr(rb_io_taint_check(io));
4596  if (fptr->fd < 0) return Qnil;
4597  if (is_socket(fptr->fd, fptr->pathv)) {
4598 #ifndef SHUT_RD
4599 # define SHUT_RD 0
4600 #endif
4601  if (shutdown(fptr->fd, SHUT_RD) < 0)
4602  rb_sys_fail_path(fptr->pathv);
4603  fptr->mode &= ~FMODE_READABLE;
4604  if (!(fptr->mode & FMODE_WRITABLE))
4605  return rb_io_close(io);
4606  return Qnil;
4607  }
4608 
4609  write_io = GetWriteIO(io);
4610  if (io != write_io) {
4611  rb_io_t *wfptr;
4612  wfptr = rb_io_get_fptr(rb_io_taint_check(write_io));
4613  wfptr->pid = fptr->pid;
4614  fptr->pid = 0;
4615  RFILE(io)->fptr = wfptr;
4616  /* bind to write_io temporarily to get rid of memory/fd leak */
4617  fptr->tied_io_for_writing = 0;
4618  RFILE(write_io)->fptr = fptr;
4619  rb_io_fptr_cleanup(fptr, FALSE);
4620  /* should not finalize fptr because another thread may be reading it */
4621  return Qnil;
4622  }
4623 
4624  if ((fptr->mode & (FMODE_DUPLEX|FMODE_WRITABLE)) == FMODE_WRITABLE) {
4625  rb_raise(rb_eIOError, "closing non-duplex IO for reading");
4626  }
4627  return rb_io_close(io);
4628 }
4629 
4630 /*
4631  * call-seq:
4632  * ios.close_write -> nil
4633  *
4634  * Closes the write end of a duplex I/O stream (i.e., one that contains
4635  * both a read and a write stream, such as a pipe). Will raise an
4636  * <code>IOError</code> if the stream is not duplexed.
4637  *
4638  * f = IO.popen("/bin/sh","r+")
4639  * f.close_write
4640  * f.print "nowhere"
4641  *
4642  * <em>produces:</em>
4643  *
4644  * prog.rb:3:in `write': not opened for writing (IOError)
4645  * from prog.rb:3:in `print'
4646  * from prog.rb:3
4647  */
4648 
4649 static VALUE
4651 {
4652  rb_io_t *fptr;
4653  VALUE write_io;
4654 
4655  write_io = GetWriteIO(io);
4656  fptr = rb_io_get_fptr(rb_io_taint_check(write_io));
4657  if (fptr->fd < 0) return Qnil;
4658  if (is_socket(fptr->fd, fptr->pathv)) {
4659 #ifndef SHUT_WR
4660 # define SHUT_WR 1
4661 #endif
4662  if (shutdown(fptr->fd, SHUT_WR) < 0)
4663  rb_sys_fail_path(fptr->pathv);
4664  fptr->mode &= ~FMODE_WRITABLE;
4665  if (!(fptr->mode & FMODE_READABLE))
4666  return rb_io_close(write_io);
4667  return Qnil;
4668  }
4669 
4670  if ((fptr->mode & (FMODE_DUPLEX|FMODE_READABLE)) == FMODE_READABLE) {
4671  rb_raise(rb_eIOError, "closing non-duplex IO for writing");
4672  }
4673 
4674  if (io != write_io) {
4675  fptr = rb_io_get_fptr(rb_io_taint_check(io));
4676  fptr->tied_io_for_writing = 0;
4677  }
4678  rb_io_close(write_io);
4679  return Qnil;
4680 }
4681 
4682 /*
4683  * call-seq:
4684  * ios.sysseek(offset, whence=IO::SEEK_SET) -> integer
4685  *
4686  * Seeks to a given <i>offset</i> in the stream according to the value
4687  * of <i>whence</i> (see <code>IO#seek</code> for values of
4688  * <i>whence</i>). Returns the new offset into the file.
4689  *
4690  * f = File.new("testfile")
4691  * f.sysseek(-13, IO::SEEK_END) #=> 53
4692  * f.sysread(10) #=> "And so on."
4693  */
4694 
4695 static VALUE
4697 {
4698  VALUE offset, ptrname;
4699  int whence = SEEK_SET;
4700  rb_io_t *fptr;
4701  off_t pos;
4702 
4703  if (rb_scan_args(argc, argv, "11", &offset, &ptrname) == 2) {
4704  whence = interpret_seek_whence(ptrname);
4705  }
4706  pos = NUM2OFFT(offset);
4707  GetOpenFile(io, fptr);
4708  if ((fptr->mode & FMODE_READABLE) &&
4709  (READ_DATA_BUFFERED(fptr) || READ_CHAR_PENDING(fptr))) {
4710  rb_raise(rb_eIOError, "sysseek for buffered IO");
4711  }
4712  if ((fptr->mode & FMODE_WRITABLE) && fptr->wbuf.len) {
4713  rb_warn("sysseek for buffered IO");
4714  }
4715  errno = 0;
4716  pos = lseek(fptr->fd, pos, whence);
4717  if (pos == -1 && errno) rb_sys_fail_path(fptr->pathv);
4718 
4719  return OFFT2NUM(pos);
4720 }
4721 
4722 /*
4723  * call-seq:
4724  * ios.syswrite(string) -> integer
4725  *
4726  * Writes the given string to <em>ios</em> using a low-level write.
4727  * Returns the number of bytes written. Do not mix with other methods
4728  * that write to <em>ios</em> or you may get unpredictable results.
4729  * Raises <code>SystemCallError</code> on error.
4730  *
4731  * f = File.new("out", "w")
4732  * f.syswrite("ABCDEF") #=> 6
4733  */
4734 
4735 static VALUE
4737 {
4738  VALUE tmp;
4739  rb_io_t *fptr;
4740  long n, len;
4741  const char *ptr;
4742 
4743  if (!RB_TYPE_P(str, T_STRING))
4744  str = rb_obj_as_string(str);
4745 
4746  io = GetWriteIO(io);
4747  GetOpenFile(io, fptr);
4748  rb_io_check_writable(fptr);
4749 
4750  if (fptr->wbuf.len) {
4751  rb_warn("syswrite for buffered IO");
4752  }
4753 
4754  tmp = rb_str_tmp_frozen_acquire(str);
4755  RSTRING_GETMEM(tmp, ptr, len);
4756  n = rb_write_internal(fptr->fd, ptr, len);
4757  if (n == -1) rb_sys_fail_path(fptr->pathv);
4758  rb_str_tmp_frozen_release(str, tmp);
4759 
4760  return LONG2FIX(n);
4761 }
4762 
4763 /*
4764  * call-seq:
4765  * ios.sysread(maxlen[, outbuf]) -> string
4766  *
4767  * Reads <i>maxlen</i> bytes from <em>ios</em> using a low-level
4768  * read and returns them as a string. Do not mix with other methods
4769  * that read from <em>ios</em> or you may get unpredictable results.
4770  *
4771  * If the optional _outbuf_ argument is present,
4772  * it must reference a String, which will receive the data.
4773  * The _outbuf_ will contain only the received data after the method call
4774  * even if it is not empty at the beginning.
4775  *
4776  * Raises <code>SystemCallError</code> on error and
4777  * <code>EOFError</code> at end of file.
4778  *
4779  * f = File.new("testfile")
4780  * f.sysread(16) #=> "This is line one"
4781  */
4782 
4783 static VALUE
4785 {
4786  VALUE len, str;
4787  rb_io_t *fptr;
4788  long n, ilen;
4789  struct read_internal_arg arg;
4790 
4791  rb_scan_args(argc, argv, "11", &len, &str);
4792  ilen = NUM2LONG(len);
4793 
4794  io_setstrbuf(&str,ilen);
4795  if (ilen == 0) return str;
4796 
4797  GetOpenFile(io, fptr);
4799 
4800  if (READ_DATA_BUFFERED(fptr)) {
4801  rb_raise(rb_eIOError, "sysread for buffered IO");
4802  }
4803 
4804  /*
4805  * FIXME: removing rb_thread_wait_fd() here changes sysread semantics
4806  * on non-blocking IOs. However, it's still currently possible
4807  * for sysread to raise Errno::EAGAIN if another thread read()s
4808  * the IO after we return from rb_thread_wait_fd() but before
4809  * we call read()
4810  */
4811  rb_thread_wait_fd(fptr->fd);
4812 
4813  rb_io_check_closed(fptr);
4814 
4815  io_setstrbuf(&str, ilen);
4816  rb_str_locktmp(str);
4817  arg.fd = fptr->fd;
4818  arg.str_ptr = RSTRING_PTR(str);
4819  arg.len = ilen;
4821  n = arg.len;
4822 
4823  if (n == -1) {
4824  rb_sys_fail_path(fptr->pathv);
4825  }
4826  io_set_read_length(str, n);
4827  if (n == 0 && ilen > 0) {
4828  rb_eof_error();
4829  }
4830  OBJ_TAINT(str);
4831 
4832  return str;
4833 }
4834 
4835 VALUE
4837 {
4838  rb_io_t *fptr;
4839 
4840  GetOpenFile(io, fptr);
4841  if (fptr->readconv)
4842  rb_econv_binmode(fptr->readconv);
4843  if (fptr->writeconv)
4844  rb_econv_binmode(fptr->writeconv);
4845  fptr->mode |= FMODE_BINMODE;
4846  fptr->mode &= ~FMODE_TEXTMODE;
4848 #ifdef O_BINARY
4849  if (!fptr->readconv) {
4851  }
4852  else {
4853  setmode(fptr->fd, O_BINARY);
4854  }
4855 #endif
4856  return io;
4857 }
4858 
4859 static void
4861 {
4862  if (fptr->readconv) {
4863  rb_econv_close(fptr->readconv);
4864  fptr->readconv = NULL;
4865  }
4866  if (fptr->writeconv) {
4867  rb_econv_close(fptr->writeconv);
4868  fptr->writeconv = NULL;
4869  }
4870  fptr->mode |= FMODE_BINMODE;
4871  fptr->mode &= ~FMODE_TEXTMODE;
4873 
4874  fptr->encs.enc = rb_ascii8bit_encoding();
4875  fptr->encs.enc2 = NULL;
4876  fptr->encs.ecflags = 0;
4877  fptr->encs.ecopts = Qnil;
4878  clear_codeconv(fptr);
4879 }
4880 
4881 VALUE
4883 {
4884  rb_io_t *fptr;
4885 
4886  GetOpenFile(io, fptr);
4887  io_ascii8bit_binmode(fptr);
4888 
4889  return io;
4890 }
4891 
4892 /*
4893  * call-seq:
4894  * ios.binmode -> ios
4895  *
4896  * Puts <em>ios</em> into binary mode.
4897  * Once a stream is in binary mode, it cannot be reset to nonbinary mode.
4898  *
4899  * - newline conversion disabled
4900  * - encoding conversion disabled
4901  * - content is treated as ASCII-8BIT
4902  */
4903 
4904 static VALUE
4906 {
4907  VALUE write_io;
4908 
4910 
4911  write_io = GetWriteIO(io);
4912  if (write_io != io)
4913  rb_io_ascii8bit_binmode(write_io);
4914  return io;
4915 }
4916 
4917 /*
4918  * call-seq:
4919  * ios.binmode? -> true or false
4920  *
4921  * Returns <code>true</code> if <em>ios</em> is binmode.
4922  */
4923 static VALUE
4925 {
4926  rb_io_t *fptr;
4927  GetOpenFile(io, fptr);
4928  return fptr->mode & FMODE_BINMODE ? Qtrue : Qfalse;
4929 }
4930 
4931 static const char*
4933 {
4934  if (fmode & FMODE_APPEND) {
4935  if ((fmode & FMODE_READWRITE) == FMODE_READWRITE) {
4936  return MODE_BTMODE("a+", "ab+", "at+");
4937  }
4938  return MODE_BTMODE("a", "ab", "at");
4939  }
4940  switch (fmode & FMODE_READWRITE) {
4941  default:
4942  rb_raise(rb_eArgError, "invalid access fmode 0x%x", fmode);
4943  case FMODE_READABLE:
4944  return MODE_BTMODE("r", "rb", "rt");
4945  case FMODE_WRITABLE:
4946  return MODE_BTMODE("w", "wb", "wt");
4947  case FMODE_READWRITE:
4948  if (fmode & FMODE_CREATE) {
4949  return MODE_BTMODE("w+", "wb+", "wt+");
4950  }
4951  return MODE_BTMODE("r+", "rb+", "rt+");
4952  }
4953 }
4954 
4955 static const char bom_prefix[] = "bom|";
4956 static const char utf_prefix[] = "utf-";
4957 enum {bom_prefix_len = (int)sizeof(bom_prefix) - 1};
4958 enum {utf_prefix_len = (int)sizeof(utf_prefix) - 1};
4959 
4960 static int
4961 io_encname_bom_p(const char *name, long len)
4962 {
4963  return len > bom_prefix_len && STRNCASECMP(name, bom_prefix, bom_prefix_len) == 0;
4964 }
4965 
4966 int
4967 rb_io_modestr_fmode(const char *modestr)
4968 {
4969  int fmode = 0;
4970  const char *m = modestr, *p = NULL;
4971 
4972  switch (*m++) {
4973  case 'r':
4974  fmode |= FMODE_READABLE;
4975  break;
4976  case 'w':
4978  break;
4979  case 'a':
4981  break;
4982  default:
4983  error:
4984  rb_raise(rb_eArgError, "invalid access mode %s", modestr);
4985  }
4986 
4987  while (*m) {
4988  switch (*m++) {
4989  case 'b':
4990  fmode |= FMODE_BINMODE;
4991  break;
4992  case 't':
4993  fmode |= FMODE_TEXTMODE;
4994  break;
4995  case '+':
4996  fmode |= FMODE_READWRITE;
4997  break;
4998  default:
4999  goto error;
5000  case ':':
5001  p = strchr(m, ':');
5002  if (io_encname_bom_p(m, p ? (long)(p - m) : (long)strlen(m)))
5003  fmode |= FMODE_SETENC_BY_BOM;
5004  goto finished;
5005  }
5006  }
5007 
5008  finished:
5009  if ((fmode & FMODE_BINMODE) && (fmode & FMODE_TEXTMODE))
5010  goto error;
5011 
5012  return fmode;
5013 }
5014 
5015 int
5017 {
5018  int fmode = 0;
5019 
5020  switch (oflags & O_ACCMODE) {
5021  case O_RDONLY:
5022  fmode = FMODE_READABLE;
5023  break;
5024  case O_WRONLY:
5025  fmode = FMODE_WRITABLE;
5026  break;
5027  case O_RDWR:
5028  fmode = FMODE_READWRITE;
5029  break;
5030  }
5031 
5032  if (oflags & O_APPEND) {
5033  fmode |= FMODE_APPEND;
5034  }
5035  if (oflags & O_TRUNC) {
5036  fmode |= FMODE_TRUNC;
5037  }
5038  if (oflags & O_CREAT) {
5039  fmode |= FMODE_CREATE;
5040  }
5041 #ifdef O_BINARY
5042  if (oflags & O_BINARY) {
5043  fmode |= FMODE_BINMODE;
5044  }
5045 #endif
5046 
5047  return fmode;
5048 }
5049 
5050 static int
5052 {
5053  int oflags = 0;
5054 
5055  switch (fmode & FMODE_READWRITE) {
5056  case FMODE_READABLE:
5057  oflags |= O_RDONLY;
5058  break;
5059  case FMODE_WRITABLE:
5060  oflags |= O_WRONLY;
5061  break;
5062  case FMODE_READWRITE:
5063  oflags |= O_RDWR;
5064  break;
5065  }
5066 
5067  if (fmode & FMODE_APPEND) {
5068  oflags |= O_APPEND;
5069  }
5070  if (fmode & FMODE_TRUNC) {
5071  oflags |= O_TRUNC;
5072  }
5073  if (fmode & FMODE_CREATE) {
5074  oflags |= O_CREAT;
5075  }
5076 #ifdef O_BINARY
5077  if (fmode & FMODE_BINMODE) {
5078  oflags |= O_BINARY;
5079  }
5080 #endif
5081 
5082  return oflags;
5083 }
5084 
5085 int
5086 rb_io_modestr_oflags(const char *modestr)
5087 {
5088  return rb_io_fmode_oflags(rb_io_modestr_fmode(modestr));
5089 }
5090 
5091 static const char*
5093 {
5094 #ifdef O_BINARY
5095 # define MODE_BINARY(a,b) ((oflags & O_BINARY) ? (b) : (a))
5096 #else
5097 # define MODE_BINARY(a,b) (a)
5098 #endif
5099  int accmode = oflags & (O_RDONLY|O_WRONLY|O_RDWR);
5100  if (oflags & O_APPEND) {
5101  if (accmode == O_WRONLY) {
5102  return MODE_BINARY("a", "ab");
5103  }
5104  if (accmode == O_RDWR) {
5105  return MODE_BINARY("a+", "ab+");
5106  }
5107  }
5108  switch (oflags & (O_RDONLY|O_WRONLY|O_RDWR)) {
5109  default:
5110  rb_raise(rb_eArgError, "invalid access oflags 0x%x", oflags);
5111  case O_RDONLY:
5112  return MODE_BINARY("r", "rb");
5113  case O_WRONLY:
5114  return MODE_BINARY("w", "wb");
5115  case O_RDWR:
5116  if (oflags & O_TRUNC) {
5117  return MODE_BINARY("w+", "wb+");
5118  }
5119  return MODE_BINARY("r+", "rb+");
5120  }
5121 }
5122 
5123 /*
5124  * Convert external/internal encodings to enc/enc2
5125  * NULL => use default encoding
5126  * Qnil => no encoding specified (internal only)
5127  */
5128 static void
5130 {
5131  int default_ext = 0;
5132 
5133  if (ext == NULL) {
5135  default_ext = 1;
5136  }
5137  if (ext == rb_ascii8bit_encoding()) {
5138  /* If external is ASCII-8BIT, no transcoding */
5139  intern = NULL;
5140  }
5141  else if (intern == NULL) {
5142  intern = rb_default_internal_encoding();
5143  }
5144  if (intern == NULL || intern == (rb_encoding *)Qnil ||
5145  (!(fmode & FMODE_SETENC_BY_BOM) && (intern == ext))) {
5146  /* No internal encoding => use external + no transcoding */
5147  *enc = (default_ext && intern != ext) ? NULL : ext;
5148  *enc2 = NULL;
5149  }
5150  else {
5151  *enc = intern;
5152  *enc2 = ext;
5153  }
5154 }
5155 
5156 static void
5158 {
5159  rb_enc_warn(enc, "Unsupported encoding %s ignored", name);
5160 }
5161 
5162 static void
5163 parse_mode_enc(const char *estr, rb_encoding *estr_enc,
5164  rb_encoding **enc_p, rb_encoding **enc2_p, int *fmode_p)
5165 {
5166  const char *p;
5167  char encname[ENCODING_MAXNAMELEN+1];
5168  int idx, idx2;
5169  int fmode = fmode_p ? *fmode_p : 0;
5170  rb_encoding *ext_enc, *int_enc;
5171  long len;
5172 
5173  /* parse estr as "enc" or "enc2:enc" or "enc:-" */
5174 
5175  p = strrchr(estr, ':');
5176  len = p ? (p++ - estr) : (long)strlen(estr);
5177  if ((fmode & FMODE_SETENC_BY_BOM) || io_encname_bom_p(estr, len)) {
5178  estr += bom_prefix_len;
5179  len -= bom_prefix_len;
5180  if (!STRNCASECMP(estr, utf_prefix, utf_prefix_len)) {
5181  fmode |= FMODE_SETENC_BY_BOM;
5182  }
5183  else {
5184  rb_enc_warn(estr_enc, "BOM with non-UTF encoding %s is nonsense", estr);
5185  fmode &= ~FMODE_SETENC_BY_BOM;
5186  }
5187  }
5188  if (len == 0 || len > ENCODING_MAXNAMELEN) {
5189  idx = -1;
5190  }
5191  else {
5192  if (p) {
5193  memcpy(encname, estr, len);
5194  encname[len] = '\0';
5195  estr = encname;
5196  }
5197  idx = rb_enc_find_index(estr);
5198  }
5199  if (fmode_p) *fmode_p = fmode;
5200 
5201  if (idx >= 0)
5202  ext_enc = rb_enc_from_index(idx);
5203  else {
5204  if (idx != -2)
5205  unsupported_encoding(estr, estr_enc);
5206  ext_enc = NULL;
5207  }
5208 
5209  int_enc = NULL;
5210  if (p) {
5211  if (*p == '-' && *(p+1) == '\0') {
5212  /* Special case - "-" => no transcoding */
5213  int_enc = (rb_encoding *)Qnil;
5214  }
5215  else {
5216  idx2 = rb_enc_find_index(p);
5217  if (idx2 < 0)
5218  unsupported_encoding(p, estr_enc);
5219  else if (!(fmode & FMODE_SETENC_BY_BOM) && (idx2 == idx)) {
5220  int_enc = (rb_encoding *)Qnil;
5221  }
5222  else
5223  int_enc = rb_enc_from_index(idx2);
5224  }
5225  }
5226 
5227  rb_io_ext_int_to_encs(ext_enc, int_enc, enc_p, enc2_p, fmode);
5228 }
5229 
5230 int
5231 rb_io_extract_encoding_option(VALUE opt, rb_encoding **enc_p, rb_encoding **enc2_p, int *fmode_p)
5232 {
5233  VALUE encoding=Qnil, extenc=Qundef, intenc=Qundef, tmp;
5234  int extracted = 0;
5235  rb_encoding *extencoding = NULL;
5236  rb_encoding *intencoding = NULL;
5237 
5238  if (!NIL_P(opt)) {
5239  VALUE v;
5240  v = rb_hash_lookup2(opt, sym_encoding, Qnil);
5241  if (v != Qnil) encoding = v;
5242  v = rb_hash_lookup2(opt, sym_extenc, Qundef);
5243  if (v != Qnil) extenc = v;
5244  v = rb_hash_lookup2(opt, sym_intenc, Qundef);
5245  if (v != Qundef) intenc = v;
5246  }
5247  if ((extenc != Qundef || intenc != Qundef) && !NIL_P(encoding)) {
5248  if (!NIL_P(ruby_verbose)) {
5249  int idx = rb_to_encoding_index(encoding);
5250  if (idx >= 0) encoding = rb_enc_from_encoding(rb_enc_from_index(idx));
5251  rb_warn("Ignoring encoding parameter '%"PRIsVALUE"': %s_encoding is used",
5252  encoding, extenc == Qundef ? "internal" : "external");
5253  }
5254  encoding = Qnil;
5255  }
5256  if (extenc != Qundef && !NIL_P(extenc)) {
5257  extencoding = rb_to_encoding(extenc);
5258  }
5259  if (intenc != Qundef) {
5260  if (NIL_P(intenc)) {
5261  /* internal_encoding: nil => no transcoding */
5262  intencoding = (rb_encoding *)Qnil;
5263  }
5264  else if (!NIL_P(tmp = rb_check_string_type(intenc))) {
5265  char *p = StringValueCStr(tmp);
5266 
5267  if (*p == '-' && *(p+1) == '\0') {
5268  /* Special case - "-" => no transcoding */
5269  intencoding = (rb_encoding *)Qnil;
5270  }
5271  else {
5272  intencoding = rb_to_encoding(intenc);
5273  }
5274  }
5275  else {
5276  intencoding = rb_to_encoding(intenc);
5277  }
5278  if (extencoding == intencoding) {
5279  intencoding = (rb_encoding *)Qnil;
5280  }
5281  }
5282  if (!NIL_P(encoding)) {
5283  extracted = 1;
5284  if (!NIL_P(tmp = rb_check_string_type(encoding))) {
5286  enc_p, enc2_p, fmode_p);
5287  }
5288  else {
5289  rb_io_ext_int_to_encs(rb_to_encoding(encoding), NULL, enc_p, enc2_p, 0);
5290  }
5291  }
5292  else if (extenc != Qundef || intenc != Qundef) {
5293  extracted = 1;
5294  rb_io_ext_int_to_encs(extencoding, intencoding, enc_p, enc2_p, 0);
5295  }
5296  return extracted;
5297 }
5298 
5299 typedef struct rb_io_enc_t convconfig_t;
5300 
5301 static void
5302 validate_enc_binmode(int *fmode_p, int ecflags, rb_encoding *enc, rb_encoding *enc2)
5303 {
5304  int fmode = *fmode_p;
5305 
5306  if ((fmode & FMODE_READABLE) &&
5307  !enc2 &&
5308  !(fmode & FMODE_BINMODE) &&
5310  rb_raise(rb_eArgError, "ASCII incompatible encoding needs binmode");
5311 
5312  if (!(fmode & FMODE_BINMODE) &&
5314  fmode |= DEFAULT_TEXTMODE;
5315  *fmode_p = fmode;
5316  }
5317 #if !DEFAULT_TEXTMODE
5318  else if (!(ecflags & ECONV_NEWLINE_DECORATOR_MASK)) {
5319  fmode &= ~FMODE_TEXTMODE;
5320  *fmode_p = fmode;
5321  }
5322 #endif
5323 }
5324 
5325 static void
5327 {
5328  if (!NIL_P(opthash)) {
5329  VALUE v;
5330  v = rb_hash_aref(opthash, sym_textmode);
5331  if (!NIL_P(v)) {
5332  if (*fmode & FMODE_TEXTMODE)
5333  rb_raise(rb_eArgError, "textmode specified twice");
5334  if (*fmode & FMODE_BINMODE)
5335  rb_raise(rb_eArgError, "both textmode and binmode specified");
5336  if (RTEST(v))
5337  *fmode |= FMODE_TEXTMODE;
5338  }
5339  v = rb_hash_aref(opthash, sym_binmode);
5340  if (!NIL_P(v)) {
5341  if (*fmode & FMODE_BINMODE)
5342  rb_raise(rb_eArgError, "binmode specified twice");
5343  if (*fmode & FMODE_TEXTMODE)
5344  rb_raise(rb_eArgError, "both textmode and binmode specified");
5345  if (RTEST(v))
5346  *fmode |= FMODE_BINMODE;
5347  }
5348 
5349  if ((*fmode & FMODE_BINMODE) && (*fmode & FMODE_TEXTMODE))
5350  rb_raise(rb_eArgError, "both textmode and binmode specified");
5351  }
5352 }
5353 
5354 static void
5355 rb_io_extract_modeenc(VALUE *vmode_p, VALUE *vperm_p, VALUE opthash,
5356  int *oflags_p, int *fmode_p, convconfig_t *convconfig_p)
5357 {
5358  VALUE vmode;
5359  int oflags, fmode;
5360  rb_encoding *enc, *enc2;
5361  int ecflags;
5362  VALUE ecopts;
5363  int has_enc = 0, has_vmode = 0;
5364  VALUE intmode;
5365 
5366  vmode = *vmode_p;
5367 
5368  /* Set to defaults */
5369  rb_io_ext_int_to_encs(NULL, NULL, &enc, &enc2, 0);
5370 
5371  vmode_handle:
5372  if (NIL_P(vmode)) {
5373  fmode = FMODE_READABLE;
5374  oflags = O_RDONLY;
5375  }
5376  else if (!NIL_P(intmode = rb_check_to_integer(vmode, "to_int"))) {
5377  vmode = intmode;
5378  oflags = NUM2INT(intmode);
5379  fmode = rb_io_oflags_fmode(oflags);
5380  }
5381  else {
5382  const char *p;
5383 
5384  SafeStringValue(vmode);
5385  p = StringValueCStr(vmode);
5386  fmode = rb_io_modestr_fmode(p);
5387  oflags = rb_io_fmode_oflags(fmode);
5388  p = strchr(p, ':');
5389  if (p) {
5390  has_enc = 1;
5391  parse_mode_enc(p+1, rb_enc_get(vmode), &enc, &enc2, &fmode);
5392  }
5393  else {
5394  rb_encoding *e;
5395 
5396  e = (fmode & FMODE_BINMODE) ? rb_ascii8bit_encoding() : NULL;
5397  rb_io_ext_int_to_encs(e, NULL, &enc, &enc2, fmode);
5398  }
5399  }
5400 
5401  if (NIL_P(opthash)) {
5402  ecflags = (fmode & FMODE_READABLE) ?
5405 #ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE
5406  ecflags |= (fmode & FMODE_WRITABLE) ?
5407  MODE_BTMODE(TEXTMODE_NEWLINE_DECORATOR_ON_WRITE,
5408  0, TEXTMODE_NEWLINE_DECORATOR_ON_WRITE) : 0;
5409 #endif
5411  ecopts = Qnil;
5412  }
5413  else {
5414  VALUE v;
5415  if (!has_vmode) {
5416  v = rb_hash_aref(opthash, sym_mode);
5417  if (!NIL_P(v)) {
5418  if (!NIL_P(vmode)) {
5419  rb_raise(rb_eArgError, "mode specified twice");
5420  }
5421  has_vmode = 1;
5422  vmode = v;
5423  goto vmode_handle;
5424  }
5425  }
5426  v = rb_hash_aref(opthash, sym_flags);
5427  if (!NIL_P(v)) {
5428  v = rb_to_int(v);
5429  oflags |= NUM2INT(v);
5430  vmode = INT2NUM(oflags);
5431  fmode = rb_io_oflags_fmode(oflags);
5432  }
5433  extract_binmode(opthash, &fmode);
5434  if (fmode & FMODE_BINMODE) {
5435 #ifdef O_BINARY
5436  oflags |= O_BINARY;
5437 #endif
5438  if (!has_enc)
5439  rb_io_ext_int_to_encs(rb_ascii8bit_encoding(), NULL, &enc, &enc2, fmode);
5440  }
5441 #if DEFAULT_TEXTMODE
5442  else if (NIL_P(vmode)) {
5443  fmode |= DEFAULT_TEXTMODE;
5444  }
5445 #endif
5446  v = rb_hash_aref(opthash, sym_perm);
5447  if (!NIL_P(v)) {
5448  if (vperm_p) {
5449  if (!NIL_P(*vperm_p)) {
5450  rb_raise(rb_eArgError, "perm specified twice");
5451  }
5452  *vperm_p = v;
5453  }
5454  else {
5455  /* perm no use, just ignore */
5456  }
5457  }
5458  ecflags = (fmode & FMODE_READABLE) ?
5461 #ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE
5462  ecflags |= (fmode & FMODE_WRITABLE) ?
5463  MODE_BTMODE(TEXTMODE_NEWLINE_DECORATOR_ON_WRITE,
5464  0, TEXTMODE_NEWLINE_DECORATOR_ON_WRITE) : 0;
5465 #endif
5466 
5467  if (rb_io_extract_encoding_option(opthash, &enc, &enc2, &fmode)) {
5468  if (has_enc) {
5469  rb_raise(rb_eArgError, "encoding specified twice");
5470  }
5471  }
5473  ecflags = rb_econv_prepare_options(opthash, &ecopts, ecflags);
5474  }
5475 
5476  validate_enc_binmode(&fmode, ecflags, enc, enc2);
5477 
5478  *vmode_p = vmode;
5479 
5480  *oflags_p = oflags;
5481  *fmode_p = fmode;
5482  convconfig_p->enc = enc;
5483  convconfig_p->enc2 = enc2;
5484  convconfig_p->ecflags = ecflags;
5485  convconfig_p->ecopts = ecopts;
5486 }
5487 
5490  int oflags;
5492 };
5493 
5494 static void *
5495 sysopen_func(void *ptr)
5496 {
5497  const struct sysopen_struct *data = ptr;
5498  const char *fname = RSTRING_PTR(data->fname);
5499  return (void *)(VALUE)rb_cloexec_open(fname, data->oflags, data->perm);
5500 }
5501 
5502 static inline int
5504 {
5505  int fd;
5507  if (0 <= fd)
5508  rb_update_max_fd(fd);
5509  return fd;
5510 }
5511 
5512 static int
5514 {
5515  int fd;
5516  struct sysopen_struct data;
5517 
5518  data.fname = rb_str_encode_ospath(fname);
5519  StringValueCStr(data.fname);
5520  data.oflags = oflags;
5521  data.perm = perm;
5522 
5523  fd = rb_sysopen_internal(&data);
5524  if (fd < 0) {
5525  int e = errno;
5526  if (rb_gc_for_fd(e)) {
5527  fd = rb_sysopen_internal(&data);
5528  }
5529  if (fd < 0) {
5530  rb_syserr_fail_path(e, fname);
5531  }
5532  }
5533  return fd;
5534 }
5535 
5536 FILE *
5537 rb_fdopen(int fd, const char *modestr)
5538 {
5539  FILE *file;
5540 
5541 #if defined(__sun)
5542  errno = 0;
5543 #endif
5544  file = fdopen(fd, modestr);
5545  if (!file) {
5546  int e = errno;
5547 #if defined(__sun)
5548  if (e == 0) {
5549  rb_gc();
5550  errno = 0;
5551  file = fdopen(fd, modestr);
5552  }
5553  else
5554 #endif
5555  if (rb_gc_for_fd(e)) {
5556  file = fdopen(fd, modestr);
5557  }
5558  if (!file) {
5559 #ifdef _WIN32
5560  if (e == 0) e = EINVAL;
5561 #elif defined(__sun)
5562  if (e == 0) e = EMFILE;
5563 #endif
5564  rb_syserr_fail(e, 0);
5565  }
5566  }
5567 
5568  /* xxx: should be _IONBF? A buffer in FILE may have trouble. */
5569 #ifdef USE_SETVBUF
5570  if (setvbuf(file, NULL, _IOFBF, 0) != 0)
5571  rb_warn("setvbuf() can't be honoured (fd=%d)", fd);
5572 #endif
5573  return file;
5574 }
5575 
5576 static int
5578 {
5579  int t = isatty(fptr->fd);
5580  if (t)
5581  fptr->mode |= FMODE_TTY|FMODE_DUPLEX;
5582  return t;
5583 }
5584 
5586 static void io_encoding_set(rb_io_t *, VALUE, VALUE, VALUE);
5587 
5588 static int
5590 {
5591  VALUE b1, b2, b3, b4;
5592 
5593  if (NIL_P(b1 = rb_io_getbyte(io))) return 0;
5594  switch (b1) {
5595  case INT2FIX(0xEF):
5596  if (NIL_P(b2 = rb_io_getbyte(io))) break;
5597  if (b2 == INT2FIX(0xBB) && !NIL_P(b3 = rb_io_getbyte(io))) {
5598  if (b3 == INT2FIX(0xBF)) {
5599  return rb_utf8_encindex();
5600  }
5601  rb_io_ungetbyte(io, b3);
5602  }
5603  rb_io_ungetbyte(io, b2);
5604  break;
5605 
5606  case INT2FIX(0xFE):
5607  if (NIL_P(b2 = rb_io_getbyte(io))) break;
5608  if (b2 == INT2FIX(0xFF)) {
5609  return ENCINDEX_UTF_16BE;
5610  }
5611  rb_io_ungetbyte(io, b2);
5612  break;
5613 
5614  case INT2FIX(0xFF):
5615  if (NIL_P(b2 = rb_io_getbyte(io))) break;
5616  if (b2 == INT2FIX(0xFE)) {
5617  b3 = rb_io_getbyte(io);
5618  if (b3 == INT2FIX(0) && !NIL_P(b4 = rb_io_getbyte(io))) {
5619  if (b4 == INT2FIX(0)) {
5620  return ENCINDEX_UTF_32LE;
5621  }
5622  rb_io_ungetbyte(io, b4);
5623  rb_io_ungetbyte(io, b3);
5624  }
5625  else {
5626  rb_io_ungetbyte(io, b3);
5627  return ENCINDEX_UTF_16LE;
5628  }
5629  }
5630  rb_io_ungetbyte(io, b2);
5631  break;
5632 
5633  case INT2FIX(0):
5634  if (NIL_P(b2 = rb_io_getbyte(io))) break;
5635  if (b2 == INT2FIX(0) && !NIL_P(b3 = rb_io_getbyte(io))) {
5636  if (b3 == INT2FIX(0xFE) && !NIL_P(b4 = rb_io_getbyte(io))) {
5637  if (b4 == INT2FIX(0xFF)) {
5638  return ENCINDEX_UTF_32BE;
5639  }
5640  rb_io_ungetbyte(io, b4);
5641  }
5642  rb_io_ungetbyte(io, b3);
5643  }
5644  rb_io_ungetbyte(io, b2);
5645  break;
5646  }
5647  rb_io_ungetbyte(io, b1);
5648  return 0;
5649 }
5650 
5651 static void
5653 {
5654  int idx = io_strip_bom(io);
5655  rb_io_t *fptr;
5656 
5657  GetOpenFile(io, fptr);
5658  if (idx) {
5661  }
5662  else {
5663  fptr->encs.enc2 = NULL;
5664  }
5665 }
5666 
5667 static VALUE
5669  const convconfig_t *convconfig, mode_t perm)
5670 {
5671  rb_io_t *fptr;
5672  convconfig_t cc;
5673  if (!convconfig) {
5674  /* Set to default encodings */
5675  rb_io_ext_int_to_encs(NULL, NULL, &cc.enc, &cc.enc2, fmode);
5676  cc.ecflags = 0;
5677  cc.ecopts = Qnil;
5678  convconfig = &cc;
5679  }
5680  validate_enc_binmode(&fmode, convconfig->ecflags,
5681  convconfig->enc, convconfig->enc2);
5682 
5683  MakeOpenFile(io, fptr);
5684  fptr->mode = fmode;
5685  fptr->encs = *convconfig;
5686  fptr->pathv = rb_str_new_frozen(filename);
5687  fptr->fd = rb_sysopen(fptr->pathv, oflags, perm);
5688  io_check_tty(fptr);
5690 
5691  return io;
5692 }
5693 
5694 static VALUE
5695 rb_file_open_internal(VALUE io, VALUE filename, const char *modestr)
5696 {
5697  int fmode = rb_io_modestr_fmode(modestr);
5698  const char *p = strchr(modestr, ':');
5699  convconfig_t convconfig;
5700 
5701  if (p) {
5703  &convconfig.enc, &convconfig.enc2, &fmode);
5704  }
5705  else {
5706  rb_encoding *e;
5707  /* Set to default encodings */
5708 
5709  e = (fmode & FMODE_BINMODE) ? rb_ascii8bit_encoding() : NULL;
5710  rb_io_ext_int_to_encs(e, NULL, &convconfig.enc, &convconfig.enc2, fmode);
5711  convconfig.ecflags = 0;
5712  convconfig.ecopts = Qnil;
5713  }
5714 
5715  return rb_file_open_generic(io, filename,
5716  rb_io_fmode_oflags(fmode),
5717  fmode,
5718  &convconfig,
5719  0666);
5720 }
5721 
5722 VALUE
5723 rb_file_open_str(VALUE fname, const char *modestr)
5724 {
5725  FilePathValue(fname);
5726  return rb_file_open_internal(io_alloc(rb_cFile), fname, modestr);
5727 }
5728 
5729 VALUE
5730 rb_file_open(const char *fname, const char *modestr)
5731 {
5732  return rb_file_open_internal(io_alloc(rb_cFile), rb_str_new_cstr(fname), modestr);
5733 }
5734 
5735 #if defined(__CYGWIN__) || !defined(HAVE_WORKING_FORK)
5736 static struct pipe_list {
5738  struct pipe_list *next;
5739 } *pipe_list;
5740 
5741 static void
5743 {
5744  struct pipe_list *list;
5745 
5746  list = ALLOC(struct pipe_list);
5747  list->fptr = fptr;
5748  list->next = pipe_list;
5749  pipe_list = list;
5750 }
5751 
5752 static void
5754 {
5755  struct pipe_list *list = pipe_list;
5756  struct pipe_list *tmp;
5757 
5758  if (list->fptr == fptr) {
5759  pipe_list = list->next;
5760  free(list);
5761  return;
5762  }
5763 
5764  while (list->next) {
5765  if (list->next->fptr == fptr) {
5766  tmp = list->next;
5767  list->next = list->next->next;
5768  free(tmp);
5769  return;
5770  }
5771  list = list->next;
5772  }
5773 }
5774 
5775 #if defined (_WIN32) || defined(__CYGWIN__)
5776 static void
5777 pipe_atexit(void)
5778 {
5779  struct pipe_list *list = pipe_list;
5780  struct pipe_list *tmp;
5781 
5782  while (list) {
5783  tmp = list->next;
5784  rb_io_fptr_finalize(list->fptr);
5785  list = tmp;
5786  }
5787 }
5788 #endif
5789 
5790 static void
5791 pipe_finalize(rb_io_t *fptr, int noraise)
5792 {
5793 #if !defined(HAVE_WORKING_FORK) && !defined(_WIN32)
5794  int status = 0;
5795  if (fptr->stdio_file) {
5796  status = pclose(fptr->stdio_file);
5797  }
5798  fptr->fd = -1;
5799  fptr->stdio_file = 0;
5800  rb_last_status_set(status, fptr->pid);
5801 #else
5802  fptr_finalize(fptr, noraise);
5803 #endif
5804  pipe_del_fptr(fptr);
5805 }
5806 #endif
5807 
5808 void
5810 {
5812  fptr->mode |= FMODE_SYNC;
5813 }
5814 
5815 void
5817 {
5818  rb_io_synchronized(fptr);
5819 }
5820 
5821 int
5822 rb_pipe(int *pipes)
5823 {
5824  int ret;
5825  ret = rb_cloexec_pipe(pipes);
5826  if (ret == -1) {
5827  if (rb_gc_for_fd(errno)) {
5828  ret = rb_cloexec_pipe(pipes);
5829  }
5830  }
5831  if (ret == 0) {
5832  rb_update_max_fd(pipes[0]);
5833  rb_update_max_fd(pipes[1]);
5834  }
5835  return ret;
5836 }
5837 
5838 #ifdef _WIN32
5839 #define HAVE_SPAWNV 1
5840 #define spawnv(mode, cmd, args) rb_w32_uaspawn((mode), (cmd), (args))
5841 #define spawn(mode, cmd) rb_w32_uspawn((mode), (cmd), 0)
5842 #endif
5843 
5844 #if defined(HAVE_WORKING_FORK) || defined(HAVE_SPAWNV)
5845 struct popen_arg {
5846  VALUE execarg_obj;
5847  struct rb_execarg *eargp;
5848  int modef;
5849  int pair[2];
5850  int write_pair[2];
5851 };
5852 #endif
5853 
5854 #ifdef HAVE_WORKING_FORK
5855 static void
5856 popen_redirect(struct popen_arg *p)
5857 {
5858  if ((p->modef & FMODE_READABLE) && (p->modef & FMODE_WRITABLE)) {
5859  close(p->write_pair[1]);
5860  if (p->write_pair[0] != 0) {
5861  dup2(p->write_pair[0], 0);
5862  close(p->write_pair[0]);
5863  }
5864  close(p->pair[0]);
5865  if (p->pair[1] != 1) {
5866  dup2(p->pair[1], 1);
5867  close(p->pair[1]);
5868  }
5869  }
5870  else if (p->modef & FMODE_READABLE) {
5871  close(p->pair[0]);
5872  if (p->pair[1] != 1) {
5873  dup2(p->pair[1], 1);
5874  close(p->pair[1]);
5875  }
5876  }
5877  else {
5878  close(p->pair[1]);
5879  if (p->pair[0] != 0) {
5880  dup2(p->pair[0], 0);
5881  close(p->pair[0]);
5882  }
5883  }
5884 }
5885 
5886 #if defined(__linux__)
5887 /* Linux /proc/self/status contains a line: "FDSize:\t<nnn>\n"
5888  * Since /proc may not be available, linux_get_maxfd is just a hint.
5889  * This function, linux_get_maxfd, must be async-signal-safe.
5890  * I.e. opendir() is not usable.
5891  *
5892  * Note that memchr() and memcmp is *not* async-signal-safe in POSIX.
5893  * However they are easy to re-implement in async-signal-safe manner.
5894  * (Also note that there is missing/memcmp.c.)
5895  */
5896 static int
5897 linux_get_maxfd(void)
5898 {
5899  int fd;
5900  char buf[4096], *p, *np, *e;
5901  ssize_t ss;
5902  fd = rb_cloexec_open("/proc/self/status", O_RDONLY|O_NOCTTY, 0);
5903  if (fd == -1) return -1;
5904  ss = read(fd, buf, sizeof(buf));
5905  if (ss == -1) goto err;
5906  p = buf;
5907  e = buf + ss;
5908  while ((int)sizeof("FDSize:\t0\n")-1 <= e-p &&
5909  (np = memchr(p, '\n', e-p)) != NULL) {
5910  if (memcmp(p, "FDSize:", sizeof("FDSize:")-1) == 0) {
5911  int fdsize;
5912  p += sizeof("FDSize:")-1;
5913  *np = '\0';
5914  fdsize = (int)ruby_strtoul(p, (char **)NULL, 10);
5915  close(fd);
5916  return fdsize;
5917  }
5918  p = np+1;
5919  }
5920  /* fall through */
5921 
5922  err:
5923  close(fd);
5924  return -1;
5925 }
5926 #endif
5927 
5928 /* This function should be async-signal-safe. */
5929 void
5930 rb_close_before_exec(int lowfd, int maxhint, VALUE noclose_fds)
5931 {
5932 #if defined(HAVE_FCNTL) && defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
5933  int fd, ret;
5934  int max = (int)max_file_descriptor;
5935 # ifdef F_MAXFD
5936  /* F_MAXFD is available since NetBSD 2.0. */
5937  ret = fcntl(0, F_MAXFD); /* async-signal-safe */
5938  if (ret != -1)
5939  maxhint = max = ret;
5940 # elif defined(__linux__)
5941  ret = linux_get_maxfd();
5942  if (maxhint < ret)
5943  maxhint = ret;
5944  /* maxhint = max = ret; if (ret == -1) abort(); // test */
5945 # endif
5946  if (max < maxhint)
5947  max = maxhint;
5948  for (fd = lowfd; fd <= max; fd++) {
5949  if (!NIL_P(noclose_fds) &&
5950  RTEST(rb_hash_lookup(noclose_fds, INT2FIX(fd)))) /* async-signal-safe */
5951  continue;
5952  ret = fcntl(fd, F_GETFD); /* async-signal-safe */
5953  if (ret != -1 && !(ret & FD_CLOEXEC)) {
5954  fcntl(fd, F_SETFD, ret|FD_CLOEXEC); /* async-signal-safe */
5955  }
5956 # define CONTIGUOUS_CLOSED_FDS 20
5957  if (ret != -1) {
5958  if (max < fd + CONTIGUOUS_CLOSED_FDS)
5959  max = fd + CONTIGUOUS_CLOSED_FDS;
5960  }
5961  }
5962 #endif
5963 }
5964 
5965 static int
5966 popen_exec(void *pp, char *errmsg, size_t errmsg_len)
5967 {
5968  struct popen_arg *p = (struct popen_arg*)pp;
5969 
5970  return rb_exec_async_signal_safe(p->eargp, errmsg, errmsg_len);
5971 }
5972 #endif
5973 
5974 #if defined(HAVE_WORKING_FORK) || defined(HAVE_SPAWNV)
5975 static VALUE
5976 rb_execarg_fixup_v(VALUE execarg_obj)
5977 {
5978  rb_execarg_parent_start(execarg_obj);
5979  return Qnil;
5980 }
5981 #else
5982 char *rb_execarg_commandline(const struct rb_execarg *eargp, VALUE *prog);
5983 #endif
5984 
5985 static VALUE
5986 pipe_open(VALUE execarg_obj, const char *modestr, int fmode,
5987  const convconfig_t *convconfig)
5988 {
5989  struct rb_execarg *eargp = NIL_P(execarg_obj) ? NULL : rb_execarg_get(execarg_obj);
5990  VALUE prog = eargp ? (eargp->use_shell ? eargp->invoke.sh.shell_script : eargp->invoke.cmd.command_name) : Qfalse ;
5991  rb_pid_t pid = 0;
5992  rb_io_t *fptr;
5993  VALUE port;
5994  rb_io_t *write_fptr;
5995  VALUE write_port;
5996 #if defined(HAVE_WORKING_FORK)
5997  int status;
5998  char errmsg[80] = { '\0' };
5999 #endif
6000 #if defined(HAVE_WORKING_FORK) || defined(HAVE_SPAWNV)
6001  int state;
6002  struct popen_arg arg;
6003 #endif
6004  int e = 0;
6005 #if defined(HAVE_SPAWNV)
6006 # if defined(HAVE_SPAWNVE)
6007 # define DO_SPAWN(cmd, args, envp) ((args) ? \
6008  spawnve(P_NOWAIT, (cmd), (args), (envp)) : \
6009  spawne(P_NOWAIT, (cmd), (envp)))
6010 # else
6011 # define DO_SPAWN(cmd, args, envp) ((args) ? \
6012  spawnv(P_NOWAIT, (cmd), (args)) : \
6013  spawn(P_NOWAIT, (cmd)))
6014 # endif
6015 # if !defined(HAVE_WORKING_FORK)
6016  char **args = NULL;
6017 # if defined(HAVE_SPAWNVE)
6018  char **envp = NULL;
6019 # endif
6020 # endif
6021 #endif
6022 #if !defined(HAVE_WORKING_FORK)
6023  struct rb_execarg sarg, *sargp = &sarg;
6024 #endif
6025  FILE *fp = 0;
6026  int fd = -1;
6027  int write_fd = -1;
6028 #if !defined(HAVE_WORKING_FORK)
6029  const char *cmd = 0;
6030 
6031  if (prog)
6032  cmd = StringValueCStr(prog);
6033 #endif
6034 
6035 #if defined(HAVE_WORKING_FORK) || defined(HAVE_SPAWNV)
6036  arg.execarg_obj = execarg_obj;
6037  arg.eargp = eargp;
6038  arg.modef = fmode;
6039  arg.pair[0] = arg.pair[1] = -1;
6040  arg.write_pair[0] = arg.write_pair[1] = -1;
6041 # if !defined(HAVE_WORKING_FORK)
6042  if (eargp && !eargp->use_shell) {
6043  args = ARGVSTR2ARGV(eargp->invoke.cmd.argv_str);
6044  }
6045 # endif
6046  switch (fmode & (FMODE_READABLE|FMODE_WRITABLE)) {
6048  if (rb_pipe(arg.write_pair) < 0)
6049  rb_sys_fail_str(prog);
6050  if (rb_pipe(arg.pair) < 0) {
6051  e = errno;
6052  close(arg.write_pair[0]);
6053  close(arg.write_pair[1]);
6054  rb_syserr_fail_str(e, prog);
6055  }
6056  if (eargp) {
6057  rb_execarg_addopt(execarg_obj, INT2FIX(0), INT2FIX(arg.write_pair[0]));
6058  rb_execarg_addopt(execarg_obj, INT2FIX(1), INT2FIX(arg.pair[1]));
6059  }
6060  break;
6061  case FMODE_READABLE:
6062  if (rb_pipe(arg.pair) < 0)
6063  rb_sys_fail_str(prog);
6064  if (eargp)
6065  rb_execarg_addopt(execarg_obj, INT2FIX(1), INT2FIX(arg.pair[1]));
6066  break;
6067  case FMODE_WRITABLE:
6068  if (rb_pipe(arg.pair) < 0)
6069  rb_sys_fail_str(prog);
6070  if (eargp)
6071  rb_execarg_addopt(execarg_obj, INT2FIX(0), INT2FIX(arg.pair[0]));
6072  break;
6073  default:
6074  rb_sys_fail_str(prog);
6075  }
6076  if (!NIL_P(execarg_obj)) {
6077  rb_protect(rb_execarg_fixup_v, execarg_obj, &state);
6078  if (state) {
6079  if (0 <= arg.write_pair[0]) close(arg.write_pair[0]);
6080  if (0 <= arg.write_pair[1]) close(arg.write_pair[1]);
6081  if (0 <= arg.pair[0]) close(arg.pair[0]);
6082  if (0 <= arg.pair[1]) close(arg.pair[1]);
6083  rb_execarg_parent_end(execarg_obj);
6084  rb_jump_tag(state);
6085  }
6086 
6087 # if defined(HAVE_WORKING_FORK)
6088  pid = rb_fork_async_signal_safe(&status, popen_exec, &arg, arg.eargp->redirect_fds, errmsg, sizeof(errmsg));
6089 # else
6090  rb_execarg_run_options(eargp, sargp, NULL, 0);
6091 # if defined(HAVE_SPAWNVE)
6092  if (eargp->envp_str) envp = (char **)RSTRING_PTR(eargp->envp_str);
6093 # endif
6094  while ((pid = DO_SPAWN(cmd, args, envp)) == -1) {
6095  /* exec failed */
6096  switch (e = errno) {
6097  case EAGAIN:
6098 # if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
6099  case EWOULDBLOCK:
6100 # endif
6101  rb_thread_sleep(1);
6102  continue;
6103  }
6104  break;
6105  }
6106  if (eargp)
6107  rb_execarg_run_options(sargp, NULL, NULL, 0);
6108 # endif
6109  rb_execarg_parent_end(execarg_obj);
6110  }
6111  else {
6112 # if defined(HAVE_WORKING_FORK)
6113  pid = rb_fork_ruby(&status);
6114  if (pid == 0) { /* child */
6115  rb_thread_atfork();
6116  popen_redirect(&arg);
6119  return Qnil;
6120  }
6121 # else
6122  rb_notimplement();
6123 # endif
6124  }
6125 
6126  /* parent */
6127  if (pid == -1) {
6128 # if defined(HAVE_WORKING_FORK)
6129  e = errno;
6130 # endif
6131  close(arg.pair[0]);
6132  close(arg.pair[1]);
6134  close(arg.write_pair[0]);
6135  close(arg.write_pair[1]);
6136  }
6137 # if defined(HAVE_WORKING_FORK)
6138  if (errmsg[0])
6139  rb_syserr_fail(e, errmsg);
6140 # endif
6141  rb_syserr_fail_str(e, prog);
6142  }
6143  if ((fmode & FMODE_READABLE) && (fmode & FMODE_WRITABLE)) {
6144  close(arg.pair[1]);
6145  fd = arg.pair[0];
6146  close(arg.write_pair[0]);
6147  write_fd = arg.write_pair[1];
6148  }
6149  else if (fmode & FMODE_READABLE) {
6150  close(arg.pair[1]);
6151  fd = arg.pair[0];
6152  }
6153  else {
6154  close(arg.pair[0]);
6155  fd = arg.pair[1];
6156  }
6157 #else
6158  cmd = rb_execarg_commandline(eargp, &prog);
6159  if (!NIL_P(execarg_obj)) {
6160  rb_execarg_parent_start(execarg_obj);
6161  rb_execarg_run_options(eargp, sargp, NULL, 0);
6162  }
6163  fp = popen(cmd, modestr);
6164  e = errno;
6165  if (eargp) {
6166  rb_execarg_parent_end(execarg_obj);
6167  rb_execarg_run_options(sargp, NULL, NULL, 0);
6168  }
6169  if (!fp) rb_syserr_fail_path(e, prog);
6170  fd = fileno(fp);
6171 #endif
6172 
6173  port = io_alloc(rb_cIO);
6174  MakeOpenFile(port, fptr);
6175  fptr->fd = fd;
6176  fptr->stdio_file = fp;
6177  fptr->mode = fmode | FMODE_SYNC|FMODE_DUPLEX;
6178  if (convconfig) {
6179  fptr->encs = *convconfig;
6180 #if defined(RUBY_TEST_CRLF_ENVIRONMENT) || defined(_WIN32)
6183  }
6184 #endif
6185  }
6186  else {
6187  if (NEED_NEWLINE_DECORATOR_ON_READ(fptr)) {
6189  }
6190 #ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE
6191  if (NEED_NEWLINE_DECORATOR_ON_WRITE(fptr)) {
6192  fptr->encs.ecflags |= TEXTMODE_NEWLINE_DECORATOR_ON_WRITE;
6193  }
6194 #endif
6195  }
6196  fptr->pid = pid;
6197 
6198  if (0 <= write_fd) {
6199  write_port = io_alloc(rb_cIO);
6200  MakeOpenFile(write_port, write_fptr);
6201  write_fptr->fd = write_fd;
6202  write_fptr->mode = (fmode & ~FMODE_READABLE)| FMODE_SYNC|FMODE_DUPLEX;
6203  fptr->mode &= ~FMODE_WRITABLE;
6204  fptr->tied_io_for_writing = write_port;
6205  rb_ivar_set(port, rb_intern("@tied_io_for_writing"), write_port);
6206  }
6207 
6208 #if defined (__CYGWIN__) || !defined(HAVE_WORKING_FORK)
6209  fptr->finalize = pipe_finalize;
6210  pipe_add_fptr(fptr);
6211 #endif
6212  return port;
6213 }
6214 
6215 static int
6217 {
6218  if (RSTRING_LEN(prog) == 1 && RSTRING_PTR(prog)[0] == '-') {
6219 #if !defined(HAVE_WORKING_FORK)
6221  "fork() function is unimplemented on this machine");
6222 #else
6223  return TRUE;
6224 #endif
6225  }
6226  return FALSE;
6227 }
6228 
6229 static VALUE
6230 pipe_open_s(VALUE prog, const char *modestr, int fmode,
6231  const convconfig_t *convconfig)
6232 {
6233  int argc = 1;
6234  VALUE *argv = &prog;
6235  VALUE execarg_obj = Qnil;
6236 
6237  if (!is_popen_fork(prog))
6238  execarg_obj = rb_execarg_new(argc, argv, TRUE);
6239  return pipe_open(execarg_obj, modestr, fmode, convconfig);
6240 }
6241 
6242 static VALUE
6244 {
6245  rb_io_t *fptr = io_close_fptr(io);
6246  if (fptr) {
6248  }
6249  return Qnil;
6250 }
6251 
6252 /*
6253  * call-seq:
6254  * IO.popen([env,] cmd, mode="r" [, opt]) -> io
6255  * IO.popen([env,] cmd, mode="r" [, opt]) {|io| block } -> obj
6256  *
6257  * Runs the specified command as a subprocess; the subprocess's
6258  * standard input and output will be connected to the returned
6259  * <code>IO</code> object.
6260  *
6261  * The PID of the started process can be obtained by IO#pid method.
6262  *
6263  * _cmd_ is a string or an array as follows.
6264  *
6265  * cmd:
6266  * "-" : fork
6267  * commandline : command line string which is passed to a shell
6268  * [env, cmdname, arg1, ..., opts] : command name and zero or more arguments (no shell)
6269  * [env, [cmdname, argv0], arg1, ..., opts] : command name, argv[0] and zero or more arguments (no shell)
6270  * (env and opts are optional.)
6271  *
6272  * If _cmd_ is a +String+ ``<code>-</code>'',
6273  * then a new instance of Ruby is started as the subprocess.
6274  *
6275  * If <i>cmd</i> is an +Array+ of +String+,
6276  * then it will be used as the subprocess's +argv+ bypassing a shell.
6277  * The array can contains a hash at first for environments and
6278  * a hash at last for options similar to <code>spawn</code>.
6279  *
6280  * The default mode for the new file object is ``r'',
6281  * but <i>mode</i> may be set to any of the modes listed in the description for class IO.
6282  * The last argument <i>opt</i> qualifies <i>mode</i>.
6283  *
6284  * # set IO encoding
6285  * IO.popen("nkf -e filename", :external_encoding=>"EUC-JP") {|nkf_io|
6286  * euc_jp_string = nkf_io.read
6287  * }
6288  *
6289  * # merge standard output and standard error using
6290  * # spawn option. See the document of Kernel.spawn.
6291  * IO.popen(["ls", "/", :err=>[:child, :out]]) {|ls_io|
6292  * ls_result_with_error = ls_io.read
6293  * }
6294  *
6295  * # spawn options can be mixed with IO options
6296  * IO.popen(["ls", "/"], :err=>[:child, :out]) {|ls_io|
6297  * ls_result_with_error = ls_io.read
6298  * }
6299  *
6300  * Raises exceptions which <code>IO.pipe</code> and
6301  * <code>Kernel.spawn</code> raise.
6302  *
6303  * If a block is given, Ruby will run the command as a child connected
6304  * to Ruby with a pipe. Ruby's end of the pipe will be passed as a
6305  * parameter to the block.
6306  * At the end of block, Ruby closes the pipe and sets <code>$?</code>.
6307  * In this case <code>IO.popen</code> returns
6308  * the value of the block.
6309  *
6310  * If a block is given with a _cmd_ of ``<code>-</code>'',
6311  * the block will be run in two separate processes: once in the parent,
6312  * and once in a child. The parent process will be passed the pipe
6313  * object as a parameter to the block, the child version of the block
6314  * will be passed +nil+, and the child's standard in and
6315  * standard out will be connected to the parent through the pipe. Not
6316  * available on all platforms.
6317  *
6318  * f = IO.popen("uname")
6319  * p f.readlines
6320  * f.close
6321  * puts "Parent is #{Process.pid}"
6322  * IO.popen("date") {|f| puts f.gets }
6323  * IO.popen("-") {|f| $stderr.puts "#{Process.pid} is here, f is #{f.inspect}"}
6324  * p $?
6325  * IO.popen(%w"sed -e s|^|<foo>| -e s&$&;zot;&", "r+") {|f|
6326  * f.puts "bar"; f.close_write; puts f.gets
6327  * }
6328  *
6329  * <em>produces:</em>
6330  *
6331  * ["Linux\n"]
6332  * Parent is 21346
6333  * Thu Jan 15 22:41:19 JST 2009
6334  * 21346 is here, f is #<IO:fd 3>
6335  * 21352 is here, f is nil
6336  * #<Process::Status: pid 21352 exit 0>
6337  * <foo>bar;zot;
6338  */
6339 
6340 static VALUE
6342 {
6343  const char *modestr;
6344  VALUE pname, pmode = Qnil, port, tmp, opt = Qnil, env = Qnil, execarg_obj = Qnil;
6345  int oflags, fmode;
6346  convconfig_t convconfig;
6347 
6348  if (argc > 1 && !NIL_P(opt = rb_check_hash_type(argv[argc-1]))) --argc;
6349  if (argc > 1 && !NIL_P(env = rb_check_hash_type(argv[0]))) --argc, ++argv;
6350  switch (argc) {
6351  case 2:
6352  pmode = argv[1];
6353  case 1:
6354  pname = argv[0];
6355  break;
6356  default:
6357  {
6358  int ex = !NIL_P(opt);
6359  rb_error_arity(argc + ex, 1 + ex, 2 + ex);
6360  }
6361  }
6362 
6363  tmp = rb_check_array_type(pname);
6364  if (!NIL_P(tmp)) {
6365  long len = RARRAY_LEN(tmp);
6366 #if SIZEOF_LONG > SIZEOF_INT
6367  if (len > INT_MAX) {
6368  rb_raise(rb_eArgError, "too many arguments");
6369  }
6370 #endif
6371  execarg_obj = rb_execarg_new((int)len, RARRAY_CONST_PTR(tmp), FALSE);
6372  RB_GC_GUARD(tmp);
6373  }
6374  else {
6375  SafeStringValue(pname);
6376  execarg_obj = Qnil;
6377  if (!is_popen_fork(pname))
6378  execarg_obj = rb_execarg_new(1, &pname, TRUE);
6379  }
6380  if (!NIL_P(execarg_obj)) {
6381  if (!NIL_P(opt))
6382  opt = rb_execarg_extract_options(execarg_obj, opt);
6383  if (!NIL_P(env))
6384  rb_execarg_setenv(execarg_obj, env);
6385  }
6386  rb_io_extract_modeenc(&pmode, 0, opt, &oflags, &fmode, &convconfig);
6387  modestr = rb_io_oflags_modestr(oflags);
6388 
6389  port = pipe_open(execarg_obj, modestr, fmode, &convconfig);
6390  if (NIL_P(port)) {
6391  /* child */
6392  if (rb_block_given_p()) {
6393  rb_yield(Qnil);
6396  _exit(0);
6397  }
6398  return Qnil;
6399  }
6400  RBASIC_SET_CLASS(port, klass);
6401  if (rb_block_given_p()) {
6402  return rb_ensure(rb_yield, port, pipe_close, port);
6403  }
6404  return port;
6405 }
6406 
6407 static void
6409  VALUE *fname_p, int *oflags_p, int *fmode_p,
6410  convconfig_t *convconfig_p, mode_t *perm_p)
6411 {
6412  VALUE opt, fname, vmode, vperm;
6413  int oflags, fmode;
6414  mode_t perm;
6415 
6416  argc = rb_scan_args(argc, argv, "12:", &fname, &vmode, &vperm, &opt);
6417  FilePathValue(fname);
6418 
6419  rb_io_extract_modeenc(&vmode, &vperm, opt, &oflags, &fmode, convconfig_p);
6420 
6421  perm = NIL_P(vperm) ? 0666 : NUM2MODET(vperm);
6422 
6423  *fname_p = fname;
6424  *oflags_p = oflags;
6425  *fmode_p = fmode;
6426  *perm_p = perm;
6427 }
6428 
6429 static VALUE
6431 {
6432  VALUE fname;
6433  int oflags, fmode;
6434  convconfig_t convconfig;
6435  mode_t perm;
6436 
6437  rb_scan_open_args(argc, argv, &fname, &oflags, &fmode, &convconfig, &perm);
6438  rb_file_open_generic(io, fname, oflags, fmode, &convconfig, perm);
6439 
6440  return io;
6441 }
6442 
6443 
6444 /*
6445  * Document-method: File::open
6446  *
6447  * call-seq:
6448  * File.open(filename, mode="r" [, opt]) -> file
6449  * File.open(filename [, mode [, perm]] [, opt]) -> file
6450  * File.open(filename, mode="r" [, opt]) {|file| block } -> obj
6451  * File.open(filename [, mode [, perm]] [, opt]) {|file| block } -> obj
6452  *
6453  * With no associated block, <code>File.open</code> is a synonym for
6454  * File.new. If the optional code block is given, it will
6455  * be passed the opened +file+ as an argument and the File object will
6456  * automatically be closed when the block terminates. The value of the block
6457  * will be returned from <code>File.open</code>.
6458  *
6459  * If a file is being created, its initial permissions may be set using the
6460  * +perm+ parameter. See File.new for further discussion.
6461  *
6462  * See IO.new for a description of the +mode+ and +opt+ parameters.
6463  */
6464 
6465 /*
6466  * Document-method: IO::open
6467  *
6468  * call-seq:
6469  * IO.open(fd, mode="r" [, opt]) -> io
6470  * IO.open(fd, mode="r" [, opt]) {|io| block } -> obj
6471  *
6472  * With no associated block, <code>IO.open</code> is a synonym for IO.new. If
6473  * the optional code block is given, it will be passed +io+ as an argument,
6474  * and the IO object will automatically be closed when the block terminates.
6475  * In this instance, IO.open returns the value of the block.
6476  *
6477  * See IO.new for a description of the +fd+, +mode+ and +opt+ parameters.
6478  */
6479 
6480 static VALUE
6482 {
6483  VALUE io = rb_class_new_instance(argc, argv, klass);
6484 
6485  if (rb_block_given_p()) {
6486  return rb_ensure(rb_yield, io, io_close, io);
6487  }
6488 
6489  return io;
6490 }
6491 
6492 /*
6493  * call-seq:
6494  * IO.sysopen(path, [mode, [perm]]) -> integer
6495  *
6496  * Opens the given path, returning the underlying file descriptor as a
6497  * <code>Integer</code>.
6498  *
6499  * IO.sysopen("testfile") #=> 3
6500  */
6501 
6502 static VALUE
6504 {
6505  VALUE fname, vmode, vperm;
6506  VALUE intmode;
6507  int oflags, fd;
6508  mode_t perm;
6509 
6510  rb_scan_args(argc, argv, "12", &fname, &vmode, &vperm);
6511  FilePathValue(fname);
6512 
6513  if (NIL_P(vmode))
6514  oflags = O_RDONLY;
6515  else if (!NIL_P(intmode = rb_check_to_integer(vmode, "to_int")))
6516  oflags = NUM2INT(intmode);
6517  else {
6518  SafeStringValue(vmode);
6519  oflags = rb_io_modestr_oflags(StringValueCStr(vmode));
6520  }
6521  if (NIL_P(vperm)) perm = 0666;
6522  else perm = NUM2MODET(vperm);
6523 
6524  RB_GC_GUARD(fname) = rb_str_new4(fname);
6525  fd = rb_sysopen(fname, oflags, perm);
6526  return INT2NUM(fd);
6527 }
6528 
6529 static VALUE
6530 check_pipe_command(VALUE filename_or_command)
6531 {
6532  char *s = RSTRING_PTR(filename_or_command);
6533  long l = RSTRING_LEN(filename_or_command);
6534  char *e = s + l;
6535  int chlen;
6536 
6537  if (rb_enc_ascget(s, e, &chlen, rb_enc_get(filename_or_command)) == '|') {
6538  VALUE cmd = rb_str_new(s+chlen, l-chlen);
6539  OBJ_INFECT(cmd, filename_or_command);
6540  return cmd;
6541  }
6542  return Qnil;
6543 }
6544 
6545 /*
6546  * call-seq:
6547  * open(path [, mode [, perm]] [, opt]) -> io or nil
6548  * open(path [, mode [, perm]] [, opt]) {|io| block } -> obj
6549  *
6550  * Creates an IO object connected to the given stream, file, or subprocess.
6551  *
6552  * If +path+ does not start with a pipe character (<code>|</code>), treat it
6553  * as the name of a file to open using the specified mode (defaulting to
6554  * "r").
6555  *
6556  * The +mode+ is either a string or an integer. If it is an integer, it
6557  * must be bitwise-or of open(2) flags, such as File::RDWR or File::EXCL. If
6558  * it is a string, it is either "fmode", "fmode:ext_enc", or
6559  * "fmode:ext_enc:int_enc".
6560  *
6561  * See the documentation of IO.new for full documentation of the +mode+ string
6562  * directives.
6563  *
6564  * If a file is being created, its initial permissions may be set using the
6565  * +perm+ parameter. See File.new and the open(2) and chmod(2) man pages for
6566  * a description of permissions.
6567  *
6568  * If a block is specified, it will be invoked with the IO object as a
6569  * parameter, and the IO will be automatically closed when the block
6570  * terminates. The call returns the value of the block.
6571  *
6572  * If +path+ starts with a pipe character (<code>"|"</code>), a subprocess is
6573  * created, connected to the caller by a pair of pipes. The returned IO
6574  * object may be used to write to the standard input and read from the
6575  * standard output of this subprocess.
6576  *
6577  * If the command following the pipe is a single minus sign
6578  * (<code>"|-"</code>), Ruby forks, and this subprocess is connected to the
6579  * parent. If the command is not <code>"-"</code>, the subprocess runs the
6580  * command.
6581  *
6582  * When the subprocess is Ruby (opened via <code>"|-"</code>), the +open+
6583  * call returns +nil+. If a block is associated with the open call, that
6584  * block will run twice --- once in the parent and once in the child.
6585  *
6586  * The block parameter will be an IO object in the parent and +nil+ in the
6587  * child. The parent's +IO+ object will be connected to the child's $stdin
6588  * and $stdout. The subprocess will be terminated at the end of the block.
6589  *
6590  * === Examples
6591  *
6592  * Reading from "testfile":
6593  *
6594  * open("testfile") do |f|
6595  * print f.gets
6596  * end
6597  *
6598  * Produces:
6599  *
6600  * This is line one
6601  *
6602  * Open a subprocess and read its output:
6603  *
6604  * cmd = open("|date")
6605  * print cmd.gets
6606  * cmd.close
6607  *
6608  * Produces:
6609  *
6610  * Wed Apr 9 08:56:31 CDT 2003
6611  *
6612  * Open a subprocess running the same Ruby program:
6613  *
6614  * f = open("|-", "w+")
6615  * if f.nil?
6616  * puts "in Child"
6617  * exit
6618  * else
6619  * puts "Got: #{f.gets}"
6620  * end
6621  *
6622  * Produces:
6623  *
6624  * Got: in Child
6625  *
6626  * Open a subprocess using a block to receive the IO object:
6627  *
6628  * open "|-" do |f|
6629  * if f then
6630  * # parent process
6631  * puts "Got: #{f.gets}"
6632  * else
6633  * # child process
6634  * puts "in Child"
6635  * end
6636  * end
6637  *
6638  * Produces:
6639  *
6640  * Got: in Child
6641  */
6642 
6643 static VALUE
6645 {
6646  ID to_open = 0;
6647  int redirect = FALSE;
6648 
6649  if (argc >= 1) {
6650  CONST_ID(to_open, "to_open");
6651  if (rb_respond_to(argv[0], to_open)) {
6652  redirect = TRUE;
6653  }
6654  else {
6655  VALUE tmp = argv[0];
6656  FilePathValue(tmp);
6657  if (NIL_P(tmp)) {
6658  redirect = TRUE;
6659  }
6660  else {
6661  VALUE cmd = check_pipe_command(tmp);
6662  if (!NIL_P(cmd)) {
6663  argv[0] = cmd;
6664  return rb_io_s_popen(argc, argv, rb_cIO);
6665  }
6666  }
6667  }
6668  }
6669  if (redirect) {
6670  VALUE io = rb_funcallv(argv[0], to_open, argc-1, argv+1);
6671 
6672  if (rb_block_given_p()) {
6673  return rb_ensure(rb_yield, io, io_close, io);
6674  }
6675  return io;
6676  }
6677  return rb_io_s_open(argc, argv, rb_cFile);
6678 }
6679 
6680 static VALUE rb_io_open_generic(VALUE, int, int, const convconfig_t *, mode_t);
6681 
6682 static VALUE
6684 {
6685  int oflags, fmode;
6686  convconfig_t convconfig;
6687  mode_t perm;
6688 
6689  rb_io_extract_modeenc(&vmode, &vperm, opt, &oflags, &fmode, &convconfig);
6690  perm = NIL_P(vperm) ? 0666 : NUM2MODET(vperm);
6691  return rb_io_open_generic(filename, oflags, fmode, &convconfig, perm);
6692 }
6693 
6694 static VALUE
6696  const convconfig_t *convconfig, mode_t perm)
6697 {
6698  VALUE cmd;
6699  if (!NIL_P(cmd = check_pipe_command(filename))) {
6700  return pipe_open_s(cmd, rb_io_oflags_modestr(oflags), fmode, convconfig);
6701  }
6702  else {
6703  return rb_file_open_generic(io_alloc(rb_cFile), filename,
6704  oflags, fmode, convconfig, perm);
6705  }
6706 }
6707 
6708 static VALUE
6710 {
6711  VALUE io;
6712 
6713  io = io_alloc(rb_cFile);
6714  rb_open_file(argc, argv, io);
6715  return io;
6716 }
6717 
6718 static VALUE
6720 {
6721  rb_io_t *fptr, *orig;
6722  int fd, fd2;
6723  off_t pos = 0;
6724 
6725  nfile = rb_io_get_io(nfile);
6726  GetOpenFile(io, fptr);
6727  GetOpenFile(nfile, orig);
6728 
6729  if (fptr == orig) return io;
6730  if (IS_PREP_STDIO(fptr)) {
6731  if ((fptr->stdio_file == stdin && !(orig->mode & FMODE_READABLE)) ||
6732  (fptr->stdio_file == stdout && !(orig->mode & FMODE_WRITABLE)) ||
6733  (fptr->stdio_file == stderr && !(orig->mode & FMODE_WRITABLE))) {
6735  "%s can't change access mode from \"%s\" to \"%s\"",
6737  rb_io_fmode_modestr(orig->mode));
6738  }
6739  }
6740  if (fptr->mode & FMODE_WRITABLE) {
6741  if (io_fflush(fptr) < 0)
6742  rb_sys_fail(0);
6743  }
6744  else {
6745  io_tell(fptr);
6746  }
6747  if (orig->mode & FMODE_READABLE) {
6748  pos = io_tell(orig);
6749  }
6750  if (orig->mode & FMODE_WRITABLE) {
6751  if (io_fflush(orig) < 0)
6752  rb_sys_fail(0);
6753  }
6754 
6755  /* copy rb_io_t structure */
6756  fptr->mode = orig->mode | (fptr->mode & FMODE_PREP);
6757  fptr->pid = orig->pid;
6758  fptr->lineno = orig->lineno;
6759  if (RTEST(orig->pathv)) fptr->pathv = orig->pathv;
6760  else if (!IS_PREP_STDIO(fptr)) fptr->pathv = Qnil;
6761  fptr->finalize = orig->finalize;
6762 #if defined (__CYGWIN__) || !defined(HAVE_WORKING_FORK)
6763  if (fptr->finalize == pipe_finalize)
6764  pipe_add_fptr(fptr);
6765 #endif
6766 
6767  fd = fptr->fd;
6768  fd2 = orig->fd;
6769  if (fd != fd2) {
6770  if (IS_PREP_STDIO(fptr) || fd <= 2 || !fptr->stdio_file) {
6771  /* need to keep FILE objects of stdin, stdout and stderr */
6772  if (rb_cloexec_dup2(fd2, fd) < 0)
6773  rb_sys_fail_path(orig->pathv);
6774  rb_update_max_fd(fd);
6775  }
6776  else {
6777  fclose(fptr->stdio_file);
6778  fptr->stdio_file = 0;
6779  fptr->fd = -1;
6780  if (rb_cloexec_dup2(fd2, fd) < 0)
6781  rb_sys_fail_path(orig->pathv);
6782  rb_update_max_fd(fd);
6783  fptr->fd = fd;
6784  }
6785  rb_notify_fd_close(fd);
6786  if ((orig->mode & FMODE_READABLE) && pos >= 0) {
6787  if (io_seek(fptr, pos, SEEK_SET) < 0 && errno) {
6788  rb_sys_fail_path(fptr->pathv);
6789  }
6790  if (io_seek(orig, pos, SEEK_SET) < 0 && errno) {
6791  rb_sys_fail_path(orig->pathv);
6792  }
6793  }
6794  }
6795 
6796  if (fptr->mode & FMODE_BINMODE) {
6797  rb_io_binmode(io);
6798  }
6799 
6800  RBASIC_SET_CLASS(io, rb_obj_class(nfile));
6801  return io;
6802 }
6803 
6804 #ifdef _WIN32
6805 int rb_freopen(VALUE fname, const char *mode, FILE *fp);
6806 #else
6807 static int
6808 rb_freopen(VALUE fname, const char *mode, FILE *fp)
6809 {
6810  if (!freopen(RSTRING_PTR(fname), mode, fp)) {
6811  RB_GC_GUARD(fname);
6812  return errno;
6813  }
6814  return 0;
6815 }
6816 #endif
6817 
6818 /*
6819  * call-seq:
6820  * ios.reopen(other_IO) -> ios
6821  * ios.reopen(path, mode_str) -> ios
6822  *
6823  * Reassociates <em>ios</em> with the I/O stream given in
6824  * <i>other_IO</i> or to a new stream opened on <i>path</i>. This may
6825  * dynamically change the actual class of this stream.
6826  *
6827  * f1 = File.new("testfile")
6828  * f2 = File.new("testfile")
6829  * f2.readlines[0] #=> "This is line one\n"
6830  * f2.reopen(f1) #=> #<File:testfile>
6831  * f2.readlines[0] #=> "This is line one\n"
6832  */
6833 
6834 static VALUE
6836 {
6837  VALUE fname, nmode, opt;
6838  int oflags;
6839  rb_io_t *fptr;
6840 
6841  if (rb_scan_args(argc, argv, "11:", &fname, &nmode, &opt) == 1) {
6842  VALUE tmp = rb_io_check_io(fname);
6843  if (!NIL_P(tmp)) {
6844  return io_reopen(file, tmp);
6845  }
6846  }
6847 
6848  FilePathValue(fname);
6849  rb_io_taint_check(file);
6850  fptr = RFILE(file)->fptr;
6851  if (!fptr) {
6852  fptr = RFILE(file)->fptr = ZALLOC(rb_io_t);
6853  }
6854 
6855  if (!NIL_P(nmode) || !NIL_P(opt)) {
6856  int fmode;
6857  convconfig_t convconfig;
6858 
6859  rb_io_extract_modeenc(&nmode, 0, opt, &oflags, &fmode, &convconfig);
6860  if (IS_PREP_STDIO(fptr) &&
6861  ((fptr->mode & FMODE_READWRITE) & (fmode & FMODE_READWRITE)) !=
6862  (fptr->mode & FMODE_READWRITE)) {
6864  "%s can't change access mode from \"%s\" to \"%s\"",
6866  rb_io_fmode_modestr(fmode));
6867  }
6868  fptr->mode = fmode;
6869  fptr->encs = convconfig;
6870  }
6871  else {
6872  oflags = rb_io_fmode_oflags(fptr->mode);
6873  }
6874 
6875  fptr->pathv = fname;
6876  if (fptr->fd < 0) {
6877  fptr->fd = rb_sysopen(fptr->pathv, oflags, 0666);
6878  fptr->stdio_file = 0;
6879  return file;
6880  }
6881 
6882  if (fptr->mode & FMODE_WRITABLE) {
6883  if (io_fflush(fptr) < 0)
6884  rb_sys_fail(0);
6885  }
6886  fptr->rbuf.off = fptr->rbuf.len = 0;
6887 
6888  if (fptr->stdio_file) {
6889  int e = rb_freopen(rb_str_encode_ospath(fptr->pathv),
6890  rb_io_oflags_modestr(oflags),
6891  fptr->stdio_file);
6892  if (e) rb_syserr_fail_path(e, fptr->pathv);
6893  fptr->fd = fileno(fptr->stdio_file);
6894  rb_fd_fix_cloexec(fptr->fd);
6895 #ifdef USE_SETVBUF
6896  if (setvbuf(fptr->stdio_file, NULL, _IOFBF, 0) != 0)
6897  rb_warn("setvbuf() can't be honoured for %"PRIsVALUE, fptr->pathv);
6898 #endif
6899  if (fptr->stdio_file == stderr) {
6900  if (setvbuf(fptr->stdio_file, NULL, _IONBF, BUFSIZ) != 0)
6901  rb_warn("setvbuf() can't be honoured for %"PRIsVALUE, fptr->pathv);
6902  }
6903  else if (fptr->stdio_file == stdout && isatty(fptr->fd)) {
6904  if (setvbuf(fptr->stdio_file, NULL, _IOLBF, BUFSIZ) != 0)
6905  rb_warn("setvbuf() can't be honoured for %"PRIsVALUE, fptr->pathv);
6906  }
6907  }
6908  else {
6909  int tmpfd = rb_sysopen(fptr->pathv, oflags, 0666);
6910  int err = 0;
6911  if (rb_cloexec_dup2(tmpfd, fptr->fd) < 0)
6912  err = errno;
6913  (void)close(tmpfd);
6914  if (err) {
6915  rb_syserr_fail_path(err, fptr->pathv);
6916  }
6917  }
6918 
6919  return file;
6920 }
6921 
6922 /* :nodoc: */
6923 static VALUE
6925 {
6926  rb_io_t *fptr, *orig;
6927  int fd;
6928  VALUE write_io;
6929  off_t pos;
6930 
6931  io = rb_io_get_io(io);
6932  if (!OBJ_INIT_COPY(dest, io)) return dest;
6933  GetOpenFile(io, orig);
6934  MakeOpenFile(dest, fptr);
6935 
6936  rb_io_flush(io);
6937 
6938  /* copy rb_io_t structure */
6939  fptr->mode = orig->mode & ~FMODE_PREP;
6940  fptr->encs = orig->encs;
6941  fptr->pid = orig->pid;
6942  fptr->lineno = orig->lineno;
6943  if (!NIL_P(orig->pathv)) fptr->pathv = orig->pathv;
6944  fptr->finalize = orig->finalize;
6945 #if defined (__CYGWIN__) || !defined(HAVE_WORKING_FORK)
6946  if (fptr->finalize == pipe_finalize)
6947  pipe_add_fptr(fptr);
6948 #endif
6949 
6950  fd = ruby_dup(orig->fd);
6951  fptr->fd = fd;
6952  pos = io_tell(orig);
6953  if (0 <= pos)
6954  io_seek(fptr, pos, SEEK_SET);
6955  if (fptr->mode & FMODE_BINMODE) {
6956  rb_io_binmode(dest);
6957  }
6958 
6959  write_io = GetWriteIO(io);
6960  if (io != write_io) {
6961  write_io = rb_obj_dup(write_io);
6962  fptr->tied_io_for_writing = write_io;
6963  rb_ivar_set(dest, rb_intern("@tied_io_for_writing"), write_io);
6964  }
6965 
6966  return dest;
6967 }
6968 
6969 /*
6970  * call-seq:
6971  * ios.printf(format_string [, obj, ...]) -> nil
6972  *
6973  * Formats and writes to <em>ios</em>, converting parameters under
6974  * control of the format string. See <code>Kernel#sprintf</code>
6975  * for details.
6976  */
6977 
6978 VALUE
6979 rb_io_printf(int argc, const VALUE *argv, VALUE out)
6980 {
6981  rb_io_write(out, rb_f_sprintf(argc, argv));
6982  return Qnil;
6983 }
6984 
6985 /*
6986  * call-seq:
6987  * printf(io, string [, obj ... ]) -> nil
6988  * printf(string [, obj ... ]) -> nil
6989  *
6990  * Equivalent to:
6991  * io.write(sprintf(string, obj, ...))
6992  * or
6993  * $stdout.write(sprintf(string, obj, ...))
6994  */
6995 
6996 static VALUE
6998 {
6999  VALUE out;
7000 
7001  if (argc == 0) return Qnil;
7002  if (RB_TYPE_P(argv[0], T_STRING)) {
7003  out = rb_stdout;
7004  }
7005  else {
7006  out = argv[0];
7007  argv++;
7008  argc--;
7009  }
7010  rb_io_write(out, rb_f_sprintf(argc, argv));
7011 
7012  return Qnil;
7013 }
7014 
7015 /*
7016  * call-seq:
7017  * ios.print -> nil
7018  * ios.print(obj, ...) -> nil
7019  *
7020  * Writes the given object(s) to <em>ios</em>. Returns +nil+.
7021  *
7022  * The stream must be opened for writing.
7023  * Each given object that isn't a string will be converted by calling
7024  * its <code>to_s</code> method.
7025  * When called without arguments, prints the contents of <code>$_</code>.
7026  *
7027  * If the output field separator (<code>$,</code>) is not +nil+,
7028  * it is inserted between objects.
7029  * If the output record separator (<code>$\</code>) is not +nil+,
7030  * it is appended to the output.
7031  *
7032  * $stdout.print("This is ", 100, " percent.\n")
7033  *
7034  * <em>produces:</em>
7035  *
7036  * This is 100 percent.
7037  */
7038 
7039 VALUE
7040 rb_io_print(int argc, const VALUE *argv, VALUE out)
7041 {
7042  int i;
7043  VALUE line;
7044 
7045  /* if no argument given, print `$_' */
7046  if (argc == 0) {
7047  argc = 1;
7048  line = rb_lastline_get();
7049  argv = &line;
7050  }
7051  for (i=0; i<argc; i++) {
7052  if (!NIL_P(rb_output_fs) && i>0) {
7053  rb_io_write(out, rb_output_fs);
7054  }
7055  rb_io_write(out, argv[i]);
7056  }
7057  if (argc > 0 && !NIL_P(rb_output_rs)) {
7058  rb_io_write(out, rb_output_rs);
7059  }
7060 
7061  return Qnil;
7062 }
7063 
7064 /*
7065  * call-seq:
7066  * print(obj, ...) -> nil
7067  *
7068  * Prints each object in turn to <code>$stdout</code>. If the output
7069  * field separator (<code>$,</code>) is not +nil+, its
7070  * contents will appear between each field. If the output record
7071  * separator (<code>$\</code>) is not +nil+, it will be
7072  * appended to the output. If no arguments are given, prints
7073  * <code>$_</code>. Objects that aren't strings will be converted by
7074  * calling their <code>to_s</code> method.
7075  *
7076  * print "cat", [1,2,3], 99, "\n"
7077  * $, = ", "
7078  * $\ = "\n"
7079  * print "cat", [1,2,3], 99
7080  *
7081  * <em>produces:</em>
7082  *
7083  * cat12399
7084  * cat, 1, 2, 3, 99
7085  */
7086 
7087 static VALUE
7089 {
7090  rb_io_print(argc, argv, rb_stdout);
7091  return Qnil;
7092 }
7093 
7094 /*
7095  * call-seq:
7096  * ios.putc(obj) -> obj
7097  *
7098  * If <i>obj</i> is <code>Numeric</code>, write the character whose code is
7099  * the least-significant byte of <i>obj</i>, otherwise write the first byte
7100  * of the string representation of <i>obj</i> to <em>ios</em>. Note: This
7101  * method is not safe for use with multi-byte characters as it will truncate
7102  * them.
7103  *
7104  * $stdout.putc "A"
7105  * $stdout.putc 65
7106  *
7107  * <em>produces:</em>
7108  *
7109  * AA
7110  */
7111 
7112 static VALUE
7114 {
7115  VALUE str;
7116  if (RB_TYPE_P(ch, T_STRING)) {
7117  str = rb_str_substr(ch, 0, 1);
7118  }
7119  else {
7120  char c = NUM2CHR(ch);
7121  str = rb_str_new(&c, 1);
7122  }
7123  rb_io_write(io, str);
7124  return ch;
7125 }
7126 
7127 /*
7128  * call-seq:
7129  * putc(int) -> int
7130  *
7131  * Equivalent to:
7132  *
7133  * $stdout.putc(int)
7134  *
7135  * Refer to the documentation for IO#putc for important information regarding
7136  * multi-byte characters.
7137  */
7138 
7139 static VALUE
7141 {
7142  if (recv == rb_stdout) {
7143  return rb_io_putc(recv, ch);
7144  }
7145  return rb_funcallv(rb_stdout, rb_intern("putc"), 1, &ch);
7146 }
7147 
7148 
7149 static int
7151 {
7152  long len = RSTRING_LEN(str);
7153  const char *ptr = RSTRING_PTR(str);
7155  int n;
7156 
7157  if (len == 0) return 0;
7158  if ((n = rb_enc_mbminlen(enc)) == 1) {
7159  return ptr[len - 1] == c;
7160  }
7161  return rb_enc_ascget(ptr + ((len - 1) / n) * n, ptr + len, &n, enc) == c;
7162 }
7163 
7164 static VALUE
7166 {
7167  VALUE tmp;
7168  long i;
7169 
7170  if (recur) {
7171  tmp = rb_str_new2("[...]");
7172  rb_io_puts(1, &tmp, out);
7173  return Qtrue;
7174  }
7175  ary = rb_check_array_type(ary);
7176  if (NIL_P(ary)) return Qfalse;
7177  for (i=0; i<RARRAY_LEN(ary); i++) {
7178  tmp = RARRAY_AREF(ary, i);
7179  rb_io_puts(1, &tmp, out);
7180  }
7181  return Qtrue;
7182 }
7183 
7184 /*
7185  * call-seq:
7186  * ios.puts(obj, ...) -> nil
7187  *
7188  * Writes the given object(s) to <em>ios</em>.
7189  * Writes a newline after any that do not already end
7190  * with a newline sequence. Returns +nil+.
7191  *
7192  * The stream must be opened for writing.
7193  * If called with an array argument, writes each element on a new line.
7194  * Each given object that isn't a string or array will be converted
7195  * by calling its +to_s+ method.
7196  * If called without arguments, outputs a single newline.
7197  *
7198  * $stdout.puts("this", "is", ["a", "test"])
7199  *
7200  * <em>produces:</em>
7201  *
7202  * this
7203  * is
7204  * a
7205  * test
7206  *
7207  * Note that +puts+ always uses newlines and is not affected
7208  * by the output record separator (<code>$\</code>).
7209  */
7210 
7211 VALUE
7212 rb_io_puts(int argc, const VALUE *argv, VALUE out)
7213 {
7214  int i;
7215  VALUE line;
7216 
7217  /* if no argument given, print newline. */
7218  if (argc == 0) {
7219  rb_io_write(out, rb_default_rs);
7220  return Qnil;
7221  }
7222  for (i=0; i<argc; i++) {
7223  if (RB_TYPE_P(argv[i], T_STRING)) {
7224  line = argv[i];
7225  goto string;
7226  }
7227  if (rb_exec_recursive(io_puts_ary, argv[i], out)) {
7228  continue;
7229  }
7230  line = rb_obj_as_string(argv[i]);
7231  string:
7232  rb_io_write(out, line);
7233  if (RSTRING_LEN(line) == 0 ||
7234  !str_end_with_asciichar(line, '\n')) {
7235  rb_io_write(out, rb_default_rs);
7236  }
7237  }
7238 
7239  return Qnil;
7240 }
7241 
7242 /*
7243  * call-seq:
7244  * puts(obj, ...) -> nil
7245  *
7246  * Equivalent to
7247  *
7248  * $stdout.puts(obj, ...)
7249  */
7250 
7251 static VALUE
7253 {
7254  if (recv == rb_stdout) {
7255  return rb_io_puts(argc, argv, recv);
7256  }
7257  return rb_funcallv(rb_stdout, rb_intern("puts"), argc, argv);
7258 }
7259 
7260 void
7261 rb_p(VALUE obj) /* for debug print within C code */
7262 {
7263  VALUE str = rb_obj_as_string(rb_inspect(obj));
7264  if (RB_TYPE_P(rb_stdout, T_FILE) &&
7266  io_write(rb_stdout, str, 1);
7268  }
7269  else {
7270  rb_io_write(rb_stdout, str);
7272  }
7273 }
7274 
7275 struct rb_f_p_arg {
7276  int argc;
7278 };
7279 
7280 static VALUE
7282 {
7283  struct rb_f_p_arg *arg1 = (struct rb_f_p_arg*)arg;
7284  int argc = arg1->argc;
7285  VALUE *argv = arg1->argv;
7286  int i;
7287  VALUE ret = Qnil;
7288 
7289  for (i=0; i<argc; i++) {
7290  rb_p(argv[i]);
7291  }
7292  if (argc == 1) {
7293  ret = argv[0];
7294  }
7295  else if (argc > 1) {
7296  ret = rb_ary_new4(argc, argv);
7297  }
7298  if (RB_TYPE_P(rb_stdout, T_FILE)) {
7300  }
7301  return ret;
7302 }
7303 
7304 /*
7305  * call-seq:
7306  * p(obj) -> obj
7307  * p(obj1, obj2, ...) -> [obj, ...]
7308  * p() -> nil
7309  *
7310  * For each object, directly writes _obj_.+inspect+ followed by a
7311  * newline to the program's standard output.
7312  *
7313  * S = Struct.new(:name, :state)
7314  * s = S['dave', 'TX']
7315  * p s
7316  *
7317  * <em>produces:</em>
7318  *
7319  * #<S name="dave", state="TX">
7320  */
7321 
7322 static VALUE
7324 {
7325  struct rb_f_p_arg arg;
7326  arg.argc = argc;
7327  arg.argv = argv;
7328 
7329  return rb_uninterruptible(rb_f_p_internal, (VALUE)&arg);
7330 }
7331 
7332 /*
7333  * call-seq:
7334  * obj.display(port=$>) -> nil
7335  *
7336  * Prints <i>obj</i> on the given port (default <code>$></code>).
7337  * Equivalent to:
7338  *
7339  * def display(port=$>)
7340  * port.write self
7341  * nil
7342  * end
7343  *
7344  * For example:
7345  *
7346  * 1.display
7347  * "cat".display
7348  * [ 4, 5, 6 ].display
7349  * puts
7350  *
7351  * <em>produces:</em>
7352  *
7353  * 1cat[4, 5, 6]
7354  */
7355 
7356 static VALUE
7358 {
7359  VALUE out;
7360 
7361  if (argc == 0) {
7362  out = rb_stdout;
7363  }
7364  else {
7365  rb_scan_args(argc, argv, "01", &out);
7366  }
7367  rb_io_write(out, self);
7368 
7369  return Qnil;
7370 }
7371 
7372 void
7373 rb_write_error2(const char *mesg, long len)
7374 {
7375  if (rb_stderr == orig_stderr || RFILE(orig_stderr)->fptr->fd < 0) {
7376  if (fwrite(mesg, sizeof(char), (size_t)len, stderr) < (size_t)len) {
7377  /* failed to write to stderr, what can we do? */
7378  return;
7379  }
7380  }
7381  else {
7382  rb_io_write(rb_stderr, rb_str_new(mesg, len));
7383  }
7384 }
7385 
7386 void
7387 rb_write_error(const char *mesg)
7388 {
7389  rb_write_error2(mesg, strlen(mesg));
7390 }
7391 
7392 void
7394 {
7395  /* a stopgap measure for the time being */
7396  if (rb_stderr == orig_stderr || RFILE(orig_stderr)->fptr->fd < 0) {
7397  size_t len = (size_t)RSTRING_LEN(mesg);
7398 #ifdef _WIN32
7399  if (isatty(fileno(stderr))) {
7400  if (rb_w32_write_console(mesg, fileno(stderr)) > 0) return;
7401  }
7402 #endif
7403  if (fwrite(RSTRING_PTR(mesg), sizeof(char), len, stderr) < len) {
7404  RB_GC_GUARD(mesg);
7405  return;
7406  }
7407  }
7408  else {
7409  /* may unlock GVL, and */
7410  rb_io_write(rb_stderr, mesg);
7411  }
7412 }
7413 
7414 static void
7416 {
7417  if (!rb_respond_to(val, mid)) {
7418  rb_raise(rb_eTypeError, "%"PRIsVALUE" must have %"PRIsVALUE" method, %"PRIsVALUE" given",
7419  rb_id2str(id), rb_id2str(mid),
7420  rb_obj_class(val));
7421  }
7422 }
7423 
7424 static void
7425 stdout_setter(VALUE val, ID id, VALUE *variable)
7426 {
7427  must_respond_to(id_write, val, id);
7428  *variable = val;
7429 }
7430 
7431 static VALUE
7432 prep_io(int fd, int fmode, VALUE klass, const char *path)
7433 {
7434  rb_io_t *fp;
7435  VALUE io = io_alloc(klass);
7436 
7437  MakeOpenFile(io, fp);
7438  fp->fd = fd;
7439  fp->mode = fmode;
7440  if (!io_check_tty(fp)) {
7441 #ifdef __CYGWIN__
7442  fp->mode |= FMODE_BINMODE;
7443  setmode(fd, O_BINARY);
7444 #endif
7445  }
7446  if (path) fp->pathv = rb_obj_freeze(rb_str_new_cstr(path));
7447  rb_update_max_fd(fd);
7448 
7449  return io;
7450 }
7451 
7452 VALUE
7453 rb_io_fdopen(int fd, int oflags, const char *path)
7454 {
7455  VALUE klass = rb_cIO;
7456 
7457  if (path && strcmp(path, "-")) klass = rb_cFile;
7458  return prep_io(fd, rb_io_oflags_fmode(oflags), klass, path);
7459 }
7460 
7461 static VALUE
7462 prep_stdio(FILE *f, int fmode, VALUE klass, const char *path)
7463 {
7464  rb_io_t *fptr;
7465  VALUE io = prep_io(fileno(f), fmode|FMODE_PREP|DEFAULT_TEXTMODE, klass, path);
7466 
7467  GetOpenFile(io, fptr);
7469 #ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE
7470  fptr->encs.ecflags |= TEXTMODE_NEWLINE_DECORATOR_ON_WRITE;
7471  if (fmode & FMODE_READABLE) {
7473  }
7474 #endif
7475  fptr->stdio_file = f;
7476 
7477  return io;
7478 }
7479 
7480 FILE *
7482 {
7483  if (!fptr->stdio_file) {
7484  int oflags = rb_io_fmode_oflags(fptr->mode);
7485  fptr->stdio_file = rb_fdopen(fptr->fd, rb_io_oflags_modestr(oflags));
7486  }
7487  return fptr->stdio_file;
7488 }
7489 
7490 static inline void
7492 {
7493  buf->ptr = NULL;
7494  buf->off = 0;
7495  buf->len = 0;
7496  buf->capa = 0;
7497 }
7498 
7499 static inline rb_io_t *
7501 {
7502  rb_io_t *fp = ALLOC(rb_io_t);
7503  fp->fd = -1;
7504  fp->stdio_file = NULL;
7505  fp->mode = 0;
7506  fp->pid = 0;
7507  fp->lineno = 0;
7508  fp->pathv = Qnil;
7509  fp->finalize = 0;
7510  rb_io_buffer_init(&fp->wbuf);
7511  rb_io_buffer_init(&fp->rbuf);
7512  rb_io_buffer_init(&fp->cbuf);
7513  fp->readconv = NULL;
7514  fp->writeconv = NULL;
7516  fp->writeconv_pre_ecflags = 0;
7517  fp->writeconv_pre_ecopts = Qnil;
7518  fp->writeconv_initialized = 0;
7519  fp->tied_io_for_writing = 0;
7520  fp->encs.enc = NULL;
7521  fp->encs.enc2 = NULL;
7522  fp->encs.ecflags = 0;
7523  fp->encs.ecopts = Qnil;
7524  fp->write_lock = 0;
7525  return fp;
7526 }
7527 
7528 rb_io_t *
7530 {
7531  rb_io_t *fp = 0;
7532 
7533  Check_Type(obj, T_FILE);
7534  if (RFILE(obj)->fptr) {
7535  rb_io_close(obj);
7536  rb_io_fptr_finalize(RFILE(obj)->fptr);
7537  RFILE(obj)->fptr = 0;
7538  }
7539  fp = rb_io_fptr_new();
7540  RFILE(obj)->fptr = fp;
7541  return fp;
7542 }
7543 
7544 /*
7545  * call-seq:
7546  * IO.new(fd [, mode] [, opt]) -> io
7547  *
7548  * Returns a new IO object (a stream) for the given integer file descriptor
7549  * +fd+ and +mode+ string. +opt+ may be used to specify parts of +mode+ in a
7550  * more readable fashion. See also IO.sysopen and IO.for_fd.
7551  *
7552  * IO.new is called by various File and IO opening methods such as IO::open,
7553  * Kernel#open, and File::open.
7554  *
7555  * === Open Mode
7556  *
7557  * When +mode+ is an integer it must be combination of the modes defined in
7558  * File::Constants (+File::RDONLY+, +File::WRONLY | File::CREAT+). See the
7559  * open(2) man page for more information.
7560  *
7561  * When +mode+ is a string it must be in one of the following forms:
7562  *
7563  * fmode
7564  * fmode ":" ext_enc
7565  * fmode ":" ext_enc ":" int_enc
7566  * fmode ":" "BOM|UTF-*"
7567  *
7568  * +fmode+ is an IO open mode string, +ext_enc+ is the external encoding for
7569  * the IO and +int_enc+ is the internal encoding.
7570  *
7571  * ==== IO Open Mode
7572  *
7573  * Ruby allows the following open modes:
7574  *
7575  * "r" Read-only, starts at beginning of file (default mode).
7576  *
7577  * "r+" Read-write, starts at beginning of file.
7578  *
7579  * "w" Write-only, truncates existing file
7580  * to zero length or creates a new file for writing.
7581  *
7582  * "w+" Read-write, truncates existing file to zero length
7583  * or creates a new file for reading and writing.
7584  *
7585  * "a" Write-only, each write call appends data at end of file.
7586  * Creates a new file for writing if file does not exist.
7587  *
7588  * "a+" Read-write, each write call appends data at end of file.
7589  * Creates a new file for reading and writing if file does
7590  * not exist.
7591  *
7592  * The following modes must be used separately, and along with one or more of
7593  * the modes seen above.
7594  *
7595  * "b" Binary file mode
7596  * Suppresses EOL <-> CRLF conversion on Windows. And
7597  * sets external encoding to ASCII-8BIT unless explicitly
7598  * specified.
7599  *
7600  * "t" Text file mode
7601  *
7602  * When the open mode of original IO is read only, the mode cannot be
7603  * changed to be writable. Similarly, the open mode cannot be changed from
7604  * write only to readable.
7605  *
7606  * When such a change is attempted the error is raised in different locations
7607  * according to the platform.
7608  *
7609  * === IO Encoding
7610  *
7611  * When +ext_enc+ is specified, strings read will be tagged by the encoding
7612  * when reading, and strings output will be converted to the specified
7613  * encoding when writing.
7614  *
7615  * When +ext_enc+ and +int_enc+ are specified read strings will be converted
7616  * from +ext_enc+ to +int_enc+ upon input, and written strings will be
7617  * converted from +int_enc+ to +ext_enc+ upon output. See Encoding for
7618  * further details of transcoding on input and output.
7619  *
7620  * If "BOM|UTF-8", "BOM|UTF-16LE" or "BOM|UTF16-BE" are used, Ruby checks for
7621  * a Unicode BOM in the input document to help determine the encoding. For
7622  * UTF-16 encodings the file open mode must be binary. When present, the BOM
7623  * is stripped and the external encoding from the BOM is used. When the BOM
7624  * is missing the given Unicode encoding is used as +ext_enc+. (The BOM-set
7625  * encoding option is case insensitive, so "bom|utf-8" is also valid.)
7626  *
7627  * === Options
7628  *
7629  * +opt+ can be used instead of +mode+ for improved readability. The
7630  * following keys are supported:
7631  *
7632  * :mode ::
7633  * Same as +mode+ parameter
7634  *
7635  * :flags ::
7636  * Specifies file open flags as integer.
7637  * If +mode+ parameter is given, this parameter will be bitwise-ORed.
7638  *
7639  * :\external_encoding ::
7640  * External encoding for the IO. "-" is a synonym for the default external
7641  * encoding.
7642  *
7643  * :\internal_encoding ::
7644  * Internal encoding for the IO. "-" is a synonym for the default internal
7645  * encoding.
7646  *
7647  * If the value is +nil+ no conversion occurs.
7648  *
7649  * :encoding ::
7650  * Specifies external and internal encodings as "extern:intern".
7651  *
7652  * :textmode ::
7653  * If the value is truth value, same as "t" in argument +mode+.
7654  *
7655  * :binmode ::
7656  * If the value is truth value, same as "b" in argument +mode+.
7657  *
7658  * :autoclose ::
7659  * If the value is +false+, the +fd+ will be kept open after this IO
7660  * instance gets finalized.
7661  *
7662  * Also, +opt+ can have same keys in String#encode for controlling conversion
7663  * between the external encoding and the internal encoding.
7664  *
7665  * === Example 1
7666  *
7667  * fd = IO.sysopen("/dev/tty", "w")
7668  * a = IO.new(fd,"w")
7669  * $stderr.puts "Hello"
7670  * a.puts "World"
7671  *
7672  * Produces:
7673  *
7674  * Hello
7675  * World
7676  *
7677  * === Example 2
7678  *
7679  * require 'fcntl'
7680  *
7681  * fd = STDERR.fcntl(Fcntl::F_DUPFD)
7682  * io = IO.new(fd, mode: 'w:UTF-16LE', cr_newline: true)
7683  * io.puts "Hello, World!"
7684  *
7685  * fd = STDERR.fcntl(Fcntl::F_DUPFD)
7686  * io = IO.new(fd, mode: 'w', cr_newline: true,
7687  * external_encoding: Encoding::UTF_16LE)
7688  * io.puts "Hello, World!"
7689  *
7690  * Both of above print "Hello, World!" in UTF-16LE to standard error output
7691  * with converting EOL generated by <code>puts</code> to CR.
7692  */
7693 
7694 static VALUE
7696 {
7697  VALUE fnum, vmode;
7698  rb_io_t *fp;
7699  int fd, fmode, oflags = O_RDONLY;
7700  convconfig_t convconfig;
7701  VALUE opt;
7702 #if defined(HAVE_FCNTL) && defined(F_GETFL)
7703  int ofmode;
7704 #else
7705  struct stat st;
7706 #endif
7707 
7708 
7709  argc = rb_scan_args(argc, argv, "11:", &fnum, &vmode, &opt);
7710  rb_io_extract_modeenc(&vmode, 0, opt, &oflags, &fmode, &convconfig);
7711 
7712  fd = NUM2INT(fnum);
7713  if (rb_reserved_fd_p(fd)) {
7714  rb_raise(rb_eArgError, "The given fd is not accessible because RubyVM reserves it");
7715  }
7716 #if defined(HAVE_FCNTL) && defined(F_GETFL)
7717  oflags = fcntl(fd, F_GETFL);
7718  if (oflags == -1) rb_sys_fail(0);
7719 #else
7720  if (fstat(fd, &st) == -1) rb_sys_fail(0);
7721 #endif
7722  rb_update_max_fd(fd);
7723 #if defined(HAVE_FCNTL) && defined(F_GETFL)
7724  ofmode = rb_io_oflags_fmode(oflags);
7725  if (NIL_P(vmode)) {
7726  fmode = ofmode;
7727  }
7728  else if ((~ofmode & fmode) & FMODE_READWRITE) {
7729  VALUE error = INT2FIX(EINVAL);
7731  }
7732 #endif
7733  if (!NIL_P(opt) && rb_hash_aref(opt, sym_autoclose) == Qfalse) {
7734  fmode |= FMODE_PREP;
7735  }
7736  MakeOpenFile(io, fp);
7737  fp->fd = fd;
7738  fp->mode = fmode;
7739  fp->encs = convconfig;
7740  clear_codeconv(fp);
7741  io_check_tty(fp);
7742  if (fileno(stdin) == fd)
7743  fp->stdio_file = stdin;
7744  else if (fileno(stdout) == fd)
7745  fp->stdio_file = stdout;
7746  else if (fileno(stderr) == fd)
7747  fp->stdio_file = stderr;
7748 
7750  return io;
7751 }
7752 
7753 /*
7754  * call-seq:
7755  * File.new(filename, mode="r" [, opt]) -> file
7756  * File.new(filename [, mode [, perm]] [, opt]) -> file
7757  *
7758  * Opens the file named by +filename+ according to the given +mode+ and
7759  * returns a new File object.
7760  *
7761  * See IO.new for a description of +mode+ and +opt+.
7762  *
7763  * If a file is being created, permission bits may be given in +perm+. These
7764  * mode and permission bits are platform dependent; on Unix systems, see
7765  * open(2) and chmod(2) man pages for details.
7766  *
7767  * === Examples
7768  *
7769  * f = File.new("testfile", "r")
7770  * f = File.new("newfile", "w+")
7771  * f = File.new("newfile", File::CREAT|File::TRUNC|File::RDWR, 0644)
7772  */
7773 
7774 static VALUE
7776 {
7777  if (RFILE(io)->fptr) {
7778  rb_raise(rb_eRuntimeError, "reinitializing File");
7779  }
7780  if (0 < argc && argc < 3) {
7781  VALUE fd = rb_check_to_int(argv[0]);
7782 
7783  if (!NIL_P(fd)) {
7784  argv[0] = fd;
7785  return rb_io_initialize(argc, argv, io);
7786  }
7787  }
7788  rb_open_file(argc, argv, io);
7789 
7790  return io;
7791 }
7792 
7793 /* :nodoc: */
7794 static VALUE
7796 {
7797  if (rb_block_given_p()) {
7798  VALUE cname = rb_obj_as_string(klass);
7799 
7800  rb_warn("%"PRIsVALUE"::new() does not take block; use %"PRIsVALUE"::open() instead",
7801  cname, cname);
7802  }
7803  return rb_class_new_instance(argc, argv, klass);
7804 }
7805 
7806 
7807 /*
7808  * call-seq:
7809  * IO.for_fd(fd, mode [, opt]) -> io
7810  *
7811  * Synonym for <code>IO.new</code>.
7812  *
7813  */
7814 
7815 static VALUE
7817 {
7818  VALUE io = rb_obj_alloc(klass);
7819  rb_io_initialize(argc, argv, io);
7820  return io;
7821 }
7822 
7823 /*
7824  * call-seq:
7825  * ios.autoclose? -> true or false
7826  *
7827  * Returns +true+ if the underlying file descriptor of _ios_ will be
7828  * closed automatically at its finalization, otherwise +false+.
7829  */
7830 
7831 static VALUE
7833 {
7834  rb_io_t *fptr = RFILE(io)->fptr;
7835  rb_io_check_closed(fptr);
7836  return (fptr->mode & FMODE_PREP) ? Qfalse : Qtrue;
7837 }
7838 
7839 /*
7840  * call-seq:
7841  * io.autoclose = bool -> true or false
7842  *
7843  * Sets auto-close flag.
7844  *
7845  * f = open("/dev/null")
7846  * IO.for_fd(f.fileno)
7847  * # ...
7848  * f.gets # may cause IOError
7849  *
7850  * f = open("/dev/null")
7851  * IO.for_fd(f.fileno).autoclose = true
7852  * # ...
7853  * f.gets # won't cause IOError
7854  */
7855 
7856 static VALUE
7858 {
7859  rb_io_t *fptr;
7860  GetOpenFile(io, fptr);
7861  if (!RTEST(autoclose))
7862  fptr->mode |= FMODE_PREP;
7863  else
7864  fptr->mode &= ~FMODE_PREP;
7865  return io;
7866 }
7867 
7868 static void
7869 argf_mark(void *ptr)
7870 {
7871  struct argf *p = ptr;
7872  rb_gc_mark(p->filename);
7874  rb_gc_mark(p->argv);
7875  rb_gc_mark(p->encs.ecopts);
7876 }
7877 
7878 static void
7879 argf_free(void *ptr)
7880 {
7881  struct argf *p = ptr;
7882  xfree(p->inplace);
7883  xfree(p);
7884 }
7885 
7886 static size_t
7887 argf_memsize(const void *ptr)
7888 {
7889  const struct argf *p = ptr;
7890  size_t size = sizeof(*p);
7891  if (p->inplace) size += strlen(p->inplace) + 1;
7892  return size;
7893 }
7894 
7895 static const rb_data_type_t argf_type = {
7896  "ARGF",
7899 };
7900 
7901 static inline void
7902 argf_init(struct argf *p, VALUE v)
7903 {
7904  p->filename = Qnil;
7905  p->current_file = Qnil;
7906  p->lineno = 0;
7907  p->argv = v;
7908 }
7909 
7910 static VALUE
7912 {
7913  struct argf *p;
7914  VALUE argf = TypedData_Make_Struct(klass, struct argf, &argf_type, p);
7915 
7916  argf_init(p, Qnil);
7917  return argf;
7918 }
7919 
7920 #undef rb_argv
7921 
7922 /* :nodoc: */
7923 static VALUE
7925 {
7926  memset(&ARGF, 0, sizeof(ARGF));
7927  argf_init(&ARGF, argv);
7928 
7929  return argf;
7930 }
7931 
7932 /* :nodoc: */
7933 static VALUE
7935 {
7936  if (!OBJ_INIT_COPY(argf, orig)) return argf;
7937  ARGF = argf_of(orig);
7938  ARGF.argv = rb_obj_dup(ARGF.argv);
7939  if (ARGF.inplace) {
7940  const char *inplace = ARGF.inplace;
7941  ARGF.inplace = 0;
7942  ARGF.inplace = ruby_strdup(inplace);
7943  }
7944  return argf;
7945 }
7946 
7947 /*
7948  * call-seq:
7949  * ARGF.lineno = integer -> integer
7950  *
7951  * Sets the line number of +ARGF+ as a whole to the given +Integer+.
7952  *
7953  * +ARGF+ sets the line number automatically as you read data, so normally
7954  * you will not need to set it explicitly. To access the current line number
7955  * use +ARGF.lineno+.
7956  *
7957  * For example:
7958  *
7959  * ARGF.lineno #=> 0
7960  * ARGF.readline #=> "This is line 1\n"
7961  * ARGF.lineno #=> 1
7962  * ARGF.lineno = 0 #=> 0
7963  * ARGF.lineno #=> 0
7964  */
7965 static VALUE
7967 {
7968  ARGF.lineno = NUM2INT(val);
7969  ARGF.last_lineno = ARGF.lineno;
7970  return Qnil;
7971 }
7972 
7973 /*
7974  * call-seq:
7975  * ARGF.lineno -> integer
7976  *
7977  * Returns the current line number of ARGF as a whole. This value
7978  * can be set manually with +ARGF.lineno=+.
7979  *
7980  * For example:
7981  *
7982  * ARGF.lineno #=> 0
7983  * ARGF.readline #=> "This is line 1\n"
7984  * ARGF.lineno #=> 1
7985  */
7986 static VALUE
7988 {
7989  return INT2FIX(ARGF.lineno);
7990 }
7991 
7992 static VALUE
7994 {
7995  return rb_funcall3(ARGF.current_file, rb_frame_this_func(), argc, argv);
7996 }
7997 
7998 #define next_argv() argf_next_argv(argf)
7999 #define ARGF_GENERIC_INPUT_P() \
8000  (ARGF.current_file == rb_stdin && !RB_TYPE_P(ARGF.current_file, T_FILE))
8001 #define ARGF_FORWARD(argc, argv) do {\
8002  if (ARGF_GENERIC_INPUT_P())\
8003  return argf_forward((argc), (argv), argf);\
8004 } while (0)
8005 #define NEXT_ARGF_FORWARD(argc, argv) do {\
8006  if (!next_argv()) return Qnil;\
8007  ARGF_FORWARD((argc), (argv));\
8008 } while (0)
8009 
8010 static void
8012 {
8013  VALUE file = ARGF.current_file;
8014  if (file == rb_stdin) return;
8015  if (RB_TYPE_P(file, T_FILE)) {
8016  rb_io_set_write_io(file, Qnil);
8017  }
8018  io_close(file);
8019  ARGF.init_p = -1;
8020 }
8021 
8022 static int
8024 {
8025  char *fn;
8026  rb_io_t *fptr;
8027  int stdout_binmode = 0;
8028  int fmode;
8029 
8030  if (RB_TYPE_P(rb_stdout, T_FILE)) {
8031  GetOpenFile(rb_stdout, fptr);
8032  if (fptr->mode & FMODE_BINMODE)
8033  stdout_binmode = 1;
8034  }
8035 
8036  if (ARGF.init_p == 0) {
8037  if (!NIL_P(ARGF.argv) && RARRAY_LEN(ARGF.argv) > 0) {
8038  ARGF.next_p = 1;
8039  }
8040  else {
8041  ARGF.next_p = -1;
8042  }
8043  ARGF.init_p = 1;
8044  }
8045  else {
8046  if (NIL_P(ARGF.argv)) {
8047  ARGF.next_p = -1;
8048  }
8049  else if (ARGF.next_p == -1 && RARRAY_LEN(ARGF.argv) > 0) {
8050  ARGF.next_p = 1;
8051  }
8052  }
8053 
8054  if (ARGF.next_p == 1) {
8055  if (ARGF.init_p == 1) argf_close(argf);
8056  retry:
8057  if (RARRAY_LEN(ARGF.argv) > 0) {
8058  VALUE filename = rb_ary_shift(ARGF.argv);
8059  StringValueCStr(filename);
8060  ARGF.filename = rb_str_encode_ospath(filename);
8061  fn = StringValueCStr(filename);
8062  if (RSTRING_LEN(filename) == 1 && fn[0] == '-') {
8063  ARGF.current_file = rb_stdin;
8064  if (ARGF.inplace) {
8065  rb_warn("Can't do inplace edit for stdio; skipping");
8066  goto retry;
8067  }
8068  }
8069  else {
8070  VALUE write_io = Qnil;
8071  int fr = rb_sysopen(filename, O_RDONLY, 0);
8072 
8073  if (ARGF.inplace) {
8074  struct stat st;
8075 #ifndef NO_SAFE_RENAME
8076  struct stat st2;
8077 #endif
8078  VALUE str;
8079  int fw;
8080 
8083  }
8084  fstat(fr, &st);
8085  str = filename;
8086  if (*ARGF.inplace) {
8087  str = rb_str_dup(str);
8088  rb_str_cat2(str, ARGF.inplace);
8089  /* TODO: encoding of ARGF.inplace */
8090 #ifdef NO_SAFE_RENAME
8091  (void)close(fr);
8092  (void)unlink(RSTRING_PTR(str));
8093  if (rename(fn, RSTRING_PTR(str)) < 0) {
8094  rb_warn("Can't rename %"PRIsVALUE" to %"PRIsVALUE": %s, skipping file",
8095  filename, str, strerror(errno));
8096  goto retry;
8097  }
8098  fr = rb_sysopen(str, O_RDONLY, 0);
8099 #else
8100  if (rename(fn, RSTRING_PTR(str)) < 0) {
8101  rb_warn("Can't rename %"PRIsVALUE" to %"PRIsVALUE": %s, skipping file",
8102  filename, str, strerror(errno));
8103  close(fr);
8104  goto retry;
8105  }
8106 #endif
8107  }
8108  else {
8109 #ifdef NO_SAFE_RENAME
8110  rb_fatal("Can't do inplace edit without backup");
8111 #else
8112  if (unlink(fn) < 0) {
8113  rb_warn("Can't remove %"PRIsVALUE": %s, skipping file",
8114  filename, strerror(errno));
8115  close(fr);
8116  goto retry;
8117  }
8118 #endif
8119  }
8120  fw = rb_sysopen(filename, O_WRONLY|O_CREAT|O_TRUNC, 0666);
8121 #ifndef NO_SAFE_RENAME
8122  fstat(fw, &st2);
8123 #ifdef HAVE_FCHMOD
8124  fchmod(fw, st.st_mode);
8125 #else
8126  chmod(fn, st.st_mode);
8127 #endif
8128  if (st.st_uid!=st2.st_uid || st.st_gid!=st2.st_gid) {
8129  int err;
8130 #ifdef HAVE_FCHOWN
8131  err = fchown(fw, st.st_uid, st.st_gid);
8132 #else
8133  err = chown(fn, st.st_uid, st.st_gid);
8134 #endif
8135  if (err && getuid() == 0 && st2.st_uid == 0) {
8136  const char *wkfn = RSTRING_PTR(filename);
8137  rb_warn("Can't set owner/group of %"PRIsVALUE" to same as %"PRIsVALUE": %s, skipping file",
8138  filename, str, strerror(errno));
8139  (void)close(fr);
8140  (void)close(fw);
8141  (void)unlink(wkfn);
8142  goto retry;
8143  }
8144  }
8145 #endif
8146  write_io = prep_io(fw, FMODE_WRITABLE, rb_cFile, fn);
8147  rb_stdout = write_io;
8148  if (stdout_binmode) rb_io_binmode(rb_stdout);
8149  }
8150  fmode = FMODE_READABLE;
8151  if (!ARGF.binmode) {
8152  fmode |= DEFAULT_TEXTMODE;
8153  }
8154  ARGF.current_file = prep_io(fr, fmode, rb_cFile, fn);
8155  if (!NIL_P(write_io)) {
8156  rb_io_set_write_io(ARGF.current_file, write_io);
8157  }
8158  }
8159  if (ARGF.binmode) rb_io_ascii8bit_binmode(ARGF.current_file);
8160  GetOpenFile(ARGF.current_file, fptr);
8161  if (ARGF.encs.enc) {
8162  fptr->encs = ARGF.encs;
8163  clear_codeconv(fptr);
8164  }
8165  else {
8167  if (!ARGF.binmode) {
8169 #ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE
8170  fptr->encs.ecflags |= TEXTMODE_NEWLINE_DECORATOR_ON_WRITE;
8171 #endif
8172  }
8173  }
8174  ARGF.next_p = 0;
8175  }
8176  else {
8177  ARGF.next_p = 1;
8178  return FALSE;
8179  }
8180  }
8181  else if (ARGF.next_p == -1) {
8182  ARGF.current_file = rb_stdin;
8183  ARGF.filename = rb_str_new2("-");
8184  if (ARGF.inplace) {
8185  rb_warn("Can't do inplace edit for stdio");
8187  }
8188  }
8189  if (ARGF.init_p == -1) ARGF.init_p = 1;
8190  return TRUE;
8191 }
8192 
8193 static VALUE
8195 {
8196  VALUE line;
8197  long lineno = ARGF.lineno;
8198 
8199  retry:
8200  if (!next_argv()) return Qnil;
8201  if (ARGF_GENERIC_INPUT_P()) {
8202  line = rb_funcall3(ARGF.current_file, idGets, argc, argv);
8203  }
8204  else {
8205  if (argc == 0 && rb_rs == rb_default_rs) {
8206  line = rb_io_gets(ARGF.current_file);
8207  }
8208  else {
8209  line = rb_io_getline(argc, argv, ARGF.current_file);
8210  }
8211  if (NIL_P(line) && ARGF.next_p != -1) {
8212  argf_close(argf);
8213  ARGF.next_p = 1;
8214  goto retry;
8215  }
8216  }
8217  if (!NIL_P(line)) {
8218  ARGF.lineno = ++lineno;
8219  ARGF.last_lineno = ARGF.lineno;
8220  }
8221  return line;
8222 }
8223 
8224 static VALUE
8226 {
8227  VALUE argf = *var;
8228  return INT2FIX(ARGF.last_lineno);
8229 }
8230 
8231 static void
8233 {
8234  VALUE argf = *var;
8235  int n = NUM2INT(val);
8236  ARGF.last_lineno = ARGF.lineno = n;
8237 }
8238 
8239 static VALUE argf_gets(int, VALUE *, VALUE);
8240 
8241 /*
8242  * call-seq:
8243  * gets(sep=$/) -> string or nil
8244  * gets(limit) -> string or nil
8245  * gets(sep, limit) -> string or nil
8246  *
8247  * Returns (and assigns to <code>$_</code>) the next line from the list
8248  * of files in +ARGV+ (or <code>$*</code>), or from standard input if
8249  * no files are present on the command line. Returns +nil+ at end of
8250  * file. The optional argument specifies the record separator. The
8251  * separator is included with the contents of each record. A separator
8252  * of +nil+ reads the entire contents, and a zero-length separator
8253  * reads the input one paragraph at a time, where paragraphs are
8254  * divided by two consecutive newlines. If the first argument is an
8255  * integer, or optional second argument is given, the returning string
8256  * would not be longer than the given value in bytes. If multiple
8257  * filenames are present in +ARGV+, <code>gets(nil)</code> will read
8258  * the contents one file at a time.
8259  *
8260  * ARGV << "testfile"
8261  * print while gets
8262  *
8263  * <em>produces:</em>
8264  *
8265  * This is line one
8266  * This is line two
8267  * This is line three
8268  * And so on...
8269  *
8270  * The style of programming using <code>$_</code> as an implicit
8271  * parameter is gradually losing favor in the Ruby community.
8272  */
8273 
8274 static VALUE
8276 {
8277  if (recv == argf) {
8278  return argf_gets(argc, argv, argf);
8279  }
8280  return rb_funcallv(argf, idGets, argc, argv);
8281 }
8282 
8283 /*
8284  * call-seq:
8285  * ARGF.gets(sep=$/) -> string or nil
8286  * ARGF.gets(limit) -> string or nil
8287  * ARGF.gets(sep, limit) -> string or nil
8288  *
8289  * Returns the next line from the current file in +ARGF+.
8290  *
8291  * By default lines are assumed to be separated by <code>$/</code>;
8292  * to use a different character as a separator, supply it as a +String+
8293  * for the _sep_ argument.
8294  *
8295  * The optional _limit_ argument specifies how many characters of each line
8296  * to return. By default all characters are returned.
8297  *
8298  */
8299 static VALUE
8301 {
8302  VALUE line;
8303 
8304  line = argf_getline(argc, argv, argf);
8305  rb_lastline_set(line);
8306 
8307  return line;
8308 }
8309 
8310 VALUE
8311 rb_gets(void)
8312 {
8313  VALUE line;
8314 
8315  if (rb_rs != rb_default_rs) {
8316  return rb_f_gets(0, 0, argf);
8317  }
8318 
8319  retry:
8320  if (!next_argv()) return Qnil;
8321  line = rb_io_gets(ARGF.current_file);
8322  if (NIL_P(line) && ARGF.next_p != -1) {
8323  rb_io_close(ARGF.current_file);
8324  ARGF.next_p = 1;
8325  goto retry;
8326  }
8327  rb_lastline_set(line);
8328  if (!NIL_P(line)) {
8329  ARGF.lineno++;
8330  ARGF.last_lineno = ARGF.lineno;
8331  }
8332 
8333  return line;
8334 }
8335 
8336 static VALUE argf_readline(int, VALUE *, VALUE);
8337 
8338 /*
8339  * call-seq:
8340  * readline(sep=$/) -> string
8341  * readline(limit) -> string
8342  * readline(sep, limit) -> string
8343  *
8344  * Equivalent to <code>Kernel::gets</code>, except
8345  * +readline+ raises +EOFError+ at end of file.
8346  */
8347 
8348 static VALUE
8350 {
8351  if (recv == argf) {
8352  return argf_readline(argc, argv, argf);
8353  }
8354  return rb_funcallv(argf, rb_intern("readline"), argc, argv);
8355 }
8356 
8357 
8358 /*
8359  * call-seq:
8360  * ARGF.readline(sep=$/) -> string
8361  * ARGF.readline(limit) -> string
8362  * ARGF.readline(sep, limit) -> string
8363  *
8364  * Returns the next line from the current file in +ARGF+.
8365  *
8366  * By default lines are assumed to be separated by <code>$/</code>;
8367  * to use a different character as a separator, supply it as a +String+
8368  * for the _sep_ argument.
8369  *
8370  * The optional _limit_ argument specifies how many characters of each line
8371  * to return. By default all characters are returned.
8372  *
8373  * An +EOFError+ is raised at the end of the file.
8374  */
8375 static VALUE
8377 {
8378  VALUE line;
8379 
8380  if (!next_argv()) rb_eof_error();
8381  ARGF_FORWARD(argc, argv);
8382  line = argf_gets(argc, argv, argf);
8383  if (NIL_P(line)) {
8384  rb_eof_error();
8385  }
8386 
8387  return line;
8388 }
8389 
8390 static VALUE argf_readlines(int, VALUE *, VALUE);
8391 
8392 /*
8393  * call-seq:
8394  * readlines(sep=$/) -> array
8395  * readlines(limit) -> array
8396  * readlines(sep, limit) -> array
8397  *
8398  * Returns an array containing the lines returned by calling
8399  * <code>Kernel.gets(<i>sep</i>)</code> until the end of file.
8400  */
8401 
8402 static VALUE
8404 {
8405  if (recv == argf) {
8406  return argf_readlines(argc, argv, argf);
8407  }
8408  return rb_funcallv(argf, rb_intern("readlines"), argc, argv);
8409 }
8410 
8411 /*
8412  * call-seq:
8413  * ARGF.readlines(sep=$/) -> array
8414  * ARGF.readlines(limit) -> array
8415  * ARGF.readlines(sep, limit) -> array
8416  *
8417  * ARGF.to_a(sep=$/) -> array
8418  * ARGF.to_a(limit) -> array
8419  * ARGF.to_a(sep, limit) -> array
8420  *
8421  * Reads +ARGF+'s current file in its entirety, returning an +Array+ of its
8422  * lines, one line per element. Lines are assumed to be separated by _sep_.
8423  *
8424  * lines = ARGF.readlines
8425  * lines[0] #=> "This is line one\n"
8426  */
8427 static VALUE
8429 {
8430  long lineno = ARGF.lineno;
8431  VALUE lines, ary;
8432 
8433  ary = rb_ary_new();
8434  while (next_argv()) {
8435  if (ARGF_GENERIC_INPUT_P()) {
8436  lines = rb_funcall3(ARGF.current_file, rb_intern("readlines"), argc, argv);
8437  }
8438  else {
8439  lines = rb_io_readlines(argc, argv, ARGF.current_file);
8440  argf_close(argf);
8441  }
8442  ARGF.next_p = 1;
8443  rb_ary_concat(ary, lines);
8444  ARGF.lineno = lineno + RARRAY_LEN(ary);
8445  ARGF.last_lineno = ARGF.lineno;
8446  }
8447  ARGF.init_p = 0;
8448  return ary;
8449 }
8450 
8451 /*
8452  * call-seq:
8453  * `cmd` -> string
8454  *
8455  * Returns the standard output of running _cmd_ in a subshell.
8456  * The built-in syntax <code>%x{...}</code> uses
8457  * this method. Sets <code>$?</code> to the process status.
8458  *
8459  * `date` #=> "Wed Apr 9 08:56:30 CDT 2003\n"
8460  * `ls testdir`.split[1] #=> "main.rb"
8461  * `echo oops && exit 99` #=> "oops\n"
8462  * $?.exitstatus #=> 99
8463  */
8464 
8465 static VALUE
8467 {
8468  VALUE port;
8469  VALUE result;
8470  rb_io_t *fptr;
8471 
8472  SafeStringValue(str);
8474  port = pipe_open_s(str, "r", FMODE_READABLE|DEFAULT_TEXTMODE, NULL);
8475  if (NIL_P(port)) return rb_str_new(0,0);
8476 
8477  GetOpenFile(port, fptr);
8478  result = read_all(fptr, remain_size(fptr), Qnil);
8479  rb_io_close(port);
8480  rb_io_fptr_finalize(fptr);
8481  rb_gc_force_recycle(port); /* also guards from premature GC */
8482 
8483  return result;
8484 }
8485 
8486 #ifdef HAVE_SYS_SELECT_H
8487 #include <sys/select.h>
8488 #endif
8489 
8490 static VALUE
8491 select_internal(VALUE read, VALUE write, VALUE except, struct timeval *tp, rb_fdset_t *fds)
8492 {
8493  VALUE res, list;
8494  rb_fdset_t *rp, *wp, *ep;
8495  rb_io_t *fptr;
8496  long i;
8497  int max = 0, n;
8498  int pending = 0;
8499  struct timeval timerec;
8500 
8501  if (!NIL_P(read)) {
8502  Check_Type(read, T_ARRAY);
8503  for (i=0; i<RARRAY_LEN(read); i++) {
8504  GetOpenFile(rb_io_get_io(RARRAY_AREF(read, i)), fptr);
8505  rb_fd_set(fptr->fd, &fds[0]);
8506  if (READ_DATA_PENDING(fptr) || READ_CHAR_PENDING(fptr)) { /* check for buffered data */
8507  pending++;
8508  rb_fd_set(fptr->fd, &fds[3]);
8509  }
8510  if (max < fptr->fd) max = fptr->fd;
8511  }
8512  if (pending) { /* no blocking if there's buffered data */
8513  timerec.tv_sec = timerec.tv_usec = 0;
8514  tp = &timerec;
8515  }
8516  rp = &fds[0];
8517  }
8518  else
8519  rp = 0;
8520 
8521  if (!NIL_P(write)) {
8522  Check_Type(write, T_ARRAY);
8523  for (i=0; i<RARRAY_LEN(write); i++) {
8524  VALUE write_io = GetWriteIO(rb_io_get_io(RARRAY_AREF(write, i)));
8525  GetOpenFile(write_io, fptr);
8526  rb_fd_set(fptr->fd, &fds[1]);
8527  if (max < fptr->fd) max = fptr->fd;
8528  }
8529  wp = &fds[1];
8530  }
8531  else
8532  wp = 0;
8533 
8534  if (!NIL_P(except)) {
8535  Check_Type(except, T_ARRAY);
8536  for (i=0; i<RARRAY_LEN(except); i++) {
8537  VALUE io = rb_io_get_io(RARRAY_AREF(except, i));
8538  VALUE write_io = GetWriteIO(io);
8539  GetOpenFile(io, fptr);
8540  rb_fd_set(fptr->fd, &fds[2]);
8541  if (max < fptr->fd) max = fptr->fd;
8542  if (io != write_io) {
8543  GetOpenFile(write_io, fptr);
8544  rb_fd_set(fptr->fd, &fds[2]);
8545  if (max < fptr->fd) max = fptr->fd;
8546  }
8547  }
8548  ep = &fds[2];
8549  }
8550  else {
8551  ep = 0;
8552  }
8553 
8554  max++;
8555 
8556  n = rb_thread_fd_select(max, rp, wp, ep, tp);
8557  if (n < 0) {
8558  rb_sys_fail(0);
8559  }
8560  if (!pending && n == 0) return Qnil; /* returns nil on timeout */
8561 
8562  res = rb_ary_new2(3);
8563  rb_ary_push(res, rp?rb_ary_new():rb_ary_new2(0));
8564  rb_ary_push(res, wp?rb_ary_new():rb_ary_new2(0));
8565  rb_ary_push(res, ep?rb_ary_new():rb_ary_new2(0));
8566 
8567  if (rp) {
8568  list = RARRAY_AREF(res, 0);
8569  for (i=0; i< RARRAY_LEN(read); i++) {
8570  VALUE obj = rb_ary_entry(read, i);
8571  VALUE io = rb_io_get_io(obj);
8572  GetOpenFile(io, fptr);
8573  if (rb_fd_isset(fptr->fd, &fds[0]) ||
8574  rb_fd_isset(fptr->fd, &fds[3])) {
8575  rb_ary_push(list, obj);
8576  }
8577  }
8578  }
8579 
8580  if (wp) {
8581  list = RARRAY_AREF(res, 1);
8582  for (i=0; i< RARRAY_LEN(write); i++) {
8583  VALUE obj = rb_ary_entry(write, i);
8584  VALUE io = rb_io_get_io(obj);
8585  VALUE write_io = GetWriteIO(io);
8586  GetOpenFile(write_io, fptr);
8587  if (rb_fd_isset(fptr->fd, &fds[1])) {
8588  rb_ary_push(list, obj);
8589  }
8590  }
8591  }
8592 
8593  if (ep) {
8594  list = RARRAY_AREF(res, 2);
8595  for (i=0; i< RARRAY_LEN(except); i++) {
8596  VALUE obj = rb_ary_entry(except, i);
8597  VALUE io = rb_io_get_io(obj);
8598  VALUE write_io = GetWriteIO(io);
8599  GetOpenFile(io, fptr);
8600  if (rb_fd_isset(fptr->fd, &fds[2])) {
8601  rb_ary_push(list, obj);
8602  }
8603  else if (io != write_io) {
8604  GetOpenFile(write_io, fptr);
8605  if (rb_fd_isset(fptr->fd, &fds[2])) {
8606  rb_ary_push(list, obj);
8607  }
8608  }
8609  }
8610  }
8611 
8612  return res; /* returns an empty array on interrupt */
8613 }
8614 
8615 struct select_args {
8616  VALUE read, write, except;
8617  struct timeval *timeout;
8618  rb_fdset_t fdsets[4];
8619 };
8620 
8621 static VALUE
8623 {
8624  struct select_args *p = (struct select_args *)arg;
8625 
8626  return select_internal(p->read, p->write, p->except, p->timeout, p->fdsets);
8627 }
8628 
8629 static VALUE
8631 {
8632  struct select_args *p = (struct select_args *)arg;
8633  int i;
8634 
8635  for (i = 0; i < numberof(p->fdsets); ++i)
8636  rb_fd_term(&p->fdsets[i]);
8637  return Qnil;
8638 }
8639 
8642 
8643 #ifdef HAVE_POSIX_FADVISE
8644 struct io_advise_struct {
8645  int fd;
8646  int advice;
8647  off_t offset;
8648  off_t len;
8649 };
8650 
8651 static VALUE
8652 io_advise_internal(void *arg)
8653 {
8654  struct io_advise_struct *ptr = arg;
8655  return posix_fadvise(ptr->fd, ptr->offset, ptr->len, ptr->advice);
8656 }
8657 
8658 static VALUE
8659 io_advise_sym_to_const(VALUE sym)
8660 {
8661 #ifdef POSIX_FADV_NORMAL
8662  if (sym == sym_normal)
8663  return INT2NUM(POSIX_FADV_NORMAL);
8664 #endif
8665 
8666 #ifdef POSIX_FADV_RANDOM
8667  if (sym == sym_random)
8668  return INT2NUM(POSIX_FADV_RANDOM);
8669 #endif
8670 
8671 #ifdef POSIX_FADV_SEQUENTIAL
8672  if (sym == sym_sequential)
8673  return INT2NUM(POSIX_FADV_SEQUENTIAL);
8674 #endif
8675 
8676 #ifdef POSIX_FADV_WILLNEED
8677  if (sym == sym_willneed)
8678  return INT2NUM(POSIX_FADV_WILLNEED);
8679 #endif
8680 
8681 #ifdef POSIX_FADV_DONTNEED
8682  if (sym == sym_dontneed)
8683  return INT2NUM(POSIX_FADV_DONTNEED);
8684 #endif
8685 
8686 #ifdef POSIX_FADV_NOREUSE
8687  if (sym == sym_noreuse)
8688  return INT2NUM(POSIX_FADV_NOREUSE);
8689 #endif
8690 
8691  return Qnil;
8692 }
8693 
8694 static VALUE
8695 do_io_advise(rb_io_t *fptr, VALUE advice, off_t offset, off_t len)
8696 {
8697  int rv;
8698  struct io_advise_struct ias;
8699  VALUE num_adv;
8700 
8701  num_adv = io_advise_sym_to_const(advice);
8702 
8703  /*
8704  * The platform doesn't support this hint. We don't raise exception, instead
8705  * silently ignore it. Because IO::advise is only hint.
8706  */
8707  if (NIL_P(num_adv))
8708  return Qnil;
8709 
8710  ias.fd = fptr->fd;
8711  ias.advice = NUM2INT(num_adv);
8712  ias.offset = offset;
8713  ias.len = len;
8714 
8715  rv = (int)rb_thread_io_blocking_region(io_advise_internal, &ias, fptr->fd);
8716  if (rv && rv != ENOSYS) {
8717  /* posix_fadvise(2) doesn't set errno. On success it returns 0; otherwise
8718  it returns the error code. */
8719  VALUE message = rb_sprintf("%"PRIsVALUE" "
8720  "(%"PRI_OFFT_PREFIX"d, "
8721  "%"PRI_OFFT_PREFIX"d, "
8722  "%"PRIsVALUE")",
8723  fptr->pathv, offset, len, advice);
8724  rb_syserr_fail_str(rv, message);
8725  }
8726 
8727  return Qnil;
8728 }
8729 
8730 #endif /* HAVE_POSIX_FADVISE */
8731 
8732 static void
8734 {
8735  if (!SYMBOL_P(advice))
8736  rb_raise(rb_eTypeError, "advice must be a Symbol");
8737 
8738  if (advice != sym_normal &&
8739  advice != sym_sequential &&
8740  advice != sym_random &&
8741  advice != sym_willneed &&
8742  advice != sym_dontneed &&
8743  advice != sym_noreuse) {
8744  rb_raise(rb_eNotImpError, "Unsupported advice: %+"PRIsVALUE, advice);
8745  }
8746 }
8747 
8748 /*
8749  * call-seq:
8750  * ios.advise(advice, offset=0, len=0) -> nil
8751  *
8752  * Announce an intention to access data from the current file in a
8753  * specific pattern. On platforms that do not support the
8754  * <em>posix_fadvise(2)</em> system call, this method is a no-op.
8755  *
8756  * _advice_ is one of the following symbols:
8757  *
8758  * :normal:: No advice to give; the default assumption for an open file.
8759  * :sequential:: The data will be accessed sequentially
8760  * with lower offsets read before higher ones.
8761  * :random:: The data will be accessed in random order.
8762  * :willneed:: The data will be accessed in the near future.
8763  * :dontneed:: The data will not be accessed in the near future.
8764  * :noreuse:: The data will only be accessed once.
8765  *
8766  * The semantics of a piece of advice are platform-dependent. See
8767  * <em>man 2 posix_fadvise</em> for details.
8768  *
8769  * "data" means the region of the current file that begins at
8770  * _offset_ and extends for _len_ bytes. If _len_ is 0, the region
8771  * ends at the last byte of the file. By default, both _offset_ and
8772  * _len_ are 0, meaning that the advice applies to the entire file.
8773  *
8774  * If an error occurs, one of the following exceptions will be raised:
8775  *
8776  * <code>IOError</code>:: The <code>IO</code> stream is closed.
8777  * <code>Errno::EBADF</code>::
8778  * The file descriptor of the current file is invalid.
8779  * <code>Errno::EINVAL</code>:: An invalid value for _advice_ was given.
8780  * <code>Errno::ESPIPE</code>::
8781  * The file descriptor of the current file refers to a FIFO or
8782  * pipe. (Linux raises <code>Errno::EINVAL</code> in this case).
8783  * <code>TypeError</code>::
8784  * Either _advice_ was not a Symbol, or one of the
8785  * other arguments was not an <code>Integer</code>.
8786  * <code>RangeError</code>:: One of the arguments given was too big/small.
8787  *
8788  * This list is not exhaustive; other Errno:: exceptions are also possible.
8789  */
8790 static VALUE
8792 {
8793  VALUE advice, offset, len;
8794  off_t off, l;
8795  rb_io_t *fptr;
8796 
8797  rb_scan_args(argc, argv, "12", &advice, &offset, &len);
8798  advice_arg_check(advice);
8799 
8800  io = GetWriteIO(io);
8801  GetOpenFile(io, fptr);
8802 
8803  off = NIL_P(offset) ? 0 : NUM2OFFT(offset);
8804  l = NIL_P(len) ? 0 : NUM2OFFT(len);
8805 
8806 #ifdef HAVE_POSIX_FADVISE
8807  return do_io_advise(fptr, advice, off, l);
8808 #else
8809  ((void)off, (void)l); /* Ignore all hint */
8810  return Qnil;
8811 #endif
8812 }
8813 
8814 /*
8815  * call-seq:
8816  * IO.select(read_array [, write_array [, error_array [, timeout]]]) -> array or nil
8817  *
8818  * Calls select(2) system call.
8819  * It monitors given arrays of <code>IO</code> objects, waits until one or more
8820  * of <code>IO</code> objects are ready for reading, are ready for writing,
8821  * and have pending exceptions respectively, and returns an array that
8822  * contains arrays of those IO objects. It will return +nil+
8823  * if optional <i>timeout</i> value is given and no <code>IO</code> object
8824  * is ready in <i>timeout</i> seconds.
8825  *
8826  * <code>IO.select</code> peeks the buffer of <code>IO</code> objects for testing readability.
8827  * If the <code>IO</code> buffer is not empty,
8828  * <code>IO.select</code> immediately notifies readability.
8829  * This "peek" only happens for <code>IO</code> objects.
8830  * It does not happen for IO-like objects such as OpenSSL::SSL::SSLSocket.
8831  *
8832  * The best way to use <code>IO.select</code> is invoking it
8833  * after nonblocking methods such as <code>read_nonblock</code>, <code>write_nonblock</code>, etc.
8834  * The methods raise an exception which is extended by
8835  * <code>IO::WaitReadable</code> or <code>IO::WaitWritable</code>.
8836  * The modules notify how the caller should wait with <code>IO.select</code>.
8837  * If <code>IO::WaitReadable</code> is raised, the caller should wait for reading.
8838  * If <code>IO::WaitWritable</code> is raised, the caller should wait for writing.
8839  *
8840  * So, blocking read (<code>readpartial</code>) can be emulated using
8841  * <code>read_nonblock</code> and <code>IO.select</code> as follows:
8842  *
8843  * begin
8844  * result = io_like.read_nonblock(maxlen)
8845  * rescue IO::WaitReadable
8846  * IO.select([io_like])
8847  * retry
8848  * rescue IO::WaitWritable
8849  * IO.select(nil, [io_like])
8850  * retry
8851  * end
8852  *
8853  * Especially, the combination of nonblocking methods and
8854  * <code>IO.select</code> is preferred for <code>IO</code> like
8855  * objects such as <code>OpenSSL::SSL::SSLSocket</code>.
8856  * It has <code>to_io</code> method to return underlying <code>IO</code> object.
8857  * <code>IO.select</code> calls <code>to_io</code> to obtain the file descriptor to wait.
8858  *
8859  * This means that readability notified by <code>IO.select</code> doesn't mean
8860  * readability from <code>OpenSSL::SSL::SSLSocket</code> object.
8861  *
8862  * The most likely situation is that <code>OpenSSL::SSL::SSLSocket</code> buffers some data.
8863  * <code>IO.select</code> doesn't see the buffer.
8864  * So <code>IO.select</code> can block when <code>OpenSSL::SSL::SSLSocket#readpartial</code> doesn't block.
8865  *
8866  * However, several more complicated situations exist.
8867  *
8868  * SSL is a protocol which is sequence of records.
8869  * The record consists of multiple bytes.
8870  * So, the remote side of SSL sends a partial record,
8871  * <code>IO.select</code> notifies readability but
8872  * <code>OpenSSL::SSL::SSLSocket</code> cannot decrypt a byte and
8873  * <code>OpenSSL::SSL::SSLSocket#readpartial</code> will blocks.
8874  *
8875  * Also, the remote side can request SSL renegotiation which forces
8876  * the local SSL engine to write some data.
8877  * This means <code>OpenSSL::SSL::SSLSocket#readpartial</code> may
8878  * invoke <code>write</code> system call and it can block.
8879  * In such a situation, <code>OpenSSL::SSL::SSLSocket#read_nonblock</code>
8880  * raises IO::WaitWritable instead of blocking.
8881  * So, the caller should wait for ready for writability as above example.
8882  *
8883  * The combination of nonblocking methods and <code>IO.select</code> is
8884  * also useful for streams such as tty, pipe socket socket when
8885  * multiple processes read from a stream.
8886  *
8887  * Finally, Linux kernel developers don't guarantee that
8888  * readability of select(2) means readability of following read(2) even
8889  * for a single process.
8890  * See select(2) manual on GNU/Linux system.
8891  *
8892  * Invoking <code>IO.select</code> before <code>IO#readpartial</code> works well as usual.
8893  * However it is not the best way to use <code>IO.select</code>.
8894  *
8895  * The writability notified by select(2) doesn't show
8896  * how many bytes writable.
8897  * <code>IO#write</code> method blocks until given whole string is written.
8898  * So, <code>IO#write(two or more bytes)</code> can block after writability is notified by <code>IO.select</code>.
8899  * <code>IO#write_nonblock</code> is required to avoid the blocking.
8900  *
8901  * Blocking write (<code>write</code>) can be emulated using
8902  * <code>write_nonblock</code> and <code>IO.select</code> as follows:
8903  * IO::WaitReadable should also be rescued for SSL renegotiation in <code>OpenSSL::SSL::SSLSocket</code>.
8904  *
8905  * while 0 < string.bytesize
8906  * begin
8907  * written = io_like.write_nonblock(string)
8908  * rescue IO::WaitReadable
8909  * IO.select([io_like])
8910  * retry
8911  * rescue IO::WaitWritable
8912  * IO.select(nil, [io_like])
8913  * retry
8914  * end
8915  * string = string.byteslice(written..-1)
8916  * end
8917  *
8918  * === Parameters
8919  * read_array:: an array of <code>IO</code> objects that wait until ready for read
8920  * write_array:: an array of <code>IO</code> objects that wait until ready for write
8921  * error_array:: an array of <code>IO</code> objects that wait for exceptions
8922  * timeout:: a numeric value in second
8923  *
8924  * === Example
8925  *
8926  * rp, wp = IO.pipe
8927  * mesg = "ping "
8928  * 100.times {
8929  * # IO.select follows IO#read. Not the best way to use IO.select.
8930  * rs, ws, = IO.select([rp], [wp])
8931  * if r = rs[0]
8932  * ret = r.read(5)
8933  * print ret
8934  * case ret
8935  * when /ping/
8936  * mesg = "pong\n"
8937  * when /pong/
8938  * mesg = "ping "
8939  * end
8940  * end
8941  * if w = ws[0]
8942  * w.write(mesg)
8943  * end
8944  * }
8945  *
8946  * <em>produces:</em>
8947  *
8948  * ping pong
8949  * ping pong
8950  * ping pong
8951  * (snipped)
8952  * ping
8953  */
8954 
8955 static VALUE
8957 {
8958  VALUE timeout;
8959  struct select_args args;
8960  struct timeval timerec;
8961  int i;
8962 
8963  rb_scan_args(argc, argv, "13", &args.read, &args.write, &args.except, &timeout);
8964  if (NIL_P(timeout)) {
8965  args.timeout = 0;
8966  }
8967  else {
8968  timerec = rb_time_interval(timeout);
8969  args.timeout = &timerec;
8970  }
8971 
8972  for (i = 0; i < numberof(args.fdsets); ++i)
8973  rb_fd_init(&args.fdsets[i]);
8974 
8975  return rb_ensure(select_call, (VALUE)&args, select_end, (VALUE)&args);
8976 }
8977 
8978 #if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__APPLE__)
8979  typedef unsigned long ioctl_req_t;
8980 # define NUM2IOCTLREQ(num) NUM2ULONG(num)
8981 #else
8982  typedef int ioctl_req_t;
8983 # define NUM2IOCTLREQ(num) NUM2INT(num)
8984 #endif
8985 
8986 #ifdef HAVE_IOCTL
8987 struct ioctl_arg {
8988  int fd;
8989  ioctl_req_t cmd;
8990  long narg;
8991 };
8992 
8993 static VALUE
8994 nogvl_ioctl(void *ptr)
8995 {
8996  struct ioctl_arg *arg = ptr;
8997 
8998  return (VALUE)ioctl(arg->fd, arg->cmd, arg->narg);
8999 }
9000 
9001 static int
9002 do_ioctl(int fd, ioctl_req_t cmd, long narg)
9003 {
9004  int retval;
9005  struct ioctl_arg arg;
9006 
9007  arg.fd = fd;
9008  arg.cmd = cmd;
9009  arg.narg = narg;
9010 
9011  retval = (int)rb_thread_io_blocking_region(nogvl_ioctl, &arg, fd);
9012 
9013  return retval;
9014 }
9015 #endif
9016 
9017 #define DEFULT_IOCTL_NARG_LEN (256)
9018 
9019 #if defined(__linux__) && defined(_IOC_SIZE)
9020 static long
9021 linux_iocparm_len(ioctl_req_t cmd)
9022 {
9023  long len;
9024 
9025  if ((cmd & 0xFFFF0000) == 0) {
9026  /* legacy and unstructured ioctl number. */
9027  return DEFULT_IOCTL_NARG_LEN;
9028  }
9029 
9030  len = _IOC_SIZE(cmd);
9031 
9032  /* paranoia check for silly drivers which don't keep ioctl convention */
9033  if (len < DEFULT_IOCTL_NARG_LEN)
9034  len = DEFULT_IOCTL_NARG_LEN;
9035 
9036  return len;
9037 }
9038 #endif
9039 
9040 static long
9042 {
9043  long len;
9044 
9045 #ifdef IOCPARM_MASK
9046 #ifndef IOCPARM_LEN
9047 #define IOCPARM_LEN(x) (((x) >> 16) & IOCPARM_MASK)
9048 #endif
9049 #endif
9050 #ifdef IOCPARM_LEN
9051  len = IOCPARM_LEN(cmd); /* on BSDish systems we're safe */
9052 #elif defined(__linux__) && defined(_IOC_SIZE)
9053  len = linux_iocparm_len(cmd);
9054 #else
9055  /* otherwise guess at what's safe */
9056  len = DEFULT_IOCTL_NARG_LEN;
9057 #endif
9058 
9059  return len;
9060 }
9061 
9062 #ifdef HAVE_FCNTL
9063 #ifdef __linux__
9064 typedef long fcntl_arg_t;
9065 #else
9066 /* posix */
9067 typedef int fcntl_arg_t;
9068 #endif
9069 
9070 #if defined __native_client__ && !defined __GLIBC__
9071 // struct flock is currently missing the NaCl newlib headers
9072 // TODO(sbc): remove this once it gets added.
9073 #undef F_GETLK
9074 #undef F_SETLK
9075 #undef F_SETLKW
9076 #endif
9077 
9078 static long
9079 fcntl_narg_len(int cmd)
9080 {
9081  long len;
9082 
9083  switch (cmd) {
9084 #ifdef F_DUPFD
9085  case F_DUPFD:
9086  len = sizeof(fcntl_arg_t);
9087  break;
9088 #endif
9089 #ifdef F_DUP2FD /* bsd specific */
9090  case F_DUP2FD:
9091  len = sizeof(int);
9092  break;
9093 #endif
9094 #ifdef F_DUPFD_CLOEXEC /* linux specific */
9095  case F_DUPFD_CLOEXEC:
9096  len = sizeof(fcntl_arg_t);
9097  break;
9098 #endif
9099 #ifdef F_GETFD
9100  case F_GETFD:
9101  len = 1;
9102  break;
9103 #endif
9104 #ifdef F_SETFD
9105  case F_SETFD:
9106  len = sizeof(fcntl_arg_t);
9107  break;
9108 #endif
9109 #ifdef F_GETFL
9110  case F_GETFL:
9111  len = 1;
9112  break;
9113 #endif
9114 #ifdef F_SETFL
9115  case F_SETFL:
9116  len = sizeof(fcntl_arg_t);
9117  break;
9118 #endif
9119 #ifdef F_GETOWN
9120  case F_GETOWN:
9121  len = 1;
9122  break;
9123 #endif
9124 #ifdef F_SETOWN
9125  case F_SETOWN:
9126  len = sizeof(fcntl_arg_t);
9127  break;
9128 #endif
9129 #ifdef F_GETOWN_EX /* linux specific */
9130  case F_GETOWN_EX:
9131  len = sizeof(struct f_owner_ex);
9132  break;
9133 #endif
9134 #ifdef F_SETOWN_EX /* linux specific */
9135  case F_SETOWN_EX:
9136  len = sizeof(struct f_owner_ex);
9137  break;
9138 #endif
9139 #ifdef F_GETLK
9140  case F_GETLK:
9141  len = sizeof(struct flock);
9142  break;
9143 #endif
9144 #ifdef F_SETLK
9145  case F_SETLK:
9146  len = sizeof(struct flock);
9147  break;
9148 #endif
9149 #ifdef F_SETLKW
9150  case F_SETLKW:
9151  len = sizeof(struct flock);
9152  break;
9153 #endif
9154 #ifdef F_READAHEAD /* bsd specific */
9155  case F_READAHEAD:
9156  len = sizeof(int);
9157  break;
9158 #endif
9159 #ifdef F_RDAHEAD /* Darwin specific */
9160  case F_RDAHEAD:
9161  len = sizeof(int);
9162  break;
9163 #endif
9164 #ifdef F_GETSIG /* linux specific */
9165  case F_GETSIG:
9166  len = 1;
9167  break;
9168 #endif
9169 #ifdef F_SETSIG /* linux specific */
9170  case F_SETSIG:
9171  len = sizeof(fcntl_arg_t);
9172  break;
9173 #endif
9174 #ifdef F_GETLEASE /* linux specific */
9175  case F_GETLEASE:
9176  len = 1;
9177  break;
9178 #endif
9179 #ifdef F_SETLEASE /* linux specific */
9180  case F_SETLEASE:
9181  len = sizeof(fcntl_arg_t);
9182  break;
9183 #endif
9184 #ifdef F_NOTIFY /* linux specific */
9185  case F_NOTIFY:
9186  len = sizeof(fcntl_arg_t);
9187  break;
9188 #endif
9189 
9190  default:
9191  len = 256;
9192  break;
9193  }
9194 
9195  return len;
9196 }
9197 #else /* HAVE_FCNTL */
9198 static long
9200 {
9201  return 0;
9202 }
9203 #endif /* HAVE_FCNTL */
9204 
9205 static long
9206 setup_narg(ioctl_req_t cmd, VALUE *argp, int io_p)
9207 {
9208  long narg = 0;
9209  VALUE arg = *argp;
9210 
9211  if (NIL_P(arg) || arg == Qfalse) {
9212  narg = 0;
9213  }
9214  else if (FIXNUM_P(arg)) {
9215  narg = FIX2LONG(arg);
9216  }
9217  else if (arg == Qtrue) {
9218  narg = 1;
9219  }
9220  else {
9221  VALUE tmp = rb_check_string_type(arg);
9222 
9223  if (NIL_P(tmp)) {
9224  narg = NUM2LONG(arg);
9225  }
9226  else {
9227  char *ptr;
9228  long len, slen;
9229 
9230  *argp = arg = tmp;
9231  if (io_p)
9232  len = ioctl_narg_len(cmd);
9233  else
9234  len = fcntl_narg_len((int)cmd);
9235  rb_str_modify(arg);
9236 
9237  slen = RSTRING_LEN(arg);
9238  /* expand for data + sentinel. */
9239  if (slen < len+1) {
9240  rb_str_resize(arg, len+1);
9241  MEMZERO(RSTRING_PTR(arg)+slen, char, len-slen);
9242  slen = len+1;
9243  }
9244  /* a little sanity check here */
9245  ptr = RSTRING_PTR(arg);
9246  ptr[slen - 1] = 17;
9247  narg = (long)(SIGNED_VALUE)ptr;
9248  }
9249  }
9250 
9251  return narg;
9252 }
9253 
9254 #ifdef HAVE_IOCTL
9255 static VALUE
9256 rb_ioctl(VALUE io, VALUE req, VALUE arg)
9257 {
9258  ioctl_req_t cmd = NUM2IOCTLREQ(req);
9259  rb_io_t *fptr;
9260  long narg;
9261  int retval;
9262 
9263  narg = setup_narg(cmd, &arg, 1);
9264  GetOpenFile(io, fptr);
9265  retval = do_ioctl(fptr->fd, cmd, narg);
9266  if (retval < 0) rb_sys_fail_path(fptr->pathv);
9267  if (RB_TYPE_P(arg, T_STRING)) {
9268  char *ptr;
9269  long slen;
9270  RSTRING_GETMEM(arg, ptr, slen);
9271  if (ptr[slen-1] != 17)
9272  rb_raise(rb_eArgError, "return value overflowed string");
9273  ptr[slen-1] = '\0';
9274  }
9275 
9276  return INT2NUM(retval);
9277 }
9278 
9279 /*
9280  * call-seq:
9281  * ios.ioctl(integer_cmd, arg) -> integer
9282  *
9283  * Provides a mechanism for issuing low-level commands to control or
9284  * query I/O devices. Arguments and results are platform dependent. If
9285  * <i>arg</i> is a number, its value is passed directly. If it is a
9286  * string, it is interpreted as a binary sequence of bytes. On Unix
9287  * platforms, see <code>ioctl(2)</code> for details. Not implemented on
9288  * all platforms.
9289  */
9290 
9291 static VALUE
9292 rb_io_ioctl(int argc, VALUE *argv, VALUE io)
9293 {
9294  VALUE req, arg;
9295 
9296  rb_scan_args(argc, argv, "11", &req, &arg);
9297  return rb_ioctl(io, req, arg);
9298 }
9299 #else
9300 #define rb_io_ioctl rb_f_notimplement
9301 #endif
9302 
9303 #ifdef HAVE_FCNTL
9304 struct fcntl_arg {
9305  int fd;
9306  int cmd;
9307  long narg;
9308 };
9309 
9310 static VALUE
9311 nogvl_fcntl(void *ptr)
9312 {
9313  struct fcntl_arg *arg = ptr;
9314 
9315 #if defined(F_DUPFD)
9316  if (arg->cmd == F_DUPFD)
9317  return (VALUE)rb_cloexec_fcntl_dupfd(arg->fd, (int)arg->narg);
9318 #endif
9319  return (VALUE)fcntl(arg->fd, arg->cmd, arg->narg);
9320 }
9321 
9322 static int
9323 do_fcntl(int fd, int cmd, long narg)
9324 {
9325  int retval;
9326  struct fcntl_arg arg;
9327 
9328  arg.fd = fd;
9329  arg.cmd = cmd;
9330  arg.narg = narg;
9331 
9332  retval = (int)rb_thread_io_blocking_region(nogvl_fcntl, &arg, fd);
9333 #if defined(F_DUPFD)
9334  if (retval != -1 && cmd == F_DUPFD) {
9335  rb_update_max_fd(retval);
9336  }
9337 #endif
9338 
9339  return retval;
9340 }
9341 
9342 static VALUE
9343 rb_fcntl(VALUE io, VALUE req, VALUE arg)
9344 {
9345  int cmd = NUM2INT(req);
9346  rb_io_t *fptr;
9347  long narg;
9348  int retval;
9349 
9350  narg = setup_narg(cmd, &arg, 0);
9351  GetOpenFile(io, fptr);
9352  retval = do_fcntl(fptr->fd, cmd, narg);
9353  if (retval < 0) rb_sys_fail_path(fptr->pathv);
9354  if (RB_TYPE_P(arg, T_STRING)) {
9355  char *ptr;
9356  long slen;
9357  RSTRING_GETMEM(arg, ptr, slen);
9358  if (ptr[slen-1] != 17)
9359  rb_raise(rb_eArgError, "return value overflowed string");
9360  ptr[slen-1] = '\0';
9361  }
9362 
9363  return INT2NUM(retval);
9364 }
9365 
9366 /*
9367  * call-seq:
9368  * ios.fcntl(integer_cmd, arg) -> integer
9369  *
9370  * Provides a mechanism for issuing low-level commands to control or
9371  * query file-oriented I/O streams. Arguments and results are platform
9372  * dependent. If <i>arg</i> is a number, its value is passed
9373  * directly. If it is a string, it is interpreted as a binary sequence
9374  * of bytes (<code>Array#pack</code> might be a useful way to build this
9375  * string). On Unix platforms, see <code>fcntl(2)</code> for details.
9376  * Not implemented on all platforms.
9377  */
9378 
9379 static VALUE
9380 rb_io_fcntl(int argc, VALUE *argv, VALUE io)
9381 {
9382  VALUE req, arg;
9383 
9384  rb_scan_args(argc, argv, "11", &req, &arg);
9385  return rb_fcntl(io, req, arg);
9386 }
9387 #else
9388 #define rb_io_fcntl rb_f_notimplement
9389 #endif
9390 
9391 #if defined(HAVE_SYSCALL) || defined(HAVE___SYSCALL)
9392 /*
9393  * call-seq:
9394  * syscall(num [, args...]) -> integer
9395  *
9396  * Calls the operating system function identified by _num_ and
9397  * returns the result of the function or raises SystemCallError if
9398  * it failed.
9399  *
9400  * Arguments for the function can follow _num_. They must be either
9401  * +String+ objects or +Integer+ objects. A +String+ object is passed
9402  * as a pointer to the byte sequence. An +Integer+ object is passed
9403  * as an integer whose bit size is same as a pointer.
9404  * Up to nine parameters may be passed.
9405  *
9406  * The function identified by _num_ is system
9407  * dependent. On some Unix systems, the numbers may be obtained from a
9408  * header file called <code>syscall.h</code>.
9409  *
9410  * syscall 4, 1, "hello\n", 6 # '4' is write(2) on our box
9411  *
9412  * <em>produces:</em>
9413  *
9414  * hello
9415  *
9416  * Calling +syscall+ on a platform which does not have any way to
9417  * an arbitrary system function just fails with NotImplementedError.
9418  *
9419  * *Note:*
9420  * +syscall+ is essentially unsafe and unportable.
9421  * Feel free to shoot your foot.
9422  * The DL (Fiddle) library is preferred for safer and a bit
9423  * more portable programming.
9424  */
9425 
9426 static VALUE
9427 rb_f_syscall(int argc, VALUE *argv)
9428 {
9429  VALUE arg[8];
9430 #if SIZEOF_VOIDP == 8 && defined(HAVE___SYSCALL) && SIZEOF_INT != 8 /* mainly *BSD */
9431 # define SYSCALL __syscall
9432 # define NUM2SYSCALLID(x) NUM2LONG(x)
9433 # define RETVAL2NUM(x) LONG2NUM(x)
9434 # if SIZEOF_LONG == 8
9435  long num, retval = -1;
9436 # elif SIZEOF_LONG_LONG == 8
9437  long long num, retval = -1;
9438 # else
9439 # error ---->> it is asserted that __syscall takes the first argument and returns retval in 64bit signed integer. <<----
9440 # endif
9441 #elif defined(__linux__)
9442 # define SYSCALL syscall
9443 # define NUM2SYSCALLID(x) NUM2LONG(x)
9444 # define RETVAL2NUM(x) LONG2NUM(x)
9445  /*
9446  * Linux man page says, syscall(2) function prototype is below.
9447  *
9448  * int syscall(int number, ...);
9449  *
9450  * But, it's incorrect. Actual one takes and returned long. (see unistd.h)
9451  */
9452  long num, retval = -1;
9453 #else
9454 # define SYSCALL syscall
9455 # define NUM2SYSCALLID(x) NUM2INT(x)
9456 # define RETVAL2NUM(x) INT2NUM(x)
9457  int num, retval = -1;
9458 #endif
9459  int i;
9460 
9461  if (RTEST(ruby_verbose)) {
9462  rb_warning("We plan to remove a syscall function at future release. DL(Fiddle) provides safer alternative.");
9463  }
9464 
9465  if (argc == 0)
9466  rb_raise(rb_eArgError, "too few arguments for syscall");
9467  if (argc > numberof(arg))
9468  rb_raise(rb_eArgError, "too many arguments for syscall");
9469  num = NUM2SYSCALLID(argv[0]); ++argv;
9470  for (i = argc - 1; i--; ) {
9471  VALUE v = rb_check_string_type(argv[i]);
9472 
9473  if (!NIL_P(v)) {
9474  SafeStringValue(v);
9475  rb_str_modify(v);
9476  arg[i] = (VALUE)StringValueCStr(v);
9477  }
9478  else {
9479  arg[i] = (VALUE)NUM2LONG(argv[i]);
9480  }
9481  }
9482 
9483  switch (argc) {
9484  case 1:
9485  retval = SYSCALL(num);
9486  break;
9487  case 2:
9488  retval = SYSCALL(num, arg[0]);
9489  break;
9490  case 3:
9491  retval = SYSCALL(num, arg[0],arg[1]);
9492  break;
9493  case 4:
9494  retval = SYSCALL(num, arg[0],arg[1],arg[2]);
9495  break;
9496  case 5:
9497  retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3]);
9498  break;
9499  case 6:
9500  retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3],arg[4]);
9501  break;
9502  case 7:
9503  retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3],arg[4],arg[5]);
9504  break;
9505  case 8:
9506  retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6]);
9507  break;
9508  }
9509 
9510  if (retval == -1)
9511  rb_sys_fail(0);
9512  return RETVAL2NUM(retval);
9513 #undef SYSCALL
9514 #undef NUM2SYSCALLID
9515 #undef RETVAL2NUM
9516 }
9517 #else
9518 #define rb_f_syscall rb_f_notimplement
9519 #endif
9520 
9521 static VALUE
9523 {
9524  return rb_class_new_instance(2, (VALUE*)args+1, *(VALUE*)args);
9525 }
9526 
9527 static rb_encoding *
9529 {
9530  rb_encoding *enc = rb_find_encoding(v);
9531  if (!enc) rb_warn("Unsupported encoding %"PRIsVALUE" ignored", v);
9532  return enc;
9533 }
9534 
9535 static void
9537 {
9538  rb_encoding *enc, *enc2;
9539  int ecflags = fptr->encs.ecflags;
9540  VALUE ecopts, tmp;
9541 
9542  if (!NIL_P(v2)) {
9543  enc2 = find_encoding(v1);
9544  tmp = rb_check_string_type(v2);
9545  if (!NIL_P(tmp)) {
9546  if (RSTRING_LEN(tmp) == 1 && RSTRING_PTR(tmp)[0] == '-') {
9547  /* Special case - "-" => no transcoding */
9548  enc = enc2;
9549  enc2 = NULL;
9550  }
9551  else
9552  enc = find_encoding(v2);
9553  if (enc == enc2) {
9554  /* Special case - "-" => no transcoding */
9555  enc2 = NULL;
9556  }
9557  }
9558  else {
9559  enc = find_encoding(v2);
9560  if (enc == enc2) {
9561  /* Special case - "-" => no transcoding */
9562  enc2 = NULL;
9563  }
9564  }
9566  ecflags = rb_econv_prepare_options(opt, &ecopts, ecflags);
9567  }
9568  else {
9569  if (NIL_P(v1)) {
9570  /* Set to default encodings */
9571  rb_io_ext_int_to_encs(NULL, NULL, &enc, &enc2, 0);
9573  ecopts = Qnil;
9574  }
9575  else {
9576  tmp = rb_check_string_type(v1);
9577  if (!NIL_P(tmp) && rb_enc_asciicompat(enc = rb_enc_get(tmp))) {
9578  parse_mode_enc(RSTRING_PTR(tmp), enc, &enc, &enc2, NULL);
9580  ecflags = rb_econv_prepare_options(opt, &ecopts, ecflags);
9581  }
9582  else {
9583  rb_io_ext_int_to_encs(find_encoding(v1), NULL, &enc, &enc2, 0);
9585  ecopts = Qnil;
9586  }
9587  }
9588  }
9589  validate_enc_binmode(&fptr->mode, ecflags, enc, enc2);
9590  fptr->encs.enc = enc;
9591  fptr->encs.enc2 = enc2;
9592  fptr->encs.ecflags = ecflags;
9593  fptr->encs.ecopts = ecopts;
9594  clear_codeconv(fptr);
9595 
9596 }
9597 
9603 };
9604 
9605 static VALUE
9607 {
9608  struct io_encoding_set_args *arg = (struct io_encoding_set_args *)v;
9609  io_encoding_set(arg->fptr, arg->v1, arg->v2, arg->opt);
9610  return Qnil;
9611 }
9612 
9613 static VALUE
9615 {
9616  VALUE *rwp = (VALUE *)rw;
9617  return rb_ensure(io_close, rwp[0], io_close, rwp[1]);
9618 }
9619 
9620 /*
9621  * call-seq:
9622  * IO.pipe -> [read_io, write_io]
9623  * IO.pipe(ext_enc) -> [read_io, write_io]
9624  * IO.pipe("ext_enc:int_enc" [, opt]) -> [read_io, write_io]
9625  * IO.pipe(ext_enc, int_enc [, opt]) -> [read_io, write_io]
9626  *
9627  * IO.pipe(...) {|read_io, write_io| ... }
9628  *
9629  * Creates a pair of pipe endpoints (connected to each other) and
9630  * returns them as a two-element array of <code>IO</code> objects:
9631  * <code>[</code> <i>read_io</i>, <i>write_io</i> <code>]</code>.
9632  *
9633  * If a block is given, the block is called and
9634  * returns the value of the block.
9635  * <i>read_io</i> and <i>write_io</i> are sent to the block as arguments.
9636  * If read_io and write_io are not closed when the block exits, they are closed.
9637  * i.e. closing read_io and/or write_io doesn't cause an error.
9638  *
9639  * Not available on all platforms.
9640  *
9641  * If an encoding (encoding name or encoding object) is specified as an optional argument,
9642  * read string from pipe is tagged with the encoding specified.
9643  * If the argument is a colon separated two encoding names "A:B",
9644  * the read string is converted from encoding A (external encoding)
9645  * to encoding B (internal encoding), then tagged with B.
9646  * If two optional arguments are specified, those must be
9647  * encoding objects or encoding names,
9648  * and the first one is the external encoding,
9649  * and the second one is the internal encoding.
9650  * If the external encoding and the internal encoding is specified,
9651  * optional hash argument specify the conversion option.
9652  *
9653  * In the example below, the two processes close the ends of the pipe
9654  * that they are not using. This is not just a cosmetic nicety. The
9655  * read end of a pipe will not generate an end of file condition if
9656  * there are any writers with the pipe still open. In the case of the
9657  * parent process, the <code>rd.read</code> will never return if it
9658  * does not first issue a <code>wr.close</code>.
9659  *
9660  * rd, wr = IO.pipe
9661  *
9662  * if fork
9663  * wr.close
9664  * puts "Parent got: <#{rd.read}>"
9665  * rd.close
9666  * Process.wait
9667  * else
9668  * rd.close
9669  * puts "Sending message to parent"
9670  * wr.write "Hi Dad"
9671  * wr.close
9672  * end
9673  *
9674  * <em>produces:</em>
9675  *
9676  * Sending message to parent
9677  * Parent got: <Hi Dad>
9678  */
9679 
9680 static VALUE
9682 {
9683  int pipes[2], state;
9684  VALUE r, w, args[3], v1, v2;
9685  VALUE opt;
9686  rb_io_t *fptr, *fptr2;
9687  struct io_encoding_set_args ies_args;
9688  int fmode = 0;
9689  VALUE ret;
9690 
9691  argc = rb_scan_args(argc, argv, "02:", &v1, &v2, &opt);
9692  if (rb_pipe(pipes) == -1)
9693  rb_sys_fail(0);
9694 
9695  args[0] = klass;
9696  args[1] = INT2NUM(pipes[0]);
9697  args[2] = INT2FIX(O_RDONLY);
9698  r = rb_protect(io_new_instance, (VALUE)args, &state);
9699  if (state) {
9700  close(pipes[0]);
9701  close(pipes[1]);
9702  rb_jump_tag(state);
9703  }
9704  GetOpenFile(r, fptr);
9705 
9706  ies_args.fptr = fptr;
9707  ies_args.v1 = v1;
9708  ies_args.v2 = v2;
9709  ies_args.opt = opt;
9710  rb_protect(io_encoding_set_v, (VALUE)&ies_args, &state);
9711  if (state) {
9712  close(pipes[1]);
9713  io_close(r);
9714  rb_jump_tag(state);
9715  }
9716 
9717  args[1] = INT2NUM(pipes[1]);
9718  args[2] = INT2FIX(O_WRONLY);
9719  w = rb_protect(io_new_instance, (VALUE)args, &state);
9720  if (state) {
9721  close(pipes[1]);
9722  if (!NIL_P(r)) rb_io_close(r);
9723  rb_jump_tag(state);
9724  }
9725  GetOpenFile(w, fptr2);
9726  rb_io_synchronized(fptr2);
9727 
9728  extract_binmode(opt, &fmode);
9729 #if DEFAULT_TEXTMODE
9730  if ((fptr->mode & FMODE_TEXTMODE) && (fmode & FMODE_BINMODE)) {
9731  fptr->mode &= ~FMODE_TEXTMODE;
9732  setmode(fptr->fd, O_BINARY);
9733  }
9734 #if defined(RUBY_TEST_CRLF_ENVIRONMENT) || defined(_WIN32)
9737  }
9738 #endif
9739 #endif
9740  fptr->mode |= fmode;
9741 #if DEFAULT_TEXTMODE
9742  if ((fptr2->mode & FMODE_TEXTMODE) && (fmode & FMODE_BINMODE)) {
9743  fptr2->mode &= ~FMODE_TEXTMODE;
9744  setmode(fptr2->fd, O_BINARY);
9745  }
9746 #endif
9747  fptr2->mode |= fmode;
9748 
9749  ret = rb_assoc_new(r, w);
9750  if (rb_block_given_p()) {
9751  VALUE rw[2];
9752  rw[0] = r;
9753  rw[1] = w;
9754  return rb_ensure(rb_yield, ret, pipe_pair_close, (VALUE)rw);
9755  }
9756  return ret;
9757 }
9758 
9759 struct foreach_arg {
9760  int argc;
9763 };
9764 
9765 static void
9766 open_key_args(int argc, VALUE *argv, VALUE opt, struct foreach_arg *arg)
9767 {
9768  VALUE path, v;
9769 
9770  path = *argv++;
9771  argc--;
9772  FilePathValue(path);
9773  arg->io = 0;
9774  arg->argc = argc;
9775  arg->argv = argv;
9776  if (NIL_P(opt)) {
9777  arg->io = rb_io_open(path, INT2NUM(O_RDONLY), INT2FIX(0666), Qnil);
9778  return;
9779  }
9780  v = rb_hash_aref(opt, sym_open_args);
9781  if (!NIL_P(v)) {
9782  VALUE args;
9783  long n;
9784 
9785  v = rb_convert_type(v, T_ARRAY, "Array", "to_ary");
9786  n = RARRAY_LEN(v) + 1;
9787 #if SIZEOF_LONG > SIZEOF_INT
9788  if (n > INT_MAX) {
9789  rb_raise(rb_eArgError, "too many arguments");
9790  }
9791 #endif
9792  args = rb_ary_tmp_new(n);
9793  rb_ary_push(args, path);
9794  rb_ary_concat(args, v);
9795  arg->io = rb_io_open_with_args((int)n, RARRAY_CONST_PTR(args));
9796  rb_ary_clear(args); /* prevent from GC */
9797  return;
9798  }
9799  arg->io = rb_io_open(path, Qnil, Qnil, opt);
9800 }
9801 
9802 static VALUE
9804 {
9805  VALUE str;
9806 
9807  while (!NIL_P(str = rb_io_getline_1(arg->rs, arg->limit, arg->chomp, arg->io))) {
9808  rb_lastline_set(str);
9809  rb_yield(str);
9810  }
9812  return Qnil;
9813 }
9814 
9815 /*
9816  * call-seq:
9817  * IO.foreach(name, sep=$/ [, open_args]) {|line| block } -> nil
9818  * IO.foreach(name, limit [, open_args]) {|line| block } -> nil
9819  * IO.foreach(name, sep, limit [, open_args]) {|line| block } -> nil
9820  * IO.foreach(...) -> an_enumerator
9821  *
9822  * Executes the block for every line in the named I/O port, where lines
9823  * are separated by <em>sep</em>.
9824  *
9825  * If no block is given, an enumerator is returned instead.
9826  *
9827  * IO.foreach("testfile") {|x| print "GOT ", x }
9828  *
9829  * <em>produces:</em>
9830  *
9831  * GOT This is line one
9832  * GOT This is line two
9833  * GOT This is line three
9834  * GOT And so on...
9835  *
9836  * If the last argument is a hash, it's the keyword argument to open.
9837  * See <code>IO.read</code> for detail.
9838  *
9839  */
9840 
9841 static VALUE
9843 {
9844  VALUE opt;
9845  int orig_argc = argc;
9846  struct foreach_arg arg;
9847  struct getline_arg garg;
9848 
9849  argc = rb_scan_args(argc, argv, "13:", NULL, NULL, NULL, NULL, &opt);
9850  RETURN_ENUMERATOR(self, orig_argc, argv);
9851  extract_getline_args(argc-1, argv+1, &garg);
9852  open_key_args(argc, argv, opt, &arg);
9853  if (NIL_P(arg.io)) return Qnil;
9854  extract_getline_opts(opt, &garg);
9855  check_getline_args(&garg.rs, &garg.limit, garg.io = arg.io);
9856  return rb_ensure(io_s_foreach, (VALUE)&garg, rb_io_close, arg.io);
9857 }
9858 
9859 static VALUE
9861 {
9862  return io_readlines(arg, arg->io);
9863 }
9864 
9865 /*
9866  * call-seq:
9867  * IO.readlines(name, sep=$/ [, open_args]) -> array
9868  * IO.readlines(name, limit [, open_args]) -> array
9869  * IO.readlines(name, sep, limit [, open_args]) -> array
9870  *
9871  * Reads the entire file specified by <i>name</i> as individual
9872  * lines, and returns those lines in an array. Lines are separated by
9873  * <i>sep</i>.
9874  *
9875  * a = IO.readlines("testfile")
9876  * a[0] #=> "This is line one\n"
9877  *
9878  * If the last argument is a hash, it's the keyword argument to open.
9879  * See <code>IO.read</code> for detail.
9880  *
9881  */
9882 
9883 static VALUE
9885 {
9886  VALUE opt;
9887  struct foreach_arg arg;
9888  struct getline_arg garg;
9889 
9890  argc = rb_scan_args(argc, argv, "13:", NULL, NULL, NULL, NULL, &opt);
9891  extract_getline_args(argc-1, argv+1, &garg);
9892  open_key_args(argc, argv, opt, &arg);
9893  if (NIL_P(arg.io)) return Qnil;
9894  extract_getline_opts(opt, &garg);
9895  check_getline_args(&garg.rs, &garg.limit, garg.io = arg.io);
9896  return rb_ensure(io_s_readlines, (VALUE)&garg, rb_io_close, arg.io);
9897 }
9898 
9899 static VALUE
9901 {
9902  return io_read(arg->argc, arg->argv, arg->io);
9903 }
9904 
9905 struct seek_arg {
9908  int mode;
9909 };
9910 
9911 static VALUE
9913 {
9914  struct seek_arg *arg = (struct seek_arg *)argp;
9915  rb_io_binmode(arg->io);
9916  return rb_io_seek(arg->io, arg->offset, arg->mode);
9917 }
9918 
9919 /*
9920  * call-seq:
9921  * IO.read(name, [length [, offset]] [, opt] ) -> string
9922  *
9923  * Opens the file, optionally seeks to the given +offset+, then returns
9924  * +length+ bytes (defaulting to the rest of the file). <code>read</code>
9925  * ensures the file is closed before returning.
9926  *
9927  * If +name+ starts with a pipe character (<code>"|"</code>), a subprocess is
9928  * created in the same way as Kernel#open, and its output is returned.
9929  *
9930  * === Options
9931  *
9932  * The options hash accepts the following keys:
9933  *
9934  * :encoding::
9935  * string or encoding
9936  *
9937  * Specifies the encoding of the read string. +:encoding+ will be ignored
9938  * if +length+ is specified. See Encoding.aliases for possible encodings.
9939  *
9940  * :mode::
9941  * string
9942  *
9943  * Specifies the <i>mode</i> argument for open(). It must start
9944  * with an "r", otherwise it will cause an error.
9945  * See IO.new for the list of possible modes.
9946  *
9947  * :open_args::
9948  * array
9949  *
9950  * Specifies arguments for open() as an array. This key can not be used
9951  * in combination with either +:encoding+ or +:mode+.
9952  *
9953  * Examples:
9954  *
9955  * IO.read("testfile") #=> "This is line one\nThis is line two\nThis is line three\nAnd so on...\n"
9956  * IO.read("testfile", 20) #=> "This is line one\nThi"
9957  * IO.read("testfile", 20, 10) #=> "ne one\nThis is line "
9958  * IO.read("binfile", mode: "rb") #=> "\xF7\x00\x00\x0E\x12"
9959  */
9960 
9961 static VALUE
9963 {
9964  VALUE opt, offset;
9965  struct foreach_arg arg;
9966 
9967  argc = rb_scan_args(argc, argv, "13:", NULL, NULL, &offset, NULL, &opt);
9968  open_key_args(argc, argv, opt, &arg);
9969  if (NIL_P(arg.io)) return Qnil;
9970  if (!NIL_P(offset)) {
9971  struct seek_arg sarg;
9972  int state = 0;
9973  sarg.io = arg.io;
9974  sarg.offset = offset;
9975  sarg.mode = SEEK_SET;
9976  rb_protect(seek_before_access, (VALUE)&sarg, &state);
9977  if (state) {
9978  rb_io_close(arg.io);
9979  rb_jump_tag(state);
9980  }
9981  if (arg.argc == 2) arg.argc = 1;
9982  }
9983  return rb_ensure(io_s_read, (VALUE)&arg, rb_io_close, arg.io);
9984 }
9985 
9986 /*
9987  * call-seq:
9988  * IO.binread(name, [length [, offset]] ) -> string
9989  *
9990  * Opens the file, optionally seeks to the given <i>offset</i>, then returns
9991  * <i>length</i> bytes (defaulting to the rest of the file).
9992  * <code>binread</code> ensures the file is closed before returning.
9993  * The open mode would be "rb:ASCII-8BIT".
9994  *
9995  * IO.binread("testfile") #=> "This is line one\nThis is line two\nThis is line three\nAnd so on...\n"
9996  * IO.binread("testfile", 20) #=> "This is line one\nThi"
9997  * IO.binread("testfile", 20, 10) #=> "ne one\nThis is line "
9998  */
9999 
10000 static VALUE
10002 {
10003  VALUE offset;
10004  struct foreach_arg arg;
10005  enum {
10007  oflags = O_RDONLY
10008 #ifdef O_BINARY
10009  |O_BINARY
10010 #endif
10011  };
10012  convconfig_t convconfig = {NULL, NULL, 0, Qnil};
10013 
10014  rb_scan_args(argc, argv, "12", NULL, NULL, &offset);
10015  FilePathValue(argv[0]);
10016  convconfig.enc = rb_ascii8bit_encoding();
10017  arg.io = rb_io_open_generic(argv[0], oflags, fmode, &convconfig, 0);
10018  if (NIL_P(arg.io)) return Qnil;
10019  arg.argv = argv+1;
10020  arg.argc = (argc > 1) ? 1 : 0;
10021  if (!NIL_P(offset)) {
10022  struct seek_arg sarg;
10023  int state = 0;
10024  sarg.io = arg.io;
10025  sarg.offset = offset;
10026  sarg.mode = SEEK_SET;
10027  rb_protect(seek_before_access, (VALUE)&sarg, &state);
10028  if (state) {
10029  rb_io_close(arg.io);
10030  rb_jump_tag(state);
10031  }
10032  }
10033  return rb_ensure(io_s_read, (VALUE)&arg, rb_io_close, arg.io);
10034 }
10035 
10036 static VALUE
10038 {
10039  return io_write(arg->io,arg->str,arg->nosync);
10040 }
10041 
10042 static VALUE
10043 io_s_write(int argc, VALUE *argv, int binary)
10044 {
10045  VALUE string, offset, opt;
10046  struct foreach_arg arg;
10047  struct write_arg warg;
10048 
10049  rb_scan_args(argc, argv, "21:", NULL, &string, &offset, &opt);
10050 
10051  if (NIL_P(opt)) opt = rb_hash_new();
10052  else opt = rb_hash_dup(opt);
10053 
10054 
10055  if (NIL_P(rb_hash_aref(opt,sym_mode))) {
10056  int mode = O_WRONLY|O_CREAT;
10057 #ifdef O_BINARY
10058  if (binary) mode |= O_BINARY;
10059 #endif
10060  if (NIL_P(offset)) mode |= O_TRUNC;
10061  rb_hash_aset(opt,sym_mode,INT2NUM(mode));
10062  }
10063  open_key_args(argc,argv,opt,&arg);
10064 
10065 #ifndef O_BINARY
10066  if (binary) rb_io_binmode_m(arg.io);
10067 #endif
10068 
10069  if (NIL_P(arg.io)) return Qnil;
10070  if (!NIL_P(offset)) {
10071  struct seek_arg sarg;
10072  int state = 0;
10073  sarg.io = arg.io;
10074  sarg.offset = offset;
10075  sarg.mode = SEEK_SET;
10076  rb_protect(seek_before_access, (VALUE)&sarg, &state);
10077  if (state) {
10078  rb_io_close(arg.io);
10079  rb_jump_tag(state);
10080  }
10081  }
10082 
10083  warg.io = arg.io;
10084  warg.str = string;
10085  warg.nosync = 0;
10086 
10087  return rb_ensure(io_s_write0, (VALUE)&warg, rb_io_close, arg.io);
10088 }
10089 
10090 /*
10091  * call-seq:
10092  * IO.write(name, string [, offset]) -> integer
10093  * IO.write(name, string [, offset] [, opt]) -> integer
10094  *
10095  * Opens the file, optionally seeks to the given <i>offset</i>, writes
10096  * <i>string</i>, then returns the length written.
10097  * <code>write</code> ensures the file is closed before returning.
10098  * If <i>offset</i> is not given, the file is truncated. Otherwise,
10099  * it is not truncated.
10100  *
10101  * IO.write("testfile", "0123456789", 20) #=> 10
10102  * # File could contain: "This is line one\nThi0123456789two\nThis is line three\nAnd so on...\n"
10103  * IO.write("testfile", "0123456789") #=> 10
10104  * # File would now read: "0123456789"
10105  *
10106  * If the last argument is a hash, it specifies options for the internal
10107  * open(). It accepts the following keys:
10108  *
10109  * :encoding::
10110  * string or encoding
10111  *
10112  * Specifies the encoding of the read string.
10113  * See Encoding.aliases for possible encodings.
10114  *
10115  * :mode::
10116  * string
10117  *
10118  * Specifies the <i>mode</i> argument for open(). It must start
10119  * with "w", "a", or "r+", otherwise it will cause an error.
10120  * See IO.new for the list of possible modes.
10121  *
10122  * :perm::
10123  * integer
10124  *
10125  * Specifies the <i>perm</i> argument for open().
10126  *
10127  * :open_args::
10128  * array
10129  *
10130  * Specifies arguments for open() as an array.
10131  * This key can not be used in combination with other keys.
10132  */
10133 
10134 static VALUE
10136 {
10137  return io_s_write(argc, argv, 0);
10138 }
10139 
10140 /*
10141  * call-seq:
10142  * IO.binwrite(name, string, [offset] ) -> integer
10143  * IO.binwrite(name, string, [offset], open_args ) -> integer
10144  *
10145  * Same as <code>IO.write</code> except opening the file in binary mode
10146  * and ASCII-8BIT encoding ("wb:ASCII-8BIT").
10147  */
10148 
10149 static VALUE
10151 {
10152  return io_s_write(argc, argv, 1);
10153 }
10154 
10158  off_t copy_length; /* (off_t)-1 if not specified */
10159  off_t src_offset; /* (off_t)-1 if not specified */
10160 
10161  int src_fd;
10162  int dst_fd;
10166  const char *syserr;
10168  const char *notimp;
10171 };
10172 
10173 static void *
10175 {
10176  VALUE th = (VALUE)arg;
10178  return NULL;
10179 }
10180 
10181 /*
10182  * returns TRUE if the preceding system call was interrupted
10183  * so we can continue. If the thread was interrupted, we
10184  * reacquire the GVL to execute interrupts before continuing.
10185  */
10186 static int
10188 {
10189  switch (errno) {
10190  case EINTR:
10191 #if defined(ERESTART)
10192  case ERESTART:
10193 #endif
10194  if (rb_thread_interrupted(stp->th)) {
10195  if (has_gvl)
10197  else
10199  }
10200  return TRUE;
10201  }
10202  return FALSE;
10203 }
10204 
10205 /* non-Linux poll may not work on all FDs */
10206 #if defined(HAVE_POLL) && defined(__linux__)
10207 # define USE_POLL 1
10208 # define IOWAIT_SYSCALL "poll"
10209 #else
10210 # define IOWAIT_SYSCALL "select"
10211 # define USE_POLL 0
10212 #endif
10213 
10214 #if USE_POLL
10215 static int
10216 nogvl_wait_for_single_fd(int fd, short events)
10217 {
10218  struct pollfd fds;
10219 
10220  fds.fd = fd;
10221  fds.events = events;
10222 
10223  return poll(&fds, 1, -1);
10224 }
10225 
10226 static int
10227 maygvl_copy_stream_wait_read(int has_gvl, struct copy_stream_struct *stp)
10228 {
10229  int ret;
10230 
10231  do {
10232  if (has_gvl) {
10234  }
10235  else {
10236  ret = nogvl_wait_for_single_fd(stp->src_fd, POLLIN);
10237  }
10238  } while (ret == -1 && maygvl_copy_stream_continue_p(has_gvl, stp));
10239 
10240  if (ret == -1) {
10241  stp->syserr = "poll";
10242  stp->error_no = errno;
10243  return -1;
10244  }
10245  return 0;
10246 }
10247 #else /* !USE_POLL */
10248 static int
10249 maygvl_select(int has_gvl, int n, rb_fdset_t *rfds, rb_fdset_t *wfds, rb_fdset_t *efds, struct timeval *timeout)
10250 {
10251  if (has_gvl)
10252  return rb_thread_fd_select(n, rfds, wfds, efds, timeout);
10253  else
10254  return rb_fd_select(n, rfds, wfds, efds, timeout);
10255 }
10256 
10257 static int
10259 {
10260  int ret;
10261 
10262  do {
10263  rb_fd_zero(&stp->fds);
10264  rb_fd_set(stp->src_fd, &stp->fds);
10265  ret = maygvl_select(has_gvl, rb_fd_max(&stp->fds), &stp->fds, NULL, NULL, NULL);
10266  } while (ret == -1 && maygvl_copy_stream_continue_p(has_gvl, stp));
10267 
10268  if (ret == -1) {
10269  stp->syserr = "select";
10270  stp->error_no = errno;
10271  return -1;
10272  }
10273  return 0;
10274 }
10275 #endif /* !USE_POLL */
10276 
10277 static int
10279 {
10280  int ret;
10281 
10282  do {
10283 #if USE_POLL
10284  ret = nogvl_wait_for_single_fd(stp->dst_fd, POLLOUT);
10285 #else
10286  rb_fd_zero(&stp->fds);
10287  rb_fd_set(stp->dst_fd, &stp->fds);
10288  ret = rb_fd_select(rb_fd_max(&stp->fds), NULL, &stp->fds, NULL, NULL);
10289 #endif
10290  } while (ret == -1 && maygvl_copy_stream_continue_p(0, stp));
10291 
10292  if (ret == -1) {
10293  stp->syserr = IOWAIT_SYSCALL;
10294  stp->error_no = errno;
10295  return -1;
10296  }
10297  return 0;
10298 }
10299 
10300 #ifdef HAVE_SENDFILE
10301 
10302 # ifdef __linux__
10303 # define USE_SENDFILE
10304 
10305 # ifdef HAVE_SYS_SENDFILE_H
10306 # include <sys/sendfile.h>
10307 # endif
10308 
10309 static ssize_t
10310 simple_sendfile(int out_fd, int in_fd, off_t *offset, off_t count)
10311 {
10312  return sendfile(out_fd, in_fd, offset, (size_t)count);
10313 }
10314 
10315 # elif 0 /* defined(__FreeBSD__) || defined(__DragonFly__) */ || defined(__APPLE__)
10316 /* This runs on FreeBSD8.1 r30210, but sendfiles blocks its execution
10317  * without cpuset -l 0.
10318  */
10319 # define USE_SENDFILE
10320 
10321 static ssize_t
10322 simple_sendfile(int out_fd, int in_fd, off_t *offset, off_t count)
10323 {
10324  int r;
10325  off_t pos = offset ? *offset : lseek(in_fd, 0, SEEK_CUR);
10326  off_t sbytes;
10327 # ifdef __APPLE__
10328  r = sendfile(in_fd, out_fd, pos, &count, NULL, 0);
10329  sbytes = count;
10330 # else
10331  r = sendfile(in_fd, out_fd, pos, (size_t)count, NULL, &sbytes, 0);
10332 # endif
10333  if (r != 0 && sbytes == 0) return -1;
10334  if (offset) {
10335  *offset += sbytes;
10336  }
10337  else {
10338  lseek(in_fd, sbytes, SEEK_CUR);
10339  }
10340  return (ssize_t)sbytes;
10341 }
10342 
10343 # endif
10344 
10345 #endif
10346 
10347 #ifdef USE_SENDFILE
10348 static int
10349 nogvl_copy_stream_sendfile(struct copy_stream_struct *stp)
10350 {
10351  struct stat src_stat, dst_stat;
10352  ssize_t ss;
10353  int ret;
10354 
10355  off_t copy_length;
10356  off_t src_offset;
10357  int use_pread;
10358 
10359  ret = fstat(stp->src_fd, &src_stat);
10360  if (ret == -1) {
10361  stp->syserr = "fstat";
10362  stp->error_no = errno;
10363  return -1;
10364  }
10365  if (!S_ISREG(src_stat.st_mode))
10366  return 0;
10367 
10368  ret = fstat(stp->dst_fd, &dst_stat);
10369  if (ret == -1) {
10370  stp->syserr = "fstat";
10371  stp->error_no = errno;
10372  return -1;
10373  }
10374 #ifndef __linux__
10375  if ((dst_stat.st_mode & S_IFMT) != S_IFSOCK)
10376  return 0;
10377 #endif
10378 
10379  src_offset = stp->src_offset;
10380  use_pread = src_offset != (off_t)-1;
10381 
10382  copy_length = stp->copy_length;
10383  if (copy_length == (off_t)-1) {
10384  if (use_pread)
10385  copy_length = src_stat.st_size - src_offset;
10386  else {
10387  off_t cur;
10388  errno = 0;
10389  cur = lseek(stp->src_fd, 0, SEEK_CUR);
10390  if (cur == (off_t)-1 && errno) {
10391  stp->syserr = "lseek";
10392  stp->error_no = errno;
10393  return -1;
10394  }
10395  copy_length = src_stat.st_size - cur;
10396  }
10397  }
10398 
10399  retry_sendfile:
10400 # if SIZEOF_OFF_T > SIZEOF_SIZE_T
10401  /* we are limited by the 32-bit ssize_t return value on 32-bit */
10402  ss = (copy_length > (off_t)SSIZE_MAX) ? SSIZE_MAX : (ssize_t)copy_length;
10403 # else
10404  ss = (ssize_t)copy_length;
10405 # endif
10406  if (use_pread) {
10407  ss = simple_sendfile(stp->dst_fd, stp->src_fd, &src_offset, ss);
10408  }
10409  else {
10410  ss = simple_sendfile(stp->dst_fd, stp->src_fd, NULL, ss);
10411  }
10412  if (0 < ss) {
10413  stp->total += ss;
10414  copy_length -= ss;
10415  if (0 < copy_length) {
10416  goto retry_sendfile;
10417  }
10418  }
10419  if (ss == -1) {
10420  if (maygvl_copy_stream_continue_p(0, stp))
10421  goto retry_sendfile;
10422  switch (errno) {
10423  case EINVAL:
10424 #ifdef ENOSYS
10425  case ENOSYS:
10426 #endif
10427  return 0;
10428  case EAGAIN:
10429 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
10430  case EWOULDBLOCK:
10431 #endif
10432 #ifndef __linux__
10433  /*
10434  * Linux requires stp->src_fd to be a mmap-able (regular) file,
10435  * select() reports regular files to always be "ready", so
10436  * there is no need to select() on it.
10437  * Other OSes may have the same limitation for sendfile() which
10438  * allow us to bypass maygvl_copy_stream_wait_read()...
10439  */
10440  if (maygvl_copy_stream_wait_read(0, stp) == -1)
10441  return -1;
10442 #endif
10443  if (nogvl_copy_stream_wait_write(stp) == -1)
10444  return -1;
10445  goto retry_sendfile;
10446  }
10447  stp->syserr = "sendfile";
10448  stp->error_no = errno;
10449  return -1;
10450  }
10451  return 1;
10452 }
10453 #endif
10454 
10455 static ssize_t
10456 maygvl_read(int has_gvl, int fd, void *buf, size_t count)
10457 {
10458  if (has_gvl)
10459  return rb_read_internal(fd, buf, count);
10460  else
10461  return read(fd, buf, count);
10462 }
10463 
10464 static ssize_t
10465 maygvl_copy_stream_read(int has_gvl, struct copy_stream_struct *stp, char *buf, size_t len, off_t offset)
10466 {
10467  ssize_t ss;
10468  retry_read:
10469  if (offset == (off_t)-1) {
10470  ss = maygvl_read(has_gvl, stp->src_fd, buf, len);
10471  }
10472  else {
10473 #ifdef HAVE_PREAD
10474  ss = pread(stp->src_fd, buf, len, offset);
10475 #else
10476  stp->notimp = "pread";
10477  return -1;
10478 #endif
10479  }
10480  if (ss == 0) {
10481  return 0;
10482  }
10483  if (ss == -1) {
10484  if (maygvl_copy_stream_continue_p(has_gvl, stp))
10485  goto retry_read;
10486  switch (errno) {
10487  case EAGAIN:
10488 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
10489  case EWOULDBLOCK:
10490 #endif
10491  if (maygvl_copy_stream_wait_read(has_gvl, stp) == -1)
10492  return -1;
10493  goto retry_read;
10494 #ifdef ENOSYS
10495  case ENOSYS:
10496  stp->notimp = "pread";
10497  return -1;
10498 #endif
10499  }
10500  stp->syserr = offset == (off_t)-1 ? "read" : "pread";
10501  stp->error_no = errno;
10502  return -1;
10503  }
10504  return ss;
10505 }
10506 
10507 static int
10509 {
10510  ssize_t ss;
10511  int off = 0;
10512  while (len) {
10513  ss = write(stp->dst_fd, buf+off, len);
10514  if (ss == -1) {
10515  if (maygvl_copy_stream_continue_p(0, stp))
10516  continue;
10517  if (errno == EAGAIN || errno == EWOULDBLOCK) {
10518  if (nogvl_copy_stream_wait_write(stp) == -1)
10519  return -1;
10520  continue;
10521  }
10522  stp->syserr = "write";
10523  stp->error_no = errno;
10524  return -1;
10525  }
10526  off += (int)ss;
10527  len -= (int)ss;
10528  stp->total += ss;
10529  }
10530  return 0;
10531 }
10532 
10533 static void
10535 {
10536  char buf[1024*16];
10537  size_t len;
10538  ssize_t ss;
10539  int ret;
10540  off_t copy_length;
10541  int use_eof;
10542  off_t src_offset;
10543  int use_pread;
10544 
10545  copy_length = stp->copy_length;
10546  use_eof = copy_length == (off_t)-1;
10547  src_offset = stp->src_offset;
10548  use_pread = src_offset != (off_t)-1;
10549 
10550  if (use_pread && stp->close_src) {
10551  off_t r;
10552  errno = 0;
10553  r = lseek(stp->src_fd, src_offset, SEEK_SET);
10554  if (r == (off_t)-1 && errno) {
10555  stp->syserr = "lseek";
10556  stp->error_no = errno;
10557  return;
10558  }
10559  src_offset = (off_t)-1;
10560  use_pread = 0;
10561  }
10562 
10563  while (use_eof || 0 < copy_length) {
10564  if (!use_eof && copy_length < (off_t)sizeof(buf)) {
10565  len = (size_t)copy_length;
10566  }
10567  else {
10568  len = sizeof(buf);
10569  }
10570  if (use_pread) {
10571  ss = maygvl_copy_stream_read(0, stp, buf, len, src_offset);
10572  if (0 < ss)
10573  src_offset += ss;
10574  }
10575  else {
10576  ss = maygvl_copy_stream_read(0, stp, buf, len, (off_t)-1);
10577  }
10578  if (ss <= 0) /* EOF or error */
10579  return;
10580 
10581  ret = nogvl_copy_stream_write(stp, buf, ss);
10582  if (ret < 0)
10583  return;
10584 
10585  if (!use_eof)
10586  copy_length -= ss;
10587  }
10588 }
10589 
10590 static void *
10592 {
10593  struct copy_stream_struct *stp = (struct copy_stream_struct *)arg;
10594 #ifdef USE_SENDFILE
10595  int ret;
10596 #endif
10597 
10598 #ifdef USE_SENDFILE
10599  ret = nogvl_copy_stream_sendfile(stp);
10600  if (ret != 0)
10601  goto finish; /* error or success */
10602 #endif
10603 
10605 
10606 #ifdef USE_SENDFILE
10607  finish:
10608 #endif
10609  return 0;
10610 }
10611 
10612 static VALUE
10614 {
10615  struct copy_stream_struct *stp = (struct copy_stream_struct *)arg;
10616  const int buflen = 16*1024;
10617  VALUE n;
10618  VALUE buf = rb_str_buf_new(buflen);
10619  off_t rest = stp->copy_length;
10620  off_t off = stp->src_offset;
10621  ID read_method = id_readpartial;
10622 
10623  if (stp->src_fd == -1) {
10624  if (!rb_respond_to(stp->src, read_method)) {
10625  read_method = id_read;
10626  }
10627  }
10628 
10629  while (1) {
10630  long numwrote;
10631  long l;
10632  if (stp->copy_length == (off_t)-1) {
10633  l = buflen;
10634  }
10635  else {
10636  if (rest == 0)
10637  break;
10638  l = buflen < rest ? buflen : (long)rest;
10639  }
10640  if (stp->src_fd == -1) {
10641  VALUE rc = rb_funcall(stp->src, read_method, 2, INT2FIX(l), buf);
10642 
10643  if (read_method == id_read && NIL_P(rc))
10644  break;
10645  }
10646  else {
10647  ssize_t ss;
10648  rb_str_resize(buf, buflen);
10649  ss = maygvl_copy_stream_read(1, stp, RSTRING_PTR(buf), l, off);
10650  rb_str_resize(buf, ss > 0 ? ss : 0);
10651  if (ss == -1)
10652  return Qnil;
10653  if (ss == 0)
10654  rb_eof_error();
10655  if (off != (off_t)-1)
10656  off += ss;
10657  }
10658  n = rb_io_write(stp->dst, buf);
10659  numwrote = NUM2LONG(n);
10660  stp->total += numwrote;
10661  rest -= numwrote;
10662  if (read_method == id_read && RSTRING_LEN(buf) == 0) {
10663  break;
10664  }
10665  }
10666 
10667  return Qnil;
10668 }
10669 
10670 static VALUE
10672 {
10673  if (stp->src_fd == -1 && stp->src_offset != (off_t)-1) {
10674  rb_raise(rb_eArgError, "cannot specify src_offset for non-IO");
10675  }
10677  (VALUE (*) (ANYARGS))0, (VALUE)0,
10678  rb_eEOFError, (VALUE)0);
10679  return Qnil;
10680 }
10681 
10682 static VALUE
10684 {
10685  struct copy_stream_struct *stp = (struct copy_stream_struct *)arg;
10686  VALUE src_io = stp->src, dst_io = stp->dst;
10687  rb_io_t *src_fptr = 0, *dst_fptr = 0;
10688  int src_fd, dst_fd;
10689  const int common_oflags = 0
10690 #ifdef O_NOCTTY
10691  | O_NOCTTY
10692 #endif
10693  ;
10694 
10695  stp->th = rb_thread_current();
10696 
10697  stp->total = 0;
10698 
10699  if (src_io == argf ||
10700  !(RB_TYPE_P(src_io, T_FILE) ||
10701  RB_TYPE_P(src_io, T_STRING) ||
10702  rb_respond_to(src_io, rb_intern("to_path")))) {
10703  src_fd = -1;
10704  }
10705  else {
10706  VALUE tmp_io = rb_io_check_io(src_io);
10707  if (!NIL_P(tmp_io)) {
10708  src_io = tmp_io;
10709  }
10710  else if (!RB_TYPE_P(src_io, T_FILE)) {
10711  VALUE args[2];
10712  FilePathValue(src_io);
10713  args[0] = src_io;
10714  args[1] = INT2NUM(O_RDONLY|common_oflags);
10715  src_io = rb_class_new_instance(2, args, rb_cFile);
10716  stp->src = src_io;
10717  stp->close_src = 1;
10718  }
10719  GetOpenFile(src_io, src_fptr);
10720  rb_io_check_byte_readable(src_fptr);
10721  src_fd = src_fptr->fd;
10722  }
10723  stp->src_fd = src_fd;
10724 
10725  if (dst_io == argf ||
10726  !(RB_TYPE_P(dst_io, T_FILE) ||
10727  RB_TYPE_P(dst_io, T_STRING) ||
10728  rb_respond_to(dst_io, rb_intern("to_path")))) {
10729  dst_fd = -1;
10730  }
10731  else {
10732  VALUE tmp_io = rb_io_check_io(dst_io);
10733  if (!NIL_P(tmp_io)) {
10734  dst_io = GetWriteIO(tmp_io);
10735  }
10736  else if (!RB_TYPE_P(dst_io, T_FILE)) {
10737  VALUE args[3];
10738  FilePathValue(dst_io);
10739  args[0] = dst_io;
10740  args[1] = INT2NUM(O_WRONLY|O_CREAT|O_TRUNC|common_oflags);
10741  args[2] = INT2FIX(0666);
10742  dst_io = rb_class_new_instance(3, args, rb_cFile);
10743  stp->dst = dst_io;
10744  stp->close_dst = 1;
10745  }
10746  else {
10747  dst_io = GetWriteIO(dst_io);
10748  stp->dst = dst_io;
10749  }
10750  GetOpenFile(dst_io, dst_fptr);
10751  rb_io_check_writable(dst_fptr);
10752  dst_fd = dst_fptr->fd;
10753  }
10754  stp->dst_fd = dst_fd;
10755 
10756 #ifdef O_BINARY
10757  if (src_fptr)
10759 #endif
10760  if (dst_fptr)
10761  io_ascii8bit_binmode(dst_fptr);
10762 
10763  if (stp->src_offset == (off_t)-1 && src_fptr && src_fptr->rbuf.len) {
10764  size_t len = src_fptr->rbuf.len;
10765  VALUE str;
10766  if (stp->copy_length != (off_t)-1 && stp->copy_length < (off_t)len) {
10767  len = (size_t)stp->copy_length;
10768  }
10769  str = rb_str_buf_new(len);
10770  rb_str_resize(str,len);
10771  read_buffered_data(RSTRING_PTR(str), len, src_fptr);
10772  if (dst_fptr) { /* IO or filename */
10773  if (io_binwrite(str, RSTRING_PTR(str), RSTRING_LEN(str), dst_fptr, 0) < 0)
10774  rb_sys_fail(0);
10775  }
10776  else /* others such as StringIO */
10777  rb_io_write(dst_io, str);
10778  stp->total += len;
10779  if (stp->copy_length != (off_t)-1)
10780  stp->copy_length -= len;
10781  }
10782 
10783  if (dst_fptr && io_fflush(dst_fptr) < 0) {
10784  rb_raise(rb_eIOError, "flush failed");
10785  }
10786 
10787  if (stp->copy_length == 0)
10788  return Qnil;
10789 
10790  if (src_fd == -1 || dst_fd == -1) {
10791  return copy_stream_fallback(stp);
10792  }
10793 
10794  rb_fd_set(src_fd, &stp->fds);
10795  rb_fd_set(dst_fd, &stp->fds);
10796 
10798  return Qnil;
10799 }
10800 
10801 static VALUE
10803 {
10804  struct copy_stream_struct *stp = (struct copy_stream_struct *)arg;
10805  if (stp->close_src) {
10806  rb_io_close_m(stp->src);
10807  }
10808  if (stp->close_dst) {
10809  rb_io_close_m(stp->dst);
10810  }
10811  rb_fd_term(&stp->fds);
10812  if (stp->syserr) {
10813  rb_syserr_fail(stp->error_no, stp->syserr);
10814  }
10815  if (stp->notimp) {
10816  rb_raise(rb_eNotImpError, "%s() not implemented", stp->notimp);
10817  }
10818  return Qnil;
10819 }
10820 
10821 /*
10822  * call-seq:
10823  * IO.copy_stream(src, dst)
10824  * IO.copy_stream(src, dst, copy_length)
10825  * IO.copy_stream(src, dst, copy_length, src_offset)
10826  *
10827  * IO.copy_stream copies <i>src</i> to <i>dst</i>.
10828  * <i>src</i> and <i>dst</i> is either a filename or an IO.
10829  *
10830  * This method returns the number of bytes copied.
10831  *
10832  * If optional arguments are not given,
10833  * the start position of the copy is
10834  * the beginning of the filename or
10835  * the current file offset of the IO.
10836  * The end position of the copy is the end of file.
10837  *
10838  * If <i>copy_length</i> is given,
10839  * No more than <i>copy_length</i> bytes are copied.
10840  *
10841  * If <i>src_offset</i> is given,
10842  * it specifies the start position of the copy.
10843  *
10844  * When <i>src_offset</i> is specified and
10845  * <i>src</i> is an IO,
10846  * IO.copy_stream doesn't move the current file offset.
10847  *
10848  */
10849 static VALUE
10851 {
10852  VALUE src, dst, length, src_offset;
10853  struct copy_stream_struct st;
10854 
10855  MEMZERO(&st, struct copy_stream_struct, 1);
10856 
10857  rb_scan_args(argc, argv, "22", &src, &dst, &length, &src_offset);
10858 
10859  st.src = src;
10860  st.dst = dst;
10861 
10862  if (NIL_P(length))
10863  st.copy_length = (off_t)-1;
10864  else
10865  st.copy_length = NUM2OFFT(length);
10866 
10867  if (NIL_P(src_offset))
10868  st.src_offset = (off_t)-1;
10869  else
10870  st.src_offset = NUM2OFFT(src_offset);
10871 
10872  rb_fd_init(&st.fds);
10874 
10875  return OFFT2NUM(st.total);
10876 }
10877 
10878 /*
10879  * call-seq:
10880  * io.external_encoding -> encoding
10881  *
10882  * Returns the Encoding object that represents the encoding of the file.
10883  * If _io_ is in write mode and no encoding is specified, returns +nil+.
10884  */
10885 
10886 static VALUE
10888 {
10889  rb_io_t *fptr;
10890 
10891  GetOpenFile(io, fptr);
10892  if (fptr->encs.enc2) {
10893  return rb_enc_from_encoding(fptr->encs.enc2);
10894  }
10895  if (fptr->mode & FMODE_WRITABLE) {
10896  if (fptr->encs.enc)
10897  return rb_enc_from_encoding(fptr->encs.enc);
10898  return Qnil;
10899  }
10900  return rb_enc_from_encoding(io_read_encoding(fptr));
10901 }
10902 
10903 /*
10904  * call-seq:
10905  * io.internal_encoding -> encoding
10906  *
10907  * Returns the Encoding of the internal string if conversion is
10908  * specified. Otherwise returns +nil+.
10909  */
10910 
10911 static VALUE
10913 {
10914  rb_io_t *fptr;
10915 
10916  GetOpenFile(io, fptr);
10917  if (!fptr->encs.enc2) return Qnil;
10918  return rb_enc_from_encoding(io_read_encoding(fptr));
10919 }
10920 
10921 /*
10922  * call-seq:
10923  * io.set_encoding(ext_enc) -> io
10924  * io.set_encoding("ext_enc:int_enc") -> io
10925  * io.set_encoding(ext_enc, int_enc) -> io
10926  * io.set_encoding("ext_enc:int_enc", opt) -> io
10927  * io.set_encoding(ext_enc, int_enc, opt) -> io
10928  *
10929  * If single argument is specified, read string from io is tagged
10930  * with the encoding specified. If encoding is a colon separated two
10931  * encoding names "A:B", the read string is converted from encoding A
10932  * (external encoding) to encoding B (internal encoding), then tagged
10933  * with B. If two arguments are specified, those must be encoding
10934  * objects or encoding names, and the first one is the external encoding, and the
10935  * second one is the internal encoding.
10936  * If the external encoding and the internal encoding is specified,
10937  * optional hash argument specify the conversion option.
10938  */
10939 
10940 static VALUE
10942 {
10943  rb_io_t *fptr;
10944  VALUE v1, v2, opt;
10945 
10946  if (!RB_TYPE_P(io, T_FILE)) {
10947  return rb_funcallv(io, id_set_encoding, argc, argv);
10948  }
10949 
10950  argc = rb_scan_args(argc, argv, "11:", &v1, &v2, &opt);
10951  GetOpenFile(io, fptr);
10952  io_encoding_set(fptr, v1, v2, opt);
10953  return io;
10954 }
10955 
10956 void
10958 {
10959  VALUE val = Qnil;
10960 
10961  rb_io_set_encoding(1, &val, rb_stdin);
10962  rb_io_set_encoding(1, &val, rb_stdout);
10963  rb_io_set_encoding(1, &val, rb_stderr);
10964 }
10965 
10966 static inline int
10968 {
10969  return arg == argf;
10970 }
10971 
10972 /*
10973  * call-seq:
10974  * ARGF.external_encoding -> encoding
10975  *
10976  * Returns the external encoding for files read from +ARGF+ as an +Encoding+
10977  * object. The external encoding is the encoding of the text as stored in a
10978  * file. Contrast with +ARGF.internal_encoding+, which is the encoding used
10979  * to represent this text within Ruby.
10980  *
10981  * To set the external encoding use +ARGF.set_encoding+.
10982  *
10983  * For example:
10984  *
10985  * ARGF.external_encoding #=> #<Encoding:UTF-8>
10986  *
10987  */
10988 static VALUE
10990 {
10991  if (!RTEST(ARGF.current_file)) {
10993  }
10994  return rb_io_external_encoding(rb_io_check_io(ARGF.current_file));
10995 }
10996 
10997 /*
10998  * call-seq:
10999  * ARGF.internal_encoding -> encoding
11000  *
11001  * Returns the internal encoding for strings read from +ARGF+ as an
11002  * +Encoding+ object.
11003  *
11004  * If +ARGF.set_encoding+ has been called with two encoding names, the second
11005  * is returned. Otherwise, if +Encoding.default_external+ has been set, that
11006  * value is returned. Failing that, if a default external encoding was
11007  * specified on the command-line, that value is used. If the encoding is
11008  * unknown, +nil+ is returned.
11009  */
11010 static VALUE
11012 {
11013  if (!RTEST(ARGF.current_file)) {
11015  }
11016  return rb_io_internal_encoding(rb_io_check_io(ARGF.current_file));
11017 }
11018 
11019 /*
11020  * call-seq:
11021  * ARGF.set_encoding(ext_enc) -> ARGF
11022  * ARGF.set_encoding("ext_enc:int_enc") -> ARGF
11023  * ARGF.set_encoding(ext_enc, int_enc) -> ARGF
11024  * ARGF.set_encoding("ext_enc:int_enc", opt) -> ARGF
11025  * ARGF.set_encoding(ext_enc, int_enc, opt) -> ARGF
11026  *
11027  * If single argument is specified, strings read from ARGF are tagged with
11028  * the encoding specified.
11029  *
11030  * If two encoding names separated by a colon are given, e.g. "ascii:utf-8",
11031  * the read string is converted from the first encoding (external encoding)
11032  * to the second encoding (internal encoding), then tagged with the second
11033  * encoding.
11034  *
11035  * If two arguments are specified, they must be encoding objects or encoding
11036  * names. Again, the first specifies the external encoding; the second
11037  * specifies the internal encoding.
11038  *
11039  * If the external encoding and the internal encoding are specified, the
11040  * optional +Hash+ argument can be used to adjust the conversion process. The
11041  * structure of this hash is explained in the String#encode documentation.
11042  *
11043  * For example:
11044  *
11045  * ARGF.set_encoding('ascii') # Tag the input as US-ASCII text
11046  * ARGF.set_encoding(Encoding::UTF_8) # Tag the input as UTF-8 text
11047  * ARGF.set_encoding('utf-8','ascii') # Transcode the input from US-ASCII
11048  * # to UTF-8.
11049  */
11050 static VALUE
11052 {
11053  rb_io_t *fptr;
11054 
11055  if (!next_argv()) {
11056  rb_raise(rb_eArgError, "no stream to set encoding");
11057  }
11058  rb_io_set_encoding(argc, argv, ARGF.current_file);
11059  GetOpenFile(ARGF.current_file, fptr);
11060  ARGF.encs = fptr->encs;
11061  return argf;
11062 }
11063 
11064 /*
11065  * call-seq:
11066  * ARGF.tell -> Integer
11067  * ARGF.pos -> Integer
11068  *
11069  * Returns the current offset (in bytes) of the current file in +ARGF+.
11070  *
11071  * ARGF.pos #=> 0
11072  * ARGF.gets #=> "This is line one\n"
11073  * ARGF.pos #=> 17
11074  *
11075  */
11076 static VALUE
11078 {
11079  if (!next_argv()) {
11080  rb_raise(rb_eArgError, "no stream to tell");
11081  }
11082  ARGF_FORWARD(0, 0);
11083  return rb_io_tell(ARGF.current_file);
11084 }
11085 
11086 /*
11087  * call-seq:
11088  * ARGF.seek(amount, whence=IO::SEEK_SET) -> 0
11089  *
11090  * Seeks to offset _amount_ (an +Integer+) in the +ARGF+ stream according to
11091  * the value of _whence_. See IO#seek for further details.
11092  */
11093 static VALUE
11095 {
11096  if (!next_argv()) {
11097  rb_raise(rb_eArgError, "no stream to seek");
11098  }
11099  ARGF_FORWARD(argc, argv);
11100  return rb_io_seek_m(argc, argv, ARGF.current_file);
11101 }
11102 
11103 /*
11104  * call-seq:
11105  * ARGF.pos = position -> Integer
11106  *
11107  * Seeks to the position given by _position_ (in bytes) in +ARGF+.
11108  *
11109  * For example:
11110  *
11111  * ARGF.pos = 17
11112  * ARGF.gets #=> "This is line two\n"
11113  */
11114 static VALUE
11116 {
11117  if (!next_argv()) {
11118  rb_raise(rb_eArgError, "no stream to set position");
11119  }
11120  ARGF_FORWARD(1, &offset);
11121  return rb_io_set_pos(ARGF.current_file, offset);
11122 }
11123 
11124 /*
11125  * call-seq:
11126  * ARGF.rewind -> 0
11127  *
11128  * Positions the current file to the beginning of input, resetting
11129  * +ARGF.lineno+ to zero.
11130  *
11131  * ARGF.readline #=> "This is line one\n"
11132  * ARGF.rewind #=> 0
11133  * ARGF.lineno #=> 0
11134  * ARGF.readline #=> "This is line one\n"
11135  */
11136 static VALUE
11138 {
11139  VALUE ret;
11140  int old_lineno;
11141 
11142  if (!next_argv()) {
11143  rb_raise(rb_eArgError, "no stream to rewind");
11144  }
11145  ARGF_FORWARD(0, 0);
11146  old_lineno = RFILE(ARGF.current_file)->fptr->lineno;
11147  ret = rb_io_rewind(ARGF.current_file);
11148  if (!global_argf_p(argf)) {
11149  ARGF.last_lineno = ARGF.lineno -= old_lineno;
11150  }
11151  return ret;
11152 }
11153 
11154 /*
11155  * call-seq:
11156  * ARGF.fileno -> integer
11157  * ARGF.to_i -> integer
11158  *
11159  * Returns an integer representing the numeric file descriptor for
11160  * the current file. Raises an +ArgumentError+ if there isn't a current file.
11161  *
11162  * ARGF.fileno #=> 3
11163  */
11164 static VALUE
11166 {
11167  if (!next_argv()) {
11168  rb_raise(rb_eArgError, "no stream");
11169  }
11170  ARGF_FORWARD(0, 0);
11171  return rb_io_fileno(ARGF.current_file);
11172 }
11173 
11174 /*
11175  * call-seq:
11176  * ARGF.to_io -> IO
11177  *
11178  * Returns an +IO+ object representing the current file. This will be a
11179  * +File+ object unless the current file is a stream such as STDIN.
11180  *
11181  * For example:
11182  *
11183  * ARGF.to_io #=> #<File:glark.txt>
11184  * ARGF.to_io #=> #<IO:<STDIN>>
11185  */
11186 static VALUE
11188 {
11189  next_argv();
11190  ARGF_FORWARD(0, 0);
11191  return ARGF.current_file;
11192 }
11193 
11194 /*
11195  * call-seq:
11196  * ARGF.eof? -> true or false
11197  * ARGF.eof -> true or false
11198  *
11199  * Returns true if the current file in +ARGF+ is at end of file, i.e. it has
11200  * no data to read. The stream must be opened for reading or an +IOError+
11201  * will be raised.
11202  *
11203  * $ echo "eof" | ruby argf.rb
11204  *
11205  * ARGF.eof? #=> false
11206  * 3.times { ARGF.readchar }
11207  * ARGF.eof? #=> false
11208  * ARGF.readchar #=> "\n"
11209  * ARGF.eof? #=> true
11210  */
11211 
11212 static VALUE
11214 {
11215  next_argv();
11216  if (RTEST(ARGF.current_file)) {
11217  if (ARGF.init_p == 0) return Qtrue;
11218  next_argv();
11219  ARGF_FORWARD(0, 0);
11220  if (rb_io_eof(ARGF.current_file)) {
11221  return Qtrue;
11222  }
11223  }
11224  return Qfalse;
11225 }
11226 
11227 /*
11228  * call-seq:
11229  * ARGF.read([length [, outbuf]]) -> string, outbuf, or nil
11230  *
11231  * Reads _length_ bytes from ARGF. The files named on the command line
11232  * are concatenated and treated as a single file by this method, so when
11233  * called without arguments the contents of this pseudo file are returned in
11234  * their entirety.
11235  *
11236  * _length_ must be a non-negative integer or +nil+.
11237  *
11238  * If _length_ is a positive integer, +read+ tries to read
11239  * _length_ bytes without any conversion (binary mode).
11240  * It returns +nil+ if an EOF is encountered before anything can be read.
11241  * Fewer than _length_ bytes are returned if an EOF is encountered during
11242  * the read.
11243  * In the case of an integer _length_, the resulting string is always
11244  * in ASCII-8BIT encoding.
11245  *
11246  * If _length_ is omitted or is +nil+, it reads until EOF
11247  * and the encoding conversion is applied, if applicable.
11248  * A string is returned even if EOF is encountered before any data is read.
11249  *
11250  * If _length_ is zero, it returns an empty string (<code>""</code>).
11251  *
11252  * If the optional _outbuf_ argument is present,
11253  * it must reference a String, which will receive the data.
11254  * The _outbuf_ will contain only the received data after the method call
11255  * even if it is not empty at the beginning.
11256  *
11257  * For example:
11258  *
11259  * $ echo "small" > small.txt
11260  * $ echo "large" > large.txt
11261  * $ ./glark.rb small.txt large.txt
11262  *
11263  * ARGF.read #=> "small\nlarge"
11264  * ARGF.read(200) #=> "small\nlarge"
11265  * ARGF.read(2) #=> "sm"
11266  * ARGF.read(0) #=> ""
11267  *
11268  * Note that this method behaves like the fread() function in C.
11269  * This means it retries to invoke read(2) system calls to read data
11270  * with the specified length.
11271  * If you need the behavior like a single read(2) system call,
11272  * consider ARGF#readpartial or ARGF#read_nonblock.
11273  */
11274 
11275 static VALUE
11277 {
11278  VALUE tmp, str, length;
11279  long len = 0;
11280 
11281  rb_scan_args(argc, argv, "02", &length, &str);
11282  if (!NIL_P(length)) {
11283  len = NUM2LONG(argv[0]);
11284  }
11285  if (!NIL_P(str)) {
11286  StringValue(str);
11287  rb_str_resize(str,0);
11288  argv[1] = Qnil;
11289  }
11290 
11291  retry:
11292  if (!next_argv()) {
11293  return str;
11294  }
11295  if (ARGF_GENERIC_INPUT_P()) {
11296  tmp = argf_forward(argc, argv, argf);
11297  }
11298  else {
11299  tmp = io_read(argc, argv, ARGF.current_file);
11300  }
11301  if (NIL_P(str)) str = tmp;
11302  else if (!NIL_P(tmp)) rb_str_append(str, tmp);
11303  if (NIL_P(tmp) || NIL_P(length)) {
11304  if (ARGF.next_p != -1) {
11305  argf_close(argf);
11306  ARGF.next_p = 1;
11307  goto retry;
11308  }
11309  }
11310  else if (argc >= 1) {
11311  long slen = RSTRING_LEN(str);
11312  if (slen < len) {
11313  len -= slen;
11314  argv[0] = INT2NUM(len);
11315  goto retry;
11316  }
11317  }
11318  return str;
11319 }
11320 
11322  int argc;
11325 };
11326 
11327 static VALUE
11329 {
11330  struct argf_call_arg *p = (struct argf_call_arg *)arg;
11331  argf_forward(p->argc, p->argv, p->argf);
11332  return Qnil;
11333 }
11334 
11335 static VALUE argf_getpartial(int argc, VALUE *argv, VALUE argf, VALUE opts,
11336  int nonblock);
11337 
11338 /*
11339  * call-seq:
11340  * ARGF.readpartial(maxlen) -> string
11341  * ARGF.readpartial(maxlen, outbuf) -> outbuf
11342  *
11343  * Reads at most _maxlen_ bytes from the ARGF stream.
11344  *
11345  * If the optional _outbuf_ argument is present,
11346  * it must reference a String, which will receive the data.
11347  * The _outbuf_ will contain only the received data after the method call
11348  * even if it is not empty at the beginning.
11349  *
11350  * It raises <code>EOFError</code> on end of ARGF stream.
11351  * Since ARGF stream is a concatenation of multiple files,
11352  * internally EOF is occur for each file.
11353  * ARGF.readpartial returns empty strings for EOFs except the last one and
11354  * raises <code>EOFError</code> for the last one.
11355  *
11356  */
11357 
11358 static VALUE
11360 {
11361  return argf_getpartial(argc, argv, argf, Qnil, 0);
11362 }
11363 
11364 /*
11365  * call-seq:
11366  * ARGF.read_nonblock(maxlen) -> string
11367  * ARGF.read_nonblock(maxlen, outbuf) -> outbuf
11368  *
11369  * Reads at most _maxlen_ bytes from the ARGF stream in non-blocking mode.
11370  */
11371 
11372 static VALUE
11374 {
11375  VALUE opts;
11376 
11377  rb_scan_args(argc, argv, "11:", NULL, NULL, &opts);
11378 
11379  if (!NIL_P(opts))
11380  argc--;
11381 
11382  return argf_getpartial(argc, argv, argf, opts, 1);
11383 }
11384 
11385 static VALUE
11386 argf_getpartial(int argc, VALUE *argv, VALUE argf, VALUE opts, int nonblock)
11387 {
11388  VALUE tmp, str, length;
11389 
11390  rb_scan_args(argc, argv, "11", &length, &str);
11391  if (!NIL_P(str)) {
11392  StringValue(str);
11393  argv[1] = str;
11394  }
11395 
11396  if (!next_argv()) {
11397  if (!NIL_P(str)) {
11398  rb_str_resize(str, 0);
11399  }
11400  rb_eof_error();
11401  }
11402  if (ARGF_GENERIC_INPUT_P()) {
11403  struct argf_call_arg arg;
11404  arg.argc = argc;
11405  arg.argv = argv;
11406  arg.argf = argf;
11407  tmp = rb_rescue2(argf_forward_call, (VALUE)&arg,
11409  }
11410  else {
11411  tmp = io_getpartial(argc, argv, ARGF.current_file, opts, nonblock);
11412  }
11413  if (NIL_P(tmp)) {
11414  if (ARGF.next_p == -1) {
11415  return io_nonblock_eof(opts);
11416  }
11417  argf_close(argf);
11418  ARGF.next_p = 1;
11419  if (RARRAY_LEN(ARGF.argv) == 0) {
11420  return io_nonblock_eof(opts);
11421  }
11422  if (NIL_P(str))
11423  str = rb_str_new(NULL, 0);
11424  return str;
11425  }
11426  return tmp;
11427 }
11428 
11429 /*
11430  * call-seq:
11431  * ARGF.getc -> String or nil
11432  *
11433  * Reads the next character from +ARGF+ and returns it as a +String+. Returns
11434  * +nil+ at the end of the stream.
11435  *
11436  * +ARGF+ treats the files named on the command line as a single file created
11437  * by concatenating their contents. After returning the last character of the
11438  * first file, it returns the first character of the second file, and so on.
11439  *
11440  * For example:
11441  *
11442  * $ echo "foo" > file
11443  * $ ruby argf.rb file
11444  *
11445  * ARGF.getc #=> "f"
11446  * ARGF.getc #=> "o"
11447  * ARGF.getc #=> "o"
11448  * ARGF.getc #=> "\n"
11449  * ARGF.getc #=> nil
11450  * ARGF.getc #=> nil
11451  */
11452 static VALUE
11454 {
11455  VALUE ch;
11456 
11457  retry:
11458  if (!next_argv()) return Qnil;
11459  if (ARGF_GENERIC_INPUT_P()) {
11460  ch = rb_funcall3(ARGF.current_file, rb_intern("getc"), 0, 0);
11461  }
11462  else {
11463  ch = rb_io_getc(ARGF.current_file);
11464  }
11465  if (NIL_P(ch) && ARGF.next_p != -1) {
11466  argf_close(argf);
11467  ARGF.next_p = 1;
11468  goto retry;
11469  }
11470 
11471  return ch;
11472 }
11473 
11474 /*
11475  * call-seq:
11476  * ARGF.getbyte -> Integer or nil
11477  *
11478  * Gets the next 8-bit byte (0..255) from +ARGF+. Returns +nil+ if called at
11479  * the end of the stream.
11480  *
11481  * For example:
11482  *
11483  * $ echo "foo" > file
11484  * $ ruby argf.rb file
11485  *
11486  * ARGF.getbyte #=> 102
11487  * ARGF.getbyte #=> 111
11488  * ARGF.getbyte #=> 111
11489  * ARGF.getbyte #=> 10
11490  * ARGF.getbyte #=> nil
11491  */
11492 static VALUE
11494 {
11495  VALUE ch;
11496 
11497  retry:
11498  if (!next_argv()) return Qnil;
11499  if (!RB_TYPE_P(ARGF.current_file, T_FILE)) {
11500  ch = rb_funcall3(ARGF.current_file, rb_intern("getbyte"), 0, 0);
11501  }
11502  else {
11503  ch = rb_io_getbyte(ARGF.current_file);
11504  }
11505  if (NIL_P(ch) && ARGF.next_p != -1) {
11506  argf_close(argf);
11507  ARGF.next_p = 1;
11508  goto retry;
11509  }
11510 
11511  return ch;
11512 }
11513 
11514 /*
11515  * call-seq:
11516  * ARGF.readchar -> String or nil
11517  *
11518  * Reads the next character from +ARGF+ and returns it as a +String+. Raises
11519  * an +EOFError+ after the last character of the last file has been read.
11520  *
11521  * For example:
11522  *
11523  * $ echo "foo" > file
11524  * $ ruby argf.rb file
11525  *
11526  * ARGF.readchar #=> "f"
11527  * ARGF.readchar #=> "o"
11528  * ARGF.readchar #=> "o"
11529  * ARGF.readchar #=> "\n"
11530  * ARGF.readchar #=> end of file reached (EOFError)
11531  */
11532 static VALUE
11534 {
11535  VALUE ch;
11536 
11537  retry:
11538  if (!next_argv()) rb_eof_error();
11539  if (!RB_TYPE_P(ARGF.current_file, T_FILE)) {
11540  ch = rb_funcall3(ARGF.current_file, rb_intern("getc"), 0, 0);
11541  }
11542  else {
11543  ch = rb_io_getc(ARGF.current_file);
11544  }
11545  if (NIL_P(ch) && ARGF.next_p != -1) {
11546  argf_close(argf);
11547  ARGF.next_p = 1;
11548  goto retry;
11549  }
11550 
11551  return ch;
11552 }
11553 
11554 /*
11555  * call-seq:
11556  * ARGF.readbyte -> Integer
11557  *
11558  * Reads the next 8-bit byte from ARGF and returns it as an +Integer+. Raises
11559  * an +EOFError+ after the last byte of the last file has been read.
11560  *
11561  * For example:
11562  *
11563  * $ echo "foo" > file
11564  * $ ruby argf.rb file
11565  *
11566  * ARGF.readbyte #=> 102
11567  * ARGF.readbyte #=> 111
11568  * ARGF.readbyte #=> 111
11569  * ARGF.readbyte #=> 10
11570  * ARGF.readbyte #=> end of file reached (EOFError)
11571  */
11572 static VALUE
11574 {
11575  VALUE c;
11576 
11577  NEXT_ARGF_FORWARD(0, 0);
11578  c = argf_getbyte(argf);
11579  if (NIL_P(c)) {
11580  rb_eof_error();
11581  }
11582  return c;
11583 }
11584 
11585 #define FOREACH_ARGF() while (next_argv())
11586 
11587 static VALUE
11589 {
11590  const VALUE current = ARGF.current_file;
11592  if (ARGF.init_p == -1 || current != ARGF.current_file) {
11594  }
11595  return Qnil;
11596 }
11597 
11598 static void
11600 {
11601  VALUE ret = rb_block_call(ARGF.current_file, mid, argc, argv, argf_block_call_i, argf);
11602  if (ret != Qundef) ARGF.next_p = 1;
11603 }
11604 
11605 static VALUE
11607 {
11608  if (!global_argf_p(argf)) {
11609  ARGF.last_lineno = ++ARGF.lineno;
11610  }
11611  return argf_block_call_i(i, argf, argc, argv, blockarg);
11612 }
11613 
11614 static void
11616 {
11617  VALUE ret = rb_block_call(ARGF.current_file, mid, argc, argv, argf_block_call_line_i, argf);
11618  if (ret != Qundef) ARGF.next_p = 1;
11619 }
11620 
11621 /*
11622  * call-seq:
11623  * ARGF.each(sep=$/) {|line| block } -> ARGF
11624  * ARGF.each(sep=$/, limit) {|line| block } -> ARGF
11625  * ARGF.each(...) -> an_enumerator
11626  *
11627  * ARGF.each_line(sep=$/) {|line| block } -> ARGF
11628  * ARGF.each_line(sep=$/, limit) {|line| block } -> ARGF
11629  * ARGF.each_line(...) -> an_enumerator
11630  *
11631  * Returns an enumerator which iterates over each line (separated by _sep_,
11632  * which defaults to your platform's newline character) of each file in
11633  * +ARGV+. If a block is supplied, each line in turn will be yielded to the
11634  * block, otherwise an enumerator is returned.
11635  * The optional _limit_ argument is an +Integer+ specifying the maximum
11636  * length of each line; longer lines will be split according to this limit.
11637  *
11638  * This method allows you to treat the files supplied on the command line as
11639  * a single file consisting of the concatenation of each named file. After
11640  * the last line of the first file has been returned, the first line of the
11641  * second file is returned. The +ARGF.filename+ and +ARGF.lineno+ methods can
11642  * be used to determine the filename and line number, respectively, of the
11643  * current line.
11644  *
11645  * For example, the following code prints out each line of each named file
11646  * prefixed with its line number, displaying the filename once per file:
11647  *
11648  * ARGF.each_line do |line|
11649  * puts ARGF.filename if ARGF.lineno == 1
11650  * puts "#{ARGF.lineno}: #{line}"
11651  * end
11652  */
11653 static VALUE
11655 {
11656  RETURN_ENUMERATOR(argf, argc, argv);
11657  FOREACH_ARGF() {
11658  argf_block_call_line(rb_intern("each_line"), argc, argv, argf);
11659  }
11660  return argf;
11661 }
11662 
11663 /*
11664  * This is a deprecated alias for <code>each_line</code>.
11665  */
11666 
11667 static VALUE
11669 {
11670  rb_warn("ARGF#lines is deprecated; use #each_line instead");
11671  if (!rb_block_given_p())
11672  return rb_enumeratorize(argf, ID2SYM(rb_intern("each_line")), argc, argv);
11673  return argf_each_line(argc, argv, argf);
11674 }
11675 
11676 /*
11677  * call-seq:
11678  * ARGF.bytes {|byte| block } -> ARGF
11679  * ARGF.bytes -> an_enumerator
11680  *
11681  * ARGF.each_byte {|byte| block } -> ARGF
11682  * ARGF.each_byte -> an_enumerator
11683  *
11684  * Iterates over each byte of each file in +ARGV+.
11685  * A byte is returned as an +Integer+ in the range 0..255.
11686  *
11687  * This method allows you to treat the files supplied on the command line as
11688  * a single file consisting of the concatenation of each named file. After
11689  * the last byte of the first file has been returned, the first byte of the
11690  * second file is returned. The +ARGF.filename+ method can be used to
11691  * determine the filename of the current byte.
11692  *
11693  * If no block is given, an enumerator is returned instead.
11694  *
11695  * For example:
11696  *
11697  * ARGF.bytes.to_a #=> [35, 32, ... 95, 10]
11698  *
11699  */
11700 static VALUE
11702 {
11703  RETURN_ENUMERATOR(argf, 0, 0);
11704  FOREACH_ARGF() {
11705  argf_block_call(rb_intern("each_byte"), 0, 0, argf);
11706  }
11707  return argf;
11708 }
11709 
11710 /*
11711  * This is a deprecated alias for <code>each_byte</code>.
11712  */
11713 
11714 static VALUE
11716 {
11717  rb_warn("ARGF#bytes is deprecated; use #each_byte instead");
11718  if (!rb_block_given_p())
11719  return rb_enumeratorize(argf, ID2SYM(rb_intern("each_byte")), 0, 0);
11720  return argf_each_byte(argf);
11721 }
11722 
11723 /*
11724  * call-seq:
11725  * ARGF.each_char {|char| block } -> ARGF
11726  * ARGF.each_char -> an_enumerator
11727  *
11728  * Iterates over each character of each file in +ARGF+.
11729  *
11730  * This method allows you to treat the files supplied on the command line as
11731  * a single file consisting of the concatenation of each named file. After
11732  * the last character of the first file has been returned, the first
11733  * character of the second file is returned. The +ARGF.filename+ method can
11734  * be used to determine the name of the file in which the current character
11735  * appears.
11736  *
11737  * If no block is given, an enumerator is returned instead.
11738  */
11739 static VALUE
11741 {
11742  RETURN_ENUMERATOR(argf, 0, 0);
11743  FOREACH_ARGF() {
11744  argf_block_call(rb_intern("each_char"), 0, 0, argf);
11745  }
11746  return argf;
11747 }
11748 
11749 /*
11750  * This is a deprecated alias for <code>each_char</code>.
11751  */
11752 
11753 static VALUE
11755 {
11756  rb_warn("ARGF#chars is deprecated; use #each_char instead");
11757  if (!rb_block_given_p())
11758  return rb_enumeratorize(argf, ID2SYM(rb_intern("each_char")), 0, 0);
11759  return argf_each_char(argf);
11760 }
11761 
11762 /*
11763  * call-seq:
11764  * ARGF.each_codepoint {|codepoint| block } -> ARGF
11765  * ARGF.each_codepoint -> an_enumerator
11766  *
11767  * Iterates over each codepoint of each file in +ARGF+.
11768  *
11769  * This method allows you to treat the files supplied on the command line as
11770  * a single file consisting of the concatenation of each named file. After
11771  * the last codepoint of the first file has been returned, the first
11772  * codepoint of the second file is returned. The +ARGF.filename+ method can
11773  * be used to determine the name of the file in which the current codepoint
11774  * appears.
11775  *
11776  * If no block is given, an enumerator is returned instead.
11777  */
11778 static VALUE
11780 {
11781  RETURN_ENUMERATOR(argf, 0, 0);
11782  FOREACH_ARGF() {
11783  argf_block_call(rb_intern("each_codepoint"), 0, 0, argf);
11784  }
11785  return argf;
11786 }
11787 
11788 /*
11789  * This is a deprecated alias for <code>each_codepoint</code>.
11790  */
11791 
11792 static VALUE
11794 {
11795  rb_warn("ARGF#codepoints is deprecated; use #each_codepoint instead");
11796  if (!rb_block_given_p())
11797  return rb_enumeratorize(argf, ID2SYM(rb_intern("each_codepoint")), 0, 0);
11798  return argf_each_codepoint(argf);
11799 }
11800 
11801 /*
11802  * call-seq:
11803  * ARGF.filename -> String
11804  * ARGF.path -> String
11805  *
11806  * Returns the current filename. "-" is returned when the current file is
11807  * STDIN.
11808  *
11809  * For example:
11810  *
11811  * $ echo "foo" > foo
11812  * $ echo "bar" > bar
11813  * $ echo "glark" > glark
11814  *
11815  * $ ruby argf.rb foo bar glark
11816  *
11817  * ARGF.filename #=> "foo"
11818  * ARGF.read(5) #=> "foo\nb"
11819  * ARGF.filename #=> "bar"
11820  * ARGF.skip
11821  * ARGF.filename #=> "glark"
11822  */
11823 static VALUE
11825 {
11826  next_argv();
11827  return ARGF.filename;
11828 }
11829 
11830 static VALUE
11832 {
11833  return argf_filename(*var);
11834 }
11835 
11836 /*
11837  * call-seq:
11838  * ARGF.file -> IO or File object
11839  *
11840  * Returns the current file as an +IO+ or +File+ object.
11841  * <code>#<IO:<STDIN>></code> is returned when the current file is STDIN.
11842  *
11843  * For example:
11844  *
11845  * $ echo "foo" > foo
11846  * $ echo "bar" > bar
11847  *
11848  * $ ruby argf.rb foo bar
11849  *
11850  * ARGF.file #=> #<File:foo>
11851  * ARGF.read(5) #=> "foo\nb"
11852  * ARGF.file #=> #<File:bar>
11853  */
11854 static VALUE
11856 {
11857  next_argv();
11858  return ARGF.current_file;
11859 }
11860 
11861 /*
11862  * call-seq:
11863  * ARGF.binmode -> ARGF
11864  *
11865  * Puts +ARGF+ into binary mode. Once a stream is in binary mode, it cannot
11866  * be reset to non-binary mode. This option has the following effects:
11867  *
11868  * * Newline conversion is disabled.
11869  * * Encoding conversion is disabled.
11870  * * Content is treated as ASCII-8BIT.
11871  */
11872 static VALUE
11874 {
11875  ARGF.binmode = 1;
11876  next_argv();
11877  ARGF_FORWARD(0, 0);
11878  rb_io_ascii8bit_binmode(ARGF.current_file);
11879  return argf;
11880 }
11881 
11882 /*
11883  * call-seq:
11884  * ARGF.binmode? -> true or false
11885  *
11886  * Returns true if +ARGF+ is being read in binary mode; false otherwise.
11887  * To enable binary mode use +ARGF.binmode+.
11888  *
11889  * For example:
11890  *
11891  * ARGF.binmode? #=> false
11892  * ARGF.binmode
11893  * ARGF.binmode? #=> true
11894  */
11895 static VALUE
11897 {
11898  return ARGF.binmode ? Qtrue : Qfalse;
11899 }
11900 
11901 /*
11902  * call-seq:
11903  * ARGF.skip -> ARGF
11904  *
11905  * Sets the current file to the next file in ARGV. If there aren't any more
11906  * files it has no effect.
11907  *
11908  * For example:
11909  *
11910  * $ ruby argf.rb foo bar
11911  * ARGF.filename #=> "foo"
11912  * ARGF.skip
11913  * ARGF.filename #=> "bar"
11914  */
11915 static VALUE
11917 {
11918  if (ARGF.init_p && ARGF.next_p == 0) {
11919  argf_close(argf);
11920  ARGF.next_p = 1;
11921  }
11922  return argf;
11923 }
11924 
11925 /*
11926  * call-seq:
11927  * ARGF.close -> ARGF
11928  *
11929  * Closes the current file and skips to the next file in ARGV. If there are
11930  * no more files to open, just closes the current file. +STDIN+ will not be
11931  * closed.
11932  *
11933  * For example:
11934  *
11935  * $ ruby argf.rb foo bar
11936  *
11937  * ARGF.filename #=> "foo"
11938  * ARGF.close
11939  * ARGF.filename #=> "bar"
11940  * ARGF.close
11941  */
11942 static VALUE
11944 {
11945  next_argv();
11946  argf_close(argf);
11947  if (ARGF.next_p != -1) {
11948  ARGF.next_p = 1;
11949  }
11950  ARGF.lineno = 0;
11951  return argf;
11952 }
11953 
11954 /*
11955  * call-seq:
11956  * ARGF.closed? -> true or false
11957  *
11958  * Returns _true_ if the current file has been closed; _false_ otherwise. Use
11959  * +ARGF.close+ to actually close the current file.
11960  */
11961 static VALUE
11963 {
11964  next_argv();
11965  ARGF_FORWARD(0, 0);
11966  return rb_io_closed(ARGF.current_file);
11967 }
11968 
11969 /*
11970  * call-seq:
11971  * ARGF.to_s -> String
11972  *
11973  * Returns "ARGF".
11974  */
11975 static VALUE
11977 {
11978  return rb_str_new2("ARGF");
11979 }
11980 
11981 /*
11982  * call-seq:
11983  * ARGF.inplace_mode -> String
11984  *
11985  * Returns the file extension appended to the names of modified files under
11986  * in-place edit mode. This value can be set using +ARGF.inplace_mode=+ or
11987  * passing the +-i+ switch to the Ruby binary.
11988  */
11989 static VALUE
11991 {
11992  if (!ARGF.inplace) return Qnil;
11993  return rb_str_new2(ARGF.inplace);
11994 }
11995 
11996 static VALUE
11997 opt_i_get(ID id, VALUE *var)
11998 {
11999  return argf_inplace_mode_get(*var);
12000 }
12001 
12002 /*
12003  * call-seq:
12004  * ARGF.inplace_mode = ext -> ARGF
12005  *
12006  * Sets the filename extension for in-place editing mode to the given String.
12007  * Each file being edited has this value appended to its filename. The
12008  * modified file is saved under this new name.
12009  *
12010  * For example:
12011  *
12012  * $ ruby argf.rb file.txt
12013  *
12014  * ARGF.inplace_mode = '.bak'
12015  * ARGF.each_line do |line|
12016  * print line.sub("foo","bar")
12017  * end
12018  *
12019  * Each line of _file.txt_ has the first occurrence of "foo" replaced with
12020  * "bar", then the new line is written out to _file.txt.bak_.
12021  */
12022 static VALUE
12024 {
12025  if (rb_safe_level() >= 1 && OBJ_TAINTED(val))
12027 
12028  if (!RTEST(val)) {
12029  if (ARGF.inplace) free(ARGF.inplace);
12030  ARGF.inplace = 0;
12031  }
12032  else {
12033  StringValue(val);
12034  if (ARGF.inplace) free(ARGF.inplace);
12035  ARGF.inplace = 0;
12036  ARGF.inplace = strdup(RSTRING_PTR(val));
12037  }
12038  return argf;
12039 }
12040 
12041 static void
12043 {
12044  argf_inplace_mode_set(*var, val);
12045 }
12046 
12047 const char *
12049 {
12050  return ARGF.inplace;
12051 }
12052 
12053 void
12054 ruby_set_inplace_mode(const char *suffix)
12055 {
12056  if (ARGF.inplace) free(ARGF.inplace);
12057  ARGF.inplace = 0;
12058  if (suffix) ARGF.inplace = strdup(suffix);
12059 }
12060 
12061 /*
12062  * call-seq:
12063  * ARGF.argv -> ARGV
12064  *
12065  * Returns the +ARGV+ array, which contains the arguments passed to your
12066  * script, one per element.
12067  *
12068  * For example:
12069  *
12070  * $ ruby argf.rb -v glark.txt
12071  *
12072  * ARGF.argv #=> ["-v", "glark.txt"]
12073  *
12074  */
12075 static VALUE
12077 {
12078  return ARGF.argv;
12079 }
12080 
12081 static VALUE
12083 {
12084  return argf_argv(*var);
12085 }
12086 
12087 VALUE
12089 {
12090  return ARGF.argv;
12091 }
12092 
12093 /*
12094  * call-seq:
12095  * ARGF.to_write_io -> io
12096  *
12097  * Returns IO instance tied to _ARGF_ for writing if inplace mode is
12098  * enabled.
12099  */
12100 static VALUE
12102 {
12103  if (!RTEST(ARGF.current_file)) {
12104  rb_raise(rb_eIOError, "not opened for writing");
12105  }
12106  return GetWriteIO(ARGF.current_file);
12107 }
12108 
12109 /*
12110  * call-seq:
12111  * ARGF.write(string) -> integer
12112  *
12113  * Writes _string_ if inplace mode.
12114  */
12115 static VALUE
12117 {
12118  return rb_io_write(argf_write_io(argf), str);
12119 }
12120 
12121 void
12123 {
12124  rb_readwrite_syserr_fail(writable, errno, mesg);
12125 }
12126 
12127 void
12129 {
12130  VALUE arg;
12131  arg = mesg ? rb_str_new2(mesg) : Qnil;
12132  if (writable == RB_IO_WAIT_WRITABLE) {
12133  switch (n) {
12134  case EAGAIN:
12136  break;
12137 #if EAGAIN != EWOULDBLOCK
12138  case EWOULDBLOCK:
12140  break;
12141 #endif
12142  case EINPROGRESS:
12144  break;
12145  default:
12147  }
12148  }
12149  else if (writable == RB_IO_WAIT_READABLE) {
12150  switch (n) {
12151  case EAGAIN:
12153  break;
12154 #if EAGAIN != EWOULDBLOCK
12155  case EWOULDBLOCK:
12157  break;
12158 #endif
12159  case EINPROGRESS:
12161  break;
12162  default:
12164  }
12165  }
12166  else {
12167  rb_bug("invalid read/write type passed to rb_readwrite_sys_fail: %d", writable);
12168  }
12169 }
12170 
12171 /*
12172  * Document-class: IOError
12173  *
12174  * Raised when an IO operation fails.
12175  *
12176  * File.open("/etc/hosts") {|f| f << "example"}
12177  * #=> IOError: not opened for writing
12178  *
12179  * File.open("/etc/hosts") {|f| f.close; f.read }
12180  * #=> IOError: closed stream
12181  *
12182  * Note that some IO failures raise <code>SystemCallError</code>s
12183  * and these are not subclasses of IOError:
12184  *
12185  * File.open("does/not/exist")
12186  * #=> Errno::ENOENT: No such file or directory - does/not/exist
12187  */
12188 
12189 /*
12190  * Document-class: EOFError
12191  *
12192  * Raised by some IO operations when reaching the end of file. Many IO
12193  * methods exist in two forms,
12194  *
12195  * one that returns +nil+ when the end of file is reached, the other
12196  * raises +EOFError+.
12197  *
12198  * +EOFError+ is a subclass of +IOError+.
12199  *
12200  * file = File.open("/etc/hosts")
12201  * file.read
12202  * file.gets #=> nil
12203  * file.readline #=> EOFError: end of file reached
12204  */
12205 
12206 /*
12207  * Document-class: ARGF
12208  *
12209  * +ARGF+ is a stream designed for use in scripts that process files given as
12210  * command-line arguments or passed in via STDIN.
12211  *
12212  * The arguments passed to your script are stored in the +ARGV+ Array, one
12213  * argument per element. +ARGF+ assumes that any arguments that aren't
12214  * filenames have been removed from +ARGV+. For example:
12215  *
12216  * $ ruby argf.rb --verbose file1 file2
12217  *
12218  * ARGV #=> ["--verbose", "file1", "file2"]
12219  * option = ARGV.shift #=> "--verbose"
12220  * ARGV #=> ["file1", "file2"]
12221  *
12222  * You can now use +ARGF+ to work with a concatenation of each of these named
12223  * files. For instance, +ARGF.read+ will return the contents of _file1_
12224  * followed by the contents of _file2_.
12225  *
12226  * After a file in +ARGV+ has been read +ARGF+ removes it from the Array.
12227  * Thus, after all files have been read +ARGV+ will be empty.
12228  *
12229  * You can manipulate +ARGV+ yourself to control what +ARGF+ operates on. If
12230  * you remove a file from +ARGV+, it is ignored by +ARGF+; if you add files to
12231  * +ARGV+, they are treated as if they were named on the command line. For
12232  * example:
12233  *
12234  * ARGV.replace ["file1"]
12235  * ARGF.readlines # Returns the contents of file1 as an Array
12236  * ARGV #=> []
12237  * ARGV.replace ["file2", "file3"]
12238  * ARGF.read # Returns the contents of file2 and file3
12239  *
12240  * If +ARGV+ is empty, +ARGF+ acts as if it contained STDIN, i.e. the data
12241  * piped to your script. For example:
12242  *
12243  * $ echo "glark" | ruby -e 'p ARGF.read'
12244  * "glark\n"
12245  */
12246 
12247 /*
12248  * The IO class is the basis for all input and output in Ruby.
12249  * An I/O stream may be <em>duplexed</em> (that is, bidirectional), and
12250  * so may use more than one native operating system stream.
12251  *
12252  * Many of the examples in this section use the File class, the only standard
12253  * subclass of IO. The two classes are closely associated. Like the File
12254  * class, the Socket library subclasses from IO (such as TCPSocket or
12255  * UDPSocket).
12256  *
12257  * The Kernel#open method can create an IO (or File) object for these types
12258  * of arguments:
12259  *
12260  * * A plain string represents a filename suitable for the underlying
12261  * operating system.
12262  *
12263  * * A string starting with <code>"|"</code> indicates a subprocess.
12264  * The remainder of the string following the <code>"|"</code> is
12265  * invoked as a process with appropriate input/output channels
12266  * connected to it.
12267  *
12268  * * A string equal to <code>"|-"</code> will create another Ruby
12269  * instance as a subprocess.
12270  *
12271  * The IO may be opened with different file modes (read-only, write-only) and
12272  * encodings for proper conversion. See IO.new for these options. See
12273  * Kernel#open for details of the various command formats described above.
12274  *
12275  * IO.popen, the Open3 library, or Process#spawn may also be used to
12276  * communicate with subprocesses through an IO.
12277  *
12278  * Ruby will convert pathnames between different operating system
12279  * conventions if possible. For instance, on a Windows system the
12280  * filename <code>"/gumby/ruby/test.rb"</code> will be opened as
12281  * <code>"\gumby\ruby\test.rb"</code>. When specifying a Windows-style
12282  * filename in a Ruby string, remember to escape the backslashes:
12283  *
12284  * "C:\\gumby\\ruby\\test.rb"
12285  *
12286  * Our examples here will use the Unix-style forward slashes;
12287  * File::ALT_SEPARATOR can be used to get the platform-specific separator
12288  * character.
12289  *
12290  * The global constant ARGF (also accessible as <code>$<</code>) provides an
12291  * IO-like stream which allows access to all files mentioned on the
12292  * command line (or STDIN if no files are mentioned). ARGF#path and its alias
12293  * ARGF#filename are provided to access the name of the file currently being
12294  * read.
12295  *
12296  * == io/console
12297  *
12298  * The io/console extension provides methods for interacting with the
12299  * console. The console can be accessed from IO.console or the standard
12300  * input/output/error IO objects.
12301  *
12302  * Requiring io/console adds the following methods:
12303  *
12304  * * IO::console
12305  * * IO#raw
12306  * * IO#raw!
12307  * * IO#cooked
12308  * * IO#cooked!
12309  * * IO#getch
12310  * * IO#echo=
12311  * * IO#echo?
12312  * * IO#noecho
12313  * * IO#winsize
12314  * * IO#winsize=
12315  * * IO#iflush
12316  * * IO#ioflush
12317  * * IO#oflush
12318  *
12319  * Example:
12320  *
12321  * require 'io/console'
12322  * rows, columns = $stdout.winsize
12323  * puts "Your screen is #{columns} wide and #{rows} tall"
12324  */
12325 
12326 void
12327 Init_IO(void)
12328 {
12329 #undef rb_intern
12330 #define rb_intern(str) rb_intern_const(str)
12331 
12332  VALUE rb_cARGF;
12333 #ifdef __CYGWIN__
12334 #include <sys/cygwin.h>
12335  static struct __cygwin_perfile pf[] =
12336  {
12337  {"", O_RDONLY | O_BINARY},
12338  {"", O_WRONLY | O_BINARY},
12339  {"", O_RDWR | O_BINARY},
12340  {"", O_APPEND | O_BINARY},
12341  {NULL, 0}
12342  };
12343  cygwin_internal(CW_PERFILE, pf);
12344 #endif
12345 
12347  rb_eEOFError = rb_define_class("EOFError", rb_eIOError);
12348 
12349  id_write = rb_intern("write");
12350  id_read = rb_intern("read");
12351  id_getc = rb_intern("getc");
12352  id_flush = rb_intern("flush");
12353  id_readpartial = rb_intern("readpartial");
12354  id_set_encoding = rb_intern("set_encoding");
12355 
12356  rb_define_global_function("syscall", rb_f_syscall, -1);
12357 
12358  rb_define_global_function("open", rb_f_open, -1);
12359  rb_define_global_function("printf", rb_f_printf, -1);
12360  rb_define_global_function("print", rb_f_print, -1);
12362  rb_define_global_function("puts", rb_f_puts, -1);
12363  rb_define_global_function("gets", rb_f_gets, -1);
12364  rb_define_global_function("readline", rb_f_readline, -1);
12365  rb_define_global_function("select", rb_f_select, -1);
12366 
12367  rb_define_global_function("readlines", rb_f_readlines, -1);
12368 
12370 
12372  rb_define_method(rb_mKernel, "display", rb_obj_display, -1);
12373 
12376 
12377  rb_mWaitReadable = rb_define_module_under(rb_cIO, "WaitReadable");
12378  rb_mWaitWritable = rb_define_module_under(rb_cIO, "WaitWritable");
12383 #if EAGAIN == EWOULDBLOCK
12385  /* same as IO::EAGAINWaitReadable */
12386  rb_define_const(rb_cIO, "EWOULDBLOCKWaitReadable", rb_eEAGAINWaitReadable);
12388  /* same as IO::EAGAINWaitWritable */
12389  rb_define_const(rb_cIO, "EWOULDBLOCKWaitWritable", rb_eEAGAINWaitWritable);
12390 #else
12395 #endif
12400 
12401 #if 0
12402  /* This is necessary only for forcing rdoc handle File::open */
12404 #endif
12405 
12422 
12423  rb_define_method(rb_cIO, "initialize", rb_io_initialize, -1);
12424 
12425  rb_output_fs = Qnil;
12427 
12430  rb_output_rs = Qnil;
12431  OBJ_FREEZE(rb_default_rs); /* avoid modifying RS_default */
12435 
12437 
12438  rb_define_method(rb_cIO, "initialize_copy", rb_io_init_copy, 1);
12439  rb_define_method(rb_cIO, "reopen", rb_io_reopen, -1);
12440 
12441  rb_define_method(rb_cIO, "print", rb_io_print, -1);
12442  rb_define_method(rb_cIO, "putc", rb_io_putc, 1);
12443  rb_define_method(rb_cIO, "puts", rb_io_puts, -1);
12444  rb_define_method(rb_cIO, "printf", rb_io_printf, -1);
12445 
12446  rb_define_method(rb_cIO, "each", rb_io_each_line, -1);
12447  rb_define_method(rb_cIO, "each_line", rb_io_each_line, -1);
12448  rb_define_method(rb_cIO, "each_byte", rb_io_each_byte, 0);
12449  rb_define_method(rb_cIO, "each_char", rb_io_each_char, 0);
12450  rb_define_method(rb_cIO, "each_codepoint", rb_io_each_codepoint, 0);
12451  rb_define_method(rb_cIO, "lines", rb_io_lines, -1);
12452  rb_define_method(rb_cIO, "bytes", rb_io_bytes, 0);
12453  rb_define_method(rb_cIO, "chars", rb_io_chars, 0);
12454  rb_define_method(rb_cIO, "codepoints", rb_io_codepoints, 0);
12455 
12456  rb_define_method(rb_cIO, "syswrite", rb_io_syswrite, 1);
12457  rb_define_method(rb_cIO, "sysread", rb_io_sysread, -1);
12458 
12459  rb_define_method(rb_cIO, "fileno", rb_io_fileno, 0);
12460  rb_define_alias(rb_cIO, "to_i", "fileno");
12461  rb_define_method(rb_cIO, "to_io", rb_io_to_io, 0);
12462 
12463  rb_define_method(rb_cIO, "fsync", rb_io_fsync, 0);
12464  rb_define_method(rb_cIO, "fdatasync", rb_io_fdatasync, 0);
12465  rb_define_method(rb_cIO, "sync", rb_io_sync, 0);
12466  rb_define_method(rb_cIO, "sync=", rb_io_set_sync, 1);
12467 
12468  rb_define_method(rb_cIO, "lineno", rb_io_lineno, 0);
12469  rb_define_method(rb_cIO, "lineno=", rb_io_set_lineno, 1);
12470 
12471  rb_define_method(rb_cIO, "readlines", rb_io_readlines, -1);
12472 
12473  /* for prelude.rb use only: */
12474  rb_define_private_method(rb_cIO, "__read_nonblock", io_read_nonblock, 3);
12475  rb_define_private_method(rb_cIO, "__write_nonblock", io_write_nonblock, 2);
12476 
12477  rb_define_method(rb_cIO, "readpartial", io_readpartial, -1);
12478  rb_define_method(rb_cIO, "read", io_read, -1);
12479  rb_define_method(rb_cIO, "write", io_write_m, 1);
12480  rb_define_method(rb_cIO, "gets", rb_io_gets_m, -1);
12481  rb_define_method(rb_cIO, "readline", rb_io_readline, -1);
12482  rb_define_method(rb_cIO, "getc", rb_io_getc, 0);
12483  rb_define_method(rb_cIO, "getbyte", rb_io_getbyte, 0);
12484  rb_define_method(rb_cIO, "readchar", rb_io_readchar, 0);
12485  rb_define_method(rb_cIO, "readbyte", rb_io_readbyte, 0);
12486  rb_define_method(rb_cIO, "ungetbyte",rb_io_ungetbyte, 1);
12487  rb_define_method(rb_cIO, "ungetc",rb_io_ungetc, 1);
12489  rb_define_method(rb_cIO, "flush", rb_io_flush, 0);
12490  rb_define_method(rb_cIO, "tell", rb_io_tell, 0);
12491  rb_define_method(rb_cIO, "seek", rb_io_seek_m, -1);
12492  /* Set I/O position from the beginning */
12493  rb_define_const(rb_cIO, "SEEK_SET", INT2FIX(SEEK_SET));
12494  /* Set I/O position from the current position */
12495  rb_define_const(rb_cIO, "SEEK_CUR", INT2FIX(SEEK_CUR));
12496  /* Set I/O position from the end */
12497  rb_define_const(rb_cIO, "SEEK_END", INT2FIX(SEEK_END));
12498 #ifdef SEEK_DATA
12499  /* Set I/O position to the next location containing data */
12500  rb_define_const(rb_cIO, "SEEK_DATA", INT2FIX(SEEK_DATA));
12501 #endif
12502 #ifdef SEEK_HOLE
12503  /* Set I/O position to the next hole */
12504  rb_define_const(rb_cIO, "SEEK_HOLE", INT2FIX(SEEK_HOLE));
12505 #endif
12506  rb_define_method(rb_cIO, "rewind", rb_io_rewind, 0);
12507  rb_define_method(rb_cIO, "pos", rb_io_tell, 0);
12508  rb_define_method(rb_cIO, "pos=", rb_io_set_pos, 1);
12509  rb_define_method(rb_cIO, "eof", rb_io_eof, 0);
12510  rb_define_method(rb_cIO, "eof?", rb_io_eof, 0);
12511 
12512  rb_define_method(rb_cIO, "close_on_exec?", rb_io_close_on_exec_p, 0);
12513  rb_define_method(rb_cIO, "close_on_exec=", rb_io_set_close_on_exec, 1);
12514 
12515  rb_define_method(rb_cIO, "close", rb_io_close_m, 0);
12516  rb_define_method(rb_cIO, "closed?", rb_io_closed, 0);
12517  rb_define_method(rb_cIO, "close_read", rb_io_close_read, 0);
12518  rb_define_method(rb_cIO, "close_write", rb_io_close_write, 0);
12519 
12520  rb_define_method(rb_cIO, "isatty", rb_io_isatty, 0);
12521  rb_define_method(rb_cIO, "tty?", rb_io_isatty, 0);
12522  rb_define_method(rb_cIO, "binmode", rb_io_binmode_m, 0);
12523  rb_define_method(rb_cIO, "binmode?", rb_io_binmode_p, 0);
12524  rb_define_method(rb_cIO, "sysseek", rb_io_sysseek, -1);
12525  rb_define_method(rb_cIO, "advise", rb_io_advise, -1);
12526 
12527  rb_define_method(rb_cIO, "ioctl", rb_io_ioctl, -1);
12528  rb_define_method(rb_cIO, "fcntl", rb_io_fcntl, -1);
12529  rb_define_method(rb_cIO, "pid", rb_io_pid, 0);
12530  rb_define_method(rb_cIO, "inspect", rb_io_inspect, 0);
12531 
12532  rb_define_method(rb_cIO, "external_encoding", rb_io_external_encoding, 0);
12533  rb_define_method(rb_cIO, "internal_encoding", rb_io_internal_encoding, 0);
12534  rb_define_method(rb_cIO, "set_encoding", rb_io_set_encoding, -1);
12535 
12536  rb_define_method(rb_cIO, "autoclose?", rb_io_autoclose_p, 0);
12537  rb_define_method(rb_cIO, "autoclose=", rb_io_set_autoclose, 1);
12538 
12539  rb_define_variable("$stdin", &rb_stdin);
12540  rb_stdin = prep_stdio(stdin, FMODE_READABLE, rb_cIO, "<STDIN>");
12542  rb_stdout = prep_stdio(stdout, FMODE_WRITABLE, rb_cIO, "<STDOUT>");
12544  rb_stderr = prep_stdio(stderr, FMODE_WRITABLE|FMODE_SYNC, rb_cIO, "<STDERR>");
12548 
12549  /* Holds the original stdin */
12550  rb_define_global_const("STDIN", rb_stdin);
12551  /* Holds the original stdout */
12552  rb_define_global_const("STDOUT", rb_stdout);
12553  /* Holds the original stderr */
12554  rb_define_global_const("STDERR", rb_stderr);
12555 
12556 #if 0
12557  /* Hack to get rdoc to regard ARGF as a class: */
12558  rb_cARGF = rb_define_class("ARGF", rb_cObject);
12559 #endif
12560 
12561  rb_cARGF = rb_class_new(rb_cObject);
12562  rb_set_class_path(rb_cARGF, rb_cObject, "ARGF.class");
12563  rb_define_alloc_func(rb_cARGF, argf_alloc);
12564 
12565  rb_include_module(rb_cARGF, rb_mEnumerable);
12566 
12567  rb_define_method(rb_cARGF, "initialize", argf_initialize, -2);
12568  rb_define_method(rb_cARGF, "initialize_copy", argf_initialize_copy, 1);
12569  rb_define_method(rb_cARGF, "to_s", argf_to_s, 0);
12570  rb_define_alias(rb_cARGF, "inspect", "to_s");
12571  rb_define_method(rb_cARGF, "argv", argf_argv, 0);
12572 
12573  rb_define_method(rb_cARGF, "fileno", argf_fileno, 0);
12574  rb_define_method(rb_cARGF, "to_i", argf_fileno, 0);
12575  rb_define_method(rb_cARGF, "to_io", argf_to_io, 0);
12576  rb_define_method(rb_cARGF, "to_write_io", argf_write_io, 0);
12577  rb_define_method(rb_cARGF, "each", argf_each_line, -1);
12578  rb_define_method(rb_cARGF, "each_line", argf_each_line, -1);
12579  rb_define_method(rb_cARGF, "each_byte", argf_each_byte, 0);
12580  rb_define_method(rb_cARGF, "each_char", argf_each_char, 0);
12581  rb_define_method(rb_cARGF, "each_codepoint", argf_each_codepoint, 0);
12582  rb_define_method(rb_cARGF, "lines", argf_lines, -1);
12583  rb_define_method(rb_cARGF, "bytes", argf_bytes, 0);
12584  rb_define_method(rb_cARGF, "chars", argf_chars, 0);
12585  rb_define_method(rb_cARGF, "codepoints", argf_codepoints, 0);
12586 
12587  rb_define_method(rb_cARGF, "read", argf_read, -1);
12588  rb_define_method(rb_cARGF, "readpartial", argf_readpartial, -1);
12589  rb_define_method(rb_cARGF, "read_nonblock", argf_read_nonblock, -1);
12590  rb_define_method(rb_cARGF, "readlines", argf_readlines, -1);
12591  rb_define_method(rb_cARGF, "to_a", argf_readlines, -1);
12592  rb_define_method(rb_cARGF, "gets", argf_gets, -1);
12593  rb_define_method(rb_cARGF, "readline", argf_readline, -1);
12594  rb_define_method(rb_cARGF, "getc", argf_getc, 0);
12595  rb_define_method(rb_cARGF, "getbyte", argf_getbyte, 0);
12596  rb_define_method(rb_cARGF, "readchar", argf_readchar, 0);
12597  rb_define_method(rb_cARGF, "readbyte", argf_readbyte, 0);
12598  rb_define_method(rb_cARGF, "tell", argf_tell, 0);
12599  rb_define_method(rb_cARGF, "seek", argf_seek_m, -1);
12600  rb_define_method(rb_cARGF, "rewind", argf_rewind, 0);
12601  rb_define_method(rb_cARGF, "pos", argf_tell, 0);
12602  rb_define_method(rb_cARGF, "pos=", argf_set_pos, 1);
12603  rb_define_method(rb_cARGF, "eof", argf_eof, 0);
12604  rb_define_method(rb_cARGF, "eof?", argf_eof, 0);
12605  rb_define_method(rb_cARGF, "binmode", argf_binmode_m, 0);
12606  rb_define_method(rb_cARGF, "binmode?", argf_binmode_p, 0);
12607 
12608  rb_define_method(rb_cARGF, "write", argf_write, 1);
12609  rb_define_method(rb_cARGF, "print", rb_io_print, -1);
12610  rb_define_method(rb_cARGF, "putc", rb_io_putc, 1);
12611  rb_define_method(rb_cARGF, "puts", rb_io_puts, -1);
12612  rb_define_method(rb_cARGF, "printf", rb_io_printf, -1);
12613 
12614  rb_define_method(rb_cARGF, "filename", argf_filename, 0);
12615  rb_define_method(rb_cARGF, "path", argf_filename, 0);
12616  rb_define_method(rb_cARGF, "file", argf_file, 0);
12617  rb_define_method(rb_cARGF, "skip", argf_skip, 0);
12618  rb_define_method(rb_cARGF, "close", argf_close_m, 0);
12619  rb_define_method(rb_cARGF, "closed?", argf_closed, 0);
12620 
12621  rb_define_method(rb_cARGF, "lineno", argf_lineno, 0);
12622  rb_define_method(rb_cARGF, "lineno=", argf_set_lineno, 1);
12623 
12624  rb_define_method(rb_cARGF, "inplace_mode", argf_inplace_mode_get, 0);
12625  rb_define_method(rb_cARGF, "inplace_mode=", argf_inplace_mode_set, 1);
12626 
12627  rb_define_method(rb_cARGF, "external_encoding", argf_external_encoding, 0);
12628  rb_define_method(rb_cARGF, "internal_encoding", argf_internal_encoding, 0);
12629  rb_define_method(rb_cARGF, "set_encoding", argf_set_encoding, -1);
12630 
12631  argf = rb_class_new_instance(0, 0, rb_cARGF);
12632 
12634  /*
12635  * ARGF is a stream designed for use in scripts that process files given
12636  * as command-line arguments or passed in via STDIN.
12637  *
12638  * See ARGF (the class) for more details.
12639  */
12640  rb_define_global_const("ARGF", argf);
12641 
12644  ARGF.filename = rb_str_new2("-");
12645 
12648 
12649 #if defined (_WIN32) || defined(__CYGWIN__)
12650  atexit(pipe_atexit);
12651 #endif
12652 
12653  Init_File();
12654 
12655  rb_define_method(rb_cFile, "initialize", rb_file_initialize, -1);
12656 
12657  sym_mode = ID2SYM(rb_intern("mode"));
12658  sym_perm = ID2SYM(rb_intern("perm"));
12659  sym_flags = ID2SYM(rb_intern("flags"));
12660  sym_extenc = ID2SYM(rb_intern("external_encoding"));
12661  sym_intenc = ID2SYM(rb_intern("internal_encoding"));
12663  sym_open_args = ID2SYM(rb_intern("open_args"));
12664  sym_textmode = ID2SYM(rb_intern("textmode"));
12665  sym_binmode = ID2SYM(rb_intern("binmode"));
12666  sym_autoclose = ID2SYM(rb_intern("autoclose"));
12667  sym_normal = ID2SYM(rb_intern("normal"));
12668  sym_sequential = ID2SYM(rb_intern("sequential"));
12669  sym_random = ID2SYM(rb_intern("random"));
12670  sym_willneed = ID2SYM(rb_intern("willneed"));
12671  sym_dontneed = ID2SYM(rb_intern("dontneed"));
12672  sym_noreuse = ID2SYM(rb_intern("noreuse"));
12673  sym_SET = ID2SYM(rb_intern("SET"));
12674  sym_CUR = ID2SYM(rb_intern("CUR"));
12675  sym_END = ID2SYM(rb_intern("END"));
12676 #ifdef SEEK_DATA
12677  sym_DATA = ID2SYM(rb_intern("DATA"));
12678 #endif
12679 #ifdef SEEK_HOLE
12680  sym_HOLE = ID2SYM(rb_intern("HOLE"));
12681 #endif
12682  sym_wait_readable = ID2SYM(rb_intern("wait_readable"));
12683  sym_wait_writable = ID2SYM(rb_intern("wait_writable"));
12684 }
static VALUE argf_bytes(VALUE argf)
Definition: io.c:11715
#define STRNCASECMP(s1, s2, n)
Definition: ruby.h:2138
#define ioctl_arg
Definition: wait.c:32
void rb_define_global_const(const char *, VALUE)
Definition: variable.c:2745
size_t iov_len
Definition: win32.h:204
struct timeval rb_time_interval(VALUE num)
Definition: time.c:2286
void rb_define_readonly_variable(const char *, const VALUE *)
Definition: variable.c:641
unsigned long ruby_strtoul(const char *str, char **endptr, int base)
Definition: util.c:117
void rb_gc(void)
Definition: gc.c:6656
#define WNOHANG
Definition: win32.h:128
static rb_io_t * io_close_fptr(VALUE io)
Definition: io.c:4427
VALUE rb_econv_open_exc(const char *senc, const char *denc, int ecflags)
Definition: transcode.c:2033
static VALUE io_read_nonblock(VALUE io, VALUE length, VALUE str, VALUE ex)
Definition: io.c:2649
static void make_readconv(rb_io_t *fptr, int size)
Definition: io.c:2223
VALUE rb_eStandardError
Definition: error.c:760
void rb_execarg_setenv(VALUE execarg_obj, VALUE env)
Definition: process.c:2293
static VALUE rb_io_rewind(VALUE io)
Definition: io.c:1735
void rb_thread_schedule(void)
Definition: thread.c:1264
const char * rb_econv_asciicompat_encoding(const char *encname)
Definition: transcode.c:1782
static VALUE rb_io_close_read(VALUE io)
Definition: io.c:4590
static void argf_close(VALUE argf)
Definition: io.c:8011
int rb_pipe(int *pipes)
Definition: io.c:5822
static VALUE rb_obj_display(int argc, VALUE *argv, VALUE self)
Definition: io.c:7357
static int nogvl_copy_stream_wait_write(struct copy_stream_struct *stp)
Definition: io.c:10278
VALUE rb_io_getbyte(VALUE io)
Definition: io.c:3896
static long fcntl_narg_len(int cmd)
Definition: io.c:9199
static VALUE rb_io_set_lineno(VALUE io, VALUE lineno)
Definition: io.c:3368
int rb_io_wait_writable(int f)
Definition: io.c:1130
static ID id_set_encoding
Definition: io.c:165
#define MBCLEN_CHARFOUND_P(ret)
Definition: encoding.h:185
static VALUE pipe_open(VALUE execarg_obj, const char *modestr, int fmode, const convconfig_t *convconfig)
Definition: io.c:5986
void rb_thread_atfork(void)
Definition: thread.c:4172
#define ECONV_NEWLINE_DECORATOR_WRITE_MASK
Definition: encoding.h:395
VALUE argf
Definition: io.c:11324
#define rb_str_new4
Definition: intern.h:859
rb_econv_result_t
Definition: encoding.h:291
static VALUE rb_io_set_sync(VALUE io, VALUE sync)
Definition: io.c:1934
VALUE rb_ary_entry(VALUE ary, long offset)
Definition: array.c:1196
#define MBCLEN_CHARFOUND_LEN(ret)
Definition: encoding.h:186
#define F_SETFD
Definition: win32.h:583
#define RARRAY_LEN(a)
Definition: ruby.h:1026
void rb_bug(const char *fmt,...)
Definition: error.c:482
#define F_DUPFD_CLOEXEC
Definition: win32.h:588
#define FALSE
Definition: nkf.h:174
#define RUBY_TYPED_FREE_IMMEDIATELY
Definition: ruby.h:1145
int ioctl(int, int,...)
Definition: win32.c:2755
static VALUE rb_io_internal_encoding(VALUE)
Definition: io.c:10912
static VALUE rb_io_s_readlines(int argc, VALUE *argv, VALUE io)
Definition: io.c:9884
#define FMODE_READWRITE
Definition: io.h:104
long rb_str_coderange_scan_restartable(const char *, const char *, rb_encoding *, int *)
Definition: string.c:530
static VALUE sym_flags
Definition: io.c:166
static VALUE sym_random
Definition: io.c:8640
static VALUE rb_io_closed(VALUE io)
Definition: io.c:4553
#define SSIZE_MAX
Definition: ruby.h:292
static void check_getline_args(VALUE *rsp, long *limit, VALUE io)
Definition: io.c:3084
size_t strlen(const char *)
static VALUE io_enc_str(VALUE str, rb_io_t *fptr)
Definition: io.c:2215
#define INT2NUM(x)
Definition: ruby.h:1538
void rb_readwrite_sys_fail(enum rb_io_wait_readwrite writable, const char *mesg)
Definition: io.c:12122
VALUE rb_cIO
Definition: io.c:141
void rb_io_check_writable(rb_io_t *fptr)
Definition: io.c:846
void * iov_base
Definition: win32.h:203
static VALUE argf_getpartial(int argc, VALUE *argv, VALUE argf, VALUE opts, int nonblock)
Definition: io.c:11386
static VALUE sym_autoclose
Definition: io.c:167
static long setup_narg(ioctl_req_t cmd, VALUE *argp, int io_p)
Definition: io.c:9206
static VALUE sym_encoding
Definition: io.c:166
static VALUE argf_set_pos(VALUE argf, VALUE offset)
Definition: io.c:11115
static const char closed_stream[]
Definition: io.c:615
static ID id_getc
Definition: io.c:165
static VALUE rb_io_codepoints(VALUE io)
Definition: io.c:3825
static VALUE sym_SET
Definition: io.c:168
int rb_io_modestr_fmode(const char *modestr)
Definition: io.c:4967
static VALUE sym_noreuse
Definition: io.c:8640
static VALUE argf_set_lineno(VALUE argf, VALUE val)
Definition: io.c:7966
VALUE rb_stderr
Definition: io.c:154
void rb_syserr_fail(int e, const char *mesg)
Definition: error.c:2314
static VALUE argf_inplace_mode_get(VALUE argf)
Definition: io.c:11990
VALUE rb_file_open_str(VALUE fname, const char *modestr)
Definition: io.c:5723
static VALUE rb_f_putc(VALUE recv, VALUE ch)
Definition: io.c:7140
void rb_define_virtual_variable(const char *, VALUE(*)(ANYARGS), void(*)(ANYARGS))
Definition: variable.c:647
static VALUE argf_readpartial(int argc, VALUE *argv, VALUE argf)
Definition: io.c:11359
VALUE rb_hash_dup(VALUE hash)
Definition: hash.c:457
#define NUM2INT(x)
Definition: ruby.h:684
int count
Definition: encoding.c:56
static VALUE io_call_close(VALUE io)
Definition: io.c:4504
static int max(int a, int b)
Definition: strftime.c:142
#define ENCINDEX_UTF_16LE
Definition: encindex.h:46
#define NUM2UINT(x)
Definition: ruby.h:685
static ID id_read
Definition: io.c:165
static int io_fflush(rb_io_t *)
Definition: io.c:1089
void rb_str_tmp_frozen_release(VALUE str, VALUE tmp)
Definition: string.c:1148
rb_uid_t getuid(void)
Definition: win32.c:2709
VALUE rb_io_eof(VALUE io)
Definition: io.c:1827
void rb_define_singleton_method(VALUE obj, const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a singleton method for obj.
Definition: class.c:1716
VALUE rb_eEWOULDBLOCK
Definition: error.c:47
char * rb_execarg_commandline(const struct rb_execarg *eargp, VALUE *prog)
Definition: process.c:3894
int rb_cloexec_open(const char *pathname, int flags, mode_t mode)
Definition: io.c:255
static const char * rb_io_fmode_modestr(int fmode)
Definition: io.c:4932
static void argf_init(struct argf *p, VALUE v)
Definition: io.c:7902
int rb_w32_set_nonblock(int)
Definition: win32.c:4373
static VALUE argf_inplace_mode_set(VALUE argf, VALUE val)
Definition: io.c:12023
int ioctl_req_t
Definition: io.c:8982
VALUE fname
Definition: io.c:5489
VALUE rb_f_sprintf(int, const VALUE *)
Definition: sprintf.c:455
static void must_respond_to(ID mid, VALUE val, ID id)
Definition: io.c:7415
#define FilePathValue(v)
Definition: ruby.h:594
#define rb_usascii_str_new2
Definition: intern.h:863
VALUE str
Definition: io.c:1222
static VALUE io_s_write(int argc, VALUE *argv, int binary)
Definition: io.c:10043
void rb_io_set_nonblock(rb_io_t *fptr)
Definition: io.c:2458
#define CLASS_OF(v)
Definition: ruby.h:453
static VALUE select_call(VALUE arg)
Definition: io.c:8622
static VALUE rb_io_open_generic(VALUE, int, int, const convconfig_t *, mode_t)
Definition: io.c:6695
VALUE rb_str_cat(VALUE, const char *, long)
Definition: string.c:2664
#define PIDT2NUM(v)
Definition: ruby.h:323
static VALUE argf_readbyte(VALUE argf)
Definition: io.c:11573
#define ARGF_FORWARD(argc, argv)
Definition: io.c:8001
static VALUE argf_gets(int, VALUE *, VALUE)
Definition: io.c:8300
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Definition: class.c:1858
struct rb_io_t rb_io_t
rb_fdset_t fdsets[4]
Definition: io.c:8618
#define Qtrue
Definition: ruby.h:437
rb_io_buffer_t cbuf
Definition: io.h:89
VALUE rb_io_binmode(VALUE io)
Definition: io.c:4836
static void argf_mark(void *ptr)
Definition: io.c:7869
VALUE ecopts
Definition: io.h:85
static VALUE io_puts_ary(VALUE ary, VALUE out, int recur)
Definition: io.c:7165
static VALUE rb_io_binmode_p(VALUE io)
Definition: io.c:4924
int rb_execarg_run_options(const struct rb_execarg *e, struct rb_execarg *s, char *errmsg, size_t errmsg_buflen)
Definition: process.c:3021
Definition: io.h:62
#define OBJ_INIT_COPY(obj, orig)
Definition: intern.h:288
#define ENC_CODERANGE_SET(obj, cr)
Definition: encoding.h:106
#define READ_DATA_PENDING_COUNT(fptr)
Definition: io.c:408
VALUE rb_ary_shift(VALUE ary)
Definition: array.c:1000
#define rb_id2str(id)
Definition: vm_backtrace.c:29
char * str_ptr
Definition: io.c:2146
static VALUE rb_eEAGAINWaitWritable
Definition: io.c:148
int rb_exec_async_signal_safe(const struct rb_execarg *e, char *errmsg, size_t errmsg_buflen)
Definition: process.c:3150
#define ECONV_ERROR_HANDLER_MASK
Definition: encoding.h:386
#define IO_WBUF_CAPA_MIN
Definition: io.c:133
#define F_DUPFD
Definition: win32.h:581
void * rb_thread_call_without_gvl2(void *(*func)(void *), void *data1, rb_unblock_function_t *ubf, void *data2)
Definition: thread.c:1420
static VALUE orig_stderr
Definition: io.c:155
#define FMODE_WRITABLE
Definition: io.h:103
rb_encoding * rb_to_encoding(VALUE enc)
Definition: encoding.c:246
void rb_fd_fix_cloexec(int fd)
Definition: io.c:231
static int is_popen_fork(VALUE prog)
Definition: io.c:6216
#define FMODE_READABLE
Definition: io.h:102
void rb_econv_close(rb_econv_t *ec)
Definition: transcode.c:1698
VALUE rs
Definition: stringio.c:992
static VALUE io_flush_buffer_async(VALUE arg)
Definition: io.c:1048
static VALUE io_binwrite_string(VALUE arg)
Definition: io.c:1273
VALUE rb_str_unlocktmp(VALUE)
Definition: string.c:2528
void rb_define_private_method(VALUE klass, const char *name, VALUE(*func)(ANYARGS), int argc)
Definition: class.c:1527
int argc
Definition: io.c:11322
static void io_encoding_set(rb_io_t *, VALUE, VALUE, VALUE)
Definition: io.c:9536
static VALUE rb_io_syswrite(VALUE io, VALUE str)
Definition: io.c:4736
VALUE rb_enc_from_encoding(rb_encoding *encoding)
Definition: encoding.c:117
static rb_encoding * find_encoding(VALUE v)
Definition: io.c:9528
ID rb_frame_this_func(void)
Definition: eval.c:979
static VALUE argf_external_encoding(VALUE argf)
Definition: io.c:10989
SOCKET rb_w32_get_osfhandle(int)
Definition: win32.c:1064
VALUE rb_eTypeError
Definition: error.c:762
static ID id_write
Definition: io.c:165
static VALUE sym_mode
Definition: io.c:166
#define O_ACCMODE
Definition: io.c:99
static VALUE argf_each_line(int argc, VALUE *argv, VALUE argf)
Definition: io.c:11654
#define UNREACHABLE
Definition: ruby.h:46
static VALUE rb_io_close_write(VALUE io)
Definition: io.c:4650
static int io_check_tty(rb_io_t *fptr)
Definition: io.c:5577
VALUE * argv
Definition: io.c:11323
rb_encoding * rb_default_internal_encoding(void)
Definition: encoding.c:1510
static VALUE argf_filename(VALUE argf)
Definition: io.c:11824
VALUE rb_ary_push(VALUE ary, VALUE item)
Definition: array.c:905
static void fptr_finalize(rb_io_t *fptr, int noraise)
Definition: io.c:4343
VALUE rb_cFile
Definition: file.c:129
void rb_close_before_exec(int lowfd, int maxhint, VALUE noclose_fds)
#define rb_io_fcntl
Definition: io.c:9388
static VALUE opt_i_get(ID id, VALUE *var)
Definition: io.c:11997
if(len<=MAX_WORD_LENGTH &&len >=MIN_WORD_LENGTH)
Definition: zonetab.h:883
int fcntl(int, int,...)
Definition: win32.c:4296
void rb_p(VALUE obj)
Definition: io.c:7261
VALUE rb_ary_tmp_new(long capa)
Definition: array.c:532
static VALUE argf_argv(VALUE argf)
Definition: io.c:12076
static int io_encname_bom_p(const char *name, long len)
Definition: io.c:4961
static VALUE rb_io_seek(VALUE io, VALUE offset, int whence)
Definition: io.c:1622
#define free(x)
Definition: io.c:25
#define rb_fd_zero(f)
Definition: intern.h:352
int rb_thread_fd_select(int, rb_fdset_t *, rb_fdset_t *, rb_fdset_t *, struct timeval *)
Definition: thread.c:3795
void ruby_sized_xfree(void *x, size_t size)
Definition: gc.c:8009
rb_pid_t rb_fork_ruby(int *status)
VALUE rb_funcall(VALUE, ID, int,...)
Calls a method.
Definition: vm_eval.c:821
#define ENCINDEX_UTF_16BE
Definition: encindex.h:45
int8_t binmode
Definition: io.c:184
VALUE rb_str_locktmp_ensure(VALUE str, VALUE(*func)(VALUE), VALUE arg)
Definition: string.c:2538
void rb_str_set_len(VALUE, long)
Definition: string.c:2545
int writeconv_pre_ecflags
Definition: io.h:94
VALUE rb_protect(VALUE(*proc)(VALUE), VALUE data, int *state)
Definition: eval.c:891
rb_io_t * fptr
Definition: io.c:2148
#define RBASIC_SET_CLASS(obj, cls)
Definition: internal.h:1314
static VALUE rb_io_readchar(VALUE io)
Definition: io.c:3873
int rb_enc_str_coderange(VALUE)
Definition: string.c:620
static VALUE argf_write(VALUE argf, VALUE str)
Definition: io.c:12116
static int rb_sysopen_internal(struct sysopen_struct *data)
Definition: io.c:5503
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition: class.c:693
VALUE rb_to_int(VALUE)
Definition: object.c:2687
int rb_cloexec_dup2(int oldfd, int newfd)
Definition: io.c:288
#define Check_Type(v, t)
Definition: ruby.h:562
void rb_raise(VALUE exc, const char *fmt,...)
Definition: error.c:2207
static VALUE rb_io_sysseek(int argc, VALUE *argv, VALUE io)
Definition: io.c:4696
#define SET_BINARY_MODE_WITH_SEEK_CUR(fptr)
Definition: io.c:593
int writeconv_initialized
Definition: io.h:93
#define RSTRING_GETMEM(str, ptrvar, lenvar)
Definition: ruby.h:991
#define FMODE_CREATE
Definition: io.h:110
VALUE rb_enc_associate(VALUE obj, rb_encoding *enc)
Definition: encoding.c:854
VALUE rb_ary_clear(VALUE ary)
Definition: array.c:3487
static VALUE pipe_close(VALUE io)
Definition: io.c:6243
static void pipe_add_fptr(rb_io_t *fptr)
Definition: io.c:5742
VALUE rb_convert_type(VALUE, int, const char *, const char *)
Definition: object.c:2630
static VALUE argf_binmode_p(VALUE argf)
Definition: io.c:11896
VALUE rb_exec_recursive(VALUE(*)(VALUE, VALUE, int), VALUE, VALUE)
Definition: thread.c:4697
#define NEED_WRITECONV(fptr)
Definition: io.c:589
long lineno
Definition: io.c:180
#define RB_GC_GUARD(v)
Definition: ruby.h:552
static VALUE rb_file_initialize(int argc, VALUE *argv, VALUE io)
Definition: io.c:7775
static VALUE io_s_readlines(struct getline_arg *arg)
Definition: io.c:9860
static VALUE argf_write_io(VALUE argf)
Definition: io.c:12101
void rb_define_alloc_func(VALUE, rb_alloc_func_t)
#define FMODE_DUPLEX
Definition: io.h:108
int rb_io_modestr_oflags(const char *modestr)
Definition: io.c:5086
static int ruby_dup(int orig)
Definition: io.c:886
VALUE rb_execarg_new(int argc, const VALUE *argv, int accept_shell)
Definition: process.c:2257
#define ENCODING_MAXNAMELEN
Definition: encoding.h:60
int rb_enc_mbclen(const char *p, const char *e, rb_encoding *enc)
Definition: encoding.c:1008
#define FMODE_BINMODE
Definition: io.h:105
static void unsupported_encoding(const char *name, rb_encoding *enc)
Definition: io.c:5157
VALUE rb_thread_io_blocking_region(rb_blocking_function_t *func, void *data1, int fd)
Definition: thread.c:1434
void rb_mutex_allow_trap(VALUE self, int val)
Definition: thread_sync.c:511
VALUE io
Definition: io.c:3037
#define FMODE_APPEND
Definition: io.h:109
void rb_include_module(VALUE klass, VALUE module)
Definition: class.c:864
#define MORE_CHAR_FINISHED
Definition: io.c:2250
VALUE rb_block_call(VALUE, ID, int, const VALUE *, rb_block_call_func_t, VALUE)
int rb_notify_fd_close(int fd)
Definition: thread.c:2200
void rb_gc_mark(VALUE ptr)
Definition: gc.c:4394
VALUE rb_hash_lookup(VALUE hash, VALUE key)
Definition: hash.c:867
static VALUE more_char(rb_io_t *fptr)
Definition: io.c:2326
static VALUE rb_io_s_sysopen(int argc, VALUE *argv)
Definition: io.c:6503
#define T_ARRAY
Definition: ruby.h:498
static VALUE argf_lineno(VALUE argf)
Definition: io.c:7987
off_t copy_length
Definition: io.c:10158
static void free_io_buffer(rb_io_buffer_t *buf)
Definition: io.c:4363
#define RFILE(obj)
Definition: ruby.h:1213
Definition: io.c:177
void rb_define_global_function(const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a global function.
Definition: class.c:1745
time_t tv_sec
Definition: missing.h:54
static VALUE ignore_closed_stream(VALUE io, VALUE exc)
Definition: io.c:4511
ID rb_id_encoding(void)
Definition: encoding.c:753
static VALUE internal_write_func(void *ptr)
Definition: io.c:946
void rb_io_check_initialized(rb_io_t *fptr)
Definition: io.c:631
static VALUE rb_eEINPROGRESSWaitWritable
Definition: io.c:151
unsigned int last
Definition: nkf.c:4311
static VALUE rb_io_each_byte(VALUE io)
Definition: io.c:3518
void rb_gc_force_recycle(VALUE obj)
Definition: gc.c:6102
VALUE writeconv_pre_ecopts
Definition: io.h:95
static void open_key_args(int argc, VALUE *argv, VALUE opt, struct foreach_arg *arg)
Definition: io.c:9766
#define IOWAIT_SYSCALL
Definition: io.c:10210
static VALUE argf_readchar(VALUE argf)
Definition: io.c:11533
#define EINPROGRESS
Definition: win32.h:477
const char * syserr
Definition: io.c:10166
void rb_update_max_fd(int fd)
Definition: io.c:189
#define FIXNUM_P(f)
Definition: ruby.h:365
static VALUE rb_io_external_encoding(VALUE io)
Definition: io.c:10887
static VALUE rb_f_readlines(int argc, VALUE *argv, VALUE recv)
Definition: io.c:8403
static void io_set_read_length(VALUE str, long n)
Definition: io.c:2384
static int argf_next_argv(VALUE argf)
Definition: io.c:8023
VALUE rb_check_to_integer(VALUE, const char *)
Definition: object.c:2673
rb_encoding * enc2
Definition: io.h:83
static const rb_data_type_t argf_type
Definition: io.c:7895
static long io_fwrite(VALUE str, rb_io_t *fptr, int nosync)
Definition: io.c:1423
static VALUE rb_f_open(int argc, VALUE *argv)
Definition: io.c:6644
static VALUE argf_each_codepoint(VALUE argf)
Definition: io.c:11779
static int rb_fix_detect_o_cloexec(int fd)
Definition: io.c:239
RUBY_FUNC_EXPORTED size_t rb_io_memsize(const rb_io_t *fptr)
Definition: io.c:4414
VALUE rb_stdin
Definition: io.c:154
#define GetOpenFile(obj, fp)
Definition: io.h:120
static ssize_t rb_write_internal2(int fd, const void *buf, size_t count)
Definition: io.c:991
VALUE envp_str
Definition: internal.h:1371
int argc
Definition: io.c:7276
static VALUE do_writeconv(VALUE str, rb_io_t *fptr, int *converted)
Definition: io.c:1366
unsigned int chomp
Definition: stringio.c:994
static void validate_enc_binmode(int *fmode_p, int ecflags, rb_encoding *enc, rb_encoding *enc2)
Definition: io.c:5302
static VALUE rb_f_p_internal(VALUE arg)
Definition: io.c:7281
VALUE rb_io_ascii8bit_binmode(VALUE io)
Definition: io.c:4882
#define OBJ_TAINTED(x)
Definition: ruby.h:1298
#define io_tell(fptr)
Definition: io.c:785
static VALUE rb_io_tell(VALUE io)
Definition: io.c:1609
const char * ptr
Definition: io.c:1223
VALUE argv
Definition: io.c:181
static VALUE argf
Definition: io.c:162
VALUE rb_mutex_new(void)
Definition: thread_sync.c:118
#define ENC_CODERANGE_7BIT
Definition: encoding.h:100
#define rb_ary_new2
Definition: intern.h:90
static VALUE argf_seek_m(int argc, VALUE *argv, VALUE argf)
Definition: io.c:11094
static void opt_i_set(VALUE val, ID id, VALUE *var)
Definition: io.c:12042
#define GetWriteIO(io)
Definition: io.c:405
const char term
Definition: id.c:37
RUBY_EXTERN void * memmove(void *, const void *, size_t)
Definition: memmove.c:7
int rb_gc_for_fd(int err)
Definition: io.c:876
long last_lineno
Definition: io.c:179
static VALUE read_all(rb_io_t *fptr, long siz, VALUE str)
Definition: io.c:2393
#define rb_fd_set(n, f)
Definition: intern.h:353
int rb_io_extract_encoding_option(VALUE opt, rb_encoding **enc_p, rb_encoding **enc2_p, int *fmode_p)
Definition: io.c:5231
static void * exec_interrupts(void *arg)
Definition: io.c:10174
#define sym(x)
Definition: date_core.c:3721
VALUE rb_io_write(VALUE io, VALUE str)
Definition: io.c:1508
VALUE rb_str_buf_cat(VALUE, const char *, long)
VALUE rb_eEAGAIN
Definition: error.c:46
static const char utf_prefix[]
Definition: io.c:4956
rb_io_t * rb_io_make_open_file(VALUE obj)
Definition: io.c:7529
int mode
Definition: io.h:65
static VALUE rb_io_set_autoclose(VALUE io, VALUE autoclose)
Definition: io.c:7857
#define NEWOBJ_OF(obj, type, klass, flags)
Definition: ruby.h:754
#define rb_fd_isset(n, f)
Definition: intern.h:355
static ssize_t maygvl_read(int has_gvl, int fd, void *buf, size_t count)
Definition: io.c:10456
static rb_encoding * io_read_encoding(rb_io_t *fptr)
Definition: io.c:828
#define RB_BLOCK_CALL_FUNC_ARGLIST(yielded_arg, callback_arg)
Definition: ruby.h:1830
static VALUE rb_io_s_popen(int argc, VALUE *argv, VALUE klass)
Definition: io.c:6341
VALUE rb_io_gets_internal(VALUE io)
Definition: io.c:3267
static VALUE rb_io_lines(int argc, VALUE *argv, VALUE io)
Definition: io.c:3492
static VALUE rb_io_getline_fast(rb_io_t *fptr, rb_encoding *enc, int chomp)
Definition: io.c:2987
void rb_exc_raise(VALUE mesg)
Definition: eval.c:620
#define SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags)
Definition: io.c:592
#define rb_io_set_close_on_exec
Definition: io.c:4156
VALUE rb_io_close(VALUE io)
Definition: io.c:4469
VALUE rb_io_flush_raw(VALUE io, int sync)
Definition: io.c:1551
VALUE rb_obj_dup(VALUE)
Definition: object.c:437
static VALUE rb_io_sysread(int argc, VALUE *argv, VALUE io)
Definition: io.c:4784
static void io_ungetbyte(VALUE str, rb_io_t *fptr)
Definition: io.c:742
static void argf_block_call(ID mid, int argc, VALUE *argv, VALUE argf)
Definition: io.c:11599
#define RB_TYPE_P(obj, type)
Definition: ruby.h:527
static VALUE rb_file_open_internal(VALUE io, VALUE filename, const char *modestr)
Definition: io.c:5695
static int str_end_with_asciichar(VALUE str, int c)
Definition: io.c:7150
static VALUE argf_binmode_m(VALUE argf)
Definition: io.c:11873
#define fmode
VALUE current_file
Definition: io.c:178
int rb_thread_fd_writable(int)
Definition: thread.c:3788
VALUE rb_econv_make_exception(rb_econv_t *ec)
Definition: transcode.c:4225
#define O_CLOEXEC
#define MEMZERO(p, type, n)
Definition: ruby.h:1660
static VALUE sym_CUR
Definition: io.c:168
void rb_econv_check_error(rb_econv_t *ec)
Definition: transcode.c:4231
rb_encoding * enc
Definition: io.h:82
VALUE rb_lastline_get(void)
Definition: vm.c:1219
int rb_to_encoding_index(VALUE enc)
Definition: encoding.c:198
rb_encoding * rb_default_external_encoding(void)
Definition: encoding.c:1425
void rb_str_setter(VALUE, ID, VALUE *)
Definition: string.c:9063
void rb_maygvl_fd_fix_cloexec(int fd)
Definition: io.c:208
static VALUE copy_stream_fallback_body(VALUE arg)
Definition: io.c:10613
void rb_thread_sleep(int)
Definition: thread.c:1241
fd_set rb_fdset_t
Definition: intern.h:351
off_t src_offset
Definition: io.c:10159
#define rb_fd_term(f)
Definition: intern.h:362
struct rb_execarg * rb_execarg_get(VALUE execarg_obj)
Definition: process.c:2268
#define ECONV_NEWLINE_DECORATOR_READ_MASK
Definition: encoding.h:394
static VALUE orig_stdout
Definition: io.c:155
long len
Definition: io.c:2147
static VALUE sym_wait_readable
Definition: io.c:169
VALUE rb_class_name(VALUE)
Definition: variable.c:443
static VALUE argf_lines(int argc, VALUE *argv, VALUE argf)
Definition: io.c:11668
VALUE rb_str_chomp_string(VALUE str, VALUE chomp)
Definition: string.c:8136
static void * nogvl_close(void *ptr)
Definition: io.c:4239
#define ALLOC_N(type, n)
Definition: ruby.h:1587
const void * buf
Definition: io.c:926
int rb_block_given_p(void)
Definition: eval.c:797
VALUE rb_hash_aset(VALUE hash, VALUE key, VALUE val)
Definition: hash.c:1576
void rb_io_unbuffered(rb_io_t *fptr)
Definition: io.c:5816
void rb_write_error2(const char *mesg, long len)
Definition: io.c:7373
static VALUE argf_internal_encoding(VALUE argf)
Definition: io.c:11011
void Init_File(void)
Definition: file.c:5953
VALUE rb_str_encode_ospath(VALUE path)
Definition: file.c:223
#define F_SETFL
Definition: win32.h:587
VALUE rb_str_substr(VALUE, long, long)
Definition: string.c:2435
int nosync
Definition: io.c:1230
#define val
static VALUE io_readpartial(int argc, VALUE *argv, VALUE io)
Definition: io.c:2628
static VALUE argf_getbyte(VALUE argf)
Definition: io.c:11493
static void stdout_setter(VALUE val, ID id, VALUE *variable)
Definition: io.c:7425
long tv_usec
Definition: missing.h:55
VALUE rb_stdout
Definition: io.c:154
RUBY_EXTERN VALUE rb_cObject
Definition: ruby.h:1872
static VALUE rb_f_backquote(VALUE obj, VALUE str)
Definition: io.c:8466
static void rb_io_buffer_init(rb_io_buffer_t *buf)
Definition: io.c:7491
VALUE rb_eRuntimeError
Definition: error.c:761
#define PREP_STDIO_NAME(f)
Definition: io.c:4161
static struct pipe_list * pipe_list
static VALUE argf_block_call_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, argf))
Definition: io.c:11588
static VALUE argf_readlines(int, VALUE *, VALUE)
Definition: io.c:8428
static VALUE argf_getline(int argc, VALUE *argv, VALUE argf)
Definition: io.c:8194
#define FMODE_SETENC_BY_BOM
Definition: io.h:115
static VALUE rb_eEWOULDBLOCKWaitWritable
Definition: io.c:150
#define MBCLEN_NEEDMORE_P(ret)
Definition: encoding.h:188
static VALUE io_nonblock_eof(VALUE opts)
Definition: io.c:2639
#define RSTRING_END(str)
Definition: ruby.h:986
static VALUE rb_io_s_binread(int argc, VALUE *argv, VALUE io)
Definition: io.c:10001
char * ruby_strdup(const char *)
Definition: util.c:496
static VALUE io_flush_buffer_sync(void *arg)
Definition: io.c:1016
FILE * rb_io_stdio_file(rb_io_t *fptr)
Definition: io.c:7481
int rb_io_oflags_fmode(int oflags)
Definition: io.c:5016
static int io_strip_bom(VALUE io)
Definition: io.c:5589
VALUE rb_str_cat2(VALUE, const char *)
VALUE rb_obj_as_string(VALUE)
Definition: string.c:1364
#define ECONV_STATEFUL_DECORATOR_MASK
Definition: encoding.h:401
static struct StringIO * writable(VALUE strio)
Definition: stringio.c:145
static ssize_t maygvl_copy_stream_read(int has_gvl, struct copy_stream_struct *stp, char *buf, size_t len, off_t offset)
Definition: io.c:10465
VALUE rb_ary_new(void)
Definition: array.c:493
#define dp(v)
Definition: vm_debug.h:21
rb_econv_t * rb_econv_open_opts(const char *source_encoding, const char *destination_encoding, int ecflags, VALUE ecopts)
Definition: transcode.c:2575
#define UINT2NUM(x)
Definition: ruby.h:1539
VALUE rb_io_get_write_io(VALUE io)
Definition: io.c:668
VALUE rb_io_print(int argc, const VALUE *argv, VALUE out)
Definition: io.c:7040
VALUE rb_execarg_extract_options(VALUE execarg_obj, VALUE opthash)
Definition: process.c:1928
static int swallow(rb_io_t *fptr, int term)
Definition: io.c:2938
static VALUE argf_set_encoding(int argc, VALUE *argv, VALUE argf)
Definition: io.c:11051
#define ARGF_GENERIC_INPUT_P()
Definition: io.c:7999
#define ECONV_PARTIAL_INPUT
Definition: encoding.h:409
VALUE rb_io_ungetbyte(VALUE io, VALUE b)
Definition: io.c:3957
#define ECONV_AFTER_OUTPUT
Definition: encoding.h:410
long limit
Definition: stringio.c:993
RUBY_EXTERN VALUE rb_mKernel
Definition: ruby.h:1860
VALUE rb_thread_current(void)
Definition: thread.c:2504
int rb_cloexec_fcntl_dupfd(int fd, int minfd)
Definition: io.c:360
static void pipe_finalize(rb_io_t *fptr, int noraise)
Definition: io.c:5791
#define NIL_P(v)
Definition: ruby.h:451
static VALUE copy_stream_fallback(struct copy_stream_struct *stp)
Definition: io.c:10671
#define ISASCII(c)
Definition: ruby.h:2121
VALUE rb_io_flush(VALUE io)
Definition: io.c:1590
static VALUE sym_textmode
Definition: io.c:167
static VALUE finish_writeconv_sync(VALUE arg)
Definition: io.c:4232
static VALUE io_write(VALUE io, VALUE str, int nosync)
Definition: io.c:1458
static VALUE rb_f_puts(int argc, VALUE *argv, VALUE recv)
Definition: io.c:7252
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition: class.c:646
static VALUE pipe_pair_close(VALUE rw)
Definition: io.c:9614
const char * ruby_get_inplace_mode(void)
Definition: io.c:12048
static int appendline(rb_io_t *fptr, int delim, VALUE *strp, long *lp)
Definition: io.c:2856
int chown(const char *, int, int)
Definition: win32.c:4698
#define ECONV_DEFAULT_NEWLINE_DECORATOR
Definition: encoding.h:403
int fd
Definition: io.h:64
VALUE rb_mutex_synchronize(VALUE mutex, VALUE(*func)(VALUE arg), VALUE arg)
Definition: thread_sync.c:488
static VALUE rb_io_each_line(int argc, VALUE *argv, VALUE io)
Definition: io.c:3472
#define MODE_BINARY(a, b)
rb_pid_t rb_fork_async_signal_safe(int *status, int(*chfunc)(void *, char *, size_t), void *charg, VALUE fds, char *errmsg, size_t errmsg_buflen)
void rb_define_const(VALUE, const char *, VALUE)
Definition: variable.c:2734
int rb_io_wait_readable(int f)
Definition: io.c:1104
int8_t next_p
Definition: io.c:184
void rb_sys_fail_str(VALUE mesg)
Definition: error.c:2332
static VALUE select_internal(VALUE read, VALUE write, VALUE except, struct timeval *tp, rb_fdset_t *fds)
Definition: io.c:8491
static VALUE io_write_nonblock(VALUE io, VALUE str, VALUE ex)
Definition: io.c:2698
rb_atomic_t cnt[RUBY_NSIG]
Definition: signal.c:525
static VALUE rb_io_each_char(VALUE io)
Definition: io.c:3674
static VALUE rb_io_open_with_args(int argc, const VALUE *argv)
Definition: io.c:6709
VALUE rb_io_check_io(VALUE io)
Definition: io.c:662
void rb_lastline_set(VALUE)
Definition: vm.c:1225
static VALUE argf_chars(VALUE argf)
Definition: io.c:11754
static VALUE rb_io_getline(int argc, VALUE *argv, VALUE io)
Definition: io.c:3252
VALUE str
Definition: io.c:1229
#define MBCLEN_NEEDMORE_LEN(ret)
Definition: encoding.h:189
#define rb_io_fdatasync
Definition: io.c:1983
struct rb_io_t::rb_io_enc_t encs
void Init_IO(void)
Definition: io.c:12327
static void * nogvl_fclose(void *ptr)
Definition: io.c:4260
union rb_execarg::@139 invoke
#define NUM2IOCTLREQ(num)
Definition: io.c:8983
int argc
Definition: ruby.c:183
#define READ_DATA_PENDING(fptr)
Definition: io.c:407
VALUE writeconv_asciicompat
Definition: io.h:92
#define FMODE_TRUNC
Definition: io.h:112
static VALUE finish_writeconv(rb_io_t *fptr, int noalloc)
Definition: io.c:4164
#define Qfalse
Definition: ruby.h:436
const char * notimp
Definition: io.c:10168
static VALUE rb_open_file(int argc, const VALUE *argv, VALUE io)
Definition: io.c:6430
rb_pid_t pid
Definition: io.h:66
#define T_BIGNUM
Definition: ruby.h:501
#define LONG_MAX
Definition: ruby.h:189
#define NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr)
Definition: io.c:591
void rb_gc_register_mark_object(VALUE obj)
Definition: gc.c:6154
#define rb_io_ioctl
Definition: io.c:9300
static VALUE rb_io_gets_m(int argc, VALUE *argv, VALUE io)
Definition: io.c:3308
VALUE rb_io_get_io(VALUE io)
Definition: io.c:656
#define RUBY_FUNC_EXPORTED
Definition: defines.h:263
static VALUE argf_eof(VALUE argf)
Definition: io.c:11213
#define ENC_CODERANGE_BROKEN
Definition: encoding.h:102
static VALUE rb_io_getline_0(VALUE rs, long limit, int chomp, rb_io_t *fptr)
Definition: io.c:3123
#define rb_ary_new4
Definition: intern.h:92
static void io_setstrbuf(VALUE *str, long len)
Definition: io.c:2363
#define rb_str_new2
Definition: intern.h:857
VALUE rb_obj_alloc(VALUE)
Definition: object.c:1845
#define ARGF
Definition: io.c:403
int err
Definition: win32.c:135
static int io_flush_buffer(rb_io_t *fptr)
Definition: io.c:1075
#define rb_enc_codepoint(p, e, enc)
Definition: encoding.h:201
#define OBJ_FREEZE(x)
Definition: ruby.h:1308
#define argf_of(obj)
Definition: io.c:402
#define rb_enc_mbminlen(enc)
Definition: encoding.h:174
Definition: io.c:1227
rb_io_wait_readwrite
Definition: ruby.h:1796
VALUE rb_io_gets(VALUE io)
Definition: io.c:3261
int rb_cloexec_dup(int oldfd)
Definition: io.c:281
static int no_exception_p(VALUE opts)
Definition: io.c:2498
#define F_GETFD
Definition: win32.h:582
static VALUE rb_f_printf(int argc, VALUE *argv)
Definition: io.c:6997
static void rscheck(const char *rsptr, long rslen, VALUE rs)
Definition: io.c:2848
VALUE * argv
Definition: io.c:7277
static int nogvl_copy_stream_write(struct copy_stream_struct *stp, char *buf, size_t len)
Definition: io.c:10508
VALUE rb_class_new_instance(int, const VALUE *, VALUE)
Definition: object.c:1891
static VALUE argf_initialize(VALUE argf, VALUE argv)
Definition: io.c:7924
#define rb_f_syscall
Definition: io.c:9518
void * rb_thread_call_without_gvl(void *(*func)(void *), void *data1, rb_unblock_function_t *ubf, void *data2)
#define ENC_CODERANGE_VALID
Definition: encoding.h:101
#define ATOMIC_CAS(var, oldval, newval)
Definition: ruby_atomic.h:132
static VALUE rb_io_seek_m(int argc, VALUE *argv, VALUE io)
Definition: io.c:1677
#define numberof(array)
Definition: etc.c:616
#define ALLOC(type)
Definition: ruby.h:1588
#define EOF
Definition: vsnprintf.c:201
#define ONIGENC_CONSTRUCT_MBCLEN_CHARFOUND(n)
Definition: onigmo.h:345
VALUE read
Definition: io.c:8616
VALUE rb_str_resize(VALUE, long)
Definition: string.c:2562
static void io_set_encoding_by_bom(VALUE io)
Definition: io.c:5652
#define DEFAULT_TEXTMODE
Definition: io.c:587
static void advice_arg_check(VALUE advice)
Definition: io.c:8733
#define NUM2OFFT(x)
Definition: ruby.h:730
#define IO_CBUF_CAPA_MIN
Definition: io.c:131
rb_encoding * rb_find_encoding(VALUE enc)
Definition: encoding.c:253
int rb_enc_ascget(const char *p, const char *e, int *len, rb_encoding *enc)
Definition: encoding.c:1032
static VALUE argf_alloc(VALUE klass)
Definition: io.c:7911
static void io_ascii8bit_binmode(rb_io_t *fptr)
Definition: io.c:4860
#define NEXT_ARGF_FORWARD(argc, argv)
Definition: io.c:8005
static VALUE prep_io(int fd, int fmode, VALUE klass, const char *path)
Definition: io.c:7432
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition: class.c:1758
int rb_cloexec_pipe(int fildes[2])
Definition: io.c:323
#define ZALLOC(type)
Definition: ruby.h:1590
static VALUE rb_f_gets(int argc, VALUE *argv, VALUE recv)
Definition: io.c:8275
#define RSTRING_LEN(str)
Definition: ruby.h:978
VALUE rb_get_argv(void)
Definition: io.c:12088
VALUE rb_yield(VALUE)
Definition: vm_eval.c:1020
void ruby_set_inplace_mode(const char *suffix)
Definition: io.c:12054
rb_io_buffer_t wbuf
Definition: io.h:71
#define RARRAY_CONST_PTR(a)
Definition: ruby.h:1028
VALUE rb_io_puts(int argc, const VALUE *argv, VALUE out)
Definition: io.c:7212
int errno
static VALUE copy_stream_body(VALUE arg)
Definition: io.c:10683
#define TRUE
Definition: nkf.h:175
#define off_t
Definition: io.c:61
static VALUE seek_before_access(VALUE argp)
Definition: io.c:9912
#define S_ISREG(m)
Definition: io.c:915
static VALUE rb_io_set_pos(VALUE io, VALUE offset)
Definition: io.c:1703
void rb_last_status_clear(void)
Definition: process.c:494
static rb_atomic_t max_file_descriptor
Definition: io.c:187
static VALUE rb_io_init_copy(VALUE dest, VALUE io)
Definition: io.c:6924
VALUE rb_mEnumerable
Definition: enum.c:18
VALUE rb_sprintf(const char *format,...)
Definition: sprintf.c:1440
rb_io_t * fptr
Definition: io.c:1221
#define id_exception
Definition: io.c:164
static void nogvl_copy_stream_read_write(struct copy_stream_struct *stp)
Definition: io.c:10534
static rb_encoding * io_input_encoding(rb_io_t *fptr)
Definition: io.c:837
void rb_execarg_parent_start(VALUE execarg_obj)
Definition: process.c:2457
static VALUE io_close(VALUE io)
Definition: io.c:4524
Definition: io.c:5736
static int rb_sysopen(VALUE fname, int oflags, mode_t perm)
Definition: io.c:5513
int rb_enc_precise_mbclen(const char *p, const char *e, rb_encoding *enc)
Definition: encoding.c:1020
#define IO_RBUF_CAPA_FOR(fptr)
Definition: io.c:132
void rb_gvar_readonly_setter(VALUE v, ID id, void *d, struct rb_global_variable *g)
Definition: variable.c:571
static VALUE argf_rewind(VALUE argf)
Definition: io.c:11137
#define NEED_READCONV(fptr)
Definition: io.c:588
static VALUE rb_io_pid(VALUE io)
Definition: io.c:2031
static VALUE rb_eEINPROGRESSWaitReadable
Definition: io.c:152
void rb_fatal(const char *fmt,...)
Definition: error.c:2261
static VALUE io_s_read(struct foreach_arg *arg)
Definition: io.c:9900
#define rb_enc_name(enc)
Definition: encoding.h:171
VALUE rb_eSystemCallError
Definition: error.c:780
static void * io_flush_buffer_sync2(void *arg)
Definition: io.c:1036
static int maygvl_copy_stream_continue_p(int has_gvl, struct copy_stream_struct *stp)
Definition: io.c:10187
void rb_last_status_set(int status, rb_pid_t pid)
Definition: process.c:485
static VALUE rb_io_readlines(int argc, VALUE *argv, VALUE io)
Definition: io.c:3420
static VALUE rb_io_s_for_fd(int argc, VALUE *argv, VALUE klass)
Definition: io.c:7816
struct rb_io_enc_t encs
Definition: io.c:183
static VALUE rb_f_select(int argc, VALUE *argv, VALUE obj)
Definition: io.c:8956
static VALUE rb_io_chars(VALUE io)
Definition: io.c:3697
#define MEMMOVE(p1, p2, type, n)
Definition: ruby.h:1662
VALUE rb_hash_new(void)
Definition: hash.c:441
static VALUE rb_io_s_open(int argc, VALUE *argv, VALUE klass)
Definition: io.c:6481
#define NUM2CHR(x)
Definition: ruby.h:1575
static void argf_lineno_setter(VALUE val, ID id, VALUE *var)
Definition: io.c:8232
#define strdup(s)
Definition: util.h:70
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Definition: class.c:1919
static VALUE argf_read_nonblock(int argc, VALUE *argv, VALUE argf)
Definition: io.c:11373
void rb_write_error_str(VALUE mesg)
Definition: io.c:7393
void rb_str_modify_expand(VALUE, long)
Definition: string.c:1988
static VALUE argf_to_io(VALUE argf)
Definition: io.c:11187
void rb_thread_execute_interrupts(VALUE th)
Definition: thread.c:2098
VALUE rb_ivar_set(VALUE, ID, VALUE)
Definition: variable.c:1364
Definition: ruby.h:1070
VALUE rb_check_hash_type(VALUE hash)
Definition: hash.c:736
static void io_unread(rb_io_t *fptr)
Definition: io.c:719
unsigned char buf[MIME_BUF_SIZE]
Definition: nkf.c:4309
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Definition: array.c:623
#define PRIsVALUE
Definition: ruby.h:135
unsigned long ID
Definition: ruby.h:86
void rb_thread_wait_fd(int)
Definition: thread.c:3782
rb_encoding * rb_usascii_encoding(void)
Definition: encoding.c:1335
VALUE tied_io_for_writing
Definition: io.h:73
#define RUBY_METHOD_FUNC(func)
Definition: ruby.h:1708
static VALUE rb_io_close_m(VALUE io)
Definition: io.c:4493
static VALUE argf_lineno_getter(ID id, VALUE *var)
Definition: io.c:8225
static ssize_t rb_write_internal(int fd, const void *buf, size_t count)
Definition: io.c:980
#define Qnil
Definition: ruby.h:438
int8_t init_p
Definition: io.c:184
#define FMODE_TEXTMODE
Definition: io.h:113
struct rb_execarg::@139::@141 cmd
static void rb_io_extract_modeenc(VALUE *vmode_p, VALUE *vperm_p, VALUE opthash, int *oflags_p, int *fmode_p, convconfig_t *convconfig_p)
Definition: io.c:5355
VALUE rb_enc_uint_chr(unsigned int code, rb_encoding *enc)
Definition: numeric.c:3268
VALUE rb_io_printf(int argc, const VALUE *argv, VALUE out)
Definition: io.c:6979
#define EWOULDBLOCK
Definition: io.c:115
#define mode_t
Definition: win32.h:119
void rb_readwrite_syserr_fail(enum rb_io_wait_readwrite writable, int n, const char *mesg)
Definition: io.c:12128
size_t rb_econv_memsize(rb_econv_t *)
Definition: transcode.c:1716
#define OBJ_TAINT(x)
Definition: ruby.h:1300
unsigned long VALUE
Definition: ruby.h:85
static VALUE argf_readline(int, VALUE *, VALUE)
Definition: io.c:8376
#define IS_PREP_STDIO(f)
Definition: io.c:4160
static VALUE rb_io_s_binwrite(int argc, VALUE *argv, VALUE io)
Definition: io.c:10150
static void extract_getline_args(int argc, VALUE *argv, struct getline_arg *args)
Definition: io.c:3060
static VALUE result
Definition: nkf.c:40
VALUE rb_eEINPROGRESS
Definition: error.c:48
VALUE rb_gets(void)
Definition: io.c:8311
char * strchr(char *, char)
int intptr_t
Definition: win32.h:90
static VALUE prep_stdio(FILE *f, int fmode, VALUE klass, const char *path)
Definition: io.c:7462
#define NEED_NEWLINE_DECORATOR_ON_WRITE(fptr)
Definition: io.c:448
char * str_ptr
Definition: io.c:2485
int rb_utf8_encindex(void)
Definition: encoding.c:1329
#define FIX2INT(x)
Definition: ruby.h:686
static void * internal_write_func2(void *ptr)
Definition: io.c:953
Definition: win32.h:202
#define ECONV_NEWLINE_DECORATOR_MASK
Definition: encoding.h:393
int rb_wait_for_single_fd(int fd, int events, struct timeval *tv)
Definition: thread.c:3992
VALUE rb_rs
Definition: io.c:158
void rb_enc_warn(rb_encoding *enc, const char *fmt,...)
Definition: error.c:235
void rb_io_synchronized(rb_io_t *fptr)
Definition: io.c:5809
VALUE rb_rescue2(VALUE(*b_proc)(ANYARGS), VALUE data1, VALUE(*r_proc)(ANYARGS), VALUE data2,...)
Definition: eval.c:825
static void extract_getline_opts(VALUE opts, struct getline_arg *args)
Definition: io.c:3044
VALUE rb_check_funcall(VALUE, ID, int, const VALUE *)
Definition: vm_eval.c:439
static VALUE rb_io_s_write(int argc, VALUE *argv, VALUE io)
Definition: io.c:10135
static long io_bufread(char *ptr, long len, rb_io_t *fptr)
Definition: io.c:2107
rb_fdset_t fds
Definition: io.c:10169
#define rb_enc_asciicompat(enc)
Definition: encoding.h:239
VALUE rb_ensure(VALUE(*b_proc)(ANYARGS), VALUE data1, VALUE(*e_proc)(ANYARGS), VALUE data2)
Definition: eval.c:923
VALUE rb_str_new_cstr(const char *)
Definition: string.c:770
int memcmp(const void *s1, const void *s2, size_t len)
Definition: memcmp.c:7
static VALUE rb_file_open_generic(VALUE io, VALUE filename, int oflags, int fmode, const convconfig_t *convconfig, mode_t perm)
Definition: io.c:5668
static VALUE argf_read(int argc, VALUE *argv, VALUE argf)
Definition: io.c:11276
static int maygvl_select(int has_gvl, int n, rb_fdset_t *rfds, rb_fdset_t *wfds, rb_fdset_t *efds, struct timeval *timeout)
Definition: io.c:10249
static int maygvl_copy_stream_wait_read(int has_gvl, struct copy_stream_struct *stp)
Definition: io.c:10258
static VALUE io_shift_cbuf(rb_io_t *fptr, int len, VALUE *strp)
Definition: io.c:2336
VALUE rb_uninterruptible(VALUE(*b_proc)(ANYARGS), VALUE data)
Definition: thread.c:5035
void rb_sys_fail(const char *mesg)
Definition: error.c:2326
static VALUE read_internal_call(VALUE arg)
Definition: io.c:2490
static VALUE sym_willneed
Definition: io.c:8640
static VALUE rb_io_autoclose_p(VALUE io)
Definition: io.c:7832
static VALUE io_write_m(VALUE io, VALUE str)
Definition: io.c:1502
void rb_jump_tag(int tag)
Definition: eval.c:788
VALUE rb_str_dup(VALUE)
Definition: string.c:1436
struct rb_io_buffer_t rb_io_buffer_t
Definition: io.h:60
static int global_argf_p(VALUE arg)
Definition: io.c:10967
static VALUE rb_io_set_encoding(int argc, VALUE *argv, VALUE io)
Definition: io.c:10941
int rb_reserved_fd_p(int fd)
void rb_define_hooked_variable(const char *, VALUE *, VALUE(*)(ANYARGS), void(*)(ANYARGS))
Definition: variable.c:616
#define rb_funcallv
Definition: console.c:21
#define READ_DATA_BUFFERED(fptr)
Definition: io.c:410
#define rb_io_close_on_exec_p
Definition: io.c:4098
int rb_respond_to(VALUE, ID)
Definition: vm_method.c:1995
struct timeval * timeout
Definition: io.c:8617
static VALUE bufread_call(VALUE arg)
Definition: io.c:2152
int rb_thread_to_be_killed(VALUE thread)
Definition: thread.c:2311
register unsigned int len
Definition: zonetab.h:51
VALUE rb_define_module_under(VALUE outer, const char *name)
Definition: class.c:790
#define StringValueCStr(v)
Definition: ruby.h:571
rb_econv_t * readconv
Definition: io.h:88
static VALUE argf_tell(VALUE argf)
Definition: io.c:11077
#define shutdown(a, b)
Definition: io.c:597
#define rb_fd_max(f)
Definition: intern.h:363
static VALUE argf_each_byte(VALUE argf)
Definition: io.c:11701
static size_t argf_memsize(const void *ptr)
Definition: io.c:7887
#define SEEK_END
Definition: io.c:790
void rb_iter_break_value(VALUE val)
Definition: vm.c:1474
VALUE rb_check_to_int(VALUE)
Definition: object.c:2693
#define recur(fmt)
int argc
Definition: io.c:9760
int rb_econv_putbackable(rb_econv_t *ec)
Definition: transcode.c:1738
#define RSTRING_PTR(str)
Definition: ruby.h:982
static VALUE argf_codepoints(VALUE argf)
Definition: io.c:11793
static VALUE sym_extenc
Definition: io.c:166
VALUE write_lock
Definition: io.h:97
struct pipe_list * next
Definition: io.c:5738
#define rb_exc_new3
Definition: intern.h:246
static VALUE argf_filename_getter(ID id, VALUE *var)
Definition: io.c:11831
static VALUE rb_io_binmode_m(VALUE io)
Definition: io.c:4905
void rb_str_modify(VALUE)
Definition: string.c:1980
static VALUE sym_perm
Definition: io.c:166
static VALUE rb_io_isatty(VALUE io)
Definition: io.c:4049
#define ENCODING_GET(obj)
Definition: encoding.h:58
rb_encoding * rb_enc_get(VALUE obj)
Definition: encoding.c:860
VALUE io
Definition: io.c:1228
static VALUE io_s_write0(struct write_arg *arg)
Definition: io.c:10037
void rb_mod_sys_fail_str(VALUE mod, VALUE mesg)
Definition: error.c:2374
void rb_insecure_operation(void)
Definition: safe.c:104
static VALUE io_flush_buffer_async2(VALUE arg)
Definition: io.c:1055
static VALUE rb_io_lineno(VALUE io)
Definition: io.c:3341
static VALUE io_read(int argc, VALUE *argv, VALUE io)
Definition: io.c:2800
int size
Definition: encoding.c:57
static int rb_freopen(VALUE fname, const char *mode, FILE *fp)
Definition: io.c:6808
VALUE rb_yield_values2(int n, const VALUE *argv)
Definition: vm_eval.c:1053
#define f
VALUE rb_hash_lookup2(VALUE hash, VALUE key, VALUE def)
Definition: hash.c:856
#define INT2FIX(i)
Definition: ruby.h:232
static VALUE io_new_instance(VALUE args)
Definition: io.c:9522
static VALUE rb_io_putc(VALUE io, VALUE ch)
Definition: io.c:7113
static VALUE rb_io_bytes(VALUE io)
Definition: io.c:3543
#define MBCLEN_INVALID_P(ret)
Definition: encoding.h:187
int rb_safe_level(void)
Definition: safe.c:35
#define RARRAY_AREF(a, i)
Definition: ruby.h:1040
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)
Definition: transcode.c:1442
VALUE rb_check_convert_type(VALUE, int, const char *, const char *)
Definition: object.c:2643
static long io_fread(VALUE str, long offset, long size, rb_io_t *fptr)
Definition: io.c:2160
static int rb_io_fmode_oflags(int fmode)
Definition: io.c:5051
static VALUE check_pipe_command(VALUE filename_or_command)
Definition: io.c:6530
int rb_io_fptr_finalize(rb_io_t *fptr)
Definition: io.c:4399
VALUE rb_mWaitReadable
Definition: io.c:144
VALUE io
Definition: io.c:9762
static VALUE rb_io_s_pipe(int argc, VALUE *argv, VALUE klass)
Definition: io.c:9681
static VALUE io_readlines(const struct getline_arg *arg, VALUE io)
Definition: io.c:3429
VALUE rb_io_fdopen(int fd, int oflags, const char *path)
Definition: io.c:7453
VALUE rb_str_buf_cat_ascii(VALUE, const char *)
Definition: string.c:2778
static VALUE rb_io_to_io(VALUE io)
Definition: io.c:2086
VALUE rb_eIOError
Definition: io.c:143
static VALUE rb_io_inspect(VALUE obj)
Definition: io.c:2050
static void rb_scan_open_args(int argc, const VALUE *argv, VALUE *fname_p, int *oflags_p, int *fmode_p, convconfig_t *convconfig_p, mode_t *perm_p)
Definition: io.c:6408
static VALUE sym_intenc
Definition: io.c:166
#define rb_intern(str)
#define ANYARGS
Definition: defines.h:173
static VALUE rb_io_s_try_convert(VALUE dummy, VALUE io)
Definition: io.c:712
VALUE rb_check_array_type(VALUE ary)
Definition: array.c:635
static void argf_block_call_line(ID mid, int argc, VALUE *argv, VALUE argf)
Definition: io.c:11615
RUBY_SYMBOL_EXPORT_BEGIN void * rb_thread_call_with_gvl(void *(*func)(void *), void *data1)
Definition: thread.c:1499
static void clear_codeconv(rb_io_t *fptr)
Definition: io.c:4392
VALUE rb_hash_aref(VALUE hash, VALUE key)
Definition: hash.c:845
static void rb_io_fptr_cleanup(rb_io_t *fptr, int noraise)
Definition: io.c:4352
void rb_error_arity(int argc, int min, int max)
#define FD_CLOEXEC
Definition: win32.h:589
#define rb_fd_select(n, rfds, wfds, efds, timeout)
Definition: intern.h:364
VALUE rb_str_catf(VALUE str, const char *format,...)
Definition: sprintf.c:1480
VALUE rb_enumeratorize(VALUE obj, VALUE meth, int argc, const VALUE *argv)
Definition: enumerator.c:450
void rb_syserr_fail_str(int e, VALUE mesg)
Definition: error.c:2320
long rb_w32_write_console(uintptr_t, int)
Definition: win32.c:7146
static VALUE rb_eEAGAINWaitReadable
Definition: io.c:147
VALUE rb_check_string_type(VALUE)
Definition: string.c:2164
#define is_socket(fd, path)
Definition: io.c:603
#define rb_funcall3
Definition: ruby.h:1771
VALUE rb_any_to_s(VALUE)
Definition: object.c:500
RUBY_EXTERN char * strerror(int)
Definition: strerror.c:11
static VALUE argf_each_char(VALUE argf)
Definition: io.c:11740
#define LONG2FIX(i)
Definition: ruby.h:234
VALUE pathv
Definition: io.h:68
static VALUE rb_io_advise(int argc, VALUE *argv, VALUE io)
Definition: io.c:8791
#define O_NONBLOCK
Definition: win32.h:590
#define ARGVSTR2ARGV(argv_str)
Definition: internal.h:1406
#define RTEST(v)
Definition: ruby.h:450
static VALUE rb_io_getc(VALUE io)
Definition: io.c:3847
void rb_thread_check_ints(void)
Definition: thread.c:1215
#define T_STRING
Definition: ruby.h:496
VALUE rb_eEOFError
Definition: io.c:142
VALUE rb_str_locktmp(VALUE)
static long io_binwrite(VALUE str, const char *ptr, long len, rb_io_t *fptr, int nosync)
Definition: io.c:1305
VALUE offset
Definition: io.c:9907
#define OBJ_INFECT(x, s)
Definition: ruby.h:1304
static VALUE argf_closed(VALUE argf)
Definition: io.c:11962
struct rb_encoding_entry * list
Definition: encoding.c:55
int flock(int, int)
Definition: flock.c:125
int rb_method_basic_definition_p(VALUE, ID)
Definition: vm_method.c:1880
void rb_define_variable(const char *, VALUE *)
Definition: variable.c:635
#define READ_CHECK(fptr)
Definition: io.c:423
#define T_FILE
Definition: ruby.h:502
static VALUE rb_io_s_read(int argc, VALUE *argv, VALUE io)
Definition: io.c:9962
#define fsync
Definition: win32.h:193
void rb_io_check_readable(rb_io_t *fptr)
Definition: io.c:822
FILE * rb_fdopen(int fd, const char *modestr)
Definition: io.c:5537
void(* finalize)(struct rb_io_t *, int)
Definition: io.h:69
static rb_io_t * flush_before_seek(rb_io_t *fptr)
Definition: io.c:775
#define TypedData_Make_Struct(klass, type, data_type, sval)
Definition: ruby.h:1182
#define rb_enc_left_char_head(s, p, e, enc)
Definition: encoding.h:216
void rb_notimplement(void)
Definition: error.c:2253
static VALUE sym_binmode
Definition: io.c:167
VALUE rb_ary_concat(VALUE x, VALUE y)
Definition: array.c:3686
static long remain_size(rb_io_t *fptr)
Definition: io.c:2186
long length
Definition: io.c:1224
static VALUE argf_argv_getter(ID id, VALUE *var)
Definition: io.c:12082
#define RETURN_ENUMERATOR(obj, argc, argv)
Definition: intern.h:240
rb_io_t * fptr
Definition: io.c:4227
#define SafeStringValue(v)
Definition: ruby.h:574
VALUE rb_eNotImpError
Definition: error.c:772
int rb_atomic_t
Definition: ruby_atomic.h:120
#define FOREACH_ARGF()
Definition: io.c:11585
static VALUE io_reopen(VALUE io, VALUE nfile)
Definition: io.c:6719
static void * sysopen_func(void *ptr)
Definition: io.c:5495
static VALUE rb_io_readline(int argc, VALUE *argv, VALUE io)
Definition: io.c:3389
#define FMODE_PREP
Definition: io.c:4159
VALUE rb_enc_str_new(const char *, long, rb_encoding *)
Definition: string.c:758
static VALUE rb_eEWOULDBLOCKWaitReadable
Definition: io.c:149
#define rb_sys_fail_path(path)
Definition: internal.h:1065
#define OFFT2NUM(v)
Definition: ruby.h:254
VALUE rb_io_addstr(VALUE io, VALUE str)
Definition: io.c:1530
static long ioctl_narg_len(ioctl_req_t cmd)
Definition: io.c:9041
static VALUE internal_read_func(void *ptr)
Definition: io.c:939
int oflags
Definition: io.c:5490
void rb_set_class_path(VALUE, VALUE, const char *)
Definition: variable.c:366
int rb_thread_interrupted(VALUE thval)
Definition: thread.c:1233
static VALUE rb_io_initialize(int argc, VALUE *argv, VALUE io)
Definition: io.c:7695
static void make_writeconv(rb_io_t *fptr)
Definition: io.c:1165
VALUE rb_io_taint_check(VALUE io)
Definition: io.c:624
const char * name
Definition: nkf.c:208
int rb_execarg_addopt(VALUE execarg_obj, VALUE key, VALUE val)
Definition: process.c:1669
#define ID2SYM(x)
Definition: ruby.h:383
#define NUM2MODET(v)
Definition: ruby.h:341
static VALUE rb_io_readbyte(VALUE io)
Definition: io.c:3929
#define READ_CHAR_PENDING_PTR(fptr)
Definition: io.c:414
#define FMODE_SYNC
Definition: io.h:106
#define FMODE_TTY
Definition: io.h:107
#define MakeOpenFile(obj, fp)
Definition: io.h:122
static void fptr_finalize_flush(rb_io_t *fptr, int noraise)
Definition: io.c:4280
#define SHUT_WR
#define SHUT_RD
VALUE rb_default_rs
Definition: io.c:160
#define MORE_CHAR_SUSPENDED
Definition: io.c:2249
RUBY_EXTERN int dup2(int, int)
Definition: dup2.c:27
static VALUE sym_sequential
Definition: io.c:8640
static VALUE io_getpartial(int argc, VALUE *argv, VALUE io, VALUE opts, int nonblock)
Definition: io.c:2508
VALUE rb_str_new_frozen(VALUE)
Definition: string.c:1123
rb_io_buffer_t rbuf
Definition: io.h:71
char * inplace
Definition: io.c:182
static VALUE rb_io_s_copy_stream(int argc, VALUE *argv, VALUE io)
Definition: io.c:10850
#define rb_fd_init(f)
Definition: intern.h:360
VALUE rb_inspect(VALUE)
Definition: object.c:519
static void clear_writeconv(rb_io_t *fptr)
Definition: io.c:4382
struct rb_io_enc_t convconfig_t
Definition: io.c:5299
static void parse_mode_enc(const char *estr, rb_encoding *estr_enc, rb_encoding **enc_p, rb_encoding **enc2_p, int *fmode_p)
Definition: io.c:5163
static VALUE fill_cbuf(rb_io_t *fptr, int ec_flags)
Definition: io.c:2252
unsigned use_shell
Definition: internal.h:1374
static rb_io_t * rb_io_get_fptr(VALUE io)
Definition: io.c:648
static VALUE rb_io_reopen(int argc, VALUE *argv, VALUE file)
Definition: io.c:6835
rb_encoding * rb_ascii8bit_encoding(void)
Definition: encoding.c:1305
static long read_buffered_data(char *ptr, long len, rb_io_t *fptr)
Definition: io.c:2093
static VALUE sym_dontneed
Definition: io.c:8640
#define FIX2UINT(x)
Definition: ruby.h:687
static int interpret_seek_whence(VALUE vwhence)
Definition: io.c:1636
void rb_warning(const char *fmt,...)
Definition: error.c:250
int rb_enc_find_index(const char *name)
Definition: encoding.c:704
#define rb_syserr_fail_path(err, path)
Definition: internal.h:1066
#define rb_io_fsync
Definition: io.c:1931
static VALUE sym_END
Definition: io.c:168
static VALUE io_s_foreach(struct getline_arg *arg)
Definition: io.c:9803
#define fileno(p)
Definition: vsnprintf.c:217
static VALUE sym_open_args
Definition: io.c:166
static VALUE pipe_open_s(VALUE prog, const char *modestr, int fmode, const convconfig_t *convconfig)
Definition: io.c:6230
int rb_io_read_pending(rb_io_t *fptr)
Definition: io.c:858
#define rb_check_frozen(obj)
Definition: intern.h:276
#define NEED_NEWLINE_DECORATOR_ON_READ(fptr)
Definition: io.c:447
#define CONST_ID(var, str)
Definition: ruby.h:1743
FILE * stdio_file
Definition: io.h:63
static VALUE rb_io_fileno(VALUE io)
Definition: io.c:1999
ssize_t rb_io_bufread(VALUE io, void *buf, size_t size)
Definition: io.c:2176
VALUE rb_str_tmp_frozen_acquire(VALUE str)
Definition: string.c:1135
static VALUE sym_normal
Definition: io.c:8640
#define MODE_BTMODE(a, b, c)
Definition: io.c:1363
#define rb_intern_const(str)
Definition: ruby.h:1756
VALUE rb_obj_freeze(VALUE)
Definition: object.c:1111
VALUE filename
Definition: io.c:178
#define memcpy(d, s, n)
Definition: ffi_common.h:55
static ID id_readpartial
Definition: io.c:165
void rb_execarg_parent_end(VALUE execarg_obj)
Definition: process.c:2496
static VALUE rb_f_p(int argc, VALUE *argv, VALUE self)
Definition: io.c:7323
static VALUE argf_forward(int argc, VALUE *argv, VALUE argf)
Definition: io.c:7993
static VALUE rb_f_readline(int argc, VALUE *argv, VALUE recv)
Definition: io.c:8349
VALUE rb_str_encode(VALUE str, VALUE to, int ecflags, VALUE ecopts)
Definition: transcode.c:2884
void void xfree(void *)
char rb_w32_fd_is_text(int)
Definition: win32.c:7599
#define io_seek(fptr, ofs, whence)
Definition: io.c:784
#define RB_WAITFD_IN
Definition: io.h:47
int fchmod(int fd, int mode)
Definition: win32.c:7481
static VALUE argf_fileno(VALUE argf)
Definition: io.c:11165
VALUE write
Definition: io.c:8616
static ssize_t rb_read_internal(int fd, void *buf, size_t count)
Definition: io.c:969
static VALUE argf_to_s(VALUE argf)
Definition: io.c:11976
VALUE rb_output_rs
Definition: io.c:159
static VALUE io_alloc(VALUE klass)
Definition: io.c:905
VALUE * argv
Definition: io.c:9761
#define READ_CHAR_PENDING_COUNT(fptr)
Definition: io.c:413
void rb_stdio_set_default_encoding(void)
Definition: io.c:10957
int lineno
Definition: io.h:67
VALUE rb_str_buf_new(long)
Definition: string.c:1247
VALUE rb_usascii_str_new(const char *, long)
Definition: string.c:742
VALUE rb_mWaitWritable
Definition: io.c:145
void rb_io_read_check(rb_io_t *fptr)
Definition: io.c:867
#define fstat(fd, st)
Definition: win32.h:184
#define SYMBOL_P(x)
Definition: ruby.h:382
#define stat(path, st)
Definition: win32.h:183
static void * nogvl_copy_stream_func(void *arg)
Definition: io.c:10591
static VALUE argf_block_call_line_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, argf))
Definition: io.c:11606
VALUE except
Definition: io.c:8616
static const char * rb_io_oflags_modestr(int oflags)
Definition: io.c:5092
#define RB_INTEGER_TYPE_P(obj)
Definition: ruby_missing.h:20
#define rb_io_sync
Definition: io.c:1932
#define DEFULT_IOCTL_NARG_LEN
Definition: io.c:9017
#define env
mode_t perm
Definition: io.c:5491
static void prepare_getline_args(int argc, VALUE *argv, struct getline_arg *args, VALUE io)
Definition: io.c:3113
ssize_t rb_io_bufwrite(VALUE io, const void *buf, size_t size)
Definition: io.c:1448
#define NULL
Definition: _sdbm.c:102
#define FIX2LONG(x)
Definition: ruby.h:363
static VALUE argf_file(VALUE argf)
Definition: io.c:11855
static VALUE copy_stream_finalize(VALUE arg)
Definition: io.c:10802
#define Qundef
Definition: ruby.h:439
static VALUE io_getc(rb_io_t *fptr, rb_encoding *enc)
Definition: io.c:3552
#define READ_CHAR_PENDING(fptr)
Definition: io.c:412
static void argf_free(void *ptr)
Definition: io.c:7879
#define READ_DATA_PENDING_PTR(fptr)
Definition: io.c:409
static void extract_binmode(VALUE opthash, int *fmode)
Definition: io.c:5326
static VALUE argf_close_m(VALUE argf)
Definition: io.c:11943
static ID id_flush
Definition: io.c:165
static VALUE select_end(VALUE arg)
Definition: io.c:8630
static void rb_io_ext_int_to_encs(rb_encoding *ext, rb_encoding *intern, rb_encoding **enc, rb_encoding **enc2, int fmode)
Definition: io.c:5129
rb_pid_t rb_waitpid(rb_pid_t pid, int *status, int flags)
Definition: process.c:902
VALUE rb_class_new(VALUE super)
Creates a new class.
Definition: class.c:242
void rb_define_method(VALUE klass, const char *name, VALUE(*func)(ANYARGS), int argc)
Definition: class.c:1515
#define ruby_verbose
Definition: ruby.h:1792
static rb_io_t * rb_io_fptr_new(void)
Definition: io.c:7500
VALUE rb_str_append(VALUE, VALUE)
Definition: string.c:2818
VALUE rb_file_open(const char *fname, const char *modestr)
Definition: io.c:5730
#define ENCINDEX_UTF_32LE
Definition: encindex.h:48
#define NOFILE
Definition: io.c:75
rb_io_t * fptr
Definition: io.c:9599
void rb_io_check_byte_readable(rb_io_t *fptr)
Definition: io.c:813
static VALUE rb_io_each_codepoint(VALUE io)
Definition: io.c:3722
static void pipe_del_fptr(rb_io_t *fptr)
Definition: io.c:5753
void rb_io_check_char_readable(rb_io_t *fptr)
Definition: io.c:794
#define next_argv()
Definition: io.c:7998
int rb_econv_prepare_options(VALUE opthash, VALUE *ecopts, int ecflags)
Definition: transcode.c:2524
void rb_econv_binmode(rb_econv_t *ec)
Definition: transcode.c:1939
void rb_warn(const char *fmt,...)
Definition: error.c:221
static VALUE rb_io_s_foreach(int argc, VALUE *argv, VALUE self)
Definition: io.c:9842
rb_io_t * fptr
Definition: io.c:5737
#define ENCINDEX_UTF_32BE
Definition: encindex.h:47
#define SEEK_SET
Definition: io.c:788
VALUE rb_eArgError
Definition: error.c:763
static VALUE rb_io_open(VALUE filename, VALUE vmode, VALUE vperm, VALUE opt)
Definition: io.c:6683
#define ECONV_UNIVERSAL_NEWLINE_DECORATOR
Definition: encoding.h:396
#define O_BINARY
Definition: _sdbm.c:88
int mode
Definition: io.c:9908
#define NUM2LONG(x)
Definition: ruby.h:648
VALUE rb_io_set_write_io(VALUE io, VALUE w)
Definition: io.c:679
static VALUE argf_initialize_copy(VALUE argf, VALUE orig)
Definition: io.c:7934
static VALUE rb_io_getline_1(VALUE rs, long limit, int chomp, VALUE io)
Definition: io.c:3229
struct rb_execarg::@139::@140 sh
static const char bom_prefix[]
Definition: io.c:4955
VALUE rb_io_ungetc(VALUE io, VALUE c)
Definition: io.c:3992
VALUE rb_output_fs
Definition: io.c:157
static VALUE argf_getc(VALUE argf)
Definition: io.c:11453
VALUE rb_mutex_owned_p(VALUE self)
Definition: thread_sync.c:316
static int maygvl_close(int fd, int keepgvl)
Definition: io.c:4247
void rb_econv_putback(rb_econv_t *ec, unsigned char *p, int n)
Definition: transcode.c:1749
static VALUE argf_skip(VALUE argf)
Definition: io.c:11916
void rb_io_check_closed(rb_io_t *fptr)
Definition: io.c:639
VALUE rb_attr_get(VALUE, ID)
Definition: variable.c:1273
#define SEEK_CUR
Definition: io.c:789
#define SET_BINARY_MODE(fptr)
Definition: io.c:590
char * strrchr(const char *, const char)
static VALUE io_encoding_set_v(VALUE v)
Definition: io.c:9606
VALUE rb_econv_str_convert(rb_econv_t *ec, VALUE src, int flags)
Definition: transcode.c:1874
VALUE io
Definition: io.c:9906
static int maygvl_fclose(FILE *file, int keepgvl)
Definition: io.c:4268
#define StringValue(v)
Definition: ruby.h:569
#define L(x)
Definition: asm.h:125
rb_econv_t * writeconv
Definition: io.h:91
static VALUE argf_forward_call(VALUE arg)
Definition: io.c:11328
void rb_write_error(const char *mesg)
Definition: io.c:7387
static int io_fillbuf(rb_io_t *fptr)
Definition: io.c:1753
Definition: io.c:9905
#define RUBY_UBF_IO
Definition: intern.h:900
static void fptr_waitpid(rb_io_t *fptr, int nohang)
Definition: io.c:4458
rb_encoding * rb_enc_from_index(int index)
Definition: encoding.c:616
VALUE rb_obj_class(VALUE)
Definition: object.c:229
VALUE rb_str_new(const char *, long)
Definition: string.c:736
#define SIGNED_VALUE
Definition: ruby.h:87
static VALUE sym_wait_writable
Definition: io.c:169
static VALUE rb_io_s_new(int argc, VALUE *argv, VALUE klass)
Definition: io.c:7795
static VALUE rb_f_print(int argc, const VALUE *argv)
Definition: io.c:7088
static void clear_readconv(rb_io_t *fptr)
Definition: io.c:4372
void rb_eof_error(void)
Definition: io.c:618