fports.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  1. /* Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
  2. * 2004, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 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. #define _GNU_SOURCE /* ask for LONG_LONG_MAX/LONG_LONG_MIN */
  21. #ifdef HAVE_CONFIG_H
  22. # include <config.h>
  23. #endif
  24. #include <stdio.h>
  25. #include <fcntl.h>
  26. #ifdef HAVE_STRING_H
  27. #include <string.h>
  28. #endif
  29. #ifdef HAVE_UNISTD_H
  30. #include <unistd.h>
  31. #endif
  32. #ifdef HAVE_IO_H
  33. #include <io.h>
  34. #endif
  35. #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
  36. #include <sys/stat.h>
  37. #endif
  38. #include <poll.h>
  39. #include <errno.h>
  40. #include <sys/types.h>
  41. #include <sys/stat.h>
  42. #include <sys/select.h>
  43. #include <full-write.h>
  44. #include "libguile/_scm.h"
  45. #include "libguile/strings.h"
  46. #include "libguile/validate.h"
  47. #include "libguile/gc.h"
  48. #include "libguile/posix.h"
  49. #include "libguile/dynwind.h"
  50. #include "libguile/hashtab.h"
  51. #include "libguile/fports.h"
  52. #if SIZEOF_OFF_T == SIZEOF_INT
  53. #define OFF_T_MAX INT_MAX
  54. #define OFF_T_MIN INT_MIN
  55. #elif SIZEOF_OFF_T == SIZEOF_LONG
  56. #define OFF_T_MAX LONG_MAX
  57. #define OFF_T_MIN LONG_MIN
  58. #elif SIZEOF_OFF_T == SIZEOF_LONG_LONG
  59. #define OFF_T_MAX LONG_LONG_MAX
  60. #define OFF_T_MIN LONG_LONG_MIN
  61. #else
  62. #error Oops, unknown OFF_T size
  63. #endif
  64. scm_t_bits scm_tc16_fport;
  65. /* default buffer size, used if the O/S won't supply a value. */
  66. static const size_t default_buffer_size = 1024;
  67. /* create FPORT buffer with specified sizes (or -1 to use default size or
  68. 0 for no buffer. */
  69. static void
  70. scm_fport_buffer_add (SCM port, long read_size, int write_size)
  71. #define FUNC_NAME "scm_fport_buffer_add"
  72. {
  73. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  74. if (read_size == -1 || write_size == -1)
  75. {
  76. size_t default_size;
  77. #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
  78. struct stat st;
  79. scm_t_fport *fp = SCM_FSTREAM (port);
  80. default_size = (fstat (fp->fdes, &st) == -1) ? default_buffer_size
  81. : st.st_blksize;
  82. #else
  83. default_size = default_buffer_size;
  84. #endif
  85. if (read_size == -1)
  86. read_size = default_size;
  87. if (write_size == -1)
  88. write_size = default_size;
  89. }
  90. if (SCM_INPUT_PORT_P (port) && read_size > 0)
  91. {
  92. pt->read_buf = scm_gc_malloc_pointerless (read_size, "port buffer");
  93. pt->read_pos = pt->read_end = pt->read_buf;
  94. pt->read_buf_size = read_size;
  95. }
  96. else
  97. {
  98. pt->read_pos = pt->read_buf = pt->read_end = &pt->shortbuf;
  99. pt->read_buf_size = 1;
  100. }
  101. if (SCM_OUTPUT_PORT_P (port) && write_size > 0)
  102. {
  103. pt->write_buf = scm_gc_malloc_pointerless (write_size, "port buffer");
  104. pt->write_pos = pt->write_buf;
  105. pt->write_buf_size = write_size;
  106. }
  107. else
  108. {
  109. pt->write_buf = pt->write_pos = &pt->shortbuf;
  110. pt->write_buf_size = 1;
  111. }
  112. pt->write_end = pt->write_buf + pt->write_buf_size;
  113. if (read_size > 0 || write_size > 0)
  114. SCM_SET_CELL_WORD_0 (port, SCM_CELL_WORD_0 (port) & ~SCM_BUF0);
  115. else
  116. SCM_SET_CELL_WORD_0 (port, SCM_CELL_WORD_0 (port) | SCM_BUF0);
  117. }
  118. #undef FUNC_NAME
  119. SCM_DEFINE (scm_setvbuf, "setvbuf", 2, 1, 0,
  120. (SCM port, SCM mode, SCM size),
  121. "Set the buffering mode for @var{port}. @var{mode} can be:\n"
  122. "@table @code\n"
  123. "@item _IONBF\n"
  124. "non-buffered\n"
  125. "@item _IOLBF\n"
  126. "line buffered\n"
  127. "@item _IOFBF\n"
  128. "block buffered, using a newly allocated buffer of @var{size} bytes.\n"
  129. "If @var{size} is omitted, a default size will be used.\n"
  130. "@end table")
  131. #define FUNC_NAME s_scm_setvbuf
  132. {
  133. int cmode;
  134. long csize;
  135. size_t ndrained;
  136. char *drained;
  137. scm_t_port *pt;
  138. port = SCM_COERCE_OUTPORT (port);
  139. SCM_VALIDATE_OPFPORT (1,port);
  140. cmode = scm_to_int (mode);
  141. if (cmode != _IONBF && cmode != _IOFBF && cmode != _IOLBF)
  142. scm_out_of_range (FUNC_NAME, mode);
  143. if (cmode == _IOLBF)
  144. {
  145. SCM_SET_CELL_WORD_0 (port, SCM_CELL_WORD_0 (port) | SCM_BUFLINE);
  146. cmode = _IOFBF;
  147. }
  148. else
  149. {
  150. SCM_SET_CELL_WORD_0 (port, SCM_CELL_WORD_0 (port) & ~(scm_t_bits)SCM_BUFLINE);
  151. }
  152. if (SCM_UNBNDP (size))
  153. {
  154. if (cmode == _IOFBF)
  155. csize = -1;
  156. else
  157. csize = 0;
  158. }
  159. else
  160. {
  161. csize = scm_to_int (size);
  162. if (csize < 0 || (cmode == _IONBF && csize > 0))
  163. scm_out_of_range (FUNC_NAME, size);
  164. }
  165. pt = SCM_PTAB_ENTRY (port);
  166. if (SCM_INPUT_PORT_P (port))
  167. {
  168. /* Drain pending input from PORT. Don't use `scm_drain_input' since
  169. it returns a string, whereas we want binary input here. */
  170. ndrained = pt->read_end - pt->read_pos;
  171. if (pt->read_buf == pt->putback_buf)
  172. ndrained += pt->saved_read_end - pt->saved_read_pos;
  173. if (ndrained > 0)
  174. {
  175. drained = scm_gc_malloc_pointerless (ndrained, "file port");
  176. scm_take_from_input_buffers (port, drained, ndrained);
  177. }
  178. }
  179. else
  180. ndrained = 0;
  181. if (SCM_OUTPUT_PORT_P (port))
  182. scm_flush_unlocked (port);
  183. if (pt->read_buf == pt->putback_buf)
  184. {
  185. pt->read_buf = pt->saved_read_buf;
  186. pt->read_pos = pt->saved_read_pos;
  187. pt->read_end = pt->saved_read_end;
  188. pt->read_buf_size = pt->saved_read_buf_size;
  189. }
  190. if (pt->read_buf != &pt->shortbuf)
  191. scm_gc_free (pt->read_buf, pt->read_buf_size, "port buffer");
  192. if (pt->write_buf != &pt->shortbuf)
  193. scm_gc_free (pt->write_buf, pt->write_buf_size, "port buffer");
  194. scm_fport_buffer_add (port, csize, csize);
  195. if (ndrained > 0)
  196. /* Put DRAINED back to PORT. */
  197. scm_unget_bytes ((unsigned char *) drained, ndrained, 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_with_encoding
  271. Return a new port open on a given file.
  272. The mode string must match the pattern: [rwa+]** which
  273. is interpreted in the usual unix way.
  274. Unless binary mode is requested, the character encoding of the new
  275. port is determined as follows: First, if GUESS_ENCODING is true,
  276. 'file-encoding' is used to guess the encoding of the file. If
  277. GUESS_ENCODING is false or if 'file-encoding' fails, ENCODING is used
  278. unless it is also false. As a last resort, the default port encoding
  279. is used. It is an error to pass a non-false GUESS_ENCODING or
  280. ENCODING if binary mode is requested.
  281. Return the new port. */
  282. SCM
  283. scm_open_file_with_encoding (SCM filename, SCM mode,
  284. SCM guess_encoding, SCM encoding)
  285. #define FUNC_NAME "open-file"
  286. {
  287. SCM port;
  288. int fdes, flags = 0, binary = 0;
  289. unsigned int retries;
  290. char *file, *md, *ptr;
  291. if (SCM_UNLIKELY (!(scm_is_false (encoding) || scm_is_string (encoding))))
  292. scm_wrong_type_arg_msg (FUNC_NAME, 0, encoding,
  293. "encoding to be string or false");
  294. scm_dynwind_begin (0);
  295. file = scm_to_locale_string (filename);
  296. scm_dynwind_free (file);
  297. md = scm_to_locale_string (mode);
  298. scm_dynwind_free (md);
  299. switch (*md)
  300. {
  301. case 'r':
  302. flags |= O_RDONLY;
  303. break;
  304. case 'w':
  305. flags |= O_WRONLY | O_CREAT | O_TRUNC;
  306. break;
  307. case 'a':
  308. flags |= O_WRONLY | O_CREAT | O_APPEND;
  309. break;
  310. default:
  311. scm_out_of_range (FUNC_NAME, mode);
  312. }
  313. ptr = md + 1;
  314. while (*ptr != '\0')
  315. {
  316. switch (*ptr)
  317. {
  318. case '+':
  319. flags = (flags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;
  320. break;
  321. case 'b':
  322. binary = 1;
  323. #if defined (O_BINARY)
  324. flags |= O_BINARY;
  325. #endif
  326. break;
  327. case '0': /* unbuffered: handled later. */
  328. case 'l': /* line buffered: handled during output. */
  329. break;
  330. default:
  331. scm_out_of_range (FUNC_NAME, mode);
  332. }
  333. ptr++;
  334. }
  335. for (retries = 0, fdes = -1;
  336. fdes < 0 && retries < 2;
  337. retries++)
  338. {
  339. SCM_SYSCALL (fdes = open_or_open64 (file, flags, 0666));
  340. if (fdes == -1)
  341. {
  342. int en = errno;
  343. if (en == EMFILE && retries == 0)
  344. /* Run the GC in case it collects open file ports that are no
  345. longer referenced. */
  346. scm_i_gc (FUNC_NAME);
  347. else
  348. SCM_SYSERROR_MSG ("~A: ~S",
  349. scm_cons (scm_strerror (scm_from_int (en)),
  350. scm_cons (filename, SCM_EOL)), en);
  351. }
  352. }
  353. /* Create a port from this file descriptor. The port's encoding is initially
  354. %default-port-encoding. */
  355. port = scm_i_fdes_to_port (fdes, scm_i_mode_bits (mode),
  356. fport_canonicalize_filename (filename));
  357. if (binary)
  358. {
  359. if (scm_is_true (encoding))
  360. scm_misc_error (FUNC_NAME,
  361. "Encoding specified on a binary port",
  362. scm_list_1 (encoding));
  363. if (scm_is_true (guess_encoding))
  364. scm_misc_error (FUNC_NAME,
  365. "Request to guess encoding on a binary port",
  366. SCM_EOL);
  367. /* Use the binary-friendly ISO-8859-1 encoding. */
  368. scm_i_set_port_encoding_x (port, NULL);
  369. }
  370. else
  371. {
  372. char *enc = NULL;
  373. if (scm_is_true (guess_encoding))
  374. {
  375. if (SCM_INPUT_PORT_P (port))
  376. enc = scm_i_scan_for_encoding (port);
  377. else
  378. scm_misc_error (FUNC_NAME,
  379. "Request to guess encoding on an output-only port",
  380. SCM_EOL);
  381. }
  382. if (!enc && scm_is_true (encoding))
  383. {
  384. char *buf = scm_to_latin1_string (encoding);
  385. enc = scm_gc_strdup (buf, "encoding");
  386. free (buf);
  387. }
  388. if (enc)
  389. scm_i_set_port_encoding_x (port, enc);
  390. }
  391. scm_dynwind_end ();
  392. return port;
  393. }
  394. #undef FUNC_NAME
  395. SCM
  396. scm_open_file (SCM filename, SCM mode)
  397. {
  398. return scm_open_file_with_encoding (filename, mode, SCM_BOOL_F, SCM_BOOL_F);
  399. }
  400. /* We can't define these using SCM_KEYWORD, because keywords have not
  401. yet been initialized when scm_init_fports is called. */
  402. static SCM k_guess_encoding = SCM_UNDEFINED;
  403. static SCM k_encoding = SCM_UNDEFINED;
  404. SCM_INTERNAL SCM scm_i_open_file (SCM, SCM, SCM);
  405. SCM_DEFINE (scm_i_open_file, "open-file", 2, 0, 1,
  406. (SCM filename, SCM mode, SCM keyword_args),
  407. "Open the file whose name is @var{filename}, and return a port\n"
  408. "representing that file. The attributes of the port are\n"
  409. "determined by the @var{mode} string. The way in which this is\n"
  410. "interpreted is similar to C stdio. The first character must be\n"
  411. "one of the following:\n"
  412. "@table @samp\n"
  413. "@item r\n"
  414. "Open an existing file for input.\n"
  415. "@item w\n"
  416. "Open a file for output, creating it if it doesn't already exist\n"
  417. "or removing its contents if it does.\n"
  418. "@item a\n"
  419. "Open a file for output, creating it if it doesn't already\n"
  420. "exist. All writes to the port will go to the end of the file.\n"
  421. "The \"append mode\" can be turned off while the port is in use\n"
  422. "@pxref{Ports and File Descriptors, fcntl}\n"
  423. "@end table\n"
  424. "The following additional characters can be appended:\n"
  425. "@table @samp\n"
  426. "@item b\n"
  427. "Open the underlying file in binary mode, if supported by the system.\n"
  428. "Also, open the file using the binary-compatible character encoding\n"
  429. "\"ISO-8859-1\", ignoring the default port encoding.\n"
  430. "@item +\n"
  431. "Open the port for both input and output. E.g., @code{r+}: open\n"
  432. "an existing file for both input and output.\n"
  433. "@item 0\n"
  434. "Create an \"unbuffered\" port. In this case input and output\n"
  435. "operations are passed directly to the underlying port\n"
  436. "implementation without additional buffering. This is likely to\n"
  437. "slow down I/O operations. The buffering mode can be changed\n"
  438. "while a port is in use @pxref{Ports and File Descriptors,\n"
  439. "setvbuf}\n"
  440. "@item l\n"
  441. "Add line-buffering to the port. The port output buffer will be\n"
  442. "automatically flushed whenever a newline character is written.\n"
  443. "@end table\n"
  444. "In theory we could create read/write ports which were buffered\n"
  445. "in one direction only. However this isn't included in the\n"
  446. "current interfaces. If a file cannot be opened with the access\n"
  447. "requested, @code{open-file} throws an exception.")
  448. #define FUNC_NAME s_scm_i_open_file
  449. {
  450. SCM encoding = SCM_BOOL_F;
  451. SCM guess_encoding = SCM_BOOL_F;
  452. scm_c_bind_keyword_arguments (FUNC_NAME, keyword_args, 0,
  453. k_guess_encoding, &guess_encoding,
  454. k_encoding, &encoding,
  455. SCM_UNDEFINED);
  456. return scm_open_file_with_encoding (filename, mode,
  457. guess_encoding, encoding);
  458. }
  459. #undef FUNC_NAME
  460. /* Building Guile ports from a file descriptor. */
  461. /* Build a Scheme port from an open file descriptor `fdes'.
  462. MODE indicates whether FILE is open for reading or writing; it uses
  463. the same notation as open-file's second argument.
  464. NAME is a string to be used as the port's filename.
  465. */
  466. SCM
  467. scm_i_fdes_to_port (int fdes, long mode_bits, SCM name)
  468. #define FUNC_NAME "scm_fdes_to_port"
  469. {
  470. SCM port;
  471. scm_t_fport *fp;
  472. /* Test that fdes is valid. */
  473. #ifdef F_GETFL
  474. int flags = fcntl (fdes, F_GETFL, 0);
  475. if (flags == -1)
  476. SCM_SYSERROR;
  477. flags &= O_ACCMODE;
  478. if (flags != O_RDWR
  479. && ((flags != O_WRONLY && (mode_bits & SCM_WRTNG))
  480. || (flags != O_RDONLY && (mode_bits & SCM_RDNG))))
  481. {
  482. SCM_MISC_ERROR ("requested file mode not available on fdes", SCM_EOL);
  483. }
  484. #else
  485. /* If we don't have F_GETFL, as on mingw, at least we can test that
  486. it is a valid file descriptor. */
  487. struct stat st;
  488. if (fstat (fdes, &st) != 0)
  489. SCM_SYSERROR;
  490. #endif
  491. fp = (scm_t_fport *) scm_gc_malloc_pointerless (sizeof (scm_t_fport),
  492. "file port");
  493. fp->fdes = fdes;
  494. port = scm_c_make_port (scm_tc16_fport, mode_bits, (scm_t_bits)fp);
  495. SCM_PTAB_ENTRY (port)->rw_random = SCM_FDES_RANDOM_P (fdes);
  496. if (mode_bits & SCM_BUF0)
  497. scm_fport_buffer_add (port, 0, 0);
  498. else
  499. scm_fport_buffer_add (port, -1, -1);
  500. SCM_SET_FILENAME (port, name);
  501. return port;
  502. }
  503. #undef FUNC_NAME
  504. SCM
  505. scm_fdes_to_port (int fdes, char *mode, SCM name)
  506. {
  507. return scm_i_fdes_to_port (fdes, scm_mode_bits (mode), name);
  508. }
  509. /* Return a lower bound on the number of bytes available for input. */
  510. static int
  511. fport_input_waiting (SCM port)
  512. {
  513. int fdes = SCM_FSTREAM (port)->fdes;
  514. struct pollfd pollfd = { fdes, POLLIN, 0 };
  515. if (poll (&pollfd, 1, 0) < 0)
  516. scm_syserror ("fport_input_waiting");
  517. return pollfd.revents & POLLIN ? 1 : 0;
  518. }
  519. /* Revealed counts --- an oddity inherited from SCSH. */
  520. #define SCM_REVEALED(x) (SCM_FSTREAM(x)->revealed)
  521. static SCM revealed_ports = SCM_EOL;
  522. static scm_i_pthread_mutex_t revealed_lock = SCM_I_PTHREAD_MUTEX_INITIALIZER;
  523. /* Find a port in the table and return its revealed count.
  524. Also used by the garbage collector.
  525. */
  526. int
  527. scm_revealed_count (SCM port)
  528. {
  529. int ret;
  530. scm_i_pthread_mutex_lock (&revealed_lock);
  531. ret = SCM_REVEALED (port);
  532. scm_i_pthread_mutex_unlock (&revealed_lock);
  533. return ret;
  534. }
  535. SCM_DEFINE (scm_port_revealed, "port-revealed", 1, 0, 0,
  536. (SCM port),
  537. "Return the revealed count for @var{port}.")
  538. #define FUNC_NAME s_scm_port_revealed
  539. {
  540. port = SCM_COERCE_OUTPORT (port);
  541. SCM_VALIDATE_OPFPORT (1, port);
  542. return scm_from_int (scm_revealed_count (port));
  543. }
  544. #undef FUNC_NAME
  545. /* Set the revealed count for a port. */
  546. SCM_DEFINE (scm_set_port_revealed_x, "set-port-revealed!", 2, 0, 0,
  547. (SCM port, SCM rcount),
  548. "Sets the revealed count for a port to a given value.\n"
  549. "The return value is unspecified.")
  550. #define FUNC_NAME s_scm_set_port_revealed_x
  551. {
  552. int r, prev;
  553. port = SCM_COERCE_OUTPORT (port);
  554. SCM_VALIDATE_OPFPORT (1, port);
  555. r = scm_to_int (rcount);
  556. scm_i_pthread_mutex_lock (&revealed_lock);
  557. prev = SCM_REVEALED (port);
  558. SCM_REVEALED (port) = r;
  559. if (r && !prev)
  560. revealed_ports = scm_cons (port, revealed_ports);
  561. else if (prev && !r)
  562. revealed_ports = scm_delq_x (port, revealed_ports);
  563. scm_i_pthread_mutex_unlock (&revealed_lock);
  564. return SCM_UNSPECIFIED;
  565. }
  566. #undef FUNC_NAME
  567. /* Set the revealed count for a port. */
  568. SCM_DEFINE (scm_adjust_port_revealed_x, "adjust-port-revealed!", 2, 0, 0,
  569. (SCM port, SCM addend),
  570. "Add @var{addend} to the revealed count of @var{port}.\n"
  571. "The return value is unspecified.")
  572. #define FUNC_NAME s_scm_adjust_port_revealed_x
  573. {
  574. int a;
  575. port = SCM_COERCE_OUTPORT (port);
  576. SCM_VALIDATE_OPFPORT (1, port);
  577. a = scm_to_int (addend);
  578. if (!a)
  579. return SCM_UNSPECIFIED;
  580. scm_i_pthread_mutex_lock (&revealed_lock);
  581. SCM_REVEALED (port) += a;
  582. if (SCM_REVEALED (port) == a)
  583. revealed_ports = scm_cons (port, revealed_ports);
  584. else if (!SCM_REVEALED (port))
  585. revealed_ports = scm_delq_x (port, revealed_ports);
  586. scm_i_pthread_mutex_unlock (&revealed_lock);
  587. return SCM_UNSPECIFIED;
  588. }
  589. #undef FUNC_NAME
  590. static int
  591. fport_print (SCM exp, SCM port, scm_print_state *pstate SCM_UNUSED)
  592. {
  593. scm_puts_unlocked ("#<", port);
  594. scm_print_port_mode (exp, port);
  595. if (SCM_OPFPORTP (exp))
  596. {
  597. int fdes;
  598. SCM name = SCM_FILENAME (exp);
  599. if (scm_is_string (name) || scm_is_symbol (name))
  600. scm_display (name, port);
  601. else
  602. scm_puts_unlocked (SCM_PTOBNAME (SCM_PTOBNUM (exp)), port);
  603. scm_putc_unlocked (' ', port);
  604. fdes = (SCM_FSTREAM (exp))->fdes;
  605. #if (defined HAVE_TTYNAME) && (defined HAVE_POSIX)
  606. if (isatty (fdes))
  607. scm_display (scm_ttyname (exp), port);
  608. else
  609. #endif /* HAVE_TTYNAME */
  610. scm_intprint (fdes, 10, port);
  611. }
  612. else
  613. {
  614. scm_puts_unlocked (SCM_PTOBNAME (SCM_PTOBNUM (exp)), port);
  615. scm_putc_unlocked (' ', port);
  616. scm_uintprint ((scm_t_bits) SCM_PTAB_ENTRY (exp), 16, port);
  617. }
  618. scm_putc_unlocked ('>', port);
  619. return 1;
  620. }
  621. static void fport_flush (SCM port);
  622. /* fill a port's read-buffer with a single read. returns the first
  623. char or EOF if end of file. */
  624. static scm_t_wchar
  625. fport_fill_input (SCM port)
  626. {
  627. long count;
  628. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  629. scm_t_fport *fp = SCM_FSTREAM (port);
  630. SCM_SYSCALL (count = read (fp->fdes, pt->read_buf, pt->read_buf_size));
  631. if (count == -1)
  632. scm_syserror ("fport_fill_input");
  633. if (count == 0)
  634. return (scm_t_wchar) EOF;
  635. else
  636. {
  637. pt->read_pos = pt->read_buf;
  638. pt->read_end = pt->read_buf + count;
  639. return *pt->read_buf;
  640. }
  641. }
  642. static scm_t_off
  643. fport_seek (SCM port, scm_t_off offset, int whence)
  644. {
  645. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  646. scm_t_fport *fp = SCM_FSTREAM (port);
  647. off_t_or_off64_t rv;
  648. off_t_or_off64_t result;
  649. if (pt->rw_active == SCM_PORT_WRITE)
  650. {
  651. if (offset != 0 || whence != SEEK_CUR)
  652. {
  653. fport_flush (port);
  654. result = rv = lseek_or_lseek64 (fp->fdes, offset, whence);
  655. }
  656. else
  657. {
  658. /* read current position without disturbing the buffer. */
  659. rv = lseek_or_lseek64 (fp->fdes, offset, whence);
  660. result = rv + (pt->write_pos - pt->write_buf);
  661. }
  662. }
  663. else if (pt->rw_active == SCM_PORT_READ)
  664. {
  665. if (offset != 0 || whence != SEEK_CUR)
  666. {
  667. /* could expand to avoid a second seek. */
  668. scm_end_input_unlocked (port);
  669. result = rv = lseek_or_lseek64 (fp->fdes, offset, whence);
  670. }
  671. else
  672. {
  673. /* read current position without disturbing the buffer
  674. (particularly the unread-char buffer). */
  675. rv = lseek_or_lseek64 (fp->fdes, offset, whence);
  676. result = rv - (pt->read_end - pt->read_pos);
  677. if (pt->read_buf == pt->putback_buf)
  678. result -= pt->saved_read_end - pt->saved_read_pos;
  679. }
  680. }
  681. else /* SCM_PORT_NEITHER */
  682. {
  683. result = rv = lseek_or_lseek64 (fp->fdes, offset, whence);
  684. }
  685. if (rv == -1)
  686. scm_syserror ("fport_seek");
  687. return result;
  688. }
  689. static void
  690. fport_truncate (SCM port, scm_t_off length)
  691. {
  692. scm_t_fport *fp = SCM_FSTREAM (port);
  693. if (ftruncate (fp->fdes, length) == -1)
  694. scm_syserror ("ftruncate");
  695. }
  696. static void
  697. fport_write (SCM port, const void *data, size_t size)
  698. #define FUNC_NAME "fport_write"
  699. {
  700. /* this procedure tries to minimize the number of writes/flushes. */
  701. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  702. if (pt->write_buf == &pt->shortbuf
  703. || (pt->write_pos == pt->write_buf && size >= pt->write_buf_size))
  704. {
  705. /* Unbuffered port, or port with empty buffer and data won't fit in
  706. buffer. */
  707. if (full_write (SCM_FPORT_FDES (port), data, size) < size)
  708. SCM_SYSERROR;
  709. return;
  710. }
  711. {
  712. scm_t_off space = pt->write_end - pt->write_pos;
  713. if (size <= space)
  714. {
  715. /* data fits in buffer. */
  716. memcpy (pt->write_pos, data, size);
  717. pt->write_pos += size;
  718. if (pt->write_pos == pt->write_end)
  719. {
  720. fport_flush (port);
  721. /* we can skip the line-buffering check if nothing's buffered. */
  722. return;
  723. }
  724. }
  725. else
  726. {
  727. memcpy (pt->write_pos, data, space);
  728. pt->write_pos = pt->write_end;
  729. fport_flush (port);
  730. {
  731. const void *ptr = ((const char *) data) + space;
  732. size_t remaining = size - space;
  733. if (size >= pt->write_buf_size)
  734. {
  735. if (full_write (SCM_FPORT_FDES (port), ptr, remaining)
  736. < remaining)
  737. SCM_SYSERROR;
  738. return;
  739. }
  740. else
  741. {
  742. memcpy (pt->write_pos, ptr, remaining);
  743. pt->write_pos += remaining;
  744. }
  745. }
  746. }
  747. /* handle line buffering. */
  748. if ((SCM_CELL_WORD_0 (port) & SCM_BUFLINE) && memchr (data, '\n', size))
  749. fport_flush (port);
  750. }
  751. }
  752. #undef FUNC_NAME
  753. static void
  754. fport_flush (SCM port)
  755. {
  756. size_t written;
  757. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  758. scm_t_fport *fp = SCM_FSTREAM (port);
  759. size_t count = pt->write_pos - pt->write_buf;
  760. written = full_write (fp->fdes, pt->write_buf, count);
  761. if (written < count)
  762. scm_syserror ("scm_flush");
  763. pt->write_pos = pt->write_buf;
  764. pt->rw_active = SCM_PORT_NEITHER;
  765. }
  766. /* clear the read buffer and adjust the file position for unread bytes. */
  767. static void
  768. fport_end_input (SCM port, int offset)
  769. {
  770. scm_t_fport *fp = SCM_FSTREAM (port);
  771. scm_t_port *pt = SCM_PTAB_ENTRY (port);
  772. offset += pt->read_end - pt->read_pos;
  773. if (offset > 0)
  774. {
  775. pt->read_pos = pt->read_end;
  776. /* will throw error if unread-char used at beginning of file
  777. then attempting to write. seems correct. */
  778. if (lseek (fp->fdes, -offset, SEEK_CUR) == -1)
  779. scm_syserror ("fport_end_input");
  780. }
  781. pt->rw_active = SCM_PORT_NEITHER;
  782. }
  783. static void
  784. close_the_fd (void *data)
  785. {
  786. scm_t_fport *fp = data;
  787. close (fp->fdes);
  788. /* There's already one exception. That's probably enough! */
  789. errno = 0;
  790. }
  791. static int
  792. fport_close (SCM port)
  793. {
  794. scm_t_fport *fp = SCM_FSTREAM (port);
  795. int rv;
  796. scm_dynwind_begin (0);
  797. scm_dynwind_unwind_handler (close_the_fd, fp, 0);
  798. fport_flush (port);
  799. scm_dynwind_end ();
  800. scm_port_non_buffer (SCM_PTAB_ENTRY (port));
  801. rv = close (fp->fdes);
  802. if (rv)
  803. /* It's not useful to retry after EINTR, as the file descriptor is
  804. in an undefined state. See http://lwn.net/Articles/365294/.
  805. Instead just throw an error if close fails, trusting that the fd
  806. was cleaned up. */
  807. scm_syserror ("fport_close");
  808. return 0;
  809. }
  810. static size_t
  811. fport_free (SCM port)
  812. {
  813. fport_close (port);
  814. return 0;
  815. }
  816. static scm_t_bits
  817. scm_make_fptob ()
  818. {
  819. scm_t_bits tc = scm_make_port_type ("file", fport_fill_input, fport_write);
  820. scm_set_port_free (tc, fport_free);
  821. scm_set_port_print (tc, fport_print);
  822. scm_set_port_flush (tc, fport_flush);
  823. scm_set_port_end_input (tc, fport_end_input);
  824. scm_set_port_close (tc, fport_close);
  825. scm_set_port_seek (tc, fport_seek);
  826. scm_set_port_truncate (tc, fport_truncate);
  827. scm_set_port_input_waiting (tc, fport_input_waiting);
  828. return tc;
  829. }
  830. /* We can't initialize the keywords from 'scm_init_fports', because
  831. keywords haven't yet been initialized at that point. */
  832. void
  833. scm_init_fports_keywords ()
  834. {
  835. k_guess_encoding = scm_from_latin1_keyword ("guess-encoding");
  836. k_encoding = scm_from_latin1_keyword ("encoding");
  837. }
  838. void
  839. scm_init_fports ()
  840. {
  841. scm_tc16_fport = scm_make_fptob ();
  842. scm_c_define ("_IOFBF", scm_from_int (_IOFBF));
  843. scm_c_define ("_IOLBF", scm_from_int (_IOLBF));
  844. scm_c_define ("_IONBF", scm_from_int (_IONBF));
  845. sys_file_port_name_canonicalization = scm_make_fluid ();
  846. scm_c_define ("%file-port-name-canonicalization",
  847. sys_file_port_name_canonicalization);
  848. #include "libguile/fports.x"
  849. }
  850. /*
  851. Local Variables:
  852. c-file-style: "gnu"
  853. End:
  854. */