Debian Codegraph @

src/port.c

raw
1 /*
2 * port.c - port implementation
3 *
4 * Copyright (c) 2000-2024 Shiro Kawai <[email protected]>
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 *
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 *
17 * 3. Neither the name of the authors nor the names of its contributors
18 * may be used to endorse or promote products derived from this
19 * software without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
27 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 */
33
34 #define LIBGAUCHE_BODY
35 #include "gauche.h"
36 #include "gauche/priv/configP.h"
37 #include "gauche/priv/portP.h"
38 #include "gauche/priv/builtin-syms.h"
39
40 #include <string.h>
41 #include <fcntl.h>
42 #include <errno.h>
43 #include <ctype.h>
44
45 #undef MAX
46 #undef MIN
47 #define MAX(a, b) ((a)>(b)? (a) : (b))
48 #define MIN(a, b) ((a)<(b)? (a) : (b))
49
50 #define PORT_BUFFER_MODE(p) \
51 (PORT_BUF(p)->mode & SCM_PORT_BUFFER_MODE_MASK)
52 #define PORT_BUFFER_SIGPIPE_SENSITIVE_P(p) \
53 (PORT_BUF(p)->mode & SCM_PORT_BUFFER_SIGPIPE_SENSITIVE)
54 #define PORT_BUFFER_ROOM(p) \
55 (PORT_BUF(p)->buffer + PORT_BUF(p)->size - PORT_BUF(p)->end)
56 #define PORT_BUFFER_AVAIL(p) \
57 (PORT_BUF(p)->current - PORT_BUF(p)->buffer)
58
59 #define PORT_UNGOTTEN(p) (P_(p)->ungotten)
60 #define PORT_SCRATCH(p) (P_(p)->scratch)
61 #define PORT_LINE(p) (P_(p)->line)
62 #define PORT_BYTES(p) (P_(p)->bytes)
63 #define PORT_COLUMN(p) (P_(p)->column)
64 #define PORT_ATTRS(p) (P_(p)->attrs)
65 #define PORT_SAVED_POS(p) (P_(p)->savedPos)
66 #define PORT_LINK(p) (P_(p)->link)
67
68 /* Parameter location for the global reader lexical mode, from which
69 ports inherit. */
70 static ScmPrimitiveParameter *readerLexicalMode;
71
72 /*================================================================
73 * Class stuff
74 */
75
76 static void port_print(ScmObj obj, ScmPort *port, ScmWriteContext *ctx);
77 static void port_finalize(ScmObj obj, void* data);
78 static void register_buffered_port(ScmPort *port);
79 static void unregister_buffered_port(ScmPort *port);
80 static void bufport_flush(ScmPort*, ScmSize, int);
81 static void file_closer(ScmPort *p);
82 static int file_buffered_port_p(ScmPort *p); /* for Scm_PortFdDup */
83 static void file_buffered_port_set_fd(ScmPort *p, int fd); /* ditto */
84
85 static ScmObj get_port_name(ScmPort *port)
86 {
87 return Scm_PortName(port);
88 }
89
90 static ScmObj get_port_current_line(ScmPort *port)
91 {
92 return SCM_MAKE_INT(Scm_PortLine(port));
93 }
94
95 static ScmObj get_port_current_column(ScmPort *port)
96 {
97 return SCM_MAKE_INT(PORT_COLUMN(port));
98 }
99
100 static void set_port_current_column(ScmPort *port, ScmObj val)
101 {
102 if (SCM_INTP(val)) {
103 PORT_COLUMN(port) = SCM_INT_VALUE(val);
104 }
105 }
106
107 static ScmObj get_port_buffering(ScmPort *port)
108 {
109 return Scm_GetPortBufferingModeAsKeyword(port);
110 }
111
112 static void set_port_buffering(ScmPort *port, ScmObj val)
113 {
114 if (SCM_PORT_TYPE(port) != SCM_PORT_FILE) {
115 Scm_Error("can't set buffering mode to non-buffered port: %S", port);
116 }
117 Scm_SetPortBufferingMode(port,Scm_BufferingMode(val,port->direction,-1));
118 }
119
120 static ScmObj get_port_sigpipe_sensitive(ScmPort *port)
121 {
122 return SCM_MAKE_BOOL(Scm_GetPortBufferSigpipeSensitive(port));
123 }
124
125 static void set_port_sigpipe_sensitive(ScmPort *port, ScmObj val)
126 {
127 Scm_SetPortBufferSigpipeSensitive(port, SCM_BOOL_VALUE(val));
128 }
129
130 static ScmObj get_port_link(ScmPort *port)
131 {
132 return PORT_LINK(port);
133 }
134
135 static ScmClassStaticSlotSpec port_slots[] = {
136 SCM_CLASS_SLOT_SPEC("name", get_port_name, NULL),
137 SCM_CLASS_SLOT_SPEC("buffering", get_port_buffering,
138 set_port_buffering),
139 SCM_CLASS_SLOT_SPEC("sigpipe-sensitive?", get_port_sigpipe_sensitive,
140 set_port_sigpipe_sensitive),
141 SCM_CLASS_SLOT_SPEC("current-line", get_port_current_line, NULL),
142 SCM_CLASS_SLOT_SPEC("current-column", get_port_current_column,
143 set_port_current_column),
144 SCM_CLASS_SLOT_SPEC("link", get_port_link, NULL),
145 SCM_CLASS_SLOT_SPEC_END()
146 };
147
148 SCM_DEFINE_BASE_CLASS(Scm_PortClass,
149 ScmPort, /* instance type */
150 port_print, NULL, NULL, NULL, NULL);
151
152 static ScmClass *port_cpl[] = {
153 SCM_CLASS_STATIC_PTR(Scm_PortClass),
154 SCM_CLASS_STATIC_PTR(Scm_TopClass),
155 NULL
156 };
157
158 SCM_DEFINE_BASE_CLASS(Scm_CodingAwarePortClass,
159 ScmPort, /* instance type */
160 port_print, NULL, NULL, NULL, port_cpl);
161
162 /*================================================================
163 * Common
164 */
165
166 /* Cleaning up:
167 * The underlying file descriptor/stream may be closed when the port
168 * is explicitly closed by close-port, or implicitly destroyed by the
169 * garbage collector. To keep consistency, Scheme ports should never
170 * share the same file descriptor. However, C code and Scheme port
171 * may share the same file descriptor for efficiency (e.g. stdios).
172 * In such cases, it is C code's responsibility to destroy the port.
173 *
174 * Port_clenaup routine may be called when the port is closed or
175 * finalized. If port is finalized before it is properly closed,
176 * we want to call close procedure of the underlying implementation.
177 * However, the fact that the port is being finalized means the
178 * extra structure used by the underlying implementation may have
179 * already GC-ed. The FINAL flag indicates that.
180
181 */
182 static void port_cleanup(ScmPort *port, _Bool final)
183 {
184 if (SCM_PORT_CLOSED_P(port)) return;
185
186 /* NB: Flush or close subroutine may raise an error and leave the port
187 not fully cleaned up. For now, we leave the port 'non-closed' state,
188 so this part may be called again---it's up to the close routine to
189 handle the situation gracefully.
190 */
191 switch (SCM_PORT_TYPE(port)) {
192 case SCM_PORT_FILE:
193 if (SCM_PORT_DIR(port) == SCM_PORT_OUTPUT) {
194 if (!SCM_PORT_ERROR_OCCURRED_P(port) && !final) {
195 bufport_flush(port, 0, TRUE);
196 }
197 if (!(SCM_PORT_FLAGS(port) & SCM_PORT_TRANSIENT)) {
198 unregister_buffered_port(port);
199 }
200 }
201 ScmPortBuffer *buf = Scm_PortBufferStruct(port);
202 if (!final && port->ownerp && buf->closer) buf->closer(port);
203 break;
204 case SCM_PORT_PROC:
205 if (!final && PORT_VT(port)->Close) PORT_VT(port)->Close(port);
206 break;
207 default:
208 break;
209 }
210 (void)SCM_INTERNAL_FASTLOCK_DESTROY(P_(port)->lock);
211
212 SCM_PORT_CLOSED_P(port) = TRUE;
213 /* avoid unnecessary finalization */
214 Scm_UnregisterFinalizer(SCM_OBJ(port));
215 }
216
217 /* called by GC.
218 NB: We only attach finalizers for SCM_PORT_FILE and SCM_PORT_PROC.
219 Attaching finalizer has overhead, which is not negligible when
220 string ports are frequently created.
221 Cf. https://github.com/shirok/Gauche/issues/937
222 */
223 static void port_finalize(ScmObj obj, void* data SCM_UNUSED)
224 {
225 if (PORT_FILE_EXTDATA_P(obj)) {
226 GC_unregister_disappearing_link((void**)&PORT_BUF(obj)->data);
227 }
228 if (PORT_PROC_EXTDATA_P(obj)) {
229 GC_unregister_disappearing_link((void**)&PORT_VT(obj)->data);
230 }
231 port_cleanup(SCM_PORT(obj),
232 PORT_FILE_EXTDATA_GONE_P(obj)||PORT_PROC_EXTDATA_GONE_P(obj));
233 }
234
235 /*
236 * Internal Constructor.
237 * If this port owns the underlying file descriptor/stream,
238 * ownerp must be TRUE.
239 */
240 static ScmPort *make_port(ScmClass *klass, ScmObj name, int dir, int type)
241 {
242 ScmPortImpl *port = (ScmPortImpl*)SCM_NEW_INSTANCE(ScmPort, klass);
243
244 port->direction = dir & SCM_PORT_IOMASK;
245 port->type = type;
246 port->scrcnt = 0;
247 port->ungotten = SCM_CHAR_INVALID;
248 port->closed = FALSE;
249 port->error = FALSE;
250 port->ownerp = FALSE;
251 port->flags =
252 SCM_VM_RUNTIME_FLAG_IS_SET(Scm_VM(), SCM_CASE_FOLD)
253 ? SCM_PORT_CASE_FOLD
254 : 0;
255 port->savedPos = SCM_UNBOUND;
256 (void)SCM_INTERNAL_FASTLOCK_INIT(port->lock);
257 port->lockOwner = NULL;
258 port->lockCount = 0;
259 (void)SCM_INTERNAL_FASTLOCK_INIT(port->attrlock);
260 port->writeState = NULL;
261 port->line = 1;
262 port->bytes = 0;
263 port->column = 0;
264 /* Initial port attributes.
265 ((name <name> . #f) ; read-only
266 (reader-lexical-mode <lexical-mode>))
267 See "Port Attributes" section below for the format of attrs. */
268 port->attrs = SCM_LIST2(Scm_Cons(SCM_SYM_NAME,
269 Scm_Cons(name, SCM_FALSE)),
270 SCM_LIST2(SCM_SYM_READER_LEXICAL_MODE,
271 Scm_ReaderLexicalMode()));
272 port->link = SCM_FALSE;
273 port->internalFlags = 0;
274
275 /* If fast lock doesn't require finalization, we can skip to register
276 a finalizer for every string port. It reduces significant overhead. */
277 #if defined(SCM_INTERNAL_FASTLOCK_FINALIZATION_NOT_REQUIRED)
278 if (type == SCM_PORT_FILE || type == SCM_PORT_PROC) {
279 Scm_RegisterFinalizer(SCM_OBJ(port), port_finalize, NULL);
280 }
281 #else
282 Scm_RegisterFinalizer(SCM_OBJ(port), port_finalize, NULL);
283 #endif
284
285 return SCM_PORT(port);
286 }
287
288 /*
289 * Close
290 */
291 void Scm_ClosePort(ScmPort *port)
292 {
293 ScmVM *vm = Scm_VM();
294 PORT_LOCK(port, vm);
295 PORT_SAFE_CALL(port,
296 do {
297 if (!SCM_PORT_CLOSED_P(port)) {
298 port_cleanup(port, FALSE);
299 }
300 } while (0), /*no cleanup*/);
301 PORT_UNLOCK(port);
302 }
303
304 /*
305 * Link
306 * NB: Always lock from iport, then oport, to avoid deadlock.
307 */
308 void Scm_LinkPorts(ScmPort *iport, ScmPort *oport)
309 {
310 if (!SCM_IPORTP(iport)) {
311 Scm_Error("input port required, but got: %S", iport);
312 }
313 if (!SCM_OPORTP(oport)) {
314 Scm_Error("output port required, but got: %S", oport);
315 }
316
317 int aborted = FALSE;
318 ScmVM *vm = Scm_VM();
319 PORT_LOCK(iport, vm);
320 PORT_LOCK(oport, vm);
321 if (!SCM_FALSEP(PORT_LINK(iport))
322 || !SCM_FALSEP(PORT_LINK(oport))) {
323 aborted = TRUE;
324 } else {
325 PORT_LINK(iport) = SCM_OBJ(oport);
326 PORT_LINK(oport) = SCM_OBJ(iport);
327 }
328 PORT_UNLOCK(oport);
329 PORT_UNLOCK(iport);
330
331 if (aborted) {
332 Scm_Error("Port(s) are already linked. Unlink them first. (%S, %S)",
333 iport, oport);
334 }
335 }
336
337 void Scm_UnlinkPorts(ScmPort *port)
338 {
339 ScmObj link = PORT_LINK(port);
340 if (SCM_PORTP(link)) {
341 ScmVM *vm = Scm_VM();
342 if (SCM_IPORTP(port)) {
343 PORT_LOCK(port, vm);
344 PORT_LOCK(link, vm);
345 if (PORT_LINK(port) == link) {
346 PORT_LINK(port) = SCM_FALSE;
347 PORT_LINK(link) = SCM_FALSE;
348 }
349 PORT_UNLOCK(link);
350 PORT_UNLOCK(port);
351 } else {
352 PORT_LOCK(link, vm);
353 PORT_LOCK(port, vm);
354 if (PORT_LINK(port) == link) {
355 PORT_LINK(port) = SCM_FALSE;
356 PORT_LINK(link) = SCM_FALSE;
357 }
358 PORT_UNLOCK(port);
359 PORT_UNLOCK(link);
360 }
361 }
362 }
363
364 static inline void flush_linked_port(ScmPort *iport)
365 {
366 ScmObj p = PORT_LINK(iport);
367 if (SCM_OPORTP(p)) Scm_Flush(SCM_PORT(p));
368 }
369
370 static inline void reset_linked_column(ScmPort *iport)
371 {
372 ScmObj p = PORT_LINK(iport);
373 /* We don't lock p. If another thread is writing to a linked port
374 something's already wrong, and even so, stepping on each other
375 about the column count won't create havoc. */
376 if (SCM_OPORTP(p)) PORT_COLUMN(p) = 0;
377 }
378
379 /*===============================================================
380 * Locking ports
381 */
382
383 /* OBSOLETED */
384 /* C routines can use PORT_SAFE_CALL, so we reimplemented this in libio.scm.
385 Kept here for ABI compatibility; will be gone by 1.0. */
386 ScmObj Scm_VMWithPortLocking(ScmPort *port SCM_UNUSED, ScmObj closure)
387 {
388 static ScmObj with_port_locking_proc = SCM_UNDEFINED;
389 SCM_BIND_PROC(with_port_locking_proc, "with-port-locking",
390 Scm_GaucheModule());
391 return Scm_ApplyRec1(with_port_locking_proc, closure);
392 }
393
394 /*===============================================================
395 * Getting information
396 */
397
398 ScmObj Scm_PortName(ScmPort *port)
399 {
400 return Scm_PortAttrGet(port, SCM_SYM_NAME, SCM_FALSE);
401 }
402
403 ScmSize Scm_PortLine(ScmPort *port)
404 {
405 return PORT_LINE(port);
406 }
407
408 ScmSize Scm_PortBytes(ScmPort *port)
409 {
410 return PORT_BYTES(port);
411 }
412
413 ScmSize Scm_PortColumn(ScmPort *port)
414 {
415 return PORT_COLUMN(port);
416 }
417
418 static void port_print(ScmObj obj, ScmPort *port,
419 ScmWriteContext *ctx SCM_UNUSED)
420 {
421 Scm_Printf(port, "#<%s%sport%s %A %p>",
422 (SCM_PORT_DIR(obj)&SCM_PORT_INPUT)? "i" : "",
423 (SCM_PORT_DIR(obj)&SCM_PORT_OUTPUT)? "o" : "",
424 SCM_PORT_CLOSED_P(obj)? "(closed)" : "",
425 Scm_PortName(SCM_PORT(obj)),
426 obj);
427 }
428
429 /* Returns port's associated file descriptor number, if any.
430 Returns -1 otherwise. */
431 int Scm_PortFileNo(ScmPort *port)
432 {
433 if (SCM_PORT_TYPE(port) == SCM_PORT_FILE) {
434 ScmPortBuffer *buf = Scm_PortBufferStruct(port);
435 if (buf->filenum) return buf->filenum(port);
436 else return -1;
437 } else {
438 /* TODO: proc port */
439 return -1;
440 }
441 }
442
443 /* Returns a pointer to the 'src' strcuture. User code should use this
444 * instead of directly referring to 'src' member.
445 */
446 ScmPortBuffer *Scm_PortBufferStruct(ScmPort *port)
447 {
448 SCM_ASSERT(port->type == SCM_PORT_FILE);
449 return PORT_BUF(port);
450 }
451
452 ScmPortInputString *Scm_PortInputStringStruct(ScmPort *port)
453 {
454 SCM_ASSERT(port->type == SCM_PORT_ISTR);
455 return PORT_ISTR(port);
456 }
457
458 ScmDString *Scm_PortOutputDString(ScmPort *port)
459 {
460 SCM_ASSERT(port->type == SCM_PORT_OSTR);
461 return PORT_OSTR(port);
462 }
463
464 ScmPortVTable *Scm_PortVTableStruct(ScmPort *port)
465 {
466 SCM_ASSERT(port->type == SCM_PORT_PROC);
467 return PORT_VT(port);
468 }
469
470 /* For input buffered port, returns the size of room that can be filled
471 by the filler */
472 ScmSize Scm_PortBufferRoom(ScmPort *port)
473 {
474 SCM_ASSERT(port->type == SCM_PORT_FILE);
475 return PORT_BUFFER_ROOM(port);
476 }
477
478 /* For output buffered port, returns the size of available data that can
479 be flushed by the flusher */
480 ScmSize Scm_PortBufferAvail(ScmPort *port)
481 {
482 SCM_ASSERT(port->type == SCM_PORT_FILE);
483 return PORT_BUFFER_AVAIL(port);
484 }
485
486 ScmWriteState *Scm_PortWriteState(ScmPort *port)
487 {
488 return P_(port)->writeState;
489 }
490
491 void Scm_PortWriteStateSet(ScmPort *port, ScmWriteState *ws)
492 {
493 P_(port)->writeState = ws;
494 }
495
496 int Scm_GetPortBufferingMode(ScmPort *port)
497 {
498 if (port->type == SCM_PORT_FILE) return PORT_BUFFER_MODE(port);
499 else return SCM_PORT_BUFFER_NONE;
500 }
501
502 void Scm_SetPortBufferingMode(ScmPort *port, int mode)
503 {
504 if (port->type != SCM_PORT_FILE) {
505 Scm_Error("Can't set buffering mode to non-buffered port: %S", port);
506 }
507 PORT_BUF(port)->mode =
508 (PORT_BUF(port)->mode & ~SCM_PORT_BUFFER_MODE_MASK)
509 | (mode & SCM_PORT_BUFFER_MODE_MASK);
510 }
511
512 int Scm_GetPortBufferSigpipeSensitive(ScmPort *port)
513 {
514 if (port->type == SCM_PORT_FILE) {
515 return (PORT_BUFFER_SIGPIPE_SENSITIVE_P(port) != FALSE);
516 } else {
517 return FALSE;
518 }
519 }
520
521 void Scm_SetPortBufferSigpipeSensitive(ScmPort *port, int sensitive)
522 {
523 if (port->type != SCM_PORT_FILE) {
524 Scm_Error("Can't set sigpipe sensitivity to non-buffered port: %S",
525 port);
526 }
527 if (sensitive) {
528 PORT_BUF(port)->mode |= SCM_PORT_BUFFER_SIGPIPE_SENSITIVE;
529 } else {
530 PORT_BUF(port)->mode &= ~SCM_PORT_BUFFER_SIGPIPE_SENSITIVE;
531 }
532 }
533
534 /* Port case folding mode is usually set at port creation, according
535 to the VM's case folding mode. In rare occasion we need to switch
536 it (but it's not generally recommended). */
537 int Scm_GetPortCaseFolding(ScmPort *port)
538 {
539 return (SCM_PORT_CASE_FOLDING(port) != FALSE);
540 }
541
542 void Scm_SetPortCaseFolding(ScmPort *port, int folding)
543 {
544 if (folding) {
545 SCM_PORT_FLAGS(port) |= SCM_PORT_CASE_FOLD;
546 } else {
547 SCM_PORT_FLAGS(port) &= ~SCM_PORT_CASE_FOLD;
548 }
549 }
550
551 /* Port's reader lexical mode is set at port creation, taken from
552 readerLexicalMode parameter. It may be altered by reader directive
553 such as #!r7rs.
554 The possible value is the same as the global reader lexical mode,
555 i.e. one of the symbols legacy, warn-legacy, permissive or strict-r7.
556 */
557 ScmObj Scm_GetPortReaderLexicalMode(ScmPort *port)
558 {
559 /* We let it throw an error if there's no reader-lexical-mode attr.
560 It must be set in the constructor. */
561 return Scm_PortAttrGet(port, SCM_SYM_READER_LEXICAL_MODE, SCM_UNBOUND);
562 }
563
564 void Scm_SetPortReaderLexicalMode(ScmPort *port, ScmObj mode)
565 {
566 /*The check is duplicatd in Scm_SetReaderLexicalMode; refactoring needed.*/
567 if (!(SCM_EQ(mode, SCM_SYM_LEGACY)
568 || SCM_EQ(mode, SCM_SYM_WARN_LEGACY)
569 || SCM_EQ(mode, SCM_SYM_PERMISSIVE)
570 || SCM_EQ(mode, SCM_SYM_STRICT_R7))) {
571 Scm_Error("reader-lexical-mode must be one of the following symbols:"
572 " legacy, warn-legacy, permissive, strict-r7, but got %S",
573 mode);
574 }
575 Scm_PortAttrSet(port, SCM_SYM_READER_LEXICAL_MODE, mode);
576 }
577
578 /* global reader lexical mode. */
579 ScmObj Scm_SetReaderLexicalMode(ScmObj mode)
580 {
581 if (!(SCM_EQ(mode, SCM_SYM_LEGACY)
582 || SCM_EQ(mode, SCM_SYM_WARN_LEGACY)
583 || SCM_EQ(mode, SCM_SYM_PERMISSIVE)
584 || SCM_EQ(mode, SCM_SYM_STRICT_R7))) {
585 Scm_Error("reader-lexical-mode must be one of the following symbols:"
586 " legacy, warn-legacy, permissive, strict-r7, but got %S",
587 mode);
588 }
589 return Scm_PrimitiveParameterSet(Scm_VM(), readerLexicalMode, mode);
590 }
591
592 ScmObj Scm_ReaderLexicalMode()
593 {
594 return Scm_PrimitiveParameterRef(Scm_VM(), readerLexicalMode);
595 }
596
597 /* flag can be checked with SCM_PORT_ERROR_OCCURRED_P() */
598 void Scm_SetPortErrorOccurred(ScmPort *port, int flag)
599 {
600 port->error = flag;
601 }
602
603 /* Query whether the port is positoinable. If setp is false, returns
604 if port can get current pos. If setp is true, returns if port
605 can set pos.
606 Note: For the buffering and procedural ports, if the user used old
607 protocol (using seeker), we can't exactly know if get/set position
608 is possible or not.
609 */
610 int Scm_PortPositionable(ScmPort *port, int setp)
611 {
612 switch (SCM_PORT_TYPE(port)) {
613 case SCM_PORT_FILE:
614 if (setp) {
615 return (PORT_BUF(port)->setpos || PORT_BUF(port)->seeker);
616 } else {
617 return (PORT_BUF(port)->getpos || PORT_BUF(port)->seeker);
618 }
619 case SCM_PORT_PROC:
620 if (setp) {
621 return (PORT_VT(port)->SetPos || PORT_VT(port)->Seek);
622 } else {
623 return (PORT_VT(port)->GetPos || PORT_VT(port)->Seek);
624 }
625 case SCM_PORT_ISTR:
626 return TRUE;
627 case SCM_PORT_OSTR:
628 if (setp) return FALSE; /* we haven't supported setpos for ostr */
629 else return TRUE;
630 }
631 return FALSE; /* dummy */
632 }
633
634 /* Duplicates the file descriptor of the source port, and set it to
635 the destination port. Both source and destination port must be
636 file ports.
637 DST also must be a file buffered port, for we rewrite the fd slot
638 in its private data structure. */
639 void Scm_PortFdDup(ScmPort *dst, ScmPort *src)
640 {
641 int r;
642
643 if (SCM_PORT_TYPE(dst) != SCM_PORT_FILE)
644 Scm_Error("file port required, but got %S", dst);
645 if (SCM_PORT_TYPE(src) != SCM_PORT_FILE)
646 Scm_Error("file port required, but got %S", src);
647 if (src->direction != dst->direction)
648 Scm_Error("port direction mismatch: got %S and %S",
649 src, dst);
650
651 int srcfd = Scm_PortFileNo(src);
652 int dstfd = Scm_PortFileNo(dst);
653
654 if (srcfd < 0) Scm_Error("port isn't associated to fd: %S", src);
655 if (dstfd < 0) Scm_Error("port isn't associated to fd: %S", dst);
656
657 if (!file_buffered_port_p(dst)) {
658 Scm_Error("port isn't directly associated to file: %S", dst);
659 }
660
661 if (dst->direction == SCM_PORT_INPUT) {
662 /* discard the current buffer */
663 ScmVM *vm = Scm_VM();
664 PORT_LOCK(dst, vm);
665 PORT_BUF(dst)->current = PORT_BUF(dst)->buffer;
666 PORT_BUF(dst)->end = PORT_BUF(dst)->buffer;
667 PORT_UNLOCK(dst);
668 } else {
669 /* flush the current buffer */
670 Scm_Flush(dst);
671 }
672 /* NB: We don't retry dup2(). By the time it returns EINTR, the
673 dstfd has actually been closed, and if other thread happens to
674 grab the same fd, retrying dup2() inadvertently closes that one.
675 */
676
677 #if defined(GAUCHE_WINDOWS)
678 r = _dup2(srcfd, dstfd);
679 #else /*!GAUCHE_WINDOWS*/
680 r = dup2(srcfd, dstfd);
681 #endif /*!GAUCHE_WINDOWS*/
682 if (r < 0) Scm_SysError("dup2 failed");
683 file_buffered_port_set_fd(dst, r);
684 }
685
686 /* Low-level function to find if the file descriptor is ready or not.
687 DIR specifies SCM_PORT_INPUT or SCM_PORT_OUTPUT.
688 If the system doesn't have select(), this function returns
689 SCM_FD_UNKNOWN. */
690 int Scm_FdReady(int fd, int dir)
691 {
692 #if defined(HAVE_SELECT) && !defined(GAUCHE_WINDOWS)
693 fd_set fds;
694 int r;
695 struct timeval tm;
696
697 /* In case if this is called on non-file ports.*/
698 if (fd < 0) return SCM_FD_READY;
699 if (fd >= FD_SETSIZE) Scm_Error("Scm_FdReady: fd out of range: %d", fd);
700
701 FD_ZERO(&fds);
702 FD_SET(fd, &fds);
703 tm.tv_sec = tm.tv_usec = 0;
704 if (dir == SCM_PORT_OUTPUT) {
705 SCM_SYSCALL(r, select(fd+1, NULL, &fds, NULL, &tm));
706 } else {
707 SCM_SYSCALL(r, select(fd+1, &fds, NULL, NULL, &tm));
708 }
709 if (r < 0) Scm_SysError("select failed");
710 if (r > 0) return SCM_FD_READY;
711 else return SCM_FD_WOULDBLOCK;
712 #elif defined(GAUCHE_WINDOWS)
713 /* Windows have select(), but it can only be used on sockets.*/
714 if (dir == SCM_PORT_OUTPUT) {
715 /* We assume it is always ok */
716 return SCM_FD_READY;
717 } else {
718 HANDLE h = (HANDLE)_get_osfhandle(fd);
719 if (h == INVALID_HANDLE_VALUE) return SCM_FD_READY;
720
721 /* pipe */
722 DWORD avail;
723 if (PeekNamedPipe(h, NULL, 0, NULL, &avail, NULL) != 0) {
724 if (avail == 0) return SCM_FD_WOULDBLOCK;
725 else return SCM_FD_READY;
726 }
727
728 /* socket */
729 int optval;
730 int optlen;
731 optlen = sizeof(optval);
732 if (getsockopt((SOCKET)h, SOL_SOCKET, SO_TYPE, (char*)&optval, &optlen) != SOCKET_ERROR) {
733 fd_set fds;
734 int r;
735 struct timeval tm;
736 FD_ZERO(&fds);
737 FD_SET((SOCKET)h, &fds);
738 tm.tv_sec = tm.tv_usec = 0;
739 /* NB: The first argument of select() is ignored on Windows */
740 SCM_SYSCALL(r, select(0, &fds, NULL, NULL, &tm));
741 if (r < 0) Scm_SysError("select failed");
742 if (r > 0) return SCM_FD_READY;
743 else return SCM_FD_WOULDBLOCK;
744 }
745
746 /* other */
747 return SCM_FD_UNKNOWN;
748 }
749 #else /*!HAVE_SELECT && !GAUCHE_WINDOWS */
750 return SCM_FD_UNKNOWN;
751 #endif /*!HAVE_SELECT && !GAUCHE_WINDOWS */
752 }
753
754 /*=================================================================
755 * Port Attributes
756 *
757 * Port attributes are stored in alist. Each entry is either one
758 * of the following form:
759 * (key value) Just a value
760 * (key value . #f) Just a value, read-only. This is a system
761 * attribute; no public interface to create this
762 * kind of API is provided. It is also undeletable.
763 * (Currently, only the internal port constructor
764 * creates this kind of attributes.)
765 *
766 * Access to the port attributes is mutexed by a separate lock than
767 * the port's main lock, for the attributes can be accessed from a
768 * thread while another thread is reading from/writing to it (e.g. taking
769 * the port name for display).
770 */
771
772 ScmObj Scm_PortAttrGet(ScmPort *p, ScmObj key, ScmObj fallback)
773 {
774 ScmObj r = SCM_UNBOUND;
775
776 /* We assume pointer op is atomic */
777 ScmObj v = Scm_Assq(key, PORT_ATTRS(p));
778 if (SCM_PAIRP(v)) {
779 SCM_ASSERT(SCM_PAIRP(SCM_CDR(v)));
780 r = SCM_CADR(v);
781 } else {
782 r = fallback;
783 }
784
785 if (SCM_UNBOUNDP(r)) {
786 Scm_Error("No port attribute for key %S in port %S", key, SCM_OBJ(p));
787 }
788 return r;
789 }
790
791 ScmObj Scm_PortAttrSet(ScmPort *p, ScmObj key, ScmObj val)
792 {
793 volatile int err_readonly = FALSE;
794 volatile int exists = FALSE;
795
796 (void)SCM_INTERNAL_FASTLOCK_LOCK(P_(p)->lock);
797 ScmObj v = Scm_Assq(key, PORT_ATTRS(p));
798 if (SCM_PAIRP(v)) {
799 SCM_ASSERT(SCM_PAIRP(SCM_CDR(v)));
800 exists = TRUE;
801 if (SCM_NULLP(SCM_CDDR(v))) {
802 SCM_SET_CAR_UNCHECKED(SCM_CDR(v), val);
803 } else {
804 err_readonly = TRUE;
805 }
806 } else {
807 PORT_ATTRS(p) = Scm_Cons(SCM_LIST2(key, val), PORT_ATTRS(p));
808 }
809 (void)SCM_INTERNAL_FASTLOCK_UNLOCK(P_(p)->lock);
810
811 if (err_readonly) {
812 Scm_Error("Port attribute '%A' is read-only in port: %S",
813 key, SCM_OBJ(p));
814 }
815 return SCM_MAKE_BOOL(exists);
816 }
817
818 ScmObj Scm_PortAttrDelete(ScmPort *p, ScmObj key)
819 {
820 int err_undeletable = FALSE;
821
822 (void)SCM_INTERNAL_FASTLOCK_LOCK(P_(p)->lock);
823 ScmObj v = Scm_Assq(key, PORT_ATTRS(p));
824 if (SCM_PAIRP(v) && SCM_PAIRP(SCM_CDR(v)) && SCM_FALSEP(SCM_CDDR(v))) {
825 err_undeletable = TRUE;
826 } else {
827 PORT_ATTRS(p) = Scm_AssocDelete(key, PORT_ATTRS(p), SCM_CMP_EQ);
828 }
829 (void)SCM_INTERNAL_FASTLOCK_UNLOCK(P_(p)->lock);
830 if (err_undeletable) {
831 Scm_Error("Port attribute '%A' is not deletable from port: %S",
832 key, SCM_OBJ(p));
833 }
834 return SCM_UNDEFINED; /* we may return more useful info in future */
835 }
836
837 ScmObj Scm_PortAttrs(ScmPort *p)
838 {
839 ScmObj h = SCM_NIL, t = SCM_NIL;
840 ScmObj cp;
841 SCM_FOR_EACH(cp, PORT_ATTRS(p)) {
842 SCM_ASSERT(SCM_PAIRP(SCM_CAR(cp)) && SCM_PAIRP(SCM_CDAR(cp)));
843 ScmObj e = SCM_CAR(cp);
844 ScmObj k = SCM_CAR(e);
845 ScmObj v = SCM_CADR(e);
846 SCM_APPEND1(h, t, Scm_Cons(k, v));
847 }
848 return h;
849 }
850
851 /*===============================================================
852 * buffered Port
853 * - mainly used for buffered file I/O, but can also be used
854 * for other purpose, like character-code conversion port.
855 */
856
857 /* [Buffered port protocol]
858 *
859 * Legends
860 * b = port->src.buf.buffer
861 * c = port->src.buf.current
862 * e = port->src.buf.end
863 * '*' = valid data
864 * '-' = invalid data
865 *
866 * Output
867 *
868 * When used as output, the end pointer always points one byte past
869 * the buffer. Initially the buffer is empty and the current pointer
870 * is the same as the beginning of the buffer.
871 *
872 * port->src.buf.flusher(ScmPort* p, int cnt, int forcep) is called when
873 * the port needs to create some room in the buffer. When the flusher
874 * is called, the buffer is like this:
875 *
876 * <--------------- size ---------------->
877 * |*********************************-----|
878 * ^ ^ ^
879 * b c e
880 *
881 * The flusher is supposed to output the cnt bytes of data beginning from
882 * the buffer, which is usually up to the current pointer (but the flusher
883 * doesn't need to check the current pointer; it is taken care of by the
884 * caller of the flusher).
885 *
886 * If the third argument forcep is false, the flusher may return before
887 * entire data is output, in case like underlying device is busy.
888 * The flusher must output at least one byte even in that case.
889 * On the other hand, if the forcep argument is true, the flusher must
890 * write cnt bytes; if it is not possible, the flusher must return -1 to
891 * indicate an error(*1).
892 *
893 * The flusher returns the number of bytes actually written out.
894 * If an error occurs, the flusher must return -1.
895 *
896 * The flusher must be aware that the port p is locked by the current
897 * thread when called.
898 *
899 * The flusher shouldn't change the buffer's internal state.
900 *
901 * After the flusher returns, bufport_flush shifts the unflushed data
902 * (if any), so the buffer becomes like this:
903 *
904 * <--------------- size ---------------->
905 * |****----------------------------------|
906 * ^ ^ ^
907 * b c e
908 *
909 * (*1) Why should these two modes need to be distinguished? Suppose
910 * you implement a buffered port that does character encoding conversion.
911 * The flusher converts the content of the buffer to different character
912 * encoding and feed it to some specified port. It is often the case
913 * that you find a few bytes at the end of the buffer which you can't
914 * convert into a whole character but have to wait for next byte(s).
915 * It is valid that you leave them in the buffer if you can expect
916 * more data to come. However, if you know it is really the end of
917 * the stream, you can't leave any data in the buffer and you should
918 * take appropriate action, for example, raising an error.
919 *
920 * Input
921 *
922 * When used as input, the end pointer points to one byte past the
923 * end of the valid data, which may be before the end of the buffer.
924 *
925 * port->src.buf.filler(ScmPort *p, int cnt) is called when the buffer
926 * doesn't have enough data to read. Suppose the input routine detects
927 * the buffer doesn't have enough data when it looks like this:
928 *
929 * <--------------- size ---------------->
930 * |-----------------------------****-----|
931 * ^ ^ ^
932 * b c e
933 *
934 * First, bufport_fill shifts the unread data (if any) to the beginning
935 * of the buffer, so it becomes like this:
936 *
937 * <--------------- size ---------------->
938 * |****----------------------------------|
939 * ^ ^
940 * bc e
941 *
942 * Then port->src.buf.filler is called. It is supposed to read as many
943 * bytes as cnt, putting them after the end pointer. The filler doesn't
944 * need to modify the end pointer; it is taken care of after the filler
945 * returns.
946 *
947 * The filler may read less than cnt bytes if all bytes of data is not
948 * available immediately. The filler returns the number of bytes
949 * actually read in. The filler should return 0 if it reaches the end
950 * of the data source. If an error occurs, the filler must return -1.
951 *
952 * bufport_fill then adjust the end pointer, so the buffer becomes like
953 * this.
954 *
955 * <--------------- size ---------------->
956 * |************************************--|
957 * ^ ^
958 * bc e
959 *
960 * Close
961 * Port is closed either explicitly (via close-port etc) or implicitly
962 * (via GC -> finalizer). In either case, the flusher is called first
963 * if there's any data remaining in the buffer. Then, if the closer
964 * procedure (port->src.buf.closer) is not NULL, and port->owner is TRUE,
965 * the closer procedure is called which has to take care of any system-
966 * level cleanup. The closer can assume the buffer is already flushed.
967 *
968 * Ready
969 * When char-ready? is called on a buffered port, it first checks if
970 * there's any data available in the buffer. If so, it returns true.
971 * If not, it calls port->src.buf.ready if it is not NULL to query
972 * the character is ready. If port->src.buf.ready is NULL, bufport
973 * assumes the input is always ready.
974 * port->src.buf.ready should return either SCM_FD_READY, SCM_FD_WOULDBLOCK
975 * or SCM_FD_UNKNOWN.
976 *
977 * Filenum
978 * Port->src.buf.filenum is a query procedure that should return the
979 * underlying integer file descriptor of the port, or -1 if there's
980 * no associated one. If it is NULL, the port is assumed not to
981 * be associated to any file descriptor.
982 *
983 * Buffering mode
984 * {For Output}
985 * SCM_PORT_BUFFER_FULL : Full buffering. The buffer is flushed
986 * only when the buffer gets full, explicitly requested, or
987 * closed. This is the default, and suitable for file I/O.
988 *
989 * SCM_PORT_BUFFER_LINE : Line buffering. The buffer is flushed
990 * when a newline character is put, other than the normal
991 * circumstances as in SCM_PORT_BUFFER_FULL. Unlike C stdio,
992 * the buffer isn't flushed when an input is called on the same
993 * terminal device.
994 * This is natural for output of interactive communication.
995 * This is the default of stdout.
996 *
997 * SCM_PORT_BUFFER_NONE : data is always passed to the flusher
998 * procedure. The buffer is used just as a temporary storage.
999 * This slows down port operation significantly. Should only
1000 * be used when you want to guarantee what you write is always
1001 * passed to the lower layer. This is the default of stderr.
1002 *
1003 * {For Input}
1004 * SCM_PORT_BUFFER_FULL : Full buffering. The filler procedure
1005 * is called only if the buffer doesn't have enough data to
1006 * satisfy the read request. Read-block or read-string won't
1007 * return until the specified bytes/characters are read from
1008 * the port, except the port reaches EOF.
1009 *
1010 * SCM_PORT_BUFFER_LINE : For input ports, this is almost the same
1011 * as BUFFER_FULL, except that read-block and read-string may
1012 * return shorter data than requested, if only that amount of
1013 * data is immediately available. Usually this mode is suitable
1014 * for the ports that is attached to a pipe or network.
1015 *
1016 * SCM_PORT_BUFFER_NONE : No buffering. Every time the data is
1017 * requested, the filler procedure is called with exact amount
1018 * of the requested data.
1019 */
1020
1021 #define SCM_PORT_DEFAULT_BUFSIZ 8192
1022
1023 ScmObj Scm_MakeBufferedPortFull(ScmClass *klass,
1024 ScmObj name,
1025 int dir, /* direction */
1026 ScmPortBuffer *bufrec,
1027 u_long flags)
1028 {
1029 ScmSize size = bufrec->size;
1030 char *buf = bufrec->buffer;
1031
1032 if (size == 0) size = SCM_PORT_DEFAULT_BUFSIZ;
1033 if (buf == NULL) buf = SCM_NEW_ATOMIC2(char*, size);
1034 ScmPort *p = make_port(klass, name, dir, SCM_PORT_FILE);
1035 p->ownerp = flags & SCM_PORT_OWNER;
1036 PORT_BUF(p)->buffer = buf;
1037 if ((dir & SCM_PORT_IOMASK) == SCM_PORT_INPUT) {
1038 PORT_BUF(p)->current = PORT_BUF(p)->buffer;
1039 PORT_BUF(p)->end = PORT_BUF(p)->buffer;
1040 } else {
1041 PORT_BUF(p)->current = PORT_BUF(p)->buffer;
1042 PORT_BUF(p)->end = PORT_BUF(p)->buffer + size;
1043 }
1044 if (dir == SCM_PORT_OUTPUT_TRANSIENT) {
1045 SCM_PORT_FLAGS(p) |= SCM_PORT_TRANSIENT;
1046 }
1047 PORT_BUF(p)->size = size;
1048 PORT_BUF(p)->mode = bufrec->mode;
1049 PORT_BUF(p)->filler = bufrec->filler;
1050 PORT_BUF(p)->flusher = bufrec->flusher;
1051 PORT_BUF(p)->closer = bufrec->closer;
1052 PORT_BUF(p)->ready = bufrec->ready;
1053 PORT_BUF(p)->filenum = bufrec->filenum;
1054 PORT_BUF(p)->seeker = bufrec->seeker;
1055 PORT_BUF(p)->data = bufrec->data;
1056 PORT_BUF(p)->idata = bufrec->idata;
1057
1058 /* When the port is GC'ed without properly closed, a finalizer is
1059 run to clean up. However, at that moment, PORT_BUF(p)->data
1060 may be already collected. We should detect the case.
1061 */
1062 if (GC_is_heap_ptr(bufrec->data)) {
1063 PORT_FILE_EXTDATA_SET(p);
1064 GC_register_disappearing_link((void**)&PORT_BUF(p)->data);
1065 }
1066
1067 if (flags & SCM_PORT_WITH_POSITION) {
1068 PORT_BUF(p)->getpos = bufrec->getpos;
1069 PORT_BUF(p)->setpos = bufrec->setpos;
1070 PORT_BUF(p)->flags = bufrec->flags;
1071 } else {
1072 PORT_BUF(p)->getpos = NULL;
1073 PORT_BUF(p)->setpos = NULL;
1074 PORT_BUF(p)->flags = 0;
1075 }
1076
1077 /* NB: DIR may be SCM_PORT_OUTPUT_TRANSIENT; in that case we don't
1078 register the buffer. */
1079 if (dir == SCM_PORT_OUTPUT) register_buffered_port(p);
1080 return SCM_OBJ(p);
1081 }
1082
1083 /* deprecated */
1084 ScmObj Scm_MakeBufferedPort(ScmClass *klass,
1085 ScmObj name,
1086 int dir, /* direction */
1087 int ownerp,
1088 ScmPortBuffer *bufrec)
1089 {
1090 return Scm_MakeBufferedPortFull(klass, name, dir, bufrec,
1091 (ownerp? SCM_PORT_OWNER : 0));
1092 }
1093
1094 /* flushes the buffer, to make a room of cnt bytes.
1095 cnt == 0 means all the available data. Note that, unless forcep == TRUE,
1096 this function only does "best effort" to make room, but doesn't
1097 guarantee to output cnt bytes. */
1098 static void bufport_flush(ScmPort *p, ScmSize cnt, int forcep)
1099 {
1100 ScmSize cursiz = PORT_BUFFER_AVAIL(p);
1101
1102 if (cursiz == 0) return;
1103 if (cnt <= 0) { cnt = cursiz; }
1104 ScmSize nwrote = PORT_BUF(p)->flusher(p, cnt, forcep);
1105 if (nwrote < 0) {
1106 PORT_BUF(p)->current = PORT_BUF(p)->buffer; /* for safety */
1107 p->error = TRUE;
1108 /* TODO: can we raise an error here, or should we propagate
1109 it to the caller? */
1110 Scm_PortError(p, SCM_PORT_ERROR_OUTPUT,
1111 "Couldn't flush port %S due to an error", p);
1112 }
1113 if (nwrote >= 0 && nwrote < cursiz) {
1114 memmove(PORT_BUF(p)->buffer, PORT_BUF(p)->buffer+nwrote,
1115 cursiz-nwrote);
1116 PORT_BUF(p)->current -= nwrote;
1117 } else {
1118 PORT_BUF(p)->current = PORT_BUF(p)->buffer;
1119 }
1120 }
1121
1122 /* Writes siz bytes in src to the buffered port. siz may be larger than
1123 the port's buffer. Won't return until entire siz bytes are written. */
1124 static void bufport_write(ScmPort *p, const char *src, ScmSize siz)
1125 {
1126 do {
1127 ScmSize room = PORT_BUF(p)->end - PORT_BUF(p)->current;
1128 if (room >= siz) {
1129 memcpy(PORT_BUF(p)->current, src, siz);
1130 PORT_BUF(p)->current += siz;
1131 siz = 0;
1132 } else {
1133 memcpy(PORT_BUF(p)->current, src, room);
1134 PORT_BUF(p)->current += room;
1135 siz -= room;
1136 src += room;
1137 bufport_flush(p, 0, FALSE);
1138 }
1139 } while (siz != 0);
1140 }
1141
1142 /* Fills the buffer. Reads at least MIN bytes (unless it reaches EOF).
1143 * If ALLOW_LESS is true, however, we allow to return before the full
1144 * data is read.
1145 * Returns the number of bytes actually read, or 0 if EOF, or -1 if error.
1146 */
1147 static ScmSize bufport_fill(ScmPort *p, ScmSize min, int allow_less)
1148 {
1149 ScmSize cursiz = PORT_BUF(p)->end - PORT_BUF(p)->current;
1150 ScmSize nread = 0, toread;
1151 if (cursiz > 0) {
1152 memmove(PORT_BUF(p)->buffer, PORT_BUF(p)->current, cursiz);
1153 PORT_BUF(p)->current = PORT_BUF(p)->buffer;
1154 PORT_BUF(p)->end = PORT_BUF(p)->current + cursiz;
1155 } else {
1156 PORT_BUF(p)->current = PORT_BUF(p)->end = PORT_BUF(p)->buffer;
1157 }
1158 if (min <= 0) min = PORT_BUFFER_ROOM(p);
1159 if (PORT_BUFFER_MODE(p) != SCM_PORT_BUFFER_NONE) {
1160 toread = PORT_BUFFER_ROOM(p);
1161 } else {
1162 toread = min;
1163 }
1164
1165 do {
1166 ScmSize r = PORT_BUF(p)->filler(p, toread-nread);
1167 if (r <= 0) break;
1168 nread += r;
1169 PORT_BUF(p)->end += r;
1170 } while (!allow_less && nread < min);
1171 return nread;
1172 }
1173
1174 /* Reads siz bytes to dst from the buffered port. siz may be larger
1175 * than the port's buffer, in which case the filler procedure is called
1176 * more than once. Unless the port buffering mode is BUFFER_FULL,
1177 * this may read less than SIZ bytes if only that amount of data is
1178 * immediately available.
1179 * Caveat: if the filler procedure returns N where 0 < N < requested size,
1180 * we know less data is available; non-greedy read can return at that point.
1181 * However, if the filler procedure returns exactly the requested size,
1182 * and we need more bytes, we gotta be careful -- next call to the filler
1183 * procedure may or may not block. So we need to check the ready procedure.
1184 */
1185 static ScmSize bufport_read(ScmPort *p, char *dst, ScmSize siz)
1186 {
1187 ScmSize nread = 0;
1188 ScmSize avail = PORT_BUF(p)->end - PORT_BUF(p)->current;
1189
1190 ScmSize req = MIN(siz, avail);
1191 if (req > 0) {
1192 memcpy(dst, PORT_BUF(p)->current, req);
1193 PORT_BUF(p)->current += req;
1194 nread += req;
1195 siz -= req;
1196 dst += req;
1197 }
1198 while (siz > 0) {
1199 /* We check data availability first, since we might already get
1200 some data from the remanings in the buffer, and it is enough
1201 if buffering mode is not full. */
1202 if (nread && (PORT_BUFFER_MODE(p) != SCM_PORT_BUFFER_FULL)) {
1203 if (PORT_BUF(p)->ready
1204 && PORT_BUF(p)->ready(p) == SCM_FD_WOULDBLOCK) {
1205 break;
1206 }
1207 }
1208
1209 ScmSize req = MIN(siz, PORT_BUF(p)->size);
1210 ScmSize r = bufport_fill(p, req, TRUE);
1211 if (r <= 0) break; /* EOF or an error*/
1212 if (r >= siz) {
1213 memcpy(dst, PORT_BUF(p)->current, siz);
1214 PORT_BUF(p)->current += siz;
1215 nread += siz;
1216 break;
1217 } else {
1218 memcpy(dst, PORT_BUF(p)->current, r);
1219 PORT_BUF(p)->current += r;
1220 nread += r;
1221 siz -= r;
1222 dst += r;
1223 }
1224 }
1225 return nread;
1226 }
1227
1228 /* Tracking buffered ports:
1229 *
1230 * The OS doesn't automatically flush the buffered output port,
1231 * as it does on FILE* structure. So Gauche keeps track of active
1232 * output buffered ports, in a weak vector.
1233 * When the port is no longer used, it is collected by GC and removed
1234 * from the vector. Scm_FlushAllPorts() flushes the active ports.
1235 *
1236 * Note that we don't remove entry from the weak vector explicitly.
1237 * We used to do that in the port finalizer; however, the finalizer
1238 * is called _after_ GC has run and determined the port is a garbage,
1239 * and at that moment GC has already cleared the vector entry. So we
1240 * can rather let GC remove the entries.
1241 *
1242 * When we find the weak vector is full, we trigger a global GC once.
1243 * It may collect garbaged ports and make some room in the vector,
1244 * even though the ports are not finalized (GC_gcollect doesn't call
1245 * finalizers; they are called at the next checkpoint in VM).
1246 */
1247
1248 /*TODO: allow to extend the port vector. */
1249
1250 #define PORT_VECTOR_SIZE 256 /* need to be 2^n */
1251
1252 static struct {
1253 ScmWeakVector *ports;
1254 ScmInternalMutex mutex;
1255 } active_buffered_ports;
1256
1257 #define PORT_HASH(port) \
1258 ((u_long)(((SCM_WORD(port)>>3) * 2654435761UL)>>16) % PORT_VECTOR_SIZE)
1259
1260 static void register_buffered_port(ScmPort *port)
1261 {
1262 int i, h, c;
1263 int tried_gc = FALSE;
1264 int need_gc = FALSE;
1265
1266 retry:
1267 h = i = (int)PORT_HASH(port);
1268 c = 0;
1269 /* search an available entry by quadratic hash
1270 used entry may have #<port> or #t. #t is for transient state
1271 during Scm_FlushAllPorts()---see below. */
1272 (void)SCM_INTERNAL_MUTEX_LOCK(active_buffered_ports.mutex);
1273 while (!SCM_FALSEP(Scm_WeakVectorRef(active_buffered_ports.ports,
1274 i, SCM_FALSE))) {
1275 i -= ++c; while (i<0) i+=PORT_VECTOR_SIZE;
1276 if (i == h) {
1277 /* Vector entry is full. We run global GC to try to collect
1278 unused entry. */
1279 need_gc = TRUE;
1280 break;
1281 }
1282 }
1283 if (!need_gc) {
1284 Scm_WeakVectorSet(active_buffered_ports.ports, i, SCM_OBJ(port));
1285 }
1286 (void)SCM_INTERNAL_MUTEX_UNLOCK(active_buffered_ports.mutex);
1287
1288 if (need_gc) {
1289 if (tried_gc) {
1290 /* We should probably try to extend the weak vector.
1291 But for the time being... */
1292 Scm_Panic("active buffered port table overflow");
1293 } else {
1294 GC_gcollect();
1295 tried_gc = TRUE;
1296 need_gc = FALSE;
1297 goto retry;
1298 }
1299 }
1300 }
1301
1302 /* This should be called when the output buffered port is explicitly closed.
1303 The ports collected by GC are automatically unregistered. */
1304 static void unregister_buffered_port(ScmPort *port)
1305 {
1306 int h = (int)PORT_HASH(port);
1307 int i = h;
1308 int c = 0;
1309 (void)SCM_INTERNAL_MUTEX_LOCK(active_buffered_ports.mutex);
1310 do {
1311 ScmObj p = Scm_WeakVectorRef(active_buffered_ports.ports, i, SCM_FALSE);
1312 if (!SCM_FALSEP(p) && SCM_EQ(SCM_OBJ(port), p)) {
1313 Scm_WeakVectorSet(active_buffered_ports.ports, i, SCM_FALSE);
1314 break;
1315 }
1316 i -= ++c; while (i<0) i+=PORT_VECTOR_SIZE;
1317 } while (i != h);
1318 (void)SCM_INTERNAL_MUTEX_UNLOCK(active_buffered_ports.mutex);
1319 }
1320
1321 /* Flush all ports. Note that it is possible that this routine can be
1322 called recursively if one of the flushing routine calls Scm_Exit.
1323 In order to avoid infinite loop, I have to delete the entries of already
1324 flushed port before calling flush, then recover them before return
1325 (unless exiting is true, in that case we know nobody cares the active
1326 port vector anymore).
1327 Even if more than one thread calls Scm_FlushAllPorts simultaneously,
1328 the flush method is called only once for each vector.
1329 */
1330 void Scm_FlushAllPorts(int exitting)
1331 {
1332 ScmObj p = SCM_FALSE;
1333 int saved = 0;
1334
1335 ScmVector *save = SCM_VECTOR(Scm_MakeVector(PORT_VECTOR_SIZE, SCM_FALSE));
1336 ScmWeakVector *ports = active_buffered_ports.ports;
1337
1338 for (int i=0; i<PORT_VECTOR_SIZE;) {
1339 (void)SCM_INTERNAL_MUTEX_LOCK(active_buffered_ports.mutex);
1340 for (; i<PORT_VECTOR_SIZE; i++) {
1341 p = Scm_WeakVectorRef(ports, i, SCM_FALSE);
1342 if (SCM_PORTP(p)) {
1343 Scm_VectorSet(save, i, p);
1344 /* Set #t so that the slot won't be reused. */
1345 Scm_WeakVectorSet(ports, i, SCM_TRUE);
1346 saved++;
1347 break;
1348 }
1349 }
1350 (void)SCM_INTERNAL_MUTEX_UNLOCK(active_buffered_ports.mutex);
1351 if (SCM_PORTP(p)) {
1352 SCM_ASSERT(SCM_PORT_TYPE(p)==SCM_PORT_FILE);
1353 if (!SCM_PORT_ERROR_OCCURRED_P(SCM_PORT(p))) {
1354 bufport_flush(SCM_PORT(p), 0, TRUE);
1355 }
1356 }
1357 }
1358 if (!exitting && saved) {
1359 (void)SCM_INTERNAL_MUTEX_LOCK(active_buffered_ports.mutex);
1360 for (int i=0; i<PORT_VECTOR_SIZE; i++) {
1361 p = Scm_VectorRef(save, i, SCM_FALSE);
1362 if (SCM_PORTP(p)) Scm_WeakVectorSet(ports, i, p);
1363 }
1364 (void)SCM_INTERNAL_MUTEX_UNLOCK(active_buffered_ports.mutex);
1365 }
1366 }
1367
1368 /* Utility procedure to translate Scheme arg into buffering mode */
1369 static ScmObj key_full = SCM_UNBOUND;
1370 static ScmObj key_modest = SCM_UNBOUND;
1371 static ScmObj key_line = SCM_UNBOUND;
1372 static ScmObj key_none = SCM_UNBOUND;
1373
1374 int Scm_KeywordToBufferingMode(ScmObj flag, int direction, int fallback)
1375 {
1376 if (SCM_EQ(flag, key_full)) return SCM_PORT_BUFFER_FULL;
1377 if (SCM_EQ(flag, key_none)) return SCM_PORT_BUFFER_NONE;
1378 if (fallback >= 0 && (SCM_UNBOUNDP(flag) || SCM_FALSEP(flag)))
1379 return fallback;
1380 if (direction == SCM_PORT_INPUT) {
1381 if (SCM_EQ(flag, key_modest)) return SCM_PORT_BUFFER_LINE;
1382 else Scm_Error("buffering mode must be one of :full, :modest or :none, but got %S", flag);
1383 }
1384 if (direction == SCM_PORT_OUTPUT) {
1385 if (SCM_EQ(flag, key_line)) return SCM_PORT_BUFFER_LINE;
1386 else Scm_Error("buffering mode must be one of :full, :line or :none, but got %S", flag);
1387 }
1388 /* if direction is none of input or output, allow both. */
1389 if (SCM_EQ(flag, key_line) || SCM_EQ(flag, key_modest)) {
1390 return SCM_PORT_BUFFER_LINE;
1391 }
1392 else Scm_Error("buffering mode must be one of :full, :modest, :line or :none, but got %S", flag);
1393 return -1; /* dummy */
1394 }
1395
1396 ScmObj Scm_GetPortBufferingModeAsKeyword(ScmPort *port)
1397 {
1398 if (SCM_PORT_TYPE(port) == SCM_PORT_FILE) {
1399 switch (PORT_BUFFER_MODE(port)) {
1400 case SCM_PORT_BUFFER_FULL: return key_full;
1401 case SCM_PORT_BUFFER_NONE: return key_none;
1402 default:
1403 if (SCM_IPORTP(port)) return key_modest;
1404 else return key_line;
1405 }
1406 }
1407 return SCM_FALSE;
1408 }
1409
1410 /* For the backward compatibility until release 1.0 */
1411 int Scm_BufferingMode(ScmObj flag, int direction, int fallback)
1412 {
1413 return Scm_KeywordToBufferingMode(flag, direction, fallback);
1414 }
1415
1416 ScmObj Scm_GetBufferingMode(ScmPort *port)
1417 {
1418 return Scm_GetPortBufferingModeAsKeyword(port);
1419 }
1420
1421 /*===============================================================
1422 * Generic procedures
1423 */
1424
1425 #define SAFE_PORT_OP
1426 #include "portapi.c"
1427 #undef SAFE_PORT_OP
1428 #include "portapi.c"
1429
1430 /*===============================================================
1431 * File Port
1432 */
1433
1434 /* We keep fd to PORT_BUF(p)->idata */
1435 #define FILE_PORT_FD(p) ((int)(PORT_BUF(p)->idata))
1436 #define FILE_PORT_FD_SET(p, fd) (PORT_BUF(p)->idata = (fd))
1437
1438 static ScmSize file_filler(ScmPort *p, ScmSize cnt)
1439 {
1440 ScmSize nread = 0;
1441 int fd = FILE_PORT_FD(p);
1442 char *datptr = PORT_BUF(p)->end;
1443 SCM_ASSERT(fd >= 0);
1444 while (nread == 0) {
1445 ScmSize r;
1446 errno = 0;
1447 SCM_SYSCALL(r, read(fd, datptr, cnt-nread));
1448 if (r < 0) {
1449 p->error = TRUE;
1450 Scm_SysError("read failed on %S", p);
1451 } else if (r == 0) {
1452 /* EOF is read */
1453 break;
1454 } else {
1455 datptr += r;
1456 nread += r;
1457 }
1458 }
1459 return nread;
1460 }
1461
1462 static ScmSize file_flusher(ScmPort *p, ScmSize cnt, int forcep)
1463 {
1464 ScmSize nwrote = 0;
1465 ScmSize datsiz = PORT_BUFFER_AVAIL(p);
1466 int fd = FILE_PORT_FD(p);
1467 char *datptr = PORT_BUF(p)->buffer;
1468
1469 SCM_ASSERT(fd >= 0);
1470 while ((!forcep && nwrote == 0)
1471 || (forcep && nwrote < cnt)) {
1472 ScmSize r;
1473 errno = 0;
1474 SCM_SYSCALL(r, write(fd, datptr, datsiz-nwrote));
1475 if (r < 0) {
1476 if (errno == EPIPE && PORT_BUFFER_SIGPIPE_SENSITIVE_P(p)) {
1477 /* (sort of) emulate termination by SIGPIPE.
1478 NB: The difference is visible from the outside world
1479 as the process exit status differ (WIFEXITED
1480 instead of WIFSIGNALED). If it becomes a problem,
1481 we can reset the signal handler to SIG_DFL and
1482 send SIGPIPE to self. */
1483 Scm_Exit(1); /* exit code is somewhat arbitrary */
1484 }
1485 p->error = TRUE;
1486 Scm_SysError("write failed on %S", p);
1487 } else {
1488 datptr += r;
1489 nwrote += r;
1490 }
1491 }
1492 return nwrote;
1493 }
1494
1495 static void file_closer(ScmPort *p)
1496 {
1497 int fd = FILE_PORT_FD(p);
1498 if (fd >= 0) {
1499 /* If close() fails, the port's CLOSED flag isn't set and file_closer
1500 may be called again (probably via finalizer). We don't want to call
1501 close() again and raise an error. */
1502 FILE_PORT_FD_SET(p, -1);
1503 if (close(fd) < 0) {
1504 Scm_SysError("close() failed on %S", SCM_OBJ(p));
1505 }
1506 }
1507 }
1508
1509 static int file_ready(ScmPort *p)
1510 {
1511 int fd = FILE_PORT_FD(p);
1512 SCM_ASSERT(fd >= 0);
1513 return Scm_FdReady(fd, SCM_PORT_DIR(p));
1514 }
1515
1516 static int file_filenum(ScmPort *p)
1517 {
1518 return FILE_PORT_FD(p);
1519 }
1520
1521 static off_t file_seeker(ScmPort *p, off_t offset, int whence)
1522 {
1523 return lseek(FILE_PORT_FD(p), offset, whence);
1524 }
1525
1526 /* Kludge: We should have better way */
1527 static int file_buffered_port_p(ScmPort *p)
1528 {
1529 return (PORT_BUF(p)->filenum == file_filenum);
1530 }
1531
1532 static void file_buffered_port_set_fd(ScmPort *p, int fd)
1533 {
1534 if (!file_buffered_port_p(p)) {
1535 Scm_Error("port is not directly conntect to fd: %S", p);
1536 }
1537 FILE_PORT_FD_SET(p, fd);
1538 }
1539
1540 ScmObj Scm_OpenFilePort(const char *path, int flags, int buffering, int perm)
1541 {
1542 int dir = 0;
1543
1544 if ((flags & O_ACCMODE) == O_RDONLY) dir = SCM_PORT_INPUT;
1545 else if ((flags & O_ACCMODE) == O_WRONLY) dir = SCM_PORT_OUTPUT;
1546 else Scm_Error("unsupported file access mode %d to open %s", flags&O_ACCMODE, path);
1547 if (buffering < SCM_PORT_BUFFER_FULL || buffering > SCM_PORT_BUFFER_NONE) {
1548 Scm_Error("bad buffering flag: %d", buffering);
1549 }
1550 #if defined(GAUCHE_WINDOWS)
1551 /* Force binary mode if not specified */
1552 if (!(flags & (O_TEXT|O_BINARY))) {
1553 flags |= O_BINARY;
1554 }
1555 #endif /*GAUCHE_WINDOWS*/
1556 int fd = open(path, flags, perm);
1557 if (fd < 0) return SCM_FALSE;
1558 /* In appending mode, we need to seek explicitly to the end to make
1559 port-tell returns the size of the file.
1560 We ignore the result of lseek here--it can fail if the opened file
1561 is a character device, for example, and it's ok. Any other serious
1562 errors would be caught by later operations anyway.
1563 */
1564 if (flags & O_APPEND) (void)lseek(fd, 0, SEEK_END);
1565
1566 ScmPortBuffer bufrec;
1567 bufrec.mode = buffering;
1568 bufrec.buffer = NULL;
1569 bufrec.size = 0;
1570 bufrec.filler = file_filler;
1571 bufrec.flusher = file_flusher;
1572 bufrec.closer = file_closer;
1573 bufrec.ready = file_ready;
1574 bufrec.filenum = file_filenum;
1575 bufrec.seeker = file_seeker;
1576 bufrec.data = NULL;
1577 bufrec.idata = fd;
1578 ScmObj p = Scm_MakeBufferedPort(SCM_CLASS_PORT, SCM_MAKE_STR_COPYING(path),
1579 dir, TRUE, &bufrec);
1580 return p;
1581 }
1582
1583 /* Create a port on specified file descriptor.
1584 NAME - used for the name of the port.
1585 DIRECTION - either SCM_PORT_INPUT or SCM_PORT_OUTPUT
1586 FD - the opened file descriptor.
1587 BUFMODE - buffering mode (ScmPortBufferMode)
1588 OWNERP - if TRUE, fd will be closed when this port is closed.
1589 */
1590 ScmObj Scm_MakePortWithFd(ScmObj name, int direction,
1591 int fd, int bufmode, int ownerp)
1592 {
1593 ScmPortBuffer bufrec;
1594 bufrec.buffer = NULL;
1595 bufrec.size = 0;
1596 bufrec.mode = bufmode;
1597 bufrec.filler = file_filler;
1598 bufrec.flusher =file_flusher;
1599 bufrec.closer = file_closer;
1600 bufrec.ready = file_ready;
1601 bufrec.filenum = file_filenum;
1602 bufrec.data = NULL;
1603 bufrec.idata = fd;
1604
1605 /* Check if the given fd is seekable, and set seeker if so. */
1606 if (lseek(fd, 0, SEEK_CUR) < 0) {
1607 bufrec.seeker = NULL;
1608 } else {
1609 bufrec.seeker = file_seeker;
1610 }
1611
1612 ScmObj p = Scm_MakeBufferedPort(SCM_CLASS_PORT, name, direction, ownerp,
1613 &bufrec);
1614 return p;
1615 }
1616
1617 /*===============================================================
1618 * String port
1619 */
1620
1621 ScmObj Scm_MakeInputStringPortFull(ScmString *str, ScmObj name,
1622 u_long flags)
1623 {
1624 ScmPort *p = make_port(SCM_CLASS_PORT, name, SCM_PORT_INPUT, SCM_PORT_ISTR);
1625 const ScmStringBody *sb = SCM_STRING_BODY(str);
1626 PORT_ISTR(p)->start = SCM_STRING_BODY_START(sb);
1627 PORT_ISTR(p)->current = SCM_STRING_BODY_START(sb);
1628 PORT_ISTR(p)->end = SCM_STRING_BODY_END(sb);
1629 if (flags&SCM_PORT_STRING_PRIVATE) PORT_PRELOCK(p, Scm_VM());
1630 return SCM_OBJ(p);
1631 }
1632
1633 /* deprecated */
1634 ScmObj Scm_MakeInputStringPort(ScmString *str, int privatep)
1635 {
1636 return Scm_MakeInputStringPortFull(str,
1637 SCM_MAKE_STR("(input string port)"),
1638 (privatep?SCM_PORT_STRING_PRIVATE:0));
1639 }
1640
1641 ScmObj Scm_MakeOutputStringPortFull(ScmObj name, u_long flags)
1642 {
1643 ScmPort *p = make_port(SCM_CLASS_PORT, name, SCM_PORT_OUTPUT, SCM_PORT_OSTR);
1644 Scm_DStringInit(PORT_OSTR(p));
1645 if (flags&SCM_PORT_STRING_PRIVATE) PORT_PRELOCK(p, Scm_VM());
1646 return SCM_OBJ(p);
1647 }
1648
1649 /* deprecated */
1650 ScmObj Scm_MakeOutputStringPort(int privatep)
1651 {
1652 return Scm_MakeOutputStringPortFull(SCM_MAKE_STR("(output string port)"),
1653 (privatep?SCM_PORT_STRING_PRIVATE:0));
1654 }
1655
1656 ScmObj Scm_GetOutputString(ScmPort *port, int flags)
1657 {
1658 if (SCM_PORT_TYPE(port) != SCM_PORT_OSTR)
1659 Scm_Error("output string port required, but got %S", port);
1660 ScmVM *vm = Scm_VM();
1661 PORT_LOCK(port, vm);
1662 ScmObj r = Scm_DStringGet(PORT_OSTR(port), flags);
1663 PORT_UNLOCK(port);
1664 return r;
1665 }
1666
1667 ScmObj Scm_GetOutputStringUnsafe(ScmPort *port, int flags)
1668 {
1669 if (SCM_PORT_TYPE(port) != SCM_PORT_OSTR)
1670 Scm_Error("output string port required, but got %S", port);
1671 return Scm_DStringGet(PORT_OSTR(port), flags);
1672 }
1673
1674 static ScmObj get_remaining_input_string_aux(const char *s, ScmSize ssiz,
1675 const char *p, ScmSize psiz,
1676 int flags);
1677
1678 ScmObj Scm_GetRemainingInputString(ScmPort *port, int flags)
1679 {
1680 if (SCM_PORT_TYPE(port) != SCM_PORT_ISTR)
1681 Scm_Error("input string port required, but got %S", port);
1682 /* NB: we don't need to lock the port, since the string body
1683 the port is pointing won't be changed. */
1684 const char *ep = PORT_ISTR(port)->end;
1685 const char *cp = PORT_ISTR(port)->current;
1686 /* Things gets complicated if there's an ungotten char or bytes.
1687 We want to share the string body whenever possible, so we
1688 first check the ungotten stuff matches the content of the
1689 buffer. */
1690 if (PORT_UNGOTTEN(port) != SCM_CHAR_INVALID) {
1691 char cbuf[SCM_CHAR_MAX_BYTES];
1692 int nbytes = SCM_CHAR_NBYTES(PORT_UNGOTTEN(port));
1693 SCM_CHAR_PUT(cbuf, PORT_UNGOTTEN(port));
1694 const char *sp = PORT_ISTR(port)->start;
1695 if (cp - sp >= nbytes
1696 && memcmp(cp - nbytes, cbuf, nbytes) == 0) {
1697 cp -= nbytes; /* we can reuse buffer */
1698 return Scm_MakeString(cp, (int)(ep-cp), -1, flags);
1699 } else {
1700 /* we need to copy */
1701 return get_remaining_input_string_aux(cp, ep-cp,
1702 cbuf, nbytes, flags);
1703 }
1704 } else if (port->scrcnt > 0) {
1705 const char *sp = PORT_ISTR(port)->start;
1706 if (cp - sp >= (int)port->scrcnt
1707 && memcmp(cp - port->scrcnt, PORT_SCRATCH(port), port->scrcnt) == 0) {
1708 cp -= port->scrcnt; /* we can reuse buffer */
1709 return Scm_MakeString(cp, (int)(ep-cp), -1, flags);
1710 } else {
1711 /* we need to copy */
1712 return get_remaining_input_string_aux(cp, ep-cp,
1713 PORT_SCRATCH(port),
1714 port->scrcnt, flags);
1715 }
1716 } else {
1717 return Scm_MakeString(cp, (int)(ep-cp), -1, flags);
1718 }
1719 }
1720
1721 static ScmObj get_remaining_input_string_aux(const char *s, ScmSize ssiz,
1722 const char *p, ScmSize psiz,
1723 int flags)
1724 {
1725 char *b = SCM_NEW_ATOMIC2(char *, psiz+ssiz+1);
1726 memcpy(b, p, psiz);
1727 memcpy(b+psiz, s, ssiz);
1728 b[psiz+ssiz] = '\0';
1729 return Scm_MakeString(b, psiz+ssiz, -1, flags);
1730 }
1731
1732 /*===============================================================
1733 * Procedural port
1734 */
1735
1736 /* To create a procedural port, fill in the ScmPortVTable function
1737 pointers and pass it to Scm_MakeVirtualPort. You don't need to
1738 provide all the functions; put NULL if you think you don't
1739 provide the functionality.
1740 */
1741
1742 /* default dummy procedures */
1743 static int null_getb(ScmPort *dummy SCM_UNUSED)
1744 {
1745 return EOF;
1746 }
1747
1748 static int null_getc(ScmPort *dummy SCM_UNUSED)
1749 {
1750 return EOF;
1751 }
1752
1753 static ScmSize null_getz(char *buf SCM_UNUSED,
1754 ScmSize buflen SCM_UNUSED,
1755 ScmPort *dummy SCM_UNUSED)
1756 {
1757 return 0;
1758 }
1759
1760 static int null_ready(ScmPort *dummy SCM_UNUSED, int charp SCM_UNUSED)
1761 {
1762 return TRUE;
1763 }
1764
1765 static void null_putb(ScmByte b SCM_UNUSED, ScmPort *dummy SCM_UNUSED)
1766 {
1767 }
1768
1769 static void null_putc(ScmChar c SCM_UNUSED, ScmPort *dummy SCM_UNUSED)
1770 {
1771 }
1772
1773 static void null_putz(const char *str SCM_UNUSED,
1774 ScmSize len SCM_UNUSED,
1775 ScmPort *dummy SCM_UNUSED)
1776 {
1777 }
1778
1779 static void null_puts(ScmString *s SCM_UNUSED, ScmPort *dummy SCM_UNUSED)
1780 {
1781 }
1782
1783 static void null_flush(ScmPort *dummy SCM_UNUSED)
1784 {
1785 }
1786
1787 ScmObj Scm_MakeVirtualPortFull(ScmClass *klass, ScmObj name,
1788 int direction,
1789 const ScmPortVTable *vtable,
1790 u_long flags SCM_UNUSED)
1791 {
1792 ScmPort *p = make_port(klass, name, direction, SCM_PORT_PROC);
1793
1794 /* Initialize default values */
1795 PORT_VT(p)->Getb = null_getb;
1796 PORT_VT(p)->Getc = null_getc;
1797 PORT_VT(p)->Getz = null_getz;
1798 PORT_VT(p)->Ready = null_ready;
1799 PORT_VT(p)->Putb = null_putb;
1800 PORT_VT(p)->Putc = null_putc;
1801 PORT_VT(p)->Putz = null_putz;
1802 PORT_VT(p)->Puts = null_puts;
1803 PORT_VT(p)->Flush = null_flush;
1804 PORT_VT(p)->Close = NULL;
1805 PORT_VT(p)->Seek = NULL;
1806 PORT_VT(p)->data = NULL;
1807 PORT_VT(p)->GetPos = NULL;
1808 PORT_VT(p)->SetPos = NULL;
1809 PORT_VT(p)->flags = 0;
1810
1811 if (vtable->Getb) PORT_VT(p)->Getb = vtable->Getb;
1812 if (vtable->Getc) PORT_VT(p)->Getc = vtable->Getc;
1813 if (vtable->Getz) PORT_VT(p)->Getz = vtable->Getz;
1814 if (vtable->Ready) PORT_VT(p)->Ready = vtable->Ready;
1815 if (vtable->Putb) PORT_VT(p)->Putb = vtable->Putb;
1816 if (vtable->Putc) PORT_VT(p)->Putc = vtable->Putc;
1817 if (vtable->Putz) PORT_VT(p)->Putz = vtable->Putz;
1818 if (vtable->Puts) PORT_VT(p)->Puts = vtable->Puts;
1819 if (vtable->Flush) PORT_VT(p)->Flush = vtable->Flush;
1820 if (vtable->Close) PORT_VT(p)->Close = vtable->Close;
1821 if (vtable->Seek) PORT_VT(p)->Seek = vtable->Seek;
1822 PORT_VT(p)->data = vtable->data;
1823 PORT_VT(p)->idata = vtable->idata;
1824
1825 /* When the port is GC'ed without properly closed, a finalizer is
1826 run to clean up. However, at that moment, PORT_VT(p)->data
1827 may be already collected. We should detect the case.
1828 */
1829 if (GC_is_heap_ptr(vtable->data)) {
1830 PORT_PROC_EXTDATA_SET(p);
1831 GC_register_disappearing_link((void**)&PORT_VT(p)->data);
1832 }
1833
1834 if (flags & SCM_PORT_WITH_POSITION) {
1835 if (vtable->GetPos) PORT_VT(p)->GetPos = vtable->GetPos;
1836 if (vtable->SetPos) PORT_VT(p)->SetPos = vtable->SetPos;
1837 PORT_VT(p)->flags = vtable->flags;
1838 }
1839
1840 return SCM_OBJ(p);
1841 }
1842
1843 /* deprecated */
1844 ScmObj Scm_MakeVirtualPort(ScmClass *klass,
1845 int direction,
1846 const ScmPortVTable *vtable)
1847 {
1848 return Scm_MakeVirtualPortFull(klass, SCM_FALSE, direction, vtable, 0);
1849 }
1850
1851 /*===============================================================
1852 * Coding-aware port
1853 */
1854
1855 /* Coding-aware port wraps an input port, and specifically recognizes
1856 'coding' magic comment. It is primarily used when loading source
1857 code, but can be used separately. */
1858
1859 static ScmPort *(*coding_aware_port_hook)(ScmPort *src,
1860 const char *srcencoding) = NULL;
1861
1862 /* gauche.charconv sets the pointer */
1863 void Scm__InstallCodingAwarePortHook(ScmPort *(*f)(ScmPort*, const char*))
1864 {
1865 coding_aware_port_hook = f;
1866 }
1867
1868 #define CODING_MAGIC_COMMENT_LINES 2 /* maximum number of lines to be
1869 looked at for the 'encoding' magic
1870 comment. */
1871
1872 typedef struct coding_port_data_rec {
1873 ScmPort *source; /* source port */
1874 int state; /* port state; see below */
1875 const char *pbuf; /* prefetched buffer. NUL terminated.
1876 contains at most CODING_MAGIC_COMMENT_LINES
1877 newlines. */
1878 int pbufsize; /* # of bytes in pbuf */
1879 } coding_port_data;
1880
1881 enum {
1882 CODING_PORT_INIT, /* initial state */
1883 CODING_PORT_RECOGNIZED, /* prefetched up to two lines, and
1884 conversion port is set if necessary.
1885 there are buffered data in lines[]. */
1886 CODING_PORT_FLUSHED /* prefetched lines are flushed. */
1887 };
1888
1889 /* A hardcoded DFA to recognize #/;.*coding[:=]\s*([\w.-]+)/ */
1890 static const char *look_for_encoding(const char *buf)
1891 {
1892 const char *s;
1893
1894 init:
1895 for (;;) {
1896 switch (*buf++) {
1897 case '\0': return NULL;
1898 case ';': goto comment;
1899 }
1900 }
1901 comment:
1902 for (;;) {
1903 switch (*buf++) {
1904 case '\0': return NULL;
1905 case '\n': goto init;
1906 case '\r': if (*buf != '\n') goto init; break;
1907 case 'c' : goto coding;
1908 }
1909 }
1910 coding:
1911 if (strncmp(buf, "oding", 5) != 0) goto comment;
1912 buf+=5;
1913 if (*buf != ':' && *buf != '=') goto comment;
1914 for (buf++;;buf++) {
1915 if (*buf != ' ' && *buf != '\t') break;
1916 }
1917 if (*buf == '\0') return NULL;
1918
1919 for (s = buf;*buf;buf++) {
1920 if (!isalnum(*buf) && *buf != '_' && *buf != '-' && *buf != '.') {
1921 break;
1922 }
1923 }
1924 if (s == buf) goto comment;
1925
1926 /* Here we found a matching string, starting from s and ends at buf. */
1927
1928 /* kludge: Emacs uses special suffix #/-(unix|dos|mac)$/ to distinguish
1929 EOL variants. For compatibility, drop such suffix if we have one. */
1930 if (buf-s > 5 && (strncmp(buf-5, "-unix", 5) == 0)) {
1931 buf -= 5;
1932 } else if (buf-s > 4 && (strncmp(buf-4, "-dos", 4) == 0
1933 || strncmp(buf-4, "-mac", 4) == 0)) {
1934 buf -= 4;
1935 }
1936
1937 /* Copy and return the encoding string */
1938 return SCM_STRDUP_PARTIAL(s, buf-s);
1939 }
1940
1941 static void coding_port_recognize_encoding(ScmPort *port,
1942 coding_port_data *data)
1943 {
1944 int num_newlines = 0;
1945 int cr_seen = FALSE;
1946
1947 SCM_ASSERT(data->source != NULL);
1948
1949 /* Prefetch up to CODING_MAGIC_COMMENT_LINES lines or the first NUL
1950 character. data->pbuf ends up holding NUL terminated string. */
1951 ScmDString ds;
1952 Scm_DStringInit(&ds);
1953 for (;num_newlines < CODING_MAGIC_COMMENT_LINES;) {
1954 int c = Scm_GetbUnsafe(data->source);
1955 if (c == EOF) break;
1956 if (c == 0) {
1957 /* take extra care not to lose '\0' */
1958 Scm_UngetbUnsafe(c, data->source);
1959 break;
1960 }
1961 SCM_DSTRING_PUTB(&ds, c);
1962 if (c == '\r') { /* for the source that only uses '\r' */
1963 if (cr_seen) num_newlines++;
1964 cr_seen = TRUE;
1965 } else if (c == '\n' || cr_seen) {
1966 num_newlines++;
1967 cr_seen = FALSE;
1968 } else {
1969 cr_seen = FALSE;
1970 }
1971 }
1972 data->pbuf = Scm_DStringGetz(&ds);
1973 data->pbufsize = (int)strlen(data->pbuf);
1974
1975 /* Look for the magic comment */
1976 const char *encoding = NULL;
1977 encoding = look_for_encoding(data->pbuf);
1978
1979 /* Wrap the source port by conversion port, if necessary. */
1980 if (encoding == NULL || Scm_SupportedCharacterEncodingP(encoding)) {
1981 return;
1982 }
1983
1984 if (coding_aware_port_hook == NULL) {
1985 /* Require gauche.charconv.
1986 NB: we don't need mutex here, for loading the module is
1987 serialized in Scm_Require. */
1988 Scm_Require(SCM_MAKE_STR("gauche/charconv"),
1989 SCM_LOAD_PROPAGATE_ERROR, NULL);
1990 if (coding_aware_port_hook == NULL) {
1991 Scm_PortError(port, SCM_PORT_ERROR_OTHER,
1992 "couldn't load gauche.charconv module");
1993 }
1994 }
1995 data->source = coding_aware_port_hook(data->source, encoding);
1996 }
1997
1998 static ScmSize coding_filler(ScmPort *p, ScmSize cnt)
1999 {
2000 ScmSize nread = 0;
2001 coding_port_data *data = (coding_port_data*)PORT_BUF(p)->data;
2002 char *datptr = PORT_BUF(p)->end;
2003
2004 SCM_ASSERT(data->source);
2005
2006 /* deals with the most frequent case */
2007 if (data->state == CODING_PORT_FLUSHED) {
2008 return Scm_GetzUnsafe(datptr, cnt, data->source);
2009 }
2010
2011 if (data->state == CODING_PORT_INIT) {
2012 coding_port_recognize_encoding(p, data);
2013 data->state = CODING_PORT_RECOGNIZED;
2014 }
2015
2016 /* Here, we have data->state == CODING_PORT_RECOGNIZED */
2017 if (data->pbufsize > 0) {
2018 if (data->pbufsize <= cnt) {
2019 memcpy(datptr, data->pbuf, data->pbufsize);
2020 nread = data->pbufsize;
2021 data->pbuf = NULL;
2022 data->pbufsize = 0;
2023 data->state = CODING_PORT_FLUSHED;
2024 } else {
2025 memcpy(datptr, data->pbuf, cnt);
2026 nread = cnt;
2027 data->pbuf += cnt;
2028 data->pbufsize -= cnt;
2029 }
2030 return nread;
2031 } else {
2032 data->state = CODING_PORT_FLUSHED;
2033 return Scm_GetzUnsafe(datptr, cnt, data->source);
2034 }
2035 }
2036
2037 static void coding_closer(ScmPort *p)
2038 {
2039 coding_port_data *data = (coding_port_data*)PORT_BUF(p)->data;
2040 if (data->source) {
2041 Scm_ClosePort(data->source);
2042 data->source = NULL;
2043 }
2044 }
2045
2046 static int coding_ready(ScmPort *p)
2047 {
2048 coding_port_data *data = (coding_port_data*)PORT_BUF(p)->data;
2049 if (data->source == NULL) return TRUE;
2050 if (data->state == CODING_PORT_RECOGNIZED) {
2051 return SCM_FD_READY;
2052 } else {
2053 return Scm_ByteReadyUnsafe(p);
2054 }
2055 }
2056
2057 static int coding_filenum(ScmPort *p)
2058 {
2059 coding_port_data *data = (coding_port_data*)PORT_BUF(p)->data;
2060 if (data->source == NULL) return -1;
2061 return Scm_PortFileNo(data->source);
2062 }
2063
2064 ScmObj Scm_MakeCodingAwarePort(ScmPort *iport)
2065 {
2066 if (!SCM_IPORTP(iport)) {
2067 Scm_Error("open-coding-aware-port requires an input port, but got %S", iport);
2068 }
2069 coding_port_data *data = SCM_NEW(coding_port_data);
2070 data->source = iport;
2071 data->state = CODING_PORT_INIT;
2072 data->pbuf = NULL;
2073 data->pbufsize = 0;
2074
2075 ScmPortBuffer bufrec;
2076 bufrec.mode = SCM_PORT_BUFFER_FULL;
2077 bufrec.buffer = NULL;
2078 bufrec.size = 0;
2079 bufrec.filler = coding_filler;
2080 bufrec.flusher = NULL;
2081 bufrec.closer = coding_closer;
2082 bufrec.ready = coding_ready;
2083 bufrec.filenum = coding_filenum;
2084 bufrec.seeker = NULL;
2085 bufrec.data = (void*)data;
2086 ScmObj p = Scm_MakeBufferedPort(SCM_CLASS_CODING_AWARE_PORT,
2087 Scm_PortName(iport), SCM_PORT_INPUT,
2088 TRUE, &bufrec);
2089 return p;
2090 }
2091
2092 /*===============================================================
2093 * Standard ports
2094 */
2095
2096 static ScmObj scm_stdin = SCM_UNBOUND;
2097 static ScmObj scm_stdout = SCM_UNBOUND;
2098 static ScmObj scm_stderr = SCM_UNBOUND;
2099
2100 #define DEFSTDPORT(Name, var) \
2101 ScmObj SCM_CPP_CAT(Scm_, Name)(void) \
2102 { \
2103 return var; \
2104 } \
2105 ScmObj SCM_CPP_CAT(Scm_Set, Name)(ScmPort *port) \
2106 { \
2107 ScmObj oldp = var; \
2108 var = SCM_OBJ(port); \
2109 return oldp; \
2110 }
2111
2112 DEFSTDPORT(Stdin, scm_stdin)
2113 DEFSTDPORT(Stdout, scm_stdout)
2114 DEFSTDPORT(Stderr, scm_stderr)
2115
2116 /* Parameters */
2117 static ScmPrimitiveParameter *scm_curin = NULL;
2118 static ScmPrimitiveParameter *scm_curout = NULL;
2119 static ScmPrimitiveParameter *scm_curerr = NULL;
2120
2121 ScmPort *Scm_CurrentInputPort()
2122 {
2123 return SCM_PORT(Scm_PrimitiveParameterRef(Scm_VM(), scm_curin));
2124 }
2125
2126 ScmPort *Scm_CurrentOutputPort()
2127 {
2128 return SCM_PORT(Scm_PrimitiveParameterRef(Scm_VM(), scm_curout));
2129 }
2130
2131 ScmPort *Scm_CurrentErrorPort()
2132 {
2133 return SCM_PORT(Scm_PrimitiveParameterRef(Scm_VM(), scm_curerr));
2134 }
2135
2136 ScmObj Scm_SetCurrentInputPort(ScmPort *port)
2137 {
2138 return Scm_PrimitiveParameterSet(Scm_VM(), scm_curin, SCM_OBJ(port));
2139 }
2140
2141 ScmObj Scm_SetCurrentOutputPort(ScmPort *port)
2142 {
2143 return Scm_PrimitiveParameterSet(Scm_VM(), scm_curout, SCM_OBJ(port));
2144 }
2145
2146 ScmObj Scm_SetCurrentErrorPort(ScmPort *port)
2147 {
2148 return Scm_PrimitiveParameterSet(Scm_VM(), scm_curerr, SCM_OBJ(port));
2149 }
2150
2151 /*===============================================================
2152 * Initialization
2153 */
2154 void Scm__InitPort(void)
2155 {
2156 if (sizeof(ScmPort) < sizeof(ScmPortImpl)) {
2157 fprintf(stderr,
2158 "sizeof(ScmPort) [%"PRIdPTR"] is smaller than "
2159 "sizeof(ScmPortImpl) [%"PRIdPTR"]\n",
2160 SCM_WORD(sizeof(ScmPort)), SCM_WORD(sizeof(ScmPortImpl)));
2161 Scm_Panic("Implementation error. Exitting.");
2162 }
2163
2164 (void)SCM_INTERNAL_MUTEX_INIT(active_buffered_ports.mutex);
2165 active_buffered_ports.ports = SCM_WEAK_VECTOR(Scm_MakeWeakVector(PORT_VECTOR_SIZE));
2166
2167 Scm_InitStaticClass(&Scm_PortClass, "<port>",
2168 Scm_GaucheModule(), port_slots, 0);
2169 Scm_InitStaticClass(&Scm_CodingAwarePortClass, "<coding-aware-port>",
2170 Scm_GaucheModule(), port_slots, 0);
2171
2172 /* This must be done before *any* port is created. */
2173 readerLexicalMode =
2174 Scm_BindPrimitiveParameter(Scm_GaucheModule(), "reader-lexical-mode",
2175 SCM_OBJ(SCM_SYM_PERMISSIVE), 0);
2176
2177 scm_stdin = Scm_MakePortWithFd(SCM_MAKE_STR("(standard input)"),
2178 SCM_PORT_INPUT, 0,
2179 SCM_PORT_BUFFER_FULL, TRUE);
2180 /* By default, stdout and stderr are SIGPIPE sensitive */
2181 scm_stdout = Scm_MakePortWithFd(SCM_MAKE_STR("(standard output)"),
2182 SCM_PORT_OUTPUT, 1,
2183 ((isatty(1)
2184 ? SCM_PORT_BUFFER_LINE
2185 : SCM_PORT_BUFFER_FULL)
2186 | SCM_PORT_BUFFER_SIGPIPE_SENSITIVE),
2187 TRUE);
2188 scm_stderr = Scm_MakePortWithFd(SCM_MAKE_STR("(standard error output)"),
2189 SCM_PORT_OUTPUT, 2,
2190 (SCM_PORT_BUFFER_NONE
2191 | SCM_PORT_BUFFER_SIGPIPE_SENSITIVE),
2192 TRUE);
2193
2194 scm_curin = Scm_BindPrimitiveParameter(Scm_SchemeModule(),
2195 "current-input-port",
2196 scm_stdin, 0);
2197 scm_curout = Scm_BindPrimitiveParameter(Scm_SchemeModule(),
2198 "current-output-port",
2199 scm_stdout, 0);
2200 scm_curerr = Scm_BindPrimitiveParameter(Scm_GaucheModule(),
2201 "current-error-port",
2202 scm_stderr, 0);
2203
2204 key_full = Scm_MakeKeyword(SCM_STRING(SCM_MAKE_STR("full")));
2205 key_modest = Scm_MakeKeyword(SCM_STRING(SCM_MAKE_STR("modest")));
2206 key_line = Scm_MakeKeyword(SCM_STRING(SCM_MAKE_STR("line")));
2207 key_none = Scm_MakeKeyword(SCM_STRING(SCM_MAKE_STR("none")));
2208 }
2209
2210 /* Windows specific:
2211
2212 When we run Windows no-console mode, stdios are bogus (gosh-noconsole
2213 wires them to NUL device, but when libgauche is called from other
2214 applications, we can't assume that.) It is too painful to be so,
2215 since when Scheme program tries to write to stdout or stderr it just
2216 crashes without any information at all.
2217
2218 So, this function re-wires Scheme standard output and error output
2219 to a special port; when an output is made for the first time
2220 the port opens up a console by AllocConsole(), and redirects further
2221 output to it.
2222
2223 Unfortunately we can't do this at initialization time, since
2224 Scm_Init() doesn't have a way to know whether we're in console mode
2225 or not. Only the application knows, thus it needs to call this API
2226 after Scheme system is initialized.
2227 */
2228 #if defined(GAUCHE_WINDOWS)
2229
2230 static ScmInternalMutex win_console_mutex;
2231 static int win_console_created = FALSE;
2232
2233 static void prepare_console_and_stdio(const char *devname, int flags,
2234 DWORD nStdHandle, int fd,
2235 int *initialized)
2236 {
2237 HANDLE h;
2238 SECURITY_ATTRIBUTES sa;
2239 int temp_fd = -1;
2240 int err = 0;
2241 #define ERR_CREATEFILE 1
2242 #define ERR_OPEN_OSFHANDLE 2
2243 #define ERR_DUP2 3
2244 #define ERR_SETSTDHANDLE 4
2245
2246 SCM_INTERNAL_MUTEX_LOCK(win_console_mutex);
2247 if (!win_console_created) {
2248 win_console_created = TRUE;
2249 AllocConsole();
2250 }
2251 if (!(*initialized)) {
2252 /* NB: Double fault will be caught in the error handling
2253 mechanism, so we don't need to worry it here. */
2254 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2255 sa.lpSecurityDescriptor = NULL;
2256 sa.bInheritHandle = TRUE;
2257 h = CreateFile(SCM_MBS2WCS(devname),
2258 GENERIC_READ | GENERIC_WRITE,
2259 FILE_SHARE_READ | FILE_SHARE_WRITE,
2260 &sa, OPEN_EXISTING, 0, NULL);
2261 if (h == INVALID_HANDLE_VALUE) {
2262 err = ERR_CREATEFILE;
2263 } else if ((temp_fd = _open_osfhandle((intptr_t)h, flags)) < 0) {
2264 err = ERR_OPEN_OSFHANDLE;
2265 } else if (_dup2(temp_fd, fd) < 0) {
2266 err = ERR_DUP2;
2267 } else if (SetStdHandle(nStdHandle, (HANDLE)_get_osfhandle(fd)) == 0) {
2268 err = ERR_SETSTDHANDLE;
2269 } else {
2270 *initialized = TRUE;
2271 }
2272 }
2273 SCM_INTERNAL_MUTEX_UNLOCK(win_console_mutex);
2274
2275 if (temp_fd >= 0) close(temp_fd);
2276 switch (err) {
2277 case ERR_CREATEFILE:
2278 Scm_SysError("CreateFile(%s) failed", devname);
2279 break; /* Dummy */
2280 case ERR_OPEN_OSFHANDLE:
2281 CloseHandle(h);
2282 Scm_SysError("_open_osfhandle failed (fd = %d)", fd);
2283 break; /* Dummy */
2284 case ERR_DUP2:
2285 CloseHandle(h);
2286 Scm_SysError("dup2(%d) failed (osf_handle)", fd);
2287 break; /* Dummy */
2288 case ERR_SETSTDHANDLE:
2289 CloseHandle(h);
2290 Scm_SysError("SetStdHandle(%d) failed (fd = %d)", (int)nStdHandle, fd);
2291 break; /* Dummy */
2292 }
2293
2294 #undef ERR_CREATEFILE
2295 #undef ERR_OPEN_OSFHANDLE
2296 #undef ERR_DUP2
2297 #undef ERR_SETSTDHANDLE
2298 }
2299
2300 static ScmSize trapper_filler(ScmPort *p, ScmSize cnt)
2301 {
2302 static int initialized = FALSE;
2303 prepare_console_and_stdio("CONIN$", _O_RDONLY | _O_BINARY,
2304 STD_INPUT_HANDLE, 0, &initialized);
2305 return file_filler(p, cnt);
2306 }
2307
2308 static ScmSize trapper_flusher1(ScmPort *p, ScmSize cnt, int forcep)
2309 {
2310 static int initialized = FALSE;
2311 prepare_console_and_stdio("CONOUT$", _O_WRONLY | _O_BINARY,
2312 STD_OUTPUT_HANDLE, 1, &initialized);
2313 return file_flusher(p, cnt, forcep);
2314 }
2315
2316 static ScmSize trapper_flusher2(ScmPort *p, ScmSize cnt, int forcep)
2317 {
2318 static int initialized = FALSE;
2319 prepare_console_and_stdio("CONOUT$", _O_WRONLY | _O_BINARY,
2320 STD_ERROR_HANDLE, 2, &initialized);
2321 return file_flusher(p, cnt, forcep);
2322 }
2323
2324 static ScmObj make_trapper_port(ScmObj name, int direction,
2325 int fd, int bufmode)
2326 {
2327 ScmPortBuffer bufrec;
2328
2329 bufrec.buffer = NULL;
2330 bufrec.size = 0;
2331 bufrec.mode = bufmode;
2332 if (fd == 0) {
2333 bufrec.filler = trapper_filler;
2334 } else {
2335 bufrec.filler = NULL;
2336 }
2337 if (fd == 1) {
2338 bufrec.flusher = trapper_flusher1;
2339 } else if (fd == 2) {
2340 bufrec.flusher = trapper_flusher2;
2341 } else {
2342 bufrec.flusher = NULL;
2343 }
2344 bufrec.closer = file_closer;
2345 bufrec.ready = file_ready;
2346 bufrec.filenum = file_filenum;
2347 bufrec.data = NULL;
2348 bufrec.idata = fd;
2349 bufrec.seeker = NULL;
2350 ScmObj p = Scm_MakeBufferedPort(SCM_CLASS_PORT, name, direction, TRUE,
2351 &bufrec);
2352 return p;
2353 }
2354
2355 /* This is supposed to be called from application main(), before any
2356 threads are created. We don't mutex here. */
2357 void Scm__SetupPortsForWindows(int has_console)
2358 {
2359 if (!has_console) {
2360 static int initialized = FALSE;
2361 static volatile ScmObj orig_stdin = SCM_FALSE;
2362 static volatile ScmObj orig_stdout = SCM_FALSE;
2363 static volatile ScmObj orig_stderr = SCM_FALSE;
2364 if (!initialized) {
2365 initialized = TRUE;
2366 SCM_INTERNAL_MUTEX_INIT(win_console_mutex);
2367 /* Original scm_stdout and scm_stderr holds ports that are
2368 connected to fd=0 and fd=1, respectively. Losing reference
2369 to those ports will eventually lead to close those fds (when
2370 those ports are GC-ed), causing complications in the code
2371 that assumes fds 0, 1 and 2 are reserved. To make things
2372 easier, we just save the original ports. */
2373 orig_stdin = scm_stdin;
2374 orig_stdout = scm_stdout;
2375 orig_stderr = scm_stderr;
2376 /* We know the destination is allocated Windows Console, so we
2377 just use fixed buffered modes. */
2378 scm_stdin = make_trapper_port(SCM_MAKE_STR("(standard input)"),
2379 SCM_PORT_INPUT, 0,
2380 SCM_PORT_BUFFER_FULL);
2381 scm_stdout = make_trapper_port(SCM_MAKE_STR("(standard output)"),
2382 SCM_PORT_OUTPUT, 1,
2383 SCM_PORT_BUFFER_LINE);
2384 scm_stderr = make_trapper_port(SCM_MAKE_STR("(standard error output)"),
2385 SCM_PORT_OUTPUT, 2,
2386 SCM_PORT_BUFFER_NONE);
2387 Scm_SetCurrentInputPort(SCM_PORT(scm_stdin));
2388 Scm_SetCurrentOutputPort(SCM_PORT(scm_stdout));
2389 Scm_SetCurrentErrorPort(SCM_PORT(scm_stderr));
2390 }
2391 (void)orig_stdin; /* suppress unused var warning */
2392 (void)orig_stdout; /* suppress unused var warning */
2393 (void)orig_stderr; /* suppress unused var warning */
2394 }
2395 }
2396 #endif /*defined(GAUCHE_WINDOWS)*/