Debian Codegraph @

src/c/streams/strm_os.d

raw
1 /* -*- Mode: C; c-basic-offset: 2; indent-tabs-mode: nil -*- */
2 /* vim: set filetype=c tabstop=2 shiftwidth=2 expandtab: */
3
4 /*
5 * strm_os.d - Operating System Stream dispatch tables
6 *
7 * Copyright (c) 1984 Taiichi Yuasa and Masami Hagiya
8 * Copyright (c) 1990 Giuseppe Attardi
9 * Copyright (c) 2001 Juan Jose Garcia Ripoll
10 * Copyright (c) 2025 Daniel Kochmanski
11 *
12 * See file 'LICENSE' for the copyright details.
13 *
14 */
15
16 /*
17 IMPLEMENTATION-DEPENDENT
18
19 The file contains code to reclaim the I/O buffer
20 by accessing the FILE structure of C.
21 */
22
23 #include <errno.h>
24 #include <sys/types.h>
25 #ifndef _MSC_VER
26 # include <unistd.h>
27 #endif
28 #include <fcntl.h>
29 #if !defined(_MSC_VER) && !defined(__MINGW32__)
30 # include <sys/stat.h>
31 /* it isn't pulled in by fcntl.h */
32 #endif
33 #include <string.h>
34 #include <stdio.h>
35 #include <ecl/ecl.h>
36 #include <ecl/ecl-inl.h>
37 #define ECL_DEFINE_AET_SIZE
38 #include <ecl/internal.h>
39
40 #ifdef HAVE_SELECT
41 # ifdef HAVE_SYS_SELECT_H
42 # include <sys/select.h>
43 # endif
44 # include <sys/time.h>
45 # include <sys/types.h>
46 # include <unistd.h>
47 #elif defined(ECL_MS_WINDOWS_HOST)
48 # include <winsock.h>
49 # include <windows.h>
50 # include <sys/stat.h>
51 # define STDIN_FILENO 0
52 # define STDOUT_FILENO 1
53 # define STDERR_FILENO 2
54 # define HAVE_SELECT
55 #endif
56 #if defined(HAVE_SYS_IOCTL_H) && !defined(ECL_MS_WINDOWS_HOST) && !defined(cygwin)
57 # include <sys/ioctl.h>
58 #endif
59
60 /* Size of the encoding buffer for vectors */
61 #define VECTOR_ENCODING_BUFFER_SIZE 2048
62
63 static int file_listen(cl_object, FILE *);
64 static int fd_listen(cl_object, int);
65
66 static void cannot_close(cl_object stream) ecl_attr_noreturn;
67 static void file_libc_error(cl_object error_type, cl_object stream, const char *msg, int narg, ...) ecl_attr_noreturn;
68 static int restartable_io_error(cl_object strm, const char *s);
69 static void io_error(cl_object strm) ecl_attr_noreturn;
70 #ifdef ECL_UNICODE
71 static cl_index encoding_error(cl_object strm, unsigned char *buffer, ecl_character c);
72 static ecl_character decoding_error(cl_object strm, unsigned char **buffer, int char_length, unsigned char *buffer_end);
73 #endif
74 static void wrong_file_handler(cl_object strm) ecl_attr_noreturn;
75 #if defined(ECL_WSOCK)
76 static void wsock_error( const char *err_msg, cl_object strm ) ecl_attr_noreturn;
77 #endif
78
79 /**********************************************************************
80 * UNINTERRUPTED OPERATIONS
81 */
82
83 #ifdef ECL_MS_WINDOWS_HOST
84 #define ecl_mode_t int
85 #else
86 #define ecl_mode_t mode_t
87 #endif
88
89 static int
90 safe_open(const ecl_filename_char *filename, int flags, ecl_mode_t mode)
91 {
92 const cl_env_ptr the_env = ecl_process_env();
93 int output;
94 ecl_disable_interrupts_env(the_env);
95 output = ecl_open(filename, flags, mode);
96 ecl_enable_interrupts_env(the_env);
97 return output;
98 }
99
100 static int
101 safe_close(int f)
102 {
103 const cl_env_ptr the_env = ecl_process_env();
104 int output;
105 ecl_disable_interrupts_env(the_env);
106 output = close(f);
107 ecl_enable_interrupts_env(the_env);
108 return output;
109 }
110
111 static FILE *
112 safe_fdopen(int fildes, const ecl_filename_char *mode)
113 {
114 const cl_env_ptr the_env = ecl_process_env();
115 FILE *output;
116 ecl_disable_interrupts_env(the_env);
117 output = ecl_fdopen(fildes, mode);
118 ecl_enable_interrupts_env(the_env);
119 return output;
120 }
121
122 static int
123 safe_fclose(FILE *stream)
124 {
125 const cl_env_ptr the_env = ecl_process_env();
126 int output;
127 /* If someone have closed our fd, do nothing. See #267. */
128 unlikely_if (fileno(stream) == -1) return 0;
129 ecl_disable_interrupts_env(the_env);
130 output = fclose(stream);
131 ecl_enable_interrupts_env(the_env);
132 return output;
133 }
134
135 /* -- Byte stack --------------------------------------------------- */
136 static cl_index
137 consume_byte_stack(cl_object strm, unsigned char *c, cl_index n)
138 {
139 cl_index out = 0;
140 while (n) {
141 cl_object l = strm->stream.byte_stack;
142 if (l == ECL_NIL)
143 return out + strm->stream.ops->read_byte8(strm, c, n);
144 *(c++) = ecl_fixnum(ECL_CONS_CAR(l));
145 out++;
146 n--;
147 strm->stream.byte_stack = l = ECL_CONS_CDR(l);
148 }
149 return out;
150 }
151
152 static void
153 io_file_unread_char(cl_object strm, ecl_character c)
154 {
155 ecl_eformat_unread_char(strm, c);
156 if (c == ECL_CHAR_CODE_NEWLINE) {
157 unsigned char *buffer = strm->stream.byte_buffer;
158 int ndx = 0;
159 cl_object l = strm->stream.byte_stack;
160 int flags = strm->stream.flags;
161 if (flags & ECL_STREAM_CR) {
162 if (flags & ECL_STREAM_LF) {
163 /* Byte stack lands in a reverse order. */
164 ndx = strm->stream.encoder(strm, buffer, ECL_CHAR_CODE_LINEFEED);
165 while (ndx != 0) l = CONS(ecl_make_fixnum(buffer[--ndx]), l);
166 }
167 ndx = strm->stream.encoder(strm, buffer, ECL_CHAR_CODE_RETURN);
168 while (ndx != 0) l = CONS(ecl_make_fixnum(buffer[--ndx]), l);
169 } else {
170 ndx = strm->stream.encoder(strm, buffer, ECL_CHAR_CODE_NEWLINE);
171 while (ndx != 0) l = CONS(ecl_make_fixnum(buffer[--ndx]), l);
172 }
173 strm->stream.byte_stack = l;
174 } else {
175 unsigned char *buffer = strm->stream.byte_buffer;
176 int ndx = 0;
177 cl_object l = strm->stream.byte_stack;
178 ndx = strm->stream.encoder(strm, buffer, c);
179 while (ndx != 0) l = CONS(ecl_make_fixnum(buffer[--ndx]), l);
180 strm->stream.byte_stack = l;
181 }
182 }
183
184 static void
185 io_file_unread_byte(cl_object strm, cl_object byte)
186 {
187 int ndx = strm->stream.byte_size/8;
188 cl_object l = strm->stream.byte_stack;
189 unsigned char *buffer = strm->stream.byte_buffer;
190 ecl_binary_unread_byte(strm, byte);
191 strm->stream.byte_encoder(strm, buffer, byte);
192 while (ndx != 0) l = CONS(ecl_make_fixnum(buffer[--ndx]), l);
193 strm->stream.byte_stack = l;
194 }
195
196 /**********************************************************************
197 * POSIX FILE STREAM
198 */
199
200 static cl_index
201 io_file_read_byte8(cl_object strm, unsigned char *c, cl_index n)
202 {
203 unlikely_if (strm->stream.byte_stack != ECL_NIL) {
204 return consume_byte_stack(strm, c, n);
205 } else {
206 int f = IO_FILE_DESCRIPTOR(strm);
207 cl_fixnum out = 0;
208 ecl_disable_interrupts();
209 do {
210 out = read(f, c, sizeof(char)*n);
211 } while (out < 0 && restartable_io_error(strm, "read"));
212 ecl_enable_interrupts();
213 return out;
214 }
215 }
216
217 static cl_index
218 output_file_write_byte8(cl_object strm, unsigned char *c, cl_index n)
219 {
220 int f = IO_FILE_DESCRIPTOR(strm);
221 cl_fixnum out;
222 ecl_disable_interrupts();
223 do {
224 out = write(f, c, sizeof(char)*n);
225 } while (out < 0 && restartable_io_error(strm, "write"));
226 ecl_enable_interrupts();
227 return out;
228 }
229
230 static cl_index
231 io_file_write_byte8(cl_object strm, unsigned char *c, cl_index n)
232 {
233 unlikely_if (strm->stream.byte_stack != ECL_NIL) {
234 /* Try to move to the beginning of the unread characters */
235 cl_object aux = ecl_file_position(strm);
236 if (!Null(aux))
237 ecl_file_position_set(strm, aux);
238 }
239 return output_file_write_byte8(strm, c, n);
240 }
241
242 static int
243 io_file_listen(cl_object strm)
244 {
245 if (strm->stream.byte_stack != ECL_NIL)
246 return ECL_LISTEN_AVAILABLE;
247 if (strm->stream.flags & ECL_STREAM_MIGHT_SEEK) {
248 cl_env_ptr the_env = ecl_process_env();
249 int f = IO_FILE_DESCRIPTOR(strm);
250 ecl_off_t disp, new;
251 ecl_disable_interrupts_env(the_env);
252 disp = lseek(f, 0, SEEK_CUR);
253 ecl_enable_interrupts_env(the_env);
254 if (disp != (ecl_off_t)-1) {
255 ecl_disable_interrupts_env(the_env);
256 new = lseek(f, 0, SEEK_END);
257 ecl_enable_interrupts_env(the_env);
258 lseek(f, disp, SEEK_SET);
259 if (new == disp) {
260 return ECL_LISTEN_NO_CHAR;
261 } else if (new != (ecl_off_t)-1) {
262 return ECL_LISTEN_AVAILABLE;
263 }
264 }
265 }
266 return fd_listen(strm, IO_FILE_DESCRIPTOR(strm));
267 }
268
269 #if defined(ECL_MS_WINDOWS_HOST)
270 static int
271 isaconsole(int i)
272 {
273 HANDLE h = (HANDLE)_get_osfhandle(i);
274 DWORD mode;
275 return !!GetConsoleMode(h, &mode);
276 }
277 #define isatty isaconsole
278 #endif
279
280 static void
281 io_file_clear_input(cl_object strm)
282 {
283 int f = IO_FILE_DESCRIPTOR(strm);
284 #if defined(ECL_MS_WINDOWS_HOST)
285 if (isatty(f)) {
286 /* Flushes Win32 console */
287 if (!FlushConsoleInputBuffer((HANDLE)_get_osfhandle(f)))
288 FEwin32_error("FlushConsoleInputBuffer() failed", 0);
289 /* Do not stop here: the FILE structure needs also to be flushed */
290 }
291 #endif
292 while (fd_listen(strm, f) == ECL_LISTEN_AVAILABLE) {
293 ecl_character c = ecl_eformat_read_char(strm);
294 if (c == EOF) return;
295 }
296 }
297
298 #define io_file_clear_output ecl_generic_void
299 #define io_file_force_output ecl_generic_void
300 #define io_file_finish_output io_file_force_output
301
302 static int
303 io_file_interactive_p(cl_object strm)
304 {
305 int f = IO_FILE_DESCRIPTOR(strm);
306 return isatty(f);
307 }
308
309 static cl_object
310 io_file_element_type(cl_object strm)
311 {
312 return IO_FILE_ELT_TYPE(strm);
313 }
314
315 static cl_object
316 io_file_length(cl_object strm)
317 {
318 int f = IO_FILE_DESCRIPTOR(strm);
319 cl_object output = ecl_file_len(f);
320 if (strm->stream.byte_size != 8) {
321 const cl_env_ptr the_env = ecl_process_env();
322 cl_index bs = strm->stream.byte_size;
323 output = ecl_floor2(output, ecl_make_fixnum(bs/8));
324 unlikely_if (ecl_nth_value(the_env, 1) != ecl_make_fixnum(0)) {
325 FEerror("File length is not on byte boundary", 0);
326 }
327 }
328 return output;
329 }
330
331 static cl_object
332 io_file_get_position(cl_object strm)
333 {
334 cl_object output;
335 ecl_off_t offset;
336
337 int f = IO_FILE_DESCRIPTOR(strm);
338 if (isatty(f)) return(ECL_NIL);
339
340 ecl_disable_interrupts();
341 offset = lseek(f, 0, SEEK_CUR);
342 ecl_enable_interrupts();
343 unlikely_if (offset < 0)
344 {
345 if (errno == ESPIPE)
346 return(ECL_NIL);
347 else
348 io_error(strm);
349 }
350 if (sizeof(ecl_off_t) == sizeof(long)) {
351 output = ecl_make_integer(offset);
352 } else {
353 output = ecl_off_t_to_integer(offset);
354 }
355 {
356 /* If there are unread octets, we return the position at which
357 * these bytes begin! */
358 cl_object l = strm->stream.byte_stack;
359 while (CONSP(l)) {
360 output = ecl_one_minus(output);
361 l = ECL_CONS_CDR(l);
362 }
363 }
364 if (strm->stream.byte_size != 8) {
365 output = ecl_floor2(output, ecl_make_fixnum(strm->stream.byte_size / 8));
366 }
367 return output;
368 }
369
370 static cl_object
371 io_file_set_position(cl_object strm, cl_object large_disp)
372 {
373 ecl_off_t disp;
374 int mode;
375 int f = IO_FILE_DESCRIPTOR(strm);
376 if (isatty(f)) return(ECL_NIL);
377 strm->stream.byte_stack = ECL_NIL;
378 if (Null(large_disp)) {
379 disp = 0;
380 mode = SEEK_END;
381 } else {
382 if (strm->stream.byte_size != 8) {
383 large_disp = ecl_times(large_disp,
384 ecl_make_fixnum(strm->stream.byte_size / 8));
385 }
386 disp = ecl_integer_to_off_t(large_disp);
387 mode = SEEK_SET;
388 }
389 disp = lseek(f, disp, mode);
390 return (disp == (ecl_off_t)-1)? ECL_NIL : ECL_T;
391 }
392
393 static cl_object
394 io_file_close(cl_object strm)
395 {
396 int f = IO_FILE_DESCRIPTOR(strm);
397 int failed;
398 unlikely_if (f == STDOUT_FILENO)
399 FEerror("Cannot close the standard output", 0);
400 unlikely_if (f == STDIN_FILENO)
401 FEerror("Cannot close the standard input", 0);
402 failed = safe_close(f);
403 unlikely_if (failed < 0)
404 cannot_close(strm);
405 IO_FILE_DESCRIPTOR(strm) = -1;
406 return ecl_generic_close(strm);
407 }
408
409 static ecl_character io_file_decode_char_from_buffer(cl_object strm, unsigned char *buffer, unsigned char **buffer_pos, unsigned char **buffer_end, bool seekable, cl_index min_needed_bytes) {
410 bool crlf = 0;
411 unsigned char *previous_buffer_pos;
412 ecl_character c;
413 AGAIN:
414 previous_buffer_pos = *buffer_pos;
415 c = strm->stream.decoder(strm, buffer_pos, *buffer_end);
416 if (c != EOF) {
417 /* Ugly handling of line breaks */
418 if (crlf) {
419 if (c == ECL_CHAR_CODE_LINEFEED) {
420 c = ECL_CHAR_CODE_NEWLINE;
421 }
422 else {
423 *buffer_pos = previous_buffer_pos;
424 c = ECL_CHAR_CODE_RETURN;
425 }
426 } else if (strm->stream.flags & ECL_STREAM_CR && c == ECL_CHAR_CODE_RETURN) {
427 if (strm->stream.flags & ECL_STREAM_LF) {
428 crlf = 1;
429 goto AGAIN;
430 }
431 else
432 c = ECL_CHAR_CODE_NEWLINE;
433 }
434 return c;
435 } else {
436 /* We need more bytes. First copy unconsumed bytes at the
437 * beginning of buffer. */
438 cl_index unconsumed_bytes = *buffer_end - *buffer_pos;
439 memcpy(buffer, *buffer_pos, unconsumed_bytes);
440 cl_index needed_bytes = VECTOR_ENCODING_BUFFER_SIZE;
441 if (!seekable && min_needed_bytes < VECTOR_ENCODING_BUFFER_SIZE)
442 needed_bytes = min_needed_bytes;
443 *buffer_end = buffer + unconsumed_bytes
444 + ecl_read_byte8(strm, buffer + unconsumed_bytes, needed_bytes);
445 if (*buffer_end == buffer + unconsumed_bytes)
446 return EOF;
447 *buffer_pos = buffer;
448 goto AGAIN;
449 }
450 }
451
452 /* The following macros create a temporary buffer for efficient
453 * reading of characters from file streams */
454 #define ECL_FILE_READ_BUFFER_CREATE(strm) \
455 cl_object __stream = (strm); \
456 unsigned char __buffer[VECTOR_ENCODING_BUFFER_SIZE + ENCODING_BUFFER_MAX_SIZE]; \
457 unsigned char *__buffer_pos = __buffer; \
458 unsigned char *__buffer_end = __buffer; \
459 /* When we can't call lseek/fseek we have to be conservative and \
460 * read only as many bytes as we actually need. Otherwise, we read \
461 * more and later reposition the file offset. */ \
462 bool __seekable = ecl_file_position(__stream) != ECL_NIL; \
463 ECL_UNWIND_PROTECT_BEGIN(ecl_process_env()) {
464
465 #define ECL_FILE_READ_BUFFER_GET_CHAR(min_needed_bytes) \
466 io_file_decode_char_from_buffer(__stream, __buffer, &__buffer_pos, &__buffer_end, __seekable, min_needed_bytes)
467
468 #define ECL_FILE_READ_BUFFER_DESTROY \
469 } ECL_UNWIND_PROTECT_THREAD_SAFE_EXIT { \
470 if (__seekable) \
471 /* INV: (buffer_end - buffer_pos) is divisible by \
472 * (strm->stream.byte_size / 8) since VECTOR_ENCODING_BUFFER_SIZE \
473 * is divisible by all byte sizes for character streams and all \
474 * decoders consume bytes in multiples of the byte size. */ \
475 ecl_file_position_set(__stream, ecl_minus(ecl_file_position(__stream), \
476 ecl_make_fixnum((__buffer_end - __buffer_pos) / (__stream->stream.byte_size / 8)))); \
477 } ECL_UNWIND_PROTECT_THREAD_SAFE_END
478
479 static cl_index
480 io_file_read_vector(cl_object strm, cl_object data, cl_index start, cl_index end)
481 {
482 cl_elttype t = ecl_array_elttype(data);
483 if (start >= end)
484 return start;
485 if (t == ecl_aet_b8 || t == ecl_aet_i8) {
486 if (strm->stream.byte_size == 8) {
487 void *aux = data->vector.self.bc + start;
488 return start + strm->stream.ops->read_byte8(strm, aux, end-start);
489 }
490 } else if (t == ecl_aet_fix || t == ecl_aet_index) {
491 if (strm->stream.byte_size == sizeof(cl_fixnum)*8) {
492 void *aux = data->vector.self.fix + start;
493 cl_index bytes = (end - start) * sizeof(cl_fixnum);
494 bytes = strm->stream.ops->read_byte8(strm, aux, bytes);
495 return start + bytes / sizeof(cl_fixnum);
496 }
497 } else if (ecl_stream_element_type(strm) == @'base-char'
498 || ecl_stream_element_type(strm) == @'character') {
499 ECL_FILE_READ_BUFFER_CREATE(strm) {
500 while (start < end) {
501 ecl_character c = ECL_FILE_READ_BUFFER_GET_CHAR((end-start) * (strm->stream.byte_size / 8));
502 if (c != EOF)
503 ecl_elt_set(data, start++, ECL_CODE_CHAR(c));
504 else
505 break;
506 }
507 } ECL_FILE_READ_BUFFER_DESTROY;
508 return start;
509 }
510 return ecl_generic_read_vector(strm, data, start, end);
511 }
512
513 static cl_index
514 io_file_write_vector(cl_object strm, cl_object data, cl_index start, cl_index end)
515 {
516 cl_elttype t = ecl_array_elttype(data);
517 if (start >= end)
518 return start;
519 if (t == ecl_aet_b8 || t == ecl_aet_i8) {
520 if (strm->stream.byte_size == 8) {
521 void *aux = data->vector.self.bc + start;
522 return strm->stream.ops->write_byte8(strm, aux, end-start);
523 }
524 } else if (t == ecl_aet_fix || t == ecl_aet_index) {
525 if (strm->stream.byte_size == sizeof(cl_fixnum)*8) {
526 void *aux = data->vector.self.fix + start;
527 cl_index bytes = (end - start) * sizeof(cl_fixnum);
528 bytes = strm->stream.ops->write_byte8(strm, aux, bytes);
529 return start + bytes / sizeof(cl_fixnum);
530 }
531 } else if (t == ecl_aet_bc) {
532 /* 1 extra byte for linefeed in crlf mode */
533 unsigned char buffer[VECTOR_ENCODING_BUFFER_SIZE + ENCODING_BUFFER_MAX_SIZE + 1];
534 cl_index nbytes = 0;
535 cl_index i;
536 for (i = start; i < end; i++) {
537 ecl_character c = *(data->vector.self.bc + i);
538 if (c == ECL_CHAR_CODE_NEWLINE) {
539 if (strm->stream.flags & ECL_STREAM_CR &&
540 strm->stream.flags & ECL_STREAM_LF)
541 nbytes += strm->stream.encoder(strm, buffer + nbytes, ECL_CHAR_CODE_RETURN);
542 else if (strm->stream.flags & ECL_STREAM_CR)
543 c = ECL_CHAR_CODE_RETURN;
544 strm->stream.column = 0;
545 }
546 nbytes += strm->stream.encoder(strm, buffer + nbytes, c);
547 write_char_increment_column(strm, c);
548 if (nbytes >= VECTOR_ENCODING_BUFFER_SIZE) {
549 strm->stream.ops->write_byte8(strm, buffer, nbytes);
550 nbytes = 0;
551 }
552 }
553 strm->stream.ops->write_byte8(strm, buffer, nbytes);
554 return end;
555 }
556 #ifdef ECL_UNICODE
557 else if (t == ecl_aet_ch) {
558 /* 1 extra byte for linefeed in crlf mode */
559 unsigned char buffer[VECTOR_ENCODING_BUFFER_SIZE + ENCODING_BUFFER_MAX_SIZE + 1];
560 cl_index nbytes = 0;
561 cl_index i;
562 for (i = start; i < end; i++) {
563 ecl_character c = *(data->vector.self.c + i);
564 if (c == ECL_CHAR_CODE_NEWLINE) {
565 if (strm->stream.flags & ECL_STREAM_CR &&
566 strm->stream.flags & ECL_STREAM_LF)
567 nbytes += strm->stream.encoder(strm, buffer + nbytes, ECL_CHAR_CODE_RETURN);
568 else if (strm->stream.flags & ECL_STREAM_CR)
569 c = ECL_CHAR_CODE_RETURN;
570 strm->stream.column = 0;
571 }
572 nbytes += strm->stream.encoder(strm, buffer + nbytes, c);
573 write_char_increment_column(strm, c);
574 if (nbytes >= VECTOR_ENCODING_BUFFER_SIZE) {
575 strm->stream.ops->write_byte8(strm, buffer, nbytes);
576 nbytes = 0;
577 }
578 }
579 strm->stream.ops->write_byte8(strm, buffer, nbytes);
580 return end;
581 }
582 #endif
583 return ecl_generic_write_vector(strm, data, start, end);
584 }
585
586 static cl_object
587 io_file_pathname(cl_object strm)
588 {
589 return IO_STREAM_FILENAME(strm);
590 }
591
592 static cl_object
593 io_file_truename(cl_object strm)
594 {
595 return cl_truename(IO_STREAM_FILENAME(strm));
596 }
597
598 const struct ecl_file_ops io_file_ops = {
599 io_file_read_byte8,
600 io_file_write_byte8,
601
602 ecl_binary_read_byte,
603 ecl_binary_write_byte,
604 io_file_unread_byte,
605 ecl_generic_peek_byte,
606
607 ecl_eformat_read_char,
608 ecl_eformat_write_char,
609 io_file_unread_char,
610 ecl_generic_peek_char,
611
612 io_file_read_vector,
613 io_file_write_vector,
614
615 io_file_listen,
616 io_file_clear_input,
617 io_file_clear_output,
618 io_file_finish_output,
619 io_file_force_output,
620
621 ecl_generic_always_true, /* input_p */
622 ecl_generic_always_true, /* output_p */
623 io_file_interactive_p,
624 io_file_element_type,
625
626 io_file_length,
627 io_file_get_position,
628 io_file_set_position,
629 ecl_eformat_file_string_length,
630 ecl_generic_column,
631
632 io_file_pathname,
633 io_file_truename,
634
635 io_file_close
636 };
637
638 const struct ecl_file_ops output_file_ops = {
639 ecl_not_input_read_byte8,
640 output_file_write_byte8,
641
642 ecl_not_input_read_byte,
643 ecl_binary_write_byte,
644 ecl_not_input_unread_byte,
645 ecl_not_input_read_byte,
646
647 ecl_not_input_read_char,
648 ecl_eformat_write_char,
649 ecl_not_input_unread_char,
650 ecl_not_input_read_char,
651
652 ecl_generic_read_vector,
653 io_file_write_vector,
654
655 ecl_not_input_listen,
656 ecl_not_input_clear_input,
657 io_file_clear_output,
658 io_file_finish_output,
659 io_file_force_output,
660
661 ecl_generic_always_false, /* input_p */
662 ecl_generic_always_true, /* output_p */
663 ecl_generic_always_false,
664 io_file_element_type,
665
666 io_file_length,
667 io_file_get_position,
668 io_file_set_position,
669 ecl_eformat_file_string_length,
670 ecl_generic_column,
671
672 io_file_pathname,
673 io_file_truename,
674
675 io_file_close
676 };
677
678 const struct ecl_file_ops input_file_ops = {
679 io_file_read_byte8,
680 ecl_not_output_write_byte8,
681
682 ecl_binary_read_byte,
683 ecl_not_output_write_byte,
684 io_file_unread_byte,
685 ecl_generic_peek_byte,
686
687 ecl_eformat_read_char,
688 ecl_not_output_write_char,
689 io_file_unread_char,
690 ecl_generic_peek_char,
691
692 io_file_read_vector,
693 ecl_generic_write_vector,
694
695 io_file_listen,
696 io_file_clear_input,
697 ecl_not_output_clear_output,
698 ecl_not_output_finish_output,
699 ecl_not_output_force_output,
700
701 ecl_generic_always_true, /* input_p */
702 ecl_generic_always_false, /* output_p */
703 io_file_interactive_p,
704 io_file_element_type,
705
706 io_file_length,
707 io_file_get_position,
708 io_file_set_position,
709 ecl_not_output_string_length,
710 ecl_unknown_column,
711
712 io_file_pathname,
713 io_file_truename,
714
715 io_file_close
716 };
717
718 cl_object
719 ecl_make_file_stream_from_fd(cl_object fname, int fd, enum ecl_smmode smm,
720 cl_fixnum byte_size, int flags, cl_object external_format)
721 {
722 cl_object stream = ecl_alloc_stream();
723 switch(smm) {
724 case ecl_smm_input:
725 smm = ecl_smm_input_file;
726 case ecl_smm_input_file:
727 case ecl_smm_probe:
728 stream->stream.ops = ecl_duplicate_dispatch_table(&input_file_ops);
729 break;
730 case ecl_smm_output:
731 smm = ecl_smm_output_file;
732 case ecl_smm_output_file:
733 stream->stream.ops = ecl_duplicate_dispatch_table(&output_file_ops);
734 break;
735 case ecl_smm_io:
736 smm = ecl_smm_io_file;
737 case ecl_smm_io_file:
738 stream->stream.ops = ecl_duplicate_dispatch_table(&io_file_ops);
739 break;
740 default:
741 FEerror("make_stream: wrong mode", 0);
742 }
743 stream->stream.mode = (short)smm;
744 stream->stream.closed = 0;
745 ecl_set_stream_elt_type(stream, byte_size, flags, external_format);
746 IO_FILE_FILENAME(stream) = fname; /* used in cl:pathname */
747 stream->stream.column = 0;
748 IO_FILE_DESCRIPTOR(stream) = fd;
749 stream->stream.last_op = 0;
750 si_set_finalizer(stream, ECL_T);
751 return stream;
752 }
753
754 /**********************************************************************
755 * C STREAMS
756 */
757
758 static cl_index
759 input_stream_read_byte8(cl_object strm, unsigned char *c, cl_index n)
760 {
761 unlikely_if (strm->stream.byte_stack != ECL_NIL) {
762 return consume_byte_stack(strm, c, n);
763 } else {
764 FILE *f = IO_STREAM_FILE(strm);
765 cl_fixnum out = 0;
766 ecl_disable_interrupts();
767 #ifdef FILE_CNT
768 do {
769 out = fread(c, sizeof(char), n, f);
770 } while (out < n && ferror(f) && restartable_io_error(strm, "fread"));
771 #else
772 /* We can't use fread here due to the buffering. It makes
773 impossible checking if we have some data available in the
774 buffer what renders listen returning incorrect result. */
775 do {
776 out = read(fileno(f), c, sizeof(char)*n);
777 } while (out < 0 && restartable_io_error(strm, "read"));
778 #endif
779 ecl_enable_interrupts();
780 return out;
781 }
782 }
783
784 static cl_index
785 output_stream_write_byte8(cl_object strm, unsigned char *c, cl_index n)
786 {
787 cl_index out;
788 ecl_disable_interrupts();
789 do {
790 out = fwrite(c, sizeof(char), n, IO_STREAM_FILE(strm));
791 } while (out < n && restartable_io_error(strm, "fwrite"));
792 ecl_enable_interrupts();
793 return out;
794 }
795
796 static cl_index
797 io_stream_write_byte8(cl_object strm, unsigned char *c, cl_index n)
798 {
799 /* When using the same stream for input and output operations, we have to
800 * use some file position operation before reading again. Besides this, if
801 * there were unread octets, we have to move to the position at the
802 * begining of them.
803 */
804 if (strm->stream.byte_stack != ECL_NIL) {
805 cl_object aux = ecl_file_position(strm);
806 if (!Null(aux))
807 ecl_file_position_set(strm, aux);
808 } else if (strm->stream.last_op > 0) {
809 ecl_fseeko(IO_STREAM_FILE(strm), 0, SEEK_CUR);
810 }
811 strm->stream.last_op = -1;
812 return output_stream_write_byte8(strm, c, n);
813 }
814
815 static void io_stream_force_output(cl_object strm);
816
817 static cl_index
818 io_stream_read_byte8(cl_object strm, unsigned char *c, cl_index n)
819 {
820 /* When using the same stream for input and output operations, we have to
821 * flush the stream before reading.
822 */
823 if (strm->stream.last_op < 0) {
824 io_stream_force_output(strm);
825 }
826 strm->stream.last_op = +1;
827 return input_stream_read_byte8(strm, c, n);
828 }
829
830 static int
831 io_stream_listen(cl_object strm)
832 {
833 if (strm->stream.byte_stack != ECL_NIL)
834 return ECL_LISTEN_AVAILABLE;
835 return file_listen(strm, IO_STREAM_FILE(strm));
836 }
837
838 static void
839 io_stream_clear_input(cl_object strm)
840 {
841 FILE *fp = IO_STREAM_FILE(strm);
842 #if defined(ECL_MS_WINDOWS_HOST)
843 int f = fileno(fp);
844 if (isatty(f)) {
845 /* Flushes Win32 console */
846 unlikely_if (!FlushConsoleInputBuffer((HANDLE)_get_osfhandle(f)))
847 FEwin32_error("FlushConsoleInputBuffer() failed", 0);
848 /* Do not stop here: the FILE structure needs also to be flushed */
849 }
850 #endif
851 while (file_listen(strm, fp) == ECL_LISTEN_AVAILABLE) {
852 ecl_disable_interrupts();
853 getc(fp);
854 ecl_enable_interrupts();
855 }
856 }
857
858 #define io_stream_clear_output ecl_generic_void
859
860 static void
861 io_stream_force_output(cl_object strm)
862 {
863 FILE *f = IO_STREAM_FILE(strm);
864 ecl_disable_interrupts();
865 while ((fflush(f) == EOF) && restartable_io_error(strm, "fflush"))
866 (void)0;
867 ecl_enable_interrupts();
868 }
869
870 #define io_stream_finish_output io_stream_force_output
871
872 static int
873 io_stream_interactive_p(cl_object strm)
874 {
875 FILE *f = IO_STREAM_FILE(strm);
876 return isatty(fileno(f));
877 }
878
879 static cl_object
880 io_stream_length(cl_object strm)
881 {
882 FILE *f = IO_STREAM_FILE(strm);
883 cl_object output = ecl_file_len(fileno(f));
884 if (strm->stream.byte_size != 8) {
885 const cl_env_ptr the_env = ecl_process_env();
886 cl_index bs = strm->stream.byte_size;
887 output = ecl_floor2(output, ecl_make_fixnum(bs/8));
888 unlikely_if (ecl_nth_value(the_env, 1) != ecl_make_fixnum(0)) {
889 FEerror("File length is not on byte boundary", 0);
890 }
891 }
892 return output;
893 }
894
895 static cl_object
896 io_stream_get_position(cl_object strm)
897 {
898 FILE *f = IO_STREAM_FILE(strm);
899 cl_object output;
900 ecl_off_t offset;
901
902 ecl_disable_interrupts();
903 offset = ecl_ftello(f);
904 ecl_enable_interrupts();
905 unlikely_if (offset < 0) {
906 if (errno == ESPIPE)
907 return(ECL_NIL);
908 else
909 io_error(strm);
910 }
911 if (sizeof(ecl_off_t) == sizeof(long)) {
912 output = ecl_make_integer(offset);
913 } else {
914 output = ecl_off_t_to_integer(offset);
915 }
916 {
917 /* If there are unread octets, we return the position at which
918 * these bytes begin! */
919 cl_object l = strm->stream.byte_stack;
920 while (CONSP(l)) {
921 output = ecl_one_minus(output);
922 l = ECL_CONS_CDR(l);
923 }
924 }
925 if (strm->stream.byte_size != 8) {
926 output = ecl_floor2(output, ecl_make_fixnum(strm->stream.byte_size / 8));
927 }
928 return output;
929 }
930
931 static cl_object
932 io_stream_set_position(cl_object strm, cl_object large_disp)
933 {
934 FILE *f = IO_STREAM_FILE(strm);
935 ecl_off_t disp;
936 int mode;
937 strm->stream.byte_stack = ECL_NIL;
938 if (Null(large_disp)) {
939 disp = 0;
940 mode = SEEK_END;
941 } else {
942 if (strm->stream.byte_size != 8) {
943 large_disp = ecl_times(large_disp,
944 ecl_make_fixnum(strm->stream.byte_size / 8));
945 }
946 disp = ecl_integer_to_off_t(large_disp);
947 mode = SEEK_SET;
948 }
949 ecl_disable_interrupts();
950 mode = ecl_fseeko(f, disp, mode);
951 ecl_enable_interrupts();
952 return mode? ECL_NIL : ECL_T;
953 }
954
955 static cl_object
956 io_stream_close(cl_object strm)
957 {
958 FILE *f = IO_STREAM_FILE(strm);
959 int failed;
960 unlikely_if (f == stdout)
961 FEerror("Cannot close the standard output", 0);
962 unlikely_if (f == stdin)
963 FEerror("Cannot close the standard input", 0);
964 unlikely_if (f == NULL)
965 wrong_file_handler(strm);
966 if (ecl_output_stream_p(strm)) {
967 ecl_force_output(strm);
968 }
969 failed = safe_fclose(f);
970 unlikely_if (failed)
971 cannot_close(strm);
972 #if !defined(GBC_BOEHM)
973 ecl_dealloc(strm->stream.buffer);
974 IO_STREAM_FILE(strm) = NULL;
975 #endif
976 return ecl_generic_close(strm);
977 }
978
979 /*
980 * Specialized sequence operations
981 */
982
983 #define io_stream_read_vector io_file_read_vector
984 #define io_stream_write_vector io_file_write_vector
985
986 const struct ecl_file_ops io_stream_ops = {
987 io_stream_read_byte8,
988 io_stream_write_byte8,
989
990 ecl_binary_read_byte,
991 ecl_binary_write_byte,
992 io_file_unread_byte,
993 ecl_generic_peek_byte,
994
995 ecl_eformat_read_char,
996 ecl_eformat_write_char,
997 io_file_unread_char,
998 ecl_generic_peek_char,
999
1000 io_file_read_vector,
1001 io_file_write_vector,
1002
1003 io_stream_listen,
1004 io_stream_clear_input,
1005 io_stream_clear_output,
1006 io_stream_finish_output,
1007 io_stream_force_output,
1008
1009 ecl_generic_always_true, /* input_p */
1010 ecl_generic_always_true, /* output_p */
1011 io_stream_interactive_p,
1012 io_file_element_type,
1013
1014 io_stream_length,
1015 io_stream_get_position,
1016 io_stream_set_position,
1017 ecl_eformat_file_string_length,
1018 ecl_generic_column,
1019
1020 io_file_pathname,
1021 io_file_truename,
1022
1023 io_stream_close
1024 };
1025
1026 const struct ecl_file_ops output_stream_ops = {
1027 ecl_not_input_read_byte8,
1028 output_stream_write_byte8,
1029
1030 ecl_not_input_read_byte,
1031 ecl_binary_write_byte,
1032 ecl_not_input_unread_byte,
1033 ecl_not_input_read_byte,
1034
1035 ecl_not_input_read_char,
1036 ecl_eformat_write_char,
1037 ecl_not_input_unread_char,
1038 ecl_not_input_read_char,
1039
1040 ecl_generic_read_vector,
1041 io_file_write_vector,
1042
1043 ecl_not_input_listen,
1044 ecl_generic_void,
1045 io_stream_clear_output,
1046 io_stream_finish_output,
1047 io_stream_force_output,
1048
1049 ecl_generic_always_false, /* input_p */
1050 ecl_generic_always_true, /* output_p */
1051 ecl_generic_always_false,
1052 io_file_element_type,
1053
1054 io_stream_length,
1055 io_stream_get_position,
1056 io_stream_set_position,
1057 ecl_eformat_file_string_length,
1058 ecl_generic_column,
1059
1060 io_file_pathname,
1061 io_file_truename,
1062
1063 io_stream_close
1064 };
1065
1066 const struct ecl_file_ops input_stream_ops = {
1067 input_stream_read_byte8,
1068 ecl_not_output_write_byte8,
1069
1070 ecl_binary_read_byte,
1071 ecl_not_output_write_byte,
1072 io_file_unread_byte,
1073 ecl_generic_peek_byte,
1074
1075 ecl_eformat_read_char,
1076 ecl_not_output_write_char,
1077 io_file_unread_char,
1078 ecl_generic_peek_char,
1079
1080 io_file_read_vector,
1081 ecl_generic_write_vector,
1082
1083 io_stream_listen,
1084 io_stream_clear_input,
1085 ecl_generic_void,
1086 ecl_generic_void,
1087 ecl_generic_void,
1088
1089 ecl_generic_always_true, /* input_p */
1090 ecl_generic_always_false, /* output_p */
1091 io_stream_interactive_p,
1092 io_file_element_type,
1093
1094 io_stream_length,
1095 io_stream_get_position,
1096 io_stream_set_position,
1097 ecl_not_output_string_length,
1098 ecl_unknown_column,
1099
1100 io_file_pathname,
1101 io_file_truename,
1102
1103 io_stream_close
1104 };
1105
1106 /**********************************************************************
1107 * WINSOCK STREAMS
1108 */
1109
1110 #if defined(ECL_WSOCK)
1111
1112 #define winsock_stream_element_type io_file_element_type
1113
1114 static cl_index
1115 winsock_stream_read_byte8(cl_object strm, unsigned char *c, cl_index n)
1116 {
1117 cl_index len = 0;
1118
1119 unlikely_if (strm->stream.byte_stack != ECL_NIL) {
1120 return consume_byte_stack(strm, c, n);
1121 }
1122 if(n > 0) {
1123 SOCKET s = (SOCKET)IO_FILE_DESCRIPTOR(strm);
1124 unlikely_if (INVALID_SOCKET == s) {
1125 wrong_file_handler(strm);
1126 } else {
1127 ecl_disable_interrupts();
1128 len = recv(s, c, n, 0);
1129 unlikely_if (len == SOCKET_ERROR)
1130 wsock_error("Cannot read bytes from Windows "
1131 "socket ~S.~%~A", strm);
1132 ecl_enable_interrupts();
1133 }
1134 }
1135 return (len > 0) ? len : EOF;
1136 }
1137
1138 static cl_index
1139 winsock_stream_write_byte8(cl_object strm, unsigned char *c, cl_index n)
1140 {
1141 cl_index out = 0;
1142 unsigned char *endp;
1143 unsigned char *p;
1144 SOCKET s = (SOCKET)IO_FILE_DESCRIPTOR(strm);
1145 unlikely_if (INVALID_SOCKET == s) {
1146 wrong_file_handler(strm);
1147 } else {
1148 ecl_disable_interrupts();
1149 do {
1150 cl_index res = send(s, c + out, n, 0);
1151 unlikely_if (res == SOCKET_ERROR) {
1152 wsock_error("Cannot write bytes to Windows"
1153 " socket ~S.~%~A", strm);
1154 break; /* stop writing */
1155 } else {
1156 out += res;
1157 n -= res;
1158 }
1159 } while (n > 0);
1160 ecl_enable_interrupts();
1161 }
1162 return out;
1163 }
1164
1165 static int
1166 winsock_stream_listen(cl_object strm)
1167 {
1168 SOCKET s;
1169 unlikely_if (strm->stream.byte_stack != ECL_NIL) {
1170 return ECL_LISTEN_AVAILABLE;
1171 }
1172 s = (SOCKET)IO_FILE_DESCRIPTOR(strm);
1173 unlikely_if (INVALID_SOCKET == s) {
1174 wrong_file_handler(strm);
1175 }
1176 {
1177 struct timeval tv = { 0, 0 };
1178 fd_set fds;
1179 cl_index result;
1180
1181 FD_ZERO( &fds );
1182 FD_SET(s, &fds);
1183 ecl_disable_interrupts();
1184 result = select( 0, &fds, NULL, NULL, &tv );
1185 unlikely_if (result == SOCKET_ERROR)
1186 wsock_error("Cannot listen on Windows "
1187 "socket ~S.~%~A", strm );
1188 ecl_enable_interrupts();
1189 return ( result > 0
1190 ? ECL_LISTEN_AVAILABLE
1191 : ECL_LISTEN_NO_CHAR );
1192 }
1193 }
1194
1195 static void
1196 winsock_stream_clear_input(cl_object strm)
1197 {
1198 while (winsock_stream_listen(strm) == ECL_LISTEN_AVAILABLE) {
1199 ecl_eformat_read_char(strm);
1200 }
1201 }
1202
1203 static cl_object
1204 winsock_stream_close(cl_object strm)
1205 {
1206 SOCKET s = (SOCKET) IO_FILE_DESCRIPTOR(strm);
1207 int failed;
1208 ecl_disable_interrupts();
1209 failed = closesocket(s);
1210 ecl_enable_interrupts();
1211 unlikely_if (failed < 0)
1212 cannot_close(strm);
1213 IO_FILE_DESCRIPTOR(strm) = (int)INVALID_SOCKET;
1214 return ecl_generic_close(strm);
1215 }
1216
1217 const struct ecl_file_ops winsock_stream_io_ops = {
1218 winsock_stream_read_byte8,
1219 winsock_stream_write_byte8,
1220
1221 ecl_binary_read_byte,
1222 ecl_binary_write_byte,
1223 io_file_unread_byte,
1224 ecl_generic_peek_byte,
1225
1226 ecl_eformat_read_char,
1227 ecl_eformat_write_char,
1228 io_file_unread_char,
1229 ecl_generic_peek_char,
1230
1231 ecl_generic_read_vector,
1232 ecl_generic_write_vector,
1233
1234 winsock_stream_listen,
1235 winsock_stream_clear_input,
1236 ecl_generic_void,
1237 ecl_generic_void,
1238 ecl_generic_void,
1239
1240 ecl_generic_always_true, /* input_p */
1241 ecl_generic_always_true, /* output_p */
1242 ecl_generic_always_false,
1243 winsock_stream_element_type,
1244
1245 ecl_not_a_file_stream,
1246 ecl_generic_always_nil, /* get_position */
1247 ecl_generic_set_position,
1248 ecl_eformat_file_string_length,
1249 ecl_generic_column,
1250
1251 ecl_not_a_file_stream,
1252 ecl_not_a_file_stream,
1253
1254 winsock_stream_close
1255 };
1256
1257 const struct ecl_file_ops winsock_stream_output_ops = {
1258 ecl_not_input_read_byte8,
1259 winsock_stream_write_byte8,
1260
1261 ecl_not_input_read_byte,
1262 ecl_binary_write_byte,
1263 ecl_not_input_unread_byte,
1264 ecl_not_input_read_byte,
1265
1266 ecl_not_input_read_char,
1267 ecl_eformat_write_char,
1268 ecl_not_input_unread_char,
1269 ecl_not_input_read_char,
1270
1271 ecl_generic_read_vector,
1272 ecl_generic_write_vector,
1273
1274 ecl_not_input_listen,
1275 ecl_not_input_clear_input,
1276 ecl_generic_void,
1277 ecl_generic_void,
1278 ecl_generic_void,
1279
1280 ecl_generic_always_false, /* input_p */
1281 ecl_generic_always_true, /* output_p */
1282 ecl_generic_always_false,
1283 winsock_stream_element_type,
1284
1285 ecl_not_a_file_stream,
1286 ecl_generic_always_nil, /* get_position */
1287 ecl_generic_set_position,
1288 ecl_eformat_file_string_length,
1289 ecl_generic_column,
1290
1291 ecl_not_a_file_stream,
1292 ecl_not_a_file_stream,
1293
1294 winsock_stream_close
1295 };
1296
1297 const struct ecl_file_ops winsock_stream_input_ops = {
1298 winsock_stream_read_byte8,
1299 ecl_not_output_write_byte8,
1300
1301 ecl_binary_read_byte,
1302 ecl_not_output_write_byte,
1303 io_file_unread_byte,
1304 ecl_generic_peek_byte,
1305
1306 ecl_eformat_read_char,
1307 ecl_not_output_write_char,
1308 io_file_unread_char,
1309 ecl_generic_peek_char,
1310
1311 ecl_generic_read_vector,
1312 ecl_generic_write_vector,
1313
1314 winsock_stream_listen,
1315 winsock_stream_clear_input,
1316 ecl_not_output_clear_output,
1317 ecl_not_output_finish_output,
1318 ecl_not_output_force_output,
1319
1320 ecl_generic_always_true, /* input_p */
1321 ecl_generic_always_false, /* output_p */
1322 ecl_generic_always_false,
1323 winsock_stream_element_type,
1324
1325 ecl_not_a_file_stream,
1326 ecl_generic_always_nil, /* get_position */
1327 ecl_generic_set_position,
1328 ecl_not_output_string_length,
1329 ecl_unknown_column,
1330
1331 ecl_not_a_file_stream,
1332 ecl_not_a_file_stream,
1333
1334 winsock_stream_close
1335 };
1336 #endif
1337
1338 /**********************************************************************
1339 * WINCONSOLE STREAM
1340 */
1341
1342 #if defined(ECL_MS_WINDOWS_HOST)
1343
1344 #define wcon_stream_element_type io_file_element_type
1345
1346 static cl_index
1347 wcon_stream_read_byte8(cl_object strm, unsigned char *c, cl_index n)
1348 {
1349 unlikely_if (strm->stream.byte_stack != ECL_NIL) {
1350 return consume_byte_stack(strm, c, n);
1351 } else {
1352 cl_env_ptr the_env = ecl_process_env();
1353 HANDLE h = (HANDLE)IO_FILE_DESCRIPTOR(strm);
1354 DWORD nchars;
1355 int ok;
1356 ecl_disable_interrupts_env(the_env);
1357 ok = ReadConsoleA(h, c, n, &nchars, NULL);
1358 ecl_enable_interrupts_env(the_env);
1359 unlikely_if (!ok) {
1360 FEwin32_error("Cannot read from console", 0);
1361 }
1362 return (nchars > 0) ? nchars : EOF;
1363 }
1364 }
1365
1366 static cl_index
1367 wcon_stream_write_byte8(cl_object strm, unsigned char *c, cl_index n)
1368 {
1369 HANDLE h = (HANDLE)IO_FILE_DESCRIPTOR(strm);
1370 DWORD nchars;
1371 unlikely_if(!WriteConsoleA(h, c, n, &nchars, NULL)) {
1372 FEwin32_error("Cannot write to console.", 0);
1373 }
1374 return nchars;
1375 }
1376
1377 static int
1378 wcon_stream_listen(cl_object strm)
1379 {
1380 HANDLE h = (HANDLE)IO_FILE_DESCRIPTOR(strm);
1381 INPUT_RECORD aux;
1382 DWORD nevents;
1383 do {
1384 unlikely_if(!PeekConsoleInput(h, &aux, 1, &nevents))
1385 FEwin32_error("Cannot read from console.", 0);
1386 if (nevents == 0)
1387 return 0;
1388 if (aux.EventType == KEY_EVENT)
1389 return 1;
1390 unlikely_if(!ReadConsoleInput(h, &aux, 1, &nevents))
1391 FEwin32_error("Cannot read from console.", 0);
1392 } while (1);
1393 }
1394
1395 static void
1396 wcon_stream_clear_input(cl_object strm)
1397 {
1398 FlushConsoleInputBuffer((HANDLE)IO_FILE_DESCRIPTOR(strm));
1399 }
1400
1401 static void
1402 wcon_stream_force_output(cl_object strm)
1403 {
1404 DWORD nchars;
1405 WriteConsole((HANDLE)IO_FILE_DESCRIPTOR(strm), 0, 0, &nchars, NULL);
1406 }
1407
1408 const struct ecl_file_ops wcon_stream_io_ops = {
1409 wcon_stream_read_byte8,
1410 wcon_stream_write_byte8,
1411
1412 ecl_binary_read_byte,
1413 ecl_binary_write_byte,
1414 io_file_unread_byte,
1415 ecl_generic_peek_byte,
1416
1417 ecl_eformat_read_char,
1418 ecl_eformat_write_char,
1419 io_file_unread_char,
1420 ecl_generic_peek_char,
1421
1422 ecl_generic_read_vector,
1423 ecl_generic_write_vector,
1424
1425 wcon_stream_listen,
1426 wcon_stream_clear_input,
1427 ecl_generic_void,
1428 wcon_stream_force_output,
1429 wcon_stream_force_output,
1430
1431 ecl_generic_always_true, /* input_p */
1432 ecl_generic_always_true, /* output_p */
1433 ecl_generic_always_false,
1434 wcon_stream_element_type,
1435
1436 ecl_not_a_file_stream,
1437 ecl_generic_always_nil, /* get_position */
1438 ecl_generic_set_position,
1439 ecl_eformat_file_string_length,
1440 ecl_generic_column,
1441
1442 io_file_pathname,
1443 io_file_truename,
1444
1445 ecl_generic_close,
1446 };
1447
1448 #define CONTROL_Z 26
1449
1450 static cl_object
1451 maybe_make_windows_console_FILE(cl_object fname, FILE *f, enum ecl_smmode smm,
1452 cl_fixnum byte_size, int flags,
1453 cl_object external_format)
1454 {
1455 int desc = fileno(f);
1456 cl_object output;
1457 if (isatty(desc)) {
1458 output = ecl_make_stream_from_FILE
1459 (fname,
1460 (void*)_get_osfhandle(desc),
1461 ecl_smm_io_wcon,
1462 byte_size, flags,
1463 external_format);
1464 output->stream.eof_char = CONTROL_Z;
1465 } else {
1466 output = ecl_make_stream_from_FILE
1467 (fname, f, smm, byte_size, flags,
1468 external_format);
1469 }
1470 return output;
1471 }
1472
1473 static cl_object
1474 maybe_make_windows_console_fd(cl_object fname, int desc, enum ecl_smmode smm,
1475 cl_fixnum byte_size, int flags,
1476 cl_object external_format)
1477 {
1478 cl_object output;
1479 if (isatty(desc)) {
1480 output = ecl_make_stream_from_FILE
1481 (fname,
1482 (void*)_get_osfhandle(desc),
1483 ecl_smm_io_wcon,
1484 byte_size, flags,
1485 external_format);
1486 output->stream.eof_char = CONTROL_Z;
1487 } else {
1488 /* Windows changes the newline characters for \r\n
1489 * even when using read()/write() */
1490 if (ecl_option_values[ECL_OPT_USE_SETMODE_ON_FILES]) {
1491 _setmode(desc, _O_BINARY);
1492 } else {
1493 external_format = ECL_CONS_CDR(external_format);
1494 }
1495 output = ecl_make_file_stream_from_fd
1496 (fname, desc, smm,
1497 byte_size, flags,
1498 external_format);
1499 }
1500 return output;
1501 }
1502
1503 cl_object
1504 si_windows_codepage_encoding()
1505 {
1506 /* Mapping from windows codepages to encoding names used by ECL */
1507 DWORD cp = GetConsoleCP();
1508 cl_object encoding;
1509 switch (cp) {
1510 #ifdef ECL_UNICODE
1511 case 437: return ecl_make_keyword("DOS-CP437");
1512 case 708: return ecl_make_keyword("ISO-8859-6");
1513 case 850: return ecl_make_keyword("DOS-CP850");
1514 case 852: return ecl_make_keyword("DOS-CP852");
1515 case 855: return ecl_make_keyword("DOS-CP855");
1516 case 857: return ecl_make_keyword("DOS-CP857");
1517 case 858: return ecl_make_keyword("DOS-CP858");
1518 case 860: return ecl_make_keyword("DOS-CP860");
1519 case 861: return ecl_make_keyword("DOS-CP861");
1520 case 862: return ecl_make_keyword("DOS-CP862");
1521 case 863: return ecl_make_keyword("DOS-CP863");
1522 case 864: return ecl_make_keyword("DOS-CP864");
1523 case 865: return ecl_make_keyword("DOS-CP865");
1524 case 866: return ecl_make_keyword("DOS-CP866");
1525 case 869: return ecl_make_keyword("DOS-CP869");
1526 case 932: return ecl_make_keyword("WINDOWS-CP932");
1527 case 936: return ecl_make_keyword("WINDOWS-CP936");
1528 case 949: return ecl_make_keyword("WINDOWS-CP949");
1529 case 950: return ecl_make_keyword("WINDOWS-CP950");
1530 case 1200: return ecl_make_keyword("UCS-2LE");
1531 case 1201: return ecl_make_keyword("UCS-2BE");
1532 case 1250: return ecl_make_keyword("WINDOWS-CP1250");
1533 case 1251: return ecl_make_keyword("WINDOWS-CP1251");
1534 case 1252: return ecl_make_keyword("WINDOWS-CP1252");
1535 case 1253: return ecl_make_keyword("WINDOWS-CP1253");
1536 case 1254: return ecl_make_keyword("WINDOWS-CP1254");
1537 case 1255: return ecl_make_keyword("WINDOWS-CP1255");
1538 case 1256: return ecl_make_keyword("WINDOWS-CP1256");
1539 case 1257: return ecl_make_keyword("WINDOWS-CP1257");
1540 case 1258: return ecl_make_keyword("WINDOWS-CP1258");
1541 case 12000: return ecl_make_keyword("UCS-4LE");
1542 case 12001: return ecl_make_keyword("UCS-4BE");
1543 case 20932: return ecl_make_keyword("JISX0212");
1544 case 21866: return ecl_make_keyword("KOI8-U");
1545 case 28591: return ecl_make_keyword("ISO-8859-1");
1546 case 28592: return ecl_make_keyword("ISO-8859-2");
1547 case 28593: return ecl_make_keyword("ISO-8859-3");
1548 case 28594: return ecl_make_keyword("ISO-8859-4");
1549 case 28595: return ecl_make_keyword("ISO-8859-5");
1550 case 28596: return ecl_make_keyword("ISO-8859-6");
1551 case 28597: return ecl_make_keyword("ISO-8859-7");
1552 case 28598: return ecl_make_keyword("ISO-8859-8");
1553 case 28599: return ecl_make_keyword("ISO-8859-9");
1554 case 28603: return ecl_make_keyword("ISO-8859-13");
1555 case 28605: return ecl_make_keyword("ISO-8859-15");
1556 case 50220: return ecl_make_keyword("ISO-2022-JP");
1557 case 65001: return ecl_make_keyword("UTF-8");
1558 #endif
1559 /* Nothing we can do here, try our best with :pass-through */
1560 default: return @':pass-through';
1561 }
1562 }
1563 #else
1564 #define maybe_make_windows_console_FILE ecl_make_stream_from_FILE
1565 #define maybe_make_windows_console_fd ecl_make_file_stream_from_fd
1566 #endif
1567
1568 cl_object
1569 si_set_buffering_mode(cl_object stream, cl_object buffer_mode_symbol)
1570 {
1571 enum ecl_smmode mode = stream->stream.mode;
1572 int buffer_mode;
1573
1574 unlikely_if (!ECL_ANSI_STREAM_P(stream)) {
1575 FEerror("Cannot set buffer of ~A", 1, stream);
1576 }
1577
1578 if (buffer_mode_symbol == @':none' || Null(buffer_mode_symbol))
1579 buffer_mode = _IONBF;
1580 else if (buffer_mode_symbol == @':line' || buffer_mode_symbol == @':line-buffered')
1581 buffer_mode = _IOLBF;
1582 else if (buffer_mode_symbol == @':full' || buffer_mode_symbol == @':fully-buffered')
1583 buffer_mode = _IOFBF;
1584 else
1585 FEerror("Not a valid buffering mode: ~A", 1, buffer_mode_symbol);
1586
1587 if (mode == ecl_smm_output || mode == ecl_smm_io || mode == ecl_smm_input) {
1588 FILE *fp = IO_STREAM_FILE(stream);
1589
1590 if (buffer_mode != _IONBF) {
1591 cl_index buffer_size = BUFSIZ;
1592 char *new_buffer = ecl_alloc_atomic(buffer_size);
1593 stream->stream.buffer = new_buffer;
1594 setvbuf(fp, new_buffer, buffer_mode, buffer_size);
1595 } else
1596 setvbuf(fp, NULL, _IONBF, 0);
1597 }
1598 @(return stream);
1599 }
1600
1601 cl_object
1602 ecl_make_stream_from_FILE(cl_object fname, void *f, enum ecl_smmode smm,
1603 cl_fixnum byte_size, int flags, cl_object external_format)
1604 {
1605 cl_object stream;
1606 stream = ecl_alloc_stream();
1607 stream->stream.mode = (short)smm;
1608 stream->stream.closed = 0;
1609 switch (smm) {
1610 case ecl_smm_io:
1611 stream->stream.ops = ecl_duplicate_dispatch_table(&io_stream_ops);
1612 break;
1613 case ecl_smm_probe:
1614 case ecl_smm_input:
1615 stream->stream.ops = ecl_duplicate_dispatch_table(&input_stream_ops);
1616 break;
1617 case ecl_smm_output:
1618 stream->stream.ops = ecl_duplicate_dispatch_table(&output_stream_ops);
1619 break;
1620 #if defined(ECL_WSOCK)
1621 case ecl_smm_input_wsock:
1622 stream->stream.ops = ecl_duplicate_dispatch_table(&winsock_stream_input_ops);
1623 break;
1624 case ecl_smm_output_wsock:
1625 stream->stream.ops = ecl_duplicate_dispatch_table(&winsock_stream_output_ops);
1626 break;
1627 case ecl_smm_io_wsock:
1628 stream->stream.ops = ecl_duplicate_dispatch_table(&winsock_stream_io_ops);
1629 break;
1630 case ecl_smm_io_wcon:
1631 stream->stream.ops = ecl_duplicate_dispatch_table(&wcon_stream_io_ops);
1632 break;
1633 #endif
1634 default:
1635 FEerror("Not a valid mode ~D for ecl_make_stream_from_FILE", 1, ecl_make_fixnum(smm));
1636 }
1637 ecl_set_stream_elt_type(stream, byte_size, flags, external_format);
1638 IO_STREAM_FILENAME(stream) = fname;
1639 stream->stream.column = 0;
1640 IO_STREAM_FILE(stream) = f;
1641 stream->stream.last_op = 0;
1642 si_set_finalizer(stream, ECL_T);
1643 return stream;
1644 }
1645
1646 cl_object
1647 ecl_make_stream_from_fd(cl_object fname, int fd, enum ecl_smmode smm,
1648 cl_fixnum byte_size, int flags, cl_object external_format)
1649 {
1650 ecl_filename_char *mode; /* file open mode */
1651 FILE *fp; /* file pointer */
1652 switch(smm) {
1653 case ecl_smm_input:
1654 mode = OPEN_R;
1655 break;
1656 case ecl_smm_output:
1657 mode = OPEN_W;
1658 break;
1659 case ecl_smm_io:
1660 mode = OPEN_RW;
1661 break;
1662 #if defined(ECL_WSOCK)
1663 case ecl_smm_input_wsock:
1664 case ecl_smm_output_wsock:
1665 case ecl_smm_io_wsock:
1666 case ecl_smm_io_wcon:
1667 break;
1668 #endif
1669 default:
1670 FEerror("make_stream: wrong mode", 0);
1671 }
1672 #if defined(ECL_WSOCK)
1673 if (smm == ecl_smm_input_wsock || smm == ecl_smm_output_wsock || smm == ecl_smm_io_wsock || smm == ecl_smm_io_wcon)
1674 fp = (FILE*)fd;
1675 else
1676 fp = safe_fdopen(fd, mode);
1677 #else
1678 fp = safe_fdopen(fd, mode);
1679 #endif
1680 if (fp == NULL) {
1681 FElibc_error("Unable to create stream for file descriptor ~D",
1682 1, ecl_make_integer(fd));
1683 }
1684 return ecl_make_stream_from_FILE(fname, fp, smm, byte_size, flags,
1685 external_format);
1686 }
1687
1688 int
1689 ecl_stream_to_handle(cl_object s, bool output)
1690 {
1691 BEGIN:
1692 if (ecl_unlikely(!ECL_ANSI_STREAM_P(s)))
1693 return -1;
1694 switch ((enum ecl_smmode)s->stream.mode) {
1695 case ecl_smm_input:
1696 if (output) return -1;
1697 return fileno(IO_STREAM_FILE(s));
1698 case ecl_smm_input_file:
1699 if (output) return -1;
1700 return IO_FILE_DESCRIPTOR(s);
1701 case ecl_smm_output:
1702 if (!output) return -1;
1703 return fileno(IO_STREAM_FILE(s));
1704 case ecl_smm_output_file:
1705 if (!output) return -1;
1706 return IO_FILE_DESCRIPTOR(s);
1707 case ecl_smm_io:
1708 return fileno(IO_STREAM_FILE(s));
1709 case ecl_smm_io_file:
1710 return IO_FILE_DESCRIPTOR(s);
1711 case ecl_smm_synonym:
1712 s = SYNONYM_STREAM_STREAM(s);
1713 goto BEGIN;
1714 case ecl_smm_two_way:
1715 s = output? TWO_WAY_STREAM_OUTPUT(s) : TWO_WAY_STREAM_INPUT(s);
1716 goto BEGIN;
1717 #if defined(ECL_WSOCK)
1718 case ecl_smm_input_wsock:
1719 case ecl_smm_output_wsock:
1720 case ecl_smm_io_wsock:
1721 #endif
1722 #if defined(ECL_MS_WINDOWS_HOST)
1723 case ecl_smm_io_wcon:
1724 #endif
1725 default:
1726 return -1;
1727 }
1728 }
1729
1730 /**********************************************************************
1731 * FILE OPENING AND CLOSING
1732 */
1733
1734 static void
1735 FEinvalid_option(cl_object option, cl_object value)
1736 {
1737 FEerror("Invalid value op option ~A: ~A", 2, option, value);
1738 }
1739
1740 static int
1741 smmode_to_open_flag(enum ecl_smmode smm)
1742 {
1743 switch (smm) {
1744 case ecl_smm_probe:
1745 case ecl_smm_input:
1746 return O_RDONLY;
1747 case ecl_smm_output:
1748 return O_WRONLY;
1749 case ecl_smm_io:
1750 return O_RDWR;
1751 default:
1752 FEerror("Illegal stream mode ~S", 1, ecl_make_fixnum(smm));
1753 }
1754 }
1755
1756 cl_object
1757 ecl_open_stream(cl_object fn, enum ecl_smmode smm, cl_object if_exists,
1758 cl_object if_does_not_exist, cl_fixnum byte_size,
1759 int flags, cl_object external_format)
1760 {
1761 cl_object output;
1762 int fd, open_flags = smmode_to_open_flag(smm) | O_BINARY;
1763 bool appending = 0;
1764 #if defined(ECL_MS_WINDOWS_HOST)
1765 ecl_mode_t mode = _S_IREAD | _S_IWRITE;
1766 #else
1767 ecl_mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
1768 #endif
1769 /* FILENAME is used only to access the actual file while a stream
1770 remembers the original pathname FN. -- jd 2020-03-27 */
1771 cl_object filename = si_coerce_to_filename(fn);
1772 ecl_filename_char *fname = ecl_filename_self(filename);
1773
1774 if (if_does_not_exist == @':create') {
1775 open_flags |= O_CREAT;
1776 if ((smm == ecl_smm_output || smm == ecl_smm_io) &&
1777 (if_exists == ECL_NIL || if_exists == @':error' || if_exists == @':rename')) {
1778 open_flags |= O_EXCL;
1779 }
1780 } else if (if_does_not_exist != ECL_NIL && if_does_not_exist != @':error') {
1781 FEinvalid_option(@':if-does-not-exist', if_does_not_exist);
1782 }
1783 if (if_exists == @':rename_and_delete' ||
1784 if_exists == @':new_version' ||
1785 if_exists == @':supersede' ||
1786 if_exists == @':truncate') {
1787 if (smm == ecl_smm_output || smm == ecl_smm_io) {
1788 open_flags |= O_TRUNC;
1789 }
1790 } else if (if_exists == @':append') {
1791 if (smm == ecl_smm_output || smm == ecl_smm_io) {
1792 appending = 1;
1793 }
1794 } else if (if_exists != ECL_NIL &&
1795 if_exists != @':error' &&
1796 if_exists != @':rename' &&
1797 if_exists != @':overwrite') {
1798 FEinvalid_option(@':if-exists', if_exists);
1799 }
1800 if (flags & ECL_STREAM_CLOSE_ON_EXEC) {
1801 open_flags |= O_CLOEXEC;
1802 }
1803 if (flags & ECL_STREAM_NONBLOCK) {
1804 open_flags |= O_NONBLOCK;
1805 }
1806
1807 fd = safe_open(fname, open_flags, mode);
1808 if (fd < 0) {
1809 if (errno == ENOENT && if_does_not_exist == ECL_NIL) {
1810 return ECL_NIL;
1811 } else if (errno == EEXIST) {
1812 if (if_exists == ECL_NIL) {
1813 return ECL_NIL;
1814 } else if (if_exists == @':error') {
1815 FEcannot_open(fn);
1816 } else if (if_exists == @':rename') {
1817 fd = ecl_backup_open(fname, smmode_to_open_flag(smm)|O_CREAT, mode);
1818 unlikely_if (fd < 0) FEcannot_open(fn);
1819 }
1820 } else {
1821 FEcannot_open(fn);
1822 }
1823 }
1824
1825 if (smm == ecl_smm_probe) {
1826 safe_close(fd);
1827 output = ecl_make_file_stream_from_fd(fn, -1, smm, byte_size, flags, external_format);
1828 ecl_generic_close(output);
1829 return output;
1830 }
1831 if (flags & ECL_STREAM_C_STREAM) {
1832 FILE *fp = 0;
1833 switch (smm) {
1834 case ecl_smm_probe:
1835 /* never happens (returns earlier) */
1836 case ecl_smm_input:
1837 fp = safe_fdopen(fd, OPEN_R);
1838 break;
1839 case ecl_smm_output:
1840 fp = safe_fdopen(fd, OPEN_W);
1841 break;
1842 case ecl_smm_io:
1843 fp = safe_fdopen(fd, OPEN_RW);
1844 break;
1845 default:;
1846 /* never reached (errors earlier) */
1847 }
1848 if (fp == NULL) {
1849 FEcannot_open(fn);
1850 }
1851 output = ecl_make_stream_from_FILE(fn, fp, smm, byte_size, flags, external_format);
1852 si_set_buffering_mode(output, byte_size? @':full' : @':line');
1853 } else {
1854 output = ecl_make_file_stream_from_fd(fn, fd, smm, byte_size, flags, external_format);
1855 }
1856
1857 output->stream.flags |= ECL_STREAM_MIGHT_SEEK;
1858 si_set_finalizer(output, ECL_T);
1859 /* Set file pointer to the correct position */
1860 ecl_file_position_set(output, appending? ECL_NIL : ecl_make_fixnum(0));
1861 return output;
1862 }
1863
1864 /**********************************************************************
1865 * BACKEND
1866 */
1867
1868 #if defined(ECL_MS_WINDOWS_HOST)
1869 static int
1870 fd_listen(cl_object stream, int fileno)
1871 {
1872 HANDLE hnd = (HANDLE)_get_osfhandle(fileno);
1873 switch (GetFileType(hnd)) {
1874 case FILE_TYPE_CHAR: {
1875 DWORD dw, dw_read, cm;
1876 if (GetNumberOfConsoleInputEvents(hnd, &dw)) {
1877 unlikely_if (!GetConsoleMode(hnd, &cm))
1878 FEwin32_error("GetConsoleMode() failed", 0);
1879 if (dw > 0) {
1880 PINPUT_RECORD recs = (PINPUT_RECORD)GC_MALLOC(sizeof(INPUT_RECORD)*dw);
1881 int i;
1882 unlikely_if (!PeekConsoleInput(hnd, recs, dw, &dw_read))
1883 FEwin32_error("PeekConsoleInput failed()", 0);
1884 if (dw_read > 0) {
1885 if (cm & ENABLE_LINE_INPUT) {
1886 for (i=0; i<dw_read; i++)
1887 if (recs[i].EventType == KEY_EVENT &&
1888 recs[i].Event.KeyEvent.bKeyDown &&
1889 recs[i].Event.KeyEvent.uChar.AsciiChar == 13)
1890 return ECL_LISTEN_AVAILABLE;
1891 } else {
1892 for (i=0; i<dw_read; i++)
1893 if (recs[i].EventType == KEY_EVENT &&
1894 recs[i].Event.KeyEvent.bKeyDown &&
1895 recs[i].Event.KeyEvent.uChar.AsciiChar != 0)
1896 return ECL_LISTEN_AVAILABLE;
1897 }
1898 }
1899 }
1900 return ECL_LISTEN_NO_CHAR;
1901 } else {
1902 FEwin32_error("GetNumberOfConsoleInputEvents() failed", 0);
1903 }
1904 break;
1905 }
1906 case FILE_TYPE_DISK:
1907 /* use regular file code below */
1908 break;
1909 case FILE_TYPE_PIPE: {
1910 DWORD dw;
1911 if (PeekNamedPipe(hnd, NULL, 0, NULL, &dw, NULL))
1912 return (dw > 0 ? ECL_LISTEN_AVAILABLE : ECL_LISTEN_NO_CHAR);
1913 else if (GetLastError() == ERROR_BROKEN_PIPE)
1914 return ECL_LISTEN_EOF;
1915 else
1916 FEwin32_error("PeekNamedPipe() failed", 0);
1917 break;
1918 }
1919 default:
1920 FEerror("Unsupported Windows file type: ~A", 1, ecl_make_fixnum(GetFileType(hnd)));
1921 break;
1922 }
1923 return ECL_LISTEN_FALLBACK;
1924 }
1925 #else
1926 static int
1927 fd_listen(cl_object stream, int fileno)
1928 {
1929 /* Method 1: poll, see POLL(2)
1930 Method 2: select, see SELECT(2)
1931 Method 3: ioctl FIONREAD, see FILIO(4)
1932 Method 4: read a byte. Use non-blocking I/O if poll or select were not
1933 available. */
1934 int result;
1935 #if defined(HAVE_POLL)
1936 struct pollfd fd = {fileno, POLLIN, 0};
1937 restart_poll:
1938 result = poll(&fd, 1, 0);
1939 if (ecl_unlikely(result < 0)) {
1940 if (errno == EINTR)
1941 goto restart_poll;
1942 else
1943 goto listen_error;
1944 }
1945 if (fd.revents == 0) {
1946 return ECL_LISTEN_NO_CHAR;
1947 }
1948 /* When read() returns a result without blocking, this can also be
1949 EOF! (Example: Linux and pipes.) We therefore refrain from simply
1950 doing { return ECL_LISTEN_AVAILABLE; } and instead try methods
1951 3 and 4. */
1952 #elif defined(HAVE_SELECT)
1953 fd_set fds;
1954 struct timeval tv = {0, 0};
1955 FD_ZERO(&fds);
1956 FD_SET(fileno, &fds);
1957 restart_select:
1958 result = select(fileno + 1, &fds, NULL, NULL, &tv);
1959 if (ecl_unlikely(result < 0)) {
1960 if (errno == EINTR)
1961 goto restart_select;
1962 if (errno != EBADF) /* UNIX_LINUX returns EBADF for files! */
1963 goto listen_error;
1964 } else if (result == 0) {
1965 return ECL_LISTEN_NO_CHAR;
1966 }
1967 #endif
1968 #ifdef FIONREAD
1969 long c = 0;
1970 result = ioctl(fileno, FIONREAD, &c);
1971 if (result == 0) {
1972 return (c > 0) ? ECL_LISTEN_AVAILABLE : ECL_LISTEN_EOF;
1973 } else if (result < 0 && errno != ENOTTY && errno != EINVAL) {
1974 goto listen_error;
1975 }
1976 #endif
1977 cl_index byte;
1978 restart_read:
1979 #if !defined(HAVE_POLL) && !defined(HAVE_SELECT)
1980 {
1981 int flags = fcntl(fileno, F_GETFL, 0);
1982 int read_errno;
1983 fcntl(fileno, F_SETFL, flags | O_NONBLOCK);
1984 result = read(fileno, &byte, 1);
1985 read_errno = errno;
1986 fcntl(fileno, F_SETFL, flags);
1987 errno = read_errno;
1988 }
1989 #else
1990 result = read(fileno, &byte, 1);
1991 #endif
1992 if (result < 0) {
1993 if (errno == EINTR)
1994 goto restart_read;
1995 if (errno == EAGAIN || errno == EWOULDBLOCK)
1996 return ECL_LISTEN_NO_CHAR;
1997 else
1998 goto listen_error;
1999 }
2000
2001 if (result == 0) {
2002 return ECL_LISTEN_EOF;
2003 }
2004
2005 stream->stream.byte_stack = CONS(ecl_make_fixnum(byte), stream->stream.byte_stack);
2006 return ECL_LISTEN_AVAILABLE;
2007 listen_error:
2008 file_libc_error(@[stream-error], stream, "Error while listening to stream.", 0);
2009 }
2010 #endif
2011
2012 static int
2013 file_listen(cl_object stream, FILE *fp)
2014 {
2015 int aux;
2016 if (feof(fp) || ferror(fp))
2017 return ECL_LISTEN_EOF;
2018 #ifdef FILE_CNT
2019 if (FILE_CNT(fp) > 0)
2020 return ECL_LISTEN_AVAILABLE;
2021 #endif
2022 aux = fd_listen(stream, fileno(fp));
2023 if (aux != ECL_LISTEN_FALLBACK)
2024 return aux;
2025 /* This code is portable, and implements the expected behavior for regular files.
2026 It will fail on noninteractive streams. */
2027 {
2028 /* regular file */
2029 ecl_off_t old_pos = ecl_ftello(fp), end_pos;
2030 unlikely_if (old_pos == -1 ||
2031 ecl_fseeko(fp, 0, SEEK_END) != 0)
2032 file_libc_error(@[file-error], stream,
2033 "Unable to check file position", 0);
2034 end_pos = ecl_ftello(fp);
2035 unlikely_if (ecl_fseeko(fp, old_pos, SEEK_SET) != 0)
2036 file_libc_error(@[file-error], stream,
2037 "Unable to check file position", 0);
2038 return (end_pos > old_pos ? ECL_LISTEN_AVAILABLE : ECL_LISTEN_EOF);
2039 }
2040 return !ECL_LISTEN_AVAILABLE;
2041 }
2042
2043 /* Compilation of this function on some platforms may give a warning:
2044 "right shift count >= width of type [-Werror=shift-count-overflow]"
2045 but on these platforms this branch is never encountered.
2046
2047 FIXME: this can probably be conditionaly defined in #if … #endif */
2048 cl_object
2049 ecl_off_t_to_integer(ecl_off_t offset)
2050 {
2051 cl_object output;
2052 if (sizeof(ecl_off_t) == sizeof(cl_fixnum)) {
2053 output = ecl_make_integer(offset);
2054 } else if (offset <= MOST_POSITIVE_FIXNUM) {
2055 output = ecl_make_fixnum((cl_fixnum)offset);
2056 } else {
2057 cl_object y = _ecl_big_register0();
2058 if (sizeof(ECL_BIGNUM_LIMBS(y)[0]) == sizeof(cl_index)) {
2059 ECL_BIGNUM_LIMBS(y)[0] = (cl_index)offset;
2060 offset >>= ECL_FIXNUM_BITS;
2061 ECL_BIGNUM_LIMBS(y)[1] = offset;
2062 ECL_BIGNUM_SIZE(y) = offset? 2 : 1;
2063 } else if (sizeof(ECL_BIGNUM_LIMBS(y)[0]) >= sizeof(ecl_off_t)) {
2064 ECL_BIGNUM_LIMBS(y)[0] = offset;
2065 ECL_BIGNUM_SIZE(y) = 1;
2066 }
2067 output = _ecl_big_register_normalize(y);
2068 }
2069 return output;
2070 }
2071
2072 /* Compilation of this function on some platforms may give a warning:
2073 "left shift count >= width of type [-Werror=shift-count-overflow]"
2074 but on these platforms this branch is never encountered.
2075
2076 FIXME: this can probably be conditionaly defined in #if … #endif */
2077 ecl_off_t
2078 ecl_integer_to_off_t(cl_object offset)
2079 {
2080 ecl_off_t output = 0;
2081 if (sizeof(ecl_off_t) == sizeof(cl_fixnum)) {
2082 output = fixint(offset);
2083 } else if (ECL_FIXNUMP(offset)) {
2084 output = fixint(offset);
2085 } else if (ECL_BIGNUMP(offset)) {
2086 if (sizeof(ECL_BIGNUM_LIMBS(offset)[0]) == sizeof(cl_index)) {
2087 if (ECL_BIGNUM_SIZE(offset) > 2) {
2088 goto ERROR;
2089 }
2090 if (ECL_BIGNUM_SIZE(offset) == 2) {
2091 output = ECL_BIGNUM_LIMBS(offset)[1];
2092 output <<= ECL_FIXNUM_BITS;
2093 }
2094 output += ECL_BIGNUM_LIMBS(offset)[0];
2095 } else if (sizeof(ECL_BIGNUM_LIMBS(offset)[0]) >= sizeof(ecl_off_t)) {
2096 if (ECL_BIGNUM_SIZE(offset) > 1) {
2097 goto ERROR;
2098 }
2099 output = ECL_BIGNUM_LIMBS(offset)[0];
2100 }
2101 } else {
2102 ERROR: FEerror("Not a valid file offset: ~S", 1, offset);
2103 }
2104 return output;
2105 }
2106
2107 /**********************************************************************
2108 * ERROR MESSAGES
2109 */
2110
2111 static void
2112 cannot_close(cl_object stream)
2113 {
2114 file_libc_error(@[file-error], stream, "Stream cannot be closed", 0);
2115 }
2116
2117 static void
2118 file_libc_error(cl_object error_type, cl_object stream,
2119 const char *msg, int narg, ...)
2120 {
2121 ecl_va_list args;
2122 cl_object rest, error = _ecl_strerror(errno);
2123
2124 ecl_va_start(args, narg, narg, 0);
2125 rest = cl_grab_rest_args(args);
2126 ecl_va_end(args);
2127
2128 si_signal_simple_error(4, (cl_object)(cl_symbols + ecl_fixnum(error_type)), ECL_NIL,
2129 @"~?~%C library explanation: ~A.",
2130 cl_list(3, ecl_make_constant_base_string(msg,-1), rest,
2131 error));
2132 _ecl_unexpected_return();
2133 }
2134
2135 static void
2136 maybe_clearerr(cl_object strm)
2137 {
2138 int t = strm->stream.mode;
2139 if (t == ecl_smm_io || t == ecl_smm_output || t == ecl_smm_input) {
2140 FILE *f = IO_STREAM_FILE(strm);
2141 if (f != NULL) clearerr(f);
2142 }
2143 }
2144
2145 static int
2146 restartable_io_error(cl_object strm, const char *s)
2147 {
2148 cl_env_ptr the_env = ecl_process_env();
2149 volatile int old_errno = errno;
2150 /* ecl_disable_interrupts(); ** done by caller */
2151 maybe_clearerr(strm);
2152 ecl_enable_interrupts_env(the_env);
2153 if (old_errno == EINTR) {
2154 return 1;
2155 } else {
2156 file_libc_error(@[stream-error], strm,
2157 "C operation (~A) signaled an error.",
2158 1, ecl_make_constant_base_string(s, strlen(s)));
2159 return 0;
2160 }
2161 }
2162
2163 static void
2164 io_error(cl_object strm)
2165 {
2166 cl_env_ptr the_env = ecl_process_env();
2167 /* ecl_disable_interrupts(); ** done by caller */
2168 maybe_clearerr(strm);
2169 ecl_enable_interrupts_env(the_env);
2170 file_libc_error(@[stream-error], strm,
2171 "Read or write operation signaled an error", 0);
2172 }
2173
2174 static void
2175 wrong_file_handler(cl_object strm)
2176 {
2177 FEerror("Internal error: stream ~S has no valid C file handler.", 1, strm);
2178 }
2179
2180 #if defined(ECL_WSOCK)
2181 static void
2182 wsock_error( const char *err_msg, cl_object strm )
2183 {
2184 char *msg;
2185 cl_object msg_obj;
2186 /* ecl_disable_interrupts(); ** done by caller */
2187 {
2188 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
2189 0, WSAGetLastError(), 0, (void*)&msg, 0, NULL);
2190 msg_obj = ecl_make_simple_base_string(msg,-1);
2191 LocalFree(msg);
2192 }
2193 ecl_enable_interrupts();
2194 FEerror(err_msg, 2, strm, msg_obj);
2195 }
2196 #endif
2197
2198 /* -- This function hooks up OS streams into Lisp standard streams ---------- */
2199
2200 void
2201 init_file(void)
2202 {
2203 int flags;
2204 cl_object standard_input;
2205 cl_object standard_output;
2206 cl_object error_output;
2207 cl_object aux;
2208 cl_object null_stream;
2209 cl_object external_format = ECL_NIL;
2210 #if defined(ECL_MS_WINDOWS_HOST)
2211 /* We start out with :pass-through external format for standard input/output
2212 * for bootstrap reasons (some of the external format support is implemented
2213 * in lisp and not available on start of ECL). The correct format is later on
2214 * set using the encoding specified by the current codepage. */
2215 external_format = cl_list(2, @':pass-through', @':crlf');
2216 # ifdef ECL_UNICODE
2217 flags = 0;
2218 # else
2219 flags = ECL_STREAM_DEFAULT_FORMAT;
2220 # endif
2221 #else
2222 flags = ECL_STREAM_DEFAULT_FORMAT;
2223 #endif
2224
2225 null_stream = ecl_make_stream_from_FILE(@"/dev/null",
2226 NULL, ecl_smm_io, 8, flags, external_format);
2227 ecl_generic_close(null_stream);
2228 null_stream = cl_make_two_way_stream(null_stream, cl_make_broadcast_stream(0));
2229 cl_core.null_stream = null_stream;
2230
2231 /* We choose C streams by default only when _not_ using threads.
2232 * The reason is that C streams block on I/O operations. */
2233 #if !defined(ECL_THREADS)
2234 standard_input = maybe_make_windows_console_FILE(@"stdin",
2235 stdin, ecl_smm_input, 8, flags, external_format);
2236 standard_output = maybe_make_windows_console_FILE(@"stdout",
2237 stdout, ecl_smm_output, 8, flags, external_format);
2238 error_output = maybe_make_windows_console_FILE(@"stderr",
2239 stderr, ecl_smm_output, 8, flags, external_format);
2240 #else
2241 standard_input = maybe_make_windows_console_fd(@"stdin",
2242 STDIN_FILENO, ecl_smm_input_file, 8, flags,
2243 external_format);
2244 standard_output = maybe_make_windows_console_fd(@"stdout",
2245 STDOUT_FILENO, ecl_smm_output_file, 8, flags,
2246 external_format);
2247 error_output = maybe_make_windows_console_fd(@"stderr",
2248 STDERR_FILENO, ecl_smm_output_file, 8, flags,
2249 external_format);
2250 #endif
2251 cl_core.standard_input = standard_input;
2252 ECL_SET(@'ext::+process-standard-input+', standard_input);
2253 ECL_SET(@'*standard-input*', standard_input);
2254 cl_core.standard_output = standard_output;
2255 ECL_SET(@'ext::+process-standard-output+', standard_output);
2256 ECL_SET(@'*standard-output*', standard_output);
2257 ECL_SET(@'*trace-output*', standard_output);
2258 cl_core.error_output = error_output;
2259 ECL_SET(@'ext::+process-error-output+', error_output);
2260 ECL_SET(@'*error-output*', error_output);
2261
2262 cl_core.terminal_io = aux
2263 = cl_make_two_way_stream(standard_input, standard_output);
2264
2265 ECL_SET(@'*terminal-io*', aux);
2266 aux = cl_make_synonym_stream(@'*terminal-io*');
2267 ECL_SET(@'*query-io*', aux);
2268 ECL_SET(@'*debug-io*', aux);
2269 }