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