fports.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  1. /* Copyright (C) 1995,1996,1997,1998,1999,2000,2001, 2002, 2003, 2004, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
  2. *
  3. * This library is free software; you can redistribute it and/or
  4. * modify it under the terms of the GNU Lesser General Public License
  5. * as published by the Free Software Foundation; either version 3 of
  6. * the License, or (at your option) any later version.
  7. *
  8. * This library is distributed in the hope that it will be useful, but
  9. * WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. * Lesser General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU Lesser General Public
  14. * License along with this library; if not, write to the Free Software
  15. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  16. * 02110-1301 USA
  17. */
  18. #define _LARGEFILE64_SOURCE /* ask for stat64 etc */
  19. #ifdef HAVE_CONFIG_H
  20. # include <config.h>
  21. #endif
  22. #include <stdio.h>
  23. #include <fcntl.h>
  24. #include "libguile/_scm.h"
  25. #include "libguile/strings.h"
  26. #include "libguile/validate.h"
  27. #include "libguile/gc.h"
  28. #include "libguile/posix.h"
  29. #include "libguile/dynwind.h"
  30. #include "libguile/hashtab.h"
  31. #include "libguile/fports.h"
  32. #ifdef HAVE_STRING_H
  33. #include <string.h>
  34. #endif
  35. #ifdef HAVE_UNISTD_H
  36. #include <unistd.h>
  37. #endif
  38. #ifdef HAVE_IO_H
  39. #include <io.h>
  40. #endif
  41. #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
  42. #include <sys/stat.h>
  43. #endif
  44. #include <errno.h>
  45. #include <sys/types.h>
  46. #include "libguile/iselect.h"
  47. /* Some defines for Windows (native port, not Cygwin). */
  48. #ifdef __MINGW32__
  49. # include <sys/stat.h>
  50. # include <winsock2.h>
  51. #endif /* __MINGW32__ */
  52. #include <full-write.h>
  53. /* Mingw (version 3.4.5, circa 2006) has ftruncate as an alias for chsize
  54. already, but have this code here in case that wasn't so in past versions,
  55. or perhaps to help other minimal DOS environments.
  56. gnulib ftruncate.c has code using fcntl F_CHSIZE and F_FREESP, which
  57. might be possibilities if we've got other systems without ftruncate. */
  58. #if HAVE_CHSIZE && ! HAVE_FTRUNCATE
  59. # define ftruncate(fd, size) chsize (fd, size)
  60. #undef HAVE_FTRUNCATE
  61. #define HAVE_FTRUNCATE 1
  62. #endif
  63. #if SIZEOF_OFF_T == SIZEOF_INT
  64. #define OFF_T_MAX INT_MAX
  65. #define OFF_T_MIN INT_MIN
  66. #elif SIZEOF_OFF_T == SIZEOF_LONG
  67. #define OFF_T_MAX LONG_MAX
  68. #define OFF_T_MIN LONG_MIN
  69. #elif SIZEOF_OFF_T == SIZEOF_LONG_LONG
  70. #define OFF_T_MAX LONG_LONG_MAX
  71. #define OFF_T_MIN LONG_LONG_MIN
  72. #else
  73. #error Oops, unknown OFF_T size
  74. #endif
  75. scm_t_bits scm_tc16_fport;
  76. /* default buffer size, used if the O/S won't supply a value. */
  77. static const size_t default_buffer_size = 1024;
  78. /* create FPORT buffer with specified sizes (or -1 to use default size or
  79. 0 for no buffer. */
  80. static void
  81. scm_fport_buffer_add (SCM port, long read_size, int write_size)
  82. #define FUNC_NAME "scm_fport_buffer_add"
  83. {
  84. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  85. if (read_size == -1 || write_size == -1)
  86. {
  87. size_t default_size;
  88. #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
  89. struct stat st;
  90. scm_t_fport *fp = SCM_FSTREAM (port);
  91. default_size = (fstat (fp->fdes, &st) == -1) ? default_buffer_size
  92. : st.st_blksize;
  93. #else
  94. default_size = default_buffer_size;
  95. #endif
  96. if (read_size == -1)
  97. read_size = default_size;
  98. if (write_size == -1)
  99. write_size = default_size;
  100. }
  101. if (SCM_INPUT_PORT_P (port) && read_size > 0)
  102. {
  103. pt->read_buf = scm_gc_malloc (read_size, "port buffer");
  104. pt->read_pos = pt->read_end = pt->read_buf;
  105. pt->read_buf_size = read_size;
  106. }
  107. else
  108. {
  109. pt->read_pos = pt->read_buf = pt->read_end = &pt->shortbuf;
  110. pt->read_buf_size = 1;
  111. }
  112. if (SCM_OUTPUT_PORT_P (port) && write_size > 0)
  113. {
  114. pt->write_buf = scm_gc_malloc (write_size, "port buffer");
  115. pt->write_pos = pt->write_buf;
  116. pt->write_buf_size = write_size;
  117. }
  118. else
  119. {
  120. pt->write_buf = pt->write_pos = &pt->shortbuf;
  121. pt->write_buf_size = 1;
  122. }
  123. pt->write_end = pt->write_buf + pt->write_buf_size;
  124. if (read_size > 0 || write_size > 0)
  125. SCM_SET_CELL_WORD_0 (port, SCM_CELL_WORD_0 (port) & ~SCM_BUF0);
  126. else
  127. SCM_SET_CELL_WORD_0 (port, SCM_CELL_WORD_0 (port) | SCM_BUF0);
  128. }
  129. #undef FUNC_NAME
  130. SCM_DEFINE (scm_setvbuf, "setvbuf", 2, 1, 0,
  131. (SCM port, SCM mode, SCM size),
  132. "Set the buffering mode for @var{port}. @var{mode} can be:\n"
  133. "@table @code\n"
  134. "@item _IONBF\n"
  135. "non-buffered\n"
  136. "@item _IOLBF\n"
  137. "line buffered\n"
  138. "@item _IOFBF\n"
  139. "block buffered, using a newly allocated buffer of @var{size} bytes.\n"
  140. "If @var{size} is omitted, a default size will be used.\n"
  141. "@end table")
  142. #define FUNC_NAME s_scm_setvbuf
  143. {
  144. int cmode;
  145. long csize;
  146. scm_t_port *pt;
  147. port = SCM_COERCE_OUTPORT (port);
  148. SCM_VALIDATE_OPFPORT (1,port);
  149. cmode = scm_to_int (mode);
  150. if (cmode != _IONBF && cmode != _IOFBF && cmode != _IOLBF)
  151. scm_out_of_range (FUNC_NAME, mode);
  152. if (cmode == _IOLBF)
  153. {
  154. SCM_SET_CELL_WORD_0 (port, SCM_CELL_WORD_0 (port) | SCM_BUFLINE);
  155. cmode = _IOFBF;
  156. }
  157. else
  158. {
  159. SCM_SET_CELL_WORD_0 (port, SCM_CELL_WORD_0 (port) & ~(scm_t_bits)SCM_BUFLINE);
  160. }
  161. if (SCM_UNBNDP (size))
  162. {
  163. if (cmode == _IOFBF)
  164. csize = -1;
  165. else
  166. csize = 0;
  167. }
  168. else
  169. {
  170. csize = scm_to_int (size);
  171. if (csize < 0 || (cmode == _IONBF && csize > 0))
  172. scm_out_of_range (FUNC_NAME, size);
  173. }
  174. pt = SCM_PTAB_ENTRY (port);
  175. /* silently discards buffered and put-back chars. */
  176. if (pt->read_buf == pt->putback_buf)
  177. {
  178. pt->read_buf = pt->saved_read_buf;
  179. pt->read_pos = pt->saved_read_pos;
  180. pt->read_end = pt->saved_read_end;
  181. pt->read_buf_size = pt->saved_read_buf_size;
  182. }
  183. if (pt->read_buf != &pt->shortbuf)
  184. scm_gc_free (pt->read_buf, pt->read_buf_size, "port buffer");
  185. if (pt->write_buf != &pt->shortbuf)
  186. scm_gc_free (pt->write_buf, pt->write_buf_size, "port buffer");
  187. scm_fport_buffer_add (port, csize, csize);
  188. return SCM_UNSPECIFIED;
  189. }
  190. #undef FUNC_NAME
  191. /* Move ports with the specified file descriptor to new descriptors,
  192. * resetting the revealed count to 0.
  193. */
  194. static void
  195. scm_i_evict_port (void *closure, SCM port)
  196. {
  197. int fd = * (int*) closure;
  198. if (SCM_FPORTP (port))
  199. {
  200. scm_t_fport *fp = SCM_FSTREAM (port);
  201. if (fp->fdes == fd)
  202. {
  203. fp->fdes = dup (fd);
  204. if (fp->fdes == -1)
  205. scm_syserror ("scm_evict_ports");
  206. scm_set_port_revealed_x (port, scm_from_int (0));
  207. }
  208. }
  209. }
  210. void
  211. scm_evict_ports (int fd)
  212. {
  213. scm_c_port_for_each (scm_i_evict_port, (void *) &fd);
  214. }
  215. SCM_DEFINE (scm_file_port_p, "file-port?", 1, 0, 0,
  216. (SCM obj),
  217. "Determine whether @var{obj} is a port that is related to a file.")
  218. #define FUNC_NAME s_scm_file_port_p
  219. {
  220. return scm_from_bool (SCM_FPORTP (obj));
  221. }
  222. #undef FUNC_NAME
  223. /* scm_open_file
  224. * Return a new port open on a given file.
  225. *
  226. * The mode string must match the pattern: [rwa+]** which
  227. * is interpreted in the usual unix way.
  228. *
  229. * Return the new port.
  230. */
  231. SCM_DEFINE (scm_open_file, "open-file", 2, 0, 0,
  232. (SCM filename, SCM mode),
  233. "Open the file whose name is @var{filename}, and return a port\n"
  234. "representing that file. The attributes of the port are\n"
  235. "determined by the @var{mode} string. The way in which this is\n"
  236. "interpreted is similar to C stdio. The first character must be\n"
  237. "one of the following:\n"
  238. "@table @samp\n"
  239. "@item r\n"
  240. "Open an existing file for input.\n"
  241. "@item w\n"
  242. "Open a file for output, creating it if it doesn't already exist\n"
  243. "or removing its contents if it does.\n"
  244. "@item a\n"
  245. "Open a file for output, creating it if it doesn't already\n"
  246. "exist. All writes to the port will go to the end of the file.\n"
  247. "The \"append mode\" can be turned off while the port is in use\n"
  248. "@pxref{Ports and File Descriptors, fcntl}\n"
  249. "@end table\n"
  250. "The following additional characters can be appended:\n"
  251. "@table @samp\n"
  252. "@item b\n"
  253. "Open the underlying file in binary mode, if supported by the operating system. "
  254. "@item +\n"
  255. "Open the port for both input and output. E.g., @code{r+}: open\n"
  256. "an existing file for both input and output.\n"
  257. "@item 0\n"
  258. "Create an \"unbuffered\" port. In this case input and output\n"
  259. "operations are passed directly to the underlying port\n"
  260. "implementation without additional buffering. This is likely to\n"
  261. "slow down I/O operations. The buffering mode can be changed\n"
  262. "while a port is in use @pxref{Ports and File Descriptors,\n"
  263. "setvbuf}\n"
  264. "@item l\n"
  265. "Add line-buffering to the port. The port output buffer will be\n"
  266. "automatically flushed whenever a newline character is written.\n"
  267. "@end table\n"
  268. "In theory we could create read/write ports which were buffered\n"
  269. "in one direction only. However this isn't included in the\n"
  270. "current interfaces. If a file cannot be opened with the access\n"
  271. "requested, @code{open-file} throws an exception.")
  272. #define FUNC_NAME s_scm_open_file
  273. {
  274. SCM port;
  275. int fdes;
  276. int flags = 0;
  277. char *file;
  278. char *md;
  279. char *ptr;
  280. scm_dynwind_begin (0);
  281. file = scm_to_locale_string (filename);
  282. scm_dynwind_free (file);
  283. md = scm_to_locale_string (mode);
  284. scm_dynwind_free (md);
  285. switch (*md)
  286. {
  287. case 'r':
  288. flags |= O_RDONLY;
  289. break;
  290. case 'w':
  291. flags |= O_WRONLY | O_CREAT | O_TRUNC;
  292. break;
  293. case 'a':
  294. flags |= O_WRONLY | O_CREAT | O_APPEND;
  295. break;
  296. default:
  297. scm_out_of_range (FUNC_NAME, mode);
  298. }
  299. ptr = md + 1;
  300. while (*ptr != '\0')
  301. {
  302. switch (*ptr)
  303. {
  304. case '+':
  305. flags = (flags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;
  306. break;
  307. case 'b':
  308. #if defined (O_BINARY)
  309. flags |= O_BINARY;
  310. #endif
  311. break;
  312. case '0': /* unbuffered: handled later. */
  313. case 'l': /* line buffered: handled during output. */
  314. break;
  315. default:
  316. scm_out_of_range (FUNC_NAME, mode);
  317. }
  318. ptr++;
  319. }
  320. SCM_SYSCALL (fdes = open_or_open64 (file, flags, 0666));
  321. if (fdes == -1)
  322. {
  323. int en = errno;
  324. SCM_SYSERROR_MSG ("~A: ~S",
  325. scm_cons (scm_strerror (scm_from_int (en)),
  326. scm_cons (filename, SCM_EOL)), en);
  327. }
  328. port = scm_i_fdes_to_port (fdes, scm_i_mode_bits (mode), filename);
  329. scm_dynwind_end ();
  330. return port;
  331. }
  332. #undef FUNC_NAME
  333. #ifdef __MINGW32__
  334. /*
  335. * Try getting the appropiate file flags for a given file descriptor
  336. * under Windows. This incorporates some fancy operations because Windows
  337. * differentiates between file, pipe and socket descriptors.
  338. */
  339. #ifndef O_ACCMODE
  340. # define O_ACCMODE 0x0003
  341. #endif
  342. static int getflags (int fdes)
  343. {
  344. int flags = 0;
  345. struct stat buf;
  346. int error, optlen = sizeof (int);
  347. /* Is this a socket ? */
  348. if (getsockopt (fdes, SOL_SOCKET, SO_ERROR, (void *) &error, &optlen) >= 0)
  349. flags = O_RDWR;
  350. /* Maybe a regular file ? */
  351. else if (fstat (fdes, &buf) < 0)
  352. flags = -1;
  353. else
  354. {
  355. /* Or an anonymous pipe handle ? */
  356. if (buf.st_mode & _S_IFIFO)
  357. flags = PeekNamedPipe ((HANDLE) _get_osfhandle (fdes), NULL, 0,
  358. NULL, NULL, NULL) ? O_RDONLY : O_WRONLY;
  359. /* stdin ? */
  360. else if (fdes == fileno (stdin) && isatty (fdes))
  361. flags = O_RDONLY;
  362. /* stdout / stderr ? */
  363. else if ((fdes == fileno (stdout) || fdes == fileno (stderr)) &&
  364. isatty (fdes))
  365. flags = O_WRONLY;
  366. else
  367. flags = buf.st_mode;
  368. }
  369. return flags;
  370. }
  371. #endif /* __MINGW32__ */
  372. /* Building Guile ports from a file descriptor. */
  373. /* Build a Scheme port from an open file descriptor `fdes'.
  374. MODE indicates whether FILE is open for reading or writing; it uses
  375. the same notation as open-file's second argument.
  376. NAME is a string to be used as the port's filename.
  377. */
  378. SCM
  379. scm_i_fdes_to_port (int fdes, long mode_bits, SCM name)
  380. #define FUNC_NAME "scm_fdes_to_port"
  381. {
  382. SCM port;
  383. scm_t_port *pt;
  384. int flags;
  385. /* test that fdes is valid. */
  386. #ifdef __MINGW32__
  387. flags = getflags (fdes);
  388. #else
  389. flags = fcntl (fdes, F_GETFL, 0);
  390. #endif
  391. if (flags == -1)
  392. SCM_SYSERROR;
  393. flags &= O_ACCMODE;
  394. if (flags != O_RDWR
  395. && ((flags != O_WRONLY && (mode_bits & SCM_WRTNG))
  396. || (flags != O_RDONLY && (mode_bits & SCM_RDNG))))
  397. {
  398. SCM_MISC_ERROR ("requested file mode not available on fdes", SCM_EOL);
  399. }
  400. scm_i_scm_pthread_mutex_lock (&scm_i_port_table_mutex);
  401. port = scm_new_port_table_entry (scm_tc16_fport);
  402. SCM_SET_CELL_TYPE(port, scm_tc16_fport | mode_bits);
  403. pt = SCM_PTAB_ENTRY(port);
  404. {
  405. scm_t_fport *fp
  406. = (scm_t_fport *) scm_gc_malloc (sizeof (scm_t_fport), "file port");
  407. fp->fdes = fdes;
  408. pt->rw_random = SCM_FDES_RANDOM_P (fdes);
  409. SCM_SETSTREAM (port, fp);
  410. if (mode_bits & SCM_BUF0)
  411. scm_fport_buffer_add (port, 0, 0);
  412. else
  413. scm_fport_buffer_add (port, -1, -1);
  414. }
  415. SCM_SET_FILENAME (port, name);
  416. scm_i_pthread_mutex_unlock (&scm_i_port_table_mutex);
  417. return port;
  418. }
  419. #undef FUNC_NAME
  420. SCM
  421. scm_fdes_to_port (int fdes, char *mode, SCM name)
  422. {
  423. return scm_i_fdes_to_port (fdes, scm_mode_bits (mode), name);
  424. }
  425. /* Return a lower bound on the number of bytes available for input. */
  426. static int
  427. fport_input_waiting (SCM port)
  428. {
  429. #ifdef HAVE_SELECT
  430. int fdes = SCM_FSTREAM (port)->fdes;
  431. struct timeval timeout;
  432. SELECT_TYPE read_set;
  433. SELECT_TYPE write_set;
  434. SELECT_TYPE except_set;
  435. FD_ZERO (&read_set);
  436. FD_ZERO (&write_set);
  437. FD_ZERO (&except_set);
  438. FD_SET (fdes, &read_set);
  439. timeout.tv_sec = 0;
  440. timeout.tv_usec = 0;
  441. if (select (SELECT_SET_SIZE,
  442. &read_set, &write_set, &except_set, &timeout)
  443. < 0)
  444. scm_syserror ("fport_input_waiting");
  445. return FD_ISSET (fdes, &read_set) ? 1 : 0;
  446. #elif HAVE_IOCTL && defined (FIONREAD)
  447. /* Note: cannot test just defined(FIONREAD) here, since mingw has FIONREAD
  448. (for use with winsock ioctlsocket()) but not ioctl(). */
  449. int fdes = SCM_FSTREAM (port)->fdes;
  450. int remir;
  451. ioctl(fdes, FIONREAD, &remir);
  452. return remir;
  453. #else
  454. scm_misc_error ("fport_input_waiting",
  455. "Not fully implemented on this platform",
  456. SCM_EOL);
  457. #endif
  458. }
  459. static int
  460. fport_print (SCM exp, SCM port, scm_print_state *pstate SCM_UNUSED)
  461. {
  462. scm_puts ("#<", port);
  463. scm_print_port_mode (exp, port);
  464. if (SCM_OPFPORTP (exp))
  465. {
  466. int fdes;
  467. SCM name = SCM_FILENAME (exp);
  468. if (scm_is_string (name) || scm_is_symbol (name))
  469. scm_display (name, port);
  470. else
  471. scm_puts (SCM_PTOBNAME (SCM_PTOBNUM (exp)), port);
  472. scm_putc (' ', port);
  473. fdes = (SCM_FSTREAM (exp))->fdes;
  474. #ifdef HAVE_TTYNAME
  475. if (isatty (fdes))
  476. scm_display (scm_ttyname (exp), port);
  477. else
  478. #endif /* HAVE_TTYNAME */
  479. scm_intprint (fdes, 10, port);
  480. }
  481. else
  482. {
  483. scm_puts (SCM_PTOBNAME (SCM_PTOBNUM (exp)), port);
  484. scm_putc (' ', port);
  485. scm_uintprint ((scm_t_bits) SCM_PTAB_ENTRY (exp), 16, port);
  486. }
  487. scm_putc ('>', port);
  488. return 1;
  489. }
  490. #ifndef __MINGW32__
  491. /* thread-local block for input on fport's fdes. */
  492. static void
  493. fport_wait_for_input (SCM port)
  494. {
  495. int fdes = SCM_FSTREAM (port)->fdes;
  496. if (!fport_input_waiting (port))
  497. {
  498. int n;
  499. SELECT_TYPE readfds;
  500. int flags = fcntl (fdes, F_GETFL);
  501. if (flags == -1)
  502. scm_syserror ("scm_fdes_wait_for_input");
  503. if (!(flags & O_NONBLOCK))
  504. do
  505. {
  506. FD_ZERO (&readfds);
  507. FD_SET (fdes, &readfds);
  508. n = scm_std_select (fdes + 1, &readfds, NULL, NULL, NULL);
  509. }
  510. while (n == -1 && errno == EINTR);
  511. }
  512. }
  513. #endif /* !__MINGW32__ */
  514. static void fport_flush (SCM port);
  515. /* fill a port's read-buffer with a single read. returns the first
  516. char or EOF if end of file. */
  517. static int
  518. fport_fill_input (SCM port)
  519. {
  520. long count;
  521. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  522. scm_t_fport *fp = SCM_FSTREAM (port);
  523. #ifndef __MINGW32__
  524. fport_wait_for_input (port);
  525. #endif /* !__MINGW32__ */
  526. SCM_SYSCALL (count = read (fp->fdes, pt->read_buf, pt->read_buf_size));
  527. if (count == -1)
  528. scm_syserror ("fport_fill_input");
  529. if (count == 0)
  530. return EOF;
  531. else
  532. {
  533. pt->read_pos = pt->read_buf;
  534. pt->read_end = pt->read_buf + count;
  535. return *pt->read_buf;
  536. }
  537. }
  538. static scm_t_off
  539. fport_seek (SCM port, scm_t_off offset, int whence)
  540. {
  541. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  542. scm_t_fport *fp = SCM_FSTREAM (port);
  543. off_t_or_off64_t rv;
  544. off_t_or_off64_t result;
  545. if (pt->rw_active == SCM_PORT_WRITE)
  546. {
  547. if (offset != 0 || whence != SEEK_CUR)
  548. {
  549. fport_flush (port);
  550. result = rv = lseek_or_lseek64 (fp->fdes, offset, whence);
  551. }
  552. else
  553. {
  554. /* read current position without disturbing the buffer. */
  555. rv = lseek_or_lseek64 (fp->fdes, offset, whence);
  556. result = rv + (pt->write_pos - pt->write_buf);
  557. }
  558. }
  559. else if (pt->rw_active == SCM_PORT_READ)
  560. {
  561. if (offset != 0 || whence != SEEK_CUR)
  562. {
  563. /* could expand to avoid a second seek. */
  564. scm_end_input (port);
  565. result = rv = lseek_or_lseek64 (fp->fdes, offset, whence);
  566. }
  567. else
  568. {
  569. /* read current position without disturbing the buffer
  570. (particularly the unread-char buffer). */
  571. rv = lseek_or_lseek64 (fp->fdes, offset, whence);
  572. result = rv - (pt->read_end - pt->read_pos);
  573. if (pt->read_buf == pt->putback_buf)
  574. result -= pt->saved_read_end - pt->saved_read_pos;
  575. }
  576. }
  577. else /* SCM_PORT_NEITHER */
  578. {
  579. result = rv = lseek_or_lseek64 (fp->fdes, offset, whence);
  580. }
  581. if (rv == -1)
  582. scm_syserror ("fport_seek");
  583. return result;
  584. }
  585. static void
  586. fport_truncate (SCM port, scm_t_off length)
  587. {
  588. scm_t_fport *fp = SCM_FSTREAM (port);
  589. if (ftruncate (fp->fdes, length) == -1)
  590. scm_syserror ("ftruncate");
  591. }
  592. /* helper for fport_write: try to write data, using multiple system
  593. calls if required. */
  594. #define FUNC_NAME "write_all"
  595. static void write_all (SCM port, const void *data, size_t remaining)
  596. {
  597. int fdes = SCM_FSTREAM (port)->fdes;
  598. while (remaining > 0)
  599. {
  600. size_t done;
  601. SCM_SYSCALL (done = write (fdes, data, remaining));
  602. if (done == -1)
  603. SCM_SYSERROR;
  604. remaining -= done;
  605. data = ((const char *) data) + done;
  606. }
  607. }
  608. #undef FUNC_NAME
  609. static void
  610. fport_write (SCM port, const void *data, size_t size)
  611. {
  612. /* this procedure tries to minimize the number of writes/flushes. */
  613. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  614. if (pt->write_buf == &pt->shortbuf
  615. || (pt->write_pos == pt->write_buf && size >= pt->write_buf_size))
  616. {
  617. /* "unbuffered" port, or
  618. port with empty buffer and data won't fit in buffer. */
  619. write_all (port, data, size);
  620. return;
  621. }
  622. {
  623. scm_t_off space = pt->write_end - pt->write_pos;
  624. if (size <= space)
  625. {
  626. /* data fits in buffer. */
  627. memcpy (pt->write_pos, data, size);
  628. pt->write_pos += size;
  629. if (pt->write_pos == pt->write_end)
  630. {
  631. fport_flush (port);
  632. /* we can skip the line-buffering check if nothing's buffered. */
  633. return;
  634. }
  635. }
  636. else
  637. {
  638. memcpy (pt->write_pos, data, space);
  639. pt->write_pos = pt->write_end;
  640. fport_flush (port);
  641. {
  642. const void *ptr = ((const char *) data) + space;
  643. size_t remaining = size - space;
  644. if (size >= pt->write_buf_size)
  645. {
  646. write_all (port, ptr, remaining);
  647. return;
  648. }
  649. else
  650. {
  651. memcpy (pt->write_pos, ptr, remaining);
  652. pt->write_pos += remaining;
  653. }
  654. }
  655. }
  656. /* handle line buffering. */
  657. if ((SCM_CELL_WORD_0 (port) & SCM_BUFLINE) && memchr (data, '\n', size))
  658. fport_flush (port);
  659. }
  660. }
  661. /* becomes 1 when process is exiting: normal exception handling won't
  662. work by this time. */
  663. extern int scm_i_terminating;
  664. static void
  665. fport_flush (SCM port)
  666. {
  667. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  668. scm_t_fport *fp = SCM_FSTREAM (port);
  669. unsigned char *ptr = pt->write_buf;
  670. long init_size = pt->write_pos - pt->write_buf;
  671. long remaining = init_size;
  672. while (remaining > 0)
  673. {
  674. long count;
  675. SCM_SYSCALL (count = write (fp->fdes, ptr, remaining));
  676. if (count < 0)
  677. {
  678. /* error. assume nothing was written this call, but
  679. fix up the buffer for any previous successful writes. */
  680. long done = init_size - remaining;
  681. if (done > 0)
  682. {
  683. int i;
  684. for (i = 0; i < remaining; i++)
  685. {
  686. *(pt->write_buf + i) = *(pt->write_buf + done + i);
  687. }
  688. pt->write_pos = pt->write_buf + remaining;
  689. }
  690. if (scm_i_terminating)
  691. {
  692. const char *msg = "Error: could not flush file-descriptor ";
  693. char buf[11];
  694. full_write (2, msg, strlen (msg));
  695. sprintf (buf, "%d\n", fp->fdes);
  696. full_write (2, buf, strlen (buf));
  697. count = remaining;
  698. }
  699. else if (scm_gc_running_p)
  700. {
  701. /* silently ignore the error. scm_error would abort if we
  702. called it now. */
  703. count = remaining;
  704. }
  705. else
  706. scm_syserror ("fport_flush");
  707. }
  708. ptr += count;
  709. remaining -= count;
  710. }
  711. pt->write_pos = pt->write_buf;
  712. pt->rw_active = SCM_PORT_NEITHER;
  713. }
  714. /* clear the read buffer and adjust the file position for unread bytes. */
  715. static void
  716. fport_end_input (SCM port, int offset)
  717. {
  718. scm_t_fport *fp = SCM_FSTREAM (port);
  719. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  720. offset += pt->read_end - pt->read_pos;
  721. if (offset > 0)
  722. {
  723. pt->read_pos = pt->read_end;
  724. /* will throw error if unread-char used at beginning of file
  725. then attempting to write. seems correct. */
  726. if (lseek (fp->fdes, -offset, SEEK_CUR) == -1)
  727. scm_syserror ("fport_end_input");
  728. }
  729. pt->rw_active = SCM_PORT_NEITHER;
  730. }
  731. static int
  732. fport_close (SCM port)
  733. {
  734. scm_t_fport *fp = SCM_FSTREAM (port);
  735. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  736. int rv;
  737. fport_flush (port);
  738. SCM_SYSCALL (rv = close (fp->fdes));
  739. if (rv == -1 && errno != EBADF)
  740. {
  741. if (scm_gc_running_p)
  742. /* silently ignore the error. scm_error would abort if we
  743. called it now. */
  744. ;
  745. else
  746. scm_syserror ("fport_close");
  747. }
  748. if (pt->read_buf == pt->putback_buf)
  749. pt->read_buf = pt->saved_read_buf;
  750. if (pt->read_buf != &pt->shortbuf)
  751. scm_gc_free (pt->read_buf, pt->read_buf_size, "port buffer");
  752. if (pt->write_buf != &pt->shortbuf)
  753. scm_gc_free (pt->write_buf, pt->write_buf_size, "port buffer");
  754. scm_gc_free (fp, sizeof (*fp), "file port");
  755. return rv;
  756. }
  757. static size_t
  758. fport_free (SCM port)
  759. {
  760. fport_close (port);
  761. return 0;
  762. }
  763. static scm_t_bits
  764. scm_make_fptob ()
  765. {
  766. scm_t_bits tc = scm_make_port_type ("file", fport_fill_input, fport_write);
  767. scm_set_port_free (tc, fport_free);
  768. scm_set_port_print (tc, fport_print);
  769. scm_set_port_flush (tc, fport_flush);
  770. scm_set_port_end_input (tc, fport_end_input);
  771. scm_set_port_close (tc, fport_close);
  772. scm_set_port_seek (tc, fport_seek);
  773. scm_set_port_truncate (tc, fport_truncate);
  774. scm_set_port_input_waiting (tc, fport_input_waiting);
  775. return tc;
  776. }
  777. void
  778. scm_init_fports ()
  779. {
  780. scm_tc16_fport = scm_make_fptob ();
  781. scm_c_define ("_IOFBF", scm_from_int (_IOFBF));
  782. scm_c_define ("_IOLBF", scm_from_int (_IOLBF));
  783. scm_c_define ("_IONBF", scm_from_int (_IONBF));
  784. #include "libguile/fports.x"
  785. }
  786. /*
  787. Local Variables:
  788. c-file-style: "gnu"
  789. End:
  790. */