Ruby  2.0.0p195(2013-05-14revision40734)
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 "ruby/ruby.h"
15 #include "ruby/io.h"
16 #include "ruby/thread.h"
17 #include "dln.h"
18 #include "internal.h"
19 #include "id.h"
20 #include <ctype.h>
21 #include <errno.h>
22 #include "ruby_atomic.h"
23 
24 #define free(x) xfree(x)
25 
26 #if defined(DOSISH) || defined(__CYGWIN__)
27 #include <io.h>
28 #endif
29 
30 #include <sys/types.h>
31 #if defined HAVE_NET_SOCKET_H
32 # include <net/socket.h>
33 #elif defined HAVE_SYS_SOCKET_H
34 # ifndef __native_client__
35 # include <sys/socket.h>
36 # endif
37 #endif
38 
39 #if defined(__BOW__) || defined(__CYGWIN__) || defined(_WIN32) || defined(__EMX__) || defined(__BEOS__) || defined(__HAIKU__)
40 # define NO_SAFE_RENAME
41 #endif
42 
43 #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__sun) || defined(_nec_ews)
44 # define USE_SETVBUF
45 #endif
46 
47 #ifdef __QNXNTO__
48 #include "unix.h"
49 #endif
50 
51 #include <sys/types.h>
52 #if defined(HAVE_SYS_IOCTL_H) && !defined(_WIN32)
53 #include <sys/ioctl.h>
54 #endif
55 #if defined(__native_client__) && defined(NACL_NEWLIB)
56 # include "nacl/ioctl.h"
57 #endif
58 #if defined(HAVE_FCNTL_H) || defined(_WIN32)
59 #include <fcntl.h>
60 #elif defined(HAVE_SYS_FCNTL_H)
61 #include <sys/fcntl.h>
62 #endif
63 
64 #if !HAVE_OFF_T && !defined(off_t)
65 # define off_t long
66 #endif
67 
68 #include <sys/stat.h>
69 
70 /* EMX has sys/param.h, but.. */
71 #if defined(HAVE_SYS_PARAM_H) && !(defined(__EMX__) || defined(__HIUX_MPP__))
72 # include <sys/param.h>
73 #endif
74 
75 #if !defined NOFILE
76 # define NOFILE 64
77 #endif
78 
79 #ifdef HAVE_UNISTD_H
80 #include <unistd.h>
81 #endif
82 
83 #ifdef HAVE_SYSCALL_H
84 #include <syscall.h>
85 #elif defined HAVE_SYS_SYSCALL_H
86 #include <sys/syscall.h>
87 #endif
88 
89 #if defined(__BEOS__) || defined(__HAIKU__)
90 # ifndef NOFILE
91 # define NOFILE (OPEN_MAX)
92 # endif
93 #endif
94 
95 #include "ruby/util.h"
96 
97 #ifndef O_ACCMODE
98 #define O_ACCMODE (O_RDONLY | O_WRONLY | O_RDWR)
99 #endif
100 
101 #if SIZEOF_OFF_T > SIZEOF_LONG && !defined(HAVE_LONG_LONG)
102 # error off_t is bigger than long, but you have no long long...
103 #endif
104 
105 #ifndef PIPE_BUF
106 # ifdef _POSIX_PIPE_BUF
107 # define PIPE_BUF _POSIX_PIPE_BUF
108 # else
109 # define PIPE_BUF 512 /* is this ok? */
110 # endif
111 #endif
112 
113 #if defined(HAVE___SYSCALL) && (defined(__APPLE__) || defined(__OpenBSD__))
114 /* Mac OS X and OpenBSD have __syscall but don't define it in headers */
115 off_t __syscall(quad_t number, ...);
116 #endif
117 
118 #define numberof(array) (int)(sizeof(array) / sizeof((array)[0]))
119 
120 #define IO_RBUF_CAPA_MIN 8192
121 #define IO_CBUF_CAPA_MIN (128*1024)
122 #define IO_RBUF_CAPA_FOR(fptr) (NEED_READCONV(fptr) ? IO_CBUF_CAPA_MIN : IO_RBUF_CAPA_MIN)
123 #define IO_WBUF_CAPA_MIN 8192
124 
125 /* define system APIs */
126 #ifdef _WIN32
127 #undef open
128 #define open rb_w32_uopen
129 #endif
130 
136 
138 VALUE rb_deferr; /* rescue VIM plugin */
140 
145 
146 static VALUE argf;
147 
151 
152 struct argf {
154  long last_lineno; /* $. */
155  long lineno;
157  char *inplace;
158  struct rb_io_enc_t encs;
160 };
161 
163 void
165 {
166  struct stat buf;
168 
169  if (fstat(fd, &buf) != 0 && errno == EBADF) {
170  rb_bug("rb_update_max_fd: invalid fd (%d) given.", fd);
171  }
172 
173  while (max_file_descriptor < afd) {
175  }
176 }
177 
178 void
180 {
181  /* MinGW don't have F_GETFD and FD_CLOEXEC. [ruby-core:40281] */
182 #if defined(HAVE_FCNTL) && defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
183  int flags, flags2, ret;
184  flags = fcntl(fd, F_GETFD); /* should not fail except EBADF. */
185  if (flags == -1) {
186  rb_bug("rb_maygvl_fd_fix_cloexec: fcntl(%d, F_GETFD) failed: %s", fd, strerror(errno));
187  }
188  if (fd <= 2)
189  flags2 = flags & ~FD_CLOEXEC; /* Clear CLOEXEC for standard file descriptors: 0, 1, 2. */
190  else
191  flags2 = flags | FD_CLOEXEC; /* Set CLOEXEC for non-standard file descriptors: 3, 4, 5, ... */
192  if (flags != flags2) {
193  ret = fcntl(fd, F_SETFD, flags2);
194  if (ret == -1) {
195  rb_bug("rb_maygvl_fd_fix_cloexec: fcntl(%d, F_SETFD, %d) failed: %s", fd, flags2, strerror(errno));
196  }
197  }
198 #endif
199 }
200 
201 void
203 {
205  rb_update_max_fd(fd);
206 }
207 
208 int
209 rb_cloexec_open(const char *pathname, int flags, mode_t mode)
210 {
211  int ret;
212 #ifdef O_CLOEXEC
213  /* O_CLOEXEC is available since Linux 2.6.23. Linux 2.6.18 silently ignore it. */
214  flags |= O_CLOEXEC;
215 #elif defined O_NOINHERIT
216  flags |= O_NOINHERIT;
217 #endif
218  ret = open(pathname, flags, mode);
219  if (ret == -1) return -1;
221  return ret;
222 }
223 
224 int
225 rb_cloexec_dup(int oldfd)
226 {
227  /* Don't allocate standard file descriptors: 0, 1, 2 */
228  return rb_cloexec_fcntl_dupfd(oldfd, 3);
229 }
230 
231 int
232 rb_cloexec_dup2(int oldfd, int newfd)
233 {
234  int ret;
235 
236  /* When oldfd == newfd, dup2 succeeds but dup3 fails with EINVAL.
237  * rb_cloexec_dup2 succeeds as dup2. */
238  if (oldfd == newfd) {
239  ret = newfd;
240  }
241  else {
242 #if defined(HAVE_DUP3) && defined(O_CLOEXEC)
243  static int try_dup3 = 1;
244  if (2 < newfd && try_dup3) {
245  ret = dup3(oldfd, newfd, O_CLOEXEC);
246  if (ret != -1)
247  return ret;
248  /* dup3 is available since Linux 2.6.27, glibc 2.9. */
249  if (errno == ENOSYS) {
250  try_dup3 = 0;
251  ret = dup2(oldfd, newfd);
252  }
253  }
254  else {
255  ret = dup2(oldfd, newfd);
256  }
257 #else
258  ret = dup2(oldfd, newfd);
259 # ifdef _WIN32
260  if (newfd >= 0 && newfd <= 2)
261  SetStdHandle(newfd == 0 ? STD_INPUT_HANDLE : newfd == 1 ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE, (HANDLE)rb_w32_get_osfhandle(newfd));
262 # endif
263 #endif
264  if (ret == -1) return -1;
265  }
267  return ret;
268 }
269 
270 int
271 rb_cloexec_pipe(int fildes[2])
272 {
273  int ret;
274 
275 #if defined(HAVE_PIPE2)
276  static int try_pipe2 = 1;
277  if (try_pipe2) {
278  ret = pipe2(fildes, O_CLOEXEC);
279  if (ret != -1)
280  return ret;
281  /* pipe2 is available since Linux 2.6.27, glibc 2.9. */
282  if (errno == ENOSYS) {
283  try_pipe2 = 0;
284  ret = pipe(fildes);
285  }
286  }
287  else {
288  ret = pipe(fildes);
289  }
290 #else
291  ret = pipe(fildes);
292 #endif
293  if (ret == -1) return -1;
294 #ifdef __CYGWIN__
295  if (ret == 0 && fildes[1] == -1) {
296  close(fildes[0]);
297  fildes[0] = -1;
298  errno = ENFILE;
299  return -1;
300  }
301 #endif
302  rb_maygvl_fd_fix_cloexec(fildes[0]);
303  rb_maygvl_fd_fix_cloexec(fildes[1]);
304  return ret;
305 }
306 
307 int
308 rb_cloexec_fcntl_dupfd(int fd, int minfd)
309 {
310  int ret;
311 
312 #if defined(HAVE_FCNTL) && defined(F_DUPFD_CLOEXEC) && defined(F_DUPFD)
313  static int try_dupfd_cloexec = 1;
314  if (try_dupfd_cloexec) {
315  ret = fcntl(fd, F_DUPFD_CLOEXEC, minfd);
316  if (ret != -1) {
317  if (ret <= 2)
319  return ret;
320  }
321  /* F_DUPFD_CLOEXEC is available since Linux 2.6.24. Linux 2.6.18 fails with EINVAL */
322  if (errno == EINVAL) {
323  ret = fcntl(fd, F_DUPFD, minfd);
324  if (ret != -1) {
325  try_dupfd_cloexec = 0;
326  }
327  }
328  }
329  else {
330  ret = fcntl(fd, F_DUPFD, minfd);
331  }
332 #elif defined(HAVE_FCNTL) && defined(F_DUPFD)
333  ret = fcntl(fd, F_DUPFD, minfd);
334 #elif defined(HAVE_DUP)
335  ret = dup(fd);
336  if (ret != -1 && ret < minfd) {
337  const int prev_fd = ret;
338  ret = rb_cloexec_fcntl_dupfd(fd, minfd);
339  close(prev_fd);
340  }
341  return ret;
342 #else
343 # error "dup() or fcntl(F_DUPFD) must be supported."
344 #endif
345  if (ret == -1) return -1;
347  return ret;
348 }
349 
350 #define argf_of(obj) (*(struct argf *)DATA_PTR(obj))
351 #define ARGF argf_of(argf)
352 
353 #ifdef _STDIO_USES_IOSTREAM /* GNU libc */
354 # ifdef _IO_fpos_t
355 # define STDIO_READ_DATA_PENDING(fp) ((fp)->_IO_read_ptr != (fp)->_IO_read_end)
356 # else
357 # define STDIO_READ_DATA_PENDING(fp) ((fp)->_gptr < (fp)->_egptr)
358 # endif
359 #elif defined(FILE_COUNT)
360 # define STDIO_READ_DATA_PENDING(fp) ((fp)->FILE_COUNT > 0)
361 #elif defined(FILE_READEND)
362 # define STDIO_READ_DATA_PENDING(fp) ((fp)->FILE_READPTR < (fp)->FILE_READEND)
363 #elif defined(__BEOS__) || defined(__HAIKU__)
364 # define STDIO_READ_DATA_PENDING(fp) ((fp)->_state._eof == 0)
365 #else
366 # define STDIO_READ_DATA_PENDING(fp) (!feof(fp))
367 #endif
368 
369 #define GetWriteIO(io) rb_io_get_write_io(io)
370 
371 #define READ_DATA_PENDING(fptr) ((fptr)->rbuf.len)
372 #define READ_DATA_PENDING_COUNT(fptr) ((fptr)->rbuf.len)
373 #define READ_DATA_PENDING_PTR(fptr) ((fptr)->rbuf.ptr+(fptr)->rbuf.off)
374 #define READ_DATA_BUFFERED(fptr) READ_DATA_PENDING(fptr)
375 
376 #define READ_CHAR_PENDING(fptr) ((fptr)->cbuf.len)
377 #define READ_CHAR_PENDING_COUNT(fptr) ((fptr)->cbuf.len)
378 #define READ_CHAR_PENDING_PTR(fptr) ((fptr)->cbuf.ptr+(fptr)->cbuf.off)
379 
380 #if defined(_WIN32)
381 #define WAIT_FD_IN_WIN32(fptr) \
382  (rb_w32_io_cancelable_p((fptr)->fd) ? 0 : rb_thread_wait_fd((fptr)->fd))
383 #else
384 #define WAIT_FD_IN_WIN32(fptr)
385 #endif
386 
387 #define READ_CHECK(fptr) do {\
388  if (!READ_DATA_PENDING(fptr)) {\
389  WAIT_FD_IN_WIN32(fptr);\
390  rb_io_check_closed(fptr);\
391  }\
392 } while(0)
393 
394 #ifndef S_ISSOCK
395 # ifdef _S_ISSOCK
396 # define S_ISSOCK(m) _S_ISSOCK(m)
397 # else
398 # ifdef _S_IFSOCK
399 # define S_ISSOCK(m) (((m) & S_IFMT) == _S_IFSOCK)
400 # else
401 # ifdef S_IFSOCK
402 # define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK)
403 # endif
404 # endif
405 # endif
406 #endif
407 
408 #define rb_sys_fail_path(path) rb_sys_fail_str(path)
409 
410 static int io_fflush(rb_io_t *);
411 static rb_io_t *flush_before_seek(rb_io_t *fptr);
412 
413 #define NEED_NEWLINE_DECORATOR_ON_READ(fptr) ((fptr)->mode & FMODE_TEXTMODE)
414 #define NEED_NEWLINE_DECORATOR_ON_WRITE(fptr) ((fptr)->mode & FMODE_TEXTMODE)
415 #if defined(RUBY_TEST_CRLF_ENVIRONMENT) || defined(_WIN32)
416 /* Windows */
417 # define DEFAULT_TEXTMODE FMODE_TEXTMODE
418 # define TEXTMODE_NEWLINE_DECORATOR_ON_WRITE ECONV_CRLF_NEWLINE_DECORATOR
419 /*
420  * CRLF newline is set as default newline decorator.
421  * If only CRLF newline conversion is needed, we use binary IO process
422  * with OS's text mode for IO performance improvement.
423  * If encoding conversion is needed or a user sets text mode, we use encoding
424  * conversion IO process and universal newline decorator by default.
425  */
426 #define NEED_READCONV(fptr) ((fptr)->encs.enc2 != NULL || (fptr)->encs.ecflags & ~ECONV_CRLF_NEWLINE_DECORATOR)
427 #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)))
428 #define SET_BINARY_MODE(fptr) setmode((fptr)->fd, O_BINARY)
429 
430 #define NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr) do {\
431  if (NEED_NEWLINE_DECORATOR_ON_READ(fptr)) {\
432  if (((fptr)->mode & FMODE_READABLE) &&\
433  !((fptr)->encs.ecflags & ECONV_NEWLINE_DECORATOR_MASK)) {\
434  setmode((fptr)->fd, O_BINARY);\
435  }\
436  else {\
437  setmode((fptr)->fd, O_TEXT);\
438  }\
439  }\
440 } while(0)
441 
442 #define SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags) do {\
443  if ((enc2) && ((ecflags) & ECONV_DEFAULT_NEWLINE_DECORATOR)) {\
444  (ecflags) |= ECONV_UNIVERSAL_NEWLINE_DECORATOR;\
445  }\
446 } while(0)
447 
448 /*
449  * IO unread with taking care of removed '\r' in text mode.
450  */
451 static void
452 io_unread(rb_io_t *fptr)
453 {
454  off_t r, pos;
455  ssize_t read_size;
456  long i;
457  long newlines = 0;
458  long extra_max;
459  char *p;
460  char *buf;
461 
462  rb_io_check_closed(fptr);
463  if (fptr->rbuf.len == 0 || fptr->mode & FMODE_DUPLEX) {
464  return;
465  }
466 
467  errno = 0;
468  if (!rb_w32_fd_is_text(fptr->fd)) {
469  r = lseek(fptr->fd, -fptr->rbuf.len, SEEK_CUR);
470  if (r < 0 && errno) {
471  if (errno == ESPIPE)
472  fptr->mode |= FMODE_DUPLEX;
473  return;
474  }
475 
476  fptr->rbuf.off = 0;
477  fptr->rbuf.len = 0;
478  return;
479  }
480 
481  pos = lseek(fptr->fd, 0, SEEK_CUR);
482  if (pos < 0 && errno) {
483  if (errno == ESPIPE)
484  fptr->mode |= FMODE_DUPLEX;
485  return;
486  }
487 
488  /* add extra offset for removed '\r' in rbuf */
489  extra_max = (long)(pos - fptr->rbuf.len);
490  p = fptr->rbuf.ptr + fptr->rbuf.off;
491 
492  /* if the end of rbuf is '\r', rbuf doesn't have '\r' within rbuf.len */
493  if (*(fptr->rbuf.ptr + fptr->rbuf.capa - 1) == '\r') {
494  newlines++;
495  }
496 
497  for (i = 0; i < fptr->rbuf.len; i++) {
498  if (*p == '\n') newlines++;
499  if (extra_max == newlines) break;
500  p++;
501  }
502 
503  buf = ALLOC_N(char, fptr->rbuf.len + newlines);
504  while (newlines >= 0) {
505  r = lseek(fptr->fd, pos - fptr->rbuf.len - newlines, SEEK_SET);
506  if (newlines == 0) break;
507  if (r < 0) {
508  newlines--;
509  continue;
510  }
511  read_size = _read(fptr->fd, buf, fptr->rbuf.len + newlines);
512  if (read_size < 0) {
513  free(buf);
514  rb_sys_fail_path(fptr->pathv);
515  }
516  if (read_size == fptr->rbuf.len) {
517  lseek(fptr->fd, r, SEEK_SET);
518  break;
519  }
520  else {
521  newlines--;
522  }
523  }
524  free(buf);
525  fptr->rbuf.off = 0;
526  fptr->rbuf.len = 0;
527  return;
528 }
529 
530 /*
531  * We use io_seek to back cursor position when changing mode from text to binary,
532  * but stdin and pipe cannot seek back. Stdin and pipe read should use encoding
533  * conversion for working properly with mode change.
534  *
535  * Return previous translation mode.
536  */
537 static inline int
538 set_binary_mode_with_seek_cur(rb_io_t *fptr)
539 {
540  if (!rb_w32_fd_is_text(fptr->fd)) return O_BINARY;
541 
542  if (fptr->rbuf.len == 0 || fptr->mode & FMODE_DUPLEX) {
543  return setmode(fptr->fd, O_BINARY);
544  }
545  flush_before_seek(fptr);
546  return setmode(fptr->fd, O_BINARY);
547 }
548 #define SET_BINARY_MODE_WITH_SEEK_CUR(fptr) set_binary_mode_with_seek_cur(fptr)
549 
550 #else
551 /* Unix */
552 # define DEFAULT_TEXTMODE 0
553 #define NEED_READCONV(fptr) ((fptr)->encs.enc2 != NULL || NEED_NEWLINE_DECORATOR_ON_READ(fptr))
554 #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)))
555 #define SET_BINARY_MODE(fptr) (void)(fptr)
556 #define NEED_NEWLINE_DECORATOR_ON_READ_CHECK(fptr) (void)(fptr)
557 #define SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(enc2, ecflags) ((void)(enc2), (void)(ecflags))
558 #define SET_BINARY_MODE_WITH_SEEK_CUR(fptr) (void)(fptr)
559 #endif
560 
561 #if !defined HAVE_SHUTDOWN && !defined shutdown
562 #define shutdown(a,b) 0
563 #endif
564 
565 #if defined(_WIN32)
566 #define is_socket(fd, path) rb_w32_is_socket(fd)
567 #elif !defined(S_ISSOCK)
568 #define is_socket(fd, path) 0
569 #else
570 static int
571 is_socket(int fd, VALUE path)
572 {
573  struct stat sbuf;
574  if (fstat(fd, &sbuf) < 0)
575  rb_sys_fail_path(path);
576  return S_ISSOCK(sbuf.st_mode);
577 }
578 #endif
579 
580 void
582 {
583  rb_raise(rb_eEOFError, "end of file reached");
584 }
585 
586 VALUE
588 {
589  if (!OBJ_UNTRUSTED(io) && rb_safe_level() >= 4)
590  rb_raise(rb_eSecurityError, "Insecure: operation on trusted IO");
591  rb_check_frozen(io);
592  return io;
593 }
594 
595 void
597 {
598  if (!fptr) {
599  rb_raise(rb_eIOError, "uninitialized stream");
600  }
601 }
602 
603 void
605 {
607  if (fptr->fd < 0) {
608  rb_raise(rb_eIOError, "closed stream");
609  }
610 }
611 
612 
613 VALUE
615 {
616  return rb_convert_type(io, T_FILE, "IO", "to_io");
617 }
618 
619 VALUE
621 {
622  return rb_check_convert_type(io, T_FILE, "IO", "to_io");
623 }
624 
625 VALUE
627 {
628  VALUE write_io;
629  rb_io_check_initialized(RFILE(io)->fptr);
630  write_io = RFILE(io)->fptr->tied_io_for_writing;
631  if (write_io) {
632  return write_io;
633  }
634  return io;
635 }
636 
637 VALUE
639 {
640  VALUE write_io;
641  rb_io_check_initialized(RFILE(io)->fptr);
642  if (!RTEST(w)) {
643  w = 0;
644  }
645  else {
646  GetWriteIO(w);
647  }
648  write_io = RFILE(io)->fptr->tied_io_for_writing;
649  RFILE(io)->fptr->tied_io_for_writing = w;
650  return write_io ? write_io : Qnil;
651 }
652 
653 /*
654  * call-seq:
655  * IO.try_convert(obj) -> io or nil
656  *
657  * Try to convert <i>obj</i> into an IO, using to_io method.
658  * Returns converted IO or nil if <i>obj</i> cannot be converted
659  * for any reason.
660  *
661  * IO.try_convert(STDOUT) #=> STDOUT
662  * IO.try_convert("STDOUT") #=> nil
663  *
664  * require 'zlib'
665  * f = open("/tmp/zz.gz") #=> #<File:/tmp/zz.gz>
666  * z = Zlib::GzipReader.open(f) #=> #<Zlib::GzipReader:0x81d8744>
667  * IO.try_convert(z) #=> #<File:/tmp/zz.gz>
668  *
669  */
670 static VALUE
672 {
673  return rb_io_check_io(io);
674 }
675 
676 #if !(defined(RUBY_TEST_CRLF_ENVIRONMENT) || defined(_WIN32))
677 static void
679 {
680  off_t r;
681  rb_io_check_closed(fptr);
682  if (fptr->rbuf.len == 0 || fptr->mode & FMODE_DUPLEX)
683  return;
684  /* xxx: target position may be negative if buffer is filled by ungetc */
685  errno = 0;
686  r = lseek(fptr->fd, -fptr->rbuf.len, SEEK_CUR);
687  if (r < 0 && errno) {
688  if (errno == ESPIPE)
689  fptr->mode |= FMODE_DUPLEX;
690  return;
691  }
692  fptr->rbuf.off = 0;
693  fptr->rbuf.len = 0;
694  return;
695 }
696 #endif
697 
698 static rb_encoding *io_input_encoding(rb_io_t *fptr);
699 
700 static void
702 {
703  long len = RSTRING_LEN(str);
704 
705  if (fptr->rbuf.ptr == NULL) {
706  const int min_capa = IO_RBUF_CAPA_FOR(fptr);
707  fptr->rbuf.off = 0;
708  fptr->rbuf.len = 0;
709 #if SIZEOF_LONG > SIZEOF_INT
710  if (len > INT_MAX)
711  rb_raise(rb_eIOError, "ungetbyte failed");
712 #endif
713  if (len > min_capa)
714  fptr->rbuf.capa = (int)len;
715  else
716  fptr->rbuf.capa = min_capa;
717  fptr->rbuf.ptr = ALLOC_N(char, fptr->rbuf.capa);
718  }
719  if (fptr->rbuf.capa < len + fptr->rbuf.len) {
720  rb_raise(rb_eIOError, "ungetbyte failed");
721  }
722  if (fptr->rbuf.off < len) {
723  MEMMOVE(fptr->rbuf.ptr+fptr->rbuf.capa-fptr->rbuf.len,
724  fptr->rbuf.ptr+fptr->rbuf.off,
725  char, fptr->rbuf.len);
726  fptr->rbuf.off = fptr->rbuf.capa-fptr->rbuf.len;
727  }
728  fptr->rbuf.off-=(int)len;
729  fptr->rbuf.len+=(int)len;
730  MEMMOVE(fptr->rbuf.ptr+fptr->rbuf.off, RSTRING_PTR(str), char, len);
731 }
732 
733 static rb_io_t *
735 {
736  if (io_fflush(fptr) < 0)
737  rb_sys_fail(0);
738  io_unread(fptr);
739  errno = 0;
740  return fptr;
741 }
742 
743 #define io_seek(fptr, ofs, whence) (errno = 0, lseek(flush_before_seek(fptr)->fd, (ofs), (whence)))
744 #define io_tell(fptr) lseek(flush_before_seek(fptr)->fd, 0, SEEK_CUR)
745 
746 #ifndef SEEK_CUR
747 # define SEEK_SET 0
748 # define SEEK_CUR 1
749 # define SEEK_END 2
750 #endif
751 
752 void
754 {
755  rb_io_check_closed(fptr);
756  if (!(fptr->mode & FMODE_READABLE)) {
757  rb_raise(rb_eIOError, "not opened for reading");
758  }
759  if (fptr->wbuf.len) {
760  if (io_fflush(fptr) < 0)
761  rb_sys_fail(0);
762  }
763  if (fptr->tied_io_for_writing) {
764  rb_io_t *wfptr;
765  GetOpenFile(fptr->tied_io_for_writing, wfptr);
766  if (io_fflush(wfptr) < 0)
767  rb_sys_fail(0);
768  }
769 }
770 
771 void
773 {
775  if (READ_CHAR_PENDING(fptr)) {
776  rb_raise(rb_eIOError, "byte oriented read for character buffered IO");
777  }
778 }
779 
780 void
782 {
784 }
785 
786 static rb_encoding*
788 {
789  if (fptr->encs.enc) {
790  return fptr->encs.enc;
791  }
793 }
794 
795 static rb_encoding*
797 {
798  if (fptr->encs.enc2) {
799  return fptr->encs.enc2;
800  }
801  return io_read_encoding(fptr);
802 }
803 
804 void
806 {
807  rb_io_check_closed(fptr);
808  if (!(fptr->mode & FMODE_WRITABLE)) {
809  rb_raise(rb_eIOError, "not opened for writing");
810  }
811  if (fptr->rbuf.len) {
812  io_unread(fptr);
813  }
814 }
815 
816 int
818 {
819  /* This function is used for bytes and chars. Confusing. */
820  if (READ_CHAR_PENDING(fptr))
821  return 1; /* should raise? */
822  return READ_DATA_PENDING(fptr);
823 }
824 
825 void
827 {
828  if (!STDIO_READ_DATA_PENDING(fp)) {
830  }
831 }
832 
833 void
835 {
836  if (!READ_DATA_PENDING(fptr)) {
837  rb_thread_wait_fd(fptr->fd);
838  }
839  return;
840 }
841 
842 static int
843 ruby_dup(int orig)
844 {
845  int fd;
846 
847  fd = rb_cloexec_dup(orig);
848  if (fd < 0) {
849  if (errno == EMFILE || errno == ENFILE || errno == ENOMEM) {
850  rb_gc();
851  fd = rb_cloexec_dup(orig);
852  }
853  if (fd < 0) {
854  rb_sys_fail(0);
855  }
856  }
857  rb_update_max_fd(fd);
858  return fd;
859 }
860 
861 static VALUE
863 {
864  NEWOBJ_OF(io, struct RFile, klass, T_FILE);
865 
866  io->fptr = 0;
867 
868  return (VALUE)io;
869 }
870 
871 #ifndef S_ISREG
872 # define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
873 #endif
874 
875 static int
877 {
878 #if defined(HAVE_FCNTL) && defined(F_GETFL) && defined(O_NONBLOCK)
879  int r;
880 #endif
881 
882  if (!(fptr->mode & FMODE_WSPLIT_INITIALIZED)) {
883  struct stat buf;
884  if (fstat(fptr->fd, &buf) == 0 &&
885  !S_ISREG(buf.st_mode)
886 #if defined(HAVE_FCNTL) && defined(F_GETFL) && defined(O_NONBLOCK)
887  && (r = fcntl(fptr->fd, F_GETFL)) != -1 &&
888  !(r & O_NONBLOCK)
889 #endif
890  ) {
891  fptr->mode |= FMODE_WSPLIT;
892  }
894  }
895  return fptr->mode & FMODE_WSPLIT;
896 }
897 
899  int fd;
900  void *buf;
901  size_t capa;
902 };
903 
905  int fd;
906  const void *buf;
907  size_t capa;
908 };
909 
910 static VALUE
912 {
913  struct io_internal_read_struct *iis = ptr;
914  return read(iis->fd, iis->buf, iis->capa);
915 }
916 
917 static VALUE
919 {
920  struct io_internal_write_struct *iis = ptr;
921  return write(iis->fd, iis->buf, iis->capa);
922 }
923 
924 static void*
926 {
927  struct io_internal_write_struct *iis = ptr;
928  return (void*)(intptr_t)write(iis->fd, iis->buf, iis->capa);
929 }
930 
931 static ssize_t
932 rb_read_internal(int fd, void *buf, size_t count)
933 {
934  struct io_internal_read_struct iis;
935  iis.fd = fd;
936  iis.buf = buf;
937  iis.capa = count;
938 
939  return (ssize_t)rb_thread_io_blocking_region(internal_read_func, &iis, fd);
940 }
941 
942 static ssize_t
943 rb_write_internal(int fd, const void *buf, size_t count)
944 {
945  struct io_internal_write_struct iis;
946  iis.fd = fd;
947  iis.buf = buf;
948  iis.capa = count;
949 
950  return (ssize_t)rb_thread_io_blocking_region(internal_write_func, &iis, fd);
951 }
952 
953 static ssize_t
954 rb_write_internal2(int fd, const void *buf, size_t count)
955 {
956  struct io_internal_write_struct iis;
957  iis.fd = fd;
958  iis.buf = buf;
959  iis.capa = count;
960 
962  RUBY_UBF_IO, NULL);
963 }
964 
965 static long
967 {
968  if (PIPE_BUF < l &&
969  !rb_thread_alone() &&
970  wsplit_p(fptr)) {
971  l = PIPE_BUF;
972  }
973  return l;
974 }
975 
976 static VALUE
978 {
979  rb_io_t *fptr = arg;
980  long l = io_writable_length(fptr, fptr->wbuf.len);
981  ssize_t r = write(fptr->fd, fptr->wbuf.ptr+fptr->wbuf.off, (size_t)l);
982 
983  if (fptr->wbuf.len <= r) {
984  fptr->wbuf.off = 0;
985  fptr->wbuf.len = 0;
986  return 0;
987  }
988  if (0 <= r) {
989  fptr->wbuf.off += (int)r;
990  fptr->wbuf.len -= (int)r;
991  errno = EAGAIN;
992  }
993  return (VALUE)-1;
994 }
995 
996 static void*
998 {
1000 
1001  /*
1002  * rb_thread_call_without_gvl2 uses 0 as interrupted.
1003  * So, we need to avoid to use 0.
1004  */
1005  return !result ? (void*)1 : (void*)result;
1006 }
1007 
1008 static VALUE
1010 {
1011  rb_io_t *fptr = (rb_io_t *)arg;
1013 }
1014 
1015 static VALUE
1017 {
1018  rb_io_t *fptr = (rb_io_t *)arg;
1019  VALUE ret;
1020 
1022  RUBY_UBF_IO, NULL);
1023 
1024  if (!ret) {
1025  /* pending async interrupt is there. */
1026  errno = EAGAIN;
1027  return -1;
1028  } else if (ret == 1) {
1029  return 0;
1030  } else
1031  return ret;
1032 }
1033 
1034 static inline int
1036 {
1037  if (fptr->write_lock) {
1038  if (rb_mutex_owned_p(fptr->write_lock))
1039  return (int)io_flush_buffer_async2((VALUE)fptr);
1040  else
1041  return (int)rb_mutex_synchronize(fptr->write_lock, io_flush_buffer_async2, (VALUE)fptr);
1042  }
1043  else {
1044  return (int)io_flush_buffer_async((VALUE)fptr);
1045  }
1046 }
1047 
1048 static int
1050 {
1051  rb_io_check_closed(fptr);
1052  if (fptr->wbuf.len == 0)
1053  return 0;
1054  rb_io_check_closed(fptr);
1055  while (fptr->wbuf.len > 0 && io_flush_buffer(fptr) != 0) {
1056  if (!rb_io_wait_writable(fptr->fd))
1057  return -1;
1058  rb_io_check_closed(fptr);
1059  }
1060  return 0;
1061 }
1062 
1063 int
1065 {
1066  if (f < 0) {
1067  rb_raise(rb_eIOError, "closed stream");
1068  }
1069  switch (errno) {
1070  case EINTR:
1071 #if defined(ERESTART)
1072  case ERESTART:
1073 #endif
1075  return TRUE;
1076 
1077  case EAGAIN:
1078 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
1079  case EWOULDBLOCK:
1080 #endif
1081  rb_thread_wait_fd(f);
1082  return TRUE;
1083 
1084  default:
1085  return FALSE;
1086  }
1087 }
1088 
1089 int
1091 {
1092  if (f < 0) {
1093  rb_raise(rb_eIOError, "closed stream");
1094  }
1095  switch (errno) {
1096  case EINTR:
1097 #if defined(ERESTART)
1098  case ERESTART:
1099 #endif
1100  /*
1101  * In old Linux, several special files under /proc and /sys don't handle
1102  * select properly. Thus we need avoid to call if don't use O_NONBLOCK.
1103  * Otherwise, we face nasty hang up. Sigh.
1104  * e.g. http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=commit;h=31b07093c44a7a442394d44423e21d783f5523b8
1105  * http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=commit;h=31b07093c44a7a442394d44423e21d783f5523b8
1106  * In EINTR case, we only need to call RUBY_VM_CHECK_INTS_BLOCKING().
1107  * Then rb_thread_check_ints() is enough.
1108  */
1110  return TRUE;
1111 
1112  case EAGAIN:
1113 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
1114  case EWOULDBLOCK:
1115 #endif
1117  return TRUE;
1118 
1119  default:
1120  return FALSE;
1121  }
1122 }
1123 
1124 static void
1126 {
1127  if (!fptr->writeconv_initialized) {
1128  const char *senc, *denc;
1129  rb_encoding *enc;
1130  int ecflags;
1131  VALUE ecopts;
1132 
1133  fptr->writeconv_initialized = 1;
1134 
1135  ecflags = fptr->encs.ecflags & ~ECONV_NEWLINE_DECORATOR_READ_MASK;
1136  ecopts = fptr->encs.ecopts;
1137 
1138  if (!fptr->encs.enc || (fptr->encs.enc == rb_ascii8bit_encoding() && !fptr->encs.enc2)) {
1139  /* no encoding conversion */
1140  fptr->writeconv_pre_ecflags = 0;
1141  fptr->writeconv_pre_ecopts = Qnil;
1142  fptr->writeconv = rb_econv_open_opts("", "", ecflags, ecopts);
1143  if (!fptr->writeconv)
1144  rb_exc_raise(rb_econv_open_exc("", "", ecflags));
1145  fptr->writeconv_asciicompat = Qnil;
1146  }
1147  else {
1148  enc = fptr->encs.enc2 ? fptr->encs.enc2 : fptr->encs.enc;
1150  if (!senc && !(fptr->encs.ecflags & ECONV_STATEFUL_DECORATOR_MASK)) {
1151  /* single conversion */
1152  fptr->writeconv_pre_ecflags = ecflags;
1153  fptr->writeconv_pre_ecopts = ecopts;
1154  fptr->writeconv = NULL;
1155  fptr->writeconv_asciicompat = Qnil;
1156  }
1157  else {
1158  /* double conversion */
1160  fptr->writeconv_pre_ecopts = ecopts;
1161  if (senc) {
1162  denc = rb_enc_name(enc);
1163  fptr->writeconv_asciicompat = rb_str_new2(senc);
1164  }
1165  else {
1166  senc = denc = "";
1168  }
1170  ecopts = fptr->encs.ecopts;
1171  fptr->writeconv = rb_econv_open_opts(senc, denc, ecflags, ecopts);
1172  if (!fptr->writeconv)
1173  rb_exc_raise(rb_econv_open_exc(senc, denc, ecflags));
1174  }
1175  }
1176  }
1177 }
1178 
1179 /* writing functions */
1183  const char *ptr;
1184  long length;
1185 };
1186 
1187 struct write_arg {
1190  int nosync;
1191 };
1192 
1193 static VALUE
1195 {
1196  struct binwrite_arg *p = (struct binwrite_arg *)arg;
1197  long l = io_writable_length(p->fptr, p->length);
1198  return rb_write_internal2(p->fptr->fd, p->ptr, l);
1199 }
1200 
1201 static long
1202 io_binwrite(VALUE str, const char *ptr, long len, rb_io_t *fptr, int nosync)
1203 {
1204  long n, r, offset = 0;
1205 
1206  /* don't write anything if current thread has a pending interrupt. */
1208 
1209  if ((n = len) <= 0) return n;
1210  if (fptr->wbuf.ptr == NULL && !(!nosync && (fptr->mode & FMODE_SYNC))) {
1211  fptr->wbuf.off = 0;
1212  fptr->wbuf.len = 0;
1213  fptr->wbuf.capa = IO_WBUF_CAPA_MIN;
1214  fptr->wbuf.ptr = ALLOC_N(char, fptr->wbuf.capa);
1215  fptr->write_lock = rb_mutex_new();
1216  rb_mutex_allow_trap(fptr->write_lock, 1);
1217  }
1218  if ((!nosync && (fptr->mode & (FMODE_SYNC|FMODE_TTY))) ||
1219  (fptr->wbuf.ptr && fptr->wbuf.capa <= fptr->wbuf.len + len)) {
1220  struct binwrite_arg arg;
1221 
1222  /*
1223  * xxx: use writev to avoid double write if available
1224  * writev may help avoid context switch between "a" and "\n" in
1225  * STDERR.puts "a" [ruby-dev:25080] (rebroken since native threads
1226  * introduced in 1.9)
1227  */
1228  if (fptr->wbuf.len && fptr->wbuf.len+len <= fptr->wbuf.capa) {
1229  if (fptr->wbuf.capa < fptr->wbuf.off+fptr->wbuf.len+len) {
1230  MEMMOVE(fptr->wbuf.ptr, fptr->wbuf.ptr+fptr->wbuf.off, char, fptr->wbuf.len);
1231  fptr->wbuf.off = 0;
1232  }
1233  MEMMOVE(fptr->wbuf.ptr+fptr->wbuf.off+fptr->wbuf.len, ptr+offset, char, len);
1234  fptr->wbuf.len += (int)len;
1235  n = 0;
1236  }
1237  if (io_fflush(fptr) < 0)
1238  return -1L;
1239  if (n == 0)
1240  return len;
1241 
1242  rb_io_check_closed(fptr);
1243  arg.fptr = fptr;
1244  arg.str = str;
1245  retry:
1246  arg.ptr = ptr + offset;
1247  arg.length = n;
1248  if (fptr->write_lock) {
1250  }
1251  else {
1252  long l = io_writable_length(fptr, n);
1253  r = rb_write_internal(fptr->fd, ptr+offset, l);
1254  }
1255  /* xxx: other threads may modify given string. */
1256  if (r == n) return len;
1257  if (0 <= r) {
1258  offset += r;
1259  n -= r;
1260  errno = EAGAIN;
1261  }
1262  if (rb_io_wait_writable(fptr->fd)) {
1263  rb_io_check_closed(fptr);
1264  if (offset < len)
1265  goto retry;
1266  }
1267  return -1L;
1268  }
1269 
1270  if (fptr->wbuf.off) {
1271  if (fptr->wbuf.len)
1272  MEMMOVE(fptr->wbuf.ptr, fptr->wbuf.ptr+fptr->wbuf.off, char, fptr->wbuf.len);
1273  fptr->wbuf.off = 0;
1274  }
1275  MEMMOVE(fptr->wbuf.ptr+fptr->wbuf.off+fptr->wbuf.len, ptr+offset, char, len);
1276  fptr->wbuf.len += (int)len;
1277  return len;
1278 }
1279 
1280 # define MODE_BTMODE(a,b,c) ((fmode & FMODE_BINMODE) ? (b) : \
1281  (fmode & FMODE_TEXTMODE) ? (c) : (a))
1282 static VALUE
1284 {
1285  if (NEED_WRITECONV(fptr)) {
1286  VALUE common_encoding = Qnil;
1287  SET_BINARY_MODE(fptr);
1288 
1289  make_writeconv(fptr);
1290 
1291  if (fptr->writeconv) {
1292 #define fmode (fptr->mode)
1293  if (!NIL_P(fptr->writeconv_asciicompat))
1294  common_encoding = fptr->writeconv_asciicompat;
1295  else if (MODE_BTMODE(DEFAULT_TEXTMODE,0,1) && !rb_enc_asciicompat(rb_enc_get(str))) {
1296  rb_raise(rb_eArgError, "ASCII incompatible string written for text mode IO without encoding conversion: %s",
1297  rb_enc_name(rb_enc_get(str)));
1298  }
1299 #undef fmode
1300  }
1301  else {
1302  if (fptr->encs.enc2)
1303  common_encoding = rb_enc_from_encoding(fptr->encs.enc2);
1304  else if (fptr->encs.enc != rb_ascii8bit_encoding())
1305  common_encoding = rb_enc_from_encoding(fptr->encs.enc);
1306  }
1307 
1308  if (!NIL_P(common_encoding)) {
1309  str = rb_str_encode(str, common_encoding,
1311  }
1312 
1313  if (fptr->writeconv) {
1315  }
1316  }
1317 #if defined(RUBY_TEST_CRLF_ENVIRONMENT) || defined(_WIN32)
1318 #define fmode (fptr->mode)
1319  else if (MODE_BTMODE(DEFAULT_TEXTMODE,0,1)) {
1320  if ((fptr->mode & FMODE_READABLE) &&
1322  setmode(fptr->fd, O_BINARY);
1323  }
1324  else {
1325  setmode(fptr->fd, O_TEXT);
1326  }
1327  if (!rb_enc_asciicompat(rb_enc_get(str))) {
1328  rb_raise(rb_eArgError, "ASCII incompatible string written for text mode IO without encoding conversion: %s",
1329  rb_enc_name(rb_enc_get(str)));
1330  }
1331  }
1332 #undef fmode
1333 #endif
1334  return str;
1335 }
1336 
1337 static long
1338 io_fwrite(VALUE str, rb_io_t *fptr, int nosync)
1339 {
1340 #ifdef _WIN32
1341  if (fptr->mode & FMODE_TTY) {
1342  long len = rb_w32_write_console(str, fptr->fd);
1343  if (len > 0) return len;
1344  }
1345 #endif
1346  str = do_writeconv(str, fptr);
1347  return io_binwrite(str, RSTRING_PTR(str), RSTRING_LEN(str),
1348  fptr, nosync);
1349 }
1350 
1351 ssize_t
1352 rb_io_bufwrite(VALUE io, const void *buf, size_t size)
1353 {
1354  rb_io_t *fptr;
1355 
1356  GetOpenFile(io, fptr);
1357  rb_io_check_writable(fptr);
1358  return (ssize_t)io_binwrite(0, buf, (long)size, fptr, 0);
1359 }
1360 
1361 static VALUE
1362 io_write(VALUE io, VALUE str, int nosync)
1363 {
1364  rb_io_t *fptr;
1365  long n;
1366  VALUE tmp;
1367 
1368  rb_secure(4);
1369  io = GetWriteIO(io);
1370  str = rb_obj_as_string(str);
1371  tmp = rb_io_check_io(io);
1372  if (NIL_P(tmp)) {
1373  /* port is not IO, call write method for it. */
1374  return rb_funcall(io, id_write, 1, str);
1375  }
1376  io = tmp;
1377  if (RSTRING_LEN(str) == 0) return INT2FIX(0);
1378 
1379  str = rb_str_new_frozen(str);
1380 
1381  GetOpenFile(io, fptr);
1382  rb_io_check_writable(fptr);
1383 
1384  n = io_fwrite(str, fptr, nosync);
1385  if (n == -1L) rb_sys_fail_path(fptr->pathv);
1386 
1387  return LONG2FIX(n);
1388 }
1389 
1390 /*
1391  * call-seq:
1392  * ios.write(string) -> integer
1393  *
1394  * Writes the given string to <em>ios</em>. The stream must be opened
1395  * for writing. If the argument is not a string, it will be converted
1396  * to a string using <code>to_s</code>. Returns the number of bytes
1397  * written.
1398  *
1399  * count = $stdout.write("This is a test\n")
1400  * puts "That was #{count} bytes of data"
1401  *
1402  * <em>produces:</em>
1403  *
1404  * This is a test
1405  * That was 15 bytes of data
1406  */
1407 
1408 static VALUE
1410 {
1411  return io_write(io, str, 0);
1412 }
1413 
1414 VALUE
1416 {
1417  return rb_funcall(io, id_write, 1, str);
1418 }
1419 
1420 /*
1421  * call-seq:
1422  * ios << obj -> ios
1423  *
1424  * String Output---Writes <i>obj</i> to <em>ios</em>.
1425  * <i>obj</i> will be converted to a string using
1426  * <code>to_s</code>.
1427  *
1428  * $stdout << "Hello " << "world!\n"
1429  *
1430  * <em>produces:</em>
1431  *
1432  * Hello world!
1433  */
1434 
1435 
1436 VALUE
1438 {
1439  rb_io_write(io, str);
1440  return io;
1441 }
1442 
1443 #ifdef HAVE_FSYNC
1444 static VALUE
1445 nogvl_fsync(void *ptr)
1446 {
1447  rb_io_t *fptr = ptr;
1448 
1449  return (VALUE)fsync(fptr->fd);
1450 }
1451 #endif
1452 
1453 /*
1454  * call-seq:
1455  * ios.flush -> ios
1456  *
1457  * Flushes any buffered data within <em>ios</em> to the underlying
1458  * operating system (note that this is Ruby internal buffering only;
1459  * the OS may buffer the data as well).
1460  *
1461  * $stdout.print "no newline"
1462  * $stdout.flush
1463  *
1464  * <em>produces:</em>
1465  *
1466  * no newline
1467  */
1468 
1469 VALUE
1471 {
1472  rb_io_t *fptr;
1473 
1474  if (!RB_TYPE_P(io, T_FILE)) {
1475  return rb_funcall(io, id_flush, 0);
1476  }
1477 
1478  io = GetWriteIO(io);
1479  GetOpenFile(io, fptr);
1480 
1481  if (fptr->mode & FMODE_WRITABLE) {
1482  if (io_fflush(fptr) < 0)
1483  rb_sys_fail(0);
1484 #ifdef _WIN32
1485  if (GetFileType((HANDLE)rb_w32_get_osfhandle(fptr->fd)) == FILE_TYPE_DISK) {
1486  rb_thread_io_blocking_region(nogvl_fsync, fptr, fptr->fd);
1487  }
1488 #endif
1489  }
1490  if (fptr->mode & FMODE_READABLE) {
1491  io_unread(fptr);
1492  }
1493 
1494  return io;
1495 }
1496 
1497 /*
1498  * call-seq:
1499  * ios.pos -> integer
1500  * ios.tell -> integer
1501  *
1502  * Returns the current offset (in bytes) of <em>ios</em>.
1503  *
1504  * f = File.new("testfile")
1505  * f.pos #=> 0
1506  * f.gets #=> "This is line one\n"
1507  * f.pos #=> 17
1508  */
1509 
1510 static VALUE
1512 {
1513  rb_io_t *fptr;
1514  off_t pos;
1515 
1516  GetOpenFile(io, fptr);
1517  pos = io_tell(fptr);
1518  if (pos < 0 && errno) rb_sys_fail_path(fptr->pathv);
1519  pos -= fptr->rbuf.len;
1520  return OFFT2NUM(pos);
1521 }
1522 
1523 static VALUE
1524 rb_io_seek(VALUE io, VALUE offset, int whence)
1525 {
1526  rb_io_t *fptr;
1527  off_t pos;
1528 
1529  pos = NUM2OFFT(offset);
1530  GetOpenFile(io, fptr);
1531  pos = io_seek(fptr, pos, whence);
1532  if (pos < 0 && errno) rb_sys_fail_path(fptr->pathv);
1533 
1534  return INT2FIX(0);
1535 }
1536 
1537 /*
1538  * call-seq:
1539  * ios.seek(amount, whence=IO::SEEK_SET) -> 0
1540  *
1541  * Seeks to a given offset <i>anInteger</i> in the stream according to
1542  * the value of <i>whence</i>:
1543  *
1544  * IO::SEEK_CUR | Seeks to _amount_ plus current position
1545  * --------------+----------------------------------------------------
1546  * IO::SEEK_END | Seeks to _amount_ plus end of stream (you probably
1547  * | want a negative value for _amount_)
1548  * --------------+----------------------------------------------------
1549  * IO::SEEK_SET | Seeks to the absolute location given by _amount_
1550  *
1551  * Example:
1552  *
1553  * f = File.new("testfile")
1554  * f.seek(-13, IO::SEEK_END) #=> 0
1555  * f.readline #=> "And so on...\n"
1556  */
1557 
1558 static VALUE
1560 {
1561  VALUE offset, ptrname;
1562  int whence = SEEK_SET;
1563 
1564  if (rb_scan_args(argc, argv, "11", &offset, &ptrname) == 2) {
1565  whence = NUM2INT(ptrname);
1566  }
1567 
1568  return rb_io_seek(io, offset, whence);
1569 }
1570 
1571 /*
1572  * call-seq:
1573  * ios.pos = integer -> integer
1574  *
1575  * Seeks to the given position (in bytes) in <em>ios</em>.
1576  * It is not guranteed that seeking to the right position when <em>ios</em>
1577  * is textmode.
1578  *
1579  * f = File.new("testfile")
1580  * f.pos = 17
1581  * f.gets #=> "This is line two\n"
1582  */
1583 
1584 static VALUE
1586 {
1587  rb_io_t *fptr;
1588  off_t pos;
1589 
1590  pos = NUM2OFFT(offset);
1591  GetOpenFile(io, fptr);
1592  pos = io_seek(fptr, pos, SEEK_SET);
1593  if (pos < 0 && errno) rb_sys_fail_path(fptr->pathv);
1594 
1595  return OFFT2NUM(pos);
1596 }
1597 
1598 static void clear_readconv(rb_io_t *fptr);
1599 
1600 /*
1601  * call-seq:
1602  * ios.rewind -> 0
1603  *
1604  * Positions <em>ios</em> to the beginning of input, resetting
1605  * <code>lineno</code> to zero.
1606  *
1607  * f = File.new("testfile")
1608  * f.readline #=> "This is line one\n"
1609  * f.rewind #=> 0
1610  * f.lineno #=> 0
1611  * f.readline #=> "This is line one\n"
1612  *
1613  * Note that it cannot be used with streams such as pipes, ttys, and sockets.
1614  */
1615 
1616 static VALUE
1618 {
1619  rb_io_t *fptr;
1620 
1621  GetOpenFile(io, fptr);
1622  if (io_seek(fptr, 0L, 0) < 0 && errno) rb_sys_fail_path(fptr->pathv);
1623 #ifdef _WIN32
1624  if (GetFileType((HANDLE)rb_w32_get_osfhandle(fptr->fd)) == FILE_TYPE_DISK) {
1625  fsync(fptr->fd);
1626  }
1627 #endif
1628  if (io == ARGF.current_file) {
1629  ARGF.lineno -= fptr->lineno;
1630  }
1631  fptr->lineno = 0;
1632  if (fptr->readconv) {
1633  clear_readconv(fptr);
1634  }
1635 
1636  return INT2FIX(0);
1637 }
1638 
1639 static int
1641 {
1642  ssize_t r;
1643 
1644  if (fptr->rbuf.ptr == NULL) {
1645  fptr->rbuf.off = 0;
1646  fptr->rbuf.len = 0;
1647  fptr->rbuf.capa = IO_RBUF_CAPA_FOR(fptr);
1648  fptr->rbuf.ptr = ALLOC_N(char, fptr->rbuf.capa);
1649 #ifdef _WIN32
1650  fptr->rbuf.capa--;
1651 #endif
1652  }
1653  if (fptr->rbuf.len == 0) {
1654  retry:
1655  {
1656  r = rb_read_internal(fptr->fd, fptr->rbuf.ptr, fptr->rbuf.capa);
1657  }
1658  if (r < 0) {
1659  if (rb_io_wait_readable(fptr->fd))
1660  goto retry;
1661  rb_sys_fail_path(fptr->pathv);
1662  }
1663  fptr->rbuf.off = 0;
1664  fptr->rbuf.len = (int)r; /* r should be <= rbuf_capa */
1665  if (r == 0)
1666  return -1; /* EOF */
1667  }
1668  return 0;
1669 }
1670 
1671 /*
1672  * call-seq:
1673  * ios.eof -> true or false
1674  * ios.eof? -> true or false
1675  *
1676  * Returns true if <em>ios</em> is at end of file that means
1677  * there are no more data to read.
1678  * The stream must be opened for reading or an <code>IOError</code> will be
1679  * raised.
1680  *
1681  * f = File.new("testfile")
1682  * dummy = f.readlines
1683  * f.eof #=> true
1684  *
1685  * If <em>ios</em> is a stream such as pipe or socket, <code>IO#eof?</code>
1686  * blocks until the other end sends some data or closes it.
1687  *
1688  * r, w = IO.pipe
1689  * Thread.new { sleep 1; w.close }
1690  * r.eof? #=> true after 1 second blocking
1691  *
1692  * r, w = IO.pipe
1693  * Thread.new { sleep 1; w.puts "a" }
1694  * r.eof? #=> false after 1 second blocking
1695  *
1696  * r, w = IO.pipe
1697  * r.eof? # blocks forever
1698  *
1699  * Note that <code>IO#eof?</code> reads data to the input byte buffer.
1700  * So <code>IO#sysread</code> may not behave as you intend with
1701  * <code>IO#eof?</code>, unless you call <code>IO#rewind</code>
1702  * first (which is not available for some streams).
1703  */
1704 
1705 VALUE
1707 {
1708  rb_io_t *fptr;
1709 
1710  GetOpenFile(io, fptr);
1712 
1713  if (READ_CHAR_PENDING(fptr)) return Qfalse;
1714  if (READ_DATA_PENDING(fptr)) return Qfalse;
1715  READ_CHECK(fptr);
1716 #if defined(RUBY_TEST_CRLF_ENVIRONMENT) || defined(_WIN32)
1717  if (!NEED_READCONV(fptr) && NEED_NEWLINE_DECORATOR_ON_READ(fptr)) {
1718  return eof(fptr->fd) ? Qtrue : Qfalse;
1719  }
1720 #endif
1721  if (io_fillbuf(fptr) < 0) {
1722  return Qtrue;
1723  }
1724  return Qfalse;
1725 }
1726 
1727 /*
1728  * call-seq:
1729  * ios.sync -> true or false
1730  *
1731  * Returns the current ``sync mode'' of <em>ios</em>. When sync mode is
1732  * true, all output is immediately flushed to the underlying operating
1733  * system and is not buffered by Ruby internally. See also
1734  * <code>IO#fsync</code>.
1735  *
1736  * f = File.new("testfile")
1737  * f.sync #=> false
1738  */
1739 
1740 static VALUE
1742 {
1743  rb_io_t *fptr;
1744 
1745  io = GetWriteIO(io);
1746  GetOpenFile(io, fptr);
1747  return (fptr->mode & FMODE_SYNC) ? Qtrue : Qfalse;
1748 }
1749 
1750 #ifdef HAVE_FSYNC
1751 
1752 /*
1753  * call-seq:
1754  * ios.sync = boolean -> boolean
1755  *
1756  * Sets the ``sync mode'' to <code>true</code> or <code>false</code>.
1757  * When sync mode is true, all output is immediately flushed to the
1758  * underlying operating system and is not buffered internally. Returns
1759  * the new state. See also <code>IO#fsync</code>.
1760  *
1761  * f = File.new("testfile")
1762  * f.sync = true
1763  *
1764  * <em>(produces no output)</em>
1765  */
1766 
1767 static VALUE
1768 rb_io_set_sync(VALUE io, VALUE sync)
1769 {
1770  rb_io_t *fptr;
1771 
1772  io = GetWriteIO(io);
1773  GetOpenFile(io, fptr);
1774  if (RTEST(sync)) {
1775  fptr->mode |= FMODE_SYNC;
1776  }
1777  else {
1778  fptr->mode &= ~FMODE_SYNC;
1779  }
1780  return sync;
1781 }
1782 
1783 /*
1784  * call-seq:
1785  * ios.fsync -> 0 or nil
1786  *
1787  * Immediately writes all buffered data in <em>ios</em> to disk.
1788  * Note that <code>fsync</code> differs from
1789  * using <code>IO#sync=</code>. The latter ensures that data is flushed
1790  * from Ruby's buffers, but does not guarantee that the underlying
1791  * operating system actually writes it to disk.
1792  *
1793  * <code>NotImplementedError</code> is raised
1794  * if the underlying operating system does not support <em>fsync(2)</em>.
1795  */
1796 
1797 static VALUE
1798 rb_io_fsync(VALUE io)
1799 {
1800  rb_io_t *fptr;
1801 
1802  io = GetWriteIO(io);
1803  GetOpenFile(io, fptr);
1804 
1805  if (io_fflush(fptr) < 0)
1806  rb_sys_fail(0);
1807 # ifndef _WIN32 /* already called in io_fflush() */
1808  if ((int)rb_thread_io_blocking_region(nogvl_fsync, fptr, fptr->fd) < 0)
1809  rb_sys_fail_path(fptr->pathv);
1810 # endif
1811  return INT2FIX(0);
1812 }
1813 #else
1814 # define rb_io_fsync rb_f_notimplement
1815 # define rb_io_sync rb_f_notimplement
1816 static VALUE
1818 {
1819  rb_notimplement();
1820  UNREACHABLE;
1821 }
1822 #endif
1823 
1824 #ifdef HAVE_FDATASYNC
1825 static VALUE
1826 nogvl_fdatasync(void *ptr)
1827 {
1828  rb_io_t *fptr = ptr;
1829 
1830  return (VALUE)fdatasync(fptr->fd);
1831 }
1832 
1833 /*
1834  * call-seq:
1835  * ios.fdatasync -> 0 or nil
1836  *
1837  * Immediately writes all buffered data in <em>ios</em> to disk.
1838  *
1839  * If the underlying operating system does not support <em>fdatasync(2)</em>,
1840  * <code>IO#fsync</code> is called instead (which might raise a
1841  * <code>NotImplementedError</code>).
1842  */
1843 
1844 static VALUE
1846 {
1847  rb_io_t *fptr;
1848 
1849  io = GetWriteIO(io);
1850  GetOpenFile(io, fptr);
1851 
1852  if (io_fflush(fptr) < 0)
1853  rb_sys_fail(0);
1854 
1855  if ((int)rb_thread_io_blocking_region(nogvl_fdatasync, fptr, fptr->fd) == 0)
1856  return INT2FIX(0);
1857 
1858  /* fall back */
1859  return rb_io_fsync(io);
1860 }
1861 #else
1862 #define rb_io_fdatasync rb_io_fsync
1863 #endif
1864 
1865 /*
1866  * call-seq:
1867  * ios.fileno -> fixnum
1868  * ios.to_i -> fixnum
1869  *
1870  * Returns an integer representing the numeric file descriptor for
1871  * <em>ios</em>.
1872  *
1873  * $stdin.fileno #=> 0
1874  * $stdout.fileno #=> 1
1875  */
1876 
1877 static VALUE
1879 {
1880  rb_io_t *fptr;
1881  int fd;
1882 
1883  GetOpenFile(io, fptr);
1884  fd = fptr->fd;
1885  return INT2FIX(fd);
1886 }
1887 
1888 
1889 /*
1890  * call-seq:
1891  * ios.pid -> fixnum
1892  *
1893  * Returns the process ID of a child process associated with
1894  * <em>ios</em>. This will be set by <code>IO.popen</code>.
1895  *
1896  * pipe = IO.popen("-")
1897  * if pipe
1898  * $stderr.puts "In parent, child pid is #{pipe.pid}"
1899  * else
1900  * $stderr.puts "In child, pid is #{$$}"
1901  * end
1902  *
1903  * <em>produces:</em>
1904  *
1905  * In child, pid is 26209
1906  * In parent, child pid is 26209
1907  */
1908 
1909 static VALUE
1911 {
1912  rb_io_t *fptr;
1913 
1914  GetOpenFile(io, fptr);
1915  if (!fptr->pid)
1916  return Qnil;
1917  return PIDT2NUM(fptr->pid);
1918 }
1919 
1920 
1921 /*
1922  * call-seq:
1923  * ios.inspect -> string
1924  *
1925  * Return a string describing this IO object.
1926  */
1927 
1928 static VALUE
1930 {
1931  rb_io_t *fptr;
1932  VALUE result;
1933  static const char closed[] = " (closed)";
1934 
1935  fptr = RFILE(rb_io_taint_check(obj))->fptr;
1936  if (!fptr) return rb_any_to_s(obj);
1937  result = rb_str_new_cstr("#<");
1938  rb_str_append(result, rb_class_name(CLASS_OF(obj)));
1939  rb_str_cat2(result, ":");
1940  if (NIL_P(fptr->pathv)) {
1941  if (fptr->fd < 0) {
1942  rb_str_cat(result, closed+1, strlen(closed)-1);
1943  }
1944  else {
1945  rb_str_catf(result, "fd %d", fptr->fd);
1946  }
1947  }
1948  else {
1949  rb_str_append(result, fptr->pathv);
1950  if (fptr->fd < 0) {
1951  rb_str_cat(result, closed, strlen(closed));
1952  }
1953  }
1954  return rb_str_cat2(result, ">");
1955 }
1956 
1957 /*
1958  * call-seq:
1959  * ios.to_io -> ios
1960  *
1961  * Returns <em>ios</em>.
1962  */
1963 
1964 static VALUE
1966 {
1967  return io;
1968 }
1969 
1970 /* reading functions */
1971 static long
1972 read_buffered_data(char *ptr, long len, rb_io_t *fptr)
1973 {
1974  int n;
1975 
1976  n = READ_DATA_PENDING_COUNT(fptr);
1977  if (n <= 0) return 0;
1978  if (n > len) n = (int)len;
1979  MEMMOVE(ptr, fptr->rbuf.ptr+fptr->rbuf.off, char, n);
1980  fptr->rbuf.off += n;
1981  fptr->rbuf.len -= n;
1982  return n;
1983 }
1984 
1985 static long
1986 io_bufread(char *ptr, long len, rb_io_t *fptr)
1987 {
1988  long offset = 0;
1989  long n = len;
1990  long c;
1991 
1992  if (READ_DATA_PENDING(fptr) == 0) {
1993  while (n > 0) {
1994  again:
1995  c = rb_read_internal(fptr->fd, ptr+offset, n);
1996  if (c == 0) break;
1997  if (c < 0) {
1998  if (rb_io_wait_readable(fptr->fd))
1999  goto again;
2000  return -1;
2001  }
2002  offset += c;
2003  if ((n -= c) <= 0) break;
2004  }
2005  return len - n;
2006  }
2007 
2008  while (n > 0) {
2009  c = read_buffered_data(ptr+offset, n, fptr);
2010  if (c > 0) {
2011  offset += c;
2012  if ((n -= c) <= 0) break;
2013  }
2014  rb_io_check_closed(fptr);
2015  if (io_fillbuf(fptr) < 0) {
2016  break;
2017  }
2018  }
2019  return len - n;
2020 }
2021 
2022 static void io_setstrbuf(VALUE *str, long len);
2023 
2024 static long
2025 io_fread(VALUE str, long offset, long size, rb_io_t *fptr)
2026 {
2027  long len;
2028 
2029  io_setstrbuf(&str, offset + size);
2030  rb_str_locktmp(str);
2031  len = io_bufread(RSTRING_PTR(str) + offset, size, fptr);
2032  rb_str_unlocktmp(str);
2033  if (len < 0) rb_sys_fail_path(fptr->pathv);
2034  return len;
2035 }
2036 
2037 ssize_t
2038 rb_io_bufread(VALUE io, void *buf, size_t size)
2039 {
2040  rb_io_t *fptr;
2041 
2042  GetOpenFile(io, fptr);
2043  rb_io_check_readable(fptr);
2044  return (ssize_t)io_bufread(buf, (long)size, fptr);
2045 }
2046 
2047 #define SMALLBUF 100
2048 
2049 static long
2051 {
2052  struct stat st;
2053  off_t siz = READ_DATA_PENDING_COUNT(fptr);
2054  off_t pos;
2055 
2056  if (fstat(fptr->fd, &st) == 0 && S_ISREG(st.st_mode)
2057 #if defined(__BEOS__) || defined(__HAIKU__)
2058  && (st.st_dev > 3)
2059 #endif
2060  )
2061  {
2062  if (io_fflush(fptr) < 0)
2063  rb_sys_fail(0);
2064  pos = lseek(fptr->fd, 0, SEEK_CUR);
2065  if (st.st_size >= pos && pos >= 0) {
2066  siz += st.st_size - pos;
2067  if (siz > LONG_MAX) {
2068  rb_raise(rb_eIOError, "file too big for single read");
2069  }
2070  }
2071  }
2072  else {
2073  siz += BUFSIZ;
2074  }
2075  return (long)siz;
2076 }
2077 
2078 static VALUE
2080 {
2081  OBJ_TAINT(str);
2082  rb_enc_associate(str, io_read_encoding(fptr));
2083  return str;
2084 }
2085 
2086 static void
2088 {
2089  if (!fptr->readconv) {
2090  int ecflags;
2091  VALUE ecopts;
2092  const char *sname, *dname;
2093  ecflags = fptr->encs.ecflags & ~ECONV_NEWLINE_DECORATOR_WRITE_MASK;
2094  ecopts = fptr->encs.ecopts;
2095  if (fptr->encs.enc2) {
2096  sname = rb_enc_name(fptr->encs.enc2);
2097  dname = rb_enc_name(fptr->encs.enc);
2098  }
2099  else {
2100  sname = dname = "";
2101  }
2102  fptr->readconv = rb_econv_open_opts(sname, dname, ecflags, ecopts);
2103  if (!fptr->readconv)
2104  rb_exc_raise(rb_econv_open_exc(sname, dname, ecflags));
2105  fptr->cbuf.off = 0;
2106  fptr->cbuf.len = 0;
2107  if (size < IO_CBUF_CAPA_MIN) size = IO_CBUF_CAPA_MIN;
2108  fptr->cbuf.capa = size;
2109  fptr->cbuf.ptr = ALLOC_N(char, fptr->cbuf.capa);
2110  }
2111 }
2112 
2113 #define MORE_CHAR_SUSPENDED Qtrue
2114 #define MORE_CHAR_FINISHED Qnil
2115 static VALUE
2116 fill_cbuf(rb_io_t *fptr, int ec_flags)
2117 {
2118  const unsigned char *ss, *sp, *se;
2119  unsigned char *ds, *dp, *de;
2120  rb_econv_result_t res;
2121  int putbackable;
2122  int cbuf_len0;
2123  VALUE exc;
2124 
2125  ec_flags |= ECONV_PARTIAL_INPUT;
2126 
2127  if (fptr->cbuf.len == fptr->cbuf.capa)
2128  return MORE_CHAR_SUSPENDED; /* cbuf full */
2129  if (fptr->cbuf.len == 0)
2130  fptr->cbuf.off = 0;
2131  else if (fptr->cbuf.off + fptr->cbuf.len == fptr->cbuf.capa) {
2132  memmove(fptr->cbuf.ptr, fptr->cbuf.ptr+fptr->cbuf.off, fptr->cbuf.len);
2133  fptr->cbuf.off = 0;
2134  }
2135 
2136  cbuf_len0 = fptr->cbuf.len;
2137 
2138  while (1) {
2139  ss = sp = (const unsigned char *)fptr->rbuf.ptr + fptr->rbuf.off;
2140  se = sp + fptr->rbuf.len;
2141  ds = dp = (unsigned char *)fptr->cbuf.ptr + fptr->cbuf.off + fptr->cbuf.len;
2142  de = (unsigned char *)fptr->cbuf.ptr + fptr->cbuf.capa;
2143  res = rb_econv_convert(fptr->readconv, &sp, se, &dp, de, ec_flags);
2144  fptr->rbuf.off += (int)(sp - ss);
2145  fptr->rbuf.len -= (int)(sp - ss);
2146  fptr->cbuf.len += (int)(dp - ds);
2147 
2148  putbackable = rb_econv_putbackable(fptr->readconv);
2149  if (putbackable) {
2150  rb_econv_putback(fptr->readconv, (unsigned char *)fptr->rbuf.ptr + fptr->rbuf.off - putbackable, putbackable);
2151  fptr->rbuf.off -= putbackable;
2152  fptr->rbuf.len += putbackable;
2153  }
2154 
2155  exc = rb_econv_make_exception(fptr->readconv);
2156  if (!NIL_P(exc))
2157  return exc;
2158 
2159  if (cbuf_len0 != fptr->cbuf.len)
2160  return MORE_CHAR_SUSPENDED;
2161 
2162  if (res == econv_finished) {
2163  return MORE_CHAR_FINISHED;
2164  }
2165 
2166  if (res == econv_source_buffer_empty) {
2167  if (fptr->rbuf.len == 0) {
2168  READ_CHECK(fptr);
2169  if (io_fillbuf(fptr) == -1) {
2170  if (!fptr->readconv) {
2171  return MORE_CHAR_FINISHED;
2172  }
2173  ds = dp = (unsigned char *)fptr->cbuf.ptr + fptr->cbuf.off + fptr->cbuf.len;
2174  de = (unsigned char *)fptr->cbuf.ptr + fptr->cbuf.capa;
2175  res = rb_econv_convert(fptr->readconv, NULL, NULL, &dp, de, 0);
2176  fptr->cbuf.len += (int)(dp - ds);
2178  break;
2179  }
2180  }
2181  }
2182  }
2183  if (cbuf_len0 != fptr->cbuf.len)
2184  return MORE_CHAR_SUSPENDED;
2185 
2186  return MORE_CHAR_FINISHED;
2187 }
2188 
2189 static VALUE
2191 {
2192  VALUE v;
2193  v = fill_cbuf(fptr, ECONV_AFTER_OUTPUT);
2194  if (v != MORE_CHAR_SUSPENDED && v != MORE_CHAR_FINISHED)
2195  rb_exc_raise(v);
2196  return v;
2197 }
2198 
2199 static VALUE
2200 io_shift_cbuf(rb_io_t *fptr, int len, VALUE *strp)
2201 {
2202  VALUE str = Qnil;
2203  if (strp) {
2204  str = *strp;
2205  if (NIL_P(str)) {
2206  *strp = str = rb_str_new(fptr->cbuf.ptr+fptr->cbuf.off, len);
2207  }
2208  else {
2209  rb_str_cat(str, fptr->cbuf.ptr+fptr->cbuf.off, len);
2210  }
2211  OBJ_TAINT(str);
2212  rb_enc_associate(str, fptr->encs.enc);
2213  }
2214  fptr->cbuf.off += len;
2215  fptr->cbuf.len -= len;
2216  /* xxx: set coderange */
2217  if (fptr->cbuf.len == 0)
2218  fptr->cbuf.off = 0;
2219  else if (fptr->cbuf.capa/2 < fptr->cbuf.off) {
2220  memmove(fptr->cbuf.ptr, fptr->cbuf.ptr+fptr->cbuf.off, fptr->cbuf.len);
2221  fptr->cbuf.off = 0;
2222  }
2223  return str;
2224 }
2225 
2226 static void
2227 io_setstrbuf(VALUE *str, long len)
2228 {
2229 #ifdef _WIN32
2230  len = (len + 1) & ~1L; /* round up for wide char */
2231 #endif
2232  if (NIL_P(*str)) {
2233  *str = rb_str_new(0, 0);
2234  }
2235  else {
2236  VALUE s = StringValue(*str);
2237  long clen = RSTRING_LEN(s);
2238  if (clen >= len) {
2239  if (clen != len) {
2240  rb_str_modify(s);
2241  rb_str_set_len(s, len);
2242  }
2243  return;
2244  }
2245  len -= clen;
2246  }
2247  rb_str_modify_expand(*str, len);
2248 }
2249 
2250 static void
2252 {
2253  if (RSTRING_LEN(str) != n) {
2254  rb_str_modify(str);
2255  rb_str_set_len(str, n);
2256  }
2257 }
2258 
2259 static VALUE
2260 read_all(rb_io_t *fptr, long siz, VALUE str)
2261 {
2262  long bytes;
2263  long n;
2264  long pos;
2265  rb_encoding *enc;
2266  int cr;
2267 
2268  if (NEED_READCONV(fptr)) {
2269  SET_BINARY_MODE(fptr);
2270  io_setstrbuf(&str,0);
2271  make_readconv(fptr, 0);
2272  while (1) {
2273  VALUE v;
2274  if (fptr->cbuf.len) {
2275  io_shift_cbuf(fptr, fptr->cbuf.len, &str);
2276  }
2277  v = fill_cbuf(fptr, 0);
2278  if (v != MORE_CHAR_SUSPENDED && v != MORE_CHAR_FINISHED) {
2279  if (fptr->cbuf.len) {
2280  io_shift_cbuf(fptr, fptr->cbuf.len, &str);
2281  }
2282  rb_exc_raise(v);
2283  }
2284  if (v == MORE_CHAR_FINISHED) {
2285  clear_readconv(fptr);
2286  return io_enc_str(str, fptr);
2287  }
2288  }
2289  }
2290 
2292  bytes = 0;
2293  pos = 0;
2294 
2295  enc = io_read_encoding(fptr);
2296  cr = 0;
2297 
2298  if (siz == 0) siz = BUFSIZ;
2299  io_setstrbuf(&str,siz);
2300  for (;;) {
2301  READ_CHECK(fptr);
2302  n = io_fread(str, bytes, siz - bytes, fptr);
2303  if (n == 0 && bytes == 0) {
2304  rb_str_set_len(str, 0);
2305  break;
2306  }
2307  bytes += n;
2308  rb_str_set_len(str, bytes);
2309  if (cr != ENC_CODERANGE_BROKEN)
2310  pos += rb_str_coderange_scan_restartable(RSTRING_PTR(str) + pos, RSTRING_PTR(str) + bytes, enc, &cr);
2311  if (bytes < siz) break;
2312  siz += BUFSIZ;
2313  rb_str_modify_expand(str, BUFSIZ);
2314  }
2315  str = io_enc_str(str, fptr);
2316  ENC_CODERANGE_SET(str, cr);
2317  return str;
2318 }
2319 
2320 void
2322 {
2323  int oflags;
2324 #ifdef F_GETFL
2325  oflags = fcntl(fptr->fd, F_GETFL);
2326  if (oflags == -1) {
2327  rb_sys_fail_path(fptr->pathv);
2328  }
2329 #else
2330  oflags = 0;
2331 #endif
2332  if ((oflags & O_NONBLOCK) == 0) {
2333  oflags |= O_NONBLOCK;
2334  if (fcntl(fptr->fd, F_SETFL, oflags) == -1) {
2335  rb_sys_fail_path(fptr->pathv);
2336  }
2337  }
2338 }
2339 
2340 static VALUE
2341 io_getpartial(int argc, VALUE *argv, VALUE io, int nonblock)
2342 {
2343  rb_io_t *fptr;
2344  VALUE length, str;
2345  long n, len;
2346 
2347  rb_scan_args(argc, argv, "11", &length, &str);
2348 
2349  if ((len = NUM2LONG(length)) < 0) {
2350  rb_raise(rb_eArgError, "negative length %ld given", len);
2351  }
2352 
2353  io_setstrbuf(&str,len);
2354  OBJ_TAINT(str);
2355 
2356  GetOpenFile(io, fptr);
2358 
2359  if (len == 0)
2360  return str;
2361 
2362  if (!nonblock)
2363  READ_CHECK(fptr);
2364  n = read_buffered_data(RSTRING_PTR(str), len, fptr);
2365  if (n <= 0) {
2366  again:
2367  if (nonblock) {
2368  rb_io_set_nonblock(fptr);
2369  }
2370  io_setstrbuf(&str, len);
2371  rb_str_locktmp(str);
2372  n = rb_read_internal(fptr->fd, RSTRING_PTR(str), len);
2373  rb_str_unlocktmp(str);
2374  if (n < 0) {
2375  if (!nonblock && rb_io_wait_readable(fptr->fd))
2376  goto again;
2377  if (nonblock && (errno == EWOULDBLOCK || errno == EAGAIN))
2378  rb_mod_sys_fail(rb_mWaitReadable, "read would block");
2379  rb_sys_fail_path(fptr->pathv);
2380  }
2381  }
2382  io_set_read_length(str, n);
2383 
2384  if (n == 0)
2385  return Qnil;
2386  else
2387  return str;
2388 }
2389 
2390 /*
2391  * call-seq:
2392  * ios.readpartial(maxlen) -> string
2393  * ios.readpartial(maxlen, outbuf) -> outbuf
2394  *
2395  * Reads at most <i>maxlen</i> bytes from the I/O stream.
2396  * It blocks only if <em>ios</em> has no data immediately available.
2397  * It doesn't block if some data available.
2398  * If the optional <i>outbuf</i> argument is present,
2399  * it must reference a String, which will receive the data.
2400  * The <i>outbuf</i> will contain only the received data after the method call
2401  * even if it is not empty at the beginning.
2402  * It raises <code>EOFError</code> on end of file.
2403  *
2404  * readpartial is designed for streams such as pipe, socket, tty, etc.
2405  * It blocks only when no data immediately available.
2406  * This means that it blocks only when following all conditions hold.
2407  * * the byte buffer in the IO object is empty.
2408  * * the content of the stream is empty.
2409  * * the stream is not reached to EOF.
2410  *
2411  * When readpartial blocks, it waits data or EOF on the stream.
2412  * If some data is reached, readpartial returns with the data.
2413  * If EOF is reached, readpartial raises EOFError.
2414  *
2415  * When readpartial doesn't blocks, it returns or raises immediately.
2416  * If the byte buffer is not empty, it returns the data in the buffer.
2417  * Otherwise if the stream has some content,
2418  * it returns the data in the stream.
2419  * Otherwise if the stream is reached to EOF, it raises EOFError.
2420  *
2421  * r, w = IO.pipe # buffer pipe content
2422  * w << "abc" # "" "abc".
2423  * r.readpartial(4096) #=> "abc" "" ""
2424  * r.readpartial(4096) # blocks because buffer and pipe is empty.
2425  *
2426  * r, w = IO.pipe # buffer pipe content
2427  * w << "abc" # "" "abc"
2428  * w.close # "" "abc" EOF
2429  * r.readpartial(4096) #=> "abc" "" EOF
2430  * r.readpartial(4096) # raises EOFError
2431  *
2432  * r, w = IO.pipe # buffer pipe content
2433  * w << "abc\ndef\n" # "" "abc\ndef\n"
2434  * r.gets #=> "abc\n" "def\n" ""
2435  * w << "ghi\n" # "def\n" "ghi\n"
2436  * r.readpartial(4096) #=> "def\n" "" "ghi\n"
2437  * r.readpartial(4096) #=> "ghi\n" "" ""
2438  *
2439  * Note that readpartial behaves similar to sysread.
2440  * The differences are:
2441  * * If the byte buffer is not empty, read from the byte buffer instead of "sysread for buffered IO (IOError)".
2442  * * It doesn't cause Errno::EWOULDBLOCK and Errno::EINTR. When readpartial meets EWOULDBLOCK and EINTR by read system call, readpartial retry the system call.
2443  *
2444  * The later means that readpartial is nonblocking-flag insensitive.
2445  * It blocks on the situation IO#sysread causes Errno::EWOULDBLOCK as if the fd is blocking mode.
2446  *
2447  */
2448 
2449 static VALUE
2451 {
2452  VALUE ret;
2453 
2454  ret = io_getpartial(argc, argv, io, 0);
2455  if (NIL_P(ret))
2456  rb_eof_error();
2457  return ret;
2458 }
2459 
2460 /*
2461  * call-seq:
2462  * ios.read_nonblock(maxlen) -> string
2463  * ios.read_nonblock(maxlen, outbuf) -> outbuf
2464  *
2465  * Reads at most <i>maxlen</i> bytes from <em>ios</em> using
2466  * the read(2) system call after O_NONBLOCK is set for
2467  * the underlying file descriptor.
2468  *
2469  * If the optional <i>outbuf</i> argument is present,
2470  * it must reference a String, which will receive the data.
2471  * The <i>outbuf</i> will contain only the received data after the method call
2472  * even if it is not empty at the beginning.
2473  *
2474  * read_nonblock just calls the read(2) system call.
2475  * It causes all errors the read(2) system call causes: Errno::EWOULDBLOCK, Errno::EINTR, etc.
2476  * The caller should care such errors.
2477  *
2478  * If the exception is Errno::EWOULDBLOCK or Errno::AGAIN,
2479  * it is extended by IO::WaitReadable.
2480  * So IO::WaitReadable can be used to rescue the exceptions for retrying read_nonblock.
2481  *
2482  * read_nonblock causes EOFError on EOF.
2483  *
2484  * If the read byte buffer is not empty,
2485  * read_nonblock reads from the buffer like readpartial.
2486  * In this case, the read(2) system call is not called.
2487  *
2488  * When read_nonblock raises an exception kind of IO::WaitReadable,
2489  * read_nonblock should not be called
2490  * until io is readable for avoiding busy loop.
2491  * This can be done as follows.
2492  *
2493  * # emulates blocking read (readpartial).
2494  * begin
2495  * result = io.read_nonblock(maxlen)
2496  * rescue IO::WaitReadable
2497  * IO.select([io])
2498  * retry
2499  * end
2500  *
2501  * Although IO#read_nonblock doesn't raise IO::WaitWritable.
2502  * OpenSSL::Buffering#read_nonblock can raise IO::WaitWritable.
2503  * If IO and SSL should be used polymorphically,
2504  * IO::WaitWritable should be rescued too.
2505  * See the document of OpenSSL::Buffering#read_nonblock for sample code.
2506  *
2507  * Note that this method is identical to readpartial
2508  * except the non-blocking flag is set.
2509  */
2510 
2511 static VALUE
2513 {
2514  VALUE ret;
2515 
2516  ret = io_getpartial(argc, argv, io, 1);
2517  if (NIL_P(ret))
2518  rb_eof_error();
2519  return ret;
2520 }
2521 
2522 /*
2523  * call-seq:
2524  * ios.write_nonblock(string) -> integer
2525  *
2526  * Writes the given string to <em>ios</em> using
2527  * the write(2) system call after O_NONBLOCK is set for
2528  * the underlying file descriptor.
2529  *
2530  * It returns the number of bytes written.
2531  *
2532  * write_nonblock just calls the write(2) system call.
2533  * It causes all errors the write(2) system call causes: Errno::EWOULDBLOCK, Errno::EINTR, etc.
2534  * The result may also be smaller than string.length (partial write).
2535  * The caller should care such errors and partial write.
2536  *
2537  * If the exception is Errno::EWOULDBLOCK or Errno::AGAIN,
2538  * it is extended by IO::WaitWritable.
2539  * So IO::WaitWritable can be used to rescue the exceptions for retrying write_nonblock.
2540  *
2541  * # Creates a pipe.
2542  * r, w = IO.pipe
2543  *
2544  * # write_nonblock writes only 65536 bytes and return 65536.
2545  * # (The pipe size is 65536 bytes on this environment.)
2546  * s = "a" * 100000
2547  * p w.write_nonblock(s) #=> 65536
2548  *
2549  * # write_nonblock cannot write a byte and raise EWOULDBLOCK (EAGAIN).
2550  * p w.write_nonblock("b") # Resource temporarily unavailable (Errno::EAGAIN)
2551  *
2552  * If the write buffer is not empty, it is flushed at first.
2553  *
2554  * When write_nonblock raises an exception kind of IO::WaitWritable,
2555  * write_nonblock should not be called
2556  * until io is writable for avoiding busy loop.
2557  * This can be done as follows.
2558  *
2559  * begin
2560  * result = io.write_nonblock(string)
2561  * rescue IO::WaitWritable, Errno::EINTR
2562  * IO.select(nil, [io])
2563  * retry
2564  * end
2565  *
2566  * Note that this doesn't guarantee to write all data in string.
2567  * The length written is reported as result and it should be checked later.
2568  *
2569  * On some platforms such as Windows, write_nonblock is not supported
2570  * according to the kind of the IO object.
2571  * In such cases, write_nonblock raises <code>Errno::EBADF</code>.
2572  *
2573  */
2574 
2575 static VALUE
2577 {
2578  rb_io_t *fptr;
2579  long n;
2580 
2581  rb_secure(4);
2582  if (!RB_TYPE_P(str, T_STRING))
2583  str = rb_obj_as_string(str);
2584 
2585  io = GetWriteIO(io);
2586  GetOpenFile(io, fptr);
2587  rb_io_check_writable(fptr);
2588 
2589  if (io_fflush(fptr) < 0)
2590  rb_sys_fail(0);
2591 
2592  rb_io_set_nonblock(fptr);
2593  n = write(fptr->fd, RSTRING_PTR(str), RSTRING_LEN(str));
2594 
2595  if (n == -1) {
2596  if (errno == EWOULDBLOCK || errno == EAGAIN)
2597  rb_mod_sys_fail(rb_mWaitWritable, "write would block");
2598  rb_sys_fail_path(fptr->pathv);
2599  }
2600 
2601  return LONG2FIX(n);
2602 }
2603 
2604 /*
2605  * call-seq:
2606  * ios.read([length [, outbuf]]) -> string, outbuf, or nil
2607  *
2608  * Reads <i>length</i> bytes from the I/O stream.
2609  *
2610  * <i>length</i> must be a non-negative integer or <code>nil</code>.
2611  *
2612  * If <i>length</i> is a positive integer,
2613  * it try to read <i>length</i> bytes without any conversion (binary mode).
2614  * It returns <code>nil</code> or a string whose length is 1 to <i>length</i> bytes.
2615  * <code>nil</code> means it met EOF at beginning.
2616  * The 1 to <i>length</i>-1 bytes string means it met EOF after reading the result.
2617  * The <i>length</i> bytes string means it doesn't meet EOF.
2618  * The resulted string is always ASCII-8BIT encoding.
2619  *
2620  * If <i>length</i> is omitted or is <code>nil</code>,
2621  * it reads until EOF and the encoding conversion is applied.
2622  * It returns a string even if EOF is met at beginning.
2623  *
2624  * If <i>length</i> is zero, it returns <code>""</code>.
2625  *
2626  * If the optional <i>outbuf</i> argument is present, it must reference
2627  * a String, which will receive the data.
2628  * The <i>outbuf</i> will contain only the received data after the method call
2629  * even if it is not empty at the beginning.
2630  *
2631  * At end of file, it returns <code>nil</code> or <code>""</code>
2632  * depend on <i>length</i>.
2633  * <code><i>ios</i>.read()</code> and
2634  * <code><i>ios</i>.read(nil)</code> returns <code>""</code>.
2635  * <code><i>ios</i>.read(<i>positive-integer</i>)</code> returns <code>nil</code>.
2636  *
2637  * f = File.new("testfile")
2638  * f.read(16) #=> "This is line one"
2639  *
2640  * # reads whole file
2641  * open("file") {|f|
2642  * data = f.read # This returns a string even if the file is empty.
2643  * ...
2644  * }
2645  *
2646  * # iterate over fixed length records.
2647  * open("fixed-record-file") {|f|
2648  * while record = f.read(256)
2649  * ...
2650  * end
2651  * }
2652  *
2653  * # iterate over variable length records.
2654  * # record is prefixed by 32-bit length.
2655  * open("variable-record-file") {|f|
2656  * while len = f.read(4)
2657  * len = len.unpack("N")[0] # 32-bit length
2658  * record = f.read(len) # This returns a string even if len is 0.
2659  * end
2660  * }
2661  *
2662  * Note that this method behaves like fread() function in C.
2663  * This means it retry to invoke read(2) system call to read data with the specified length (or until EOF).
2664  * This behavior is preserved even if <i>ios</i> is non-blocking mode.
2665  * (This method is non-blocking flag insensitive as other methods.)
2666  * If you need the behavior like single read(2) system call,
2667  * consider readpartial, read_nonblock and sysread.
2668  */
2669 
2670 static VALUE
2672 {
2673  rb_io_t *fptr;
2674  long n, len;
2675  VALUE length, str;
2676 #if defined(RUBY_TEST_CRLF_ENVIRONMENT) || defined(_WIN32)
2677  int previous_mode;
2678 #endif
2679 
2680  rb_scan_args(argc, argv, "02", &length, &str);
2681 
2682  if (NIL_P(length)) {
2683  GetOpenFile(io, fptr);
2685  return read_all(fptr, remain_size(fptr), str);
2686  }
2687  len = NUM2LONG(length);
2688  if (len < 0) {
2689  rb_raise(rb_eArgError, "negative length %ld given", len);
2690  }
2691 
2692  io_setstrbuf(&str,len);
2693 
2694  GetOpenFile(io, fptr);
2696  if (len == 0) return str;
2697 
2698  READ_CHECK(fptr);
2699 #if defined(RUBY_TEST_CRLF_ENVIRONMENT) || defined(_WIN32)
2700  previous_mode = set_binary_mode_with_seek_cur(fptr);
2701 #endif
2702  n = io_fread(str, 0, len, fptr);
2703  io_set_read_length(str, n);
2704 #if defined(RUBY_TEST_CRLF_ENVIRONMENT) || defined(_WIN32)
2705  if (previous_mode == O_TEXT) {
2706  setmode(fptr->fd, O_TEXT);
2707  }
2708 #endif
2709  if (n == 0) return Qnil;
2710  OBJ_TAINT(str);
2711 
2712  return str;
2713 }
2714 
2715 static void
2716 rscheck(const char *rsptr, long rslen, VALUE rs)
2717 {
2718  if (!rs) return;
2719  if (RSTRING_PTR(rs) != rsptr && RSTRING_LEN(rs) != rslen)
2720  rb_raise(rb_eRuntimeError, "rs modified");
2721 }
2722 
2723 static int
2724 appendline(rb_io_t *fptr, int delim, VALUE *strp, long *lp)
2725 {
2726  VALUE str = *strp;
2727  long limit = *lp;
2728 
2729  if (NEED_READCONV(fptr)) {
2730  SET_BINARY_MODE(fptr);
2731  make_readconv(fptr, 0);
2732  do {
2733  const char *p, *e;
2734  int searchlen;
2735  if (fptr->cbuf.len) {
2736  p = fptr->cbuf.ptr+fptr->cbuf.off;
2737  searchlen = fptr->cbuf.len;
2738  if (0 < limit && limit < searchlen)
2739  searchlen = (int)limit;
2740  e = memchr(p, delim, searchlen);
2741  if (e) {
2742  int len = (int)(e-p+1);
2743  if (NIL_P(str))
2744  *strp = str = rb_str_new(p, len);
2745  else
2746  rb_str_buf_cat(str, p, len);
2747  fptr->cbuf.off += len;
2748  fptr->cbuf.len -= len;
2749  limit -= len;
2750  *lp = limit;
2751  return delim;
2752  }
2753 
2754  if (NIL_P(str))
2755  *strp = str = rb_str_new(p, searchlen);
2756  else
2757  rb_str_buf_cat(str, p, searchlen);
2758  fptr->cbuf.off += searchlen;
2759  fptr->cbuf.len -= searchlen;
2760  limit -= searchlen;
2761 
2762  if (limit == 0) {
2763  *lp = limit;
2764  return (unsigned char)RSTRING_PTR(str)[RSTRING_LEN(str)-1];
2765  }
2766  }
2767  } while (more_char(fptr) != MORE_CHAR_FINISHED);
2768  clear_readconv(fptr);
2769  *lp = limit;
2770  return EOF;
2771  }
2772 
2774  do {
2775  long pending = READ_DATA_PENDING_COUNT(fptr);
2776  if (pending > 0) {
2777  const char *p = READ_DATA_PENDING_PTR(fptr);
2778  const char *e;
2779  long last;
2780 
2781  if (limit > 0 && pending > limit) pending = limit;
2782  e = memchr(p, delim, pending);
2783  if (e) pending = e - p + 1;
2784  if (!NIL_P(str)) {
2785  last = RSTRING_LEN(str);
2786  rb_str_resize(str, last + pending);
2787  }
2788  else {
2789  last = 0;
2790  *strp = str = rb_str_buf_new(pending);
2791  rb_str_set_len(str, pending);
2792  }
2793  read_buffered_data(RSTRING_PTR(str) + last, pending, fptr); /* must not fail */
2794  limit -= pending;
2795  *lp = limit;
2796  if (e) return delim;
2797  if (limit == 0)
2798  return (unsigned char)RSTRING_PTR(str)[RSTRING_LEN(str)-1];
2799  }
2800  READ_CHECK(fptr);
2801  } while (io_fillbuf(fptr) >= 0);
2802  *lp = limit;
2803  return EOF;
2804 }
2805 
2806 static inline int
2807 swallow(rb_io_t *fptr, int term)
2808 {
2809  if (NEED_READCONV(fptr)) {
2810  rb_encoding *enc = io_read_encoding(fptr);
2811  int needconv = rb_enc_mbminlen(enc) != 1;
2812  SET_BINARY_MODE(fptr);
2813  make_readconv(fptr, 0);
2814  do {
2815  size_t cnt;
2816  while ((cnt = READ_CHAR_PENDING_COUNT(fptr)) > 0) {
2817  const char *p = READ_CHAR_PENDING_PTR(fptr);
2818  int i;
2819  if (!needconv) {
2820  if (*p != term) return TRUE;
2821  i = (int)cnt;
2822  while (--i && *++p == term);
2823  }
2824  else {
2825  const char *e = p + cnt;
2826  if (rb_enc_ascget(p, e, &i, enc) != term) return TRUE;
2827  while ((p += i) < e && rb_enc_ascget(p, e, &i, enc) == term);
2828  i = (int)(e - p);
2829  }
2830  io_shift_cbuf(fptr, (int)cnt - i, NULL);
2831  }
2832  } while (more_char(fptr) != MORE_CHAR_FINISHED);
2833  return FALSE;
2834  }
2835 
2837  do {
2838  size_t cnt;
2839  while ((cnt = READ_DATA_PENDING_COUNT(fptr)) > 0) {
2840  char buf[1024];
2841  const char *p = READ_DATA_PENDING_PTR(fptr);
2842  int i;
2843  if (cnt > sizeof buf) cnt = sizeof buf;
2844  if (*p != term) return TRUE;
2845  i = (int)cnt;
2846  while (--i && *++p == term);
2847  if (!read_buffered_data(buf, cnt - i, fptr)) /* must not fail */
2848  rb_sys_fail_path(fptr->pathv);
2849  }
2850  READ_CHECK(fptr);
2851  } while (io_fillbuf(fptr) == 0);
2852  return FALSE;
2853 }
2854 
2855 static VALUE
2857 {
2858  VALUE str = Qnil;
2859  int len = 0;
2860  long pos = 0;
2861  int cr = 0;
2862 
2863  for (;;) {
2864  int pending = READ_DATA_PENDING_COUNT(fptr);
2865 
2866  if (pending > 0) {
2867  const char *p = READ_DATA_PENDING_PTR(fptr);
2868  const char *e;
2869 
2870  e = memchr(p, '\n', pending);
2871  if (e) {
2872  pending = (int)(e - p + 1);
2873  }
2874  if (NIL_P(str)) {
2875  str = rb_str_new(p, pending);
2876  fptr->rbuf.off += pending;
2877  fptr->rbuf.len -= pending;
2878  }
2879  else {
2880  rb_str_resize(str, len + pending);
2881  read_buffered_data(RSTRING_PTR(str)+len, pending, fptr);
2882  }
2883  len += pending;
2884  if (cr != ENC_CODERANGE_BROKEN)
2885  pos += rb_str_coderange_scan_restartable(RSTRING_PTR(str) + pos, RSTRING_PTR(str) + len, enc, &cr);
2886  if (e) break;
2887  }
2888  READ_CHECK(fptr);
2889  if (io_fillbuf(fptr) < 0) {
2890  if (NIL_P(str)) return Qnil;
2891  break;
2892  }
2893  }
2894 
2895  str = io_enc_str(str, fptr);
2896  ENC_CODERANGE_SET(str, cr);
2897  fptr->lineno++;
2898  if (io == ARGF.current_file) {
2899  ARGF.lineno++;
2900  ARGF.last_lineno = ARGF.lineno;
2901  }
2902  else {
2903  ARGF.last_lineno = fptr->lineno;
2904  }
2905 
2906  return str;
2907 }
2908 
2909 static void
2910 prepare_getline_args(int argc, VALUE *argv, VALUE *rsp, long *limit, VALUE io)
2911 {
2912  VALUE rs = rb_rs, lim = Qnil;
2913  rb_io_t *fptr;
2914 
2915  if (argc == 1) {
2916  VALUE tmp = Qnil;
2917 
2918  if (NIL_P(argv[0]) || !NIL_P(tmp = rb_check_string_type(argv[0]))) {
2919  rs = tmp;
2920  }
2921  else {
2922  lim = argv[0];
2923  }
2924  }
2925  else if (2 <= argc) {
2926  rb_scan_args(argc, argv, "2", &rs, &lim);
2927  if (!NIL_P(rs))
2928  StringValue(rs);
2929  }
2930  if (!NIL_P(rs)) {
2931  rb_encoding *enc_rs, *enc_io;
2932 
2933  GetOpenFile(io, fptr);
2934  enc_rs = rb_enc_get(rs);
2935  enc_io = io_read_encoding(fptr);
2936  if (enc_io != enc_rs &&
2938  (RSTRING_LEN(rs) > 0 && !rb_enc_asciicompat(enc_io)))) {
2939  if (rs == rb_default_rs) {
2940  rs = rb_enc_str_new(0, 0, enc_io);
2941  rb_str_buf_cat_ascii(rs, "\n");
2942  }
2943  else {
2944  rb_raise(rb_eArgError, "encoding mismatch: %s IO with %s RS",
2945  rb_enc_name(enc_io),
2946  rb_enc_name(enc_rs));
2947  }
2948  }
2949  }
2950  *rsp = rs;
2951  *limit = NIL_P(lim) ? -1L : NUM2LONG(lim);
2952 }
2953 
2954 static VALUE
2955 rb_io_getline_1(VALUE rs, long limit, VALUE io)
2956 {
2957  VALUE str = Qnil;
2958  rb_io_t *fptr;
2959  int nolimit = 0;
2960  rb_encoding *enc;
2961 
2962  GetOpenFile(io, fptr);
2964  if (NIL_P(rs) && limit < 0) {
2965  str = read_all(fptr, 0, Qnil);
2966  if (RSTRING_LEN(str) == 0) return Qnil;
2967  }
2968  else if (limit == 0) {
2969  return rb_enc_str_new(0, 0, io_read_encoding(fptr));
2970  }
2971  else if (rs == rb_default_rs && limit < 0 && !NEED_READCONV(fptr) &&
2972  rb_enc_asciicompat(enc = io_read_encoding(fptr))) {
2974  return rb_io_getline_fast(fptr, enc, io);
2975  }
2976  else {
2977  int c, newline = -1;
2978  const char *rsptr = 0;
2979  long rslen = 0;
2980  int rspara = 0;
2981  int extra_limit = 16;
2982 
2983  SET_BINARY_MODE(fptr);
2984  enc = io_read_encoding(fptr);
2985 
2986  if (!NIL_P(rs)) {
2987  rslen = RSTRING_LEN(rs);
2988  if (rslen == 0) {
2989  rsptr = "\n\n";
2990  rslen = 2;
2991  rspara = 1;
2992  swallow(fptr, '\n');
2993  rs = 0;
2994  if (!rb_enc_asciicompat(enc)) {
2995  rs = rb_usascii_str_new(rsptr, rslen);
2996  rs = rb_str_encode(rs, rb_enc_from_encoding(enc), 0, Qnil);
2997  OBJ_FREEZE(rs);
2998  rsptr = RSTRING_PTR(rs);
2999  rslen = RSTRING_LEN(rs);
3000  }
3001  }
3002  else {
3003  rsptr = RSTRING_PTR(rs);
3004  }
3005  newline = (unsigned char)rsptr[rslen - 1];
3006  }
3007 
3008  /* MS - Optimisation */
3009  while ((c = appendline(fptr, newline, &str, &limit)) != EOF) {
3010  const char *s, *p, *pp, *e;
3011 
3012  if (c == newline) {
3013  if (RSTRING_LEN(str) < rslen) continue;
3014  s = RSTRING_PTR(str);
3015  e = s + RSTRING_LEN(str);
3016  p = e - rslen;
3017  pp = rb_enc_left_char_head(s, p, e, enc);
3018  if (pp != p) continue;
3019  if (!rspara) rscheck(rsptr, rslen, rs);
3020  if (memcmp(p, rsptr, rslen) == 0) break;
3021  }
3022  if (limit == 0) {
3023  s = RSTRING_PTR(str);
3024  p = s + RSTRING_LEN(str);
3025  pp = rb_enc_left_char_head(s, p-1, p, enc);
3026  if (extra_limit &&
3028  /* relax the limit while incomplete character.
3029  * extra_limit limits the relax length */
3030  limit = 1;
3031  extra_limit--;
3032  }
3033  else {
3034  nolimit = 1;
3035  break;
3036  }
3037  }
3038  }
3039 
3040  if (rspara) {
3041  if (c != EOF) {
3042  swallow(fptr, '\n');
3043  }
3044  }
3045  if (!NIL_P(str))
3046  str = io_enc_str(str, fptr);
3047  }
3048 
3049  if (!NIL_P(str)) {
3050  if (!nolimit) {
3051  fptr->lineno++;
3052  if (io == ARGF.current_file) {
3053  ARGF.lineno++;
3054  ARGF.last_lineno = ARGF.lineno;
3055  }
3056  else {
3057  ARGF.last_lineno = fptr->lineno;
3058  }
3059  }
3060  }
3061 
3062  return str;
3063 }
3064 
3065 static VALUE
3067 {
3068  VALUE rs;
3069  long limit;
3070 
3071  prepare_getline_args(argc, argv, &rs, &limit, io);
3072  return rb_io_getline_1(rs, limit, io);
3073 }
3074 
3075 VALUE
3077 {
3078  return rb_io_getline_1(rb_default_rs, -1, io);
3079 }
3080 
3081 /*
3082  * call-seq:
3083  * ios.gets(sep=$/) -> string or nil
3084  * ios.gets(limit) -> string or nil
3085  * ios.gets(sep, limit) -> string or nil
3086  *
3087  * Reads the next ``line'' from the I/O stream; lines are separated by
3088  * <i>sep</i>. A separator of <code>nil</code> reads the entire
3089  * contents, and a zero-length separator reads the input a paragraph at
3090  * a time (two successive newlines in the input separate paragraphs).
3091  * The stream must be opened for reading or an <code>IOError</code>
3092  * will be raised. The line read in will be returned and also assigned
3093  * to <code>$_</code>. Returns <code>nil</code> if called at end of
3094  * file. If the first argument is an integer, or optional second
3095  * argument is given, the returning string would not be longer than the
3096  * given value in bytes.
3097  *
3098  * File.new("testfile").gets #=> "This is line one\n"
3099  * $_ #=> "This is line one\n"
3100  */
3101 
3102 static VALUE
3104 {
3105  VALUE str;
3106 
3107  str = rb_io_getline(argc, argv, io);
3108  rb_lastline_set(str);
3109 
3110  return str;
3111 }
3112 
3113 /*
3114  * call-seq:
3115  * ios.lineno -> integer
3116  *
3117  * Returns the current line number in <em>ios</em>. The stream must be
3118  * opened for reading. <code>lineno</code> counts the number of times
3119  * #gets is called rather than the number of newlines encountered. The two
3120  * values will differ if #gets is called with a separator other than newline.
3121  *
3122  * Methods that use <code>$/</code> like #each, #lines and #readline will
3123  * also increment <code>lineno</code>.
3124  *
3125  * See also the <code>$.</code> variable.
3126  *
3127  * f = File.new("testfile")
3128  * f.lineno #=> 0
3129  * f.gets #=> "This is line one\n"
3130  * f.lineno #=> 1
3131  * f.gets #=> "This is line two\n"
3132  * f.lineno #=> 2
3133  */
3134 
3135 static VALUE
3137 {
3138  rb_io_t *fptr;
3139 
3140  GetOpenFile(io, fptr);
3142  return INT2NUM(fptr->lineno);
3143 }
3144 
3145 /*
3146  * call-seq:
3147  * ios.lineno = integer -> integer
3148  *
3149  * Manually sets the current line number to the given value.
3150  * <code>$.</code> is updated only on the next read.
3151  *
3152  * f = File.new("testfile")
3153  * f.gets #=> "This is line one\n"
3154  * $. #=> 1
3155  * f.lineno = 1000
3156  * f.lineno #=> 1000
3157  * $. #=> 1 # lineno of last read
3158  * f.gets #=> "This is line two\n"
3159  * $. #=> 1001 # lineno of last read
3160  */
3161 
3162 static VALUE
3164 {
3165  rb_io_t *fptr;
3166 
3167  GetOpenFile(io, fptr);
3169  fptr->lineno = NUM2INT(lineno);
3170  return lineno;
3171 }
3172 
3173 /*
3174  * call-seq:
3175  * ios.readline(sep=$/) -> string
3176  * ios.readline(limit) -> string
3177  * ios.readline(sep, limit) -> string
3178  *
3179  * Reads a line as with <code>IO#gets</code>, but raises an
3180  * <code>EOFError</code> on end of file.
3181  */
3182 
3183 static VALUE
3185 {
3186  VALUE line = rb_io_gets_m(argc, argv, io);
3187 
3188  if (NIL_P(line)) {
3189  rb_eof_error();
3190  }
3191  return line;
3192 }
3193 
3194 /*
3195  * call-seq:
3196  * ios.readlines(sep=$/) -> array
3197  * ios.readlines(limit) -> array
3198  * ios.readlines(sep, limit) -> array
3199  *
3200  * Reads all of the lines in <em>ios</em>, and returns them in
3201  * <i>anArray</i>. Lines are separated by the optional <i>sep</i>. If
3202  * <i>sep</i> is <code>nil</code>, the rest of the stream is returned
3203  * as a single record. If the first argument is an integer, or
3204  * optional second argument is given, the returning string would not be
3205  * longer than the given value in bytes. The stream must be opened for
3206  * reading or an <code>IOError</code> will be raised.
3207  *
3208  * f = File.new("testfile")
3209  * f.readlines[0] #=> "This is line one\n"
3210  */
3211 
3212 static VALUE
3214 {
3215  VALUE line, ary, rs;
3216  long limit;
3217 
3218  prepare_getline_args(argc, argv, &rs, &limit, io);
3219  if (limit == 0)
3220  rb_raise(rb_eArgError, "invalid limit: 0 for readlines");
3221  ary = rb_ary_new();
3222  while (!NIL_P(line = rb_io_getline_1(rs, limit, io))) {
3223  rb_ary_push(ary, line);
3224  }
3225  return ary;
3226 }
3227 
3228 /*
3229  * call-seq:
3230  * ios.each(sep=$/) {|line| block } -> ios
3231  * ios.each(limit) {|line| block } -> ios
3232  * ios.each(sep,limit) {|line| block } -> ios
3233  * ios.each(...) -> an_enumerator
3234  *
3235  * ios.each_line(sep=$/) {|line| block } -> ios
3236  * ios.each_line(limit) {|line| block } -> ios
3237  * ios.each_line(sep,limit) {|line| block } -> ios
3238  * ios.each_line(...) -> an_enumerator
3239  *
3240  * Executes the block for every line in <em>ios</em>, where lines are
3241  * separated by <i>sep</i>. <em>ios</em> must be opened for
3242  * reading or an <code>IOError</code> will be raised.
3243  *
3244  * If no block is given, an enumerator is returned instead.
3245  *
3246  * f = File.new("testfile")
3247  * f.each {|line| puts "#{f.lineno}: #{line}" }
3248  *
3249  * <em>produces:</em>
3250  *
3251  * 1: This is line one
3252  * 2: This is line two
3253  * 3: This is line three
3254  * 4: And so on...
3255  */
3256 
3257 static VALUE
3259 {
3260  VALUE str, rs;
3261  long limit;
3262 
3263  RETURN_ENUMERATOR(io, argc, argv);
3264  prepare_getline_args(argc, argv, &rs, &limit, io);
3265  if (limit == 0)
3266  rb_raise(rb_eArgError, "invalid limit: 0 for each_line");
3267  while (!NIL_P(str = rb_io_getline_1(rs, limit, io))) {
3268  rb_yield(str);
3269  }
3270  return io;
3271 }
3272 
3273 /*
3274  * This is a deprecated alias for <code>each_line</code>.
3275  */
3276 
3277 static VALUE
3279 {
3280  rb_warn("IO#lines is deprecated; use #each_line instead");
3281  if (!rb_block_given_p())
3282  return rb_enumeratorize(io, ID2SYM(rb_intern("each_line")), argc, argv);
3283  return rb_io_each_line(argc, argv, io);
3284 }
3285 
3286 /*
3287  * call-seq:
3288  * ios.each_byte {|byte| block } -> ios
3289  * ios.each_byte -> an_enumerator
3290  *
3291  * Calls the given block once for each byte (0..255) in <em>ios</em>,
3292  * passing the byte as an argument. The stream must be opened for
3293  * reading or an <code>IOError</code> will be raised.
3294  *
3295  * If no block is given, an enumerator is returned instead.
3296  *
3297  * f = File.new("testfile")
3298  * checksum = 0
3299  * f.each_byte {|x| checksum ^= x } #=> #<File:testfile>
3300  * checksum #=> 12
3301  */
3302 
3303 static VALUE
3305 {
3306  rb_io_t *fptr;
3307 
3308  RETURN_ENUMERATOR(io, 0, 0);
3309  GetOpenFile(io, fptr);
3310 
3311  for (;;) {
3312  while (fptr->rbuf.len > 0) {
3313  char *p = fptr->rbuf.ptr + fptr->rbuf.off++;
3314  fptr->rbuf.len--;
3315  rb_yield(INT2FIX(*p & 0xff));
3316  errno = 0;
3317  }
3319  READ_CHECK(fptr);
3320  if (io_fillbuf(fptr) < 0) {
3321  break;
3322  }
3323  }
3324  return io;
3325 }
3326 
3327 /*
3328  * This is a deprecated alias for <code>each_byte</code>.
3329  */
3330 
3331 static VALUE
3333 {
3334  rb_warn("IO#bytes is deprecated; use #each_byte instead");
3335  if (!rb_block_given_p())
3336  return rb_enumeratorize(io, ID2SYM(rb_intern("each_byte")), 0, 0);
3337  return rb_io_each_byte(io);
3338 }
3339 
3340 static VALUE
3342 {
3343  int r, n, cr = 0;
3344  VALUE str;
3345 
3346  if (NEED_READCONV(fptr)) {
3347  VALUE str = Qnil;
3348  rb_encoding *read_enc = io_read_encoding(fptr);
3349 
3350  SET_BINARY_MODE(fptr);
3351  make_readconv(fptr, 0);
3352 
3353  while (1) {
3354  if (fptr->cbuf.len) {
3355  r = rb_enc_precise_mbclen(fptr->cbuf.ptr+fptr->cbuf.off,
3356  fptr->cbuf.ptr+fptr->cbuf.off+fptr->cbuf.len,
3357  read_enc);
3358  if (!MBCLEN_NEEDMORE_P(r))
3359  break;
3360  if (fptr->cbuf.len == fptr->cbuf.capa) {
3361  rb_raise(rb_eIOError, "too long character");
3362  }
3363  }
3364 
3365  if (more_char(fptr) == MORE_CHAR_FINISHED) {
3366  if (fptr->cbuf.len == 0) {
3367  clear_readconv(fptr);
3368  return Qnil;
3369  }
3370  /* return an unit of an incomplete character just before EOF */
3371  str = rb_enc_str_new(fptr->cbuf.ptr+fptr->cbuf.off, 1, read_enc);
3372  fptr->cbuf.off += 1;
3373  fptr->cbuf.len -= 1;
3374  if (fptr->cbuf.len == 0) clear_readconv(fptr);
3376  return str;
3377  }
3378  }
3379  if (MBCLEN_INVALID_P(r)) {
3380  r = rb_enc_mbclen(fptr->cbuf.ptr+fptr->cbuf.off,
3381  fptr->cbuf.ptr+fptr->cbuf.off+fptr->cbuf.len,
3382  read_enc);
3383  io_shift_cbuf(fptr, r, &str);
3384  cr = ENC_CODERANGE_BROKEN;
3385  }
3386  else {
3387  io_shift_cbuf(fptr, MBCLEN_CHARFOUND_LEN(r), &str);
3389  }
3390  str = io_enc_str(str, fptr);
3391  ENC_CODERANGE_SET(str, cr);
3392  return str;
3393  }
3394 
3396  if (io_fillbuf(fptr) < 0) {
3397  return Qnil;
3398  }
3399  if (rb_enc_asciicompat(enc) && ISASCII(fptr->rbuf.ptr[fptr->rbuf.off])) {
3400  str = rb_str_new(fptr->rbuf.ptr+fptr->rbuf.off, 1);
3401  fptr->rbuf.off += 1;
3402  fptr->rbuf.len -= 1;
3403  cr = ENC_CODERANGE_7BIT;
3404  }
3405  else {
3406  r = rb_enc_precise_mbclen(fptr->rbuf.ptr+fptr->rbuf.off, fptr->rbuf.ptr+fptr->rbuf.off+fptr->rbuf.len, enc);
3407  if (MBCLEN_CHARFOUND_P(r) &&
3408  (n = MBCLEN_CHARFOUND_LEN(r)) <= fptr->rbuf.len) {
3409  str = rb_str_new(fptr->rbuf.ptr+fptr->rbuf.off, n);
3410  fptr->rbuf.off += n;
3411  fptr->rbuf.len -= n;
3412  cr = ENC_CODERANGE_VALID;
3413  }
3414  else if (MBCLEN_NEEDMORE_P(r)) {
3415  str = rb_str_new(fptr->rbuf.ptr+fptr->rbuf.off, fptr->rbuf.len);
3416  fptr->rbuf.len = 0;
3417  getc_needmore:
3418  if (io_fillbuf(fptr) != -1) {
3419  rb_str_cat(str, fptr->rbuf.ptr+fptr->rbuf.off, 1);
3420  fptr->rbuf.off++;
3421  fptr->rbuf.len--;
3422  r = rb_enc_precise_mbclen(RSTRING_PTR(str), RSTRING_PTR(str)+RSTRING_LEN(str), enc);
3423  if (MBCLEN_NEEDMORE_P(r)) {
3424  goto getc_needmore;
3425  }
3426  else if (MBCLEN_CHARFOUND_P(r)) {
3427  cr = ENC_CODERANGE_VALID;
3428  }
3429  }
3430  }
3431  else {
3432  str = rb_str_new(fptr->rbuf.ptr+fptr->rbuf.off, 1);
3433  fptr->rbuf.off++;
3434  fptr->rbuf.len--;
3435  }
3436  }
3437  if (!cr) cr = ENC_CODERANGE_BROKEN;
3438  str = io_enc_str(str, fptr);
3439  ENC_CODERANGE_SET(str, cr);
3440  return str;
3441 }
3442 
3443 /*
3444  * call-seq:
3445  * ios.each_char {|c| block } -> ios
3446  * ios.each_char -> an_enumerator
3447  *
3448  * Calls the given block once for each character in <em>ios</em>,
3449  * passing the character as an argument. The stream must be opened for
3450  * reading or an <code>IOError</code> will be raised.
3451  *
3452  * If no block is given, an enumerator is returned instead.
3453  *
3454  * f = File.new("testfile")
3455  * f.each_char {|c| print c, ' ' } #=> #<File:testfile>
3456  */
3457 
3458 static VALUE
3460 {
3461  rb_io_t *fptr;
3462  rb_encoding *enc;
3463  VALUE c;
3464 
3465  RETURN_ENUMERATOR(io, 0, 0);
3466  GetOpenFile(io, fptr);
3468 
3469  enc = io_input_encoding(fptr);
3470  READ_CHECK(fptr);
3471  while (!NIL_P(c = io_getc(fptr, enc))) {
3472  rb_yield(c);
3473  }
3474  return io;
3475 }
3476 
3477 /*
3478  * This is a deprecated alias for <code>each_char</code>.
3479  */
3480 
3481 static VALUE
3483 {
3484  rb_warn("IO#chars is deprecated; use #each_char instead");
3485  if (!rb_block_given_p())
3486  return rb_enumeratorize(io, ID2SYM(rb_intern("each_char")), 0, 0);
3487  return rb_io_each_char(io);
3488 }
3489 
3490 
3491 /*
3492  * call-seq:
3493  * ios.each_codepoint {|c| block } -> ios
3494  * ios.codepoints {|c| block } -> ios
3495  * ios.each_codepoint -> an_enumerator
3496  * ios.codepoints -> an_enumerator
3497  *
3498  * Passes the <code>Integer</code> ordinal of each character in <i>ios</i>,
3499  * passing the codepoint as an argument. The stream must be opened for
3500  * reading or an <code>IOError</code> will be raised.
3501  *
3502  * If no block is given, an enumerator is returned instead.
3503  *
3504  */
3505 
3506 static VALUE
3508 {
3509  rb_io_t *fptr;
3510  rb_encoding *enc;
3511  unsigned int c;
3512  int r, n;
3513 
3514  RETURN_ENUMERATOR(io, 0, 0);
3515  GetOpenFile(io, fptr);
3517 
3518  READ_CHECK(fptr);
3519  if (NEED_READCONV(fptr)) {
3520  SET_BINARY_MODE(fptr);
3521  for (;;) {
3522  make_readconv(fptr, 0);
3523  for (;;) {
3524  if (fptr->cbuf.len) {
3525  if (fptr->encs.enc)
3526  r = rb_enc_precise_mbclen(fptr->cbuf.ptr+fptr->cbuf.off,
3527  fptr->cbuf.ptr+fptr->cbuf.off+fptr->cbuf.len,
3528  fptr->encs.enc);
3529  else
3531  if (!MBCLEN_NEEDMORE_P(r))
3532  break;
3533  if (fptr->cbuf.len == fptr->cbuf.capa) {
3534  rb_raise(rb_eIOError, "too long character");
3535  }
3536  }
3537  if (more_char(fptr) == MORE_CHAR_FINISHED) {
3538  clear_readconv(fptr);
3539  /* ignore an incomplete character before EOF */
3540  return io;
3541  }
3542  }
3543  if (MBCLEN_INVALID_P(r)) {
3544  rb_raise(rb_eArgError, "invalid byte sequence in %s",
3545  rb_enc_name(fptr->encs.enc));
3546  }
3547  n = MBCLEN_CHARFOUND_LEN(r);
3548  if (fptr->encs.enc) {
3549  c = rb_enc_codepoint(fptr->cbuf.ptr+fptr->cbuf.off,
3550  fptr->cbuf.ptr+fptr->cbuf.off+fptr->cbuf.len,
3551  fptr->encs.enc);
3552  }
3553  else {
3554  c = (unsigned char)fptr->cbuf.ptr[fptr->cbuf.off];
3555  }
3556  fptr->cbuf.off += n;
3557  fptr->cbuf.len -= n;
3558  rb_yield(UINT2NUM(c));
3559  }
3560  }
3562  enc = io_input_encoding(fptr);
3563  for (;;) {
3564  if (io_fillbuf(fptr) < 0) {
3565  return io;
3566  }
3567  r = rb_enc_precise_mbclen(fptr->rbuf.ptr+fptr->rbuf.off,
3568  fptr->rbuf.ptr+fptr->rbuf.off+fptr->rbuf.len, enc);
3569  if (MBCLEN_CHARFOUND_P(r) &&
3570  (n = MBCLEN_CHARFOUND_LEN(r)) <= fptr->rbuf.len) {
3571  c = rb_enc_codepoint(fptr->rbuf.ptr+fptr->rbuf.off,
3572  fptr->rbuf.ptr+fptr->rbuf.off+fptr->rbuf.len, enc);
3573  fptr->rbuf.off += n;
3574  fptr->rbuf.len -= n;
3575  rb_yield(UINT2NUM(c));
3576  }
3577  else if (MBCLEN_INVALID_P(r)) {
3578  rb_raise(rb_eArgError, "invalid byte sequence in %s", rb_enc_name(enc));
3579  }
3580  else {
3581  continue;
3582  }
3583  }
3584  return io;
3585 }
3586 
3587 /*
3588  * This is a deprecated alias for <code>each_codepoint</code>.
3589  */
3590 
3591 static VALUE
3593 {
3594  rb_warn("IO#codepoints is deprecated; use #each_codepoint instead");
3595  if (!rb_block_given_p())
3596  return rb_enumeratorize(io, ID2SYM(rb_intern("each_codepoint")), 0, 0);
3597  return rb_io_each_codepoint(io);
3598 }
3599 
3600 
3601 /*
3602  * call-seq:
3603  * ios.getc -> string or nil
3604  *
3605  * Reads a one-character string from <em>ios</em>. Returns
3606  * <code>nil</code> if called at end of file.
3607  *
3608  * f = File.new("testfile")
3609  * f.getc #=> "h"
3610  * f.getc #=> "e"
3611  */
3612 
3613 static VALUE
3615 {
3616  rb_io_t *fptr;
3617  rb_encoding *enc;
3618 
3619  GetOpenFile(io, fptr);
3621 
3622  enc = io_input_encoding(fptr);
3623  READ_CHECK(fptr);
3624  return io_getc(fptr, enc);
3625 }
3626 
3627 /*
3628  * call-seq:
3629  * ios.readchar -> string
3630  *
3631  * Reads a one-character string from <em>ios</em>. Raises an
3632  * <code>EOFError</code> on end of file.
3633  *
3634  * f = File.new("testfile")
3635  * f.readchar #=> "h"
3636  * f.readchar #=> "e"
3637  */
3638 
3639 static VALUE
3641 {
3642  VALUE c = rb_io_getc(io);
3643 
3644  if (NIL_P(c)) {
3645  rb_eof_error();
3646  }
3647  return c;
3648 }
3649 
3650 /*
3651  * call-seq:
3652  * ios.getbyte -> fixnum or nil
3653  *
3654  * Gets the next 8-bit byte (0..255) from <em>ios</em>. Returns
3655  * <code>nil</code> if called at end of file.
3656  *
3657  * f = File.new("testfile")
3658  * f.getbyte #=> 84
3659  * f.getbyte #=> 104
3660  */
3661 
3662 VALUE
3664 {
3665  rb_io_t *fptr;
3666  int c;
3667 
3668  GetOpenFile(io, fptr);
3670  READ_CHECK(fptr);
3671  if (fptr->fd == 0 && (fptr->mode & FMODE_TTY) && RB_TYPE_P(rb_stdout, T_FILE)) {
3672  rb_io_t *ofp;
3673  GetOpenFile(rb_stdout, ofp);
3674  if (ofp->mode & FMODE_TTY) {
3676  }
3677  }
3678  if (io_fillbuf(fptr) < 0) {
3679  return Qnil;
3680  }
3681  fptr->rbuf.off++;
3682  fptr->rbuf.len--;
3683  c = (unsigned char)fptr->rbuf.ptr[fptr->rbuf.off-1];
3684  return INT2FIX(c & 0xff);
3685 }
3686 
3687 /*
3688  * call-seq:
3689  * ios.readbyte -> fixnum
3690  *
3691  * Reads a byte as with <code>IO#getbyte</code>, but raises an
3692  * <code>EOFError</code> on end of file.
3693  */
3694 
3695 static VALUE
3697 {
3698  VALUE c = rb_io_getbyte(io);
3699 
3700  if (NIL_P(c)) {
3701  rb_eof_error();
3702  }
3703  return c;
3704 }
3705 
3706 /*
3707  * call-seq:
3708  * ios.ungetbyte(string) -> nil
3709  * ios.ungetbyte(integer) -> nil
3710  *
3711  * Pushes back bytes (passed as a parameter) onto <em>ios</em>,
3712  * such that a subsequent buffered read will return it. Only one byte
3713  * may be pushed back before a subsequent read operation (that is,
3714  * you will be able to read only the last of several bytes that have been pushed
3715  * back). Has no effect with unbuffered reads (such as <code>IO#sysread</code>).
3716  *
3717  * f = File.new("testfile") #=> #<File:testfile>
3718  * b = f.getbyte #=> 0x38
3719  * f.ungetbyte(b) #=> nil
3720  * f.getbyte #=> 0x38
3721  */
3722 
3723 VALUE
3725 {
3726  rb_io_t *fptr;
3727 
3728  GetOpenFile(io, fptr);
3730  if (NIL_P(b)) return Qnil;
3731  if (FIXNUM_P(b)) {
3732  char cc = FIX2INT(b);
3733  b = rb_str_new(&cc, 1);
3734  }
3735  else {
3736  SafeStringValue(b);
3737  }
3738  io_ungetbyte(b, fptr);
3739  return Qnil;
3740 }
3741 
3742 /*
3743  * call-seq:
3744  * ios.ungetc(string) -> nil
3745  *
3746  * Pushes back one character (passed as a parameter) onto <em>ios</em>,
3747  * such that a subsequent buffered character read will return it. Only one character
3748  * may be pushed back before a subsequent read operation (that is,
3749  * you will be able to read only the last of several characters that have been pushed
3750  * back). Has no effect with unbuffered reads (such as <code>IO#sysread</code>).
3751  *
3752  * f = File.new("testfile") #=> #<File:testfile>
3753  * c = f.getc #=> "8"
3754  * f.ungetc(c) #=> nil
3755  * f.getc #=> "8"
3756  */
3757 
3758 VALUE
3760 {
3761  rb_io_t *fptr;
3762  long len;
3763 
3764  GetOpenFile(io, fptr);
3766  if (NIL_P(c)) return Qnil;
3767  if (FIXNUM_P(c)) {
3768  c = rb_enc_uint_chr(FIX2UINT(c), io_read_encoding(fptr));
3769  }
3770  else if (RB_TYPE_P(c, T_BIGNUM)) {
3771  c = rb_enc_uint_chr(NUM2UINT(c), io_read_encoding(fptr));
3772  }
3773  else {
3774  SafeStringValue(c);
3775  }
3776  if (NEED_READCONV(fptr)) {
3777  SET_BINARY_MODE(fptr);
3778  len = RSTRING_LEN(c);
3779 #if SIZEOF_LONG > SIZEOF_INT
3780  if (len > INT_MAX)
3781  rb_raise(rb_eIOError, "ungetc failed");
3782 #endif
3783  make_readconv(fptr, (int)len);
3784  if (fptr->cbuf.capa - fptr->cbuf.len < len)
3785  rb_raise(rb_eIOError, "ungetc failed");
3786  if (fptr->cbuf.off < len) {
3787  MEMMOVE(fptr->cbuf.ptr+fptr->cbuf.capa-fptr->cbuf.len,
3788  fptr->cbuf.ptr+fptr->cbuf.off,
3789  char, fptr->cbuf.len);
3790  fptr->cbuf.off = fptr->cbuf.capa-fptr->cbuf.len;
3791  }
3792  fptr->cbuf.off -= (int)len;
3793  fptr->cbuf.len += (int)len;
3794  MEMMOVE(fptr->cbuf.ptr+fptr->cbuf.off, RSTRING_PTR(c), char, len);
3795  }
3796  else {
3798  io_ungetbyte(c, fptr);
3799  }
3800  return Qnil;
3801 }
3802 
3803 /*
3804  * call-seq:
3805  * ios.isatty -> true or false
3806  * ios.tty? -> true or false
3807  *
3808  * Returns <code>true</code> if <em>ios</em> is associated with a
3809  * terminal device (tty), <code>false</code> otherwise.
3810  *
3811  * File.new("testfile").isatty #=> false
3812  * File.new("/dev/tty").isatty #=> true
3813  */
3814 
3815 static VALUE
3817 {
3818  rb_io_t *fptr;
3819 
3820  GetOpenFile(io, fptr);
3821  if (isatty(fptr->fd) == 0)
3822  return Qfalse;
3823  return Qtrue;
3824 }
3825 
3826 #if defined(HAVE_FCNTL) && defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
3827 /*
3828  * call-seq:
3829  * ios.close_on_exec? -> true or false
3830  *
3831  * Returns <code>true</code> if <em>ios</em> will be closed on exec.
3832  *
3833  * f = open("/dev/null")
3834  * f.close_on_exec? #=> false
3835  * f.close_on_exec = true
3836  * f.close_on_exec? #=> true
3837  * f.close_on_exec = false
3838  * f.close_on_exec? #=> false
3839  */
3840 
3841 static VALUE
3843 {
3844  rb_io_t *fptr;
3845  VALUE write_io;
3846  int fd, ret;
3847 
3848  write_io = GetWriteIO(io);
3849  if (io != write_io) {
3850  GetOpenFile(write_io, fptr);
3851  if (fptr && 0 <= (fd = fptr->fd)) {
3852  if ((ret = fcntl(fd, F_GETFD)) == -1) rb_sys_fail_path(fptr->pathv);
3853  if (!(ret & FD_CLOEXEC)) return Qfalse;
3854  }
3855  }
3856 
3857  GetOpenFile(io, fptr);
3858  if (fptr && 0 <= (fd = fptr->fd)) {
3859  if ((ret = fcntl(fd, F_GETFD)) == -1) rb_sys_fail_path(fptr->pathv);
3860  if (!(ret & FD_CLOEXEC)) return Qfalse;
3861  }
3862  return Qtrue;
3863 }
3864 #else
3865 #define rb_io_close_on_exec_p rb_f_notimplement
3866 #endif
3867 
3868 #if defined(HAVE_FCNTL) && defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
3869 /*
3870  * call-seq:
3871  * ios.close_on_exec = bool -> true or false
3872  *
3873  * Sets a close-on-exec flag.
3874  *
3875  * f = open("/dev/null")
3876  * f.close_on_exec = true
3877  * system("cat", "/proc/self/fd/#{f.fileno}") # cat: /proc/self/fd/3: No such file or directory
3878  * f.closed? #=> false
3879  *
3880  * Ruby sets close-on-exec flags of all file descriptors by default
3881  * since Ruby 2.0.0.
3882  * So you don't need to set by yourself.
3883  * Also, unsetting a close-on-exec flag can cause file descriptor leak
3884  * if another thread use fork() and exec() (via system() method for example).
3885  * If you really needs file descriptor inheritance to child process,
3886  * use spawn()'s argument such as fd=>fd.
3887  */
3888 
3889 static VALUE
3891 {
3892  int flag = RTEST(arg) ? FD_CLOEXEC : 0;
3893  rb_io_t *fptr;
3894  VALUE write_io;
3895  int fd, ret;
3896 
3897  write_io = GetWriteIO(io);
3898  if (io != write_io) {
3899  GetOpenFile(write_io, fptr);
3900  if (fptr && 0 <= (fd = fptr->fd)) {
3901  if ((ret = fcntl(fptr->fd, F_GETFD)) == -1) rb_sys_fail_path(fptr->pathv);
3902  if ((ret & FD_CLOEXEC) != flag) {
3903  ret = (ret & ~FD_CLOEXEC) | flag;
3904  ret = fcntl(fd, F_SETFD, ret);
3905  if (ret == -1) rb_sys_fail_path(fptr->pathv);
3906  }
3907  }
3908 
3909  }
3910 
3911  GetOpenFile(io, fptr);
3912  if (fptr && 0 <= (fd = fptr->fd)) {
3913  if ((ret = fcntl(fd, F_GETFD)) == -1) rb_sys_fail_path(fptr->pathv);
3914  if ((ret & FD_CLOEXEC) != flag) {
3915  ret = (ret & ~FD_CLOEXEC) | flag;
3916  ret = fcntl(fd, F_SETFD, ret);
3917  if (ret == -1) rb_sys_fail_path(fptr->pathv);
3918  }
3919  }
3920  return Qnil;
3921 }
3922 #else
3923 #define rb_io_set_close_on_exec rb_f_notimplement
3924 #endif
3925 
3926 #define FMODE_PREP (1<<16)
3927 #define IS_PREP_STDIO(f) ((f)->mode & FMODE_PREP)
3928 #define PREP_STDIO_NAME(f) (RSTRING_PTR((f)->pathv))
3929 
3930 static VALUE
3931 finish_writeconv(rb_io_t *fptr, int noalloc)
3932 {
3933  unsigned char *ds, *dp, *de;
3934  rb_econv_result_t res;
3935 
3936  if (!fptr->wbuf.ptr) {
3937  unsigned char buf[1024];
3938  long r;
3939 
3941  while (res == econv_destination_buffer_full) {
3942  ds = dp = buf;
3943  de = buf + sizeof(buf);
3944  res = rb_econv_convert(fptr->writeconv, NULL, NULL, &dp, de, 0);
3945  while (dp-ds) {
3946  retry:
3947  if (fptr->write_lock && rb_mutex_owned_p(fptr->write_lock))
3948  r = rb_write_internal2(fptr->fd, ds, dp-ds);
3949  else
3950  r = rb_write_internal(fptr->fd, ds, dp-ds);
3951  if (r == dp-ds)
3952  break;
3953  if (0 <= r) {
3954  ds += r;
3955  }
3956  if (rb_io_wait_writable(fptr->fd)) {
3957  if (fptr->fd < 0)
3958  return noalloc ? Qtrue : rb_exc_new3(rb_eIOError, rb_str_new_cstr("closed stream"));
3959  goto retry;
3960  }
3961  return noalloc ? Qtrue : INT2NUM(errno);
3962  }
3963  if (res == econv_invalid_byte_sequence ||
3964  res == econv_incomplete_input ||
3965  res == econv_undefined_conversion) {
3966  return noalloc ? Qtrue : rb_econv_make_exception(fptr->writeconv);
3967  }
3968  }
3969 
3970  return Qnil;
3971  }
3972 
3974  while (res == econv_destination_buffer_full) {
3975  if (fptr->wbuf.len == fptr->wbuf.capa) {
3976  if (io_fflush(fptr) < 0)
3977  return noalloc ? Qtrue : INT2NUM(errno);
3978  }
3979 
3980  ds = dp = (unsigned char *)fptr->wbuf.ptr + fptr->wbuf.off + fptr->wbuf.len;
3981  de = (unsigned char *)fptr->wbuf.ptr + fptr->wbuf.capa;
3982  res = rb_econv_convert(fptr->writeconv, NULL, NULL, &dp, de, 0);
3983  fptr->wbuf.len += (int)(dp - ds);
3984  if (res == econv_invalid_byte_sequence ||
3985  res == econv_incomplete_input ||
3986  res == econv_undefined_conversion) {
3987  return noalloc ? Qtrue : rb_econv_make_exception(fptr->writeconv);
3988  }
3989  }
3990  return Qnil;
3991 }
3992 
3995  int noalloc;
3996 };
3997 
3998 static VALUE
4000 {
4001  struct finish_writeconv_arg *p = (struct finish_writeconv_arg *)arg;
4002  return finish_writeconv(p->fptr, p->noalloc);
4003 }
4004 
4005 static void*
4006 nogvl_close(void *ptr)
4007 {
4008  int *fd = ptr;
4009 
4010  return (void*)(intptr_t)close(*fd);
4011 }
4012 
4013 static int
4014 maygvl_close(int fd, int keepgvl)
4015 {
4016  if (keepgvl)
4017  return close(fd);
4018 
4019  /*
4020  * close() may block for certain file types (NFS, SO_LINGER sockets,
4021  * inotify), so let other threads run.
4022  */
4024 }
4025 
4026 static void*
4027 nogvl_fclose(void *ptr)
4028 {
4029  FILE *file = ptr;
4030 
4031  return (void*)(intptr_t)fclose(file);
4032 }
4033 
4034 static int
4035 maygvl_fclose(FILE *file, int keepgvl)
4036 {
4037  if (keepgvl)
4038  return fclose(file);
4039 
4041 }
4042 
4043 static void
4044 fptr_finalize(rb_io_t *fptr, int noraise)
4045 {
4046  VALUE err = Qnil;
4047  int fd = fptr->fd;
4048  FILE *stdio_file = fptr->stdio_file;
4049 
4050  if (fptr->writeconv) {
4051  if (fptr->write_lock && !noraise) {
4052  struct finish_writeconv_arg arg;
4053  arg.fptr = fptr;
4054  arg.noalloc = noraise;
4056  }
4057  else {
4058  err = finish_writeconv(fptr, noraise);
4059  }
4060  }
4061  if (fptr->wbuf.len) {
4062  if (noraise) {
4063  if ((int)io_flush_buffer_sync(fptr) < 0 && NIL_P(err))
4064  err = Qtrue;
4065  }
4066  else {
4067  if (io_fflush(fptr) < 0 && NIL_P(err))
4068  err = INT2NUM(errno);
4069  }
4070  }
4071 
4072  fptr->fd = -1;
4073  fptr->stdio_file = 0;
4074  fptr->mode &= ~(FMODE_READABLE|FMODE_WRITABLE);
4075 
4076  if (IS_PREP_STDIO(fptr) || fd <= 2) {
4077  /* need to keep FILE objects of stdin, stdout and stderr */
4078  }
4079  else if (stdio_file) {
4080  /* stdio_file is deallocated anyway
4081  * even if fclose failed. */
4082  if ((maygvl_fclose(stdio_file, noraise) < 0) && NIL_P(err))
4083  err = noraise ? Qtrue : INT2NUM(errno);
4084  }
4085  else if (0 <= fd) {
4086  /* fptr->fd may be closed even if close fails.
4087  * POSIX doesn't specify it.
4088  * We assumes it is closed. */
4089  if ((maygvl_close(fd, noraise) < 0) && NIL_P(err))
4090  err = noraise ? Qtrue : INT2NUM(errno);
4091  }
4092 
4093  if (!NIL_P(err) && !noraise) {
4094  switch (TYPE(err)) {
4095  case T_FIXNUM:
4096  case T_BIGNUM:
4097  errno = NUM2INT(err);
4098  rb_sys_fail_path(fptr->pathv);
4099 
4100  default:
4101  rb_exc_raise(err);
4102  }
4103  }
4104 }
4105 
4106 static void
4107 rb_io_fptr_cleanup(rb_io_t *fptr, int noraise)
4108 {
4109  if (fptr->finalize) {
4110  (*fptr->finalize)(fptr, noraise);
4111  }
4112  else {
4113  fptr_finalize(fptr, noraise);
4114  }
4115 }
4116 
4117 static void
4119 {
4120  if (fptr->readconv) {
4121  rb_econv_close(fptr->readconv);
4122  fptr->readconv = NULL;
4123  }
4124  if (fptr->cbuf.ptr) {
4125  free(fptr->cbuf.ptr);
4126  fptr->cbuf.ptr = NULL;
4127  }
4128 }
4129 
4130 static void
4132 {
4133  if (fptr->writeconv) {
4134  rb_econv_close(fptr->writeconv);
4135  fptr->writeconv = NULL;
4136  }
4137  fptr->writeconv_initialized = 0;
4138 }
4139 
4140 static void
4142 {
4143  clear_readconv(fptr);
4144  clear_writeconv(fptr);
4145 }
4146 
4147 int
4149 {
4150  if (!fptr) return 0;
4151  fptr->pathv = Qnil;
4152  if (0 <= fptr->fd)
4153  rb_io_fptr_cleanup(fptr, TRUE);
4154  fptr->write_lock = 0;
4155  if (fptr->rbuf.ptr) {
4156  free(fptr->rbuf.ptr);
4157  fptr->rbuf.ptr = 0;
4158  }
4159  if (fptr->wbuf.ptr) {
4160  free(fptr->wbuf.ptr);
4161  fptr->wbuf.ptr = 0;
4162  }
4163  clear_codeconv(fptr);
4164  free(fptr);
4165  return 1;
4166 }
4167 
4168 size_t rb_econv_memsize(rb_econv_t *);
4169 
4170 RUBY_FUNC_EXPORTED size_t
4172 {
4173  size_t size = sizeof(rb_io_t);
4174  size += fptr->rbuf.capa;
4175  size += fptr->wbuf.capa;
4176  size += fptr->cbuf.capa;
4177  if (fptr->readconv) size += rb_econv_memsize(fptr->readconv);
4178  if (fptr->writeconv) size += rb_econv_memsize(fptr->writeconv);
4179  return size;
4180 }
4181 
4182 VALUE
4184 {
4185  rb_io_t *fptr;
4186  int fd;
4187  VALUE write_io;
4188  rb_io_t *write_fptr;
4189 
4190  write_io = GetWriteIO(io);
4191  if (io != write_io) {
4192  write_fptr = RFILE(write_io)->fptr;
4193  if (write_fptr && 0 <= write_fptr->fd) {
4194  rb_io_fptr_cleanup(write_fptr, TRUE);
4195  }
4196  }
4197 
4198  fptr = RFILE(io)->fptr;
4199  if (!fptr) return Qnil;
4200  if (fptr->fd < 0) return Qnil;
4201 
4202  fd = fptr->fd;
4203  rb_thread_fd_close(fd);
4204  rb_io_fptr_cleanup(fptr, FALSE);
4205 
4206  if (fptr->pid) {
4208  rb_syswait(fptr->pid);
4209  fptr->pid = 0;
4210  }
4211 
4212  return Qnil;
4213 }
4214 
4215 /*
4216  * call-seq:
4217  * ios.close -> nil
4218  *
4219  * Closes <em>ios</em> and flushes any pending writes to the operating
4220  * system. The stream is unavailable for any further data operations;
4221  * an <code>IOError</code> is raised if such an attempt is made. I/O
4222  * streams are automatically closed when they are claimed by the
4223  * garbage collector.
4224  *
4225  * If <em>ios</em> is opened by <code>IO.popen</code>,
4226  * <code>close</code> sets <code>$?</code>.
4227  */
4228 
4229 static VALUE
4231 {
4232  if (rb_safe_level() >= 4 && !OBJ_UNTRUSTED(io)) {
4233  rb_raise(rb_eSecurityError, "Insecure: can't close");
4234  }
4235  rb_io_check_closed(RFILE(io)->fptr);
4236  rb_io_close(io);
4237  return Qnil;
4238 }
4239 
4240 static VALUE
4242 {
4243  return rb_funcall(io, rb_intern("close"), 0, 0);
4244 }
4245 
4246 static VALUE
4248 {
4249  return rb_rescue(io_call_close, io, 0, 0);
4250 }
4251 
4252 /*
4253  * call-seq:
4254  * ios.closed? -> true or false
4255  *
4256  * Returns <code>true</code> if <em>ios</em> is completely closed (for
4257  * duplex streams, both reader and writer), <code>false</code>
4258  * otherwise.
4259  *
4260  * f = File.new("testfile")
4261  * f.close #=> nil
4262  * f.closed? #=> true
4263  * f = IO.popen("/bin/sh","r+")
4264  * f.close_write #=> nil
4265  * f.closed? #=> false
4266  * f.close_read #=> nil
4267  * f.closed? #=> true
4268  */
4269 
4270 
4271 static VALUE
4273 {
4274  rb_io_t *fptr;
4275  VALUE write_io;
4276  rb_io_t *write_fptr;
4277 
4278  write_io = GetWriteIO(io);
4279  if (io != write_io) {
4280  write_fptr = RFILE(write_io)->fptr;
4281  if (write_fptr && 0 <= write_fptr->fd) {
4282  return Qfalse;
4283  }
4284  }
4285 
4286  fptr = RFILE(io)->fptr;
4288  return 0 <= fptr->fd ? Qfalse : Qtrue;
4289 }
4290 
4291 /*
4292  * call-seq:
4293  * ios.close_read -> nil
4294  *
4295  * Closes the read end of a duplex I/O stream (i.e., one that contains
4296  * both a read and a write stream, such as a pipe). Will raise an
4297  * <code>IOError</code> if the stream is not duplexed.
4298  *
4299  * f = IO.popen("/bin/sh","r+")
4300  * f.close_read
4301  * f.readlines
4302  *
4303  * <em>produces:</em>
4304  *
4305  * prog.rb:3:in `readlines': not opened for reading (IOError)
4306  * from prog.rb:3
4307  */
4308 
4309 static VALUE
4311 {
4312  rb_io_t *fptr;
4313  VALUE write_io;
4314 
4315  if (rb_safe_level() >= 4 && !OBJ_UNTRUSTED(io)) {
4316  rb_raise(rb_eSecurityError, "Insecure: can't close");
4317  }
4318  GetOpenFile(io, fptr);
4319  if (is_socket(fptr->fd, fptr->pathv)) {
4320 #ifndef SHUT_RD
4321 # define SHUT_RD 0
4322 #endif
4323  if (shutdown(fptr->fd, SHUT_RD) < 0)
4324  rb_sys_fail_path(fptr->pathv);
4325  fptr->mode &= ~FMODE_READABLE;
4326  if (!(fptr->mode & FMODE_WRITABLE))
4327  return rb_io_close(io);
4328  return Qnil;
4329  }
4330 
4331  write_io = GetWriteIO(io);
4332  if (io != write_io) {
4333  rb_io_t *wfptr;
4334  rb_io_fptr_cleanup(fptr, FALSE);
4335  GetOpenFile(write_io, wfptr);
4336  RFILE(io)->fptr = wfptr;
4337  RFILE(write_io)->fptr = NULL;
4338  rb_io_fptr_finalize(fptr);
4339  return Qnil;
4340  }
4341 
4342  if (fptr->mode & FMODE_WRITABLE) {
4343  rb_raise(rb_eIOError, "closing non-duplex IO for reading");
4344  }
4345  return rb_io_close(io);
4346 }
4347 
4348 /*
4349  * call-seq:
4350  * ios.close_write -> nil
4351  *
4352  * Closes the write end of a duplex I/O stream (i.e., one that contains
4353  * both a read and a write stream, such as a pipe). Will raise an
4354  * <code>IOError</code> if the stream is not duplexed.
4355  *
4356  * f = IO.popen("/bin/sh","r+")
4357  * f.close_write
4358  * f.print "nowhere"
4359  *
4360  * <em>produces:</em>
4361  *
4362  * prog.rb:3:in `write': not opened for writing (IOError)
4363  * from prog.rb:3:in `print'
4364  * from prog.rb:3
4365  */
4366 
4367 static VALUE
4369 {
4370  rb_io_t *fptr;
4371  VALUE write_io;
4372 
4373  if (rb_safe_level() >= 4 && !OBJ_UNTRUSTED(io)) {
4374  rb_raise(rb_eSecurityError, "Insecure: can't close");
4375  }
4376  write_io = GetWriteIO(io);
4377  GetOpenFile(write_io, fptr);
4378  if (is_socket(fptr->fd, fptr->pathv)) {
4379 #ifndef SHUT_WR
4380 # define SHUT_WR 1
4381 #endif
4382  if (shutdown(fptr->fd, SHUT_WR) < 0)
4383  rb_sys_fail_path(fptr->pathv);
4384  fptr->mode &= ~FMODE_WRITABLE;
4385  if (!(fptr->mode & FMODE_READABLE))
4386  return rb_io_close(write_io);
4387  return Qnil;
4388  }
4389 
4390  if (fptr->mode & FMODE_READABLE) {
4391  rb_raise(rb_eIOError, "closing non-duplex IO for writing");
4392  }
4393 
4394  rb_io_close(write_io);
4395  if (io != write_io) {
4396  GetOpenFile(io, fptr);
4397  fptr->tied_io_for_writing = 0;
4398  fptr->mode &= ~FMODE_DUPLEX;
4399  }
4400  return Qnil;
4401 }
4402 
4403 /*
4404  * call-seq:
4405  * ios.sysseek(offset, whence=IO::SEEK_SET) -> integer
4406  *
4407  * Seeks to a given <i>offset</i> in the stream according to the value
4408  * of <i>whence</i> (see <code>IO#seek</code> for values of
4409  * <i>whence</i>). Returns the new offset into the file.
4410  *
4411  * f = File.new("testfile")
4412  * f.sysseek(-13, IO::SEEK_END) #=> 53
4413  * f.sysread(10) #=> "And so on."
4414  */
4415 
4416 static VALUE
4418 {
4419  VALUE offset, ptrname;
4420  int whence = SEEK_SET;
4421  rb_io_t *fptr;
4422  off_t pos;
4423 
4424  if (rb_scan_args(argc, argv, "11", &offset, &ptrname) == 2) {
4425  whence = NUM2INT(ptrname);
4426  }
4427  pos = NUM2OFFT(offset);
4428  GetOpenFile(io, fptr);
4429  if ((fptr->mode & FMODE_READABLE) &&
4430  (READ_DATA_BUFFERED(fptr) || READ_CHAR_PENDING(fptr))) {
4431  rb_raise(rb_eIOError, "sysseek for buffered IO");
4432  }
4433  if ((fptr->mode & FMODE_WRITABLE) && fptr->wbuf.len) {
4434  rb_warn("sysseek for buffered IO");
4435  }
4436  errno = 0;
4437  pos = lseek(fptr->fd, pos, whence);
4438  if (pos == -1 && errno) rb_sys_fail_path(fptr->pathv);
4439 
4440  return OFFT2NUM(pos);
4441 }
4442 
4443 /*
4444  * call-seq:
4445  * ios.syswrite(string) -> integer
4446  *
4447  * Writes the given string to <em>ios</em> using a low-level write.
4448  * Returns the number of bytes written. Do not mix with other methods
4449  * that write to <em>ios</em> or you may get unpredictable results.
4450  * Raises <code>SystemCallError</code> on error.
4451  *
4452  * f = File.new("out", "w")
4453  * f.syswrite("ABCDEF") #=> 6
4454  */
4455 
4456 static VALUE
4458 {
4459  rb_io_t *fptr;
4460  long n;
4461 
4462  rb_secure(4);
4463  if (!RB_TYPE_P(str, T_STRING))
4464  str = rb_obj_as_string(str);
4465 
4466  io = GetWriteIO(io);
4467  GetOpenFile(io, fptr);
4468  rb_io_check_writable(fptr);
4469 
4470  str = rb_str_new_frozen(str);
4471 
4472  if (fptr->wbuf.len) {
4473  rb_warn("syswrite for buffered IO");
4474  }
4475 
4476  n = rb_write_internal(fptr->fd, RSTRING_PTR(str), RSTRING_LEN(str));
4477 
4478  if (n == -1) rb_sys_fail_path(fptr->pathv);
4479 
4480  return LONG2FIX(n);
4481 }
4482 
4483 /*
4484  * call-seq:
4485  * ios.sysread(maxlen[, outbuf]) -> string
4486  *
4487  * Reads <i>maxlen</i> bytes from <em>ios</em> using a low-level
4488  * read and returns them as a string. Do not mix with other methods
4489  * that read from <em>ios</em> or you may get unpredictable results.
4490  * If the optional <i>outbuf</i> argument is present, it must reference
4491  * a String, which will receive the data.
4492  * The <i>outbuf</i> will contain only the received data after the method call
4493  * even if it is not empty at the beginning.
4494  * Raises <code>SystemCallError</code> on error and
4495  * <code>EOFError</code> at end of file.
4496  *
4497  * f = File.new("testfile")
4498  * f.sysread(16) #=> "This is line one"
4499  */
4500 
4501 static VALUE
4503 {
4504  VALUE len, str;
4505  rb_io_t *fptr;
4506  long n, ilen;
4507 
4508  rb_scan_args(argc, argv, "11", &len, &str);
4509  ilen = NUM2LONG(len);
4510 
4511  io_setstrbuf(&str,ilen);
4512  if (ilen == 0) return str;
4513 
4514  GetOpenFile(io, fptr);
4516 
4517  if (READ_DATA_BUFFERED(fptr)) {
4518  rb_raise(rb_eIOError, "sysread for buffered IO");
4519  }
4520 
4521  n = fptr->fd;
4522 
4523  /*
4524  * FIXME: removing rb_thread_wait_fd() here changes sysread semantics
4525  * on non-blocking IOs. However, it's still currently possible
4526  * for sysread to raise Errno::EAGAIN if another thread read()s
4527  * the IO after we return from rb_thread_wait_fd() but before
4528  * we call read()
4529  */
4530  rb_thread_wait_fd(fptr->fd);
4531 
4532  rb_io_check_closed(fptr);
4533 
4534  io_setstrbuf(&str, ilen);
4535  rb_str_locktmp(str);
4536  n = rb_read_internal(fptr->fd, RSTRING_PTR(str), ilen);
4537  rb_str_unlocktmp(str);
4538 
4539  if (n == -1) {
4540  rb_sys_fail_path(fptr->pathv);
4541  }
4542  io_set_read_length(str, n);
4543  if (n == 0 && ilen > 0) {
4544  rb_eof_error();
4545  }
4546  OBJ_TAINT(str);
4547 
4548  return str;
4549 }
4550 
4551 VALUE
4553 {
4554  rb_io_t *fptr;
4555 
4556  GetOpenFile(io, fptr);
4557  if (fptr->readconv)
4558  rb_econv_binmode(fptr->readconv);
4559  if (fptr->writeconv)
4560  rb_econv_binmode(fptr->writeconv);
4561  fptr->mode |= FMODE_BINMODE;
4562  fptr->mode &= ~FMODE_TEXTMODE;
4564 #ifdef O_BINARY
4565  if (!fptr->readconv) {
4567  }
4568  else {
4569  setmode(fptr->fd, O_BINARY);
4570  }
4571 #endif
4572  return io;
4573 }
4574 
4575 VALUE
4577 {
4578  rb_io_t *fptr;
4579 
4580  GetOpenFile(io, fptr);
4581  if (fptr->readconv) {
4582  rb_econv_close(fptr->readconv);
4583  fptr->readconv = NULL;
4584  }
4585  if (fptr->writeconv) {
4586  rb_econv_close(fptr->writeconv);
4587  fptr->writeconv = NULL;
4588  }
4589  fptr->mode |= FMODE_BINMODE;
4590  fptr->mode &= ~FMODE_TEXTMODE;
4592 
4593  fptr->encs.enc = rb_ascii8bit_encoding();
4594  fptr->encs.enc2 = NULL;
4595  fptr->encs.ecflags = 0;
4596  fptr->encs.ecopts = Qnil;
4597  clear_codeconv(fptr);
4598 
4599  return io;
4600 }
4601 
4602 /*
4603  * call-seq:
4604  * ios.binmode -> ios
4605  *
4606  * Puts <em>ios</em> into binary mode.
4607  * Once a stream is in binary mode, it cannot be reset to nonbinary mode.
4608  *
4609  * - newline conversion disabled
4610  * - encoding conversion disabled
4611  * - content is treated as ASCII-8BIT
4612  *
4613  */
4614 
4615 static VALUE
4617 {
4618  VALUE write_io;
4619 
4621 
4622  write_io = GetWriteIO(io);
4623  if (write_io != io)
4624  rb_io_ascii8bit_binmode(write_io);
4625  return io;
4626 }
4627 
4628 /*
4629  * call-seq:
4630  * ios.binmode? -> true or false
4631  *
4632  * Returns <code>true</code> if <em>ios</em> is binmode.
4633  */
4634 static VALUE
4636 {
4637  rb_io_t *fptr;
4638  GetOpenFile(io, fptr);
4639  return fptr->mode & FMODE_BINMODE ? Qtrue : Qfalse;
4640 }
4641 
4642 static const char*
4644 {
4645  if (fmode & FMODE_APPEND) {
4646  if ((fmode & FMODE_READWRITE) == FMODE_READWRITE) {
4647  return MODE_BTMODE("a+", "ab+", "at+");
4648  }
4649  return MODE_BTMODE("a", "ab", "at");
4650  }
4651  switch (fmode & FMODE_READWRITE) {
4652  default:
4653  rb_raise(rb_eArgError, "invalid access fmode 0x%x", fmode);
4654  case FMODE_READABLE:
4655  return MODE_BTMODE("r", "rb", "rt");
4656  case FMODE_WRITABLE:
4657  return MODE_BTMODE("w", "wb", "wt");
4658  case FMODE_READWRITE:
4659  if (fmode & FMODE_CREATE) {
4660  return MODE_BTMODE("w+", "wb+", "wt+");
4661  }
4662  return MODE_BTMODE("r+", "rb+", "rt+");
4663  }
4664 }
4665 
4666 static int
4667 io_encname_bom_p(const char *name, long len)
4668 {
4669  static const char bom_prefix[] = "bom|utf-";
4670  enum {bom_prefix_len = (int)sizeof(bom_prefix) - 1};
4671  if (!len) {
4672  const char *p = strchr(name, ':');
4673  len = p ? (long)(p - name) : (long)strlen(name);
4674  }
4675  return len > bom_prefix_len && STRNCASECMP(name, bom_prefix, bom_prefix_len) == 0;
4676 }
4677 
4678 int
4679 rb_io_modestr_fmode(const char *modestr)
4680 {
4681  int fmode = 0;
4682  const char *m = modestr, *p = NULL;
4683 
4684  switch (*m++) {
4685  case 'r':
4686  fmode |= FMODE_READABLE;
4687  break;
4688  case 'w':
4690  break;
4691  case 'a':
4693  break;
4694  default:
4695  error:
4696  rb_raise(rb_eArgError, "invalid access mode %s", modestr);
4697  }
4698 
4699  while (*m) {
4700  switch (*m++) {
4701  case 'b':
4702  fmode |= FMODE_BINMODE;
4703  break;
4704  case 't':
4705  fmode |= FMODE_TEXTMODE;
4706  break;
4707  case '+':
4708  fmode |= FMODE_READWRITE;
4709  break;
4710  default:
4711  goto error;
4712  case ':':
4713  p = m;
4714  goto finished;
4715  }
4716  }
4717 
4718  finished:
4719  if ((fmode & FMODE_BINMODE) && (fmode & FMODE_TEXTMODE))
4720  goto error;
4721  if (p && io_encname_bom_p(p, 0))
4722  fmode |= FMODE_SETENC_BY_BOM;
4723 
4724  return fmode;
4725 }
4726 
4727 int
4729 {
4730  int fmode = 0;
4731 
4732  switch (oflags & (O_RDONLY|O_WRONLY|O_RDWR)) {
4733  case O_RDONLY:
4734  fmode = FMODE_READABLE;
4735  break;
4736  case O_WRONLY:
4737  fmode = FMODE_WRITABLE;
4738  break;
4739  case O_RDWR:
4740  fmode = FMODE_READWRITE;
4741  break;
4742  }
4743 
4744  if (oflags & O_APPEND) {
4745  fmode |= FMODE_APPEND;
4746  }
4747  if (oflags & O_TRUNC) {
4748  fmode |= FMODE_TRUNC;
4749  }
4750  if (oflags & O_CREAT) {
4751  fmode |= FMODE_CREATE;
4752  }
4753 #ifdef O_BINARY
4754  if (oflags & O_BINARY) {
4755  fmode |= FMODE_BINMODE;
4756  }
4757 #endif
4758 
4759  return fmode;
4760 }
4761 
4762 static int
4764 {
4765  int oflags = 0;
4766 
4767  switch (fmode & FMODE_READWRITE) {
4768  case FMODE_READABLE:
4769  oflags |= O_RDONLY;
4770  break;
4771  case FMODE_WRITABLE:
4772  oflags |= O_WRONLY;
4773  break;
4774  case FMODE_READWRITE:
4775  oflags |= O_RDWR;
4776  break;
4777  }
4778 
4779  if (fmode & FMODE_APPEND) {
4780  oflags |= O_APPEND;
4781  }
4782  if (fmode & FMODE_TRUNC) {
4783  oflags |= O_TRUNC;
4784  }
4785  if (fmode & FMODE_CREATE) {
4786  oflags |= O_CREAT;
4787  }
4788 #ifdef O_BINARY
4789  if (fmode & FMODE_BINMODE) {
4790  oflags |= O_BINARY;
4791  }
4792 #endif
4793 
4794  return oflags;
4795 }
4796 
4797 int
4798 rb_io_modestr_oflags(const char *modestr)
4799 {
4800  return rb_io_fmode_oflags(rb_io_modestr_fmode(modestr));
4801 }
4802 
4803 static const char*
4805 {
4806 #ifdef O_BINARY
4807 # define MODE_BINARY(a,b) ((oflags & O_BINARY) ? (b) : (a))
4808 #else
4809 # define MODE_BINARY(a,b) (a)
4810 #endif
4811  int accmode = oflags & (O_RDONLY|O_WRONLY|O_RDWR);
4812  if (oflags & O_APPEND) {
4813  if (accmode == O_WRONLY) {
4814  return MODE_BINARY("a", "ab");
4815  }
4816  if (accmode == O_RDWR) {
4817  return MODE_BINARY("a+", "ab+");
4818  }
4819  }
4820  switch (oflags & (O_RDONLY|O_WRONLY|O_RDWR)) {
4821  default:
4822  rb_raise(rb_eArgError, "invalid access oflags 0x%x", oflags);
4823  case O_RDONLY:
4824  return MODE_BINARY("r", "rb");
4825  case O_WRONLY:
4826  return MODE_BINARY("w", "wb");
4827  case O_RDWR:
4828  return MODE_BINARY("r+", "rb+");
4829  }
4830 }
4831 
4832 /*
4833  * Convert external/internal encodings to enc/enc2
4834  * NULL => use default encoding
4835  * Qnil => no encoding specified (internal only)
4836  */
4837 static void
4838 rb_io_ext_int_to_encs(rb_encoding *ext, rb_encoding *intern, rb_encoding **enc, rb_encoding **enc2, int fmode)
4839 {
4840  int default_ext = 0;
4841 
4842  if (ext == NULL) {
4844  default_ext = 1;
4845  }
4846  if (intern == NULL && ext != rb_ascii8bit_encoding())
4847  /* If external is ASCII-8BIT, no default transcoding */
4848  intern = rb_default_internal_encoding();
4849  if (intern == NULL || intern == (rb_encoding *)Qnil ||
4850  (!(fmode & FMODE_SETENC_BY_BOM) && (intern == ext))) {
4851  /* No internal encoding => use external + no transcoding */
4852  *enc = (default_ext && intern != ext) ? NULL : ext;
4853  *enc2 = NULL;
4854  }
4855  else {
4856  *enc = intern;
4857  *enc2 = ext;
4858  }
4859 }
4860 
4861 static void
4863 {
4864  rb_warn("Unsupported encoding %s ignored", name);
4865 }
4866 
4867 static void
4868 parse_mode_enc(const char *estr, rb_encoding **enc_p, rb_encoding **enc2_p, int *fmode_p)
4869 {
4870  const char *p;
4871  char encname[ENCODING_MAXNAMELEN+1];
4872  int idx, idx2;
4873  int fmode = fmode_p ? *fmode_p : 0;
4874  rb_encoding *ext_enc, *int_enc;
4875 
4876  /* parse estr as "enc" or "enc2:enc" or "enc:-" */
4877 
4878  p = strrchr(estr, ':');
4879  if (p) {
4880  long len = (p++) - estr;
4881  if (len == 0 || len > ENCODING_MAXNAMELEN)
4882  idx = -1;
4883  else {
4884  if (io_encname_bom_p(estr, len)) {
4885  fmode |= FMODE_SETENC_BY_BOM;
4886  estr += 4;
4887  len -= 4;
4888  }
4889  memcpy(encname, estr, len);
4890  encname[len] = '\0';
4891  estr = encname;
4892  idx = rb_enc_find_index(encname);
4893  }
4894  }
4895  else {
4896  long len = strlen(estr);
4897  if (io_encname_bom_p(estr, len)) {
4898  fmode |= FMODE_SETENC_BY_BOM;
4899  estr += 4;
4900  len -= 4;
4901  memcpy(encname, estr, len);
4902  encname[len] = '\0';
4903  estr = encname;
4904  }
4905  idx = rb_enc_find_index(estr);
4906  }
4907  if (fmode_p) *fmode_p = fmode;
4908 
4909  if (idx >= 0)
4910  ext_enc = rb_enc_from_index(idx);
4911  else {
4912  if (idx != -2)
4913  unsupported_encoding(estr);
4914  ext_enc = NULL;
4915  }
4916 
4917  int_enc = NULL;
4918  if (p) {
4919  if (*p == '-' && *(p+1) == '\0') {
4920  /* Special case - "-" => no transcoding */
4921  int_enc = (rb_encoding *)Qnil;
4922  }
4923  else {
4924  idx2 = rb_enc_find_index(p);
4925  if (idx2 < 0)
4927  else if (!(fmode & FMODE_SETENC_BY_BOM) && (idx2 == idx)) {
4928  int_enc = (rb_encoding *)Qnil;
4929  }
4930  else
4931  int_enc = rb_enc_from_index(idx2);
4932  }
4933  }
4934 
4935  rb_io_ext_int_to_encs(ext_enc, int_enc, enc_p, enc2_p, fmode);
4936 }
4937 
4938 int
4939 rb_io_extract_encoding_option(VALUE opt, rb_encoding **enc_p, rb_encoding **enc2_p, int *fmode_p)
4940 {
4941  VALUE encoding=Qnil, extenc=Qundef, intenc=Qundef, tmp;
4942  int extracted = 0;
4943  rb_encoding *extencoding = NULL;
4944  rb_encoding *intencoding = NULL;
4945 
4946  if (!NIL_P(opt)) {
4947  VALUE v;
4948  v = rb_hash_lookup2(opt, sym_encoding, Qnil);
4949  if (v != Qnil) encoding = v;
4950  v = rb_hash_lookup2(opt, sym_extenc, Qundef);
4951  if (v != Qnil) extenc = v;
4952  v = rb_hash_lookup2(opt, sym_intenc, Qundef);
4953  if (v != Qundef) intenc = v;
4954  }
4955  if ((extenc != Qundef || intenc != Qundef) && !NIL_P(encoding)) {
4956  if (!NIL_P(ruby_verbose)) {
4957  int idx = rb_to_encoding_index(encoding);
4958  rb_warn("Ignoring encoding parameter '%s': %s_encoding is used",
4959  idx < 0 ? StringValueCStr(encoding) : rb_enc_name(rb_enc_from_index(idx)),
4960  extenc == Qundef ? "internal" : "external");
4961  }
4962  encoding = Qnil;
4963  }
4964  if (extenc != Qundef && !NIL_P(extenc)) {
4965  extencoding = rb_to_encoding(extenc);
4966  }
4967  if (intenc != Qundef) {
4968  if (NIL_P(intenc)) {
4969  /* internal_encoding: nil => no transcoding */
4970  intencoding = (rb_encoding *)Qnil;
4971  }
4972  else if (!NIL_P(tmp = rb_check_string_type(intenc))) {
4973  char *p = StringValueCStr(tmp);
4974 
4975  if (*p == '-' && *(p+1) == '\0') {
4976  /* Special case - "-" => no transcoding */
4977  intencoding = (rb_encoding *)Qnil;
4978  }
4979  else {
4980  intencoding = rb_to_encoding(intenc);
4981  }
4982  }
4983  else {
4984  intencoding = rb_to_encoding(intenc);
4985  }
4986  if (extencoding == intencoding) {
4987  intencoding = (rb_encoding *)Qnil;
4988  }
4989  }
4990  if (!NIL_P(encoding)) {
4991  extracted = 1;
4992  if (!NIL_P(tmp = rb_check_string_type(encoding))) {
4993  parse_mode_enc(StringValueCStr(tmp), enc_p, enc2_p, fmode_p);
4994  }
4995  else {
4996  rb_io_ext_int_to_encs(rb_to_encoding(encoding), NULL, enc_p, enc2_p, 0);
4997  }
4998  }
4999  else if (extenc != Qundef || intenc != Qundef) {
5000  extracted = 1;
5001  rb_io_ext_int_to_encs(extencoding, intencoding, enc_p, enc2_p, 0);
5002  }
5003  return extracted;
5004 }
5005 
5006 typedef struct rb_io_enc_t convconfig_t;
5007 
5008 static void
5009 validate_enc_binmode(int *fmode_p, int ecflags, rb_encoding *enc, rb_encoding *enc2)
5010 {
5011  int fmode = *fmode_p;
5012 
5013  if ((fmode & FMODE_READABLE) &&
5014  !enc2 &&
5015  !(fmode & FMODE_BINMODE) &&
5017  rb_raise(rb_eArgError, "ASCII incompatible encoding needs binmode");
5018 
5019  if (!(fmode & FMODE_BINMODE) &&
5021  fmode |= DEFAULT_TEXTMODE;
5022  *fmode_p = fmode;
5023  }
5024 #if !DEFAULT_TEXTMODE
5025  else if (!(ecflags & ECONV_NEWLINE_DECORATOR_MASK)) {
5026  fmode &= ~FMODE_TEXTMODE;
5027  *fmode_p = fmode;
5028  }
5029 #endif
5030 }
5031 
5032 static void
5033 extract_binmode(VALUE opthash, int *fmode)
5034 {
5035  if (!NIL_P(opthash)) {
5036  VALUE v;
5037  v = rb_hash_aref(opthash, sym_textmode);
5038  if (!NIL_P(v)) {
5039  if (*fmode & FMODE_TEXTMODE)
5040  rb_raise(rb_eArgError, "textmode specified twice");
5041  if (RTEST(v))
5042  *fmode |= FMODE_TEXTMODE;
5043  }
5044  v = rb_hash_aref(opthash, sym_binmode);
5045  if (!NIL_P(v)) {
5046  if (*fmode & FMODE_BINMODE)
5047  rb_raise(rb_eArgError, "binmode specified twice");
5048  if (RTEST(v))
5049  *fmode |= FMODE_BINMODE;
5050  }
5051 
5052  if ((*fmode & FMODE_BINMODE) && (*fmode & FMODE_TEXTMODE))
5053  rb_raise(rb_eArgError, "both textmode and binmode specified");
5054  }
5055 }
5056 
5057 static void
5058 rb_io_extract_modeenc(VALUE *vmode_p, VALUE *vperm_p, VALUE opthash,
5059  int *oflags_p, int *fmode_p, convconfig_t *convconfig_p)
5060 {
5061  VALUE vmode;
5062  int oflags, fmode;
5063  rb_encoding *enc, *enc2;
5064  int ecflags;
5065  VALUE ecopts;
5066  int has_enc = 0, has_vmode = 0;
5067  VALUE intmode;
5068 
5069  vmode = *vmode_p;
5070 
5071  /* Set to defaults */
5072  rb_io_ext_int_to_encs(NULL, NULL, &enc, &enc2, 0);
5073 
5074  vmode_handle:
5075  if (NIL_P(vmode)) {
5076  fmode = FMODE_READABLE;
5077  oflags = O_RDONLY;
5078  }
5079  else if (!NIL_P(intmode = rb_check_to_integer(vmode, "to_int"))) {
5080  vmode = intmode;
5081  oflags = NUM2INT(intmode);
5082  fmode = rb_io_oflags_fmode(oflags);
5083  }
5084  else {
5085  const char *p;
5086 
5087  SafeStringValue(vmode);
5088  p = StringValueCStr(vmode);
5089  fmode = rb_io_modestr_fmode(p);
5090  oflags = rb_io_fmode_oflags(fmode);
5091  p = strchr(p, ':');
5092  if (p) {
5093  has_enc = 1;
5094  parse_mode_enc(p+1, &enc, &enc2, &fmode);
5095  }
5096  else {
5097  rb_encoding *e;
5098 
5099  e = (fmode & FMODE_BINMODE) ? rb_ascii8bit_encoding() : NULL;
5100  rb_io_ext_int_to_encs(e, NULL, &enc, &enc2, fmode);
5101  }
5102  }
5103 
5104  if (NIL_P(opthash)) {
5105  ecflags = (fmode & FMODE_READABLE) ?
5108 #ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE
5109  ecflags |= (fmode & FMODE_WRITABLE) ?
5110  MODE_BTMODE(TEXTMODE_NEWLINE_DECORATOR_ON_WRITE,
5111  0, TEXTMODE_NEWLINE_DECORATOR_ON_WRITE) : 0;
5112 #endif
5114  ecopts = Qnil;
5115  }
5116  else {
5117  VALUE v;
5118  extract_binmode(opthash, &fmode);
5119  if (fmode & FMODE_BINMODE) {
5120 #ifdef O_BINARY
5121  oflags |= O_BINARY;
5122 #endif
5123  if (!has_enc)
5124  rb_io_ext_int_to_encs(rb_ascii8bit_encoding(), NULL, &enc, &enc2, fmode);
5125  }
5126 #if DEFAULT_TEXTMODE
5127  else if (NIL_P(vmode)) {
5128  fmode |= DEFAULT_TEXTMODE;
5129  }
5130 #endif
5131  if (!has_vmode) {
5132  v = rb_hash_aref(opthash, sym_mode);
5133  if (!NIL_P(v)) {
5134  if (!NIL_P(vmode)) {
5135  rb_raise(rb_eArgError, "mode specified twice");
5136  }
5137  has_vmode = 1;
5138  vmode = v;
5139  goto vmode_handle;
5140  }
5141  }
5142  v = rb_hash_aref(opthash, sym_perm);
5143  if (!NIL_P(v)) {
5144  if (vperm_p) {
5145  if (!NIL_P(*vperm_p)) {
5146  rb_raise(rb_eArgError, "perm specified twice");
5147  }
5148  *vperm_p = v;
5149  }
5150  else {
5151  /* perm no use, just ignore */
5152  }
5153  }
5154  ecflags = (fmode & FMODE_READABLE) ?
5157 #ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE
5158  ecflags |= (fmode & FMODE_WRITABLE) ?
5159  MODE_BTMODE(TEXTMODE_NEWLINE_DECORATOR_ON_WRITE,
5160  0, TEXTMODE_NEWLINE_DECORATOR_ON_WRITE) : 0;
5161 #endif
5162 
5163  if (rb_io_extract_encoding_option(opthash, &enc, &enc2, &fmode)) {
5164  if (has_enc) {
5165  rb_raise(rb_eArgError, "encoding specified twice");
5166  }
5167  }
5169  ecflags = rb_econv_prepare_options(opthash, &ecopts, ecflags);
5170  }
5171 
5172  validate_enc_binmode(&fmode, ecflags, enc, enc2);
5173 
5174  *vmode_p = vmode;
5175 
5176  *oflags_p = oflags;
5177  *fmode_p = fmode;
5178  convconfig_p->enc = enc;
5179  convconfig_p->enc2 = enc2;
5180  convconfig_p->ecflags = ecflags;
5181  convconfig_p->ecopts = ecopts;
5182 }
5183 
5186  int oflags;
5188 };
5189 
5190 static void *
5191 sysopen_func(void *ptr)
5192 {
5193  const struct sysopen_struct *data = ptr;
5194  const char *fname = RSTRING_PTR(data->fname);
5195  return (void *)(VALUE)rb_cloexec_open(fname, data->oflags, data->perm);
5196 }
5197 
5198 static inline int
5200 {
5201  int fd;
5203  if (0 <= fd)
5204  rb_update_max_fd(fd);
5205  return fd;
5206 }
5207 
5208 static int
5210 {
5211  int fd;
5212  struct sysopen_struct data;
5213 
5214  data.fname = rb_str_encode_ospath(fname);
5215  data.oflags = oflags;
5216  data.perm = perm;
5217 
5218  fd = rb_sysopen_internal(&data);
5219  if (fd < 0) {
5220  if (errno == EMFILE || errno == ENFILE) {
5221  rb_gc();
5222  fd = rb_sysopen_internal(&data);
5223  }
5224  if (fd < 0) {
5225  rb_sys_fail_path(fname);
5226  }
5227  }
5228  return fd;
5229 }
5230 
5231 FILE *
5232 rb_fdopen(int fd, const char *modestr)
5233 {
5234  FILE *file;
5235 
5236 #if defined(__sun)
5237  errno = 0;
5238 #endif
5239  file = fdopen(fd, modestr);
5240  if (!file) {
5241  if (
5242 #if defined(__sun)
5243  errno == 0 ||
5244 #endif
5245  errno == EMFILE || errno == ENFILE) {
5246  rb_gc();
5247 #if defined(__sun)
5248  errno = 0;
5249 #endif
5250  file = fdopen(fd, modestr);
5251  }
5252  if (!file) {
5253 #ifdef _WIN32
5254  if (errno == 0) errno = EINVAL;
5255 #elif defined(__sun)
5256  if (errno == 0) errno = EMFILE;
5257 #endif
5258  rb_sys_fail(0);
5259  }
5260  }
5261 
5262  /* xxx: should be _IONBF? A buffer in FILE may have trouble. */
5263 #ifdef USE_SETVBUF
5264  if (setvbuf(file, NULL, _IOFBF, 0) != 0)
5265  rb_warn("setvbuf() can't be honoured (fd=%d)", fd);
5266 #endif
5267  return file;
5268 }
5269 
5270 static void
5272 {
5273  if (isatty(fptr->fd))
5274  fptr->mode |= FMODE_TTY|FMODE_DUPLEX;
5275 }
5276 
5278 static void io_encoding_set(rb_io_t *, VALUE, VALUE, VALUE);
5279 
5280 static int
5282 {
5283  VALUE b1, b2, b3, b4;
5284 
5285  if (NIL_P(b1 = rb_io_getbyte(io))) return 0;
5286  switch (b1) {
5287  case INT2FIX(0xEF):
5288  if (NIL_P(b2 = rb_io_getbyte(io))) break;
5289  if (b2 == INT2FIX(0xBB) && !NIL_P(b3 = rb_io_getbyte(io))) {
5290  if (b3 == INT2FIX(0xBF)) {
5291  return rb_utf8_encindex();
5292  }
5293  rb_io_ungetbyte(io, b3);
5294  }
5295  rb_io_ungetbyte(io, b2);
5296  break;
5297 
5298  case INT2FIX(0xFE):
5299  if (NIL_P(b2 = rb_io_getbyte(io))) break;
5300  if (b2 == INT2FIX(0xFF)) {
5301  return rb_enc_find_index("UTF-16BE");
5302  }
5303  rb_io_ungetbyte(io, b2);
5304  break;
5305 
5306  case INT2FIX(0xFF):
5307  if (NIL_P(b2 = rb_io_getbyte(io))) break;
5308  if (b2 == INT2FIX(0xFE)) {
5309  b3 = rb_io_getbyte(io);
5310  if (b3 == INT2FIX(0) && !NIL_P(b4 = rb_io_getbyte(io))) {
5311  if (b4 == INT2FIX(0)) {
5312  return rb_enc_find_index("UTF-32LE");
5313  }
5314  rb_io_ungetbyte(io, b4);
5315  rb_io_ungetbyte(io, b3);
5316  }
5317  else {
5318  rb_io_ungetbyte(io, b3);
5319  return rb_enc_find_index("UTF-16LE");
5320  }
5321  }
5322  rb_io_ungetbyte(io, b2);
5323  break;
5324 
5325  case INT2FIX(0):
5326  if (NIL_P(b2 = rb_io_getbyte(io))) break;
5327  if (b2 == INT2FIX(0) && !NIL_P(b3 = rb_io_getbyte(io))) {
5328  if (b3 == INT2FIX(0xFE) && !NIL_P(b4 = rb_io_getbyte(io))) {
5329  if (b4 == INT2FIX(0xFF)) {
5330  return rb_enc_find_index("UTF-32BE");
5331  }
5332  rb_io_ungetbyte(io, b4);
5333  }
5334  rb_io_ungetbyte(io, b3);
5335  }
5336  rb_io_ungetbyte(io, b2);
5337  break;
5338  }
5339  rb_io_ungetbyte(io, b1);
5340  return 0;
5341 }
5342 
5343 static void
5345 {
5346  int idx = io_strip_bom(io);
5347  rb_io_t *fptr;
5348 
5349  GetOpenFile(io, fptr);
5350  if (idx) {
5353  }
5354  else {
5355  fptr->encs.enc2 = NULL;
5356  }
5357 }
5358 
5359 static VALUE
5360 rb_file_open_generic(VALUE io, VALUE filename, int oflags, int fmode, convconfig_t *convconfig, mode_t perm)
5361 {
5362  rb_io_t *fptr;
5363  convconfig_t cc;
5364  if (!convconfig) {
5365  /* Set to default encodings */
5366  rb_io_ext_int_to_encs(NULL, NULL, &cc.enc, &cc.enc2, fmode);
5367  cc.ecflags = 0;
5368  cc.ecopts = Qnil;
5369  convconfig = &cc;
5370  }
5371  validate_enc_binmode(&fmode, convconfig->ecflags,
5372  convconfig->enc, convconfig->enc2);
5373 
5374  MakeOpenFile(io, fptr);
5375  fptr->mode = fmode;
5376  fptr->encs = *convconfig;
5377  fptr->pathv = rb_str_new_frozen(filename);
5378  fptr->fd = rb_sysopen(fptr->pathv, oflags, perm);
5379  io_check_tty(fptr);
5381 
5382  return io;
5383 }
5384 
5385 static VALUE
5386 rb_file_open_internal(VALUE io, VALUE filename, const char *modestr)
5387 {
5388  int fmode = rb_io_modestr_fmode(modestr);
5389  const char *p = strchr(modestr, ':');
5390  convconfig_t convconfig;
5391 
5392  if (p) {
5393  parse_mode_enc(p+1, &convconfig.enc, &convconfig.enc2, &fmode);
5394  }
5395  else {
5396  rb_encoding *e;
5397  /* Set to default encodings */
5398 
5399  e = (fmode & FMODE_BINMODE) ? rb_ascii8bit_encoding() : NULL;
5400  rb_io_ext_int_to_encs(e, NULL, &convconfig.enc, &convconfig.enc2, fmode);
5401  convconfig.ecflags = 0;
5402  convconfig.ecopts = Qnil;
5403  }
5404 
5405  return rb_file_open_generic(io, filename,
5406  rb_io_fmode_oflags(fmode),
5407  fmode,
5408  &convconfig,
5409  0666);
5410 }
5411 
5412 VALUE
5413 rb_file_open_str(VALUE fname, const char *modestr)
5414 {
5415  FilePathValue(fname);
5416  return rb_file_open_internal(io_alloc(rb_cFile), fname, modestr);
5417 }
5418 
5419 VALUE
5420 rb_file_open(const char *fname, const char *modestr)
5421 {
5422  return rb_file_open_internal(io_alloc(rb_cFile), rb_str_new_cstr(fname), modestr);
5423 }
5424 
5425 #if defined(__CYGWIN__) || !defined(HAVE_FORK)
5426 static struct pipe_list {
5428  struct pipe_list *next;
5429 } *pipe_list;
5430 
5431 static void
5433 {
5434  struct pipe_list *list;
5435 
5436  list = ALLOC(struct pipe_list);
5437  list->fptr = fptr;
5438  list->next = pipe_list;
5439  pipe_list = list;
5440 }
5441 
5442 static void
5444 {
5445  struct pipe_list *list = pipe_list;
5446  struct pipe_list *tmp;
5447 
5448  if (list->fptr == fptr) {
5449  pipe_list = list->next;
5450  free(list);
5451  return;
5452  }
5453 
5454  while (list->next) {
5455  if (list->next->fptr == fptr) {
5456  tmp = list->next;
5457  list->next = list->next->next;
5458  free(tmp);
5459  return;
5460  }
5461  list = list->next;
5462  }
5463 }
5464 
5465 static void
5467 {
5468  struct pipe_list *list = pipe_list;
5469  struct pipe_list *tmp;
5470 
5471  while (list) {
5472  tmp = list->next;
5473  rb_io_fptr_finalize(list->fptr);
5474  list = tmp;
5475  }
5476 }
5477 
5478 static void
5479 pipe_finalize(rb_io_t *fptr, int noraise)
5480 {
5481 #if !defined(HAVE_FORK) && !defined(_WIN32)
5482  int status = 0;
5483  if (fptr->stdio_file) {
5484  status = pclose(fptr->stdio_file);
5485  }
5486  fptr->fd = -1;
5487  fptr->stdio_file = 0;
5488  rb_last_status_set(status, fptr->pid);
5489 #else
5490  fptr_finalize(fptr, noraise);
5491 #endif
5492  pipe_del_fptr(fptr);
5493 }
5494 #endif
5495 
5496 void
5498 {
5500  fptr->mode |= FMODE_SYNC;
5501 }
5502 
5503 void
5505 {
5506  rb_io_synchronized(fptr);
5507 }
5508 
5509 int
5510 rb_pipe(int *pipes)
5511 {
5512  int ret;
5513  ret = rb_cloexec_pipe(pipes);
5514  if (ret == -1) {
5515  if (errno == EMFILE || errno == ENFILE) {
5516  rb_gc();
5517  ret = rb_cloexec_pipe(pipes);
5518  }
5519  }
5520  if (ret == 0) {
5521  rb_update_max_fd(pipes[0]);
5522  rb_update_max_fd(pipes[1]);
5523  }
5524  return ret;
5525 }
5526 
5527 #ifdef _WIN32
5528 #define HAVE_SPAWNV 1
5529 #define spawnv(mode, cmd, args) rb_w32_aspawn((mode), (cmd), (args))
5530 #define spawn(mode, cmd) rb_w32_spawn((mode), (cmd), 0)
5531 #endif
5532 
5533 #if defined(HAVE_FORK) || defined(HAVE_SPAWNV)
5534 struct popen_arg {
5535  VALUE execarg_obj;
5536  struct rb_execarg *eargp;
5537  int modef;
5538  int pair[2];
5539  int write_pair[2];
5540 };
5541 #endif
5542 
5543 #ifdef HAVE_FORK
5544 static void
5545 popen_redirect(struct popen_arg *p)
5546 {
5547  if ((p->modef & FMODE_READABLE) && (p->modef & FMODE_WRITABLE)) {
5548  close(p->write_pair[1]);
5549  if (p->write_pair[0] != 0) {
5550  dup2(p->write_pair[0], 0);
5551  close(p->write_pair[0]);
5552  }
5553  close(p->pair[0]);
5554  if (p->pair[1] != 1) {
5555  dup2(p->pair[1], 1);
5556  close(p->pair[1]);
5557  }
5558  }
5559  else if (p->modef & FMODE_READABLE) {
5560  close(p->pair[0]);
5561  if (p->pair[1] != 1) {
5562  dup2(p->pair[1], 1);
5563  close(p->pair[1]);
5564  }
5565  }
5566  else {
5567  close(p->pair[1]);
5568  if (p->pair[0] != 0) {
5569  dup2(p->pair[0], 0);
5570  close(p->pair[0]);
5571  }
5572  }
5573 }
5574 
5575 #if defined(__linux__)
5576 /* Linux /proc/self/status contains a line: "FDSize:\t<nnn>\n"
5577  * Since /proc may not be available, linux_get_maxfd is just a hint.
5578  * This function, linux_get_maxfd, must be async-signal-safe.
5579  * I.e. opendir() is not usable.
5580  *
5581  * Note that memchr() and memcmp is *not* async-signal-safe in POSIX.
5582  * However they are easy to re-implement in async-signal-safe manner.
5583  * (Also note that there is missing/memcmp.c.)
5584  */
5585 static int
5586 linux_get_maxfd(void)
5587 {
5588  int fd;
5589  char buf[4096], *p, *np, *e;
5590  ssize_t ss;
5591  fd = rb_cloexec_open("/proc/self/status", O_RDONLY|O_NOCTTY, 0);
5592  if (fd == -1) return -1;
5593  ss = read(fd, buf, sizeof(buf));
5594  if (ss == -1) goto err;
5595  p = buf;
5596  e = buf + ss;
5597  while ((int)sizeof("FDSize:\t0\n")-1 <= e-p &&
5598  (np = memchr(p, '\n', e-p)) != NULL) {
5599  if (memcmp(p, "FDSize:", sizeof("FDSize:")-1) == 0) {
5600  int fdsize;
5601  p += sizeof("FDSize:")-1;
5602  *np = '\0';
5603  fdsize = (int)ruby_strtoul(p, (char **)NULL, 10);
5604  close(fd);
5605  return fdsize;
5606  }
5607  p = np+1;
5608  }
5609  /* fall through */
5610 
5611  err:
5612  close(fd);
5613  return -1;
5614 }
5615 #endif
5616 
5617 /* This function should be async-signal-safe. */
5618 void
5619 rb_close_before_exec(int lowfd, int maxhint, VALUE noclose_fds)
5620 {
5621  int fd, ret;
5622  int max = (int)max_file_descriptor;
5623 #ifdef F_MAXFD
5624  /* F_MAXFD is available since NetBSD 2.0. */
5625  ret = fcntl(0, F_MAXFD); /* async-signal-safe */
5626  if (ret != -1)
5627  maxhint = max = ret;
5628 #elif defined(__linux__)
5629  ret = linux_get_maxfd();
5630  if (maxhint < ret)
5631  maxhint = ret;
5632  /* maxhint = max = ret; if (ret == -1) abort(); // test */
5633 #endif
5634  if (max < maxhint)
5635  max = maxhint;
5636  for (fd = lowfd; fd <= max; fd++) {
5637  if (!NIL_P(noclose_fds) &&
5638  RTEST(rb_hash_lookup(noclose_fds, INT2FIX(fd)))) /* async-signal-safe */
5639  continue;
5640  ret = fcntl(fd, F_GETFD); /* async-signal-safe */
5641  if (ret != -1 && !(ret & FD_CLOEXEC)) {
5642  fcntl(fd, F_SETFD, ret|FD_CLOEXEC); /* async-signal-safe */
5643  }
5644 #define CONTIGUOUS_CLOSED_FDS 20
5645  if (ret != -1) {
5646  if (max < fd + CONTIGUOUS_CLOSED_FDS)
5647  max = fd + CONTIGUOUS_CLOSED_FDS;
5648  }
5649  }
5650 }
5651 
5652 static int
5653 popen_exec(void *pp, char *errmsg, size_t errmsg_len)
5654 {
5655  struct popen_arg *p = (struct popen_arg*)pp;
5656 
5657  return rb_exec_async_signal_safe(p->eargp, errmsg, errmsg_len);
5658 }
5659 #endif
5660 
5661 static VALUE
5662 pipe_open(VALUE execarg_obj, const char *modestr, int fmode, convconfig_t *convconfig)
5663 {
5664  struct rb_execarg *eargp = NIL_P(execarg_obj) ? NULL : rb_execarg_get(execarg_obj);
5665  VALUE prog = eargp ? (eargp->use_shell ? eargp->invoke.sh.shell_script : eargp->invoke.cmd.command_name) : Qfalse ;
5666  rb_pid_t pid = 0;
5667  rb_io_t *fptr;
5668  VALUE port;
5669  rb_io_t *write_fptr;
5670  VALUE write_port;
5671 #if defined(HAVE_FORK)
5672  int status;
5673  char errmsg[80] = { '\0' };
5674 #endif
5675 #if defined(HAVE_FORK) || defined(HAVE_SPAWNV)
5676  struct popen_arg arg;
5677  int e = 0;
5678 #endif
5679 #if defined(HAVE_SPAWNV)
5680 # if defined(HAVE_SPAWNVE)
5681 # define DO_SPAWN(cmd, args, envp) ((args) ? \
5682  spawnve(P_NOWAIT, (cmd), (args), (envp)) : \
5683  spawne(P_NOWAIT, (cmd), (envp)))
5684 # else
5685 # define DO_SPAWN(cmd, args, envp) ((args) ? \
5686  spawnv(P_NOWAIT, (cmd), (args)) : \
5687  spawn(P_NOWAIT, (cmd)))
5688 # endif
5689 # if !defined(HAVE_FORK)
5690  char **args = NULL;
5691 # if defined(HAVE_SPAWNVE)
5692  char **envp = NULL;
5693 # endif
5694 # endif
5695 #endif
5696 #if !defined(HAVE_FORK)
5697  struct rb_execarg sarg, *sargp = &sarg;
5698 #endif
5699  FILE *fp = 0;
5700  int fd = -1;
5701  int write_fd = -1;
5702 #if !defined(HAVE_FORK)
5703  const char *cmd = 0;
5704 #if !defined(HAVE_SPAWNV)
5705  int argc;
5706  VALUE *argv;
5707 #endif
5708 
5709  if (prog)
5710  cmd = StringValueCStr(prog);
5711 #endif
5712 
5713 #if defined(HAVE_FORK) || defined(HAVE_SPAWNV)
5714  arg.execarg_obj = execarg_obj;
5715  arg.eargp = eargp;
5716  arg.modef = fmode;
5717  arg.pair[0] = arg.pair[1] = -1;
5718  arg.write_pair[0] = arg.write_pair[1] = -1;
5719 # if !defined(HAVE_FORK)
5720  if (eargp && !eargp->use_shell) {
5721  args = ARGVSTR2ARGV(eargp->invoke.cmd.argv_str);
5722  }
5723 # endif
5724  switch (fmode & (FMODE_READABLE|FMODE_WRITABLE)) {
5726  if (rb_pipe(arg.write_pair) < 0)
5727  rb_sys_fail_str(prog);
5728  if (rb_pipe(arg.pair) < 0) {
5729  int e = errno;
5730  close(arg.write_pair[0]);
5731  close(arg.write_pair[1]);
5732  errno = e;
5733  rb_sys_fail_str(prog);
5734  }
5735  if (eargp) {
5736  rb_execarg_addopt(execarg_obj, INT2FIX(0), INT2FIX(arg.write_pair[0]));
5737  rb_execarg_addopt(execarg_obj, INT2FIX(1), INT2FIX(arg.pair[1]));
5738  }
5739  break;
5740  case FMODE_READABLE:
5741  if (rb_pipe(arg.pair) < 0)
5742  rb_sys_fail_str(prog);
5743  if (eargp)
5744  rb_execarg_addopt(execarg_obj, INT2FIX(1), INT2FIX(arg.pair[1]));
5745  break;
5746  case FMODE_WRITABLE:
5747  if (rb_pipe(arg.pair) < 0)
5748  rb_sys_fail_str(prog);
5749  if (eargp)
5750  rb_execarg_addopt(execarg_obj, INT2FIX(0), INT2FIX(arg.pair[0]));
5751  break;
5752  default:
5753  rb_sys_fail_str(prog);
5754  }
5755  if (!NIL_P(execarg_obj)) {
5756  rb_execarg_fixup(execarg_obj);
5757 # if defined(HAVE_FORK)
5758  pid = rb_fork_async_signal_safe(&status, popen_exec, &arg, arg.eargp->redirect_fds, errmsg, sizeof(errmsg));
5759 # else
5760  rb_execarg_run_options(eargp, sargp, NULL, 0);
5761 # if defined(HAVE_SPAWNVE)
5762  if (eargp->envp_str) envp = (char **)RSTRING_PTR(eargp->envp_str);
5763 # endif
5764  while ((pid = DO_SPAWN(cmd, args, envp)) == -1) {
5765  /* exec failed */
5766  switch (e = errno) {
5767  case EAGAIN:
5768 # if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
5769  case EWOULDBLOCK:
5770 # endif
5771  rb_thread_sleep(1);
5772  continue;
5773  }
5774  break;
5775  }
5776  if (eargp)
5777  rb_execarg_run_options(sargp, NULL, NULL, 0);
5778 # endif
5779  }
5780  else {
5781 # if defined(HAVE_FORK)
5782  pid = rb_fork_ruby(&status);
5783  if (pid == 0) { /* child */
5784  rb_thread_atfork();
5785  popen_redirect(&arg);
5788  return Qnil;
5789  }
5790 # else
5791  rb_notimplement();
5792 # endif
5793  }
5794 
5795  /* parent */
5796  if (pid == -1) {
5797 # if defined(HAVE_FORK)
5798  e = errno;
5799 # endif
5800  close(arg.pair[0]);
5801  close(arg.pair[1]);
5803  close(arg.write_pair[0]);
5804  close(arg.write_pair[1]);
5805  }
5806  errno = e;
5807 # if defined(HAVE_FORK)
5808  if (errmsg[0])
5809  rb_sys_fail(errmsg);
5810 # endif
5811  rb_sys_fail_str(prog);
5812  }
5813  if ((fmode & FMODE_READABLE) && (fmode & FMODE_WRITABLE)) {
5814  close(arg.pair[1]);
5815  fd = arg.pair[0];
5816  close(arg.write_pair[0]);
5817  write_fd = arg.write_pair[1];
5818  }
5819  else if (fmode & FMODE_READABLE) {
5820  close(arg.pair[1]);
5821  fd = arg.pair[0];
5822  }
5823  else {
5824  close(arg.pair[0]);
5825  fd = arg.pair[1];
5826  }
5827 #else
5828  if (argc) {
5829  prog = rb_ary_join(rb_ary_new4(argc, argv), rb_str_new2(" "));
5830  cmd = StringValueCStr(prog);
5831  }
5832  if (!NIL_P(execarg_obj)) {
5833  rb_execarg_fixup(execarg_obj);
5834  rb_execarg_run_options(eargp, sargp, NULL, 0);
5835  }
5836  fp = popen(cmd, modestr);
5837  if (eargp)
5838  rb_execarg_run_options(sargp, NULL, NULL, 0);
5839  if (!fp) rb_sys_fail_path(prog);
5840  fd = fileno(fp);
5841 #endif
5842 
5843  port = io_alloc(rb_cIO);
5844  MakeOpenFile(port, fptr);
5845  fptr->fd = fd;
5846  fptr->stdio_file = fp;
5847  fptr->mode = fmode | FMODE_SYNC|FMODE_DUPLEX;
5848  if (convconfig) {
5849  fptr->encs = *convconfig;
5850 #if defined(RUBY_TEST_CRLF_ENVIRONMENT) || defined(_WIN32)
5853  }
5854 #endif
5855  }
5856  else {
5857  if (NEED_NEWLINE_DECORATOR_ON_READ(fptr)) {
5859  }
5860 #ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE
5861  if (NEED_NEWLINE_DECORATOR_ON_WRITE(fptr)) {
5862  fptr->encs.ecflags |= TEXTMODE_NEWLINE_DECORATOR_ON_WRITE;
5863  }
5864 #endif
5865  }
5866  fptr->pid = pid;
5867 
5868  if (0 <= write_fd) {
5869  write_port = io_alloc(rb_cIO);
5870  MakeOpenFile(write_port, write_fptr);
5871  write_fptr->fd = write_fd;
5872  write_fptr->mode = (fmode & ~FMODE_READABLE)| FMODE_SYNC|FMODE_DUPLEX;
5873  fptr->mode &= ~FMODE_WRITABLE;
5874  fptr->tied_io_for_writing = write_port;
5875  rb_ivar_set(port, rb_intern("@tied_io_for_writing"), write_port);
5876  }
5877 
5878 #if defined (__CYGWIN__) || !defined(HAVE_FORK)
5879  fptr->finalize = pipe_finalize;
5880  pipe_add_fptr(fptr);
5881 #endif
5882  return port;
5883 }
5884 
5885 static int
5887 {
5888  if (RSTRING_LEN(prog) == 1 && RSTRING_PTR(prog)[0] == '-') {
5889 #if !defined(HAVE_FORK)
5891  "fork() function is unimplemented on this machine");
5892 #else
5893  return TRUE;
5894 #endif
5895  }
5896  return FALSE;
5897 }
5898 
5899 static VALUE
5900 pipe_open_s(VALUE prog, const char *modestr, int fmode, convconfig_t *convconfig)
5901 {
5902  int argc = 1;
5903  VALUE *argv = &prog;
5904  VALUE execarg_obj = Qnil;
5905 
5906  if (!is_popen_fork(prog))
5907  execarg_obj = rb_execarg_new(argc, argv, TRUE);
5908  return pipe_open(execarg_obj, modestr, fmode, convconfig);
5909 }
5910 
5911 /*
5912  * call-seq:
5913  * IO.popen([env,] cmd, mode="r" [, opt]) -> io
5914  * IO.popen([env,] cmd, mode="r" [, opt]) {|io| block } -> obj
5915  *
5916  * Runs the specified command as a subprocess; the subprocess's
5917  * standard input and output will be connected to the returned
5918  * <code>IO</code> object.
5919  *
5920  * The PID of the started process can be obtained by IO#pid method.
5921  *
5922  * _cmd_ is a string or an array as follows.
5923  *
5924  * cmd:
5925  * "-" : fork
5926  * commandline : command line string which is passed to a shell
5927  * [env, cmdname, arg1, ..., opts] : command name and zero or more arguments (no shell)
5928  * [env, [cmdname, argv0], arg1, ..., opts] : command name, argv[0] and zero or more arguments (no shell)
5929  * (env and opts are optional.)
5930  *
5931  * If _cmd_ is a +String+ ``<code>-</code>'',
5932  * then a new instance of Ruby is started as the subprocess.
5933  *
5934  * If <i>cmd</i> is an +Array+ of +String+,
5935  * then it will be used as the subprocess's +argv+ bypassing a shell.
5936  * The array can contains a hash at first for environments and
5937  * a hash at last for options similar to <code>spawn</code>.
5938  *
5939  * The default mode for the new file object is ``r'',
5940  * but <i>mode</i> may be set to any of the modes listed in the description for class IO.
5941  * The last argument <i>opt</i> qualifies <i>mode</i>.
5942  *
5943  * # set IO encoding
5944  * IO.popen("nkf -e filename", :external_encoding=>"EUC-JP") {|nkf_io|
5945  * euc_jp_string = nkf_io.read
5946  * }
5947  *
5948  * # merge standard output and standard error using
5949  * # spawn option. See the document of Kernel.spawn.
5950  * IO.popen(["ls", "/", :err=>[:child, :out]]) {|ls_io|
5951  * ls_result_with_error = ls_io.read
5952  * }
5953  *
5954  * # spawn options can be mixed with IO options
5955  * IO.popen(["ls", "/"], :err=>[:child, :out]) {|ls_io|
5956  * ls_result_with_error = ls_io.read
5957  * }
5958  *
5959  * Raises exceptions which <code>IO.pipe</code> and
5960  * <code>Kernel.spawn</code> raise.
5961  *
5962  * If a block is given, Ruby will run the command as a child connected
5963  * to Ruby with a pipe. Ruby's end of the pipe will be passed as a
5964  * parameter to the block.
5965  * At the end of block, Ruby close the pipe and sets <code>$?</code>.
5966  * In this case <code>IO.popen</code> returns
5967  * the value of the block.
5968  *
5969  * If a block is given with a _cmd_ of ``<code>-</code>'',
5970  * the block will be run in two separate processes: once in the parent,
5971  * and once in a child. The parent process will be passed the pipe
5972  * object as a parameter to the block, the child version of the block
5973  * will be passed <code>nil</code>, and the child's standard in and
5974  * standard out will be connected to the parent through the pipe. Not
5975  * available on all platforms.
5976  *
5977  * f = IO.popen("uname")
5978  * p f.readlines
5979  * f.close
5980  * puts "Parent is #{Process.pid}"
5981  * IO.popen("date") { |f| puts f.gets }
5982  * IO.popen("-") {|f| $stderr.puts "#{Process.pid} is here, f is #{f.inspect}"}
5983  * p $?
5984  * IO.popen(%w"sed -e s|^|<foo>| -e s&$&;zot;&", "r+") {|f|
5985  * f.puts "bar"; f.close_write; puts f.gets
5986  * }
5987  *
5988  * <em>produces:</em>
5989  *
5990  * ["Linux\n"]
5991  * Parent is 21346
5992  * Thu Jan 15 22:41:19 JST 2009
5993  * 21346 is here, f is #<IO:fd 3>
5994  * 21352 is here, f is nil
5995  * #<Process::Status: pid 21352 exit 0>
5996  * <foo>bar;zot;
5997  */
5998 
5999 static VALUE
6001 {
6002  const char *modestr;
6003  VALUE pname, pmode = Qnil, port, tmp, opt = Qnil, env = Qnil, execarg_obj = Qnil;
6004  int oflags, fmode;
6005  convconfig_t convconfig;
6006 
6007  if (argc > 1 && !NIL_P(opt = rb_check_hash_type(argv[argc-1]))) --argc;
6008  if (argc > 1 && !NIL_P(env = rb_check_hash_type(argv[0]))) --argc, ++argv;
6009  switch (argc) {
6010  case 2:
6011  pmode = argv[1];
6012  case 1:
6013  pname = argv[0];
6014  break;
6015  default:
6016  {
6017  int ex = !NIL_P(opt);
6018  rb_error_arity(argc + ex, 1 + ex, 2 + ex);
6019  }
6020  }
6021 
6022  tmp = rb_check_array_type(pname);
6023  if (!NIL_P(tmp)) {
6024  long len = RARRAY_LEN(tmp);
6025 #if SIZEOF_LONG > SIZEOF_INT
6026  if (len > INT_MAX) {
6027  rb_raise(rb_eArgError, "too many arguments");
6028  }
6029 #endif
6030  tmp = rb_ary_dup(tmp);
6031  RBASIC(tmp)->klass = 0;
6032  execarg_obj = rb_execarg_new((int)len, RARRAY_PTR(tmp), FALSE);
6033  rb_ary_clear(tmp);
6034  }
6035  else {
6036  SafeStringValue(pname);
6037  execarg_obj = Qnil;
6038  if (!is_popen_fork(pname))
6039  execarg_obj = rb_execarg_new(1, &pname, TRUE);
6040  }
6041  if (!NIL_P(execarg_obj)) {
6042  if (!NIL_P(opt))
6043  opt = rb_execarg_extract_options(execarg_obj, opt);
6044  if (!NIL_P(env))
6045  rb_execarg_setenv(execarg_obj, env);
6046  }
6047  rb_io_extract_modeenc(&pmode, 0, opt, &oflags, &fmode, &convconfig);
6048  modestr = rb_io_oflags_modestr(oflags);
6049 
6050  port = pipe_open(execarg_obj, modestr, fmode, &convconfig);
6051  if (NIL_P(port)) {
6052  /* child */
6053  if (rb_block_given_p()) {
6054  rb_yield(Qnil);
6057  _exit(0);
6058  }
6059  return Qnil;
6060  }
6061  RBASIC(port)->klass = klass;
6062  if (rb_block_given_p()) {
6063  return rb_ensure(rb_yield, port, io_close, port);
6064  }
6065  return port;
6066 }
6067 
6068 static void
6070  VALUE *fname_p, int *oflags_p, int *fmode_p,
6071  convconfig_t *convconfig_p, mode_t *perm_p)
6072 {
6073  VALUE opt, fname, vmode, vperm;
6074  int oflags, fmode;
6075  mode_t perm;
6076 
6077  argc = rb_scan_args(argc, argv, "12:", &fname, &vmode, &vperm, &opt);
6078  FilePathValue(fname);
6079 
6080  rb_io_extract_modeenc(&vmode, &vperm, opt, &oflags, &fmode, convconfig_p);
6081 
6082  perm = NIL_P(vperm) ? 0666 : NUM2MODET(vperm);
6083 
6084  *fname_p = fname;
6085  *oflags_p = oflags;
6086  *fmode_p = fmode;
6087  *perm_p = perm;
6088 }
6089 
6090 static VALUE
6092 {
6093  VALUE fname;
6094  int oflags, fmode;
6095  convconfig_t convconfig;
6096  mode_t perm;
6097 
6098  rb_scan_open_args(argc, argv, &fname, &oflags, &fmode, &convconfig, &perm);
6099  rb_file_open_generic(io, fname, oflags, fmode, &convconfig, perm);
6100 
6101  return io;
6102 }
6103 
6104 
6105 /*
6106  * Document-method: File::open
6107  *
6108  * call-seq:
6109  * File.open(filename, mode="r" [, opt]) -> file
6110  * File.open(filename [, mode [, perm]] [, opt]) -> file
6111  * File.open(filename, mode="r" [, opt]) {|file| block } -> obj
6112  * File.open(filename [, mode [, perm]] [, opt]) {|file| block } -> obj
6113  *
6114  * With no associated block, <code>File.open</code> is a synonym for
6115  * File.new. If the optional code block is given, it will
6116  * be passed the opened +file+ as an argument and the File object will
6117  * automatically be closed when the block terminates. The value of the block
6118  * will be returned from <code>File.open</code>.
6119  *
6120  * If a file is being created, its initial permissions may be set using the
6121  * +perm+ parameter. See File.new for further discussion.
6122  *
6123  * See IO.new for a description of the +mode+ and +opt+ parameters.
6124  */
6125 
6126 /*
6127  * Document-method: IO::open
6128  *
6129  * call-seq:
6130  * IO.open(fd, mode="r" [, opt]) -> io
6131  * IO.open(fd, mode="r" [, opt]) { |io| block } -> obj
6132  *
6133  * With no associated block, <code>IO.open</code> is a synonym for IO.new. If
6134  * the optional code block is given, it will be passed +io+ as an argument,
6135  * and the IO object will automatically be closed when the block terminates.
6136  * In this instance, IO.open returns the value of the block.
6137  *
6138  * See IO.new for a description of the +fd+, +mode+ and +opt+ parameters.
6139  */
6140 
6141 static VALUE
6143 {
6144  VALUE io = rb_class_new_instance(argc, argv, klass);
6145 
6146  if (rb_block_given_p()) {
6147  return rb_ensure(rb_yield, io, io_close, io);
6148  }
6149 
6150  return io;
6151 }
6152 
6153 /*
6154  * call-seq:
6155  * IO.sysopen(path, [mode, [perm]]) -> fixnum
6156  *
6157  * Opens the given path, returning the underlying file descriptor as a
6158  * <code>Fixnum</code>.
6159  *
6160  * IO.sysopen("testfile") #=> 3
6161  */
6162 
6163 static VALUE
6165 {
6166  VALUE fname, vmode, vperm;
6167  VALUE intmode;
6168  int oflags, fd;
6169  mode_t perm;
6170 
6171  rb_scan_args(argc, argv, "12", &fname, &vmode, &vperm);
6172  FilePathValue(fname);
6173 
6174  if (NIL_P(vmode))
6175  oflags = O_RDONLY;
6176  else if (!NIL_P(intmode = rb_check_to_integer(vmode, "to_int")))
6177  oflags = NUM2INT(intmode);
6178  else {
6179  SafeStringValue(vmode);
6180  oflags = rb_io_modestr_oflags(StringValueCStr(vmode));
6181  }
6182  if (NIL_P(vperm)) perm = 0666;
6183  else perm = NUM2MODET(vperm);
6184 
6185  RB_GC_GUARD(fname) = rb_str_new4(fname);
6186  fd = rb_sysopen(fname, oflags, perm);
6187  return INT2NUM(fd);
6188 }
6189 
6190 static VALUE
6191 check_pipe_command(VALUE filename_or_command)
6192 {
6193  char *s = RSTRING_PTR(filename_or_command);
6194  long l = RSTRING_LEN(filename_or_command);
6195  char *e = s + l;
6196  int chlen;
6197 
6198  if (rb_enc_ascget(s, e, &chlen, rb_enc_get(filename_or_command)) == '|') {
6199  VALUE cmd = rb_str_new(s+chlen, l-chlen);
6200  OBJ_INFECT(cmd, filename_or_command);
6201  return cmd;
6202  }
6203  return Qnil;
6204 }
6205 
6206 /*
6207  * call-seq:
6208  * open(path [, mode [, perm]] [, opt]) -> io or nil
6209  * open(path [, mode [, perm]] [, opt]) {|io| block } -> obj
6210  *
6211  * Creates an IO object connected to the given stream, file, or subprocess.
6212  *
6213  * If +path+ does not start with a pipe character (<code>|</code>), treat it
6214  * as the name of a file to open using the specified mode (defaulting to
6215  * "r").
6216  *
6217  * The +mode+ is either a string or an integer. If it is an integer, it
6218  * must be bitwise-or of open(2) flags, such as File::RDWR or File::EXCL. If
6219  * it is a string, it is either "fmode", "fmode:ext_enc", or
6220  * "fmode:ext_enc:int_enc".
6221  *
6222  * See the documentation of IO.new for full documentation of the +mode+ string
6223  * directives.
6224  *
6225  * If a file is being created, its initial permissions may be set using the
6226  * +perm+ parameter. See File.new and the open(2) and chmod(2) man pages for
6227  * a description of permissions.
6228  *
6229  * If a block is specified, it will be invoked with the IO object as a
6230  * parameter, and the IO will be automatically closed when the block
6231  * terminates. The call returns the value of the block.
6232  *
6233  * If +path+ starts with a pipe character (<code>"|"</code>), a subprocess is
6234  * created, connected to the caller by a pair of pipes. The returned IO
6235  * object may be used to write to the standard input and read from the
6236  * standard output of this subprocess.
6237  *
6238  * If the command following the pipe is a single minus sign
6239  * (<code>"|-"</code>), Ruby forks, and this subprocess is connected to the
6240  * parent. If the command is not <code>"-"</code>, the subprocess runs the
6241  * command.
6242  *
6243  * When the subprocess is ruby (opened via <code>"|-"</code>), the +open+
6244  * call returns +nil+. If a block is associated with the open call, that
6245  * block will run twice --- once in the parent and once in the child.
6246  *
6247  * The block parameter will be an IO object in the parent and +nil+ in the
6248  * child. The parent's +IO+ object will be connected to the child's $stdin
6249  * and $stdout. The subprocess will be terminated at the end of the block.
6250  *
6251  * === Examples
6252  *
6253  * Reading from "testfile":
6254  *
6255  * open("testfile") do |f|
6256  * print f.gets
6257  * end
6258  *
6259  * Produces:
6260  *
6261  * This is line one
6262  *
6263  * Open a subprocess and read its output:
6264  *
6265  * cmd = open("|date")
6266  * print cmd.gets
6267  * cmd.close
6268  *
6269  * Produces:
6270  *
6271  * Wed Apr 9 08:56:31 CDT 2003
6272  *
6273  * Open a subprocess running the same Ruby program:
6274  *
6275  * f = open("|-", "w+")
6276  * if f == nil
6277  * puts "in Child"
6278  * exit
6279  * else
6280  * puts "Got: #{f.gets}"
6281  * end
6282  *
6283  * Produces:
6284  *
6285  * Got: in Child
6286  *
6287  * Open a subprocess using a block to receive the IO object:
6288  *
6289  * open "|-" do |f|
6290  * if f then
6291  * # parent process
6292  * puts "Got: #{f.gets}"
6293  * else
6294  * # child process
6295  * puts "in Child"
6296  * end
6297  * end
6298  *
6299  * Produces:
6300  *
6301  * Got: in Child
6302  */
6303 
6304 static VALUE
6306 {
6307  ID to_open = 0;
6308  int redirect = FALSE;
6309 
6310  if (argc >= 1) {
6311  CONST_ID(to_open, "to_open");
6312  if (rb_respond_to(argv[0], to_open)) {
6313  redirect = TRUE;
6314  }
6315  else {
6316  VALUE tmp = argv[0];
6317  FilePathValue(tmp);
6318  if (NIL_P(tmp)) {
6319  redirect = TRUE;
6320  }
6321  else {
6322  VALUE cmd = check_pipe_command(tmp);
6323  if (!NIL_P(cmd)) {
6324  argv[0] = cmd;
6325  return rb_io_s_popen(argc, argv, rb_cIO);
6326  }
6327  }
6328  }
6329  }
6330  if (redirect) {
6331  VALUE io = rb_funcall2(argv[0], to_open, argc-1, argv+1);
6332 
6333  if (rb_block_given_p()) {
6334  return rb_ensure(rb_yield, io, io_close, io);
6335  }
6336  return io;
6337  }
6338  return rb_io_s_open(argc, argv, rb_cFile);
6339 }
6340 
6341 static VALUE
6342 rb_io_open(VALUE filename, VALUE vmode, VALUE vperm, VALUE opt)
6343 {
6344  VALUE cmd;
6345  int oflags, fmode;
6346  convconfig_t convconfig;
6347  mode_t perm;
6348 
6349  rb_io_extract_modeenc(&vmode, &vperm, opt, &oflags, &fmode, &convconfig);
6350  perm = NIL_P(vperm) ? 0666 : NUM2MODET(vperm);
6351 
6352  if (!NIL_P(cmd = check_pipe_command(filename))) {
6353  return pipe_open_s(cmd, rb_io_oflags_modestr(oflags), fmode, &convconfig);
6354  }
6355  else {
6356  return rb_file_open_generic(io_alloc(rb_cFile), filename,
6357  oflags, fmode, &convconfig, perm);
6358  }
6359 }
6360 
6361 static VALUE
6363 {
6364  VALUE io;
6365 
6366  io = io_alloc(rb_cFile);
6367  rb_open_file(argc, argv, io);
6368  return io;
6369 }
6370 
6371 static VALUE
6373 {
6374  rb_io_t *fptr, *orig;
6375  int fd, fd2;
6376  off_t pos = 0;
6377 
6378  nfile = rb_io_get_io(nfile);
6379  if (rb_safe_level() >= 4 &&
6380  (!OBJ_UNTRUSTED(io) || !OBJ_UNTRUSTED(nfile))) {
6381  rb_raise(rb_eSecurityError, "Insecure: can't reopen");
6382  }
6383  GetOpenFile(io, fptr);
6384  GetOpenFile(nfile, orig);
6385 
6386  if (fptr == orig) return io;
6387  if (IS_PREP_STDIO(fptr)) {
6388  if ((fptr->stdio_file == stdin && !(orig->mode & FMODE_READABLE)) ||
6389  (fptr->stdio_file == stdout && !(orig->mode & FMODE_WRITABLE)) ||
6390  (fptr->stdio_file == stderr && !(orig->mode & FMODE_WRITABLE))) {
6392  "%s can't change access mode from \"%s\" to \"%s\"",
6394  rb_io_fmode_modestr(orig->mode));
6395  }
6396  }
6397  if (fptr->mode & FMODE_WRITABLE) {
6398  if (io_fflush(fptr) < 0)
6399  rb_sys_fail(0);
6400  }
6401  else {
6402  io_tell(fptr);
6403  }
6404  if (orig->mode & FMODE_READABLE) {
6405  pos = io_tell(orig);
6406  }
6407  if (orig->mode & FMODE_WRITABLE) {
6408  if (io_fflush(orig) < 0)
6409  rb_sys_fail(0);
6410  }
6411 
6412  /* copy rb_io_t structure */
6413  fptr->mode = orig->mode | (fptr->mode & FMODE_PREP);
6414  fptr->pid = orig->pid;
6415  fptr->lineno = orig->lineno;
6416  if (RTEST(orig->pathv)) fptr->pathv = orig->pathv;
6417  else if (!IS_PREP_STDIO(fptr)) fptr->pathv = Qnil;
6418  fptr->finalize = orig->finalize;
6419 #if defined (__CYGWIN__) || !defined(HAVE_FORK)
6420  if (fptr->finalize == pipe_finalize)
6421  pipe_add_fptr(fptr);
6422 #endif
6423 
6424  fd = fptr->fd;
6425  fd2 = orig->fd;
6426  if (fd != fd2) {
6427  if (IS_PREP_STDIO(fptr) || fd <= 2 || !fptr->stdio_file) {
6428  /* need to keep FILE objects of stdin, stdout and stderr */
6429  if (rb_cloexec_dup2(fd2, fd) < 0)
6430  rb_sys_fail_path(orig->pathv);
6431  rb_update_max_fd(fd);
6432  }
6433  else {
6434  fclose(fptr->stdio_file);
6435  fptr->stdio_file = 0;
6436  fptr->fd = -1;
6437  if (rb_cloexec_dup2(fd2, fd) < 0)
6438  rb_sys_fail_path(orig->pathv);
6439  rb_update_max_fd(fd);
6440  fptr->fd = fd;
6441  }
6442  rb_thread_fd_close(fd);
6443  if ((orig->mode & FMODE_READABLE) && pos >= 0) {
6444  if (io_seek(fptr, pos, SEEK_SET) < 0 && errno) {
6445  rb_sys_fail_path(fptr->pathv);
6446  }
6447  if (io_seek(orig, pos, SEEK_SET) < 0 && errno) {
6448  rb_sys_fail_path(orig->pathv);
6449  }
6450  }
6451  }
6452 
6453  if (fptr->mode & FMODE_BINMODE) {
6454  rb_io_binmode(io);
6455  }
6456 
6457  RBASIC(io)->klass = rb_obj_class(nfile);
6458  return io;
6459 }
6460 
6461 /*
6462  * call-seq:
6463  * ios.reopen(other_IO) -> ios
6464  * ios.reopen(path, mode_str) -> ios
6465  *
6466  * Reassociates <em>ios</em> with the I/O stream given in
6467  * <i>other_IO</i> or to a new stream opened on <i>path</i>. This may
6468  * dynamically change the actual class of this stream.
6469  *
6470  * f1 = File.new("testfile")
6471  * f2 = File.new("testfile")
6472  * f2.readlines[0] #=> "This is line one\n"
6473  * f2.reopen(f1) #=> #<File:testfile>
6474  * f2.readlines[0] #=> "This is line one\n"
6475  */
6476 
6477 static VALUE
6479 {
6480  VALUE fname, nmode, opt;
6481  int oflags;
6482  rb_io_t *fptr;
6483 
6484  rb_secure(4);
6485  if (rb_scan_args(argc, argv, "11:", &fname, &nmode, &opt) == 1) {
6486  VALUE tmp = rb_io_check_io(fname);
6487  if (!NIL_P(tmp)) {
6488  return io_reopen(file, tmp);
6489  }
6490  }
6491 
6492  FilePathValue(fname);
6493  rb_io_taint_check(file);
6494  fptr = RFILE(file)->fptr;
6495  if (!fptr) {
6496  fptr = RFILE(file)->fptr = ALLOC(rb_io_t);
6497  MEMZERO(fptr, rb_io_t, 1);
6498  }
6499 
6500  if (!NIL_P(nmode) || !NIL_P(opt)) {
6501  int fmode;
6502  convconfig_t convconfig;
6503 
6504  rb_io_extract_modeenc(&nmode, 0, opt, &oflags, &fmode, &convconfig);
6505  if (IS_PREP_STDIO(fptr) &&
6506  ((fptr->mode & FMODE_READWRITE) & (fmode & FMODE_READWRITE)) !=
6507  (fptr->mode & FMODE_READWRITE)) {
6509  "%s can't change access mode from \"%s\" to \"%s\"",
6511  rb_io_fmode_modestr(fmode));
6512  }
6513  fptr->mode = fmode;
6514  fptr->encs = convconfig;
6515  }
6516  else {
6517  oflags = rb_io_fmode_oflags(fptr->mode);
6518  }
6519 
6520  fptr->pathv = rb_str_new_frozen(fname);
6521  if (fptr->fd < 0) {
6522  fptr->fd = rb_sysopen(fptr->pathv, oflags, 0666);
6523  fptr->stdio_file = 0;
6524  return file;
6525  }
6526 
6527  if (fptr->mode & FMODE_WRITABLE) {
6528  if (io_fflush(fptr) < 0)
6529  rb_sys_fail(0);
6530  }
6531  fptr->rbuf.off = fptr->rbuf.len = 0;
6532 
6533  if (fptr->stdio_file) {
6534  if (freopen(RSTRING_PTR(fptr->pathv), rb_io_oflags_modestr(oflags), fptr->stdio_file) == 0) {
6535  rb_sys_fail_path(fptr->pathv);
6536  }
6537  fptr->fd = fileno(fptr->stdio_file);
6538  rb_fd_fix_cloexec(fptr->fd);
6539 #ifdef USE_SETVBUF
6540  if (setvbuf(fptr->stdio_file, NULL, _IOFBF, 0) != 0)
6541  rb_warn("setvbuf() can't be honoured for %s", RSTRING_PTR(fptr->pathv));
6542 #endif
6543  if (fptr->stdio_file == stderr) {
6544  if (setvbuf(fptr->stdio_file, NULL, _IONBF, BUFSIZ) != 0)
6545  rb_warn("setvbuf() can't be honoured for %s", RSTRING_PTR(fptr->pathv));
6546  }
6547  else if (fptr->stdio_file == stdout && isatty(fptr->fd)) {
6548  if (setvbuf(fptr->stdio_file, NULL, _IOLBF, BUFSIZ) != 0)
6549  rb_warn("setvbuf() can't be honoured for %s", RSTRING_PTR(fptr->pathv));
6550  }
6551  }
6552  else {
6553  if (close(fptr->fd) < 0)
6554  rb_sys_fail_path(fptr->pathv);
6555  fptr->fd = -1;
6556  fptr->fd = rb_sysopen(fptr->pathv, oflags, 0666);
6557  }
6558 
6559  return file;
6560 }
6561 
6562 /* :nodoc: */
6563 static VALUE
6565 {
6566  rb_io_t *fptr, *orig;
6567  int fd;
6568  VALUE write_io;
6569  off_t pos;
6570 
6571  io = rb_io_get_io(io);
6572  if (!OBJ_INIT_COPY(dest, io)) return dest;
6573  GetOpenFile(io, orig);
6574  MakeOpenFile(dest, fptr);
6575 
6576  rb_io_flush(io);
6577 
6578  /* copy rb_io_t structure */
6579  fptr->mode = orig->mode & ~FMODE_PREP;
6580  fptr->encs = orig->encs;
6581  fptr->pid = orig->pid;
6582  fptr->lineno = orig->lineno;
6583  if (!NIL_P(orig->pathv)) fptr->pathv = orig->pathv;
6584  fptr->finalize = orig->finalize;
6585 #if defined (__CYGWIN__) || !defined(HAVE_FORK)
6586  if (fptr->finalize == pipe_finalize)
6587  pipe_add_fptr(fptr);
6588 #endif
6589 
6590  fd = ruby_dup(orig->fd);
6591  fptr->fd = fd;
6592  pos = io_tell(orig);
6593  if (0 <= pos)
6594  io_seek(fptr, pos, SEEK_SET);
6595  if (fptr->mode & FMODE_BINMODE) {
6596  rb_io_binmode(dest);
6597  }
6598 
6599  write_io = GetWriteIO(io);
6600  if (io != write_io) {
6601  write_io = rb_obj_dup(write_io);
6602  fptr->tied_io_for_writing = write_io;
6603  rb_ivar_set(dest, rb_intern("@tied_io_for_writing"), write_io);
6604  }
6605 
6606  return dest;
6607 }
6608 
6609 /*
6610  * call-seq:
6611  * ios.printf(format_string [, obj, ...]) -> nil
6612  *
6613  * Formats and writes to <em>ios</em>, converting parameters under
6614  * control of the format string. See <code>Kernel#sprintf</code>
6615  * for details.
6616  */
6617 
6618 VALUE
6620 {
6621  rb_io_write(out, rb_f_sprintf(argc, argv));
6622  return Qnil;
6623 }
6624 
6625 /*
6626  * call-seq:
6627  * printf(io, string [, obj ... ]) -> nil
6628  * printf(string [, obj ... ]) -> nil
6629  *
6630  * Equivalent to:
6631  * io.write(sprintf(string, obj, ...)
6632  * or
6633  * $stdout.write(sprintf(string, obj, ...)
6634  */
6635 
6636 static VALUE
6638 {
6639  VALUE out;
6640 
6641  if (argc == 0) return Qnil;
6642  if (RB_TYPE_P(argv[0], T_STRING)) {
6643  out = rb_stdout;
6644  }
6645  else {
6646  out = argv[0];
6647  argv++;
6648  argc--;
6649  }
6650  rb_io_write(out, rb_f_sprintf(argc, argv));
6651 
6652  return Qnil;
6653 }
6654 
6655 /*
6656  * call-seq:
6657  * ios.print() -> nil
6658  * ios.print(obj, ...) -> nil
6659  *
6660  * Writes the given object(s) to <em>ios</em>. The stream must be
6661  * opened for writing. If the output field separator (<code>$,</code>)
6662  * is not <code>nil</code>, it will be inserted between each object.
6663  * If the output record separator (<code>$\</code>)
6664  * is not <code>nil</code>, it will be appended to the output. If no
6665  * arguments are given, prints <code>$_</code>. Objects that aren't
6666  * strings will be converted by calling their <code>to_s</code> method.
6667  * With no argument, prints the contents of the variable <code>$_</code>.
6668  * Returns <code>nil</code>.
6669  *
6670  * $stdout.print("This is ", 100, " percent.\n")
6671  *
6672  * <em>produces:</em>
6673  *
6674  * This is 100 percent.
6675  */
6676 
6677 VALUE
6679 {
6680  int i;
6681  VALUE line;
6682 
6683  /* if no argument given, print `$_' */
6684  if (argc == 0) {
6685  argc = 1;
6686  line = rb_lastline_get();
6687  argv = &line;
6688  }
6689  for (i=0; i<argc; i++) {
6690  if (!NIL_P(rb_output_fs) && i>0) {
6691  rb_io_write(out, rb_output_fs);
6692  }
6693  rb_io_write(out, argv[i]);
6694  }
6695  if (argc > 0 && !NIL_P(rb_output_rs)) {
6696  rb_io_write(out, rb_output_rs);
6697  }
6698 
6699  return Qnil;
6700 }
6701 
6702 /*
6703  * call-seq:
6704  * print(obj, ...) -> nil
6705  *
6706  * Prints each object in turn to <code>$stdout</code>. If the output
6707  * field separator (<code>$,</code>) is not +nil+, its
6708  * contents will appear between each field. If the output record
6709  * separator (<code>$\</code>) is not +nil+, it will be
6710  * appended to the output. If no arguments are given, prints
6711  * <code>$_</code>. Objects that aren't strings will be converted by
6712  * calling their <code>to_s</code> method.
6713  *
6714  * print "cat", [1,2,3], 99, "\n"
6715  * $, = ", "
6716  * $\ = "\n"
6717  * print "cat", [1,2,3], 99
6718  *
6719  * <em>produces:</em>
6720  *
6721  * cat12399
6722  * cat, 1, 2, 3, 99
6723  */
6724 
6725 static VALUE
6727 {
6728  rb_io_print(argc, argv, rb_stdout);
6729  return Qnil;
6730 }
6731 
6732 /*
6733  * call-seq:
6734  * ios.putc(obj) -> obj
6735  *
6736  * If <i>obj</i> is <code>Numeric</code>, write the character whose code is
6737  * the least-significant byte of <i>obj</i>, otherwise write the first byte
6738  * of the string representation of <i>obj</i> to <em>ios</em>. Note: This
6739  * method is not safe for use with multi-byte characters as it will truncate
6740  * them.
6741  *
6742  * $stdout.putc "A"
6743  * $stdout.putc 65
6744  *
6745  * <em>produces:</em>
6746  *
6747  * AA
6748  */
6749 
6750 static VALUE
6752 {
6753  VALUE str;
6754  if (RB_TYPE_P(ch, T_STRING)) {
6755  str = rb_str_substr(ch, 0, 1);
6756  }
6757  else {
6758  char c = NUM2CHR(ch);
6759  str = rb_str_new(&c, 1);
6760  }
6761  rb_io_write(io, str);
6762  return ch;
6763 }
6764 
6765 /*
6766  * call-seq:
6767  * putc(int) -> int
6768  *
6769  * Equivalent to:
6770  *
6771  * $stdout.putc(int)
6772  *
6773  * Refer to the documentation for IO#putc for important information regarding
6774  * multi-byte characters.
6775  */
6776 
6777 static VALUE
6779 {
6780  if (recv == rb_stdout) {
6781  return rb_io_putc(recv, ch);
6782  }
6783  return rb_funcall2(rb_stdout, rb_intern("putc"), 1, &ch);
6784 }
6785 
6786 
6787 static int
6789 {
6790  long len = RSTRING_LEN(str);
6791  const char *ptr = RSTRING_PTR(str);
6793  int n;
6794 
6795  if (len == 0) return 0;
6796  if ((n = rb_enc_mbminlen(enc)) == 1) {
6797  return ptr[len - 1] == c;
6798  }
6799  return rb_enc_ascget(ptr + ((len - 1) / n) * n, ptr + len, &n, enc) == c;
6800 }
6801 
6802 static VALUE
6804 {
6805  VALUE tmp;
6806  long i;
6807 
6808  if (recur) {
6809  tmp = rb_str_new2("[...]");
6810  rb_io_puts(1, &tmp, out);
6811  return Qtrue;
6812  }
6813  ary = rb_check_array_type(ary);
6814  if (NIL_P(ary)) return Qfalse;
6815  for (i=0; i<RARRAY_LEN(ary); i++) {
6816  tmp = RARRAY_PTR(ary)[i];
6817  rb_io_puts(1, &tmp, out);
6818  }
6819  return Qtrue;
6820 }
6821 
6822 /*
6823  * call-seq:
6824  * ios.puts(obj, ...) -> nil
6825  *
6826  * Writes the given objects to <em>ios</em> as with
6827  * <code>IO#print</code>. Writes a record separator (typically a
6828  * newline) after any that do not already end with a newline sequence.
6829  * If called with an array argument, writes each element on a new line.
6830  * If called without arguments, outputs a single record separator.
6831  *
6832  * $stdout.puts("this", "is", "a", "test")
6833  *
6834  * <em>produces:</em>
6835  *
6836  * this
6837  * is
6838  * a
6839  * test
6840  */
6841 
6842 VALUE
6844 {
6845  int i;
6846  VALUE line;
6847 
6848  /* if no argument given, print newline. */
6849  if (argc == 0) {
6850  rb_io_write(out, rb_default_rs);
6851  return Qnil;
6852  }
6853  for (i=0; i<argc; i++) {
6854  if (RB_TYPE_P(argv[i], T_STRING)) {
6855  line = argv[i];
6856  goto string;
6857  }
6858  if (rb_exec_recursive(io_puts_ary, argv[i], out)) {
6859  continue;
6860  }
6861  line = rb_obj_as_string(argv[i]);
6862  string:
6863  rb_io_write(out, line);
6864  if (RSTRING_LEN(line) == 0 ||
6865  !str_end_with_asciichar(line, '\n')) {
6866  rb_io_write(out, rb_default_rs);
6867  }
6868  }
6869 
6870  return Qnil;
6871 }
6872 
6873 /*
6874  * call-seq:
6875  * puts(obj, ...) -> nil
6876  *
6877  * Equivalent to
6878  *
6879  * $stdout.puts(obj, ...)
6880  */
6881 
6882 static VALUE
6884 {
6885  if (recv == rb_stdout) {
6886  return rb_io_puts(argc, argv, recv);
6887  }
6888  return rb_funcall2(rb_stdout, rb_intern("puts"), argc, argv);
6889 }
6890 
6891 void
6892 rb_p(VALUE obj) /* for debug print within C code */
6893 {
6894  VALUE str = rb_obj_as_string(rb_inspect(obj));
6895  if (RB_TYPE_P(rb_stdout, T_FILE) &&
6897  io_write(rb_stdout, str, 1);
6899  }
6900  else {
6901  rb_io_write(rb_stdout, str);
6903  }
6904 }
6905 
6906 struct rb_f_p_arg {
6907  int argc;
6909 };
6910 
6911 static VALUE
6913 {
6914  struct rb_f_p_arg *arg1 = (struct rb_f_p_arg*)arg;
6915  int argc = arg1->argc;
6916  VALUE *argv = arg1->argv;
6917  int i;
6918  VALUE ret = Qnil;
6919 
6920  for (i=0; i<argc; i++) {
6921  rb_p(argv[i]);
6922  }
6923  if (argc == 1) {
6924  ret = argv[0];
6925  }
6926  else if (argc > 1) {
6927  ret = rb_ary_new4(argc, argv);
6928  }
6929  if (RB_TYPE_P(rb_stdout, T_FILE)) {
6931  }
6932  return ret;
6933 }
6934 
6935 /*
6936  * call-seq:
6937  * p(obj) -> obj
6938  * p(obj1, obj2, ...) -> [obj, ...]
6939  * p() -> nil
6940  *
6941  * For each object, directly writes _obj_.+inspect+ followed by a
6942  * newline to the program's standard output.
6943  *
6944  * S = Struct.new(:name, :state)
6945  * s = S['dave', 'TX']
6946  * p s
6947  *
6948  * <em>produces:</em>
6949  *
6950  * #<S name="dave", state="TX">
6951  */
6952 
6953 static VALUE
6955 {
6956  struct rb_f_p_arg arg;
6957  arg.argc = argc;
6958  arg.argv = argv;
6959 
6960  return rb_uninterruptible(rb_f_p_internal, (VALUE)&arg);
6961 }
6962 
6963 /*
6964  * call-seq:
6965  * obj.display(port=$>) -> nil
6966  *
6967  * Prints <i>obj</i> on the given port (default <code>$></code>).
6968  * Equivalent to:
6969  *
6970  * def display(port=$>)
6971  * port.write self
6972  * end
6973  *
6974  * For example:
6975  *
6976  * 1.display
6977  * "cat".display
6978  * [ 4, 5, 6 ].display
6979  * puts
6980  *
6981  * <em>produces:</em>
6982  *
6983  * 1cat456
6984  */
6985 
6986 static VALUE
6988 {
6989  VALUE out;
6990 
6991  if (argc == 0) {
6992  out = rb_stdout;
6993  }
6994  else {
6995  rb_scan_args(argc, argv, "01", &out);
6996  }
6997  rb_io_write(out, self);
6998 
6999  return Qnil;
7000 }
7001 
7002 void
7003 rb_write_error2(const char *mesg, long len)
7004 {
7005  if (rb_stderr == orig_stderr || RFILE(orig_stderr)->fptr->fd < 0) {
7006  if (fwrite(mesg, sizeof(char), (size_t)len, stderr) < (size_t)len) {
7007  /* failed to write to stderr, what can we do? */
7008  return;
7009  }
7010  }
7011  else {
7012  rb_io_write(rb_stderr, rb_str_new(mesg, len));
7013  }
7014 }
7015 
7016 void
7017 rb_write_error(const char *mesg)
7018 {
7019  rb_write_error2(mesg, strlen(mesg));
7020 }
7021 
7022 void
7024 {
7025  /* a stopgap measure for the time being */
7026  if (rb_stderr == orig_stderr || RFILE(orig_stderr)->fptr->fd < 0) {
7027  size_t len = (size_t)RSTRING_LEN(mesg);
7028  if (fwrite(RSTRING_PTR(mesg), sizeof(char), len, stderr) < len) {
7029  RB_GC_GUARD(mesg);
7030  return;
7031  }
7032  }
7033  else {
7034  /* may unlock GVL, and */
7035  rb_io_write(rb_stderr, mesg);
7036  }
7037 }
7038 
7039 static void
7041 {
7042  if (!rb_respond_to(val, mid)) {
7043  rb_raise(rb_eTypeError, "%s must have %s method, %s given",
7044  rb_id2name(id), rb_id2name(mid),
7045  rb_obj_classname(val));
7046  }
7047 }
7048 
7049 static void
7050 stdout_setter(VALUE val, ID id, VALUE *variable)
7051 {
7052  must_respond_to(id_write, val, id);
7053  *variable = val;
7054 }
7055 
7056 static VALUE
7057 prep_io(int fd, int fmode, VALUE klass, const char *path)
7058 {
7059  rb_io_t *fp;
7060  VALUE io = io_alloc(klass);
7061 
7062  MakeOpenFile(io, fp);
7063  fp->fd = fd;
7064 #ifdef __CYGWIN__
7065  if (!isatty(fd)) {
7066  fmode |= FMODE_BINMODE;
7067  setmode(fd, O_BINARY);
7068  }
7069 #endif
7070  fp->mode = fmode;
7071  io_check_tty(fp);
7072  if (path) fp->pathv = rb_obj_freeze(rb_str_new_cstr(path));
7073  rb_update_max_fd(fd);
7074 
7075  return io;
7076 }
7077 
7078 VALUE
7079 rb_io_fdopen(int fd, int oflags, const char *path)
7080 {
7081  VALUE klass = rb_cIO;
7082 
7083  if (path && strcmp(path, "-")) klass = rb_cFile;
7084  return prep_io(fd, rb_io_oflags_fmode(oflags), klass, path);
7085 }
7086 
7087 static VALUE
7088 prep_stdio(FILE *f, int fmode, VALUE klass, const char *path)
7089 {
7090  rb_io_t *fptr;
7091  VALUE io = prep_io(fileno(f), fmode|FMODE_PREP|DEFAULT_TEXTMODE, klass, path);
7092 
7093  GetOpenFile(io, fptr);
7095 #ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE
7096  fptr->encs.ecflags |= TEXTMODE_NEWLINE_DECORATOR_ON_WRITE;
7097  if (fmode & FMODE_READABLE) {
7099  }
7100 #endif
7101  fptr->stdio_file = f;
7102 
7103  return io;
7104 }
7105 
7106 FILE *
7108 {
7109  if (!fptr->stdio_file) {
7110  int oflags = rb_io_fmode_oflags(fptr->mode);
7111  fptr->stdio_file = rb_fdopen(fptr->fd, rb_io_oflags_modestr(oflags));
7112  }
7113  return fptr->stdio_file;
7114 }
7115 
7116 /*
7117  * call-seq:
7118  * IO.new(fd [, mode] [, opt]) -> io
7119  *
7120  * Returns a new IO object (a stream) for the given integer file descriptor
7121  * +fd+ and +mode+ string. +opt+ may be used to specify parts of +mode+ in a
7122  * more readable fashion. See also IO.sysopen and IO.for_fd.
7123  *
7124  * IO.new is called by various File and IO opening methods such as IO::open,
7125  * Kernel#open, and File::open.
7126  *
7127  * === Open Mode
7128  *
7129  * When +mode+ is an integer it must be combination of the modes defined in
7130  * File::Constants (+File::RDONLY+, +File::WRONLY | File::CREAT+). See the
7131  * open(2) man page for more information.
7132  *
7133  * When +mode+ is a string it must be in one of the following forms:
7134  *
7135  * fmode
7136  * fmode ":" ext_enc
7137  * fmode ":" ext_enc ":" int_enc
7138  * fmode ":" "BOM|UTF-*"
7139  *
7140  * +fmode+ is an IO open mode string, +ext_enc+ is the external encoding for
7141  * the IO and +int_enc+ is the internal encoding.
7142  *
7143  * ==== IO Open Mode
7144  *
7145  * Ruby allows the following open modes:
7146  *
7147  * "r" Read-only, starts at beginning of file (default mode).
7148  *
7149  * "r+" Read-write, starts at beginning of file.
7150  *
7151  * "w" Write-only, truncates existing file
7152  * to zero length or creates a new file for writing.
7153  *
7154  * "w+" Read-write, truncates existing file to zero length
7155  * or creates a new file for reading and writing.
7156  *
7157  * "a" Write-only, starts at end of file if file exists,
7158  * otherwise creates a new file for writing.
7159  *
7160  * "a+" Read-write, starts at end of file if file exists,
7161  * otherwise creates a new file for reading and
7162  * writing.
7163  *
7164  * The following modes must be used separately, and along with one or more of
7165  * the modes seen above.
7166  *
7167  * "b" Binary file mode
7168  * Suppresses EOL <-> CRLF conversion on Windows. And
7169  * sets external encoding to ASCII-8BIT unless explicitly
7170  * specified.
7171  *
7172  * "t" Text file mode
7173  *
7174  * When the open mode of original IO is read only, the mode cannot be
7175  * changed to be writable. Similarly, the open mode cannot be changed from
7176  * write only to readable.
7177  *
7178  * When such a change is attempted the error is raised in different locations
7179  * according to the platform.
7180  *
7181  * === IO Encoding
7182  *
7183  * When +ext_enc+ is specified, strings read will be tagged by the encoding
7184  * when reading, and strings output will be converted to the specified
7185  * encoding when writing.
7186  *
7187  * When +ext_enc+ and +int_enc+ are specified read strings will be converted
7188  * from +ext_enc+ to +int_enc+ upon input, and written strings will be
7189  * converted from +int_enc+ to +ext_enc+ upon output. See Encoding for
7190  * further details of transcoding on input and output.
7191  *
7192  * If "BOM|UTF-8", "BOM|UTF-16LE" or "BOM|UTF16-BE" are used, ruby checks for
7193  * a Unicode BOM in the input document to help determine the encoding. For
7194  * UTF-16 encodings the file open mode must be binary. When present, the BOM
7195  * is stripped and the external encoding from the BOM is used. When the BOM
7196  * is missing the given Unicode encoding is used as +ext_enc+. (The BOM-set
7197  * encoding option is case insensitive, so "bom|utf-8" is also valid.)
7198  *
7199  * === Options
7200  *
7201  * +opt+ can be used instead of +mode+ for improved readability. The
7202  * following keys are supported:
7203  *
7204  * :mode ::
7205  * Same as +mode+ parameter
7206  *
7207  * :\external_encoding ::
7208  * External encoding for the IO. "-" is a synonym for the default external
7209  * encoding.
7210  *
7211  * :\internal_encoding ::
7212  * Internal encoding for the IO. "-" is a synonym for the default internal
7213  * encoding.
7214  *
7215  * If the value is nil no conversion occurs.
7216  *
7217  * :encoding ::
7218  * Specifies external and internal encodings as "extern:intern".
7219  *
7220  * :textmode ::
7221  * If the value is truth value, same as "t" in argument +mode+.
7222  *
7223  * :binmode ::
7224  * If the value is truth value, same as "b" in argument +mode+.
7225  *
7226  * :autoclose ::
7227  * If the value is +false+, the +fd+ will be kept open after this IO
7228  * instance gets finalized.
7229  *
7230  * Also, +opt+ can have same keys in String#encode for controlling conversion
7231  * between the external encoding and the internal encoding.
7232  *
7233  * === Example 1
7234  *
7235  * fd = IO.sysopen("/dev/tty", "w")
7236  * a = IO.new(fd,"w")
7237  * $stderr.puts "Hello"
7238  * a.puts "World"
7239  *
7240  * Produces:
7241  *
7242  * Hello
7243  * World
7244  *
7245  * === Example 2
7246  *
7247  * require 'fcntl'
7248  *
7249  * fd = STDERR.fcntl(Fcntl::F_DUPFD)
7250  * io = IO.new(fd, mode: 'w:UTF-16LE', cr_newline: true)
7251  * io.puts "Hello, World!"
7252  *
7253  * fd = STDERR.fcntl(Fcntl::F_DUPFD)
7254  * io = IO.new(fd, mode: 'w', cr_newline: true,
7255  * external_encoding: Encoding::UTF_16LE)
7256  * io.puts "Hello, World!"
7257  *
7258  * Both of above print "Hello, World!" in UTF-16LE to standard error output
7259  * with converting EOL generated by <code>puts</code> to CR.
7260  */
7261 
7262 static VALUE
7264 {
7265  VALUE fnum, vmode;
7266  rb_io_t *fp;
7267  int fd, fmode, oflags = O_RDONLY;
7268  convconfig_t convconfig;
7269  VALUE opt;
7270 #if defined(HAVE_FCNTL) && defined(F_GETFL)
7271  int ofmode;
7272 #else
7273  struct stat st;
7274 #endif
7275 
7276  rb_secure(4);
7277 
7278  argc = rb_scan_args(argc, argv, "11:", &fnum, &vmode, &opt);
7279  rb_io_extract_modeenc(&vmode, 0, opt, &oflags, &fmode, &convconfig);
7280 
7281  fd = NUM2INT(fnum);
7282  if (rb_reserved_fd_p(fd)) {
7283  rb_raise(rb_eArgError, "The given fd is not accessible because RubyVM reserves it");
7284  }
7285 #if defined(HAVE_FCNTL) && defined(F_GETFL)
7286  oflags = fcntl(fd, F_GETFL);
7287  if (oflags == -1) rb_sys_fail(0);
7288 #else
7289  if (fstat(fd, &st) == -1) rb_sys_fail(0);
7290 #endif
7291  rb_update_max_fd(fd);
7292 #if defined(HAVE_FCNTL) && defined(F_GETFL)
7293  ofmode = rb_io_oflags_fmode(oflags);
7294  if (NIL_P(vmode)) {
7295  fmode = ofmode;
7296  }
7297  else if ((~ofmode & fmode) & FMODE_READWRITE) {
7298  VALUE error = INT2FIX(EINVAL);
7300  }
7301 #endif
7302  if (!NIL_P(opt) && rb_hash_aref(opt, sym_autoclose) == Qfalse) {
7303  fmode |= FMODE_PREP;
7304  }
7305  MakeOpenFile(io, fp);
7306  fp->fd = fd;
7307  fp->mode = fmode;
7308  fp->encs = convconfig;
7309  clear_codeconv(fp);
7310  io_check_tty(fp);
7311  if (fileno(stdin) == fd)
7312  fp->stdio_file = stdin;
7313  else if (fileno(stdout) == fd)
7314  fp->stdio_file = stdout;
7315  else if (fileno(stderr) == fd)
7316  fp->stdio_file = stderr;
7317 
7319  return io;
7320 }
7321 
7322 /*
7323  * call-seq:
7324  * File.new(filename, mode="r" [, opt]) -> file
7325  * File.new(filename [, mode [, perm]] [, opt]) -> file
7326  *
7327  * Opens the file named by +filename+ according to the given +mode+ and
7328  * returns a new File object.
7329  *
7330  * See IO.new for a description of +mode+ and +opt+.
7331  *
7332  * If a file is being created, permission bits may be given in +perm+. These
7333  * mode and permission bits are platform dependent; on Unix systems, see
7334  * open(2) and chmod(2) man pages for details.
7335  *
7336  * === Examples
7337  *
7338  * f = File.new("testfile", "r")
7339  * f = File.new("newfile", "w+")
7340  * f = File.new("newfile", File::CREAT|File::TRUNC|File::RDWR, 0644)
7341  */
7342 
7343 static VALUE
7345 {
7346  if (RFILE(io)->fptr) {
7347  rb_raise(rb_eRuntimeError, "reinitializing File");
7348  }
7349  if (0 < argc && argc < 3) {
7350  VALUE fd = rb_check_convert_type(argv[0], T_FIXNUM, "Fixnum", "to_int");
7351 
7352  if (!NIL_P(fd)) {
7353  argv[0] = fd;
7354  return rb_io_initialize(argc, argv, io);
7355  }
7356  }
7357  rb_open_file(argc, argv, io);
7358 
7359  return io;
7360 }
7361 
7362 /* :nodoc: */
7363 static VALUE
7365 {
7366  if (rb_block_given_p()) {
7367  const char *cname = rb_class2name(klass);
7368 
7369  rb_warn("%s::new() does not take block; use %s::open() instead",
7370  cname, cname);
7371  }
7372  return rb_class_new_instance(argc, argv, klass);
7373 }
7374 
7375 
7376 /*
7377  * call-seq:
7378  * IO.for_fd(fd, mode [, opt]) -> io
7379  *
7380  * Synonym for <code>IO.new</code>.
7381  *
7382  */
7383 
7384 static VALUE
7386 {
7387  VALUE io = rb_obj_alloc(klass);
7388  rb_io_initialize(argc, argv, io);
7389  return io;
7390 }
7391 
7392 /*
7393  * call-seq:
7394  * ios.autoclose? -> true or false
7395  *
7396  * Returns +true+ if the underlying file descriptor of _ios_ will be
7397  * closed automatically at its finalization, otherwise +false+.
7398  */
7399 
7400 static VALUE
7402 {
7403  rb_io_t *fptr;
7404  rb_secure(4);
7405  GetOpenFile(io, fptr);
7406  return (fptr->mode & FMODE_PREP) ? Qfalse : Qtrue;
7407 }
7408 
7409 /*
7410  * call-seq:
7411  * io.autoclose = bool -> true or false
7412  *
7413  * Sets auto-close flag.
7414  *
7415  * f = open("/dev/null")
7416  * IO.for_fd(f.fileno)
7417  * # ...
7418  * f.gets # may cause IOError
7419  *
7420  * f = open("/dev/null")
7421  * IO.for_fd(f.fileno).autoclose = true
7422  * # ...
7423  * f.gets # won't cause IOError
7424  */
7425 
7426 static VALUE
7428 {
7429  rb_io_t *fptr;
7430  rb_secure(4);
7431  GetOpenFile(io, fptr);
7432  if (!RTEST(autoclose))
7433  fptr->mode |= FMODE_PREP;
7434  else
7435  fptr->mode &= ~FMODE_PREP;
7436  return io;
7437 }
7438 
7439 static void
7440 argf_mark(void *ptr)
7441 {
7442  struct argf *p = ptr;
7443  rb_gc_mark(p->filename);
7445  rb_gc_mark(p->argv);
7446  rb_gc_mark(p->encs.ecopts);
7447 }
7448 
7449 static void
7450 argf_free(void *ptr)
7451 {
7452  struct argf *p = ptr;
7453  xfree(p->inplace);
7454  xfree(p);
7455 }
7456 
7457 static size_t
7458 argf_memsize(const void *ptr)
7459 {
7460  const struct argf *p = ptr;
7461  size_t size = sizeof(*p);
7462  if (!ptr) return 0;
7463  if (p->inplace) size += strlen(p->inplace) + 1;
7464  return size;
7465 }
7466 
7467 static const rb_data_type_t argf_type = {
7468  "ARGF",
7470 };
7471 
7472 static inline void
7473 argf_init(struct argf *p, VALUE v)
7474 {
7475  p->filename = Qnil;
7476  p->current_file = Qnil;
7477  p->lineno = 0;
7478  p->argv = v;
7479 }
7480 
7481 static VALUE
7483 {
7484  struct argf *p;
7485  VALUE argf = TypedData_Make_Struct(klass, struct argf, &argf_type, p);
7486 
7487  argf_init(p, Qnil);
7488  return argf;
7489 }
7490 
7491 #undef rb_argv
7492 
7493 /* :nodoc: */
7494 static VALUE
7496 {
7497  memset(&ARGF, 0, sizeof(ARGF));
7498  argf_init(&ARGF, argv);
7499 
7500  return argf;
7501 }
7502 
7503 /* :nodoc: */
7504 static VALUE
7506 {
7507  if (!OBJ_INIT_COPY(argf, orig)) return argf;
7508  ARGF = argf_of(orig);
7509  ARGF.argv = rb_obj_dup(ARGF.argv);
7510  if (ARGF.inplace) {
7511  const char *inplace = ARGF.inplace;
7512  ARGF.inplace = 0;
7513  ARGF.inplace = ruby_strdup(inplace);
7514  }
7515  return argf;
7516 }
7517 
7518 /*
7519  * call-seq:
7520  * ARGF.lineno = integer -> integer
7521  *
7522  * Sets the line number of +ARGF+ as a whole to the given +Integer+.
7523  *
7524  * +ARGF+ sets the line number automatically as you read data, so normally
7525  * you will not need to set it explicitly. To access the current line number
7526  * use +ARGF.lineno+.
7527  *
7528  * For example:
7529  *
7530  * ARGF.lineno #=> 0
7531  * ARGF.readline #=> "This is line 1\n"
7532  * ARGF.lineno #=> 1
7533  * ARGF.lineno = 0 #=> 0
7534  * ARGF.lineno #=> 0
7535  */
7536 static VALUE
7538 {
7539  ARGF.lineno = NUM2INT(val);
7540  ARGF.last_lineno = ARGF.lineno;
7541  return Qnil;
7542 }
7543 
7544 /*
7545  * call-seq:
7546  * ARGF.lineno -> integer
7547  *
7548  * Returns the current line number of ARGF as a whole. This value
7549  * can be set manually with +ARGF.lineno=+.
7550  *
7551  * For example:
7552  *
7553  * ARGF.lineno #=> 0
7554  * ARGF.readline #=> "This is line 1\n"
7555  * ARGF.lineno #=> 1
7556  */
7557 static VALUE
7559 {
7560  return INT2FIX(ARGF.lineno);
7561 }
7562 
7563 static VALUE
7565 {
7566  return rb_funcall3(ARGF.current_file, rb_frame_this_func(), argc, argv);
7567 }
7568 
7569 #define next_argv() argf_next_argv(argf)
7570 #define ARGF_GENERIC_INPUT_P() \
7571  (ARGF.current_file == rb_stdin && !RB_TYPE_P(ARGF.current_file, T_FILE))
7572 #define ARGF_FORWARD(argc, argv) do {\
7573  if (ARGF_GENERIC_INPUT_P())\
7574  return argf_forward((argc), (argv), argf);\
7575 } while (0)
7576 #define NEXT_ARGF_FORWARD(argc, argv) do {\
7577  if (!next_argv()) return Qnil;\
7578  ARGF_FORWARD((argc), (argv));\
7579 } while (0)
7580 
7581 static void
7583 {
7584  if (file == rb_stdin) return;
7585  if (RB_TYPE_P(file, T_FILE)) {
7586  rb_io_set_write_io(file, Qnil);
7587  }
7588  rb_funcall3(file, rb_intern("close"), 0, 0);
7589 }
7590 
7591 static int
7593 {
7594  char *fn;
7595  rb_io_t *fptr;
7596  int stdout_binmode = 0;
7597  int fmode;
7598 
7599  if (RB_TYPE_P(rb_stdout, T_FILE)) {
7600  GetOpenFile(rb_stdout, fptr);
7601  if (fptr->mode & FMODE_BINMODE)
7602  stdout_binmode = 1;
7603  }
7604 
7605  if (ARGF.init_p == 0) {
7606  if (!NIL_P(ARGF.argv) && RARRAY_LEN(ARGF.argv) > 0) {
7607  ARGF.next_p = 1;
7608  }
7609  else {
7610  ARGF.next_p = -1;
7611  }
7612  ARGF.init_p = 1;
7613  }
7614  else {
7615  if (NIL_P(ARGF.argv)) {
7616  ARGF.next_p = -1;
7617  }
7618  else if (ARGF.next_p == -1 && RARRAY_LEN(ARGF.argv) > 0) {
7619  ARGF.next_p = 1;
7620  }
7621  }
7622 
7623  if (ARGF.next_p == 1) {
7624  retry:
7625  if (RARRAY_LEN(ARGF.argv) > 0) {
7626  ARGF.filename = rb_ary_shift(ARGF.argv);
7627  fn = StringValueCStr(ARGF.filename);
7628  if (strlen(fn) == 1 && fn[0] == '-') {
7629  ARGF.current_file = rb_stdin;
7630  if (ARGF.inplace) {
7631  rb_warn("Can't do inplace edit for stdio; skipping");
7632  goto retry;
7633  }
7634  }
7635  else {
7636  VALUE write_io = Qnil;
7637  int fr = rb_sysopen(ARGF.filename, O_RDONLY, 0);
7638 
7639  if (ARGF.inplace) {
7640  struct stat st;
7641 #ifndef NO_SAFE_RENAME
7642  struct stat st2;
7643 #endif
7644  VALUE str;
7645  int fw;
7646 
7649  }
7650  fstat(fr, &st);
7651  if (*ARGF.inplace) {
7652  str = rb_str_new2(fn);
7653  rb_str_cat2(str, ARGF.inplace);
7654 #ifdef NO_SAFE_RENAME
7655  (void)close(fr);
7656  (void)unlink(RSTRING_PTR(str));
7657  if (rename(fn, RSTRING_PTR(str)) < 0) {
7658  rb_warn("Can't rename %s to %s: %s, skipping file",
7659  fn, RSTRING_PTR(str), strerror(errno));
7660  goto retry;
7661  }
7662  fr = rb_sysopen(str, O_RDONLY, 0);
7663 #else
7664  if (rename(fn, RSTRING_PTR(str)) < 0) {
7665  rb_warn("Can't rename %s to %s: %s, skipping file",
7666  fn, RSTRING_PTR(str), strerror(errno));
7667  close(fr);
7668  goto retry;
7669  }
7670 #endif
7671  }
7672  else {
7673 #ifdef NO_SAFE_RENAME
7674  rb_fatal("Can't do inplace edit without backup");
7675 #else
7676  if (unlink(fn) < 0) {
7677  rb_warn("Can't remove %s: %s, skipping file",
7678  fn, strerror(errno));
7679  close(fr);
7680  goto retry;
7681  }
7682 #endif
7683  }
7684  fw = rb_sysopen(ARGF.filename, O_WRONLY|O_CREAT|O_TRUNC, 0666);
7685 #ifndef NO_SAFE_RENAME
7686  fstat(fw, &st2);
7687 #ifdef HAVE_FCHMOD
7688  fchmod(fw, st.st_mode);
7689 #else
7690  chmod(fn, st.st_mode);
7691 #endif
7692  if (st.st_uid!=st2.st_uid || st.st_gid!=st2.st_gid) {
7693  int err;
7694 #ifdef HAVE_FCHOWN
7695  err = fchown(fw, st.st_uid, st.st_gid);
7696 #else
7697  err = chown(fn, st.st_uid, st.st_gid);
7698 #endif
7699  if (err && getuid() == 0 && st2.st_uid == 0) {
7700  const char *wkfn = RSTRING_PTR(ARGF.filename);
7701  rb_warn("Can't set owner/group of %s to same as %s: %s, skipping file",
7702  wkfn, fn, strerror(errno));
7703  (void)close(fr);
7704  (void)close(fw);
7705  (void)unlink(wkfn);
7706  goto retry;
7707  }
7708  }
7709 #endif
7710  write_io = prep_io(fw, FMODE_WRITABLE, rb_cFile, fn);
7711  rb_stdout = write_io;
7712  if (stdout_binmode) rb_io_binmode(rb_stdout);
7713  }
7714  fmode = FMODE_READABLE;
7715  if (!ARGF.binmode) {
7716  fmode |= DEFAULT_TEXTMODE;
7717  }
7718  ARGF.current_file = prep_io(fr, fmode, rb_cFile, fn);
7719  if (!NIL_P(write_io)) {
7720  rb_io_set_write_io(ARGF.current_file, write_io);
7721  }
7722  }
7723  if (ARGF.binmode) rb_io_ascii8bit_binmode(ARGF.current_file);
7724  GetOpenFile(ARGF.current_file, fptr);
7725  if (ARGF.encs.enc) {
7726  fptr->encs = ARGF.encs;
7727  clear_codeconv(fptr);
7728  }
7729  else {
7731  if (!ARGF.binmode) {
7733 #ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE
7734  fptr->encs.ecflags |= TEXTMODE_NEWLINE_DECORATOR_ON_WRITE;
7735 #endif
7736  }
7737  }
7738  ARGF.next_p = 0;
7739  }
7740  else {
7741  ARGF.next_p = 1;
7742  return FALSE;
7743  }
7744  }
7745  else if (ARGF.next_p == -1) {
7746  ARGF.current_file = rb_stdin;
7747  ARGF.filename = rb_str_new2("-");
7748  if (ARGF.inplace) {
7749  rb_warn("Can't do inplace edit for stdio");
7751  }
7752  }
7753  return TRUE;
7754 }
7755 
7756 static VALUE
7758 {
7759  VALUE line;
7760  long lineno = ARGF.lineno;
7761 
7762  retry:
7763  if (!next_argv()) return Qnil;
7764  if (ARGF_GENERIC_INPUT_P()) {
7765  line = rb_funcall3(ARGF.current_file, idGets, argc, argv);
7766  }
7767  else {
7768  if (argc == 0 && rb_rs == rb_default_rs) {
7769  line = rb_io_gets(ARGF.current_file);
7770  }
7771  else {
7772  line = rb_io_getline(argc, argv, ARGF.current_file);
7773  }
7774  if (NIL_P(line) && ARGF.next_p != -1) {
7775  argf_close(ARGF.current_file);
7776  ARGF.next_p = 1;
7777  goto retry;
7778  }
7779  }
7780  if (!NIL_P(line)) {
7781  ARGF.lineno = ++lineno;
7782  ARGF.last_lineno = ARGF.lineno;
7783  }
7784  return line;
7785 }
7786 
7787 static VALUE
7789 {
7790  VALUE argf = *var;
7791  return INT2FIX(ARGF.last_lineno);
7792 }
7793 
7794 static void
7796 {
7797  VALUE argf = *var;
7798  int n = NUM2INT(val);
7799  ARGF.last_lineno = ARGF.lineno = n;
7800 }
7801 
7802 static VALUE argf_gets(int, VALUE *, VALUE);
7803 
7804 /*
7805  * call-seq:
7806  * gets(sep=$/) -> string or nil
7807  * gets(limit) -> string or nil
7808  * gets(sep,limit) -> string or nil
7809  *
7810  * Returns (and assigns to <code>$_</code>) the next line from the list
7811  * of files in +ARGV+ (or <code>$*</code>), or from standard input if
7812  * no files are present on the command line. Returns +nil+ at end of
7813  * file. The optional argument specifies the record separator. The
7814  * separator is included with the contents of each record. A separator
7815  * of +nil+ reads the entire contents, and a zero-length separator
7816  * reads the input one paragraph at a time, where paragraphs are
7817  * divided by two consecutive newlines. If the first argument is an
7818  * integer, or optional second argument is given, the returning string
7819  * would not be longer than the given value in bytes. If multiple
7820  * filenames are present in +ARGV+, +gets(nil)+ will read the contents
7821  * one file at a time.
7822  *
7823  * ARGV << "testfile"
7824  * print while gets
7825  *
7826  * <em>produces:</em>
7827  *
7828  * This is line one
7829  * This is line two
7830  * This is line three
7831  * And so on...
7832  *
7833  * The style of programming using <code>$_</code> as an implicit
7834  * parameter is gradually losing favor in the Ruby community.
7835  */
7836 
7837 static VALUE
7839 {
7840  if (recv == argf) {
7841  return argf_gets(argc, argv, argf);
7842  }
7843  return rb_funcall2(argf, idGets, argc, argv);
7844 }
7845 
7846 /*
7847  * call-seq:
7848  * ARGF.gets(sep=$/) -> string
7849  * ARGF.gets(limit) -> string
7850  * ARGF.gets(sep, limit) -> string
7851  *
7852  * Returns the next line from the current file in +ARGF+.
7853  *
7854  * By default lines are assumed to be separated by +$/+; to use a different
7855  * character as a separator, supply it as a +String+ for the _sep_ argument.
7856  *
7857  * The optional _limit_ argument specifies how many characters of each line
7858  * to return. By default all characters are returned.
7859  *
7860  */
7861 static VALUE
7863 {
7864  VALUE line;
7865 
7866  line = argf_getline(argc, argv, argf);
7867  rb_lastline_set(line);
7868 
7869  return line;
7870 }
7871 
7872 VALUE
7873 rb_gets(void)
7874 {
7875  VALUE line;
7876 
7877  if (rb_rs != rb_default_rs) {
7878  return rb_f_gets(0, 0, argf);
7879  }
7880 
7881  retry:
7882  if (!next_argv()) return Qnil;
7883  line = rb_io_gets(ARGF.current_file);
7884  if (NIL_P(line) && ARGF.next_p != -1) {
7885  rb_io_close(ARGF.current_file);
7886  ARGF.next_p = 1;
7887  goto retry;
7888  }
7889  rb_lastline_set(line);
7890  if (!NIL_P(line)) {
7891  ARGF.lineno++;
7892  ARGF.last_lineno = ARGF.lineno;
7893  }
7894 
7895  return line;
7896 }
7897 
7898 static VALUE argf_readline(int, VALUE *, VALUE);
7899 
7900 /*
7901  * call-seq:
7902  * readline(sep=$/) -> string
7903  * readline(limit) -> string
7904  * readline(sep, limit) -> string
7905  *
7906  * Equivalent to <code>Kernel::gets</code>, except
7907  * +readline+ raises +EOFError+ at end of file.
7908  */
7909 
7910 static VALUE
7912 {
7913  if (recv == argf) {
7914  return argf_readline(argc, argv, argf);
7915  }
7916  return rb_funcall2(argf, rb_intern("readline"), argc, argv);
7917 }
7918 
7919 
7920 /*
7921  * call-seq:
7922  * ARGF.readline(sep=$/) -> string
7923  * ARGF.readline(limit) -> string
7924  * ARGF.readline(sep, limit) -> string
7925  *
7926  * Returns the next line from the current file in +ARGF+.
7927  *
7928  * By default lines are assumed to be separated by +$/+; to use a different
7929  * character as a separator, supply it as a +String+ for the _sep_ argument.
7930  *
7931  * The optional _limit_ argument specifies how many characters of each line
7932  * to return. By default all characters are returned.
7933  *
7934  * An +EOFError+ is raised at the end of the file.
7935  */
7936 static VALUE
7938 {
7939  VALUE line;
7940 
7941  if (!next_argv()) rb_eof_error();
7942  ARGF_FORWARD(argc, argv);
7943  line = argf_gets(argc, argv, argf);
7944  if (NIL_P(line)) {
7945  rb_eof_error();
7946  }
7947 
7948  return line;
7949 }
7950 
7951 static VALUE argf_readlines(int, VALUE *, VALUE);
7952 
7953 /*
7954  * call-seq:
7955  * readlines(sep=$/) -> array
7956  * readlines(limit) -> array
7957  * readlines(sep,limit) -> array
7958  *
7959  * Returns an array containing the lines returned by calling
7960  * <code>Kernel.gets(<i>sep</i>)</code> until the end of file.
7961  */
7962 
7963 static VALUE
7965 {
7966  if (recv == argf) {
7967  return argf_readlines(argc, argv, argf);
7968  }
7969  return rb_funcall2(argf, rb_intern("readlines"), argc, argv);
7970 }
7971 
7972 /*
7973  * call-seq:
7974  * ARGF.readlines(sep=$/) -> array
7975  * ARGF.readlines(limit) -> array
7976  * ARGF.readlines(sep, limit) -> array
7977  *
7978  * ARGF.to_a(sep=$/) -> array
7979  * ARGF.to_a(limit) -> array
7980  * ARGF.to_a(sep, limit) -> array
7981  *
7982  * Reads +ARGF+'s current file in its entirety, returning an +Array+ of its
7983  * lines, one line per element. Lines are assumed to be separated by _sep_.
7984  *
7985  * lines = ARGF.readlines
7986  * lines[0] #=> "This is line one\n"
7987  */
7988 static VALUE
7990 {
7991  long lineno = ARGF.lineno;
7992  VALUE lines, ary;
7993 
7994  ary = rb_ary_new();
7995  while (next_argv()) {
7996  if (ARGF_GENERIC_INPUT_P()) {
7997  lines = rb_funcall3(ARGF.current_file, rb_intern("readlines"), argc, argv);
7998  }
7999  else {
8000  lines = rb_io_readlines(argc, argv, ARGF.current_file);
8001  argf_close(ARGF.current_file);
8002  }
8003  ARGF.next_p = 1;
8004  rb_ary_concat(ary, lines);
8005  ARGF.lineno = lineno + RARRAY_LEN(ary);
8006  ARGF.last_lineno = ARGF.lineno;
8007  }
8008  ARGF.init_p = 0;
8009  return ary;
8010 }
8011 
8012 /*
8013  * call-seq:
8014  * `cmd` -> string
8015  *
8016  * Returns the standard output of running _cmd_ in a subshell.
8017  * The built-in syntax <code>%x{...}</code> uses
8018  * this method. Sets <code>$?</code> to the process status.
8019  *
8020  * `date` #=> "Wed Apr 9 08:56:30 CDT 2003\n"
8021  * `ls testdir`.split[1] #=> "main.rb"
8022  * `echo oops && exit 99` #=> "oops\n"
8023  * $?.exitstatus #=> 99
8024  */
8025 
8026 static VALUE
8028 {
8029  volatile VALUE port;
8030  VALUE result;
8031  rb_io_t *fptr;
8032 
8033  SafeStringValue(str);
8035  port = pipe_open_s(str, "r", FMODE_READABLE|DEFAULT_TEXTMODE, NULL);
8036  if (NIL_P(port)) return rb_str_new(0,0);
8037 
8038  GetOpenFile(port, fptr);
8039  result = read_all(fptr, remain_size(fptr), Qnil);
8040  rb_io_close(port);
8041 
8042  return result;
8043 }
8044 
8045 #ifdef HAVE_SYS_SELECT_H
8046 #include <sys/select.h>
8047 #endif
8048 
8049 static VALUE
8050 select_internal(VALUE read, VALUE write, VALUE except, struct timeval *tp, rb_fdset_t *fds)
8051 {
8052  VALUE res, list;
8053  rb_fdset_t *rp, *wp, *ep;
8054  rb_io_t *fptr;
8055  long i;
8056  int max = 0, n;
8057  int pending = 0;
8058  struct timeval timerec;
8059 
8060  if (!NIL_P(read)) {
8061  Check_Type(read, T_ARRAY);
8062  for (i=0; i<RARRAY_LEN(read); i++) {
8063  GetOpenFile(rb_io_get_io(RARRAY_PTR(read)[i]), fptr);
8064  rb_fd_set(fptr->fd, &fds[0]);
8065  if (READ_DATA_PENDING(fptr) || READ_CHAR_PENDING(fptr)) { /* check for buffered data */
8066  pending++;
8067  rb_fd_set(fptr->fd, &fds[3]);
8068  }
8069  if (max < fptr->fd) max = fptr->fd;
8070  }
8071  if (pending) { /* no blocking if there's buffered data */
8072  timerec.tv_sec = timerec.tv_usec = 0;
8073  tp = &timerec;
8074  }
8075  rp = &fds[0];
8076  }
8077  else
8078  rp = 0;
8079 
8080  if (!NIL_P(write)) {
8081  Check_Type(write, T_ARRAY);
8082  for (i=0; i<RARRAY_LEN(write); i++) {
8083  VALUE write_io = GetWriteIO(rb_io_get_io(RARRAY_PTR(write)[i]));
8084  GetOpenFile(write_io, fptr);
8085  rb_fd_set(fptr->fd, &fds[1]);
8086  if (max < fptr->fd) max = fptr->fd;
8087  }
8088  wp = &fds[1];
8089  }
8090  else
8091  wp = 0;
8092 
8093  if (!NIL_P(except)) {
8094  Check_Type(except, T_ARRAY);
8095  for (i=0; i<RARRAY_LEN(except); i++) {
8096  VALUE io = rb_io_get_io(RARRAY_PTR(except)[i]);
8097  VALUE write_io = GetWriteIO(io);
8098  GetOpenFile(io, fptr);
8099  rb_fd_set(fptr->fd, &fds[2]);
8100  if (max < fptr->fd) max = fptr->fd;
8101  if (io != write_io) {
8102  GetOpenFile(write_io, fptr);
8103  rb_fd_set(fptr->fd, &fds[2]);
8104  if (max < fptr->fd) max = fptr->fd;
8105  }
8106  }
8107  ep = &fds[2];
8108  }
8109  else {
8110  ep = 0;
8111  }
8112 
8113  max++;
8114 
8115  n = rb_thread_fd_select(max, rp, wp, ep, tp);
8116  if (n < 0) {
8117  rb_sys_fail(0);
8118  }
8119  if (!pending && n == 0) return Qnil; /* returns nil on timeout */
8120 
8121  res = rb_ary_new2(3);
8122  rb_ary_push(res, rp?rb_ary_new():rb_ary_new2(0));
8123  rb_ary_push(res, wp?rb_ary_new():rb_ary_new2(0));
8124  rb_ary_push(res, ep?rb_ary_new():rb_ary_new2(0));
8125 
8126  if (rp) {
8127  list = RARRAY_PTR(res)[0];
8128  for (i=0; i< RARRAY_LEN(read); i++) {
8129  VALUE obj = rb_ary_entry(read, i);
8130  VALUE io = rb_io_get_io(obj);
8131  GetOpenFile(io, fptr);
8132  if (rb_fd_isset(fptr->fd, &fds[0]) ||
8133  rb_fd_isset(fptr->fd, &fds[3])) {
8134  rb_ary_push(list, obj);
8135  }
8136  }
8137  }
8138 
8139  if (wp) {
8140  list = RARRAY_PTR(res)[1];
8141  for (i=0; i< RARRAY_LEN(write); i++) {
8142  VALUE obj = rb_ary_entry(write, i);
8143  VALUE io = rb_io_get_io(obj);
8144  VALUE write_io = GetWriteIO(io);
8145  GetOpenFile(write_io, fptr);
8146  if (rb_fd_isset(fptr->fd, &fds[1])) {
8147  rb_ary_push(list, obj);
8148  }
8149  }
8150  }
8151 
8152  if (ep) {
8153  list = RARRAY_PTR(res)[2];
8154  for (i=0; i< RARRAY_LEN(except); i++) {
8155  VALUE obj = rb_ary_entry(except, i);
8156  VALUE io = rb_io_get_io(obj);
8157  VALUE write_io = GetWriteIO(io);
8158  GetOpenFile(io, fptr);
8159  if (rb_fd_isset(fptr->fd, &fds[2])) {
8160  rb_ary_push(list, obj);
8161  }
8162  else if (io != write_io) {
8163  GetOpenFile(write_io, fptr);
8164  if (rb_fd_isset(fptr->fd, &fds[2])) {
8165  rb_ary_push(list, obj);
8166  }
8167  }
8168  }
8169  }
8170 
8171  return res; /* returns an empty array on interrupt */
8172 }
8173 
8174 struct select_args {
8176  struct timeval *timeout;
8178 };
8179 
8180 static VALUE
8182 {
8183  struct select_args *p = (struct select_args *)arg;
8184 
8185  return select_internal(p->read, p->write, p->except, p->timeout, p->fdsets);
8186 }
8187 
8188 static VALUE
8190 {
8191  struct select_args *p = (struct select_args *)arg;
8192  int i;
8193 
8194  for (i = 0; i < numberof(p->fdsets); ++i)
8195  rb_fd_term(&p->fdsets[i]);
8196  return Qnil;
8197 }
8198 
8201 
8202 #ifdef HAVE_POSIX_FADVISE
8203 struct io_advise_struct {
8204  int fd;
8205  off_t offset;
8206  off_t len;
8207  int advice;
8208 };
8209 
8210 static VALUE
8211 io_advise_internal(void *arg)
8212 {
8213  struct io_advise_struct *ptr = arg;
8214  return posix_fadvise(ptr->fd, ptr->offset, ptr->len, ptr->advice);
8215 }
8216 
8217 static VALUE
8218 io_advise_sym_to_const(VALUE sym)
8219 {
8220 #ifdef POSIX_FADV_NORMAL
8221  if (sym == sym_normal)
8222  return INT2NUM(POSIX_FADV_NORMAL);
8223 #endif
8224 
8225 #ifdef POSIX_FADV_RANDOM
8226  if (sym == sym_random)
8227  return INT2NUM(POSIX_FADV_RANDOM);
8228 #endif
8229 
8230 #ifdef POSIX_FADV_SEQUENTIAL
8231  if (sym == sym_sequential)
8232  return INT2NUM(POSIX_FADV_SEQUENTIAL);
8233 #endif
8234 
8235 #ifdef POSIX_FADV_WILLNEED
8236  if (sym == sym_willneed)
8237  return INT2NUM(POSIX_FADV_WILLNEED);
8238 #endif
8239 
8240 #ifdef POSIX_FADV_DONTNEED
8241  if (sym == sym_dontneed)
8242  return INT2NUM(POSIX_FADV_DONTNEED);
8243 #endif
8244 
8245 #ifdef POSIX_FADV_NOREUSE
8246  if (sym == sym_noreuse)
8247  return INT2NUM(POSIX_FADV_NOREUSE);
8248 #endif
8249 
8250  return Qnil;
8251 }
8252 
8253 static VALUE
8254 do_io_advise(rb_io_t *fptr, VALUE advice, off_t offset, off_t len)
8255 {
8256  int rv;
8257  struct io_advise_struct ias;
8258  VALUE num_adv;
8259 
8260  num_adv = io_advise_sym_to_const(advice);
8261 
8262  /*
8263  * The platform doesn't support this hint. We don't raise exception, instead
8264  * silently ignore it. Because IO::advise is only hint.
8265  */
8266  if (NIL_P(num_adv))
8267  return Qnil;
8268 
8269  ias.fd = fptr->fd;
8270  ias.advice = NUM2INT(num_adv);
8271  ias.offset = offset;
8272  ias.len = len;
8273 
8274  rv = (int)rb_thread_io_blocking_region(io_advise_internal, &ias, fptr->fd);
8275  if (rv) {
8276  /* posix_fadvise(2) doesn't set errno. On success it returns 0; otherwise
8277  it returns the error code. */
8278  rb_syserr_fail_str(rv, fptr->pathv);
8279  }
8280 
8281  return Qnil;
8282 }
8283 
8284 #endif /* HAVE_POSIX_FADVISE */
8285 
8286 static void
8288 {
8289  if (!SYMBOL_P(advice))
8290  rb_raise(rb_eTypeError, "advice must be a Symbol");
8291 
8292  if (advice != sym_normal &&
8293  advice != sym_sequential &&
8294  advice != sym_random &&
8295  advice != sym_willneed &&
8296  advice != sym_dontneed &&
8297  advice != sym_noreuse) {
8298  VALUE symname = rb_inspect(advice);
8299  rb_raise(rb_eNotImpError, "Unsupported advice: %s",
8300  StringValuePtr(symname));
8301  }
8302 }
8303 
8304 /*
8305  * call-seq:
8306  * ios.advise(advice, offset=0, len=0) -> nil
8307  *
8308  * Announce an intention to access data from the current file in a
8309  * specific pattern. On platforms that do not support the
8310  * <em>posix_fadvise(2)</em> system call, this method is a no-op.
8311  *
8312  * _advice_ is one of the following symbols:
8313  *
8314  * * :normal - No advice to give; the default assumption for an open file.
8315  * * :sequential - The data will be accessed sequentially:
8316  * with lower offsets read before higher ones.
8317  * * :random - The data will be accessed in random order.
8318  * * :willneed - The data will be accessed in the near future.
8319  * * :dontneed - The data will not be accessed in the near future.
8320  * * :noreuse - The data will only be accessed once.
8321  *
8322  * The semantics of a piece of advice are platform-dependent. See
8323  * <em>man 2 posix_fadvise</em> for details.
8324  *
8325  * "data" means the region of the current file that begins at
8326  * _offset_ and extends for _len_ bytes. If _len_ is 0, the region
8327  * ends at the last byte of the file. By default, both _offset_ and
8328  * _len_ are 0, meaning that the advice applies to the entire file.
8329  *
8330  * If an error occurs, one of the following exceptions will be raised:
8331  *
8332  * * <code>IOError</code> - The <code>IO</code> stream is closed.
8333  * * <code>Errno::EBADF</code> - The file descriptor of the current file is
8334  invalid.
8335  * * <code>Errno::EINVAL</code> - An invalid value for _advice_ was given.
8336  * * <code>Errno::ESPIPE</code> - The file descriptor of the current
8337  * * file refers to a FIFO or pipe. (Linux raises <code>Errno::EINVAL</code>
8338  * * in this case).
8339  * * <code>TypeError</code> - Either _advice_ was not a Symbol, or one of the
8340  other arguments was not an <code>Integer</code>.
8341  * * <code>RangeError</code> - One of the arguments given was too big/small.
8342  *
8343  * This list is not exhaustive; other Errno:: exceptions are also possible.
8344  */
8345 static VALUE
8347 {
8348  VALUE advice, offset, len;
8349  off_t off, l;
8350  rb_io_t *fptr;
8351 
8352  rb_scan_args(argc, argv, "12", &advice, &offset, &len);
8353  advice_arg_check(advice);
8354 
8355  io = GetWriteIO(io);
8356  GetOpenFile(io, fptr);
8357 
8358  off = NIL_P(offset) ? 0 : NUM2OFFT(offset);
8359  l = NIL_P(len) ? 0 : NUM2OFFT(len);
8360 
8361 #ifdef HAVE_POSIX_FADVISE
8362  return do_io_advise(fptr, advice, off, l);
8363 #else
8364  ((void)off, (void)l); /* Ignore all hint */
8365  return Qnil;
8366 #endif
8367 }
8368 
8369 /*
8370  * call-seq:
8371  * IO.select(read_array
8372  * [, write_array
8373  * [, error_array
8374  * [, timeout]]]) -> array or nil
8375  *
8376  * Calls select(2) system call.
8377  * It monitors given arrays of <code>IO</code> objects, waits one or more
8378  * of <code>IO</code> objects ready for reading, are ready for writing,
8379  * and have pending exceptions respectably, and returns an array that
8380  * contains arrays of those IO objects. It will return <code>nil</code>
8381  * if optional <i>timeout</i> value is given and no <code>IO</code> object
8382  * is ready in <i>timeout</i> seconds.
8383  *
8384  * === Parameters
8385  * read_array:: an array of <code>IO</code> objects that wait until ready for read
8386  * write_array:: an array of <code>IO</code> objects that wait until ready for write
8387  * error_array:: an array of <code>IO</code> objects that wait for exceptions
8388  * timeout:: a numeric value in second
8389  *
8390  * === Example
8391  *
8392  * rp, wp = IO.pipe
8393  * mesg = "ping "
8394  * 100.times {
8395  * rs, ws, = IO.select([rp], [wp])
8396  * if r = rs[0]
8397  * ret = r.read(5)
8398  * print ret
8399  * case ret
8400  * when /ping/
8401  * mesg = "pong\n"
8402  * when /pong/
8403  * mesg = "ping "
8404  * end
8405  * end
8406  * if w = ws[0]
8407  * w.write(mesg)
8408  * end
8409  * }
8410  *
8411  * <em>produces:</em>
8412  *
8413  * ping pong
8414  * ping pong
8415  * ping pong
8416  * (snipped)
8417  * ping
8418  */
8419 
8420 static VALUE
8422 {
8423  VALUE timeout;
8424  struct select_args args;
8425  struct timeval timerec;
8426  int i;
8427 
8428  rb_scan_args(argc, argv, "13", &args.read, &args.write, &args.except, &timeout);
8429  if (NIL_P(timeout)) {
8430  args.timeout = 0;
8431  }
8432  else {
8433  timerec = rb_time_interval(timeout);
8434  args.timeout = &timerec;
8435  }
8436 
8437  for (i = 0; i < numberof(args.fdsets); ++i)
8438  rb_fd_init(&args.fdsets[i]);
8439 
8440  return rb_ensure(select_call, (VALUE)&args, select_end, (VALUE)&args);
8441 }
8442 
8443 #if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__APPLE__)
8444  typedef unsigned long ioctl_req_t;
8445 # define NUM2IOCTLREQ(num) NUM2ULONG(num)
8446 #else
8447  typedef int ioctl_req_t;
8448 # define NUM2IOCTLREQ(num) NUM2INT(num)
8449 #endif
8450 
8451 struct ioctl_arg {
8452  int fd;
8453  ioctl_req_t cmd;
8454  long narg;
8455 };
8456 
8457 static VALUE
8458 nogvl_ioctl(void *ptr)
8459 {
8460  struct ioctl_arg *arg = ptr;
8461 
8462  return (VALUE)ioctl(arg->fd, arg->cmd, arg->narg);
8463 }
8464 
8465 static int
8466 do_ioctl(int fd, ioctl_req_t cmd, long narg)
8467 {
8468  int retval;
8469  struct ioctl_arg arg;
8470 
8471  arg.fd = fd;
8472  arg.cmd = cmd;
8473  arg.narg = narg;
8474 
8475  retval = (int)rb_thread_io_blocking_region(nogvl_ioctl, &arg, fd);
8476 
8477  return retval;
8478 }
8479 
8480 #define DEFULT_IOCTL_NARG_LEN (256)
8481 
8482 #ifdef __linux__
8483 static long
8484 linux_iocparm_len(ioctl_req_t cmd)
8485 {
8486  long len;
8487 
8488  if ((cmd & 0xFFFF0000) == 0) {
8489  /* legacy and unstructured ioctl number. */
8490  return DEFULT_IOCTL_NARG_LEN;
8491  }
8492 
8493  len = _IOC_SIZE(cmd);
8494 
8495  /* paranoia check for silly drivers which don't keep ioctl convention */
8496  if (len < DEFULT_IOCTL_NARG_LEN)
8497  len = DEFULT_IOCTL_NARG_LEN;
8498 
8499  return len;
8500 }
8501 #endif
8502 
8503 static long
8504 ioctl_narg_len(ioctl_req_t cmd)
8505 {
8506  long len;
8507 
8508 #ifdef IOCPARM_MASK
8509 #ifndef IOCPARM_LEN
8510 #define IOCPARM_LEN(x) (((x) >> 16) & IOCPARM_MASK)
8511 #endif
8512 #endif
8513 #ifdef IOCPARM_LEN
8514  len = IOCPARM_LEN(cmd); /* on BSDish systems we're safe */
8515 #elif defined(__linux__)
8516  len = linux_iocparm_len(cmd);
8517 #else
8518  /* otherwise guess at what's safe */
8519  len = DEFULT_IOCTL_NARG_LEN;
8520 #endif
8521 
8522  return len;
8523 }
8524 
8525 #ifdef HAVE_FCNTL
8526 #ifdef __linux__
8527 typedef long fcntl_arg_t;
8528 #else
8529 /* posix */
8530 typedef int fcntl_arg_t;
8531 #endif
8532 
8533 static long
8534 fcntl_narg_len(int cmd)
8535 {
8536  long len;
8537 
8538  switch (cmd) {
8539 #ifdef F_DUPFD
8540  case F_DUPFD:
8541  len = sizeof(fcntl_arg_t);
8542  break;
8543 #endif
8544 #ifdef F_DUP2FD /* bsd specific */
8545  case F_DUP2FD:
8546  len = sizeof(int);
8547  break;
8548 #endif
8549 #ifdef F_DUPFD_CLOEXEC /* linux specific */
8550  case F_DUPFD_CLOEXEC:
8551  len = sizeof(fcntl_arg_t);
8552  break;
8553 #endif
8554 #ifdef F_GETFD
8555  case F_GETFD:
8556  len = 1;
8557  break;
8558 #endif
8559 #ifdef F_SETFD
8560  case F_SETFD:
8561  len = sizeof(fcntl_arg_t);
8562  break;
8563 #endif
8564 #ifdef F_GETFL
8565  case F_GETFL:
8566  len = 1;
8567  break;
8568 #endif
8569 #ifdef F_SETFL
8570  case F_SETFL:
8571  len = sizeof(fcntl_arg_t);
8572  break;
8573 #endif
8574 #ifdef F_GETOWN
8575  case F_GETOWN:
8576  len = 1;
8577  break;
8578 #endif
8579 #ifdef F_SETOWN
8580  case F_SETOWN:
8581  len = sizeof(fcntl_arg_t);
8582  break;
8583 #endif
8584 #ifdef F_GETOWN_EX /* linux specific */
8585  case F_GETOWN_EX:
8586  len = sizeof(struct f_owner_ex);
8587  break;
8588 #endif
8589 #ifdef F_SETOWN_EX /* linux specific */
8590  case F_SETOWN_EX:
8591  len = sizeof(struct f_owner_ex);
8592  break;
8593 #endif
8594 #ifdef F_GETLK
8595  case F_GETLK:
8596  len = sizeof(struct flock);
8597  break;
8598 #endif
8599 #ifdef F_SETLK
8600  case F_SETLK:
8601  len = sizeof(struct flock);
8602  break;
8603 #endif
8604 #ifdef F_SETLKW
8605  case F_SETLKW:
8606  len = sizeof(struct flock);
8607  break;
8608 #endif
8609 #ifdef F_READAHEAD /* bsd specific */
8610  case F_READAHEAD:
8611  len = sizeof(int);
8612  break;
8613 #endif
8614 #ifdef F_RDAHEAD /* Darwin specific */
8615  case F_RDAHEAD:
8616  len = sizeof(int);
8617  break;
8618 #endif
8619 #ifdef F_GETSIG /* linux specific */
8620  case F_GETSIG:
8621  len = 1;
8622  break;
8623 #endif
8624 #ifdef F_SETSIG /* linux specific */
8625  case F_SETSIG:
8626  len = sizeof(fcntl_arg_t);
8627  break;
8628 #endif
8629 #ifdef F_GETLEASE /* linux specific */
8630  case F_GETLEASE:
8631  len = 1;
8632  break;
8633 #endif
8634 #ifdef F_SETLEASE /* linux specific */
8635  case F_SETLEASE:
8636  len = sizeof(fcntl_arg_t);
8637  break;
8638 #endif
8639 #ifdef F_NOTIFY /* linux specific */
8640  case F_NOTIFY:
8641  len = sizeof(fcntl_arg_t);
8642  break;
8643 #endif
8644 
8645  default:
8646  len = 256;
8647  break;
8648  }
8649 
8650  return len;
8651 }
8652 #else /* HAVE_FCNTL */
8653 static long
8655 {
8656  return 0;
8657 }
8658 #endif /* HAVE_FCNTL */
8659 
8660 static long
8661 setup_narg(ioctl_req_t cmd, VALUE *argp, int io_p)
8662 {
8663  long narg = 0;
8664  VALUE arg = *argp;
8665 
8666  if (NIL_P(arg) || arg == Qfalse) {
8667  narg = 0;
8668  }
8669  else if (FIXNUM_P(arg)) {
8670  narg = FIX2LONG(arg);
8671  }
8672  else if (arg == Qtrue) {
8673  narg = 1;
8674  }
8675  else {
8676  VALUE tmp = rb_check_string_type(arg);
8677 
8678  if (NIL_P(tmp)) {
8679  narg = NUM2LONG(arg);
8680  }
8681  else {
8682  long len;
8683 
8684  *argp = arg = tmp;
8685  if (io_p)
8686  len = ioctl_narg_len(cmd);
8687  else
8688  len = fcntl_narg_len((int)cmd);
8689  rb_str_modify(arg);
8690 
8691  /* expand for data + sentinel. */
8692  if (RSTRING_LEN(arg) < len+1) {
8693  rb_str_resize(arg, len+1);
8694  }
8695  /* a little sanity check here */
8696  RSTRING_PTR(arg)[RSTRING_LEN(arg) - 1] = 17;
8697  narg = (long)(SIGNED_VALUE)RSTRING_PTR(arg);
8698  }
8699  }
8700 
8701  return narg;
8702 }
8703 
8704 static VALUE
8706 {
8707  ioctl_req_t cmd = NUM2IOCTLREQ(req);
8708  rb_io_t *fptr;
8709  long narg;
8710  int retval;
8711 
8712  rb_secure(2);
8713 
8714  narg = setup_narg(cmd, &arg, 1);
8715  GetOpenFile(io, fptr);
8716  retval = do_ioctl(fptr->fd, cmd, narg);
8717  if (retval < 0) rb_sys_fail_path(fptr->pathv);
8718  if (RB_TYPE_P(arg, T_STRING)) {
8719  if (RSTRING_PTR(arg)[RSTRING_LEN(arg)-1] != 17)
8720  rb_raise(rb_eArgError, "return value overflowed string");
8721  RSTRING_PTR(arg)[RSTRING_LEN(arg)-1] = '\0';
8722  }
8723 
8724  return INT2NUM(retval);
8725 }
8726 
8727 /*
8728  * call-seq:
8729  * ios.ioctl(integer_cmd, arg) -> integer
8730  *
8731  * Provides a mechanism for issuing low-level commands to control or
8732  * query I/O devices. Arguments and results are platform dependent. If
8733  * <i>arg</i> is a number, its value is passed directly. If it is a
8734  * string, it is interpreted as a binary sequence of bytes. On Unix
8735  * platforms, see <code>ioctl(2)</code> for details. Not implemented on
8736  * all platforms.
8737  */
8738 
8739 static VALUE
8741 {
8742  VALUE req, arg;
8743 
8744  rb_scan_args(argc, argv, "11", &req, &arg);
8745  return rb_ioctl(io, req, arg);
8746 }
8747 
8748 #ifdef HAVE_FCNTL
8749 struct fcntl_arg {
8750  int fd;
8751  int cmd;
8752  long narg;
8753 };
8754 
8755 static VALUE
8756 nogvl_fcntl(void *ptr)
8757 {
8758  struct fcntl_arg *arg = ptr;
8759 
8760 #if defined(F_DUPFD)
8761  if (arg->cmd == F_DUPFD)
8762  return (VALUE)rb_cloexec_fcntl_dupfd(arg->fd, (int)arg->narg);
8763 #endif
8764  return (VALUE)fcntl(arg->fd, arg->cmd, arg->narg);
8765 }
8766 
8767 static int
8768 do_fcntl(int fd, int cmd, long narg)
8769 {
8770  int retval;
8771  struct fcntl_arg arg;
8772 
8773  arg.fd = fd;
8774  arg.cmd = cmd;
8775  arg.narg = narg;
8776 
8777  retval = (int)rb_thread_io_blocking_region(nogvl_fcntl, &arg, fd);
8778 #if defined(F_DUPFD)
8779  if (retval != -1 && cmd == F_DUPFD) {
8780  rb_update_max_fd(retval);
8781  }
8782 #endif
8783 
8784  return retval;
8785 }
8786 
8787 static VALUE
8788 rb_fcntl(VALUE io, VALUE req, VALUE arg)
8789 {
8790  int cmd = NUM2INT(req);
8791  rb_io_t *fptr;
8792  long narg;
8793  int retval;
8794 
8795  rb_secure(2);
8796 
8797  narg = setup_narg(cmd, &arg, 0);
8798  GetOpenFile(io, fptr);
8799  retval = do_fcntl(fptr->fd, cmd, narg);
8800  if (retval < 0) rb_sys_fail_path(fptr->pathv);
8801  if (RB_TYPE_P(arg, T_STRING)) {
8802  if (RSTRING_PTR(arg)[RSTRING_LEN(arg)-1] != 17)
8803  rb_raise(rb_eArgError, "return value overflowed string");
8804  RSTRING_PTR(arg)[RSTRING_LEN(arg)-1] = '\0';
8805  }
8806 
8807  if (cmd == F_SETFL) {
8808  if (narg & O_NONBLOCK) {
8809  fptr->mode |= FMODE_WSPLIT_INITIALIZED;
8810  fptr->mode &= ~FMODE_WSPLIT;
8811  }
8812  else {
8814  }
8815  }
8816 
8817  return INT2NUM(retval);
8818 }
8819 
8820 /*
8821  * call-seq:
8822  * ios.fcntl(integer_cmd, arg) -> integer
8823  *
8824  * Provides a mechanism for issuing low-level commands to control or
8825  * query file-oriented I/O streams. Arguments and results are platform
8826  * dependent. If <i>arg</i> is a number, its value is passed
8827  * directly. If it is a string, it is interpreted as a binary sequence
8828  * of bytes (<code>Array#pack</code> might be a useful way to build this
8829  * string). On Unix platforms, see <code>fcntl(2)</code> for details.
8830  * Not implemented on all platforms.
8831  */
8832 
8833 static VALUE
8834 rb_io_fcntl(int argc, VALUE *argv, VALUE io)
8835 {
8836  VALUE req, arg;
8837 
8838  rb_scan_args(argc, argv, "11", &req, &arg);
8839  return rb_fcntl(io, req, arg);
8840 }
8841 #else
8842 #define rb_io_fcntl rb_f_notimplement
8843 #endif
8844 
8845 #if defined(HAVE_SYSCALL) || defined(HAVE___SYSCALL)
8846 /*
8847  * call-seq:
8848  * syscall(num [, args...]) -> integer
8849  *
8850  * Calls the operating system function identified by _num_ and
8851  * returns the result of the function or raises SystemCallError if
8852  * it failed.
8853  *
8854  * Arguments for the function can follow _num_. They must be either
8855  * +String+ objects or +Integer+ objects. A +String+ object is passed
8856  * as a pointer to the byte sequence. An +Integer+ object is passed
8857  * as an integer whose bit size is same as a pointer.
8858  * Up to nine parameters may be passed (14 on the Atari-ST).
8859  *
8860  * The function identified by _num_ is system
8861  * dependent. On some Unix systems, the numbers may be obtained from a
8862  * header file called <code>syscall.h</code>.
8863  *
8864  * syscall 4, 1, "hello\n", 6 # '4' is write(2) on our box
8865  *
8866  * <em>produces:</em>
8867  *
8868  * hello
8869  *
8870  *
8871  * Calling +syscall+ on a platform which does not have any way to
8872  * an arbitrary system function just fails with NotImplementedError.
8873  *
8874  * Note::
8875  * +syscall+ is essentially unsafe and unportable. Feel free to shoot your foot.
8876  * DL (Fiddle) library is preferred for safer and a bit more portable programming.
8877  */
8878 
8879 static VALUE
8880 rb_f_syscall(int argc, VALUE *argv)
8881 {
8882 #ifdef atarist
8883  VALUE arg[13]; /* yes, we really need that many ! */
8884 #else
8885  VALUE arg[8];
8886 #endif
8887 #if SIZEOF_VOIDP == 8 && defined(HAVE___SYSCALL) && SIZEOF_INT != 8 /* mainly *BSD */
8888 # define SYSCALL __syscall
8889 # define NUM2SYSCALLID(x) NUM2LONG(x)
8890 # define RETVAL2NUM(x) LONG2NUM(x)
8891 # if SIZEOF_LONG == 8
8892  long num, retval = -1;
8893 # elif SIZEOF_LONG_LONG == 8
8894  long long num, retval = -1;
8895 # else
8896 # error ---->> it is asserted that __syscall takes the first argument and returns retval in 64bit signed integer. <<----
8897 # endif
8898 #elif defined(__linux__)
8899 # define SYSCALL syscall
8900 # define NUM2SYSCALLID(x) NUM2LONG(x)
8901 # define RETVAL2NUM(x) LONG2NUM(x)
8902  /*
8903  * Linux man page says, syscall(2) function prototype is below.
8904  *
8905  * int syscall(int number, ...);
8906  *
8907  * But, it's incorrect. Actual one takes and returned long. (see unistd.h)
8908  */
8909  long num, retval = -1;
8910 #else
8911 # define SYSCALL syscall
8912 # define NUM2SYSCALLID(x) NUM2INT(x)
8913 # define RETVAL2NUM(x) INT2NUM(x)
8914  int num, retval = -1;
8915 #endif
8916  int i;
8917 
8918  if (RTEST(ruby_verbose)) {
8919  rb_warning("We plan to remove a syscall function at future release. DL(Fiddle) provides safer alternative.");
8920  }
8921 
8922  rb_secure(2);
8923  if (argc == 0)
8924  rb_raise(rb_eArgError, "too few arguments for syscall");
8925  if (argc > numberof(arg))
8926  rb_raise(rb_eArgError, "too many arguments for syscall");
8927  num = NUM2SYSCALLID(argv[0]); ++argv;
8928  for (i = argc - 1; i--; ) {
8929  VALUE v = rb_check_string_type(argv[i]);
8930 
8931  if (!NIL_P(v)) {
8932  SafeStringValue(v);
8933  rb_str_modify(v);
8934  arg[i] = (VALUE)StringValueCStr(v);
8935  }
8936  else {
8937  arg[i] = (VALUE)NUM2LONG(argv[i]);
8938  }
8939  }
8940 
8941  switch (argc) {
8942  case 1:
8943  retval = SYSCALL(num);
8944  break;
8945  case 2:
8946  retval = SYSCALL(num, arg[0]);
8947  break;
8948  case 3:
8949  retval = SYSCALL(num, arg[0],arg[1]);
8950  break;
8951  case 4:
8952  retval = SYSCALL(num, arg[0],arg[1],arg[2]);
8953  break;
8954  case 5:
8955  retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3]);
8956  break;
8957  case 6:
8958  retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3],arg[4]);
8959  break;
8960  case 7:
8961  retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3],arg[4],arg[5]);
8962  break;
8963  case 8:
8964  retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6]);
8965  break;
8966 #ifdef atarist
8967  case 9:
8968  retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
8969  arg[7]);
8970  break;
8971  case 10:
8972  retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
8973  arg[7], arg[8]);
8974  break;
8975  case 11:
8976  retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
8977  arg[7], arg[8], arg[9]);
8978  break;
8979  case 12:
8980  retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
8981  arg[7], arg[8], arg[9], arg[10]);
8982  break;
8983  case 13:
8984  retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
8985  arg[7], arg[8], arg[9], arg[10], arg[11]);
8986  break;
8987  case 14:
8988  retval = SYSCALL(num, arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
8989  arg[7], arg[8], arg[9], arg[10], arg[11], arg[12]);
8990  break;
8991 #endif
8992  }
8993 
8994  if (retval == -1)
8995  rb_sys_fail(0);
8996  return RETVAL2NUM(retval);
8997 #undef SYSCALL
8998 #undef NUM2SYSCALLID
8999 #undef RETVAL2NUM
9000 }
9001 #else
9002 #define rb_f_syscall rb_f_notimplement
9003 #endif
9004 
9005 static VALUE
9007 {
9008  return rb_class_new_instance(2, (VALUE*)args+1, *(VALUE*)args);
9009 }
9010 
9011 static rb_encoding *
9013 {
9014  rb_encoding *enc = rb_find_encoding(v);
9015  if (!enc) unsupported_encoding(StringValueCStr(v));
9016  return enc;
9017 }
9018 
9019 static void
9021 {
9022  rb_encoding *enc, *enc2;
9023  int ecflags = fptr->encs.ecflags;
9024  VALUE ecopts, tmp;
9025 
9026  if (!NIL_P(v2)) {
9027  enc2 = find_encoding(v1);
9028  tmp = rb_check_string_type(v2);
9029  if (!NIL_P(tmp)) {
9030  if (RSTRING_LEN(tmp) == 1 && RSTRING_PTR(tmp)[0] == '-') {
9031  /* Special case - "-" => no transcoding */
9032  enc = enc2;
9033  enc2 = NULL;
9034  }
9035  else
9036  enc = find_encoding(v2);
9037  if (enc == enc2) {
9038  /* Special case - "-" => no transcoding */
9039  enc2 = NULL;
9040  }
9041  }
9042  else {
9043  enc = find_encoding(v2);
9044  if (enc == enc2) {
9045  /* Special case - "-" => no transcoding */
9046  enc2 = NULL;
9047  }
9048  }
9050  ecflags = rb_econv_prepare_options(opt, &ecopts, ecflags);
9051  }
9052  else {
9053  if (NIL_P(v1)) {
9054  /* Set to default encodings */
9055  rb_io_ext_int_to_encs(NULL, NULL, &enc, &enc2, 0);
9057  ecopts = Qnil;
9058  }
9059  else {
9060  tmp = rb_check_string_type(v1);
9061  if (!NIL_P(tmp) && rb_enc_asciicompat(rb_enc_get(tmp))) {
9062  parse_mode_enc(RSTRING_PTR(tmp), &enc, &enc2, NULL);
9064  ecflags = rb_econv_prepare_options(opt, &ecopts, ecflags);
9065  }
9066  else {
9067  rb_io_ext_int_to_encs(find_encoding(v1), NULL, &enc, &enc2, 0);
9069  ecopts = Qnil;
9070  }
9071  }
9072  }
9073  validate_enc_binmode(&fptr->mode, ecflags, enc, enc2);
9074  fptr->encs.enc = enc;
9075  fptr->encs.enc2 = enc2;
9076  fptr->encs.ecflags = ecflags;
9077  fptr->encs.ecopts = ecopts;
9078  clear_codeconv(fptr);
9079 
9080 }
9081 
9082 static VALUE
9084 {
9085  VALUE *rwp = (VALUE *)rw;
9086  return rb_ensure(io_close, rwp[0], io_close, rwp[1]);
9087 }
9088 
9089 /*
9090  * call-seq:
9091  * IO.pipe -> [read_io, write_io]
9092  * IO.pipe(ext_enc) -> [read_io, write_io]
9093  * IO.pipe("ext_enc:int_enc" [, opt]) -> [read_io, write_io]
9094  * IO.pipe(ext_enc, int_enc [, opt]) -> [read_io, write_io]
9095  *
9096  * IO.pipe(...) {|read_io, write_io| ... }
9097  *
9098  * Creates a pair of pipe endpoints (connected to each other) and
9099  * returns them as a two-element array of <code>IO</code> objects:
9100  * <code>[</code> <i>read_io</i>, <i>write_io</i> <code>]</code>.
9101  *
9102  * If a block is given, the block is called and
9103  * returns the value of the block.
9104  * <i>read_io</i> and <i>write_io</i> are sent to the block as arguments.
9105  * If read_io and write_io are not closed when the block exits, they are closed.
9106  * i.e. closing read_io and/or write_io doesn't cause an error.
9107  *
9108  * Not available on all platforms.
9109  *
9110  * If an encoding (encoding name or encoding object) is specified as an optional argument,
9111  * read string from pipe is tagged with the encoding specified.
9112  * If the argument is a colon separated two encoding names "A:B",
9113  * the read string is converted from encoding A (external encoding)
9114  * to encoding B (internal encoding), then tagged with B.
9115  * If two optional arguments are specified, those must be
9116  * encoding objects or encoding names,
9117  * and the first one is the external encoding,
9118  * and the second one is the internal encoding.
9119  * If the external encoding and the internal encoding is specified,
9120  * optional hash argument specify the conversion option.
9121  *
9122  * In the example below, the two processes close the ends of the pipe
9123  * that they are not using. This is not just a cosmetic nicety. The
9124  * read end of a pipe will not generate an end of file condition if
9125  * there are any writers with the pipe still open. In the case of the
9126  * parent process, the <code>rd.read</code> will never return if it
9127  * does not first issue a <code>wr.close</code>.
9128  *
9129  * rd, wr = IO.pipe
9130  *
9131  * if fork
9132  * wr.close
9133  * puts "Parent got: <#{rd.read}>"
9134  * rd.close
9135  * Process.wait
9136  * else
9137  * rd.close
9138  * puts "Sending message to parent"
9139  * wr.write "Hi Dad"
9140  * wr.close
9141  * end
9142  *
9143  * <em>produces:</em>
9144  *
9145  * Sending message to parent
9146  * Parent got: <Hi Dad>
9147  */
9148 
9149 static VALUE
9151 {
9152  int pipes[2], state;
9153  VALUE r, w, args[3], v1, v2;
9154  VALUE opt;
9155  rb_io_t *fptr, *fptr2;
9156  int fmode = 0;
9157  VALUE ret;
9158 
9159  argc = rb_scan_args(argc, argv, "02:", &v1, &v2, &opt);
9160  if (rb_pipe(pipes) == -1)
9161  rb_sys_fail(0);
9162 
9163  args[0] = klass;
9164  args[1] = INT2NUM(pipes[0]);
9165  args[2] = INT2FIX(O_RDONLY);
9166  r = rb_protect(io_new_instance, (VALUE)args, &state);
9167  if (state) {
9168  close(pipes[0]);
9169  close(pipes[1]);
9170  rb_jump_tag(state);
9171  }
9172  GetOpenFile(r, fptr);
9173  io_encoding_set(fptr, v1, v2, opt);
9174  args[1] = INT2NUM(pipes[1]);
9175  args[2] = INT2FIX(O_WRONLY);
9176  w = rb_protect(io_new_instance, (VALUE)args, &state);
9177  if (state) {
9178  close(pipes[1]);
9179  if (!NIL_P(r)) rb_io_close(r);
9180  rb_jump_tag(state);
9181  }
9182  GetOpenFile(w, fptr2);
9183  rb_io_synchronized(fptr2);
9184 
9185  extract_binmode(opt, &fmode);
9186 #if DEFAULT_TEXTMODE
9187  if ((fptr->mode & FMODE_TEXTMODE) && (fmode & FMODE_BINMODE)) {
9188  fptr->mode &= ~FMODE_TEXTMODE;
9189  setmode(fptr->fd, O_BINARY);
9190  }
9191 #if defined(RUBY_TEST_CRLF_ENVIRONMENT) || defined(_WIN32)
9194  }
9195 #endif
9196 #endif
9197  fptr->mode |= fmode;
9198 #if DEFAULT_TEXTMODE
9199  if ((fptr2->mode & FMODE_TEXTMODE) && (fmode & FMODE_BINMODE)) {
9200  fptr2->mode &= ~FMODE_TEXTMODE;
9201  setmode(fptr2->fd, O_BINARY);
9202  }
9203 #endif
9204  fptr2->mode |= fmode;
9205 
9206  ret = rb_assoc_new(r, w);
9207  if (rb_block_given_p()) {
9208  VALUE rw[2];
9209  rw[0] = r;
9210  rw[1] = w;
9211  return rb_ensure(rb_yield, ret, pipe_pair_close, (VALUE)rw);
9212  }
9213  return ret;
9214 }
9215 
9216 struct foreach_arg {
9217  int argc;
9220 };
9221 
9222 static void
9223 open_key_args(int argc, VALUE *argv, VALUE opt, struct foreach_arg *arg)
9224 {
9225  VALUE path, v;
9226 
9227  path = *argv++;
9228  argc--;
9229  FilePathValue(path);
9230  arg->io = 0;
9231  arg->argc = argc;
9232  arg->argv = argv;
9233  if (NIL_P(opt)) {
9234  arg->io = rb_io_open(path, INT2NUM(O_RDONLY), INT2FIX(0666), Qnil);
9235  return;
9236  }
9237  v = rb_hash_aref(opt, sym_open_args);
9238  if (!NIL_P(v)) {
9239  VALUE args;
9240  long n;
9241 
9242  v = rb_convert_type(v, T_ARRAY, "Array", "to_ary");
9243  n = RARRAY_LEN(v) + 1;
9244 #if SIZEOF_LONG > SIZEOF_INT
9245  if (n > INT_MAX) {
9246  rb_raise(rb_eArgError, "too many arguments");
9247  }
9248 #endif
9249  args = rb_ary_tmp_new(n);
9250  rb_ary_push(args, path);
9251  rb_ary_concat(args, v);
9252  arg->io = rb_io_open_with_args((int)n, RARRAY_PTR(args));
9253  rb_ary_clear(args); /* prevent from GC */
9254  return;
9255  }
9256  arg->io = rb_io_open(path, Qnil, Qnil, opt);
9257 }
9258 
9259 static VALUE
9261 {
9262  VALUE str;
9263 
9264  while (!NIL_P(str = rb_io_gets_m(arg->argc, arg->argv, arg->io))) {
9265  rb_yield(str);
9266  }
9267  return Qnil;
9268 }
9269 
9270 /*
9271  * call-seq:
9272  * IO.foreach(name, sep=$/ [, open_args]) {|line| block } -> nil
9273  * IO.foreach(name, limit [, open_args]) {|line| block } -> nil
9274  * IO.foreach(name, sep, limit [, open_args]) {|line| block } -> nil
9275  * IO.foreach(...) -> an_enumerator
9276  *
9277  * Executes the block for every line in the named I/O port, where lines
9278  * are separated by <em>sep</em>.
9279  *
9280  * If no block is given, an enumerator is returned instead.
9281  *
9282  * IO.foreach("testfile") {|x| print "GOT ", x }
9283  *
9284  * <em>produces:</em>
9285  *
9286  * GOT This is line one
9287  * GOT This is line two
9288  * GOT This is line three
9289  * GOT And so on...
9290  *
9291  * If the last argument is a hash, it's the keyword argument to open.
9292  * See <code>IO.read</code> for detail.
9293  *
9294  */
9295 
9296 static VALUE
9298 {
9299  VALUE opt;
9300  int orig_argc = argc;
9301  struct foreach_arg arg;
9302 
9303  argc = rb_scan_args(argc, argv, "13:", NULL, NULL, NULL, NULL, &opt);
9304  RETURN_ENUMERATOR(self, orig_argc, argv);
9305  open_key_args(argc, argv, opt, &arg);
9306  if (NIL_P(arg.io)) return Qnil;
9307  return rb_ensure(io_s_foreach, (VALUE)&arg, rb_io_close, arg.io);
9308 }
9309 
9310 static VALUE
9312 {
9313  return rb_io_readlines(arg->argc, arg->argv, arg->io);
9314 }
9315 
9316 /*
9317  * call-seq:
9318  * IO.readlines(name, sep=$/ [, open_args]) -> array
9319  * IO.readlines(name, limit [, open_args]) -> array
9320  * IO.readlines(name, sep, limit [, open_args]) -> array
9321  *
9322  * Reads the entire file specified by <i>name</i> as individual
9323  * lines, and returns those lines in an array. Lines are separated by
9324  * <i>sep</i>.
9325  *
9326  * a = IO.readlines("testfile")
9327  * a[0] #=> "This is line one\n"
9328  *
9329  * If the last argument is a hash, it's the keyword argument to open.
9330  * See <code>IO.read</code> for detail.
9331  *
9332  */
9333 
9334 static VALUE
9336 {
9337  VALUE opt;
9338  struct foreach_arg arg;
9339 
9340  argc = rb_scan_args(argc, argv, "13:", NULL, NULL, NULL, NULL, &opt);
9341  open_key_args(argc, argv, opt, &arg);
9342  if (NIL_P(arg.io)) return Qnil;
9343  return rb_ensure(io_s_readlines, (VALUE)&arg, rb_io_close, arg.io);
9344 }
9345 
9346 static VALUE
9348 {
9349  return io_read(arg->argc, arg->argv, arg->io);
9350 }
9351 
9352 struct seek_arg {
9355  int mode;
9356 };
9357 
9358 static VALUE
9360 {
9361  struct seek_arg *arg = (struct seek_arg *)argp;
9362  rb_io_binmode(arg->io);
9363  return rb_io_seek(arg->io, arg->offset, arg->mode);
9364 }
9365 
9366 /*
9367  * call-seq:
9368  * IO.read(name, [length [, offset]] ) -> string
9369  * IO.read(name, [length [, offset]], open_args) -> string
9370  *
9371  * Opens the file, optionally seeks to the given +offset+, then returns
9372  * +length+ bytes (defaulting to the rest of the file). <code>read</code>
9373  * ensures the file is closed before returning.
9374  *
9375  * If the last argument is a hash, it specifies option for internal
9376  * open(). The key would be the following. open_args: is exclusive
9377  * to others.
9378  *
9379  * encoding::
9380  * string or encoding
9381  *
9382  * specifies encoding of the read string. +encoding+ will be ignored
9383  * if length is specified.
9384  *
9385  * mode::
9386  * string
9387  *
9388  * specifies mode argument for open(). It should start with "r"
9389  * otherwise it will cause an error.
9390  *
9391  * open_args:: array of strings
9392  *
9393  * specifies arguments for open() as an array.
9394  *
9395  * Examples:
9396  *
9397  * IO.read("testfile") #=> "This is line one\nThis is line two\nThis is line three\nAnd so on...\n"
9398  * IO.read("testfile", 20) #=> "This is line one\nThi"
9399  * IO.read("testfile", 20, 10) #=> "ne one\nThis is line "
9400  */
9401 
9402 static VALUE
9404 {
9405  VALUE opt, offset;
9406  struct foreach_arg arg;
9407 
9408  argc = rb_scan_args(argc, argv, "13:", NULL, NULL, &offset, NULL, &opt);
9409  open_key_args(argc, argv, opt, &arg);
9410  if (NIL_P(arg.io)) return Qnil;
9411  if (!NIL_P(offset)) {
9412  struct seek_arg sarg;
9413  int state = 0;
9414  sarg.io = arg.io;
9415  sarg.offset = offset;
9416  sarg.mode = SEEK_SET;
9417  rb_protect(seek_before_access, (VALUE)&sarg, &state);
9418  if (state) {
9419  rb_io_close(arg.io);
9420  rb_jump_tag(state);
9421  }
9422  if (arg.argc == 2) arg.argc = 1;
9423  }
9424  return rb_ensure(io_s_read, (VALUE)&arg, rb_io_close, arg.io);
9425 }
9426 
9427 /*
9428  * call-seq:
9429  * IO.binread(name, [length [, offset]] ) -> string
9430  *
9431  * Opens the file, optionally seeks to the given <i>offset</i>, then returns
9432  * <i>length</i> bytes (defaulting to the rest of the file).
9433  * <code>binread</code> ensures the file is closed before returning.
9434  * The open mode would be "rb:ASCII-8BIT".
9435  *
9436  * IO.binread("testfile") #=> "This is line one\nThis is line two\nThis is line three\nAnd so on...\n"
9437  * IO.binread("testfile", 20) #=> "This is line one\nThi"
9438  * IO.binread("testfile", 20, 10) #=> "ne one\nThis is line "
9439  */
9440 
9441 static VALUE
9443 {
9444  VALUE offset;
9445  struct foreach_arg arg;
9446 
9447  rb_scan_args(argc, argv, "12", NULL, NULL, &offset);
9448  FilePathValue(argv[0]);
9449  arg.io = rb_io_open(argv[0], rb_str_new_cstr("rb:ASCII-8BIT"), Qnil, Qnil);
9450  if (NIL_P(arg.io)) return Qnil;
9451  arg.argv = argv+1;
9452  arg.argc = (argc > 1) ? 1 : 0;
9453  if (!NIL_P(offset)) {
9454  rb_io_seek(arg.io, offset, SEEK_SET);
9455  }
9456  return rb_ensure(io_s_read, (VALUE)&arg, rb_io_close, arg.io);
9457 }
9458 
9459 static VALUE
9461 {
9462  return io_write(arg->io,arg->str,arg->nosync);
9463 }
9464 
9465 static VALUE
9466 io_s_write(int argc, VALUE *argv, int binary)
9467 {
9468  VALUE string, offset, opt;
9469  struct foreach_arg arg;
9470  struct write_arg warg;
9471 
9472  rb_scan_args(argc, argv, "21:", NULL, &string, &offset, &opt);
9473 
9474  if (NIL_P(opt)) opt = rb_hash_new();
9475  else opt = rb_hash_dup(opt);
9476 
9477 
9478  if (NIL_P(rb_hash_aref(opt,sym_mode))) {
9479  int mode = O_WRONLY|O_CREAT;
9480 #ifdef O_BINARY
9481  if (binary) mode |= O_BINARY;
9482 #endif
9483  if (NIL_P(offset)) mode |= O_TRUNC;
9484  rb_hash_aset(opt,sym_mode,INT2NUM(mode));
9485  }
9486  open_key_args(argc,argv,opt,&arg);
9487 
9488 #ifndef O_BINARY
9489  if (binary) rb_io_binmode_m(arg.io);
9490 #endif
9491 
9492  if (NIL_P(arg.io)) return Qnil;
9493  if (!NIL_P(offset)) {
9494  struct seek_arg sarg;
9495  int state = 0;
9496  sarg.io = arg.io;
9497  sarg.offset = offset;
9498  sarg.mode = SEEK_SET;
9499  rb_protect(seek_before_access, (VALUE)&sarg, &state);
9500  if (state) {
9501  rb_io_close(arg.io);
9502  rb_jump_tag(state);
9503  }
9504  }
9505 
9506  warg.io = arg.io;
9507  warg.str = string;
9508  warg.nosync = 0;
9509 
9510  return rb_ensure(io_s_write0, (VALUE)&warg, rb_io_close, arg.io);
9511 }
9512 
9513 /*
9514  * call-seq:
9515  * IO.write(name, string, [offset] ) => fixnum
9516  * IO.write(name, string, [offset], open_args ) => fixnum
9517  *
9518  * Opens the file, optionally seeks to the given <i>offset</i>, writes
9519  * <i>string</i>, then returns the length written.
9520  * <code>write</code> ensures the file is closed before returning.
9521  * If <i>offset</i> is not given, the file is truncated. Otherwise,
9522  * it is not truncated.
9523  *
9524  * If the last argument is a hash, it specifies option for internal
9525  * open(). The key would be the following. open_args: is exclusive
9526  * to others.
9527  *
9528  * encoding: string or encoding
9529  *
9530  * specifies encoding of the read string. encoding will be ignored
9531  * if length is specified.
9532  *
9533  * mode: string
9534  *
9535  * specifies mode argument for open(). it should start with "w" or "a" or "r+"
9536  * otherwise it would cause error.
9537  *
9538  * perm: fixnum
9539  *
9540  * specifies perm argument for open().
9541  *
9542  * open_args: array
9543  *
9544  * specifies arguments for open() as an array.
9545  *
9546  * IO.write("testfile", "0123456789", 20) # => 10
9547  * # File could contain: "This is line one\nThi0123456789two\nThis is line three\nAnd so on...\n"
9548  * IO.write("testfile", "0123456789") #=> 10
9549  * # File would now read: "0123456789"
9550  */
9551 
9552 static VALUE
9554 {
9555  return io_s_write(argc, argv, 0);
9556 }
9557 
9558 /*
9559  * call-seq:
9560  * IO.binwrite(name, string, [offset] ) => fixnum
9561  * IO.binwrite(name, string, [offset], open_args ) => fixnum
9562  *
9563  * Same as <code>IO.write</code> except opening the file in binary mode
9564  * and ASCII-8BIT encoding ("wb:ASCII-8BIT").
9565  *
9566  */
9567 
9568 static VALUE
9570 {
9571  return io_s_write(argc, argv, 1);
9572 }
9573 
9577  off_t copy_length; /* (off_t)-1 if not specified */
9578  off_t src_offset; /* (off_t)-1 if not specified */
9579 
9580  int src_fd;
9581  int dst_fd;
9585  const char *syserr;
9587  const char *notimp;
9590 };
9591 
9592 static void *
9594 {
9595  VALUE th = (VALUE)arg;
9597  return NULL;
9598 }
9599 
9600 /*
9601  * returns TRUE if the preceding system call was interrupted
9602  * so we can continue. If the thread was interrupted, we
9603  * reacquire the GVL to execute interrupts before continuing.
9604  */
9605 static int
9607 {
9608  switch (errno) {
9609  case EINTR:
9610 #if defined(ERESTART)
9611  case ERESTART:
9612 #endif
9613  if (rb_thread_interrupted(stp->th)) {
9614  if (has_gvl)
9616  else
9618  }
9619  return TRUE;
9620  }
9621  return FALSE;
9622 }
9623 
9624 static int
9625 maygvl_select(int has_gvl, int n, rb_fdset_t *rfds, rb_fdset_t *wfds, rb_fdset_t *efds, struct timeval *timeout)
9626 {
9627  if (has_gvl)
9628  return rb_thread_fd_select(n, rfds, wfds, efds, timeout);
9629  else
9630  return rb_fd_select(n, rfds, wfds, efds, timeout);
9631 }
9632 
9633 static int
9635 {
9636  int ret;
9637 
9638  do {
9639  rb_fd_zero(&stp->fds);
9640  rb_fd_set(stp->src_fd, &stp->fds);
9641  ret = maygvl_select(has_gvl, rb_fd_max(&stp->fds), &stp->fds, NULL, NULL, NULL);
9642  } while (ret == -1 && maygvl_copy_stream_continue_p(has_gvl, stp));
9643 
9644  if (ret == -1) {
9645  stp->syserr = "select";
9646  stp->error_no = errno;
9647  return -1;
9648  }
9649  return 0;
9650 }
9651 
9652 static int
9654 {
9655  int ret;
9656 
9657  do {
9658  rb_fd_zero(&stp->fds);
9659  rb_fd_set(stp->dst_fd, &stp->fds);
9660  ret = rb_fd_select(rb_fd_max(&stp->fds), NULL, &stp->fds, NULL, NULL);
9661  } while (ret == -1 && maygvl_copy_stream_continue_p(0, stp));
9662 
9663  if (ret == -1) {
9664  stp->syserr = "select";
9665  stp->error_no = errno;
9666  return -1;
9667  }
9668  return 0;
9669 }
9670 
9671 #ifdef HAVE_SENDFILE
9672 
9673 # ifdef __linux__
9674 # define USE_SENDFILE
9675 
9676 # ifdef HAVE_SYS_SENDFILE_H
9677 # include <sys/sendfile.h>
9678 # endif
9679 
9680 static ssize_t
9681 simple_sendfile(int out_fd, int in_fd, off_t *offset, off_t count)
9682 {
9683  return sendfile(out_fd, in_fd, offset, (size_t)count);
9684 }
9685 
9686 # elif 0 /* defined(__FreeBSD__) || defined(__DragonFly__) */ || defined(__APPLE__)
9687 /* This runs on FreeBSD8.1 r30210, but sendfiles blocks its execution
9688  * without cpuset -l 0.
9689  */
9690 # define USE_SENDFILE
9691 
9692 # ifdef HAVE_SYS_UIO_H
9693 # include <sys/uio.h>
9694 # endif
9695 
9696 static ssize_t
9697 simple_sendfile(int out_fd, int in_fd, off_t *offset, off_t count)
9698 {
9699  int r;
9700  off_t pos = offset ? *offset : lseek(in_fd, 0, SEEK_CUR);
9701  off_t sbytes;
9702 # ifdef __APPLE__
9703  r = sendfile(in_fd, out_fd, pos, &count, NULL, 0);
9704  sbytes = count;
9705 # else
9706  r = sendfile(in_fd, out_fd, pos, (size_t)count, NULL, &sbytes, 0);
9707 # endif
9708  if (r != 0 && sbytes == 0) return -1;
9709  if (offset) {
9710  *offset += sbytes;
9711  }
9712  else {
9713  lseek(in_fd, sbytes, SEEK_CUR);
9714  }
9715  return (ssize_t)sbytes;
9716 }
9717 
9718 # endif
9719 
9720 #endif
9721 
9722 #ifdef USE_SENDFILE
9723 static int
9724 nogvl_copy_stream_sendfile(struct copy_stream_struct *stp)
9725 {
9726  struct stat src_stat, dst_stat;
9727  ssize_t ss;
9728  int ret;
9729 
9730  off_t copy_length;
9731  off_t src_offset;
9732  int use_pread;
9733 
9734  ret = fstat(stp->src_fd, &src_stat);
9735  if (ret == -1) {
9736  stp->syserr = "fstat";
9737  stp->error_no = errno;
9738  return -1;
9739  }
9740  if (!S_ISREG(src_stat.st_mode))
9741  return 0;
9742 
9743  ret = fstat(stp->dst_fd, &dst_stat);
9744  if (ret == -1) {
9745  stp->syserr = "fstat";
9746  stp->error_no = errno;
9747  return -1;
9748  }
9749  if ((dst_stat.st_mode & S_IFMT) != S_IFSOCK)
9750  return 0;
9751 
9752  src_offset = stp->src_offset;
9753  use_pread = src_offset != (off_t)-1;
9754 
9755  copy_length = stp->copy_length;
9756  if (copy_length == (off_t)-1) {
9757  if (use_pread)
9758  copy_length = src_stat.st_size - src_offset;
9759  else {
9760  off_t cur;
9761  errno = 0;
9762  cur = lseek(stp->src_fd, 0, SEEK_CUR);
9763  if (cur == (off_t)-1 && errno) {
9764  stp->syserr = "lseek";
9765  stp->error_no = errno;
9766  return -1;
9767  }
9768  copy_length = src_stat.st_size - cur;
9769  }
9770  }
9771 
9772  retry_sendfile:
9773 # if SIZEOF_OFF_T > SIZEOF_SIZE_T
9774  /* we are limited by the 32-bit ssize_t return value on 32-bit */
9775  ss = (copy_length > (off_t)SSIZE_MAX) ? SSIZE_MAX : (ssize_t)copy_length;
9776 # else
9777  ss = (ssize_t)copy_length;
9778 # endif
9779  if (use_pread) {
9780  ss = simple_sendfile(stp->dst_fd, stp->src_fd, &src_offset, ss);
9781  }
9782  else {
9783  ss = simple_sendfile(stp->dst_fd, stp->src_fd, NULL, ss);
9784  }
9785  if (0 < ss) {
9786  stp->total += ss;
9787  copy_length -= ss;
9788  if (0 < copy_length) {
9789  goto retry_sendfile;
9790  }
9791  }
9792  if (ss == -1) {
9793  if (maygvl_copy_stream_continue_p(0, stp))
9794  goto retry_sendfile;
9795  switch (errno) {
9796  case EINVAL:
9797 #ifdef ENOSYS
9798  case ENOSYS:
9799 #endif
9800  return 0;
9801  case EAGAIN:
9802 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
9803  case EWOULDBLOCK:
9804 #endif
9805 #ifndef __linux__
9806  /*
9807  * Linux requires stp->src_fd to be a mmap-able (regular) file,
9808  * select() reports regular files to always be "ready", so
9809  * there is no need to select() on it.
9810  * Other OSes may have the same limitation for sendfile() which
9811  * allow us to bypass maygvl_copy_stream_wait_read()...
9812  */
9813  if (maygvl_copy_stream_wait_read(0, stp) == -1)
9814  return -1;
9815 #endif
9816  if (nogvl_copy_stream_wait_write(stp) == -1)
9817  return -1;
9818  goto retry_sendfile;
9819  }
9820  stp->syserr = "sendfile";
9821  stp->error_no = errno;
9822  return -1;
9823  }
9824  return 1;
9825 }
9826 #endif
9827 
9828 static ssize_t
9829 maygvl_read(int has_gvl, int fd, void *buf, size_t count)
9830 {
9831  if (has_gvl)
9832  return rb_read_internal(fd, buf, count);
9833  else
9834  return read(fd, buf, count);
9835 }
9836 
9837 static ssize_t
9838 maygvl_copy_stream_read(int has_gvl, struct copy_stream_struct *stp, char *buf, size_t len, off_t offset)
9839 {
9840  ssize_t ss;
9841  retry_read:
9842  if (offset == (off_t)-1) {
9843  ss = maygvl_read(has_gvl, stp->src_fd, buf, len);
9844  }
9845  else {
9846 #ifdef HAVE_PREAD
9847  ss = pread(stp->src_fd, buf, len, offset);
9848 #else
9849  stp->notimp = "pread";
9850  return -1;
9851 #endif
9852  }
9853  if (ss == 0) {
9854  return 0;
9855  }
9856  if (ss == -1) {
9857  if (maygvl_copy_stream_continue_p(has_gvl, stp))
9858  goto retry_read;
9859  switch (errno) {
9860  case EAGAIN:
9861 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
9862  case EWOULDBLOCK:
9863 #endif
9864  if (maygvl_copy_stream_wait_read(has_gvl, stp) == -1)
9865  return -1;
9866  goto retry_read;
9867 #ifdef ENOSYS
9868  case ENOSYS:
9869 #endif
9870  stp->notimp = "pread";
9871  return -1;
9872  }
9873  stp->syserr = offset == (off_t)-1 ? "read" : "pread";
9874  stp->error_no = errno;
9875  return -1;
9876  }
9877  return ss;
9878 }
9879 
9880 static int
9881 nogvl_copy_stream_write(struct copy_stream_struct *stp, char *buf, size_t len)
9882 {
9883  ssize_t ss;
9884  int off = 0;
9885  while (len) {
9886  ss = write(stp->dst_fd, buf+off, len);
9887  if (ss == -1) {
9888  if (maygvl_copy_stream_continue_p(0, stp))
9889  continue;
9890  if (errno == EAGAIN || errno == EWOULDBLOCK) {
9891  if (nogvl_copy_stream_wait_write(stp) == -1)
9892  return -1;
9893  continue;
9894  }
9895  stp->syserr = "write";
9896  stp->error_no = errno;
9897  return -1;
9898  }
9899  off += (int)ss;
9900  len -= (int)ss;
9901  stp->total += ss;
9902  }
9903  return 0;
9904 }
9905 
9906 static void
9908 {
9909  char buf[1024*16];
9910  size_t len;
9911  ssize_t ss;
9912  int ret;
9913  off_t copy_length;
9914  int use_eof;
9915  off_t src_offset;
9916  int use_pread;
9917 
9918  copy_length = stp->copy_length;
9919  use_eof = copy_length == (off_t)-1;
9920  src_offset = stp->src_offset;
9921  use_pread = src_offset != (off_t)-1;
9922 
9923  if (use_pread && stp->close_src) {
9924  off_t r;
9925  errno = 0;
9926  r = lseek(stp->src_fd, src_offset, SEEK_SET);
9927  if (r == (off_t)-1 && errno) {
9928  stp->syserr = "lseek";
9929  stp->error_no = errno;
9930  return;
9931  }
9932  src_offset = (off_t)-1;
9933  use_pread = 0;
9934  }
9935 
9936  while (use_eof || 0 < copy_length) {
9937  if (!use_eof && copy_length < (off_t)sizeof(buf)) {
9938  len = (size_t)copy_length;
9939  }
9940  else {
9941  len = sizeof(buf);
9942  }
9943  if (use_pread) {
9944  ss = maygvl_copy_stream_read(0, stp, buf, len, src_offset);
9945  if (0 < ss)
9946  src_offset += ss;
9947  }
9948  else {
9949  ss = maygvl_copy_stream_read(0, stp, buf, len, (off_t)-1);
9950  }
9951  if (ss <= 0) /* EOF or error */
9952  return;
9953 
9954  ret = nogvl_copy_stream_write(stp, buf, ss);
9955  if (ret < 0)
9956  return;
9957 
9958  if (!use_eof)
9959  copy_length -= ss;
9960  }
9961 }
9962 
9963 static void *
9965 {
9966  struct copy_stream_struct *stp = (struct copy_stream_struct *)arg;
9967 #ifdef USE_SENDFILE
9968  int ret;
9969 #endif
9970 
9971 #ifdef USE_SENDFILE
9972  ret = nogvl_copy_stream_sendfile(stp);
9973  if (ret != 0)
9974  goto finish; /* error or success */
9975 #endif
9976 
9978 
9979 #ifdef USE_SENDFILE
9980  finish:
9981 #endif
9982  return 0;
9983 }
9984 
9985 static VALUE
9987 {
9988  struct copy_stream_struct *stp = (struct copy_stream_struct *)arg;
9989  const int buflen = 16*1024;
9990  VALUE n;
9991  VALUE buf = rb_str_buf_new(buflen);
9992  off_t rest = stp->copy_length;
9993  off_t off = stp->src_offset;
9994  ID read_method = id_readpartial;
9995 
9996  if (stp->src_fd == -1) {
9997  if (!rb_respond_to(stp->src, read_method)) {
9998  read_method = id_read;
9999  }
10000  }
10001 
10002  while (1) {
10003  long numwrote;
10004  long l;
10005  if (stp->copy_length == (off_t)-1) {
10006  l = buflen;
10007  }
10008  else {
10009  if (rest == 0)
10010  break;
10011  l = buflen < rest ? buflen : (long)rest;
10012  }
10013  if (stp->src_fd == -1) {
10014  VALUE rc = rb_funcall(stp->src, read_method, 2, INT2FIX(l), buf);
10015 
10016  if (read_method == id_read && NIL_P(rc))
10017  break;
10018  }
10019  else {
10020  ssize_t ss;
10021  rb_str_resize(buf, buflen);
10022  ss = maygvl_copy_stream_read(1, stp, RSTRING_PTR(buf), l, off);
10023  if (ss == -1)
10024  return Qnil;
10025  if (ss == 0)
10026  rb_eof_error();
10027  rb_str_resize(buf, ss);
10028  if (off != (off_t)-1)
10029  off += ss;
10030  }
10031  n = rb_io_write(stp->dst, buf);
10032  numwrote = NUM2LONG(n);
10033  stp->total += numwrote;
10034  rest -= numwrote;
10035  if (read_method == id_read && RSTRING_LEN(buf) == 0) {
10036  break;
10037  }
10038  }
10039 
10040  return Qnil;
10041 }
10042 
10043 static VALUE
10045 {
10046  if (stp->src_fd == -1 && stp->src_offset != (off_t)-1) {
10047  rb_raise(rb_eArgError, "cannot specify src_offset for non-IO");
10048  }
10050  (VALUE (*) (ANYARGS))0, (VALUE)0,
10051  rb_eEOFError, (VALUE)0);
10052  return Qnil;
10053 }
10054 
10055 static VALUE
10057 {
10058  struct copy_stream_struct *stp = (struct copy_stream_struct *)arg;
10059  VALUE src_io, dst_io;
10060  rb_io_t *src_fptr = 0, *dst_fptr = 0;
10061  int src_fd, dst_fd;
10062 
10063  stp->th = rb_thread_current();
10064 
10065  stp->total = 0;
10066 
10067  if (stp->src == argf ||
10068  !(RB_TYPE_P(stp->src, T_FILE) ||
10069  RB_TYPE_P(stp->src, T_STRING) ||
10070  rb_respond_to(stp->src, rb_intern("to_path")))) {
10071  src_fd = -1;
10072  }
10073  else {
10074  src_io = RB_TYPE_P(stp->src, T_FILE) ? stp->src : Qnil;
10075  if (NIL_P(src_io)) {
10076  VALUE args[2];
10077  int oflags = O_RDONLY;
10078 #ifdef O_NOCTTY
10079  oflags |= O_NOCTTY;
10080 #endif
10081  FilePathValue(stp->src);
10082  args[0] = stp->src;
10083  args[1] = INT2NUM(oflags);
10084  src_io = rb_class_new_instance(2, args, rb_cFile);
10085  stp->src = src_io;
10086  stp->close_src = 1;
10087  }
10088  GetOpenFile(src_io, src_fptr);
10089  rb_io_check_byte_readable(src_fptr);
10090  src_fd = src_fptr->fd;
10091  }
10092  stp->src_fd = src_fd;
10093 
10094  if (stp->dst == argf ||
10095  !(RB_TYPE_P(stp->dst, T_FILE) ||
10096  RB_TYPE_P(stp->dst, T_STRING) ||
10097  rb_respond_to(stp->dst, rb_intern("to_path")))) {
10098  dst_fd = -1;
10099  }
10100  else {
10101  dst_io = RB_TYPE_P(stp->dst, T_FILE) ? stp->dst : Qnil;
10102  if (NIL_P(dst_io)) {
10103  VALUE args[3];
10104  int oflags = O_WRONLY|O_CREAT|O_TRUNC;
10105 #ifdef O_NOCTTY
10106  oflags |= O_NOCTTY;
10107 #endif
10108  FilePathValue(stp->dst);
10109  args[0] = stp->dst;
10110  args[1] = INT2NUM(oflags);
10111  args[2] = INT2FIX(0666);
10112  dst_io = rb_class_new_instance(3, args, rb_cFile);
10113  stp->dst = dst_io;
10114  stp->close_dst = 1;
10115  }
10116  else {
10117  dst_io = GetWriteIO(dst_io);
10118  stp->dst = dst_io;
10119  }
10120  GetOpenFile(dst_io, dst_fptr);
10121  rb_io_check_writable(dst_fptr);
10122  dst_fd = dst_fptr->fd;
10123  }
10124  stp->dst_fd = dst_fd;
10125 
10126 #ifdef O_BINARY
10127  if (src_fptr)
10129  if (dst_fptr)
10130  setmode(dst_fd, O_BINARY);
10131 #endif
10132 
10133  if (stp->src_offset == (off_t)-1 && src_fptr && src_fptr->rbuf.len) {
10134  size_t len = src_fptr->rbuf.len;
10135  VALUE str;
10136  if (stp->copy_length != (off_t)-1 && stp->copy_length < (off_t)len) {
10137  len = (size_t)stp->copy_length;
10138  }
10139  str = rb_str_buf_new(len);
10140  rb_str_resize(str,len);
10141  read_buffered_data(RSTRING_PTR(str), len, src_fptr);
10142  if (dst_fptr) { /* IO or filename */
10143  if (io_binwrite(str, RSTRING_PTR(str), RSTRING_LEN(str), dst_fptr, 0) < 0)
10144  rb_sys_fail(0);
10145  }
10146  else /* others such as StringIO */
10147  rb_io_write(stp->dst, str);
10148  stp->total += len;
10149  if (stp->copy_length != (off_t)-1)
10150  stp->copy_length -= len;
10151  }
10152 
10153  if (dst_fptr && io_fflush(dst_fptr) < 0) {
10154  rb_raise(rb_eIOError, "flush failed");
10155  }
10156 
10157  if (stp->copy_length == 0)
10158  return Qnil;
10159 
10160  if (src_fd == -1 || dst_fd == -1) {
10161  return copy_stream_fallback(stp);
10162  }
10163 
10164  rb_fd_set(src_fd, &stp->fds);
10165  rb_fd_set(dst_fd, &stp->fds);
10166 
10168  return Qnil;
10169 }
10170 
10171 static VALUE
10173 {
10174  struct copy_stream_struct *stp = (struct copy_stream_struct *)arg;
10175  if (stp->close_src) {
10176  rb_io_close_m(stp->src);
10177  }
10178  if (stp->close_dst) {
10179  rb_io_close_m(stp->dst);
10180  }
10181  rb_fd_term(&stp->fds);
10182  if (stp->syserr) {
10183  errno = stp->error_no;
10184  rb_sys_fail(stp->syserr);
10185  }
10186  if (stp->notimp) {
10187  rb_raise(rb_eNotImpError, "%s() not implemented", stp->notimp);
10188  }
10189  return Qnil;
10190 }
10191 
10192 /*
10193  * call-seq:
10194  * IO.copy_stream(src, dst)
10195  * IO.copy_stream(src, dst, copy_length)
10196  * IO.copy_stream(src, dst, copy_length, src_offset)
10197  *
10198  * IO.copy_stream copies <i>src</i> to <i>dst</i>.
10199  * <i>src</i> and <i>dst</i> is either a filename or an IO.
10200  *
10201  * This method returns the number of bytes copied.
10202  *
10203  * If optional arguments are not given,
10204  * the start position of the copy is
10205  * the beginning of the filename or
10206  * the current file offset of the IO.
10207  * The end position of the copy is the end of file.
10208  *
10209  * If <i>copy_length</i> is given,
10210  * No more than <i>copy_length</i> bytes are copied.
10211  *
10212  * If <i>src_offset</i> is given,
10213  * it specifies the start position of the copy.
10214  *
10215  * When <i>src_offset</i> is specified and
10216  * <i>src</i> is an IO,
10217  * IO.copy_stream doesn't move the current file offset.
10218  *
10219  */
10220 static VALUE
10222 {
10223  VALUE src, dst, length, src_offset;
10224  struct copy_stream_struct st;
10225 
10226  MEMZERO(&st, struct copy_stream_struct, 1);
10227 
10228  rb_scan_args(argc, argv, "22", &src, &dst, &length, &src_offset);
10229 
10230  st.src = src;
10231  st.dst = dst;
10232 
10233  if (NIL_P(length))
10234  st.copy_length = (off_t)-1;
10235  else
10236  st.copy_length = NUM2OFFT(length);
10237 
10238  if (NIL_P(src_offset))
10239  st.src_offset = (off_t)-1;
10240  else
10241  st.src_offset = NUM2OFFT(src_offset);
10242 
10243  rb_fd_init(&st.fds);
10245 
10246  return OFFT2NUM(st.total);
10247 }
10248 
10249 /*
10250  * call-seq:
10251  * io.external_encoding -> encoding
10252  *
10253  * Returns the Encoding object that represents the encoding of the file.
10254  * If io is write mode and no encoding is specified, returns <code>nil</code>.
10255  */
10256 
10257 static VALUE
10259 {
10260  rb_io_t *fptr;
10261 
10262  GetOpenFile(io, fptr);
10263  if (fptr->encs.enc2) {
10264  return rb_enc_from_encoding(fptr->encs.enc2);
10265  }
10266  if (fptr->mode & FMODE_WRITABLE) {
10267  if (fptr->encs.enc)
10268  return rb_enc_from_encoding(fptr->encs.enc);
10269  return Qnil;
10270  }
10271  return rb_enc_from_encoding(io_read_encoding(fptr));
10272 }
10273 
10274 /*
10275  * call-seq:
10276  * io.internal_encoding -> encoding
10277  *
10278  * Returns the Encoding of the internal string if conversion is
10279  * specified. Otherwise returns nil.
10280  */
10281 
10282 static VALUE
10284 {
10285  rb_io_t *fptr;
10286 
10287  GetOpenFile(io, fptr);
10288  if (!fptr->encs.enc2) return Qnil;
10289  return rb_enc_from_encoding(io_read_encoding(fptr));
10290 }
10291 
10292 /*
10293  * call-seq:
10294  * io.set_encoding(ext_enc) -> io
10295  * io.set_encoding("ext_enc:int_enc") -> io
10296  * io.set_encoding(ext_enc, int_enc) -> io
10297  * io.set_encoding("ext_enc:int_enc", opt) -> io
10298  * io.set_encoding(ext_enc, int_enc, opt) -> io
10299  *
10300  * If single argument is specified, read string from io is tagged
10301  * with the encoding specified. If encoding is a colon separated two
10302  * encoding names "A:B", the read string is converted from encoding A
10303  * (external encoding) to encoding B (internal encoding), then tagged
10304  * with B. If two arguments are specified, those must be encoding
10305  * objects or encoding names, and the first one is the external encoding, and the
10306  * second one is the internal encoding.
10307  * If the external encoding and the internal encoding is specified,
10308  * optional hash argument specify the conversion option.
10309  */
10310 
10311 static VALUE
10313 {
10314  rb_io_t *fptr;
10315  VALUE v1, v2, opt;
10316 
10317  if (!RB_TYPE_P(io, T_FILE)) {
10318  return rb_funcall2(io, id_set_encoding, argc, argv);
10319  }
10320 
10321  argc = rb_scan_args(argc, argv, "11:", &v1, &v2, &opt);
10322  GetOpenFile(io, fptr);
10323  io_encoding_set(fptr, v1, v2, opt);
10324  return io;
10325 }
10326 
10327 void
10329 {
10330  extern VALUE rb_stdin, rb_stdout, rb_stderr;
10331  VALUE val = Qnil;
10332 
10333  rb_io_set_encoding(1, &val, rb_stdin);
10334  rb_io_set_encoding(1, &val, rb_stdout);
10335  rb_io_set_encoding(1, &val, rb_stderr);
10336 }
10337 
10338 /*
10339  * call-seq:
10340  * ARGF.external_encoding -> encoding
10341  *
10342  * Returns the external encoding for files read from +ARGF+ as an +Encoding+
10343  * object. The external encoding is the encoding of the text as stored in a
10344  * file. Contrast with +ARGF.internal_encoding+, which is the encoding used
10345  * to represent this text within Ruby.
10346  *
10347  * To set the external encoding use +ARGF.set_encoding+.
10348  *
10349  * For example:
10350  *
10351  * ARGF.external_encoding #=> #<Encoding:UTF-8>
10352  *
10353  */
10354 static VALUE
10356 {
10357  if (!RTEST(ARGF.current_file)) {
10359  }
10360  return rb_io_external_encoding(rb_io_check_io(ARGF.current_file));
10361 }
10362 
10363 /*
10364  * call-seq:
10365  * ARGF.internal_encoding -> encoding
10366  *
10367  * Returns the internal encoding for strings read from +ARGF+ as an
10368  * +Encoding+ object.
10369  *
10370  * If +ARGF.set_encoding+ has been called with two encoding names, the second
10371  * is returned. Otherwise, if +Encoding.default_external+ has been set, that
10372  * value is returned. Failing that, if a default external encoding was
10373  * specified on the command-line, that value is used. If the encoding is
10374  * unknown, nil is returned.
10375  */
10376 static VALUE
10378 {
10379  if (!RTEST(ARGF.current_file)) {
10381  }
10382  return rb_io_internal_encoding(rb_io_check_io(ARGF.current_file));
10383 }
10384 
10385 /*
10386  * call-seq:
10387  * ARGF.set_encoding(ext_enc) -> ARGF
10388  * ARGF.set_encoding("ext_enc:int_enc") -> ARGF
10389  * ARGF.set_encoding(ext_enc, int_enc) -> ARGF
10390  * ARGF.set_encoding("ext_enc:int_enc", opt) -> ARGF
10391  * ARGF.set_encoding(ext_enc, int_enc, opt) -> ARGF
10392  *
10393  * If single argument is specified, strings read from ARGF are tagged with
10394  * the encoding specified.
10395  *
10396  * If two encoding names separated by a colon are given, e.g. "ascii:utf-8",
10397  * the read string is converted from the first encoding (external encoding)
10398  * to the second encoding (internal encoding), then tagged with the second
10399  * encoding.
10400  *
10401  * If two arguments are specified, they must be encoding objects or encoding
10402  * names. Again, the first specifies the external encoding; the second
10403  * specifies the internal encoding.
10404  *
10405  * If the external encoding and the internal encoding are specified, the
10406  * optional +Hash+ argument can be used to adjust the conversion process. The
10407  * structure of this hash is explained in the +String#encode+ documentation.
10408  *
10409  * For example:
10410  *
10411  * ARGF.set_encoding('ascii') # Tag the input as US-ASCII text
10412  * ARGF.set_encoding(Encoding::UTF_8) # Tag the input as UTF-8 text
10413  * ARGF.set_encoding('utf-8','ascii') # Transcode the input from US-ASCII
10414  * # to UTF-8.
10415  */
10416 static VALUE
10418 {
10419  rb_io_t *fptr;
10420 
10421  if (!next_argv()) {
10422  rb_raise(rb_eArgError, "no stream to set encoding");
10423  }
10424  rb_io_set_encoding(argc, argv, ARGF.current_file);
10425  GetOpenFile(ARGF.current_file, fptr);
10426  ARGF.encs = fptr->encs;
10427  return argf;
10428 }
10429 
10430 /*
10431  * call-seq:
10432  * ARGF.tell -> Integer
10433  * ARGF.pos -> Integer
10434  *
10435  * Returns the current offset (in bytes) of the current file in +ARGF+.
10436  *
10437  * ARGF.pos #=> 0
10438  * ARGF.gets #=> "This is line one\n"
10439  * ARGF.pos #=> 17
10440  *
10441  */
10442 static VALUE
10444 {
10445  if (!next_argv()) {
10446  rb_raise(rb_eArgError, "no stream to tell");
10447  }
10448  ARGF_FORWARD(0, 0);
10449  return rb_io_tell(ARGF.current_file);
10450 }
10451 
10452 /*
10453  * call-seq:
10454  * ARGF.seek(amount, whence=IO::SEEK_SET) -> 0
10455  *
10456  * Seeks to offset _amount_ (an +Integer+) in the +ARGF+ stream according to
10457  * the value of _whence_. See +IO#seek+ for further details.
10458  */
10459 static VALUE
10461 {
10462  if (!next_argv()) {
10463  rb_raise(rb_eArgError, "no stream to seek");
10464  }
10465  ARGF_FORWARD(argc, argv);
10466  return rb_io_seek_m(argc, argv, ARGF.current_file);
10467 }
10468 
10469 /*
10470  * call-seq:
10471  * ARGF.pos = position -> Integer
10472  *
10473  * Seeks to the position given by _position_ (in bytes) in +ARGF+.
10474  *
10475  * For example:
10476  *
10477  * ARGF.pos = 17
10478  * ARGF.gets #=> "This is line two\n"
10479  */
10480 static VALUE
10482 {
10483  if (!next_argv()) {
10484  rb_raise(rb_eArgError, "no stream to set position");
10485  }
10486  ARGF_FORWARD(1, &offset);
10487  return rb_io_set_pos(ARGF.current_file, offset);
10488 }
10489 
10490 /*
10491  * call-seq:
10492  * ARGF.rewind -> 0
10493  *
10494  * Positions the current file to the beginning of input, resetting
10495  * +ARGF.lineno+ to zero.
10496  *
10497  * ARGF.readline #=> "This is line one\n"
10498  * ARGF.rewind #=> 0
10499  * ARGF.lineno #=> 0
10500  * ARGF.readline #=> "This is line one\n"
10501  */
10502 static VALUE
10504 {
10505  if (!next_argv()) {
10506  rb_raise(rb_eArgError, "no stream to rewind");
10507  }
10508  ARGF_FORWARD(0, 0);
10509  return rb_io_rewind(ARGF.current_file);
10510 }
10511 
10512 /*
10513  * call-seq:
10514  * ARGF.fileno -> fixnum
10515  * ARGF.to_i -> fixnum
10516  *
10517  * Returns an integer representing the numeric file descriptor for
10518  * the current file. Raises an +ArgumentError+ if there isn't a current file.
10519  *
10520  * ARGF.fileno #=> 3
10521  */
10522 static VALUE
10524 {
10525  if (!next_argv()) {
10526  rb_raise(rb_eArgError, "no stream");
10527  }
10528  ARGF_FORWARD(0, 0);
10529  return rb_io_fileno(ARGF.current_file);
10530 }
10531 
10532 /*
10533  * call-seq:
10534  * ARGF.to_io -> IO
10535  *
10536  * Returns an +IO+ object representing the current file. This will be a
10537  * +File+ object unless the current file is a stream such as STDIN.
10538  *
10539  * For example:
10540  *
10541  * ARGF.to_io #=> #<File:glark.txt>
10542  * ARGF.to_io #=> #<IO:<STDIN>>
10543  */
10544 static VALUE
10546 {
10547  next_argv();
10548  ARGF_FORWARD(0, 0);
10549  return ARGF.current_file;
10550 }
10551 
10552 /*
10553  * call-seq:
10554  * ARGF.eof? -> true or false
10555  * ARGF.eof -> true or false
10556  *
10557  * Returns true if the current file in +ARGF+ is at end of file, i.e. it has
10558  * no data to read. The stream must be opened for reading or an +IOError+
10559  * will be raised.
10560  *
10561  * $ echo "eof" | ruby argf.rb
10562  *
10563  * ARGF.eof? #=> false
10564  * 3.times { ARGF.readchar }
10565  * ARGF.eof? #=> false
10566  * ARGF.readchar #=> "\n"
10567  * ARGF.eof? #=> true
10568  */
10569 
10570 static VALUE
10572 {
10573  next_argv();
10574  if (RTEST(ARGF.current_file)) {
10575  if (ARGF.init_p == 0) return Qtrue;
10576  next_argv();
10577  ARGF_FORWARD(0, 0);
10578  if (rb_io_eof(ARGF.current_file)) {
10579  return Qtrue;
10580  }
10581  }
10582  return Qfalse;
10583 }
10584 
10585 /*
10586  * call-seq:
10587  * ARGF.read([length [, outbuf]]) -> string, outbuf, or nil
10588  *
10589  * Reads _length_ bytes from ARGF. The files named on the command line
10590  * are concatenated and treated as a single file by this method, so when
10591  * called without arguments the contents of this pseudo file are returned in
10592  * their entirety.
10593  *
10594  * _length_ must be a non-negative integer or nil. If it is a positive
10595  * integer, +read+ tries to read at most _length_ bytes. It returns nil
10596  * if an EOF was encountered before anything could be read. Fewer than
10597  * _length_ bytes may be returned if an EOF is encountered during the read.
10598  *
10599  * If _length_ is omitted or is _nil_, it reads until EOF. A String is
10600  * returned even if EOF is encountered before any data is read.
10601  *
10602  * If _length_ is zero, it returns _""_.
10603  *
10604  * If the optional _outbuf_ argument is present, it must reference a String,
10605  * which will receive the data.
10606  * The <i>outbuf</i> will contain only the received data after the method call
10607  * even if it is not empty at the beginning.
10608  *
10609  * For example:
10610  *
10611  * $ echo "small" > small.txt
10612  * $ echo "large" > large.txt
10613  * $ ./glark.rb small.txt large.txt
10614  *
10615  * ARGF.read #=> "small\nlarge"
10616  * ARGF.read(200) #=> "small\nlarge"
10617  * ARGF.read(2) #=> "sm"
10618  * ARGF.read(0) #=> ""
10619  *
10620  * Note that this method behaves like fread() function in C. If you need the
10621  * behavior like read(2) system call, consider +ARGF.readpartial+.
10622  */
10623 
10624 static VALUE
10626 {
10627  VALUE tmp, str, length;
10628  long len = 0;
10629 
10630  rb_scan_args(argc, argv, "02", &length, &str);
10631  if (!NIL_P(length)) {
10632  len = NUM2LONG(argv[0]);
10633  }
10634  if (!NIL_P(str)) {
10635  StringValue(str);
10636  rb_str_resize(str,0);
10637  argv[1] = Qnil;
10638  }
10639 
10640  retry:
10641  if (!next_argv()) {
10642  return str;
10643  }
10644  if (ARGF_GENERIC_INPUT_P()) {
10645  tmp = argf_forward(argc, argv, argf);
10646  }
10647  else {
10648  tmp = io_read(argc, argv, ARGF.current_file);
10649  }
10650  if (NIL_P(str)) str = tmp;
10651  else if (!NIL_P(tmp)) rb_str_append(str, tmp);
10652  if (NIL_P(tmp) || NIL_P(length)) {
10653  if (ARGF.next_p != -1) {
10654  argf_close(ARGF.current_file);
10655  ARGF.next_p = 1;
10656  goto retry;
10657  }
10658  }
10659  else if (argc >= 1) {
10660  if (RSTRING_LEN(str) < len) {
10661  len -= RSTRING_LEN(str);
10662  argv[0] = INT2NUM(len);
10663  goto retry;
10664  }
10665  }
10666  return str;
10667 }
10668 
10670  int argc;
10673 };
10674 
10675 static VALUE
10677 {
10678  struct argf_call_arg *p = (struct argf_call_arg *)arg;
10679  argf_forward(p->argc, p->argv, p->argf);
10680  return Qnil;
10681 }
10682 
10683 static VALUE argf_getpartial(int argc, VALUE *argv, VALUE argf, int nonblock);
10684 
10685 /*
10686  * call-seq:
10687  * ARGF.readpartial(maxlen) -> string
10688  * ARGF.readpartial(maxlen, outbuf) -> outbuf
10689  *
10690  * Reads at most _maxlen_ bytes from the ARGF stream. It blocks only if
10691  * +ARGF+ has no data immediately available. If the optional _outbuf_
10692  * argument is present, it must reference a String, which will receive the
10693  * data.
10694  * The <i>outbuf</i> will contain only the received data after the method call
10695  * even if it is not empty at the beginning.
10696  * It raises <code>EOFError</code> on end of file.
10697  *
10698  * +readpartial+ is designed for streams such as pipes, sockets, and ttys. It
10699  * blocks only when no data is immediately available. This means that it
10700  * blocks only when following all conditions hold:
10701  *
10702  * * The byte buffer in the +IO+ object is empty.
10703  * * The content of the stream is empty.
10704  * * The stream has not reached EOF.
10705  *
10706  * When +readpartial+ blocks, it waits for data or EOF. If some data is read,
10707  * +readpartial+ returns with the data. If EOF is reached, readpartial raises
10708  * an +EOFError+.
10709  *
10710  * When +readpartial+ doesn't block, it returns or raises immediately. If
10711  * the byte buffer is not empty, it returns the data in the buffer. Otherwise, if
10712  * the stream has some content, it returns the data in the stream. If the
10713  * stream reaches EOF an +EOFError+ is raised.
10714  */
10715 
10716 static VALUE
10718 {
10719  return argf_getpartial(argc, argv, argf, 0);
10720 }
10721 
10722 /*
10723  * call-seq:
10724  * ARGF.read_nonblock(maxlen) -> string
10725  * ARGF.read_nonblock(maxlen, outbuf) -> outbuf
10726  *
10727  * Reads at most _maxlen_ bytes from the ARGF stream in non-blocking mode.
10728  */
10729 
10730 static VALUE
10732 {
10733  return argf_getpartial(argc, argv, argf, 1);
10734 }
10735 
10736 static VALUE
10737 argf_getpartial(int argc, VALUE *argv, VALUE argf, int nonblock)
10738 {
10739  VALUE tmp, str, length;
10740 
10741  rb_scan_args(argc, argv, "11", &length, &str);
10742  if (!NIL_P(str)) {
10743  StringValue(str);
10744  argv[1] = str;
10745  }
10746 
10747  if (!next_argv()) {
10748  rb_str_resize(str, 0);
10749  rb_eof_error();
10750  }
10751  if (ARGF_GENERIC_INPUT_P()) {
10752  struct argf_call_arg arg;
10753  arg.argc = argc;
10754  arg.argv = argv;
10755  arg.argf = argf;
10756  tmp = rb_rescue2(argf_forward_call, (VALUE)&arg,
10758  }
10759  else {
10760  tmp = io_getpartial(argc, argv, ARGF.current_file, nonblock);
10761  }
10762  if (NIL_P(tmp)) {
10763  if (ARGF.next_p == -1) {
10764  rb_eof_error();
10765  }
10766  argf_close(ARGF.current_file);
10767  ARGF.next_p = 1;
10768  if (RARRAY_LEN(ARGF.argv) == 0)
10769  rb_eof_error();
10770  if (NIL_P(str))
10771  str = rb_str_new(NULL, 0);
10772  return str;
10773  }
10774  return tmp;
10775 }
10776 
10777 /*
10778  * call-seq:
10779  * ARGF.getc -> String or nil
10780  *
10781  * Reads the next character from +ARGF+ and returns it as a +String+. Returns
10782  * +nil+ at the end of the stream.
10783  *
10784  * +ARGF+ treats the files named on the command line as a single file created
10785  * by concatenating their contents. After returning the last character of the
10786  * first file, it returns the first character of the second file, and so on.
10787  *
10788  * For example:
10789  *
10790  * $ echo "foo" > file
10791  * $ ruby argf.rb file
10792  *
10793  * ARGF.getc #=> "f"
10794  * ARGF.getc #=> "o"
10795  * ARGF.getc #=> "o"
10796  * ARGF.getc #=> "\n"
10797  * ARGF.getc #=> nil
10798  * ARGF.getc #=> nil
10799  */
10800 static VALUE
10802 {
10803  VALUE ch;
10804 
10805  retry:
10806  if (!next_argv()) return Qnil;
10807  if (ARGF_GENERIC_INPUT_P()) {
10808  ch = rb_funcall3(ARGF.current_file, rb_intern("getc"), 0, 0);
10809  }
10810  else {
10811  ch = rb_io_getc(ARGF.current_file);
10812  }
10813  if (NIL_P(ch) && ARGF.next_p != -1) {
10814  argf_close(ARGF.current_file);
10815  ARGF.next_p = 1;
10816  goto retry;
10817  }
10818 
10819  return ch;
10820 }
10821 
10822 /*
10823  * call-seq:
10824  * ARGF.getbyte -> Fixnum or nil
10825  *
10826  * Gets the next 8-bit byte (0..255) from +ARGF+. Returns +nil+ if called at
10827  * the end of the stream.
10828  *
10829  * For example:
10830  *
10831  * $ echo "foo" > file
10832  * $ ruby argf.rb file
10833  *
10834  * ARGF.getbyte #=> 102
10835  * ARGF.getbyte #=> 111
10836  * ARGF.getbyte #=> 111
10837  * ARGF.getbyte #=> 10
10838  * ARGF.getbyte #=> nil
10839  */
10840 static VALUE
10842 {
10843  VALUE ch;
10844 
10845  retry:
10846  if (!next_argv()) return Qnil;
10847  if (!RB_TYPE_P(ARGF.current_file, T_FILE)) {
10848  ch = rb_funcall3(ARGF.current_file, rb_intern("getbyte"), 0, 0);
10849  }
10850  else {
10851  ch = rb_io_getbyte(ARGF.current_file);
10852  }
10853  if (NIL_P(ch) && ARGF.next_p != -1) {
10854  argf_close(ARGF.current_file);
10855  ARGF.next_p = 1;
10856  goto retry;
10857  }
10858 
10859  return ch;
10860 }
10861 
10862 /*
10863  * call-seq:
10864  * ARGF.readchar -> String or nil
10865  *
10866  * Reads the next character from +ARGF+ and returns it as a +String+. Raises
10867  * an +EOFError+ after the last character of the last file has been read.
10868  *
10869  * For example:
10870  *
10871  * $ echo "foo" > file
10872  * $ ruby argf.rb file
10873  *
10874  * ARGF.readchar #=> "f"
10875  * ARGF.readchar #=> "o"
10876  * ARGF.readchar #=> "o"
10877  * ARGF.readchar #=> "\n"
10878  * ARGF.readchar #=> end of file reached (EOFError)
10879  */
10880 static VALUE
10882 {
10883  VALUE ch;
10884 
10885  retry:
10886  if (!next_argv()) rb_eof_error();
10887  if (!RB_TYPE_P(ARGF.current_file, T_FILE)) {
10888  ch = rb_funcall3(ARGF.current_file, rb_intern("getc"), 0, 0);
10889  }
10890  else {
10891  ch = rb_io_getc(ARGF.current_file);
10892  }
10893  if (NIL_P(ch) && ARGF.next_p != -1) {
10894  argf_close(ARGF.current_file);
10895  ARGF.next_p = 1;
10896  goto retry;
10897  }
10898 
10899  return ch;
10900 }
10901 
10902 /*
10903  * call-seq:
10904  * ARGF.readbyte -> Fixnum
10905  *
10906  * Reads the next 8-bit byte from ARGF and returns it as a +Fixnum+. Raises
10907  * an +EOFError+ after the last byte of the last file has been read.
10908  *
10909  * For example:
10910  *
10911  * $ echo "foo" > file
10912  * $ ruby argf.rb file
10913  *
10914  * ARGF.readbyte #=> 102
10915  * ARGF.readbyte #=> 111
10916  * ARGF.readbyte #=> 111
10917  * ARGF.readbyte #=> 10
10918  * ARGF.readbyte #=> end of file reached (EOFError)
10919  */
10920 static VALUE
10922 {
10923  VALUE c;
10924 
10925  NEXT_ARGF_FORWARD(0, 0);
10926  c = argf_getbyte(argf);
10927  if (NIL_P(c)) {
10928  rb_eof_error();
10929  }
10930  return c;
10931 }
10932 
10933 /*
10934  * call-seq:
10935  * ARGF.each(sep=$/) {|line| block } -> ARGF
10936  * ARGF.each(sep=$/,limit) {|line| block } -> ARGF
10937  * ARGF.each(...) -> an_enumerator
10938  *
10939  * ARGF.each_line(sep=$/) {|line| block } -> ARGF
10940  * ARGF.each_line(sep=$/,limit) {|line| block } -> ARGF
10941  * ARGF.each_line(...) -> an_enumerator
10942  *
10943  * Returns an enumerator which iterates over each line (separated by _sep_,
10944  * which defaults to your platform's newline character) of each file in
10945  * +ARGV+. If a block is supplied, each line in turn will be yielded to the
10946  * block, otherwise an enumerator is returned.
10947  * The optional _limit_ argument is a +Fixnum+ specifying the maximum
10948  * length of each line; longer lines will be split according to this limit.
10949  *
10950  * This method allows you to treat the files supplied on the command line as
10951  * a single file consisting of the concatenation of each named file. After
10952  * the last line of the first file has been returned, the first line of the
10953  * second file is returned. The +ARGF.filename+ and +ARGF.lineno+ methods can
10954  * be used to determine the filename and line number, respectively, of the
10955  * current line.
10956  *
10957  * For example, the following code prints out each line of each named file
10958  * prefixed with its line number, displaying the filename once per file:
10959  *
10960  * ARGF.lines do |line|
10961  * puts ARGF.filename if ARGF.lineno == 1
10962  * puts "#{ARGF.lineno}: #{line}"
10963  * end
10964  */
10965 static VALUE
10967 {
10968  RETURN_ENUMERATOR(argf, argc, argv);
10969  for (;;) {
10970  if (!next_argv()) return argf;
10971  rb_block_call(ARGF.current_file, rb_intern("each_line"), argc, argv, 0, 0);
10972  ARGF.next_p = 1;
10973  }
10974 }
10975 
10976 /*
10977  * This is a deprecated alias for <code>each_line</code>.
10978  */
10979 
10980 static VALUE
10982 {
10983  rb_warn("ARGF#lines is deprecated; use #each_line instead");
10984  if (!rb_block_given_p())
10985  return rb_enumeratorize(argf, ID2SYM(rb_intern("each_line")), argc, argv);
10986  return argf_each_line(argc, argv, argf);
10987 }
10988 
10989 /*
10990  * call-seq:
10991  * ARGF.bytes {|byte| block } -> ARGF
10992  * ARGF.bytes -> an_enumerator
10993  *
10994  * ARGF.each_byte {|byte| block } -> ARGF
10995  * ARGF.each_byte -> an_enumerator
10996  *
10997  * Iterates over each byte of each file in +ARGV+.
10998  * A byte is returned as a +Fixnum+ in the range 0..255.
10999  *
11000  * This method allows you to treat the files supplied on the command line as
11001  * a single file consisting of the concatenation of each named file. After
11002  * the last byte of the first file has been returned, the first byte of the
11003  * second file is returned. The +ARGF.filename+ method can be used to
11004  * determine the filename of the current byte.
11005  *
11006  * If no block is given, an enumerator is returned instead.
11007  *
11008  * For example:
11009  *
11010  * ARGF.bytes.to_a #=> [35, 32, ... 95, 10]
11011  *
11012  */
11013 static VALUE
11015 {
11016  RETURN_ENUMERATOR(argf, 0, 0);
11017  for (;;) {
11018  if (!next_argv()) return argf;
11019  rb_block_call(ARGF.current_file, rb_intern("each_byte"), 0, 0, 0, 0);
11020  ARGF.next_p = 1;
11021  }
11022 }
11023 
11024 /*
11025  * This is a deprecated alias for <code>each_byte</code>.
11026  */
11027 
11028 static VALUE
11030 {
11031  rb_warn("ARGF#bytes is deprecated; use #each_byte instead");
11032  if (!rb_block_given_p())
11033  return rb_enumeratorize(argf, ID2SYM(rb_intern("each_byte")), 0, 0);
11034  return argf_each_byte(argf);
11035 }
11036 
11037 /*
11038  * call-seq:
11039  * ARGF.each_char {|char| block } -> ARGF
11040  * ARGF.each_char -> an_enumerator
11041  *
11042  * Iterates over each character of each file in +ARGF+.
11043  *
11044  * This method allows you to treat the files supplied on the command line as
11045  * a single file consisting of the concatenation of each named file. After
11046  * the last character of the first file has been returned, the first
11047  * character of the second file is returned. The +ARGF.filename+ method can
11048  * be used to determine the name of the file in which the current character
11049  * appears.
11050  *
11051  * If no block is given, an enumerator is returned instead.
11052  */
11053 static VALUE
11055 {
11056  RETURN_ENUMERATOR(argf, 0, 0);
11057  for (;;) {
11058  if (!next_argv()) return argf;
11059  rb_block_call(ARGF.current_file, rb_intern("each_char"), 0, 0, 0, 0);
11060  ARGF.next_p = 1;
11061  }
11062 }
11063 
11064 /*
11065  * This is a deprecated alias for <code>each_char</code>.
11066  */
11067 
11068 static VALUE
11070 {
11071  rb_warn("ARGF#chars is deprecated; use #each_char instead");
11072  if (!rb_block_given_p())
11073  return rb_enumeratorize(argf, ID2SYM(rb_intern("each_char")), 0, 0);
11074  return argf_each_char(argf);
11075 }
11076 
11077 /*
11078  * call-seq:
11079  * ARGF.each_codepoint {|codepoint| block } -> ARGF
11080  * ARGF.each_codepoint -> an_enumerator
11081  *
11082  * Iterates over each codepoint of each file in +ARGF+.
11083  *
11084  * This method allows you to treat the files supplied on the command line as
11085  * a single file consisting of the concatenation of each named file. After
11086  * the last codepoint of the first file has been returned, the first
11087  * codepoint of the second file is returned. The +ARGF.filename+ method can
11088  * be used to determine the name of the file in which the current codepoint
11089  * appears.
11090  *
11091  * If no block is given, an enumerator is returned instead.
11092  */
11093 static VALUE
11095 {
11096  RETURN_ENUMERATOR(argf, 0, 0);
11097  for (;;) {
11098  if (!next_argv()) return argf;
11099  rb_block_call(ARGF.current_file, rb_intern("each_codepoint"), 0, 0, 0, 0);
11100  ARGF.next_p = 1;
11101  }
11102 }
11103 
11104 /*
11105  * This is a deprecated alias for <code>each_codepoint</code>.
11106  */
11107 
11108 static VALUE
11110 {
11111  rb_warn("ARGF#codepoints is deprecated; use #each_codepoint instead");
11112  if (!rb_block_given_p())
11113  return rb_enumeratorize(argf, ID2SYM(rb_intern("each_codepoint")), 0, 0);
11114  return argf_each_codepoint(argf);
11115 }
11116 
11117 /*
11118  * call-seq:
11119  * ARGF.filename -> String
11120  * ARGF.path -> String
11121  *
11122  * Returns the current filename. "-" is returned when the current file is
11123  * STDIN.
11124  *
11125  * For example:
11126  *
11127  * $ echo "foo" > foo
11128  * $ echo "bar" > bar
11129  * $ echo "glark" > glark
11130  *
11131  * $ ruby argf.rb foo bar glark
11132  *
11133  * ARGF.filename #=> "foo"
11134  * ARGF.read(5) #=> "foo\nb"
11135  * ARGF.filename #=> "bar"
11136  * ARGF.skip
11137  * ARGF.filename #=> "glark"
11138  */
11139 static VALUE
11141 {
11142  next_argv();
11143  return ARGF.filename;
11144 }
11145 
11146 static VALUE
11148 {
11149  return argf_filename(*var);
11150 }
11151 
11152 /*
11153  * call-seq:
11154  * ARGF.file -> IO or File object
11155  *
11156  * Returns the current file as an +IO+ or +File+ object. #<IO:<STDIN>> is
11157  * returned when the current file is STDIN.
11158  *
11159  * For example:
11160  *
11161  * $ echo "foo" > foo
11162  * $ echo "bar" > bar
11163  *
11164  * $ ruby argf.rb foo bar
11165  *
11166  * ARGF.file #=> #<File:foo>
11167  * ARGF.read(5) #=> "foo\nb"
11168  * ARGF.file #=> #<File:bar>
11169  */
11170 static VALUE
11172 {
11173  next_argv();
11174  return ARGF.current_file;
11175 }
11176 
11177 /*
11178  * call-seq:
11179  * ARGF.binmode -> ARGF
11180  *
11181  * Puts +ARGF+ into binary mode. Once a stream is in binary mode, it cannot
11182  * be reset to non-binary mode. This option has the following effects:
11183  *
11184  * * Newline conversion is disabled.
11185  * * Encoding conversion is disabled.
11186  * * Content is treated as ASCII-8BIT.
11187  */
11188 static VALUE
11190 {
11191  ARGF.binmode = 1;
11192  next_argv();
11193  ARGF_FORWARD(0, 0);
11194  rb_io_ascii8bit_binmode(ARGF.current_file);
11195  return argf;
11196 }
11197 
11198 /*
11199  * call-seq:
11200  * ARGF.binmode? -> true or false
11201  *
11202  * Returns true if +ARGF+ is being read in binary mode; false otherwise. (To
11203  * enable binary mode use +ARGF.binmode+.
11204  *
11205  * For example:
11206  *
11207  * ARGF.binmode? #=> false
11208  * ARGF.binmode
11209  * ARGF.binmode? #=> true
11210  */
11211 static VALUE
11213 {
11214  return ARGF.binmode ? Qtrue : Qfalse;
11215 }
11216 
11217 /*
11218  * call-seq:
11219  * ARGF.skip -> ARGF
11220  *
11221  * Sets the current file to the next file in ARGV. If there aren't any more
11222  * files it has no effect.
11223  *
11224  * For example:
11225  *
11226  * $ ruby argf.rb foo bar
11227  * ARGF.filename #=> "foo"
11228  * ARGF.skip
11229  * ARGF.filename #=> "bar"
11230  */
11231 static VALUE
11233 {
11234  if (ARGF.init_p && ARGF.next_p == 0) {
11235  argf_close(ARGF.current_file);
11236  ARGF.next_p = 1;
11237  }
11238  return argf;
11239 }
11240 
11241 /*
11242  * call-seq:
11243  * ARGF.close -> ARGF
11244  *
11245  * Closes the current file and skips to the next in the stream. Trying to
11246  * close a file that has already been closed causes an +IOError+ to be
11247  * raised.
11248  *
11249  * For example:
11250  *
11251  * $ ruby argf.rb foo bar
11252  *
11253  * ARGF.filename #=> "foo"
11254  * ARGF.close
11255  * ARGF.filename #=> "bar"
11256  * ARGF.close
11257  * ARGF.close #=> closed stream (IOError)
11258  */
11259 static VALUE
11261 {
11262  next_argv();
11263  argf_close(ARGF.current_file);
11264  if (ARGF.next_p != -1) {
11265  ARGF.next_p = 1;
11266  }
11267  ARGF.lineno = 0;
11268  return argf;
11269 }
11270 
11271 /*
11272  * call-seq:
11273  * ARGF.closed? -> true or false
11274  *
11275  * Returns _true_ if the current file has been closed; _false_ otherwise. Use
11276  * +ARGF.close+ to actually close the current file.
11277  */
11278 static VALUE
11280 {
11281  next_argv();
11282  ARGF_FORWARD(0, 0);
11283  return rb_io_closed(ARGF.current_file);
11284 }
11285 
11286 /*
11287  * call-seq:
11288  * ARGF.to_s -> String
11289  *
11290  * Returns "ARGF".
11291  */
11292 static VALUE
11294 {
11295  return rb_str_new2("ARGF");
11296 }
11297 
11298 /*
11299  * call-seq:
11300  * ARGF.inplace_mode -> String
11301  *
11302  * Returns the file extension appended to the names of modified files under
11303  * inplace-edit mode. This value can be set using +ARGF.inplace_mode=+ or
11304  * passing the +-i+ switch to the Ruby binary.
11305  */
11306 static VALUE
11308 {
11309  if (!ARGF.inplace) return Qnil;
11310  return rb_str_new2(ARGF.inplace);
11311 }
11312 
11313 static VALUE
11314 opt_i_get(ID id, VALUE *var)
11315 {
11316  return argf_inplace_mode_get(*var);
11317 }
11318 
11319 /*
11320  * call-seq:
11321  * ARGF.inplace_mode = ext -> ARGF
11322  *
11323  * Sets the filename extension for inplace editing mode to the given String.
11324  * Each file being edited has this value appended to its filename. The
11325  * modified file is saved under this new name.
11326  *
11327  * For example:
11328  *
11329  * $ ruby argf.rb file.txt
11330  *
11331  * ARGF.inplace_mode = '.bak'
11332  * ARGF.lines do |line|
11333  * print line.sub("foo","bar")
11334  * end
11335  *
11336  * Each line of _file.txt_ has the first occurrence of "foo" replaced with
11337  * "bar", then the new line is written out to _file.txt.bak_.
11338  */
11339 static VALUE
11341 {
11342  if (rb_safe_level() >= 1 && OBJ_TAINTED(val))
11344 
11345  if (!RTEST(val)) {
11346  if (ARGF.inplace) free(ARGF.inplace);
11347  ARGF.inplace = 0;
11348  }
11349  else {
11350  StringValue(val);
11351  if (ARGF.inplace) free(ARGF.inplace);
11352  ARGF.inplace = 0;
11353  ARGF.inplace = strdup(RSTRING_PTR(val));
11354  }
11355  return argf;
11356 }
11357 
11358 static void
11359 opt_i_set(VALUE val, ID id, VALUE *var)
11360 {
11361  argf_inplace_mode_set(*var, val);
11362 }
11363 
11364 const char *
11366 {
11367  return ARGF.inplace;
11368 }
11369 
11370 void
11371 ruby_set_inplace_mode(const char *suffix)
11372 {
11373  if (ARGF.inplace) free(ARGF.inplace);
11374  ARGF.inplace = 0;
11375  if (suffix) ARGF.inplace = strdup(suffix);
11376 }
11377 
11378 /*
11379  * call-seq:
11380  * ARGF.argv -> ARGV
11381  *
11382  * Returns the +ARGV+ array, which contains the arguments passed to your
11383  * script, one per element.
11384  *
11385  * For example:
11386  *
11387  * $ ruby argf.rb -v glark.txt
11388  *
11389  * ARGF.argv #=> ["-v", "glark.txt"]
11390  *
11391  */
11392 static VALUE
11394 {
11395  return ARGF.argv;
11396 }
11397 
11398 static VALUE
11400 {
11401  return argf_argv(*var);
11402 }
11403 
11404 VALUE
11406 {
11407  return ARGF.argv;
11408 }
11409 
11410 /*
11411  * call-seq:
11412  * ARGF.to_write_io -> io
11413  *
11414  * Returns IO instance tied to _ARGF_ for writing if inplace mode is
11415  * enabled.
11416  */
11417 static VALUE
11419 {
11420  if (!RTEST(ARGF.current_file)) {
11421  rb_raise(rb_eIOError, "not opened for writing");
11422  }
11423  return GetWriteIO(ARGF.current_file);
11424 }
11425 
11426 /*
11427  * call-seq:
11428  * ARGF.write(string) -> integer
11429  *
11430  * Writes _string_ if inplace mode.
11431  */
11432 static VALUE
11434 {
11435  return rb_io_write(argf_write_io(argf), str);
11436 }
11437 
11438 /*
11439  * Document-class: IOError
11440  *
11441  * Raised when an IO operation fails.
11442  *
11443  * File.open("/etc/hosts") {|f| f << "example"}
11444  * #=> IOError: not opened for writing
11445  *
11446  * File.open("/etc/hosts") {|f| f.close; f.read }
11447  * #=> IOError: closed stream
11448  *
11449  * Note that some IO failures raise +SystemCallError+s and these are not
11450  * subclasses of IOError:
11451  *
11452  * File.open("does/not/exist")
11453  * #=> Errno::ENOENT: No such file or directory - does/not/exist
11454  */
11455 
11456 /*
11457  * Document-class: EOFError
11458  *
11459  * Raised by some IO operations when reaching the end of file. Many IO
11460  * methods exist in two forms,
11461  *
11462  * one that returns +nil+ when the end of file is reached, the other
11463  * raises EOFError +EOFError+.
11464  *
11465  * +EOFError+ is a subclass of +IOError+.
11466  *
11467  * file = File.open("/etc/hosts")
11468  * file.read
11469  * file.gets #=> nil
11470  * file.readline #=> EOFError: end of file reached
11471  */
11472 
11473 /*
11474  * Document-class: ARGF
11475  *
11476  * +ARGF+ is a stream designed for use in scripts that process files given as
11477  * command-line arguments or passed in via STDIN.
11478  *
11479  * The arguments passed to your script are stored in the +ARGV+ Array, one
11480  * argument per element. +ARGF+ assumes that any arguments that aren't
11481  * filenames have been removed from +ARGV+. For example:
11482  *
11483  * $ ruby argf.rb --verbose file1 file2
11484  *
11485  * ARGV #=> ["--verbose", "file1", "file2"]
11486  * option = ARGV.shift #=> "--verbose"
11487  * ARGV #=> ["file1", "file2"]
11488  *
11489  * You can now use +ARGF+ to work with a concatenation of each of these named
11490  * files. For instance, +ARGF.read+ will return the contents of _file1_
11491  * followed by the contents of _file2_.
11492  *
11493  * After a file in +ARGV+ has been read +ARGF+ removes it from the Array.
11494  * Thus, after all files have been read +ARGV+ will be empty.
11495  *
11496  * You can manipulate +ARGV+ yourself to control what +ARGF+ operates on. If
11497  * you remove a file from +ARGV+, it is ignored by +ARGF+; if you add files to
11498  * +ARGV+, they are treated as if they were named on the command line. For
11499  * example:
11500  *
11501  * ARGV.replace ["file1"]
11502  * ARGF.readlines # Returns the contents of file1 as an Array
11503  * ARGV #=> []
11504  * ARGV.replace ["file2", "file3"]
11505  * ARGF.read # Returns the contents of file2 and file3
11506  *
11507  * If +ARGV+ is empty, +ARGF+ acts as if it contained STDIN, i.e. the data
11508  * piped to your script. For example:
11509  *
11510  * $ echo "glark" | ruby -e 'p ARGF.read'
11511  * "glark\n"
11512  */
11513 
11514 /*
11515  * The IO class is the basis for all input and output in Ruby.
11516  * An I/O stream may be <em>duplexed</em> (that is, bidirectional), and
11517  * so may use more than one native operating system stream.
11518  *
11519  * Many of the examples in this section use the File class, the only standard
11520  * subclass of IO. The two classes are closely associated. Like the File
11521  * class, the Socket library subclasses from IO (such as TCPSocket or
11522  * UDPSocket).
11523  *
11524  * The Kernel#open method can create an IO (or File) object for these types
11525  * of arguments:
11526  *
11527  * * A plain string represents a filename suitable for the underlying
11528  * operating system.
11529  *
11530  * * A string starting with <code>"|"</code> indicates a subprocess.
11531  * The remainder of the string following the <code>"|"</code> is
11532  * invoked as a process with appropriate input/output channels
11533  * connected to it.
11534  *
11535  * * A string equal to <code>"|-"</code> will create another Ruby
11536  * instance as a subprocess.
11537  *
11538  * The IO may be opened with different file modes (read-only, write-only) and
11539  * encodings for proper conversion. See IO.new for these options. See
11540  * Kernel#open for details of the various command formats described above.
11541  *
11542  * IO.popen, the Open3 library, or Process#spawn may also be used to
11543  * communicate with subprocesses through an IO.
11544  *
11545  * Ruby will convert pathnames between different operating system
11546  * conventions if possible. For instance, on a Windows system the
11547  * filename <code>"/gumby/ruby/test.rb"</code> will be opened as
11548  * <code>"\gumby\ruby\test.rb"</code>. When specifying a Windows-style
11549  * filename in a Ruby string, remember to escape the backslashes:
11550  *
11551  * "c:\\gumby\\ruby\\test.rb"
11552  *
11553  * Our examples here will use the Unix-style forward slashes;
11554  * File::ALT_SEPARATOR can be used to get the platform-specific separator
11555  * character.
11556  *
11557  * The global constant ARGF (also accessible as $<) provides an
11558  * IO-like stream which allows access to all files mentioned on the
11559  * command line (or STDIN if no files are mentioned). ARGF#path and its alias
11560  * ARGF#filename are provided to access the name of the file currently being
11561  * read.
11562  *
11563  * == io/console
11564  *
11565  * The io/console extension provides methods for interacting with the
11566  * console. The console can be accessed from IO.console or the standard
11567  * input/output/error IO objects.
11568  *
11569  * Requiring io/console adds the following methods:
11570  *
11571  * * IO::console
11572  * * IO#raw
11573  * * IO#raw!
11574  * * IO#cooked
11575  * * IO#cooked!
11576  * * IO#getch
11577  * * IO#echo=
11578  * * IO#echo?
11579  * * IO#noecho
11580  * * IO#winsize
11581  * * IO#winsize=
11582  * * IO#iflush
11583  * * IO#ioflush
11584  * * IO#oflush
11585  *
11586  * Example:
11587  *
11588  * require 'io/console'
11589  * rows, columns = $stdin.winsize
11590  * puts "Your screen is #{columns} wide and #{rows} tall"
11591  */
11592 
11593 void
11594 Init_IO(void)
11595 {
11596 #undef rb_intern
11597 #define rb_intern(str) rb_intern_const(str)
11598 
11599  VALUE rb_cARGF;
11600 #ifdef __CYGWIN__
11601 #include <sys/cygwin.h>
11602  static struct __cygwin_perfile pf[] =
11603  {
11604  {"", O_RDONLY | O_BINARY},
11605  {"", O_WRONLY | O_BINARY},
11606  {"", O_RDWR | O_BINARY},
11607  {"", O_APPEND | O_BINARY},
11608  {NULL, 0}
11609  };
11610  cygwin_internal(CW_PERFILE, pf);
11611 #endif
11612 
11614  rb_eEOFError = rb_define_class("EOFError", rb_eIOError);
11615 
11616  id_write = rb_intern("write");
11617  id_read = rb_intern("read");
11618  id_getc = rb_intern("getc");
11619  id_flush = rb_intern("flush");
11620  id_readpartial = rb_intern("readpartial");
11621  id_set_encoding = rb_intern("set_encoding");
11622 
11623  rb_define_global_function("syscall", rb_f_syscall, -1);
11624 
11625  rb_define_global_function("open", rb_f_open, -1);
11626  rb_define_global_function("printf", rb_f_printf, -1);
11627  rb_define_global_function("print", rb_f_print, -1);
11629  rb_define_global_function("puts", rb_f_puts, -1);
11630  rb_define_global_function("gets", rb_f_gets, -1);
11631  rb_define_global_function("readline", rb_f_readline, -1);
11632  rb_define_global_function("select", rb_f_select, -1);
11633 
11634  rb_define_global_function("readlines", rb_f_readlines, -1);
11635 
11637 
11639  rb_define_method(rb_mKernel, "display", rb_obj_display, -1);
11640 
11643 
11644  rb_mWaitReadable = rb_define_module_under(rb_cIO, "WaitReadable");
11645  rb_mWaitWritable = rb_define_module_under(rb_cIO, "WaitWritable");
11646 
11647 #if 0
11648  /* This is necessary only for forcing rdoc handle File::open */
11650 #endif
11651 
11668 
11669  rb_define_method(rb_cIO, "initialize", rb_io_initialize, -1);
11670 
11671  rb_output_fs = Qnil;
11673 
11676  rb_output_rs = Qnil;
11677  OBJ_FREEZE(rb_default_rs); /* avoid modifying RS_default */
11681 
11683 
11684  rb_define_method(rb_cIO, "initialize_copy", rb_io_init_copy, 1);
11685  rb_define_method(rb_cIO, "reopen", rb_io_reopen, -1);
11686 
11687  rb_define_method(rb_cIO, "print", rb_io_print, -1);
11688  rb_define_method(rb_cIO, "putc", rb_io_putc, 1);
11689  rb_define_method(rb_cIO, "puts", rb_io_puts, -1);
11690  rb_define_method(rb_cIO, "printf", rb_io_printf, -1);
11691 
11692  rb_define_method(rb_cIO, "each", rb_io_each_line, -1);
11693  rb_define_method(rb_cIO, "each_line", rb_io_each_line, -1);
11694  rb_define_method(rb_cIO, "each_byte", rb_io_each_byte, 0);
11695  rb_define_method(rb_cIO, "each_char", rb_io_each_char, 0);
11696  rb_define_method(rb_cIO, "each_codepoint", rb_io_each_codepoint, 0);
11697  rb_define_method(rb_cIO, "lines", rb_io_lines, -1);
11698  rb_define_method(rb_cIO, "bytes", rb_io_bytes, 0);
11699  rb_define_method(rb_cIO, "chars", rb_io_chars, 0);
11700  rb_define_method(rb_cIO, "codepoints", rb_io_codepoints, 0);
11701 
11702  rb_define_method(rb_cIO, "syswrite", rb_io_syswrite, 1);
11703  rb_define_method(rb_cIO, "sysread", rb_io_sysread, -1);
11704 
11705  rb_define_method(rb_cIO, "fileno", rb_io_fileno, 0);
11706  rb_define_alias(rb_cIO, "to_i", "fileno");
11707  rb_define_method(rb_cIO, "to_io", rb_io_to_io, 0);
11708 
11709  rb_define_method(rb_cIO, "fsync", rb_io_fsync, 0);
11710  rb_define_method(rb_cIO, "fdatasync", rb_io_fdatasync, 0);
11711  rb_define_method(rb_cIO, "sync", rb_io_sync, 0);
11712  rb_define_method(rb_cIO, "sync=", rb_io_set_sync, 1);
11713 
11714  rb_define_method(rb_cIO, "lineno", rb_io_lineno, 0);
11715  rb_define_method(rb_cIO, "lineno=", rb_io_set_lineno, 1);
11716 
11717  rb_define_method(rb_cIO, "readlines", rb_io_readlines, -1);
11718 
11719  rb_define_method(rb_cIO, "read_nonblock", io_read_nonblock, -1);
11720  rb_define_method(rb_cIO, "write_nonblock", rb_io_write_nonblock, 1);
11721  rb_define_method(rb_cIO, "readpartial", io_readpartial, -1);
11722  rb_define_method(rb_cIO, "read", io_read, -1);
11723  rb_define_method(rb_cIO, "write", io_write_m, 1);
11724  rb_define_method(rb_cIO, "gets", rb_io_gets_m, -1);
11725  rb_define_method(rb_cIO, "readline", rb_io_readline, -1);
11726  rb_define_method(rb_cIO, "getc", rb_io_getc, 0);
11727  rb_define_method(rb_cIO, "getbyte", rb_io_getbyte, 0);
11728  rb_define_method(rb_cIO, "readchar", rb_io_readchar, 0);
11729  rb_define_method(rb_cIO, "readbyte", rb_io_readbyte, 0);
11730  rb_define_method(rb_cIO, "ungetbyte",rb_io_ungetbyte, 1);
11731  rb_define_method(rb_cIO, "ungetc",rb_io_ungetc, 1);
11733  rb_define_method(rb_cIO, "flush", rb_io_flush, 0);
11734  rb_define_method(rb_cIO, "tell", rb_io_tell, 0);
11735  rb_define_method(rb_cIO, "seek", rb_io_seek_m, -1);
11736  rb_define_const(rb_cIO, "SEEK_SET", INT2FIX(SEEK_SET));
11737  rb_define_const(rb_cIO, "SEEK_CUR", INT2FIX(SEEK_CUR));
11738  rb_define_const(rb_cIO, "SEEK_END", INT2FIX(SEEK_END));
11739  rb_define_method(rb_cIO, "rewind", rb_io_rewind, 0);
11740  rb_define_method(rb_cIO, "pos", rb_io_tell, 0);
11741  rb_define_method(rb_cIO, "pos=", rb_io_set_pos, 1);
11742  rb_define_method(rb_cIO, "eof", rb_io_eof, 0);
11743  rb_define_method(rb_cIO, "eof?", rb_io_eof, 0);
11744 
11745  rb_define_method(rb_cIO, "close_on_exec?", rb_io_close_on_exec_p, 0);
11746  rb_define_method(rb_cIO, "close_on_exec=", rb_io_set_close_on_exec, 1);
11747 
11748  rb_define_method(rb_cIO, "close", rb_io_close_m, 0);
11749  rb_define_method(rb_cIO, "closed?", rb_io_closed, 0);
11750  rb_define_method(rb_cIO, "close_read", rb_io_close_read, 0);
11751  rb_define_method(rb_cIO, "close_write", rb_io_close_write, 0);
11752 
11753  rb_define_method(rb_cIO, "isatty", rb_io_isatty, 0);
11754  rb_define_method(rb_cIO, "tty?", rb_io_isatty, 0);
11755  rb_define_method(rb_cIO, "binmode", rb_io_binmode_m, 0);
11756  rb_define_method(rb_cIO, "binmode?", rb_io_binmode_p, 0);
11757  rb_define_method(rb_cIO, "sysseek", rb_io_sysseek, -1);
11758  rb_define_method(rb_cIO, "advise", rb_io_advise, -1);
11759 
11760  rb_define_method(rb_cIO, "ioctl", rb_io_ioctl, -1);
11761  rb_define_method(rb_cIO, "fcntl", rb_io_fcntl, -1);
11762  rb_define_method(rb_cIO, "pid", rb_io_pid, 0);
11763  rb_define_method(rb_cIO, "inspect", rb_io_inspect, 0);
11764 
11765  rb_define_method(rb_cIO, "external_encoding", rb_io_external_encoding, 0);
11766  rb_define_method(rb_cIO, "internal_encoding", rb_io_internal_encoding, 0);
11767  rb_define_method(rb_cIO, "set_encoding", rb_io_set_encoding, -1);
11768 
11769  rb_define_method(rb_cIO, "autoclose?", rb_io_autoclose_p, 0);
11770  rb_define_method(rb_cIO, "autoclose=", rb_io_set_autoclose, 1);
11771 
11772  rb_define_variable("$stdin", &rb_stdin);
11773  rb_stdin = prep_stdio(stdin, FMODE_READABLE, rb_cIO, "<STDIN>");
11775  rb_stdout = prep_stdio(stdout, FMODE_WRITABLE, rb_cIO, "<STDOUT>");
11777  rb_stderr = prep_stdio(stderr, FMODE_WRITABLE|FMODE_SYNC, rb_cIO, "<STDERR>");
11781 
11782  /* Holds the original stdin */
11783  rb_define_global_const("STDIN", rb_stdin);
11784  /* Holds the original stdout */
11785  rb_define_global_const("STDOUT", rb_stdout);
11786  /* Holds the original stderr */
11787  rb_define_global_const("STDERR", rb_stderr);
11788 
11789 #if 0
11790  /* Hack to get rdoc to regard ARGF as a class: */
11791  rb_cARGF = rb_define_class("ARGF", rb_cObject);
11792 #endif
11793 
11794  rb_cARGF = rb_class_new(rb_cObject);
11795  rb_set_class_path(rb_cARGF, rb_cObject, "ARGF.class");
11796  rb_define_alloc_func(rb_cARGF, argf_alloc);
11797 
11798  rb_include_module(rb_cARGF, rb_mEnumerable);
11799 
11800  rb_define_method(rb_cARGF, "initialize", argf_initialize, -2);
11801  rb_define_method(rb_cARGF, "initialize_copy", argf_initialize_copy, 1);
11802  rb_define_method(rb_cARGF, "to_s", argf_to_s, 0);
11803  rb_define_alias(rb_cARGF, "inspect", "to_s");
11804  rb_define_method(rb_cARGF, "argv", argf_argv, 0);
11805 
11806  rb_define_method(rb_cARGF, "fileno", argf_fileno, 0);
11807  rb_define_method(rb_cARGF, "to_i", argf_fileno, 0);
11808  rb_define_method(rb_cARGF, "to_io", argf_to_io, 0);
11809  rb_define_method(rb_cARGF, "to_write_io", argf_write_io, 0);
11810  rb_define_method(rb_cARGF, "each", argf_each_line, -1);
11811  rb_define_method(rb_cARGF, "each_line", argf_each_line, -1);
11812  rb_define_method(rb_cARGF, "each_byte", argf_each_byte, 0);
11813  rb_define_method(rb_cARGF, "each_char", argf_each_char, 0);
11814  rb_define_method(rb_cARGF, "each_codepoint", argf_each_codepoint, 0);
11815  rb_define_method(rb_cARGF, "lines", argf_lines, -1);
11816  rb_define_method(rb_cARGF, "bytes", argf_bytes, 0);
11817  rb_define_method(rb_cARGF, "chars", argf_chars, 0);
11818  rb_define_method(rb_cARGF, "codepoints", argf_codepoints, 0);
11819 
11820  rb_define_method(rb_cARGF, "read", argf_read, -1);
11821  rb_define_method(rb_cARGF, "readpartial", argf_readpartial, -1);
11822  rb_define_method(rb_cARGF, "read_nonblock", argf_read_nonblock, -1);
11823  rb_define_method(rb_cARGF, "readlines", argf_readlines, -1);
11824  rb_define_method(rb_cARGF, "to_a", argf_readlines, -1);
11825  rb_define_method(rb_cARGF, "gets", argf_gets, -1);
11826  rb_define_method(rb_cARGF, "readline", argf_readline, -1);
11827  rb_define_method(rb_cARGF, "getc", argf_getc, 0);
11828  rb_define_method(rb_cARGF, "getbyte", argf_getbyte, 0);
11829  rb_define_method(rb_cARGF, "readchar", argf_readchar, 0);
11830  rb_define_method(rb_cARGF, "readbyte", argf_readbyte, 0);
11831  rb_define_method(rb_cARGF, "tell", argf_tell, 0);
11832  rb_define_method(rb_cARGF, "seek", argf_seek_m, -1);
11833  rb_define_method(rb_cARGF, "rewind", argf_rewind, 0);
11834  rb_define_method(rb_cARGF, "pos", argf_tell, 0);
11835  rb_define_method(rb_cARGF, "pos=", argf_set_pos, 1);
11836  rb_define_method(rb_cARGF, "eof", argf_eof, 0);
11837  rb_define_method(rb_cARGF, "eof?", argf_eof, 0);
11838  rb_define_method(rb_cARGF, "binmode", argf_binmode_m, 0);
11839  rb_define_method(rb_cARGF, "binmode?", argf_binmode_p, 0);
11840 
11841  rb_define_method(rb_cARGF, "write", argf_write, 1);
11842  rb_define_method(rb_cARGF, "print", rb_io_print, -1);
11843  rb_define_method(rb_cARGF, "putc", rb_io_putc, 1);
11844  rb_define_method(rb_cARGF, "puts", rb_io_puts, -1);
11845  rb_define_method(rb_cARGF, "printf", rb_io_printf, -1);
11846 
11847  rb_define_method(rb_cARGF, "filename", argf_filename, 0);
11848  rb_define_method(rb_cARGF, "path", argf_filename, 0);
11849  rb_define_method(rb_cARGF, "file", argf_file, 0);
11850  rb_define_method(rb_cARGF, "skip", argf_skip, 0);
11851  rb_define_method(rb_cARGF, "close", argf_close_m, 0);
11852  rb_define_method(rb_cARGF, "closed?", argf_closed, 0);
11853 
11854  rb_define_method(rb_cARGF, "lineno", argf_lineno, 0);
11855  rb_define_method(rb_cARGF, "lineno=", argf_set_lineno, 1);
11856 
11857  rb_define_method(rb_cARGF, "inplace_mode", argf_inplace_mode_get, 0);
11858  rb_define_method(rb_cARGF, "inplace_mode=", argf_inplace_mode_set, 1);
11859 
11860  rb_define_method(rb_cARGF, "external_encoding", argf_external_encoding, 0);
11861  rb_define_method(rb_cARGF, "internal_encoding", argf_internal_encoding, 0);
11862  rb_define_method(rb_cARGF, "set_encoding", argf_set_encoding, -1);
11863 
11864  argf = rb_class_new_instance(0, 0, rb_cARGF);
11865 
11867  /*
11868  * ARGF is a stream designed for use in scripts that process files given
11869  * as command-line arguments or passed in via STDIN.
11870  *
11871  * See ARGF (the class) for more details.
11872  */
11873  rb_define_global_const("ARGF", argf);
11874 
11877  ARGF.filename = rb_str_new2("-");
11878 
11881 
11882 #if defined (_WIN32) || defined(__CYGWIN__)
11883  atexit(pipe_atexit);
11884 #endif
11885 
11886  Init_File();
11887 
11888  rb_define_method(rb_cFile, "initialize", rb_file_initialize, -1);
11889 
11890  sym_mode = ID2SYM(rb_intern("mode"));
11891  sym_perm = ID2SYM(rb_intern("perm"));
11892  sym_extenc = ID2SYM(rb_intern("external_encoding"));
11893  sym_intenc = ID2SYM(rb_intern("internal_encoding"));
11894  sym_encoding = ID2SYM(rb_intern("encoding"));
11895  sym_open_args = ID2SYM(rb_intern("open_args"));
11896  sym_textmode = ID2SYM(rb_intern("textmode"));
11897  sym_binmode = ID2SYM(rb_intern("binmode"));
11898  sym_autoclose = ID2SYM(rb_intern("autoclose"));
11899  sym_normal = ID2SYM(rb_intern("normal"));
11900  sym_sequential = ID2SYM(rb_intern("sequential"));
11901  sym_random = ID2SYM(rb_intern("random"));
11902  sym_willneed = ID2SYM(rb_intern("willneed"));
11903  sym_dontneed = ID2SYM(rb_intern("dontneed"));
11904  sym_noreuse = ID2SYM(rb_intern("noreuse"));
11905 }
11906