Zero-offset branches are backward branches; fix "br" backward branches
[bpt/guile.git] / libguile / fports.c
CommitLineData
073167ef 1/* Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
122f24cc
LC
2 * 2004, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013,
3 * 2014 Free Software Foundation, Inc.
073167ef 4 *
73be1d9e 5 * This library is free software; you can redistribute it and/or
53befeb7
NJ
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.
0f2d19dd 9 *
53befeb7
NJ
10 * This library is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
73be1d9e
MV
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
0f2d19dd 14 *
73be1d9e
MV
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
53befeb7
NJ
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18 * 02110-1301 USA
73be1d9e 19 */
1bbd0b84 20
1bbd0b84 21
0f2d19dd 22\f
8ab3d8a0 23#define _LARGEFILE64_SOURCE /* ask for stat64 etc */
9858e529 24#define _GNU_SOURCE /* ask for LONG_LONG_MAX/LONG_LONG_MIN */
8ab3d8a0 25
dbb605f5 26#ifdef HAVE_CONFIG_H
85286595
RB
27# include <config.h>
28#endif
0f2d19dd
JB
29
30#include <stdio.h>
cb63cf9e 31#include <fcntl.h>
95b88819
GH
32
33#ifdef HAVE_STRING_H
34#include <string.h>
35#endif
0f2d19dd
JB
36#ifdef HAVE_UNISTD_H
37#include <unistd.h>
0f2d19dd 38#endif
b8b17bfd
MV
39#ifdef HAVE_IO_H
40#include <io.h>
41#endif
f47a5239 42#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
cb63cf9e
JB
43#include <sys/stat.h>
44#endif
c7519da3 45#include <poll.h>
cb63cf9e 46#include <errno.h>
8ab3d8a0 47#include <sys/types.h>
09b204d3 48#include <sys/stat.h>
629987ed 49#include <sys/select.h>
e145dd02 50
5335850d
LC
51#include <full-write.h>
52
629987ed
AW
53#include "libguile/_scm.h"
54#include "libguile/strings.h"
55#include "libguile/validate.h"
56#include "libguile/gc.h"
57#include "libguile/posix.h"
58#include "libguile/dynwind.h"
59#include "libguile/hashtab.h"
8ab3d8a0 60
629987ed 61#include "libguile/fports.h"
122f24cc 62#include "libguile/ports-internal.h"
8ab3d8a0
KR
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
a98bddfd 76
92c2555f 77scm_t_bits scm_tc16_fport;
a98bddfd
DH
78
79
19b27fa2 80/* default buffer size, used if the O/S won't supply a value. */
1be6b49c 81static const size_t default_buffer_size = 1024;
19b27fa2 82
122f24cc
LC
83/* Create FPORT buffers with specified sizes (or -1 to use default size
84 or 0 for no buffer.) */
cb63cf9e 85static void
122f24cc 86scm_fport_buffer_add (SCM port, long read_size, long write_size)
c6c79933 87#define FUNC_NAME "scm_fport_buffer_add"
e145dd02 88{
92c2555f 89 scm_t_port *pt = SCM_PTAB_ENTRY (port);
e145dd02 90
cb63cf9e
JB
91 if (read_size == -1 || write_size == -1)
92 {
1be6b49c 93 size_t default_size;
f47a5239 94#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
cb63cf9e 95 struct stat st;
b8b17bfd 96 scm_t_fport *fp = SCM_FSTREAM (port);
cb63cf9e 97
19b27fa2
GH
98 default_size = (fstat (fp->fdes, &st) == -1) ? default_buffer_size
99 : st.st_blksize;
cb63cf9e 100#else
19b27fa2 101 default_size = default_buffer_size;
cb63cf9e
JB
102#endif
103 if (read_size == -1)
104 read_size = default_size;
105 if (write_size == -1)
106 write_size = default_size;
107 }
0f2d19dd 108
f5f2dcff 109 if (SCM_INPUT_PORT_P (port) && read_size > 0)
cb63cf9e 110 {
92d8fd32 111 pt->read_buf = scm_gc_malloc_pointerless (read_size, "port buffer");
cb63cf9e
JB
112 pt->read_pos = pt->read_end = pt->read_buf;
113 pt->read_buf_size = read_size;
114 }
115 else
116 {
840ae05d 117 pt->read_pos = pt->read_buf = pt->read_end = &pt->shortbuf;
cb63cf9e
JB
118 pt->read_buf_size = 1;
119 }
1717856b 120
f5f2dcff 121 if (SCM_OUTPUT_PORT_P (port) && write_size > 0)
cb63cf9e 122 {
92d8fd32 123 pt->write_buf = scm_gc_malloc_pointerless (write_size, "port buffer");
cb63cf9e
JB
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)
54778cd3 135 SCM_SET_CELL_WORD_0 (port, SCM_CELL_WORD_0 (port) & ~SCM_BUF0);
cb63cf9e 136 else
54778cd3 137 SCM_SET_CELL_WORD_0 (port, SCM_CELL_WORD_0 (port) | SCM_BUF0);
7a6f1ffa 138}
c6c79933 139#undef FUNC_NAME
7a6f1ffa 140
a1ec6916 141SCM_DEFINE (scm_setvbuf, "setvbuf", 2, 1, 0,
1bbd0b84 142 (SCM port, SCM mode, SCM size),
fc0d72d4
MD
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"
122f24cc
LC
152 "@end table\n\n"
153 "Only certain types of ports are supported, most importantly\n"
154 "file ports.")
1bbd0b84 155#define FUNC_NAME s_scm_setvbuf
7a6f1ffa 156{
1be6b49c 157 int cmode;
c014a02e 158 long csize;
e8b21eec
LC
159 size_t ndrained;
160 char *drained;
92c2555f 161 scm_t_port *pt;
e140d85d 162 scm_t_ptob_descriptor *ptob;
7a6f1ffa 163
78446828
MV
164 port = SCM_COERCE_OUTPORT (port);
165
122f24cc 166 SCM_VALIDATE_OPENPORT (1, port);
e140d85d 167 ptob = SCM_PORT_DESCRIPTOR (port);
122f24cc 168
e140d85d 169 if (ptob->setvbuf == NULL)
122f24cc
LC
170 scm_wrong_type_arg_msg (FUNC_NAME, 1, port,
171 "port that supports 'setvbuf'");
172
a55c2b68 173 cmode = scm_to_int (mode);
d3639214 174 if (cmode != _IONBF && cmode != _IOFBF && cmode != _IOLBF)
1bbd0b84 175 scm_out_of_range (FUNC_NAME, mode);
d3639214
GH
176
177 if (cmode == _IOLBF)
178 {
54778cd3 179 SCM_SET_CELL_WORD_0 (port, SCM_CELL_WORD_0 (port) | SCM_BUFLINE);
d3639214
GH
180 cmode = _IOFBF;
181 }
182 else
122f24cc
LC
183 SCM_SET_CELL_WORD_0 (port,
184 SCM_CELL_WORD_0 (port) & ~(scm_t_bits) SCM_BUFLINE);
d3639214 185
7a6f1ffa 186 if (SCM_UNBNDP (size))
cb63cf9e
JB
187 {
188 if (cmode == _IOFBF)
189 csize = -1;
190 else
191 csize = 0;
192 }
7a6f1ffa
GH
193 else
194 {
a55c2b68 195 csize = scm_to_int (size);
cb63cf9e 196 if (csize < 0 || (cmode == _IONBF && csize > 0))
1bbd0b84 197 scm_out_of_range (FUNC_NAME, size);
7a6f1ffa 198 }
d3639214 199
cb63cf9e 200 pt = SCM_PTAB_ENTRY (port);
7a6f1ffa 201
67a72dc1 202 if (SCM_INPUT_PORT_P (port))
e8b21eec
LC
203 {
204 /* Drain pending input from PORT. Don't use `scm_drain_input' since
205 it returns a string, whereas we want binary input here. */
206 ndrained = pt->read_end - pt->read_pos;
207 if (pt->read_buf == pt->putback_buf)
208 ndrained += pt->saved_read_end - pt->saved_read_pos;
209
210 if (ndrained > 0)
211 {
212 drained = scm_gc_malloc_pointerless (ndrained, "file port");
213 scm_take_from_input_buffers (port, drained, ndrained);
214 }
215 }
67a72dc1 216 else
e8b21eec 217 ndrained = 0;
67a72dc1
AW
218
219 if (SCM_OUTPUT_PORT_P (port))
4251ae2e 220 scm_flush_unlocked (port);
67a72dc1 221
4c9419ac
MV
222 if (pt->read_buf == pt->putback_buf)
223 {
224 pt->read_buf = pt->saved_read_buf;
225 pt->read_pos = pt->saved_read_pos;
226 pt->read_end = pt->saved_read_end;
227 pt->read_buf_size = pt->saved_read_buf_size;
228 }
7a6f1ffa 229
e140d85d 230 ptob->setvbuf (port, csize, csize);
67a72dc1 231
e8b21eec
LC
232 if (ndrained > 0)
233 /* Put DRAINED back to PORT. */
7f6c3f8f 234 scm_unget_bytes ((unsigned char *) drained, ndrained, port);
67a72dc1 235
cb63cf9e 236 return SCM_UNSPECIFIED;
0f2d19dd 237}
1bbd0b84 238#undef FUNC_NAME
0f2d19dd 239
eadd48de 240/* Move ports with the specified file descriptor to new descriptors,
387d418c 241 * resetting the revealed count to 0.
0f2d19dd 242 */
ee834df4
LC
243static void
244scm_i_evict_port (void *closure, SCM port)
0f2d19dd 245{
5dbc6c06 246 int fd = * (int*) closure;
0f2d19dd 247
5dbc6c06 248 if (SCM_FPORTP (port))
eadd48de 249 {
e9d8bc25
LC
250 scm_t_port *p;
251 scm_t_fport *fp;
252
253 /* XXX: In some cases, we can encounter a port with no associated ptab
254 entry. */
255 p = SCM_PTAB_ENTRY (port);
256 fp = (p != NULL) ? (scm_t_fport *) p->stream : NULL;
cb63cf9e 257
e9d8bc25 258 if ((fp != NULL) && (fp->fdes == fd))
eadd48de 259 {
5dbc6c06
HWN
260 fp->fdes = dup (fd);
261 if (fp->fdes == -1)
262 scm_syserror ("scm_evict_ports");
263 scm_set_port_revealed_x (port, scm_from_int (0));
eadd48de
GH
264 }
265 }
5dbc6c06
HWN
266}
267
268void
269scm_evict_ports (int fd)
270{
ee834df4 271 scm_c_port_for_each (scm_i_evict_port, (void *) &fd);
eadd48de 272}
0f2d19dd 273
efa40607
DH
274
275SCM_DEFINE (scm_file_port_p, "file-port?", 1, 0, 0,
276 (SCM obj),
2069af38 277 "Determine whether @var{obj} is a port that is related to a file.")
efa40607
DH
278#define FUNC_NAME s_scm_file_port_p
279{
7888309b 280 return scm_from_bool (SCM_FPORTP (obj));
efa40607
DH
281}
282#undef FUNC_NAME
283
284
69cac238 285static SCM sys_file_port_name_canonicalization;
0157a341
AW
286SCM_SYMBOL (sym_relative, "relative");
287SCM_SYMBOL (sym_absolute, "absolute");
288
289static SCM
290fport_canonicalize_filename (SCM filename)
291{
69cac238
AW
292 SCM mode = scm_fluid_ref (sys_file_port_name_canonicalization);
293
0157a341
AW
294 if (!scm_is_string (filename))
295 {
296 return filename;
297 }
69cac238 298 else if (scm_is_eq (mode, sym_relative))
0157a341 299 {
22457d57
AW
300 SCM path, rel;
301
302 path = scm_variable_ref (scm_c_module_lookup (scm_the_root_module (),
303 "%load-path"));
304 rel = scm_i_relativize_path (filename, path);
305
306 return scm_is_true (rel) ? rel : filename;
0157a341 307 }
69cac238 308 else if (scm_is_eq (mode, sym_absolute))
0157a341
AW
309 {
310 char *str, *canon;
311
312 str = scm_to_locale_string (filename);
313 canon = canonicalize_file_name (str);
314 free (str);
315
316 return canon ? scm_take_locale_string (canon) : filename;
317 }
318 else
319 {
320 return filename;
321 }
322}
323
3ace9a8e
MW
324/* scm_open_file_with_encoding
325 Return a new port open on a given file.
0157a341 326
3ace9a8e
MW
327 The mode string must match the pattern: [rwa+]** which
328 is interpreted in the usual unix way.
329
330 Unless binary mode is requested, the character encoding of the new
331 port is determined as follows: First, if GUESS_ENCODING is true,
332 'file-encoding' is used to guess the encoding of the file. If
333 GUESS_ENCODING is false or if 'file-encoding' fails, ENCODING is used
334 unless it is also false. As a last resort, the default port encoding
335 is used. It is an error to pass a non-false GUESS_ENCODING or
336 ENCODING if binary mode is requested.
337
338 Return the new port. */
339SCM
340scm_open_file_with_encoding (SCM filename, SCM mode,
341 SCM guess_encoding, SCM encoding)
342#define FUNC_NAME "open-file"
0f2d19dd 343{
19639113 344 SCM port;
9a334eb3 345 int fdes, flags = 0, binary = 0;
64e3a89c
LC
346 unsigned int retries;
347 char *file, *md, *ptr;
19639113 348
3ace9a8e
MW
349 if (SCM_UNLIKELY (!(scm_is_false (encoding) || scm_is_string (encoding))))
350 scm_wrong_type_arg_msg (FUNC_NAME, 0, encoding,
351 "encoding to be string or false");
352
661ae7ab 353 scm_dynwind_begin (0);
19639113 354
7f9994d9 355 file = scm_to_locale_string (filename);
661ae7ab 356 scm_dynwind_free (file);
7f9994d9
MV
357
358 md = scm_to_locale_string (mode);
661ae7ab 359 scm_dynwind_free (md);
19639113 360
1e6808ea 361 switch (*md)
0f2d19dd 362 {
cb63cf9e
JB
363 case 'r':
364 flags |= O_RDONLY;
365 break;
366 case 'w':
367 flags |= O_WRONLY | O_CREAT | O_TRUNC;
368 break;
369 case 'a':
370 flags |= O_WRONLY | O_CREAT | O_APPEND;
371 break;
372 default:
1e6808ea 373 scm_out_of_range (FUNC_NAME, mode);
0f2d19dd 374 }
1e6808ea 375 ptr = md + 1;
cb63cf9e 376 while (*ptr != '\0')
e145dd02 377 {
cb63cf9e
JB
378 switch (*ptr)
379 {
380 case '+':
381 flags = (flags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;
382 break;
9f561420 383 case 'b':
9a334eb3 384 binary = 1;
9f561420
GH
385#if defined (O_BINARY)
386 flags |= O_BINARY;
387#endif
388 break;
cb63cf9e 389 case '0': /* unbuffered: handled later. */
d3639214 390 case 'l': /* line buffered: handled during output. */
cb63cf9e
JB
391 break;
392 default:
1e6808ea 393 scm_out_of_range (FUNC_NAME, mode);
cb63cf9e
JB
394 }
395 ptr++;
e145dd02 396 }
cb63cf9e 397
64e3a89c
LC
398 for (retries = 0, fdes = -1;
399 fdes < 0 && retries < 2;
400 retries++)
401 {
402 SCM_SYSCALL (fdes = open_or_open64 (file, flags, 0666));
403 if (fdes == -1)
404 {
405 int en = errno;
406
407 if (en == EMFILE && retries == 0)
408 /* Run the GC in case it collects open file ports that are no
409 longer referenced. */
410 scm_i_gc (FUNC_NAME);
411 else
412 SCM_SYSERROR_MSG ("~A: ~S",
413 scm_cons (scm_strerror (scm_from_int (en)),
414 scm_cons (filename, SCM_EOL)), en);
415 }
0f2d19dd 416 }
64e3a89c 417
211683cc
MG
418 /* Create a port from this file descriptor. The port's encoding is initially
419 %default-port-encoding. */
0157a341
AW
420 port = scm_i_fdes_to_port (fdes, scm_i_mode_bits (mode),
421 fport_canonicalize_filename (filename));
7f9994d9 422
9a334eb3 423 if (binary)
211683cc 424 {
3ace9a8e
MW
425 if (scm_is_true (encoding))
426 scm_misc_error (FUNC_NAME,
427 "Encoding specified on a binary port",
428 scm_list_1 (encoding));
429 if (scm_is_true (guess_encoding))
430 scm_misc_error (FUNC_NAME,
431 "Request to guess encoding on a binary port",
432 SCM_EOL);
433
434 /* Use the binary-friendly ISO-8859-1 encoding. */
435 scm_i_set_port_encoding_x (port, NULL);
211683cc
MG
436 }
437 else
3ace9a8e
MW
438 {
439 char *enc = NULL;
440
441 if (scm_is_true (guess_encoding))
442 {
443 if (SCM_INPUT_PORT_P (port))
444 enc = scm_i_scan_for_encoding (port);
445 else
446 scm_misc_error (FUNC_NAME,
447 "Request to guess encoding on an output-only port",
448 SCM_EOL);
449 }
450
451 if (!enc && scm_is_true (encoding))
452 {
453 char *buf = scm_to_latin1_string (encoding);
454 enc = scm_gc_strdup (buf, "encoding");
455 free (buf);
456 }
457
458 if (enc)
459 scm_i_set_port_encoding_x (port, enc);
460 }
211683cc 461
661ae7ab 462 scm_dynwind_end ();
7f9994d9 463
0f2d19dd
JB
464 return port;
465}
1bbd0b84 466#undef FUNC_NAME
0f2d19dd 467
3ace9a8e
MW
468SCM
469scm_open_file (SCM filename, SCM mode)
470{
471 return scm_open_file_with_encoding (filename, mode, SCM_BOOL_F, SCM_BOOL_F);
472}
473
474/* We can't define these using SCM_KEYWORD, because keywords have not
475 yet been initialized when scm_init_fports is called. */
476static SCM k_guess_encoding = SCM_UNDEFINED;
477static SCM k_encoding = SCM_UNDEFINED;
478
6a9d9e3a
AW
479SCM_INTERNAL SCM scm_i_open_file (SCM, SCM, SCM);
480
3ace9a8e
MW
481SCM_DEFINE (scm_i_open_file, "open-file", 2, 0, 1,
482 (SCM filename, SCM mode, SCM keyword_args),
483 "Open the file whose name is @var{filename}, and return a port\n"
484 "representing that file. The attributes of the port are\n"
485 "determined by the @var{mode} string. The way in which this is\n"
486 "interpreted is similar to C stdio. The first character must be\n"
487 "one of the following:\n"
488 "@table @samp\n"
489 "@item r\n"
490 "Open an existing file for input.\n"
491 "@item w\n"
492 "Open a file for output, creating it if it doesn't already exist\n"
493 "or removing its contents if it does.\n"
494 "@item a\n"
495 "Open a file for output, creating it if it doesn't already\n"
496 "exist. All writes to the port will go to the end of the file.\n"
497 "The \"append mode\" can be turned off while the port is in use\n"
498 "@pxref{Ports and File Descriptors, fcntl}\n"
499 "@end table\n"
500 "The following additional characters can be appended:\n"
501 "@table @samp\n"
502 "@item b\n"
503 "Open the underlying file in binary mode, if supported by the system.\n"
504 "Also, open the file using the binary-compatible character encoding\n"
505 "\"ISO-8859-1\", ignoring the default port encoding.\n"
506 "@item +\n"
507 "Open the port for both input and output. E.g., @code{r+}: open\n"
508 "an existing file for both input and output.\n"
509 "@item 0\n"
510 "Create an \"unbuffered\" port. In this case input and output\n"
511 "operations are passed directly to the underlying port\n"
512 "implementation without additional buffering. This is likely to\n"
513 "slow down I/O operations. The buffering mode can be changed\n"
514 "while a port is in use @pxref{Ports and File Descriptors,\n"
515 "setvbuf}\n"
516 "@item l\n"
517 "Add line-buffering to the port. The port output buffer will be\n"
518 "automatically flushed whenever a newline character is written.\n"
519 "@end table\n"
520 "In theory we could create read/write ports which were buffered\n"
521 "in one direction only. However this isn't included in the\n"
522 "current interfaces. If a file cannot be opened with the access\n"
523 "requested, @code{open-file} throws an exception.")
524#define FUNC_NAME s_scm_i_open_file
525{
526 SCM encoding = SCM_BOOL_F;
527 SCM guess_encoding = SCM_BOOL_F;
528
529 scm_c_bind_keyword_arguments (FUNC_NAME, keyword_args, 0,
530 k_guess_encoding, &guess_encoding,
531 k_encoding, &encoding,
532 SCM_UNDEFINED);
533
534 return scm_open_file_with_encoding (filename, mode,
535 guess_encoding, encoding);
536}
537#undef FUNC_NAME
538
e145dd02 539\f
cb63cf9e 540/* Building Guile ports from a file descriptor. */
e145dd02 541
cb63cf9e 542/* Build a Scheme port from an open file descriptor `fdes'.
a089567e
JB
543 MODE indicates whether FILE is open for reading or writing; it uses
544 the same notation as open-file's second argument.
19b27fa2
GH
545 NAME is a string to be used as the port's filename.
546*/
a089567e 547SCM
d617ee18 548scm_i_fdes_to_port (int fdes, long mode_bits, SCM name)
19b27fa2 549#define FUNC_NAME "scm_fdes_to_port"
a089567e 550{
a089567e 551 SCM port;
2721f918 552 scm_t_fport *fp;
19b27fa2 553
09b204d3
AW
554 /* Test that fdes is valid. */
555#ifdef F_GETFL
556 int flags = fcntl (fdes, F_GETFL, 0);
19b27fa2
GH
557 if (flags == -1)
558 SCM_SYSERROR;
559 flags &= O_ACCMODE;
560 if (flags != O_RDWR
561 && ((flags != O_WRONLY && (mode_bits & SCM_WRTNG))
562 || (flags != O_RDONLY && (mode_bits & SCM_RDNG))))
563 {
564 SCM_MISC_ERROR ("requested file mode not available on fdes", SCM_EOL);
565 }
09b204d3
AW
566#else
567 /* If we don't have F_GETFL, as on mingw, at least we can test that
568 it is a valid file descriptor. */
569 struct stat st;
570 if (fstat (fdes, &st) != 0)
571 SCM_SYSERROR;
572#endif
a089567e 573
2721f918
AW
574 fp = (scm_t_fport *) scm_gc_malloc_pointerless (sizeof (scm_t_fport),
575 "file port");
576 fp->fdes = fdes;
577
578 port = scm_c_make_port (scm_tc16_fport, mode_bits, (scm_t_bits)fp);
579
580 SCM_PTAB_ENTRY (port)->rw_random = SCM_FDES_RANDOM_P (fdes);
581
582 if (mode_bits & SCM_BUF0)
583 scm_fport_buffer_add (port, 0, 0);
584 else
585 scm_fport_buffer_add (port, -1, -1);
586
b24b5e13 587 SCM_SET_FILENAME (port, name);
2721f918 588
e145dd02
JB
589 return port;
590}
19b27fa2 591#undef FUNC_NAME
e145dd02 592
d617ee18
MV
593SCM
594scm_fdes_to_port (int fdes, char *mode, SCM name)
595{
596 return scm_i_fdes_to_port (fdes, scm_mode_bits (mode), name);
597}
598
affc96b5 599/* Return a lower bound on the number of bytes available for input. */
cb63cf9e 600static int
affc96b5 601fport_input_waiting (SCM port)
e145dd02 602{
23f2b9a3 603 int fdes = SCM_FSTREAM (port)->fdes;
c7519da3 604
c7519da3
CC
605 struct pollfd pollfd = { fdes, POLLIN, 0 };
606
607 if (poll (&pollfd, 1, 0) < 0)
608 scm_syserror ("fport_input_waiting");
609
610 return pollfd.revents & POLLIN ? 1 : 0;
a089567e
JB
611}
612
3753e227
AW
613
614\f
615
616/* Revealed counts --- an oddity inherited from SCSH. */
617
618#define SCM_REVEALED(x) (SCM_FSTREAM(x)->revealed)
619
620static SCM revealed_ports = SCM_EOL;
621static scm_i_pthread_mutex_t revealed_lock = SCM_I_PTHREAD_MUTEX_INITIALIZER;
3753e227
AW
622
623/* Find a port in the table and return its revealed count.
624 Also used by the garbage collector.
625 */
626int
627scm_revealed_count (SCM port)
628{
629 int ret;
630
631 scm_i_pthread_mutex_lock (&revealed_lock);
632 ret = SCM_REVEALED (port);
633 scm_i_pthread_mutex_unlock (&revealed_lock);
634
635 return ret;
636}
637
638SCM_DEFINE (scm_port_revealed, "port-revealed", 1, 0, 0,
639 (SCM port),
640 "Return the revealed count for @var{port}.")
641#define FUNC_NAME s_scm_port_revealed
642{
643 port = SCM_COERCE_OUTPORT (port);
644 SCM_VALIDATE_OPFPORT (1, port);
645 return scm_from_int (scm_revealed_count (port));
646}
647#undef FUNC_NAME
648
649/* Set the revealed count for a port. */
650SCM_DEFINE (scm_set_port_revealed_x, "set-port-revealed!", 2, 0, 0,
651 (SCM port, SCM rcount),
652 "Sets the revealed count for a port to a given value.\n"
653 "The return value is unspecified.")
654#define FUNC_NAME s_scm_set_port_revealed_x
655{
656 int r, prev;
657
658 port = SCM_COERCE_OUTPORT (port);
659 SCM_VALIDATE_OPFPORT (1, port);
660
661 r = scm_to_int (rcount);
662
663 scm_i_pthread_mutex_lock (&revealed_lock);
664
665 prev = SCM_REVEALED (port);
666 SCM_REVEALED (port) = r;
667
668 if (r && !prev)
669 revealed_ports = scm_cons (port, revealed_ports);
670 else if (prev && !r)
671 revealed_ports = scm_delq_x (port, revealed_ports);
672
673 scm_i_pthread_mutex_unlock (&revealed_lock);
674
675 return SCM_UNSPECIFIED;
676}
677#undef FUNC_NAME
678
679/* Set the revealed count for a port. */
680SCM_DEFINE (scm_adjust_port_revealed_x, "adjust-port-revealed!", 2, 0, 0,
681 (SCM port, SCM addend),
682 "Add @var{addend} to the revealed count of @var{port}.\n"
683 "The return value is unspecified.")
684#define FUNC_NAME s_scm_adjust_port_revealed_x
685{
686 int a;
687
688 port = SCM_COERCE_OUTPORT (port);
689 SCM_VALIDATE_OPFPORT (1, port);
690
691 a = scm_to_int (addend);
692 if (!a)
693 return SCM_UNSPECIFIED;
694
695 scm_i_pthread_mutex_lock (&revealed_lock);
696
697 SCM_REVEALED (port) += a;
698 if (SCM_REVEALED (port) == a)
699 revealed_ports = scm_cons (port, revealed_ports);
700 else if (!SCM_REVEALED (port))
701 revealed_ports = scm_delq_x (port, revealed_ports);
702
703 scm_i_pthread_mutex_unlock (&revealed_lock);
704
705 return SCM_UNSPECIFIED;
706}
707#undef FUNC_NAME
708
709
cb63cf9e 710\f
0f2d19dd 711static int
e81d98ec 712fport_print (SCM exp, SCM port, scm_print_state *pstate SCM_UNUSED)
0f2d19dd 713{
0607ebbf 714 scm_puts_unlocked ("#<", port);
b3ec3c64
MD
715 scm_print_port_mode (exp, port);
716 if (SCM_OPFPORTP (exp))
0f2d19dd 717 {
b3ec3c64 718 int fdes;
b24b5e13 719 SCM name = SCM_FILENAME (exp);
cc95e00a 720 if (scm_is_string (name) || scm_is_symbol (name))
b24b5e13
DH
721 scm_display (name, port);
722 else
0607ebbf
AW
723 scm_puts_unlocked (SCM_PTOBNAME (SCM_PTOBNUM (exp)), port);
724 scm_putc_unlocked (' ', port);
b3ec3c64 725 fdes = (SCM_FSTREAM (exp))->fdes;
073167ef
LC
726
727#if (defined HAVE_TTYNAME) && (defined HAVE_POSIX)
b3ec3c64 728 if (isatty (fdes))
eb372585 729 scm_display (scm_ttyname (exp), port);
b3ec3c64 730 else
82893676 731#endif /* HAVE_TTYNAME */
b3ec3c64 732 scm_intprint (fdes, 10, port);
0f2d19dd
JB
733 }
734 else
735 {
0607ebbf
AW
736 scm_puts_unlocked (SCM_PTOBNAME (SCM_PTOBNUM (exp)), port);
737 scm_putc_unlocked (' ', port);
0345e278 738 scm_uintprint ((scm_t_bits) SCM_PTAB_ENTRY (exp), 16, port);
0f2d19dd 739 }
0607ebbf 740 scm_putc_unlocked ('>', port);
b3ec3c64 741 return 1;
0f2d19dd
JB
742}
743
affc96b5 744static void fport_flush (SCM port);
0f2d19dd 745
c2da2648
GH
746/* fill a port's read-buffer with a single read. returns the first
747 char or EOF if end of file. */
889975e5 748static scm_t_wchar
affc96b5 749fport_fill_input (SCM port)
0f2d19dd 750{
c014a02e 751 long count;
92c2555f
MV
752 scm_t_port *pt = SCM_PTAB_ENTRY (port);
753 scm_t_fport *fp = SCM_FSTREAM (port);
cb63cf9e 754
cb63cf9e
JB
755 SCM_SYSCALL (count = read (fp->fdes, pt->read_buf, pt->read_buf_size));
756 if (count == -1)
affc96b5 757 scm_syserror ("fport_fill_input");
cb63cf9e 758 if (count == 0)
889975e5 759 return (scm_t_wchar) EOF;
cb63cf9e
JB
760 else
761 {
5c070ca7 762 pt->read_pos = pt->read_buf;
cb63cf9e 763 pt->read_end = pt->read_buf + count;
5c070ca7 764 return *pt->read_buf;
cb63cf9e 765 }
0f2d19dd
JB
766}
767
0a94eb00
LC
768static scm_t_off
769fport_seek (SCM port, scm_t_off offset, int whence)
0f2d19dd 770{
92c2555f
MV
771 scm_t_port *pt = SCM_PTAB_ENTRY (port);
772 scm_t_fport *fp = SCM_FSTREAM (port);
8ab3d8a0
KR
773 off_t_or_off64_t rv;
774 off_t_or_off64_t result;
7dcb364d
GH
775
776 if (pt->rw_active == SCM_PORT_WRITE)
777 {
778 if (offset != 0 || whence != SEEK_CUR)
779 {
780 fport_flush (port);
8ab3d8a0 781 result = rv = lseek_or_lseek64 (fp->fdes, offset, whence);
7dcb364d
GH
782 }
783 else
784 {
785 /* read current position without disturbing the buffer. */
8ab3d8a0 786 rv = lseek_or_lseek64 (fp->fdes, offset, whence);
7dcb364d
GH
787 result = rv + (pt->write_pos - pt->write_buf);
788 }
789 }
790 else if (pt->rw_active == SCM_PORT_READ)
791 {
792 if (offset != 0 || whence != SEEK_CUR)
793 {
794 /* could expand to avoid a second seek. */
4251ae2e 795 scm_end_input_unlocked (port);
8ab3d8a0 796 result = rv = lseek_or_lseek64 (fp->fdes, offset, whence);
7dcb364d
GH
797 }
798 else
799 {
800 /* read current position without disturbing the buffer
801 (particularly the unread-char buffer). */
8ab3d8a0 802 rv = lseek_or_lseek64 (fp->fdes, offset, whence);
7dcb364d
GH
803 result = rv - (pt->read_end - pt->read_pos);
804
805 if (pt->read_buf == pt->putback_buf)
806 result -= pt->saved_read_end - pt->saved_read_pos;
807 }
808 }
809 else /* SCM_PORT_NEITHER */
810 {
8ab3d8a0 811 result = rv = lseek_or_lseek64 (fp->fdes, offset, whence);
7dcb364d 812 }
cb8dfa3f 813
7dcb364d 814 if (rv == -1)
affc96b5 815 scm_syserror ("fport_seek");
7dcb364d 816
cb8dfa3f 817 return result;
0f2d19dd
JB
818}
819
840ae05d 820static void
f1ce9199 821fport_truncate (SCM port, scm_t_off length)
840ae05d 822{
92c2555f 823 scm_t_fport *fp = SCM_FSTREAM (port);
840ae05d
JB
824
825 if (ftruncate (fp->fdes, length) == -1)
826 scm_syserror ("ftruncate");
827}
828
31703ab8 829static void
8aa011a1 830fport_write (SCM port, const void *data, size_t size)
daa4a3f1 831#define FUNC_NAME "fport_write"
31703ab8 832{
0c6d2191 833 /* this procedure tries to minimize the number of writes/flushes. */
92c2555f 834 scm_t_port *pt = SCM_PTAB_ENTRY (port);
31703ab8 835
0c6d2191
GH
836 if (pt->write_buf == &pt->shortbuf
837 || (pt->write_pos == pt->write_buf && size >= pt->write_buf_size))
31703ab8 838 {
daa4a3f1
LC
839 /* Unbuffered port, or port with empty buffer and data won't fit in
840 buffer. */
841 if (full_write (SCM_FPORT_FDES (port), data, size) < size)
842 SCM_SYSERROR;
843
0c6d2191 844 return;
31703ab8 845 }
d3639214 846
0c6d2191 847 {
f1ce9199 848 scm_t_off space = pt->write_end - pt->write_pos;
0c6d2191
GH
849
850 if (size <= space)
851 {
852 /* data fits in buffer. */
853 memcpy (pt->write_pos, data, size);
854 pt->write_pos += size;
855 if (pt->write_pos == pt->write_end)
856 {
affc96b5 857 fport_flush (port);
0c6d2191
GH
858 /* we can skip the line-buffering check if nothing's buffered. */
859 return;
860 }
861 }
862 else
863 {
864 memcpy (pt->write_pos, data, space);
865 pt->write_pos = pt->write_end;
866 fport_flush (port);
867 {
868 const void *ptr = ((const char *) data) + space;
869 size_t remaining = size - space;
870
871 if (size >= pt->write_buf_size)
872 {
daa4a3f1
LC
873 if (full_write (SCM_FPORT_FDES (port), ptr, remaining)
874 < remaining)
875 SCM_SYSERROR;
0c6d2191
GH
876 return;
877 }
878 else
879 {
880 memcpy (pt->write_pos, ptr, remaining);
881 pt->write_pos += remaining;
882 }
31703ab8 883 }
0c6d2191 884 }
31703ab8 885
0c6d2191
GH
886 /* handle line buffering. */
887 if ((SCM_CELL_WORD_0 (port) & SCM_BUFLINE) && memchr (data, '\n', size))
888 fport_flush (port);
889 }
31703ab8 890}
daa4a3f1 891#undef FUNC_NAME
31703ab8 892
cb63cf9e 893static void
affc96b5 894fport_flush (SCM port)
0f2d19dd 895{
5335850d 896 size_t written;
92c2555f
MV
897 scm_t_port *pt = SCM_PTAB_ENTRY (port);
898 scm_t_fport *fp = SCM_FSTREAM (port);
5335850d 899 size_t count = pt->write_pos - pt->write_buf;
cb63cf9e 900
5335850d
LC
901 written = full_write (fp->fdes, pt->write_buf, count);
902 if (written < count)
903 scm_syserror ("scm_flush");
cb63cf9e 904
cb63cf9e 905 pt->write_pos = pt->write_buf;
61e452ba 906 pt->rw_active = SCM_PORT_NEITHER;
840ae05d
JB
907}
908
283a1a0e 909/* clear the read buffer and adjust the file position for unread bytes. */
840ae05d 910static void
affc96b5 911fport_end_input (SCM port, int offset)
840ae05d 912{
92c2555f
MV
913 scm_t_fport *fp = SCM_FSTREAM (port);
914 scm_t_port *pt = SCM_PTAB_ENTRY (port);
283a1a0e
GH
915
916 offset += pt->read_end - pt->read_pos;
840ae05d 917
840ae05d
JB
918 if (offset > 0)
919 {
920 pt->read_pos = pt->read_end;
921 /* will throw error if unread-char used at beginning of file
922 then attempting to write. seems correct. */
923 if (lseek (fp->fdes, -offset, SEEK_CUR) == -1)
affc96b5 924 scm_syserror ("fport_end_input");
840ae05d 925 }
61e452ba 926 pt->rw_active = SCM_PORT_NEITHER;
8f29fbd0
JB
927}
928
5a771d5f
AW
929static void
930close_the_fd (void *data)
931{
932 scm_t_fport *fp = data;
933
934 close (fp->fdes);
935 /* There's already one exception. That's probably enough! */
936 errno = 0;
937}
938
6a2c4c81 939static int
affc96b5 940fport_close (SCM port)
6a2c4c81 941{
92c2555f 942 scm_t_fport *fp = SCM_FSTREAM (port);
cb63cf9e 943 int rv;
840ae05d 944
5a771d5f
AW
945 scm_dynwind_begin (0);
946 scm_dynwind_unwind_handler (close_the_fd, fp, 0);
affc96b5 947 fport_flush (port);
5a771d5f
AW
948 scm_dynwind_end ();
949
950 scm_port_non_buffer (SCM_PTAB_ENTRY (port));
951
952 rv = close (fp->fdes);
953 if (rv)
954 /* It's not useful to retry after EINTR, as the file descriptor is
955 in an undefined state. See http://lwn.net/Articles/365294/.
956 Instead just throw an error if close fails, trusting that the fd
957 was cleaned up. */
958 scm_syserror ("fport_close");
959
960 return 0;
6a2c4c81
JB
961}
962
1be6b49c 963static size_t
affc96b5 964fport_free (SCM port)
b3ec3c64 965{
affc96b5 966 fport_close (port);
b3ec3c64
MD
967 return 0;
968}
969
92c2555f 970static scm_t_bits
b3ec3c64
MD
971scm_make_fptob ()
972{
92c2555f 973 scm_t_bits tc = scm_make_port_type ("file", fport_fill_input, fport_write);
a98bddfd 974
affc96b5 975 scm_set_port_free (tc, fport_free);
e841c3e0 976 scm_set_port_print (tc, fport_print);
affc96b5
GH
977 scm_set_port_flush (tc, fport_flush);
978 scm_set_port_end_input (tc, fport_end_input);
979 scm_set_port_close (tc, fport_close);
980 scm_set_port_seek (tc, fport_seek);
981 scm_set_port_truncate (tc, fport_truncate);
982 scm_set_port_input_waiting (tc, fport_input_waiting);
e140d85d 983 scm_set_port_setvbuf (tc, scm_fport_buffer_add);
a98bddfd
DH
984
985 return tc;
b3ec3c64 986}
0f2d19dd 987
3ace9a8e
MW
988/* We can't initialize the keywords from 'scm_init_fports', because
989 keywords haven't yet been initialized at that point. */
990void
991scm_init_fports_keywords ()
992{
993 k_guess_encoding = scm_from_latin1_keyword ("guess-encoding");
994 k_encoding = scm_from_latin1_keyword ("encoding");
995}
996
0f2d19dd
JB
997void
998scm_init_fports ()
0f2d19dd 999{
a98bddfd
DH
1000 scm_tc16_fport = scm_make_fptob ();
1001
e11e83f3
MV
1002 scm_c_define ("_IOFBF", scm_from_int (_IOFBF));
1003 scm_c_define ("_IOLBF", scm_from_int (_IOLBF));
1004 scm_c_define ("_IONBF", scm_from_int (_IONBF));
a98bddfd 1005
69cac238
AW
1006 sys_file_port_name_canonicalization = scm_make_fluid ();
1007 scm_c_define ("%file-port-name-canonicalization",
1008 sys_file_port_name_canonicalization);
1009
a98bddfd 1010#include "libguile/fports.x"
0f2d19dd 1011}
89e00824
ML
1012
1013/*
1014 Local Variables:
1015 c-file-style: "gnu"
1016 End:
1017*/