fports.c 24 KB

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