PageRenderTime 72ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 2ms

/io.c

https://github.com/fizx/ruby
C | 9980 lines | 6598 code | 920 blank | 2462 comment | 1514 complexity | 7622f3d92fa620ec0eca01f887fc6906 MD5 | raw file
Possible License(s): LGPL-2.1, AGPL-3.0, GPL-2.0, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. /**********************************************************************
  2. io.c -
  3. $Author$
  4. created at: Fri Oct 15 18:08:59 JST 1993
  5. Copyright (C) 1993-2007 Yukihiro Matsumoto
  6. Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
  7. Copyright (C) 2000 Information-technology Promotion Agency, Japan
  8. **********************************************************************/
  9. #include "ruby/ruby.h"
  10. #include "ruby/io.h"
  11. #include "dln.h"
  12. #include <ctype.h>
  13. #include <errno.h>
  14. #define free(x) xfree(x)
  15. #if defined(DOSISH) || defined(__CYGWIN__)
  16. #include <io.h>
  17. #endif
  18. #include <sys/types.h>
  19. #if defined HAVE_NET_SOCKET_H
  20. # include <net/socket.h>
  21. #elif defined HAVE_SYS_SOCKET_H
  22. # include <sys/socket.h>
  23. #endif
  24. #if defined(__BOW__) || defined(__CYGWIN__) || defined(_WIN32) || defined(__EMX__) || defined(__BEOS__) || defined(__HAIKU__)
  25. # define NO_SAFE_RENAME
  26. #endif
  27. #if defined(__CYGWIN__) || defined(_WIN32)
  28. # define NO_LONG_FNAME
  29. #endif
  30. #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(sun) || defined(_nec_ews)
  31. # define USE_SETVBUF
  32. #endif
  33. #ifdef __QNXNTO__
  34. #include "unix.h"
  35. #endif
  36. #include <sys/types.h>
  37. #if defined(HAVE_SYS_IOCTL_H) && !defined(_WIN32)
  38. #include <sys/ioctl.h>
  39. #endif
  40. #if defined(HAVE_FCNTL_H) || defined(_WIN32)
  41. #include <fcntl.h>
  42. #elif defined(HAVE_SYS_FCNTL_H)
  43. #include <sys/fcntl.h>
  44. #endif
  45. #if !HAVE_OFF_T && !defined(off_t)
  46. # define off_t long
  47. #endif
  48. #include <sys/stat.h>
  49. /* EMX has sys/param.h, but.. */
  50. #if defined(HAVE_SYS_PARAM_H) && !(defined(__EMX__) || defined(__HIUX_MPP__))
  51. # include <sys/param.h>
  52. #endif
  53. #if !defined NOFILE
  54. # define NOFILE 64
  55. #endif
  56. #ifdef HAVE_UNISTD_H
  57. #include <unistd.h>
  58. #endif
  59. #ifdef HAVE_SYSCALL_H
  60. #include <syscall.h>
  61. #elif defined HAVE_SYS_SYSCALL_H
  62. #include <sys/syscall.h>
  63. #endif
  64. extern void Init_File(void);
  65. #if defined(__BEOS__) || defined(__HAIKU__)
  66. # ifndef NOFILE
  67. # define NOFILE (OPEN_MAX)
  68. # endif
  69. #endif
  70. #include "ruby/util.h"
  71. #ifndef O_ACCMODE
  72. #define O_ACCMODE (O_RDONLY | O_WRONLY | O_RDWR)
  73. #endif
  74. #if SIZEOF_OFF_T > SIZEOF_LONG && !defined(HAVE_LONG_LONG)
  75. # error off_t is bigger than long, but you have no long long...
  76. #endif
  77. #ifndef PIPE_BUF
  78. # ifdef _POSIX_PIPE_BUF
  79. # define PIPE_BUF _POSIX_PIPE_BUF
  80. # else
  81. # define PIPE_BUF 512 /* is this ok? */
  82. # endif
  83. #endif
  84. #define numberof(array) (int)(sizeof(array) / sizeof((array)[0]))
  85. VALUE rb_cIO;
  86. VALUE rb_eEOFError;
  87. VALUE rb_eIOError;
  88. VALUE rb_mWaitReadable;
  89. VALUE rb_mWaitWritable;
  90. VALUE rb_stdin, rb_stdout, rb_stderr;
  91. VALUE rb_deferr; /* rescue VIM plugin */
  92. static VALUE orig_stdout, orig_stderr;
  93. VALUE rb_output_fs;
  94. VALUE rb_rs;
  95. VALUE rb_output_rs;
  96. VALUE rb_default_rs;
  97. static VALUE argf;
  98. static ID id_write, id_read, id_getc, id_flush, id_readpartial;
  99. static VALUE sym_mode, sym_perm, sym_extenc, sym_intenc, sym_encoding, sym_open_args;
  100. static VALUE sym_textmode, sym_binmode;
  101. struct timeval rb_time_interval(VALUE);
  102. struct argf {
  103. VALUE filename, current_file;
  104. int last_lineno; /* $. */
  105. int lineno;
  106. int init_p, next_p;
  107. VALUE argv;
  108. char *inplace;
  109. int binmode;
  110. struct rb_io_enc_t encs;
  111. };
  112. static int max_file_descriptor = NOFILE;
  113. #define UPDATE_MAXFD(fd) \
  114. do { \
  115. if (max_file_descriptor < (fd)) max_file_descriptor = (fd); \
  116. } while (0)
  117. #define argf_of(obj) (*(struct argf *)DATA_PTR(obj))
  118. #define ARGF argf_of(argf)
  119. #ifdef _STDIO_USES_IOSTREAM /* GNU libc */
  120. # ifdef _IO_fpos_t
  121. # define STDIO_READ_DATA_PENDING(fp) ((fp)->_IO_read_ptr != (fp)->_IO_read_end)
  122. # else
  123. # define STDIO_READ_DATA_PENDING(fp) ((fp)->_gptr < (fp)->_egptr)
  124. # endif
  125. #elif defined(FILE_COUNT)
  126. # define STDIO_READ_DATA_PENDING(fp) ((fp)->FILE_COUNT > 0)
  127. #elif defined(FILE_READEND)
  128. # define STDIO_READ_DATA_PENDING(fp) ((fp)->FILE_READPTR < (fp)->FILE_READEND)
  129. #elif defined(__BEOS__) || defined(__HAIKU__)
  130. # define STDIO_READ_DATA_PENDING(fp) (fp->_state._eof == 0)
  131. #else
  132. # define STDIO_READ_DATA_PENDING(fp) (!feof(fp))
  133. #endif
  134. #define GetWriteIO(io) rb_io_get_write_io(io)
  135. #define READ_DATA_PENDING(fptr) ((fptr)->rbuf_len)
  136. #define READ_DATA_PENDING_COUNT(fptr) ((fptr)->rbuf_len)
  137. #define READ_DATA_PENDING_PTR(fptr) ((fptr)->rbuf+(fptr)->rbuf_off)
  138. #define READ_DATA_BUFFERED(fptr) READ_DATA_PENDING(fptr)
  139. #define READ_CHECK(fptr) do {\
  140. if (!READ_DATA_PENDING(fptr)) {\
  141. rb_thread_wait_fd((fptr)->fd);\
  142. rb_io_check_closed(fptr);\
  143. }\
  144. } while(0)
  145. #ifndef S_ISSOCK
  146. # ifdef _S_ISSOCK
  147. # define S_ISSOCK(m) _S_ISSOCK(m)
  148. # else
  149. # ifdef _S_IFSOCK
  150. # define S_ISSOCK(m) ((m & S_IFMT) == _S_IFSOCK)
  151. # else
  152. # ifdef S_IFSOCK
  153. # define S_ISSOCK(m) ((m & S_IFMT) == S_IFSOCK)
  154. # endif
  155. # endif
  156. # endif
  157. #endif
  158. #if !defined HAVE_SHUTDOWN && !defined shutdown
  159. #define shutdown(a,b) 0
  160. #endif
  161. #define rb_sys_fail_path(path) rb_sys_fail(NIL_P(path) ? 0 : RSTRING_PTR(path))
  162. #if defined(_WIN32)
  163. #define is_socket(fd, path) rb_w32_is_socket(fd)
  164. #elif !defined(S_ISSOCK)
  165. #define is_socket(fd, path) 0
  166. #else
  167. static int
  168. is_socket(int fd, VALUE path)
  169. {
  170. struct stat sbuf;
  171. if (fstat(fd, &sbuf) < 0)
  172. rb_sys_fail_path(path);
  173. return S_ISSOCK(sbuf.st_mode);
  174. }
  175. #endif
  176. void
  177. rb_eof_error(void)
  178. {
  179. rb_raise(rb_eEOFError, "end of file reached");
  180. }
  181. VALUE
  182. rb_io_taint_check(VALUE io)
  183. {
  184. if (!OBJ_UNTRUSTED(io) && rb_safe_level() >= 4)
  185. rb_raise(rb_eSecurityError, "Insecure: operation on trusted IO");
  186. rb_check_frozen(io);
  187. return io;
  188. }
  189. void
  190. rb_io_check_initialized(rb_io_t *fptr)
  191. {
  192. if (!fptr) {
  193. rb_raise(rb_eIOError, "uninitialized stream");
  194. }
  195. }
  196. void
  197. rb_io_check_closed(rb_io_t *fptr)
  198. {
  199. rb_io_check_initialized(fptr);
  200. if (fptr->fd < 0) {
  201. rb_raise(rb_eIOError, "closed stream");
  202. }
  203. }
  204. static int io_fflush(rb_io_t *);
  205. VALUE
  206. rb_io_get_io(VALUE io)
  207. {
  208. return rb_convert_type(io, T_FILE, "IO", "to_io");
  209. }
  210. static VALUE
  211. rb_io_check_io(VALUE io)
  212. {
  213. return rb_check_convert_type(io, T_FILE, "IO", "to_io");
  214. }
  215. VALUE
  216. rb_io_get_write_io(VALUE io)
  217. {
  218. VALUE write_io;
  219. rb_io_check_initialized(RFILE(io)->fptr);
  220. write_io = RFILE(io)->fptr->tied_io_for_writing;
  221. if (write_io) {
  222. return write_io;
  223. }
  224. return io;
  225. }
  226. /*
  227. * call-seq:
  228. * IO.try_convert(obj) -> io or nil
  229. *
  230. * Try to convert <i>obj</i> into an IO, using to_io method.
  231. * Returns converted IO or nil if <i>obj</i> cannot be converted
  232. * for any reason.
  233. *
  234. * IO.try_convert(STDOUT) # => STDOUT
  235. * IO.try_convert("STDOUT") # => nil
  236. *
  237. * require 'zlib'
  238. * f = open("/tmp/zz.gz") # => #<File:/tmp/zz.gz>
  239. * z = Zlib::GzipReader.open(f) # => #<Zlib::GzipReader:0x81d8744>
  240. * IO.try_convert(z) # => #<File:/tmp/zz.gz>
  241. *
  242. */
  243. static VALUE
  244. rb_io_s_try_convert(VALUE dummy, VALUE io)
  245. {
  246. return rb_io_check_io(io);
  247. }
  248. static void
  249. io_unread(rb_io_t *fptr)
  250. {
  251. off_t r;
  252. rb_io_check_closed(fptr);
  253. if (fptr->rbuf_len == 0 || fptr->mode & FMODE_DUPLEX)
  254. return;
  255. /* xxx: target position may be negative if buffer is filled by ungetc */
  256. r = lseek(fptr->fd, -fptr->rbuf_len, SEEK_CUR);
  257. if (r < 0) {
  258. if (errno == ESPIPE)
  259. fptr->mode |= FMODE_DUPLEX;
  260. return;
  261. }
  262. fptr->rbuf_off = 0;
  263. fptr->rbuf_len = 0;
  264. return;
  265. }
  266. static rb_encoding *io_input_encoding(rb_io_t *fptr);
  267. static void
  268. io_ungetbyte(VALUE str, rb_io_t *fptr)
  269. {
  270. long len = RSTRING_LEN(str);
  271. if (fptr->rbuf == NULL) {
  272. fptr->rbuf_off = 0;
  273. fptr->rbuf_len = 0;
  274. #if SIZEOF_LONG > SIZEOF_INT
  275. if (len > INT_MAX)
  276. rb_raise(rb_eIOError, "ungetbyte failed");
  277. #endif
  278. if (len > 8192)
  279. fptr->rbuf_capa = (int)len;
  280. else
  281. fptr->rbuf_capa = 8192;
  282. fptr->rbuf = ALLOC_N(char, fptr->rbuf_capa);
  283. }
  284. if (fptr->rbuf_capa < len + fptr->rbuf_len) {
  285. rb_raise(rb_eIOError, "ungetbyte failed");
  286. }
  287. if (fptr->rbuf_off < len) {
  288. MEMMOVE(fptr->rbuf+fptr->rbuf_capa-fptr->rbuf_len,
  289. fptr->rbuf+fptr->rbuf_off,
  290. char, fptr->rbuf_len);
  291. fptr->rbuf_off = fptr->rbuf_capa-fptr->rbuf_len;
  292. }
  293. fptr->rbuf_off-=(int)len;
  294. fptr->rbuf_len+=(int)len;
  295. MEMMOVE(fptr->rbuf+fptr->rbuf_off, RSTRING_PTR(str), char, len);
  296. }
  297. static rb_io_t *
  298. flush_before_seek(rb_io_t *fptr)
  299. {
  300. if (io_fflush(fptr) < 0)
  301. rb_sys_fail(0);
  302. io_unread(fptr);
  303. errno = 0;
  304. return fptr;
  305. }
  306. #define io_set_eof(fptr) (void)(((fptr)->mode & FMODE_TTY) && ((fptr)->mode |= FMODE_EOF))
  307. #define io_unset_eof(fptr) (fptr->mode &= ~FMODE_EOF)
  308. #define io_seek(fptr, ofs, whence) (io_unset_eof(fptr), lseek(flush_before_seek(fptr)->fd, ofs, whence))
  309. #define io_tell(fptr) lseek(flush_before_seek(fptr)->fd, 0, SEEK_CUR)
  310. #ifndef SEEK_CUR
  311. # define SEEK_SET 0
  312. # define SEEK_CUR 1
  313. # define SEEK_END 2
  314. #endif
  315. #define FMODE_SYNCWRITE (FMODE_SYNC|FMODE_WRITABLE)
  316. void
  317. rb_io_check_readable(rb_io_t *fptr)
  318. {
  319. rb_io_check_closed(fptr);
  320. if (!(fptr->mode & FMODE_READABLE)) {
  321. rb_raise(rb_eIOError, "not opened for reading");
  322. }
  323. if (fptr->wbuf_len) {
  324. if (io_fflush(fptr) < 0)
  325. rb_sys_fail(0);
  326. }
  327. if (fptr->tied_io_for_writing) {
  328. rb_io_t *wfptr;
  329. GetOpenFile(fptr->tied_io_for_writing, wfptr);
  330. if (io_fflush(wfptr) < 0)
  331. rb_sys_fail(0);
  332. }
  333. }
  334. static rb_encoding*
  335. io_read_encoding(rb_io_t *fptr)
  336. {
  337. if (fptr->encs.enc) {
  338. return fptr->encs.enc;
  339. }
  340. return rb_default_external_encoding();
  341. }
  342. static rb_encoding*
  343. io_input_encoding(rb_io_t *fptr)
  344. {
  345. if (fptr->encs.enc2) {
  346. return fptr->encs.enc2;
  347. }
  348. return io_read_encoding(fptr);
  349. }
  350. void
  351. rb_io_check_writable(rb_io_t *fptr)
  352. {
  353. rb_io_check_closed(fptr);
  354. if (!(fptr->mode & FMODE_WRITABLE)) {
  355. rb_raise(rb_eIOError, "not opened for writing");
  356. }
  357. if (fptr->rbuf_len) {
  358. io_unread(fptr);
  359. }
  360. }
  361. int
  362. rb_io_read_pending(rb_io_t *fptr)
  363. {
  364. return READ_DATA_PENDING(fptr);
  365. }
  366. void
  367. rb_read_check(FILE *fp)
  368. {
  369. if (!STDIO_READ_DATA_PENDING(fp)) {
  370. rb_thread_wait_fd(fileno(fp));
  371. }
  372. }
  373. void
  374. rb_io_read_check(rb_io_t *fptr)
  375. {
  376. if (!READ_DATA_PENDING(fptr)) {
  377. rb_thread_wait_fd(fptr->fd);
  378. }
  379. return;
  380. }
  381. static int
  382. ruby_dup(int orig)
  383. {
  384. int fd;
  385. fd = dup(orig);
  386. if (fd < 0) {
  387. if (errno == EMFILE || errno == ENFILE || errno == ENOMEM) {
  388. rb_gc();
  389. fd = dup(orig);
  390. }
  391. if (fd < 0) {
  392. rb_sys_fail(0);
  393. }
  394. }
  395. return fd;
  396. }
  397. static VALUE
  398. io_alloc(VALUE klass)
  399. {
  400. NEWOBJ(io, struct RFile);
  401. OBJSETUP(io, klass, T_FILE);
  402. io->fptr = 0;
  403. return (VALUE)io;
  404. }
  405. #ifndef S_ISREG
  406. # define S_ISREG(m) ((m & S_IFMT) == S_IFREG)
  407. #endif
  408. static int
  409. wsplit_p(rb_io_t *fptr)
  410. {
  411. #if defined(HAVE_FCNTL) && defined(F_GETFL) && defined(O_NONBLOCK)
  412. int r;
  413. #endif
  414. if (!(fptr->mode & FMODE_WSPLIT_INITIALIZED)) {
  415. struct stat buf;
  416. if (fstat(fptr->fd, &buf) == 0 &&
  417. !S_ISREG(buf.st_mode)
  418. #if defined(HAVE_FCNTL) && defined(F_GETFL) && defined(O_NONBLOCK)
  419. && (r = fcntl(fptr->fd, F_GETFL)) != -1 &&
  420. !(r & O_NONBLOCK)
  421. #endif
  422. ) {
  423. fptr->mode |= FMODE_WSPLIT;
  424. }
  425. fptr->mode |= FMODE_WSPLIT_INITIALIZED;
  426. }
  427. return fptr->mode & FMODE_WSPLIT;
  428. }
  429. struct io_internal_struct {
  430. int fd;
  431. void *buf;
  432. size_t capa;
  433. };
  434. static VALUE
  435. internal_read_func(void *ptr)
  436. {
  437. struct io_internal_struct *iis = (struct io_internal_struct*)ptr;
  438. return read(iis->fd, iis->buf, iis->capa);
  439. }
  440. static VALUE
  441. internal_write_func(void *ptr)
  442. {
  443. struct io_internal_struct *iis = (struct io_internal_struct*)ptr;
  444. return write(iis->fd, iis->buf, iis->capa);
  445. }
  446. static ssize_t
  447. rb_read_internal(int fd, void *buf, size_t count)
  448. {
  449. struct io_internal_struct iis;
  450. iis.fd = fd;
  451. iis.buf = buf;
  452. iis.capa = count;
  453. return (ssize_t)rb_thread_blocking_region(internal_read_func, &iis, RUBY_UBF_IO, 0);
  454. }
  455. static ssize_t
  456. rb_write_internal(int fd, void *buf, size_t count)
  457. {
  458. struct io_internal_struct iis;
  459. iis.fd = fd;
  460. iis.buf = buf;
  461. iis.capa = count;
  462. return (ssize_t)rb_thread_blocking_region(internal_write_func, &iis, RUBY_UBF_IO, 0);
  463. }
  464. static long
  465. io_writable_length(rb_io_t *fptr, long l)
  466. {
  467. if (PIPE_BUF < l &&
  468. !rb_thread_alone() &&
  469. wsplit_p(fptr)) {
  470. l = PIPE_BUF;
  471. }
  472. return l;
  473. }
  474. static VALUE
  475. io_flush_buffer(VALUE arg)
  476. {
  477. rb_io_t *fptr = (rb_io_t *)arg;
  478. long l = io_writable_length(fptr, fptr->wbuf_len);
  479. return rb_write_internal(fptr->fd, fptr->wbuf+fptr->wbuf_off, l);
  480. }
  481. static int
  482. io_fflush(rb_io_t *fptr)
  483. {
  484. long r;
  485. rb_io_check_closed(fptr);
  486. if (fptr->wbuf_len == 0)
  487. return 0;
  488. if (!rb_thread_fd_writable(fptr->fd)) {
  489. rb_io_check_closed(fptr);
  490. }
  491. retry:
  492. if (fptr->wbuf_len == 0)
  493. return 0;
  494. if (fptr->write_lock) {
  495. r = rb_mutex_synchronize(fptr->write_lock, io_flush_buffer, (VALUE)fptr);
  496. }
  497. else {
  498. long l = io_writable_length(fptr, fptr->wbuf_len);
  499. r = rb_write_internal(fptr->fd, fptr->wbuf+fptr->wbuf_off, l);
  500. }
  501. /* xxx: Other threads may modify wbuf.
  502. * A lock is required, definitely. */
  503. rb_io_check_closed(fptr);
  504. if (fptr->wbuf_len <= r) {
  505. fptr->wbuf_off = 0;
  506. fptr->wbuf_len = 0;
  507. return 0;
  508. }
  509. if (0 <= r) {
  510. fptr->wbuf_off += (int)r;
  511. fptr->wbuf_len -= (int)r;
  512. errno = EAGAIN;
  513. }
  514. if (rb_io_wait_writable(fptr->fd)) {
  515. rb_io_check_closed(fptr);
  516. goto retry;
  517. }
  518. return -1;
  519. }
  520. #ifdef HAVE_RB_FD_INIT
  521. static VALUE
  522. wait_readable(VALUE p)
  523. {
  524. rb_fdset_t *rfds = (rb_fdset_t *)p;
  525. return rb_thread_select(rb_fd_max(rfds), rb_fd_ptr(rfds), NULL, NULL, NULL);
  526. }
  527. #endif
  528. int
  529. rb_io_wait_readable(int f)
  530. {
  531. rb_fdset_t rfds;
  532. if (f < 0) {
  533. rb_raise(rb_eIOError, "closed stream");
  534. }
  535. switch (errno) {
  536. case EINTR:
  537. #if defined(ERESTART)
  538. case ERESTART:
  539. #endif
  540. rb_thread_wait_fd(f);
  541. return TRUE;
  542. case EAGAIN:
  543. #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
  544. case EWOULDBLOCK:
  545. #endif
  546. rb_fd_init(&rfds);
  547. rb_fd_set(f, &rfds);
  548. #ifdef HAVE_RB_FD_INIT
  549. rb_ensure(wait_readable, (VALUE)&rfds,
  550. (VALUE (*)(VALUE))rb_fd_term, (VALUE)&rfds);
  551. #else
  552. rb_thread_select(f + 1, rb_fd_ptr(&rfds), NULL, NULL, NULL);
  553. #endif
  554. return TRUE;
  555. default:
  556. return FALSE;
  557. }
  558. }
  559. #ifdef HAVE_RB_FD_INIT
  560. static VALUE
  561. wait_writable(VALUE p)
  562. {
  563. rb_fdset_t *wfds = (rb_fdset_t *)p;
  564. return rb_thread_select(rb_fd_max(wfds), NULL, rb_fd_ptr(wfds), NULL, NULL);
  565. }
  566. #endif
  567. int
  568. rb_io_wait_writable(int f)
  569. {
  570. rb_fdset_t wfds;
  571. if (f < 0) {
  572. rb_raise(rb_eIOError, "closed stream");
  573. }
  574. switch (errno) {
  575. case EINTR:
  576. #if defined(ERESTART)
  577. case ERESTART:
  578. #endif
  579. rb_thread_fd_writable(f);
  580. return TRUE;
  581. case EAGAIN:
  582. #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
  583. case EWOULDBLOCK:
  584. #endif
  585. rb_fd_init(&wfds);
  586. rb_fd_set(f, &wfds);
  587. #ifdef HAVE_RB_FD_INIT
  588. rb_ensure(wait_writable, (VALUE)&wfds,
  589. (VALUE (*)(VALUE))rb_fd_term, (VALUE)&wfds);
  590. #else
  591. rb_thread_select(f + 1, NULL, rb_fd_ptr(&wfds), NULL, NULL);
  592. #endif
  593. return TRUE;
  594. default:
  595. return FALSE;
  596. }
  597. }
  598. #if defined(RUBY_TEST_CRLF_ENVIRONMENT) || defined(_WIN32)
  599. /* Windows */
  600. # define NEED_NEWLINE_DECORATOR_ON_READ(fptr) (!(fptr->mode & FMODE_BINMODE))
  601. # define NEED_NEWLINE_DECORATOR_ON_WRITE(fptr) (!(fptr->mode & FMODE_BINMODE))
  602. # define TEXTMODE_NEWLINE_DECORATOR_ON_WRITE ECONV_CRLF_NEWLINE_DECORATOR
  603. #else
  604. /* Unix */
  605. # define NEED_NEWLINE_DECORATOR_ON_READ(fptr) (fptr->mode & FMODE_TEXTMODE)
  606. # define NEED_NEWLINE_DECORATOR_ON_WRITE(fptr) 0
  607. #endif
  608. #define NEED_READCONV(fptr) (fptr->encs.enc2 != NULL || NEED_NEWLINE_DECORATOR_ON_READ(fptr))
  609. #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)))
  610. static void
  611. make_writeconv(rb_io_t *fptr)
  612. {
  613. if (!fptr->writeconv_initialized) {
  614. const char *senc, *denc;
  615. rb_encoding *enc;
  616. int ecflags;
  617. VALUE ecopts;
  618. fptr->writeconv_initialized = 1;
  619. ecflags = fptr->encs.ecflags;
  620. ecopts = fptr->encs.ecopts;
  621. #ifdef TEXTMODE_NEWLINE_DECORATOR_ON_WRITE
  622. if (NEED_NEWLINE_DECORATOR_ON_WRITE(fptr))
  623. ecflags |= TEXTMODE_NEWLINE_DECORATOR_ON_WRITE;
  624. #endif
  625. if (!fptr->encs.enc || (fptr->encs.enc == rb_ascii8bit_encoding() && !fptr->encs.enc2)) {
  626. /* no encoding conversion */
  627. fptr->writeconv_pre_ecflags = 0;
  628. fptr->writeconv_pre_ecopts = Qnil;
  629. fptr->writeconv = rb_econv_open_opts("", "", ecflags, ecopts);
  630. if (!fptr->writeconv)
  631. rb_exc_raise(rb_econv_open_exc("", "", ecflags));
  632. fptr->writeconv_asciicompat = Qnil;
  633. }
  634. else {
  635. enc = fptr->encs.enc2 ? fptr->encs.enc2 : fptr->encs.enc;
  636. senc = rb_econv_asciicompat_encoding(rb_enc_name(enc));
  637. if (!senc && !(fptr->encs.ecflags & ECONV_STATEFUL_DECORATOR_MASK)) {
  638. /* single conversion */
  639. fptr->writeconv_pre_ecflags = ecflags;
  640. fptr->writeconv_pre_ecopts = ecopts;
  641. fptr->writeconv = NULL;
  642. fptr->writeconv_asciicompat = Qnil;
  643. }
  644. else {
  645. /* double conversion */
  646. fptr->writeconv_pre_ecflags = ecflags & ~ECONV_STATEFUL_DECORATOR_MASK;
  647. fptr->writeconv_pre_ecopts = ecopts;
  648. if (senc) {
  649. denc = rb_enc_name(enc);
  650. fptr->writeconv_asciicompat = rb_str_new2(senc);
  651. }
  652. else {
  653. senc = denc = "";
  654. fptr->writeconv_asciicompat = rb_str_new2(rb_enc_name(enc));
  655. }
  656. ecflags = fptr->encs.ecflags & (ECONV_ERROR_HANDLER_MASK|ECONV_STATEFUL_DECORATOR_MASK);
  657. ecopts = fptr->encs.ecopts;
  658. fptr->writeconv = rb_econv_open_opts(senc, denc, ecflags, ecopts);
  659. if (!fptr->writeconv)
  660. rb_exc_raise(rb_econv_open_exc(senc, denc, ecflags));
  661. }
  662. }
  663. }
  664. }
  665. /* writing functions */
  666. struct binwrite_arg {
  667. rb_io_t *fptr;
  668. VALUE str;
  669. long offset;
  670. long length;
  671. };
  672. static VALUE
  673. io_binwrite_string(VALUE arg)
  674. {
  675. struct binwrite_arg *p = (struct binwrite_arg *)arg;
  676. long l = io_writable_length(p->fptr, p->length);
  677. return rb_write_internal(p->fptr->fd, RSTRING_PTR(p->str)+p->offset, l);
  678. }
  679. static long
  680. io_binwrite(VALUE str, rb_io_t *fptr, int nosync)
  681. {
  682. long len, n, r, offset = 0;
  683. len = RSTRING_LEN(str);
  684. if ((n = len) <= 0) return n;
  685. if (fptr->wbuf == NULL && !(!nosync && (fptr->mode & FMODE_SYNC))) {
  686. fptr->wbuf_off = 0;
  687. fptr->wbuf_len = 0;
  688. fptr->wbuf_capa = 8192;
  689. fptr->wbuf = ALLOC_N(char, fptr->wbuf_capa);
  690. fptr->write_lock = rb_mutex_new();
  691. }
  692. if ((!nosync && (fptr->mode & (FMODE_SYNC|FMODE_TTY))) ||
  693. (fptr->wbuf && fptr->wbuf_capa <= fptr->wbuf_len + len)) {
  694. struct binwrite_arg arg;
  695. /* xxx: use writev to avoid double write if available */
  696. if (fptr->wbuf_len && fptr->wbuf_len+len <= fptr->wbuf_capa) {
  697. if (fptr->wbuf_capa < fptr->wbuf_off+fptr->wbuf_len+len) {
  698. MEMMOVE(fptr->wbuf, fptr->wbuf+fptr->wbuf_off, char, fptr->wbuf_len);
  699. fptr->wbuf_off = 0;
  700. }
  701. MEMMOVE(fptr->wbuf+fptr->wbuf_off+fptr->wbuf_len, RSTRING_PTR(str)+offset, char, len);
  702. fptr->wbuf_len += (int)len;
  703. n = 0;
  704. }
  705. if (io_fflush(fptr) < 0)
  706. return -1L;
  707. if (n == 0)
  708. return len;
  709. /* avoid context switch between "a" and "\n" in STDERR.puts "a".
  710. [ruby-dev:25080] */
  711. if (fptr->stdio_file != stderr && !rb_thread_fd_writable(fptr->fd)) {
  712. rb_io_check_closed(fptr);
  713. }
  714. arg.fptr = fptr;
  715. arg.str = str;
  716. retry:
  717. arg.offset = offset;
  718. arg.length = n;
  719. if (fptr->write_lock) {
  720. r = rb_mutex_synchronize(fptr->write_lock, io_binwrite_string, (VALUE)&arg);
  721. }
  722. else {
  723. long l = io_writable_length(fptr, n);
  724. r = rb_write_internal(fptr->fd, RSTRING_PTR(str)+offset, l);
  725. }
  726. /* xxx: other threads may modify given string. */
  727. if (r == n) return len;
  728. if (0 <= r) {
  729. offset += r;
  730. n -= r;
  731. errno = EAGAIN;
  732. }
  733. if (rb_io_wait_writable(fptr->fd)) {
  734. rb_io_check_closed(fptr);
  735. if (offset < RSTRING_LEN(str))
  736. goto retry;
  737. }
  738. return -1L;
  739. }
  740. if (fptr->wbuf_off) {
  741. if (fptr->wbuf_len)
  742. MEMMOVE(fptr->wbuf, fptr->wbuf+fptr->wbuf_off, char, fptr->wbuf_len);
  743. fptr->wbuf_off = 0;
  744. }
  745. MEMMOVE(fptr->wbuf+fptr->wbuf_off+fptr->wbuf_len, RSTRING_PTR(str)+offset, char, len);
  746. fptr->wbuf_len += (int)len;
  747. return len;
  748. }
  749. static VALUE
  750. do_writeconv(VALUE str, rb_io_t *fptr)
  751. {
  752. if (NEED_WRITECONV(fptr)) {
  753. VALUE common_encoding = Qnil;
  754. make_writeconv(fptr);
  755. if (fptr->writeconv) {
  756. if (!NIL_P(fptr->writeconv_asciicompat))
  757. common_encoding = fptr->writeconv_asciicompat;
  758. else if (!rb_enc_asciicompat(rb_enc_get(str))) {
  759. rb_raise(rb_eArgError, "ASCII incompatible string written for text mode IO without encoding conversion: %s",
  760. rb_enc_name(rb_enc_get(str)));
  761. }
  762. }
  763. else {
  764. if (fptr->encs.enc2)
  765. common_encoding = rb_enc_from_encoding(fptr->encs.enc2);
  766. else if (fptr->encs.enc != rb_ascii8bit_encoding())
  767. common_encoding = rb_enc_from_encoding(fptr->encs.enc);
  768. }
  769. if (!NIL_P(common_encoding)) {
  770. str = rb_str_encode(str, common_encoding,
  771. fptr->writeconv_pre_ecflags, fptr->writeconv_pre_ecopts);
  772. }
  773. if (fptr->writeconv) {
  774. str = rb_econv_str_convert(fptr->writeconv, str, ECONV_PARTIAL_INPUT);
  775. }
  776. }
  777. return str;
  778. }
  779. static long
  780. io_fwrite(VALUE str, rb_io_t *fptr, int nosync)
  781. {
  782. str = do_writeconv(str, fptr);
  783. return io_binwrite(str, fptr, nosync);
  784. }
  785. static VALUE
  786. io_write(VALUE io, VALUE str, int nosync)
  787. {
  788. rb_io_t *fptr;
  789. long n;
  790. VALUE tmp;
  791. rb_secure(4);
  792. io = GetWriteIO(io);
  793. str = rb_obj_as_string(str);
  794. tmp = rb_io_check_io(io);
  795. if (NIL_P(tmp)) {
  796. /* port is not IO, call write method for it. */
  797. return rb_funcall(io, id_write, 1, str);
  798. }
  799. io = tmp;
  800. if (RSTRING_LEN(str) == 0) return INT2FIX(0);
  801. GetOpenFile(io, fptr);
  802. rb_io_check_writable(fptr);
  803. n = io_fwrite(str, fptr, nosync);
  804. if (n == -1L) rb_sys_fail_path(fptr->pathv);
  805. return LONG2FIX(n);
  806. }
  807. /*
  808. * call-seq:
  809. * ios.write(string) => integer
  810. *
  811. * Writes the given string to <em>ios</em>. The stream must be opened
  812. * for writing. If the argument is not a string, it will be converted
  813. * to a string using <code>to_s</code>. Returns the number of bytes
  814. * written.
  815. *
  816. * count = $stdout.write( "This is a test\n" )
  817. * puts "That was #{count} bytes of data"
  818. *
  819. * <em>produces:</em>
  820. *
  821. * This is a test
  822. * That was 15 bytes of data
  823. */
  824. static VALUE
  825. io_write_m(VALUE io, VALUE str)
  826. {
  827. return io_write(io, str, 0);
  828. }
  829. VALUE
  830. rb_io_write(VALUE io, VALUE str)
  831. {
  832. return rb_funcall(io, id_write, 1, str);
  833. }
  834. /*
  835. * call-seq:
  836. * ios << obj => ios
  837. *
  838. * String Output---Writes <i>obj</i> to <em>ios</em>.
  839. * <i>obj</i> will be converted to a string using
  840. * <code>to_s</code>.
  841. *
  842. * $stdout << "Hello " << "world!\n"
  843. *
  844. * <em>produces:</em>
  845. *
  846. * Hello world!
  847. */
  848. VALUE
  849. rb_io_addstr(VALUE io, VALUE str)
  850. {
  851. rb_io_write(io, str);
  852. return io;
  853. }
  854. /*
  855. * call-seq:
  856. * ios.flush => ios
  857. *
  858. * Flushes any buffered data within <em>ios</em> to the underlying
  859. * operating system (note that this is Ruby internal buffering only;
  860. * the OS may buffer the data as well).
  861. *
  862. * $stdout.print "no newline"
  863. * $stdout.flush
  864. *
  865. * <em>produces:</em>
  866. *
  867. * no newline
  868. */
  869. VALUE
  870. rb_io_flush(VALUE io)
  871. {
  872. rb_io_t *fptr;
  873. if (TYPE(io) != T_FILE) {
  874. return rb_funcall(io, id_flush, 0);
  875. }
  876. io = GetWriteIO(io);
  877. GetOpenFile(io, fptr);
  878. if (fptr->mode & FMODE_WRITABLE) {
  879. if (io_fflush(fptr) < 0)
  880. rb_sys_fail(0);
  881. #ifdef _WIN32
  882. fsync(fptr->fd);
  883. #endif
  884. }
  885. if (fptr->mode & FMODE_READABLE) {
  886. io_unread(fptr);
  887. }
  888. return io;
  889. }
  890. /*
  891. * call-seq:
  892. * ios.pos => integer
  893. * ios.tell => integer
  894. *
  895. * Returns the current offset (in bytes) of <em>ios</em>.
  896. *
  897. * f = File.new("testfile")
  898. * f.pos #=> 0
  899. * f.gets #=> "This is line one\n"
  900. * f.pos #=> 17
  901. */
  902. static VALUE
  903. rb_io_tell(VALUE io)
  904. {
  905. rb_io_t *fptr;
  906. off_t pos;
  907. GetOpenFile(io, fptr);
  908. pos = io_tell(fptr);
  909. if (pos < 0 && errno) rb_sys_fail_path(fptr->pathv);
  910. pos -= fptr->rbuf_len;
  911. return OFFT2NUM(pos);
  912. }
  913. static VALUE
  914. rb_io_seek(VALUE io, VALUE offset, int whence)
  915. {
  916. rb_io_t *fptr;
  917. off_t pos;
  918. pos = NUM2OFFT(offset);
  919. GetOpenFile(io, fptr);
  920. pos = io_seek(fptr, pos, whence);
  921. if (pos < 0 && errno) rb_sys_fail_path(fptr->pathv);
  922. return INT2FIX(0);
  923. }
  924. /*
  925. * call-seq:
  926. * ios.seek(amount, whence=IO::SEEK_SET) -> 0
  927. *
  928. * Seeks to a given offset <i>anInteger</i> in the stream according to
  929. * the value of <i>whence</i>:
  930. *
  931. * IO::SEEK_CUR | Seeks to _amount_ plus current position
  932. * --------------+----------------------------------------------------
  933. * IO::SEEK_END | Seeks to _amount_ plus end of stream (you probably
  934. * | want a negative value for _amount_)
  935. * --------------+----------------------------------------------------
  936. * IO::SEEK_SET | Seeks to the absolute location given by _amount_
  937. *
  938. * Example:
  939. *
  940. * f = File.new("testfile")
  941. * f.seek(-13, IO::SEEK_END) #=> 0
  942. * f.readline #=> "And so on...\n"
  943. */
  944. static VALUE
  945. rb_io_seek_m(int argc, VALUE *argv, VALUE io)
  946. {
  947. VALUE offset, ptrname;
  948. int whence = SEEK_SET;
  949. if (rb_scan_args(argc, argv, "11", &offset, &ptrname) == 2) {
  950. whence = NUM2INT(ptrname);
  951. }
  952. return rb_io_seek(io, offset, whence);
  953. }
  954. /*
  955. * call-seq:
  956. * ios.pos = integer => integer
  957. *
  958. * Seeks to the given position (in bytes) in <em>ios</em>.
  959. *
  960. * f = File.new("testfile")
  961. * f.pos = 17
  962. * f.gets #=> "This is line two\n"
  963. */
  964. static VALUE
  965. rb_io_set_pos(VALUE io, VALUE offset)
  966. {
  967. rb_io_t *fptr;
  968. off_t pos;
  969. pos = NUM2OFFT(offset);
  970. GetOpenFile(io, fptr);
  971. pos = io_seek(fptr, pos, SEEK_SET);
  972. if (pos < 0) rb_sys_fail_path(fptr->pathv);
  973. return OFFT2NUM(pos);
  974. }
  975. static void clear_readconv(rb_io_t *fptr);
  976. /*
  977. * call-seq:
  978. * ios.rewind => 0
  979. *
  980. * Positions <em>ios</em> to the beginning of input, resetting
  981. * <code>lineno</code> to zero.
  982. *
  983. * f = File.new("testfile")
  984. * f.readline #=> "This is line one\n"
  985. * f.rewind #=> 0
  986. * f.lineno #=> 0
  987. * f.readline #=> "This is line one\n"
  988. */
  989. static VALUE
  990. rb_io_rewind(VALUE io)
  991. {
  992. rb_io_t *fptr;
  993. GetOpenFile(io, fptr);
  994. if (io_seek(fptr, 0L, 0) < 0) rb_sys_fail_path(fptr->pathv);
  995. if (io == ARGF.current_file) {
  996. ARGF.lineno -= fptr->lineno;
  997. }
  998. fptr->lineno = 0;
  999. if (fptr->readconv) {
  1000. clear_readconv(fptr);
  1001. }
  1002. return INT2FIX(0);
  1003. }
  1004. static int
  1005. io_fillbuf(rb_io_t *fptr)
  1006. {
  1007. ssize_t r;
  1008. if (fptr->mode & FMODE_EOF) {
  1009. return -1;
  1010. }
  1011. if (fptr->rbuf == NULL) {
  1012. fptr->rbuf_off = 0;
  1013. fptr->rbuf_len = 0;
  1014. fptr->rbuf_capa = 8192;
  1015. fptr->rbuf = ALLOC_N(char, fptr->rbuf_capa);
  1016. }
  1017. if (fptr->rbuf_len == 0) {
  1018. retry:
  1019. {
  1020. r = rb_read_internal(fptr->fd, fptr->rbuf, fptr->rbuf_capa);
  1021. }
  1022. if (r < 0) {
  1023. if (rb_io_wait_readable(fptr->fd))
  1024. goto retry;
  1025. rb_sys_fail_path(fptr->pathv);
  1026. }
  1027. fptr->rbuf_off = 0;
  1028. fptr->rbuf_len = (int)r; /* r should be <= rbuf_capa */
  1029. if (r == 0) {
  1030. io_set_eof(fptr);
  1031. return -1; /* EOF */
  1032. }
  1033. }
  1034. return 0;
  1035. }
  1036. /*
  1037. * call-seq:
  1038. * ios.eof => true or false
  1039. * ios.eof? => true or false
  1040. *
  1041. * Returns true if <em>ios</em> is at end of file that means
  1042. * there are no more data to read.
  1043. * The stream must be opened for reading or an <code>IOError</code> will be
  1044. * raised.
  1045. *
  1046. * f = File.new("testfile")
  1047. * dummy = f.readlines
  1048. * f.eof #=> true
  1049. *
  1050. * If <em>ios</em> is a stream such as pipe or socket, <code>IO#eof?</code>
  1051. * blocks until the other end sends some data or closes it.
  1052. *
  1053. * r, w = IO.pipe
  1054. * Thread.new { sleep 1; w.close }
  1055. * r.eof? #=> true after 1 second blocking
  1056. *
  1057. * r, w = IO.pipe
  1058. * Thread.new { sleep 1; w.puts "a" }
  1059. * r.eof? #=> false after 1 second blocking
  1060. *
  1061. * r, w = IO.pipe
  1062. * r.eof? # blocks forever
  1063. *
  1064. * Note that <code>IO#eof?</code> reads data to a input buffer.
  1065. * So <code>IO#sysread</code> doesn't work with <code>IO#eof?</code>.
  1066. */
  1067. VALUE
  1068. rb_io_eof(VALUE io)
  1069. {
  1070. rb_io_t *fptr;
  1071. GetOpenFile(io, fptr);
  1072. rb_io_check_readable(fptr);
  1073. if (READ_DATA_PENDING(fptr)) return Qfalse;
  1074. READ_CHECK(fptr);
  1075. if (io_fillbuf(fptr) < 0) {
  1076. return Qtrue;
  1077. }
  1078. return Qfalse;
  1079. }
  1080. /*
  1081. * call-seq:
  1082. * ios.sync => true or false
  1083. *
  1084. * Returns the current ``sync mode'' of <em>ios</em>. When sync mode is
  1085. * true, all output is immediately flushed to the underlying operating
  1086. * system and is not buffered by Ruby internally. See also
  1087. * <code>IO#fsync</code>.
  1088. *
  1089. * f = File.new("testfile")
  1090. * f.sync #=> false
  1091. */
  1092. static VALUE
  1093. rb_io_sync(VALUE io)
  1094. {
  1095. rb_io_t *fptr;
  1096. io = GetWriteIO(io);
  1097. GetOpenFile(io, fptr);
  1098. return (fptr->mode & FMODE_SYNC) ? Qtrue : Qfalse;
  1099. }
  1100. /*
  1101. * call-seq:
  1102. * ios.sync = boolean => boolean
  1103. *
  1104. * Sets the ``sync mode'' to <code>true</code> or <code>false</code>.
  1105. * When sync mode is true, all output is immediately flushed to the
  1106. * underlying operating system and is not buffered internally. Returns
  1107. * the new state. See also <code>IO#fsync</code>.
  1108. *
  1109. * f = File.new("testfile")
  1110. * f.sync = true
  1111. *
  1112. * <em>(produces no output)</em>
  1113. */
  1114. static VALUE
  1115. rb_io_set_sync(VALUE io, VALUE sync)
  1116. {
  1117. rb_io_t *fptr;
  1118. io = GetWriteIO(io);
  1119. GetOpenFile(io, fptr);
  1120. if (RTEST(sync)) {
  1121. fptr->mode |= FMODE_SYNC;
  1122. }
  1123. else {
  1124. fptr->mode &= ~FMODE_SYNC;
  1125. }
  1126. return sync;
  1127. }
  1128. #ifdef HAVE_FSYNC
  1129. /*
  1130. * call-seq:
  1131. * ios.fsync => 0 or nil
  1132. *
  1133. * Immediately writes all buffered data in <em>ios</em> to disk.
  1134. * Note that <code>fsync</code> differs from
  1135. * using <code>IO#sync=</code>. The latter ensures that data is flushed
  1136. * from Ruby's buffers, but doesn't not guarantee that the underlying
  1137. * operating system actually writes it to disk.
  1138. *
  1139. * <code>NotImplementedError</code> is raised
  1140. * if the underlying operating system does not support <em>fsync(2)</em>.
  1141. */
  1142. static VALUE
  1143. rb_io_fsync(VALUE io)
  1144. {
  1145. rb_io_t *fptr;
  1146. io = GetWriteIO(io);
  1147. GetOpenFile(io, fptr);
  1148. if (io_fflush(fptr) < 0)
  1149. rb_sys_fail(0);
  1150. if (fsync(fptr->fd) < 0)
  1151. rb_sys_fail_path(fptr->pathv);
  1152. return INT2FIX(0);
  1153. }
  1154. #else
  1155. #define rb_io_fsync rb_f_notimplement
  1156. #endif
  1157. #ifdef HAVE_FDATASYNC
  1158. /*
  1159. * call-seq:
  1160. * ios.fdatasync => 0 or nil
  1161. *
  1162. * Immediately writes all buffered data in <em>ios</em> to disk.
  1163. *
  1164. * <code>NotImplementedError</code> is raised
  1165. * if the underlying operating system does not support <em>fdatasync(2)</em>.
  1166. */
  1167. static VALUE
  1168. rb_io_fdatasync(VALUE io)
  1169. {
  1170. rb_io_t *fptr;
  1171. io = GetWriteIO(io);
  1172. GetOpenFile(io, fptr);
  1173. if (io_fflush(fptr) < 0)
  1174. rb_sys_fail(0);
  1175. if (fdatasync(fptr->fd) < 0)
  1176. rb_sys_fail_path(fptr->pathv);
  1177. return INT2FIX(0);
  1178. }
  1179. #else
  1180. #define rb_io_fdatasync rb_f_notimplement
  1181. #endif
  1182. /*
  1183. * call-seq:
  1184. * ios.fileno => fixnum
  1185. * ios.to_i => fixnum
  1186. *
  1187. * Returns an integer representing the numeric file descriptor for
  1188. * <em>ios</em>.
  1189. *
  1190. * $stdin.fileno #=> 0
  1191. * $stdout.fileno #=> 1
  1192. */
  1193. static VALUE
  1194. rb_io_fileno(VALUE io)
  1195. {
  1196. rb_io_t *fptr;
  1197. int fd;
  1198. GetOpenFile(io, fptr);
  1199. fd = fptr->fd;
  1200. return INT2FIX(fd);
  1201. }
  1202. /*
  1203. * call-seq:
  1204. * ios.pid => fixnum
  1205. *
  1206. * Returns the process ID of a child process associated with
  1207. * <em>ios</em>. This will be set by <code>IO.popen</code>.
  1208. *
  1209. * pipe = IO.popen("-")
  1210. * if pipe
  1211. * $stderr.puts "In parent, child pid is #{pipe.pid}"
  1212. * else
  1213. * $stderr.puts "In child, pid is #{$$}"
  1214. * end
  1215. *
  1216. * <em>produces:</em>
  1217. *
  1218. * In child, pid is 26209
  1219. * In parent, child pid is 26209
  1220. */
  1221. static VALUE
  1222. rb_io_pid(VALUE io)
  1223. {
  1224. rb_io_t *fptr;
  1225. GetOpenFile(io, fptr);
  1226. if (!fptr->pid)
  1227. return Qnil;
  1228. return PIDT2NUM(fptr->pid);
  1229. }
  1230. /*
  1231. * call-seq:
  1232. * ios.inspect => string
  1233. *
  1234. * Return a string describing this IO object.
  1235. */
  1236. static VALUE
  1237. rb_io_inspect(VALUE obj)
  1238. {
  1239. rb_io_t *fptr;
  1240. const char *cname;
  1241. char fd_desc[256];
  1242. const char *path;
  1243. const char *st = "";
  1244. fptr = RFILE(rb_io_taint_check(obj))->fptr;
  1245. if (!fptr) return rb_any_to_s(obj);
  1246. cname = rb_obj_classname(obj);
  1247. if (NIL_P(fptr->pathv)) {
  1248. if (fptr->fd < 0) {
  1249. path = "";
  1250. st = "(closed)";
  1251. }
  1252. else {
  1253. snprintf(fd_desc, sizeof(fd_desc), "fd %d", fptr->fd);
  1254. path = fd_desc;
  1255. }
  1256. }
  1257. else {
  1258. path = RSTRING_PTR(fptr->pathv);
  1259. if (fptr->fd < 0) {
  1260. st = " (closed)";
  1261. }
  1262. }
  1263. return rb_sprintf("#<%s:%s%s>", cname, path, st);
  1264. }
  1265. /*
  1266. * call-seq:
  1267. * ios.to_io -> ios
  1268. *
  1269. * Returns <em>ios</em>.
  1270. */
  1271. static VALUE
  1272. rb_io_to_io(VALUE io)
  1273. {
  1274. return io;
  1275. }
  1276. /* reading functions */
  1277. static long
  1278. read_buffered_data(char *ptr, long len, rb_io_t *fptr)
  1279. {
  1280. int n;
  1281. n = READ_DATA_PENDING_COUNT(fptr);
  1282. if (n <= 0) return 0;
  1283. if (n > len) n = (int)len;
  1284. MEMMOVE(ptr, fptr->rbuf+fptr->rbuf_off, char, n);
  1285. fptr->rbuf_off += n;
  1286. fptr->rbuf_len -= n;
  1287. return n;
  1288. }
  1289. static long
  1290. io_fread(VALUE str, long offset, rb_io_t *fptr)
  1291. {
  1292. long len = RSTRING_LEN(str) - offset;
  1293. long n = len;
  1294. long c;
  1295. if (READ_DATA_PENDING(fptr) == 0) {
  1296. while (n > 0) {
  1297. again:
  1298. c = rb_read_internal(fptr->fd, RSTRING_PTR(str)+offset, n);
  1299. if (c == 0) {
  1300. io_set_eof(fptr);
  1301. break;
  1302. }
  1303. if (c < 0) {
  1304. if (rb_io_wait_readable(fptr->fd))
  1305. goto again;
  1306. rb_sys_fail_path(fptr->pathv);
  1307. }
  1308. offset += c;
  1309. if ((n -= c) <= 0) break;
  1310. rb_thread_wait_fd(fptr->fd);
  1311. }
  1312. return len - n;
  1313. }
  1314. while (n > 0) {
  1315. c = read_buffered_data(RSTRING_PTR(str)+offset, n, fptr);
  1316. if (c > 0) {
  1317. offset += c;
  1318. if ((n -= c) <= 0) break;
  1319. }
  1320. rb_thread_wait_fd(fptr->fd);
  1321. rb_io_check_closed(fptr);
  1322. if (io_fillbuf(fptr) < 0) {
  1323. break;
  1324. }
  1325. }
  1326. return len - n;
  1327. }
  1328. #define SMALLBUF 100
  1329. static long
  1330. remain_size(rb_io_t *fptr)
  1331. {
  1332. struct stat st;
  1333. off_t siz = READ_DATA_PENDING_COUNT(fptr);
  1334. off_t pos;
  1335. if (fstat(fptr->fd, &st) == 0 && S_ISREG(st.st_mode)
  1336. #if defined(__BEOS__) || defined(__HAIKU__)
  1337. && (st.st_dev > 3)
  1338. #endif
  1339. )
  1340. {
  1341. if (io_fflush(fptr) < 0)
  1342. rb_sys_fail(0);
  1343. pos = lseek(fptr->fd, 0, SEEK_CUR);
  1344. if (st.st_size >= pos && pos >= 0) {
  1345. siz += st.st_size - pos;
  1346. if (siz > LONG_MAX) {
  1347. rb_raise(rb_eIOError, "file too big for single read");
  1348. }
  1349. }
  1350. }
  1351. else {
  1352. siz += BUFSIZ;
  1353. }
  1354. return (long)siz;
  1355. }
  1356. static VALUE
  1357. io_enc_str(VALUE str, rb_io_t *fptr)
  1358. {
  1359. OBJ_TAINT(str);
  1360. rb_enc_associate(str, io_read_encoding(fptr));
  1361. return str;
  1362. }
  1363. static void
  1364. make_readconv(rb_io_t *fptr, int size)
  1365. {
  1366. if (!fptr->readconv) {
  1367. int ecflags;
  1368. VALUE ecopts;
  1369. const char *sname, *dname;
  1370. ecflags = fptr->encs.ecflags;
  1371. ecopts = fptr->encs.ecopts;
  1372. if (NEED_NEWLINE_DECORATOR_ON_READ(fptr))
  1373. ecflags |= ECONV_UNIVERSAL_NEWLINE_DECORATOR;
  1374. if (fptr->encs.enc2) {
  1375. sname = rb_enc_name(fptr->encs.enc2);
  1376. dname = rb_enc_name(fptr->encs.enc);
  1377. }
  1378. else {
  1379. sname = dname = "";
  1380. }
  1381. fptr->readconv = rb_econv_open_opts(sname, dname, ecflags, ecopts);
  1382. if (!fptr->readconv)
  1383. rb_exc_raise(rb_econv_open_exc(sname, dname, ecflags));
  1384. fptr->cbuf_off = 0;
  1385. fptr->cbuf_len = 0;
  1386. fptr->cbuf_capa = size < 1024 ? 1024 : size;
  1387. fptr->cbuf = ALLOC_N(char, fptr->cbuf_capa);
  1388. }
  1389. }
  1390. #define MORE_CHAR_SUSPENDED Qtrue
  1391. #define MORE_CHAR_FINISHED Qnil
  1392. static VALUE
  1393. fill_cbuf(rb_io_t *fptr, int ec_flags)
  1394. {
  1395. const unsigned char *ss, *sp, *se;
  1396. unsigned char *ds, *dp, *de;
  1397. rb_econv_result_t res;
  1398. int putbackable;
  1399. int cbuf_len0;
  1400. VALUE exc;
  1401. ec_flags |= ECONV_PARTIAL_INPUT;
  1402. if (fptr->cbuf_len == fptr->cbuf_capa)
  1403. return MORE_CHAR_SUSPENDED; /* cbuf full */
  1404. if (fptr->cbuf_len == 0)
  1405. fptr->cbuf_off = 0;
  1406. else if (fptr->cbuf_off + fptr->cbuf_len == fptr->cbuf_capa) {
  1407. memmove(fptr->cbuf, fptr->cbuf+fptr->cbuf_off, fptr->cbuf_len);
  1408. fptr->cbuf_off = 0;
  1409. }
  1410. cbuf_len0 = fptr->cbuf_len;
  1411. while (1) {
  1412. ss = sp = (const unsigned char *)fptr->rbuf + fptr->rbuf_off;
  1413. se = sp + fptr->rbuf_len;
  1414. ds = dp = (unsigned char *)fptr->cbuf + fptr->cbuf_off + fptr->cbuf_len;
  1415. de = (unsigned char *)fptr->cbuf + fptr->cbuf_capa;
  1416. res = rb_econv_convert(fptr->readconv, &sp, se, &dp, de, ec_flags);
  1417. fptr->rbuf_off += (int)(sp - ss);
  1418. fptr->rbuf_len -= (int)(sp - ss);
  1419. fptr->cbuf_len += (int)(dp - ds);
  1420. putbackable = rb_econv_putbackable(fptr->readconv);
  1421. if (putbackable) {
  1422. rb_econv_putback(fptr->readconv, (unsigned char *)fptr->rbuf + fptr->rbuf_off - putbackable, putbackable);
  1423. fptr->rbuf_off -= putbackable;
  1424. fptr->rbuf_len += putbackable;
  1425. }
  1426. exc = rb_econv_make_exception(fptr->readconv);
  1427. if (!NIL_P(exc))
  1428. return exc;
  1429. if (cbuf_len0 != fptr->cbuf_len)
  1430. return MORE_CHAR_SUSPENDED;
  1431. if (res == econv_finished) {
  1432. return MORE_CHAR_FINISHED;
  1433. }
  1434. if (res == econv_source_buffer_empty) {
  1435. if (fptr->rbuf_len == 0) {
  1436. rb_thread_wait_fd(fptr->fd);
  1437. rb_io_check_closed(fptr);
  1438. if (io_fillbuf(fptr) == -1) {
  1439. ds = dp = (unsigned char *)fptr->cbuf + fptr->cbuf_off + fptr->cbuf_len;
  1440. de = (unsigned char *)fptr->cbuf + fptr->cbuf_capa;
  1441. res = rb_econv_convert(fptr->readconv, NULL, NULL, &dp, de, 0);
  1442. fptr->cbuf_len += (int)(dp - ds);
  1443. rb_econv_check_error(fptr->readconv);
  1444. }
  1445. }
  1446. }
  1447. }
  1448. }
  1449. static VALUE
  1450. more_char(rb_io_t *fptr)
  1451. {
  1452. VALUE v;
  1453. v = fill_cbuf(fptr, ECONV_AFTER_OUTPUT);
  1454. if (v != MORE_CHAR_SUSPENDED && v != MORE_CHAR_FINISHED)
  1455. rb_exc_raise(v);
  1456. return v;
  1457. }
  1458. static VALUE
  1459. io_shift_cbuf(rb_io_t *fptr, int len, VALUE *strp)
  1460. {
  1461. VALUE str;
  1462. if (NIL_P(*strp)) {
  1463. *strp = str = rb_str_new(fptr->cbuf+fptr->cbuf_off, len);
  1464. }
  1465. else {
  1466. size_t slen;
  1467. str = *strp;
  1468. slen = RSTRING_LEN(str);
  1469. rb_str_resize(str, RSTRING_LEN(str) + len);
  1470. memcpy(RSTRING_PTR(str)+slen, fptr->cbuf+fptr->cbuf_off, len);
  1471. }
  1472. fptr->cbuf_off += len;
  1473. fptr->cbuf_len -= len;
  1474. OBJ_TAINT(str);
  1475. rb_enc_associate(str, fptr->encs.enc);
  1476. /* xxx: set coderange */
  1477. if (fptr->cbuf_len == 0)
  1478. fptr->cbuf_off = 0;
  1479. else if (fptr->cbuf_capa/2 < fptr->cbuf_off) {
  1480. memmove(fptr->cbuf, fptr->cbuf+fptr->cbuf_off, fptr->cbuf_len);
  1481. fptr->cbuf_off = 0;
  1482. }
  1483. return str;
  1484. }
  1485. static VALUE
  1486. read_all(rb_io_t *fptr, long siz, VALUE str)
  1487. {
  1488. long bytes;
  1489. long n;
  1490. long pos;
  1491. rb_encoding *enc;
  1492. int cr;
  1493. if (NEED_READCONV(fptr)) {
  1494. if (NIL_P(str)) str = rb_str_new(NULL, 0);
  1495. else rb_str_set_len(str, 0);
  1496. make_readconv(fptr, 0);
  1497. while (1) {
  1498. VALUE v;
  1499. if (fptr->cbuf_len) {
  1500. io_shift_cbuf(fptr, fptr->cbuf_len, &str);
  1501. }
  1502. v = fill_cbuf(fptr, 0);
  1503. if (v != MORE_CHAR_SUSPENDED && v != MORE_CHAR_FINISHED) {
  1504. if (fptr->cbuf_len) {
  1505. io_shift_cbuf(fptr, fptr->cbuf_len, &str);
  1506. }
  1507. rb_exc_raise(v);
  1508. }
  1509. if (v == MORE_CHAR_FINISHED) {
  1510. clear_readconv(fptr);
  1511. return io_enc_str(str, fptr);
  1512. }
  1513. }
  1514. }
  1515. bytes = 0;
  1516. pos = 0;
  1517. enc = io_read_encoding(fptr);
  1518. cr = 0;
  1519. if (siz == 0) siz = BUFSIZ;
  1520. if (NIL_P(str)) {
  1521. str = rb_str_new(0, siz);
  1522. }
  1523. else {
  1524. rb_str_resize(str, siz);
  1525. }
  1526. for (;;) {
  1527. READ_CHECK(fptr);
  1528. n = io_fread(str, bytes, fptr);
  1529. if (n == 0 && bytes == 0) {
  1530. break;
  1531. }
  1532. bytes += n;
  1533. if (cr != ENC_CODERANGE_BROKEN)
  1534. pos += rb_str_coderange_scan_restartable(RSTRING_PTR(str) + pos, RSTRING_PTR(str) + bytes, enc, &cr);
  1535. if (bytes < siz) break;
  1536. siz += BUFSIZ;
  1537. rb_str_resize(str, siz);
  1538. }
  1539. if (bytes != siz) rb_str_resize(str, bytes);
  1540. str = io_enc_str(str, fptr);
  1541. ENC_CODERANGE_SET(str, cr);
  1542. return str;
  1543. }
  1544. void
  1545. rb_io_set_nonblock(rb_io_t *fptr)
  1546. {
  1547. int oflags;
  1548. #ifdef F_GETFL
  1549. oflags = fcntl(fptr->fd, F_GETFL);
  1550. if (oflags == -1) {
  1551. rb_sys_fail_path(fptr->pathv);
  1552. }
  1553. #else
  1554. oflags = 0;
  1555. #endif
  1556. if ((oflags & O_NONBLOCK) == 0) {
  1557. oflags |= O_NONBLOCK;
  1558. if (fcntl(fptr->fd, F_SETFL, oflags) == -1) {
  1559. rb_sys_fail_path(fptr->pathv);
  1560. }
  1561. }
  1562. }
  1563. static VALUE
  1564. io_getpartial(int argc, VALUE *argv, VALUE io, int nonblock)
  1565. {
  1566. rb_io_t *fptr;
  1567. VALUE length, str;
  1568. long n, len;
  1569. rb_scan_args(argc, argv, "11", &length, &str);
  1570. if ((len = NUM2LONG(length)) < 0) {
  1571. rb_raise(rb_eArgError, "negative length %ld given", len);
  1572. }
  1573. if (NIL_P(str)) {
  1574. str = rb_str_new(0, len);
  1575. }
  1576. else {
  1577. StringValue(str);
  1578. rb_str_modify(str);
  1579. rb_str_resize(str, len);
  1580. }
  1581. OBJ_TAINT(str);
  1582. GetOpenFile(io, fptr);
  1583. rb_io_check_readable(fptr);
  1584. if (len == 0)
  1585. return str;
  1586. if (!nonblock)
  1587. READ_CHECK(fptr);
  1588. if (RSTRING_LEN(str) != len) {
  1589. modified:
  1590. rb_raise(rb_eRuntimeError, "buffer string modified");
  1591. }
  1592. n = read_buffered_data(RSTRING_PTR(str), len, fptr);
  1593. if (n <= 0) {
  1594. again:
  1595. if (RSTRING_LEN(str) != len) goto modified;
  1596. if (nonblock) {
  1597. rb_io_set_nonblock(fptr);
  1598. }
  1599. n = rb_read_internal(fptr->fd, RSTRING_PTR(str), len);
  1600. if (n < 0) {
  1601. if (!nonblock && rb_io_wait_readable(fptr->fd))
  1602. goto again;
  1603. if (nonblock && (errno == EWOULDBLOCK || errno == EAGAIN))
  1604. rb_mod_sys_fail(rb_mWaitReadable, "read would block");
  1605. rb_sys_fail_path(fptr->pathv);
  1606. }
  1607. else if (n == 0) {
  1608. io_set_eof(fptr);
  1609. }
  1610. }
  1611. rb_str_resize(str, n);
  1612. if (n == 0)
  1613. return Qnil;
  1614. else
  1615. return str;
  1616. }
  1617. /*
  1618. * call-seq:
  1619. * ios.readpartial(maxlen) => string
  1620. * ios.readpartial(maxlen, outbuf) => outbuf
  1621. *
  1622. * Reads at most <i>maxlen</i> bytes from the I/O stream.
  1623. * It blocks only if <em>ios</em> has no data immediately available.
  1624. * It doesn't block if some data available.
  1625. * If the optional <i>outbuf</i> argument is present,
  1626. * it must reference a String, which will receive the data.
  1627. * It raises <code>EOFError</code> on end of file.
  1628. *
  1629. * readpartial is designed for streams such as pipe, socket, tty, etc.
  1630. * It blocks only when no data immediately available.
  1631. * This means that it blocks only when following all conditions hold.
  1632. * * the buffer in the IO object is empty.
  1633. * * the content of the stream is empty.
  1634. * * the stream is not reached to EOF.
  1635. *
  1636. * When readpartial blocks, it waits data or EOF on the stream.
  1637. * If some data is reached, readpartial returns with the data.
  1638. * If EOF is reached, readpartial raises EOFError.
  1639. *
  1640. * When readpartial doesn't blocks, it returns or raises immediately.
  1641. * If the buffer is not empty, it returns the data in the buffer.
  1642. * Otherwise if the stream has some content,
  1643. * it returns the data in the stream.
  1644. * Otherwise if the stream is reached to EOF, it raises EOFError.
  1645. *
  1646. * r, w = IO.pipe # buffer pipe content
  1647. * w << "abc" # "" "abc".
  1648. * r.readpartial(4096) #=> "abc" "" ""
  1649. * r.readpartial(4096) # blocks because buffer and pipe is empty.
  1650. *
  1651. * r, w = IO.pipe # buffer pipe content
  1652. * w << "abc" # "" "abc"
  1653. * w.close # "" "abc" EOF
  1654. * r.readpartial(4096) #=> "abc" "" EOF
  1655. * r.readpartial(4096) # raises EOFError
  1656. *
  1657. * r, w = IO.pipe # buffer pipe content
  1658. * w << "abc\ndef\n" # "" "abc\ndef\n"
  1659. * r.gets #=> "abc\n" "def\n" ""
  1660. * w << "ghi\n" # "def\n" "ghi\n"
  1661. * r.readpartial(4096) #=> "def\n" "" "ghi\n"
  1662. * r.readpartial(4096) #=> "ghi\n" "" ""
  1663. *
  1664. * Note that readpartial behaves similar to sysread.
  1665. * The differences are:
  1666. * * If the buffer is not empty, read from the buffer instead of "sysread for buffered IO (IOError)".
  1667. * * It doesn't cause Errno::EWOULDBLOCK and Errno::EINTR. When readpartial meets EWOULDBLOCK and EINTR by read system call, readpartial retry the system call.
  1668. *
  1669. * The later means that readpartial is nonblocking-flag insensitive.
  1670. * It blocks on the situation IO#sysread causes Errno::EWOULDBLOCK as if the fd is blocking mode.
  1671. *
  1672. */
  1673. static VALUE
  1674. io_readpartial(int argc, VALUE *argv, VALUE io)
  1675. {
  1676. VALUE ret;
  1677. ret = io_getpartial(argc, argv, io, 0);
  1678. if (NIL_P(ret))
  1679. rb_eof_error();
  1680. else
  1681. return ret;
  1682. }
  1683. /*
  1684. * call-seq:
  1685. * ios.read_nonblock(maxlen) => string
  1686. * ios.read_nonblock(maxlen, outbuf) => outbuf
  1687. *
  1688. * Reads at most <i>maxlen</i> bytes from <em>ios</em> using
  1689. * the read(2) system call after O_NONBLOCK is set for
  1690. * the underlying file descriptor.
  1691. *
  1692. * If the optional <i>outbuf</i> argument is present,
  1693. * it must reference a String, which will receive the data.
  1694. *
  1695. * read_nonblock just calls the read(2) system call.
  1696. * It causes all errors the read(2) system call causes: Errno::EWOULDBLOCK, Errno::EINTR, etc.
  1697. * The caller should care such errors.
  1698. *
  1699. * If the exception is Errno::EWOULDBLOCK or Errno::AGAIN,
  1700. * it is extended by IO::WaitReadable.
  1701. * So IO::WaitReadable can be used to rescue the exceptions for retrying read_nonblock.
  1702. *
  1703. * read_nonblock causes EOFError on EOF.
  1704. *
  1705. * If the read buffer is not empty,
  1706. * read_nonblock reads from the buffer like readpartial.
  1707. * In this case, the read(2) system call is not called.
  1708. *
  1709. * When read_nonblock raises an exception kind of IO::WaitReadable,
  1710. * read_nonblock should not be called
  1711. * until io is readable for avoiding busy loop.
  1712. * This can be done as follows.
  1713. *
  1714. * begin
  1715. * result = io.read_nonblock(maxlen)
  1716. * rescue IO::WaitReadable, Errno::EINTR
  1717. * IO.select([io])
  1718. * retry
  1719. * end
  1720. *
  1721. * Note that this is identical to readpartial
  1722. * except the non-blocking flag is set.
  1723. */
  1724. static VALUE
  1725. io_read_nonblock(int argc, VALUE *argv, VALUE io)
  1726. {
  1727. VALUE ret;
  1728. ret = io_getpartial(argc, argv, io, 1);
  1729. if (NIL_P(ret))
  1730. rb_eof_error();
  1731. else
  1732. return ret;
  1733. }
  1734. /*
  1735. * call-seq:
  1736. * ios.write_nonblock(string) => integer
  1737. *
  1738. * Writes the given string to <em>ios</em> using
  1739. * the write(2) system call after O_NONBLOCK is set for
  1740. * the underlying file descriptor.
  1741. *
  1742. * It returns the number of bytes written.
  1743. *
  1744. * write_nonblock just calls the write(2) system call.
  1745. * It causes all errors the write(2) system call causes: Errno::EWOULDBLOCK, Errno::EINTR, etc.
  1746. * The result may also be smaller than string.length (partial write).
  1747. * The caller should care such errors and partial write.
  1748. *
  1749. * If the exception is Errno::EWOULDBLOCK or Errno::AGAIN,
  1750. * it is extended by IO::WaitWritable.
  1751. * So IO::WaitWritable can be used to rescue the exceptions for retrying write_nonblock.
  1752. *
  1753. * # Creates a pipe.
  1754. * r, w = IO.pipe
  1755. *
  1756. * # write_nonblock writes only 65536 bytes and return 65536.
  1757. * # (The pipe size is 65536 bytes on this environment.)
  1758. * s = "a" * 100000
  1759. * p w.write_nonblock(s) #=> 65536
  1760. *
  1761. * # write_nonblock cannot write a byte and raise EWOULDBLOCK (EAGAIN).
  1762. * p w.write_nonblock("b") # Resource temporarily unavailable (Errno::EAGAIN)
  1763. *
  1764. * If the write buffer is not empty, it is flushed at first.
  1765. *
  1766. * When write_nonblock raises an exception kind of IO::WaitWritable,
  1767. * write_nonblock should not be called
  1768. * until io is writable for avoiding busy loop.
  1769. * This can be done as follows.
  1770. *
  1771. * begin
  1772. * result = io.write_nonblock(string)
  1773. * rescue IO::WaitWritable, Errno::EINTR
  1774. * IO.select(nil, [io])
  1775. * retry
  1776. * end
  1777. *
  1778. * Note that this doesn't guarantee to write all data in string.
  1779. * The length written is reported as result and it should be checked later.
  1780. *
  1781. */
  1782. static VALUE
  1783. rb_io_write_nonblock(VALUE io, VALUE str)
  1784. {
  1785. rb_io_t *fptr;
  1786. long n;
  1787. rb_secure(4);
  1788. if (TYPE(str) != T_STRING)
  1789. str = rb_obj_as_string(str);
  1790. io = GetWriteIO(io);
  1791. Get

Large files files are truncated, but you can click here to view the full file