fports.c 27 KB

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