Debian Codegraph @

generic/tclIORChan.c

raw
1 /*
2 * tclIORChan.c --
3 *
4 * This file contains the implementation of Tcl's generic channel
5 * reflection code, which allows the implementation of Tcl channels in
6 * Tcl code.
7 *
8 * Parts of this file are based on code contributed by Jean-Claude
9 * Wippler.
10 *
11 * See TIP #219 for the specification of this functionality.
12 *
13 * Copyright (c) 2004-2005 ActiveState, a division of Sophos
14 *
15 * See the file "license.terms" for information on usage and redistribution of
16 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
17 */
18
19 #include "tclInt.h"
20 #include "tclIO.h"
21 #include <assert.h>
22
23 #ifndef EINVAL
24 #define EINVAL 9
25 #endif
26 #ifndef EOK
27 #define EOK 0
28 #endif
29
30 /*
31 * Signatures of all functions used in the C layer of the reflection.
32 */
33
34 static int ReflectClose(void *clientData,
35 Tcl_Interp *interp);
36 static int ReflectClose2(void *clientData,
37 Tcl_Interp *interp, int flags);
38 static int ReflectInput(void *clientData, char *buf,
39 int toRead, int *errorCodePtr);
40 static int ReflectOutput(void *clientData, const char *buf,
41 int toWrite, int *errorCodePtr);
42 static void ReflectWatch(void *clientData, int mask);
43 static int ReflectBlock(void *clientData, int mode);
44 #ifdef TCL_THREADS
45 static void ReflectThread(void *clientData, int action);
46 static int ReflectEventRun(Tcl_Event *ev, int flags);
47 static int ReflectEventDelete(Tcl_Event *ev, void *cd);
48 #endif
49 static Tcl_WideInt ReflectSeekWide(void *clientData,
50 Tcl_WideInt offset, int mode, int *errorCodePtr);
51 static int ReflectSeek(void *clientData, long offset,
52 int mode, int *errorCodePtr);
53 static int ReflectGetOption(void *clientData,
54 Tcl_Interp *interp, const char *optionName,
55 Tcl_DString *dsPtr);
56 static int ReflectSetOption(void *clientData,
57 Tcl_Interp *interp, const char *optionName,
58 const char *newValue);
59
60 /*
61 * The C layer channel type/driver definition used by the reflection.
62 */
63
64 static const Tcl_ChannelType tclRChannelType = {
65 "tclrchannel", /* Type name. */
66 TCL_CHANNEL_VERSION_5, /* v5 channel */
67 ReflectClose, /* Close channel, clean instance data */
68 ReflectInput, /* Handle read request */
69 ReflectOutput, /* Handle write request */
70 ReflectSeek, /* Move location of access point. NULL'able */
71 ReflectSetOption, /* Set options. NULL'able */
72 ReflectGetOption, /* Get options. NULL'able */
73 ReflectWatch, /* Initialize notifier */
74 NULL, /* Get OS handle from the channel. NULL'able */
75 ReflectClose2, /* No close2 support. NULL'able */
76 ReflectBlock, /* Set blocking/nonblocking. NULL'able */
77 NULL, /* Flush channel. Not used by core. NULL'able */
78 NULL, /* Handle events. NULL'able */
79 ReflectSeekWide, /* Move access point (64 bit). NULL'able */
80 #ifdef TCL_THREADS
81 ReflectThread, /* thread action, tracking owner */
82 #else
83 NULL, /* thread action */
84 #endif
85 NULL /* truncate */
86 };
87
88 /*
89 * Instance data for a reflected channel. ===========================
90 */
91
92 typedef struct {
93 Tcl_Channel chan; /* Back reference to generic channel
94 * structure. */
95 Tcl_Interp *interp; /* Reference to the interpreter containing the
96 * Tcl level part of the channel. NULL here
97 * signals the channel is dead because the
98 * interpreter/thread containing its Tcl
99 * command is gone.
100 */
101 #ifdef TCL_THREADS
102 Tcl_ThreadId thread; /* Thread the 'interp' belongs to. == Handler thread */
103 Tcl_ThreadId owner; /* Thread owning the structure. == Channel thread */
104 #endif
105 Tcl_Obj *cmd; /* Callback command prefix */
106 Tcl_Obj *methods; /* Methods to append to command prefix */
107 Tcl_Obj *name; /* Name of the channel as created */
108
109 int mode; /* Mask of R/W mode */
110 int interest; /* Mask of events the channel is interested
111 * in. */
112
113 int dead; /* Boolean signal that some operations
114 * should no longer be attempted. */
115
116 /*
117 * Note regarding the usage of timers.
118 *
119 * Most channel implementations need a timer in the C level to ensure that
120 * data in buffers is flushed out through the generation of fake file
121 * events.
122 *
123 * See 'refchan', 'memchan', etc.
124 *
125 * Here this is _not_ required. Interest in events is posted to the Tcl
126 * level via 'watch'. And posting of events is possible from the Tcl level
127 * as well, via 'chan postevent'. This means that the generation of all
128 * events, fake or not, timer based or not, is completely in the hands of
129 * the Tcl level. Therefore no timer here.
130 */
131 } ReflectedChannel;
132
133 /*
134 * Structure of the table mapping from channel handles to reflected
135 * channels. Each interpreter which has the handler command for one or more
136 * reflected channels records them in such a table, so that 'chan postevent'
137 * is able to find them even if the actual channel was moved to a different
138 * interpreter and/or thread.
139 *
140 * The table is reachable via the standard interpreter AssocData, the key is
141 * defined below.
142 */
143
144 typedef struct {
145 Tcl_HashTable map;
146 } ReflectedChannelMap;
147
148 #define RCMKEY "ReflectedChannelMap"
149
150 /*
151 * Event literals. ==================================================
152 */
153
154 static const char *const eventOptions[] = {
155 "read", "write", NULL
156 };
157 typedef enum {
158 EVENT_READ, EVENT_WRITE
159 } EventOption;
160
161 /*
162 * Method literals. ==================================================
163 */
164
165 static const char *const methodNames[] = {
166 "blocking", /* OPT */
167 "cget", /* OPT \/ Together or none */
168 "cgetall", /* OPT /\ of these two */
169 "configure", /* OPT */
170 "finalize", /* */
171 "initialize", /* */
172 "read", /* OPT */
173 "seek", /* OPT */
174 "watch", /* */
175 "write", /* OPT */
176 NULL
177 };
178 typedef enum {
179 METH_BLOCKING,
180 METH_CGET,
181 METH_CGETALL,
182 METH_CONFIGURE,
183 METH_FINAL,
184 METH_INIT,
185 METH_READ,
186 METH_SEEK,
187 METH_WATCH,
188 METH_WRITE
189 } MethodName;
190
191 #define FLAG(m) (1 << (m))
192 #define REQUIRED_METHODS \
193 (FLAG(METH_INIT) | FLAG(METH_FINAL) | FLAG(METH_WATCH))
194 #define NULLABLE_METHODS \
195 (FLAG(METH_BLOCKING) | FLAG(METH_SEEK) | \
196 FLAG(METH_CONFIGURE) | FLAG(METH_CGET) | \
197 FLAG(METH_CGETALL))
198
199 #define RANDW \
200 (TCL_READABLE | TCL_WRITABLE)
201
202 #define IMPLIES(a,b) ((!(a)) || (b))
203 #define NEGIMPL(a,b)
204 #define HAS(x,f) ((x) & FLAG(f))
205
206 #ifdef TCL_THREADS
207 /*
208 * Thread specific types and structures.
209 *
210 * We are here essentially creating a very specific implementation of 'thread
211 * send'.
212 */
213
214 /*
215 * Enumeration of all operations which can be forwarded.
216 */
217
218 typedef enum {
219 ForwardedClose,
220 ForwardedInput,
221 ForwardedOutput,
222 ForwardedSeek,
223 ForwardedWatch,
224 ForwardedBlock,
225 ForwardedSetOpt,
226 ForwardedGetOpt,
227 ForwardedGetOptAll
228 } ForwardedOperation;
229
230 /*
231 * Event used to forward driver invocations to the thread actually managing
232 * the channel. We cannot construct the command to execute and forward that.
233 * Because then it will contain a mixture of Tcl_Obj's belonging to both the
234 * command handler thread (CT), and the thread managing the channel (MT),
235 * executed in CT. Tcl_Obj's are not allowed to cross thread boundaries. So we
236 * forward an operation code, the argument details, and reference to results.
237 * The command is assembled in the CT and belongs fully to that thread. No
238 * sharing problems.
239 */
240
241 typedef struct ForwardParamBase {
242 int code; /* O: Ok/Fail of the cmd handler */
243 char *msgStr; /* O: Error message for handler failure */
244 int mustFree; /* O: True if msgStr is allocated, false if
245 * otherwise (static). */
246 } ForwardParamBase;
247
248 /*
249 * Operation specific parameter/result structures. (These are "subtypes" of
250 * ForwardParamBase. Where an operation does not need any special types, it
251 * has no "subtype" and just uses ForwardParamBase, as listed above.)
252 */
253
254 struct ForwardParamInput {
255 ForwardParamBase base; /* "Supertype". MUST COME FIRST. */
256 char *buf; /* O: Where to store the read bytes */
257 int toRead; /* I: #bytes to read,
258 * O: #bytes actually read */
259 };
260 struct ForwardParamOutput {
261 ForwardParamBase base; /* "Supertype". MUST COME FIRST. */
262 const char *buf; /* I: Where the bytes to write come from */
263 int toWrite; /* I: #bytes to write,
264 * O: #bytes actually written */
265 };
266 struct ForwardParamSeek {
267 ForwardParamBase base; /* "Supertype". MUST COME FIRST. */
268 int seekMode; /* I: How to seek */
269 Tcl_WideInt offset; /* I: Where to seek,
270 * O: New location */
271 };
272 struct ForwardParamWatch {
273 ForwardParamBase base; /* "Supertype". MUST COME FIRST. */
274 int mask; /* I: What events to watch for */
275 };
276 struct ForwardParamBlock {
277 ForwardParamBase base; /* "Supertype". MUST COME FIRST. */
278 int nonblocking; /* I: What mode to activate */
279 };
280 struct ForwardParamSetOpt {
281 ForwardParamBase base; /* "Supertype". MUST COME FIRST. */
282 const char *name; /* Name of option to set */
283 const char *value; /* Value to set */
284 };
285 struct ForwardParamGetOpt {
286 ForwardParamBase base; /* "Supertype". MUST COME FIRST. */
287 const char *name; /* Name of option to get, maybe NULL */
288 Tcl_DString *value; /* Result */
289 };
290
291 /*
292 * Now join all these together in a single union for convenience.
293 */
294
295 typedef union ForwardParam {
296 ForwardParamBase base;
297 struct ForwardParamInput input;
298 struct ForwardParamOutput output;
299 struct ForwardParamSeek seek;
300 struct ForwardParamWatch watch;
301 struct ForwardParamBlock block;
302 struct ForwardParamSetOpt setOpt;
303 struct ForwardParamGetOpt getOpt;
304 } ForwardParam;
305
306 /*
307 * Forward declaration.
308 */
309
310 typedef struct ForwardingResult ForwardingResult;
311
312 /*
313 * General event structure, with reference to operation specific data.
314 */
315
316 typedef struct ForwardingEvent {
317 Tcl_Event event; /* Basic event data, has to be first item */
318 ForwardingResult *resultPtr;
319 ForwardedOperation op; /* Forwarded driver operation */
320 ReflectedChannel *rcPtr; /* Channel instance */
321 ForwardParam *param; /* Packaged arguments and return values, a
322 * ForwardParam pointer. */
323 } ForwardingEvent;
324
325 /*
326 * Structure to manage the result of the forwarding. This is not the result of
327 * the operation itself, but about the success of the forward event itself.
328 * The event can be successful, even if the operation which was forwarded
329 * failed. It is also there to manage the synchronization between the involved
330 * threads.
331 */
332
333 struct ForwardingResult {
334 Tcl_ThreadId src; /* Originating thread. */
335 Tcl_ThreadId dst; /* Thread the op was forwarded to. */
336 Tcl_Interp *dsti; /* Interpreter in the thread the op was
337 * forwarded to. */
338 /*
339 * Note regarding 'dsti' above: Its information is also available via the
340 * chain evPtr->rcPtr->interp, however, as can be seen, two more
341 * indirections are needed to retrieve it. And the evPtr may be gone,
342 * breaking the chain.
343 */
344 Tcl_Condition done; /* Condition variable the forwarder blocks
345 * on. */
346 int result; /* TCL_OK or TCL_ERROR */
347 ForwardingEvent *evPtr; /* Event the result belongs to. */
348 ForwardingResult *prevPtr, *nextPtr;
349 /* Links into the list of pending forwarded
350 * results. */
351 };
352
353 typedef struct ThreadSpecificData {
354 /*
355 * Table of all reflected channels owned by this thread. This is the
356 * per-thread version of the per-interpreter map.
357 */
358
359 ReflectedChannelMap *rcmPtr;
360 } ThreadSpecificData;
361
362 static Tcl_ThreadDataKey dataKey;
363
364 /*
365 * List of forwarded operations which have not completed yet, plus the mutex
366 * to protect the access to this process global list.
367 */
368
369 static ForwardingResult *forwardList = NULL;
370 TCL_DECLARE_MUTEX(rcForwardMutex)
371
372 /*
373 * Function containing the generic code executing a forward, and wrapper
374 * macros for the actual operations we wish to forward. Uses ForwardProc as
375 * the event function executed by the thread receiving a forwarding event
376 * (which executes the appropriate function and collects the result, if any).
377 *
378 * The ExitProc ensures that things do not deadlock when the sending thread
379 * involved in the forwarding exits. It also clean things up so that we don't
380 * leak resources when threads go away.
381 */
382
383 static void ForwardOpToHandlerThread(ReflectedChannel *rcPtr,
384 ForwardedOperation op, void *param);
385 static int ForwardProc(Tcl_Event *evPtr, int mask);
386 static void SrcExitProc(void *clientData);
387
388 #define FreeReceivedError(p) \
389 if ((p)->base.mustFree) { \
390 ckfree((p)->base.msgStr); \
391 }
392 #define PassReceivedErrorInterp(i,p) \
393 if ((i) != NULL) { \
394 Tcl_SetChannelErrorInterp((i), \
395 Tcl_NewStringObj((p)->base.msgStr, -1)); \
396 } \
397 FreeReceivedError(p)
398 #define PassReceivedError(c,p) \
399 Tcl_SetChannelError((c), Tcl_NewStringObj((p)->base.msgStr, -1)); \
400 FreeReceivedError(p)
401 #define ForwardSetStaticError(p,emsg) \
402 (p)->base.code = TCL_ERROR; \
403 (p)->base.mustFree = 0; \
404 (p)->base.msgStr = (char *) (emsg)
405 #define ForwardSetDynamicError(p,emsg) \
406 (p)->base.code = TCL_ERROR; \
407 (p)->base.mustFree = 1; \
408 (p)->base.msgStr = (char *) (emsg)
409
410 static void ForwardSetObjError(ForwardParam *p, Tcl_Obj *objPtr);
411
412 static ReflectedChannelMap * GetThreadReflectedChannelMap(void);
413 static Tcl_ExitProc DeleteThreadReflectedChannelMap;
414
415 #endif /* TCL_THREADS */
416
417 #define SetChannelErrorStr(c,msgStr) \
418 Tcl_SetChannelError((c), Tcl_NewStringObj((msgStr), -1))
419
420 static Tcl_Obj * MarshallError(Tcl_Interp *interp);
421 static void UnmarshallErrorResult(Tcl_Interp *interp,
422 Tcl_Obj *msgObj);
423
424 /*
425 * Static functions for this file:
426 */
427
428 static int EncodeEventMask(Tcl_Interp *interp,
429 const char *objName, Tcl_Obj *obj, int *mask);
430 static Tcl_Obj * DecodeEventMask(int mask);
431 static ReflectedChannel * NewReflectedChannel(Tcl_Interp *interp,
432 Tcl_Obj *cmdpfxObj, int mode, Tcl_Obj *handleObj);
433 static Tcl_Obj * NextHandle(void);
434 static Tcl_FreeProc FreeReflectedChannel;
435 static int InvokeTclMethod(ReflectedChannel *rcPtr,
436 MethodName method, Tcl_Obj *argOneObj,
437 Tcl_Obj *argTwoObj, Tcl_Obj **resultObjPtr);
438
439 static ReflectedChannelMap * GetReflectedChannelMap(Tcl_Interp *interp);
440 static Tcl_InterpDeleteProc DeleteReflectedChannelMap;
441 static int ErrnoReturn(ReflectedChannel *rcPtr, Tcl_Obj *resObj);
442 static void MarkDead(ReflectedChannel *rcPtr);
443
444 /*
445 * Global constant strings (messages). ==================
446 * These string are used directly as bypass errors, thus they have to be valid
447 * Tcl lists where the last element is the message itself. Hence the
448 * list-quoting to keep the words of the message together. See also [x].
449 */
450
451 static const char *msg_read_toomuch = "{read delivered more than requested}";
452 static const char *msg_write_toomuch = "{write wrote more than requested}";
453 static const char *msg_write_nothing = "{write wrote nothing}";
454 static const char *msg_seek_beforestart = "{Tried to seek before origin}";
455 #ifdef TCL_THREADS
456 static const char *msg_send_originlost = "{Channel thread lost}";
457 #endif /* TCL_THREADS */
458 static const char *msg_send_dstlost = "{Owner lost}";
459 static const char *msg_dstlost = "-code 1 -level 0 -errorcode NONE -errorinfo {} -errorline 1 {Owner lost}";
460
461 /*
462 * Main methods to plug into the 'chan' ensemble'. ==================
463 */
464
465 /*
466 *----------------------------------------------------------------------
467 *
468 * TclChanCreateObjCmd --
469 *
470 * This function is invoked to process the "chan create" Tcl command.
471 * See the user documentation for details on what it does.
472 *
473 * Results:
474 * A standard Tcl result. The handle of the new channel is placed in the
475 * interp result.
476 *
477 * Side effects:
478 * Creates a new channel.
479 *
480 *----------------------------------------------------------------------
481 */
482
483 int
484 TclChanCreateObjCmd(
485 void *dummy,
486 Tcl_Interp *interp,
487 int objc,
488 Tcl_Obj *const *objv)
489 {
490 ReflectedChannel *rcPtr; /* Instance data of the new channel */
491 Tcl_Obj *rcId; /* Handle of the new channel */
492 int mode; /* R/W mode of new channel. Has to match
493 * abilities of handler commands */
494 Tcl_Obj *cmdObj; /* Command prefix, list of words */
495 Tcl_Obj *cmdNameObj; /* Command name */
496 Tcl_Channel chan; /* Token for the new channel */
497 Tcl_Obj *modeObj; /* mode in obj form for method call */
498 int listc; /* Result of 'initialize', and of */
499 Tcl_Obj **listv; /* its sublist in the 2nd element */
500 int methIndex; /* Encoded method name */
501 int result; /* Result code for 'initialize' */
502 Tcl_Obj *resObj; /* Result data for 'initialize' */
503 int methods; /* Bitmask for supported methods. */
504 Channel *chanPtr; /* 'chan' resolved to internal struct. */
505 Tcl_Obj *err; /* Error message */
506 ReflectedChannelMap *rcmPtr;
507 /* Map of reflected channels with handlers in
508 * this interp. */
509 Tcl_HashEntry *hPtr; /* Entry in the above map */
510 int isNew; /* Placeholder. */
511 (void)dummy;
512
513 /*
514 * Syntax: chan create MODE CMDPREFIX
515 * [0] [1] [2] [3]
516 *
517 * Actually: rCreate MODE CMDPREFIX
518 * [0] [1] [2]
519 */
520
521 #define MODE (1)
522 #define CMD (2)
523
524 /*
525 * Number of arguments...
526 */
527
528 if (objc != 3) {
529 Tcl_WrongNumArgs(interp, 1, objv, "mode cmdprefix");
530 return TCL_ERROR;
531 }
532
533 /*
534 * First argument is a list of modes. Allowed entries are "read", "write".
535 * Empty list is uncommon, but allowed. Abbreviations are ok.
536 */
537
538 modeObj = objv[MODE];
539 if (EncodeEventMask(interp, "mode", objv[MODE], &mode) != TCL_OK) {
540 return TCL_ERROR;
541 }
542
543 /*
544 * Second argument is command prefix, i.e. list of words, first word is
545 * name of handler command, other words are fixed arguments. Run the
546 * 'initialize' method to get the list of supported methods. Validate
547 * this.
548 */
549
550 cmdObj = objv[CMD];
551
552 /*
553 * Basic check that the command prefix truly is a list.
554 */
555
556 if (Tcl_ListObjIndex(interp, cmdObj, 0, &cmdNameObj) != TCL_OK) {
557 return TCL_ERROR;
558 }
559
560 /*
561 * Now create the channel.
562 */
563
564 rcId = NextHandle();
565 rcPtr = NewReflectedChannel(interp, cmdObj, mode, rcId);
566 if (!rcPtr) {
567 return TCL_ERROR;
568 }
569
570 /*
571 * Invoke 'initialize' and validate that the handler is present and ok.
572 * Squash the channel if not.
573 *
574 * Note: The conversion of 'mode' back into a Tcl_Obj ensures that
575 * 'initialize' is invoked with canonical mode names, and no
576 * abbreviations. Using modeObj directly could feed abbreviations into the
577 * handler, and the handler is not specified to handle such.
578 */
579
580 modeObj = DecodeEventMask(mode);
581 /* assert modeObj.refCount == 1 */
582 result = InvokeTclMethod(rcPtr, METH_INIT, modeObj, NULL, &resObj);
583 Tcl_DecrRefCount(modeObj);
584
585 if (result != TCL_OK) {
586 UnmarshallErrorResult(interp, resObj);
587 Tcl_DecrRefCount(resObj); /* Remove reference held from invoke */
588 goto error;
589 }
590
591 /*
592 * Verify the result.
593 * - List, of method names. Convert to mask.
594 * Check for non-optionals through the mask.
595 * Compare open mode against optional r/w.
596 */
597
598 if (TclListObjGetElements(NULL, resObj, &listc, &listv) != TCL_OK) {
599 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
600 "chan handler \"%s initialize\" returned non-list: %s",
601 TclGetString(cmdObj), TclGetString(resObj)));
602 Tcl_DecrRefCount(resObj);
603 goto error;
604 }
605
606 methods = 0;
607 while (listc > 0) {
608 if (Tcl_GetIndexFromObj(interp, listv[listc-1], methodNames,
609 "method", TCL_EXACT, &methIndex) != TCL_OK) {
610 TclNewLiteralStringObj(err, "chan handler \"");
611 Tcl_AppendObjToObj(err, cmdObj);
612 Tcl_AppendToObj(err, " initialize\" returned ", -1);
613 Tcl_AppendObjToObj(err, Tcl_GetObjResult(interp));
614 Tcl_SetObjResult(interp, err);
615 Tcl_DecrRefCount(resObj);
616 goto error;
617 }
618
619 methods |= FLAG(methIndex);
620 listc--;
621 }
622 Tcl_DecrRefCount(resObj);
623
624 if ((REQUIRED_METHODS & methods) != REQUIRED_METHODS) {
625 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
626 "chan handler \"%s\" does not support all required methods",
627 TclGetString(cmdObj)));
628 goto error;
629 }
630
631 if ((mode & TCL_READABLE) && !HAS(methods, METH_READ)) {
632 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
633 "chan handler \"%s\" lacks a \"read\" method",
634 TclGetString(cmdObj)));
635 goto error;
636 }
637
638 if ((mode & TCL_WRITABLE) && !HAS(methods, METH_WRITE)) {
639 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
640 "chan handler \"%s\" lacks a \"write\" method",
641 TclGetString(cmdObj)));
642 goto error;
643 }
644
645 if (!IMPLIES(HAS(methods, METH_CGET), HAS(methods, METH_CGETALL))) {
646 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
647 "chan handler \"%s\" supports \"cget\" but not \"cgetall\"",
648 TclGetString(cmdObj)));
649 goto error;
650 }
651
652 if (!IMPLIES(HAS(methods, METH_CGETALL), HAS(methods, METH_CGET))) {
653 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
654 "chan handler \"%s\" supports \"cgetall\" but not \"cget\"",
655 TclGetString(cmdObj)));
656 goto error;
657 }
658
659 Tcl_ResetResult(interp);
660
661 /*
662 * Everything is fine now.
663 */
664
665 chan = Tcl_CreateChannel(&tclRChannelType, TclGetString(rcId), rcPtr,
666 mode);
667 rcPtr->chan = chan;
668 TclChannelPreserve(chan);
669 chanPtr = (Channel *) chan;
670
671 if ((methods & NULLABLE_METHODS) != NULLABLE_METHODS) {
672 /*
673 * Some of the nullable methods are not supported. We clone the
674 * channel type, null the associated C functions, and use the result
675 * as the actual channel type.
676 */
677
678 Tcl_ChannelType *clonePtr = (Tcl_ChannelType *)ckalloc(sizeof(Tcl_ChannelType));
679
680 memcpy(clonePtr, &tclRChannelType, sizeof(Tcl_ChannelType));
681
682 if (!(methods & FLAG(METH_CONFIGURE))) {
683 clonePtr->setOptionProc = NULL;
684 }
685
686 if (!(methods & FLAG(METH_CGET)) && !(methods & FLAG(METH_CGETALL))) {
687 clonePtr->getOptionProc = NULL;
688 }
689 if (!(methods & FLAG(METH_BLOCKING))) {
690 clonePtr->blockModeProc = NULL;
691 }
692 if (!(methods & FLAG(METH_SEEK))) {
693 clonePtr->seekProc = NULL;
694 clonePtr->wideSeekProc = NULL;
695 }
696
697 chanPtr->typePtr = clonePtr;
698 }
699
700 /*
701 * Register the channel in the I/O system, and in our our map for 'chan
702 * postevent'.
703 */
704
705 Tcl_RegisterChannel(interp, chan);
706
707 rcmPtr = GetReflectedChannelMap(interp);
708 hPtr = Tcl_CreateHashEntry(&rcmPtr->map, chanPtr->state->channelName,
709 &isNew);
710 if (!isNew && chanPtr != Tcl_GetHashValue(hPtr)) {
711 Tcl_Panic("TclChanCreateObjCmd: duplicate channel names");
712 }
713 Tcl_SetHashValue(hPtr, chan);
714 #ifdef TCL_THREADS
715 rcmPtr = GetThreadReflectedChannelMap();
716 hPtr = Tcl_CreateHashEntry(&rcmPtr->map, chanPtr->state->channelName,
717 &isNew);
718 Tcl_SetHashValue(hPtr, chan);
719 #endif
720
721 /*
722 * Return handle as result of command.
723 */
724
725 Tcl_SetObjResult(interp,
726 Tcl_NewStringObj(chanPtr->state->channelName, -1));
727 return TCL_OK;
728
729 error:
730 Tcl_DecrRefCount(rcPtr->name);
731 Tcl_DecrRefCount(rcPtr->methods);
732 Tcl_DecrRefCount(rcPtr->cmd);
733 ckfree((char*) rcPtr);
734 return TCL_ERROR;
735
736 #undef MODE
737 #undef CMD
738 }
739
740 /*
741 *----------------------------------------------------------------------
742 *
743 * TclChanPostEventObjCmd --
744 *
745 * This function is invoked to process the "chan postevent" Tcl command.
746 * See the user documentation for details on what it does.
747 *
748 * Results:
749 * A standard Tcl result.
750 *
751 * Side effects:
752 * Posts events to a reflected channel, invokes event handlers. The
753 * latter implies that arbitrary side effects are possible.
754 *
755 *----------------------------------------------------------------------
756 */
757
758 #ifdef TCL_THREADS
759 typedef struct ReflectEvent {
760 Tcl_Event header;
761 ReflectedChannel *rcPtr;
762 int events;
763 } ReflectEvent;
764
765 static int
766 ReflectEventRun(
767 Tcl_Event *ev,
768 int flags)
769 {
770 /* OWNER thread
771 *
772 * Note: When the channel is closed any pending events of this type are
773 * deleted. See ReflectClose() for the Tcl_DeleteEvents() calls
774 * accomplishing that.
775 */
776
777 ReflectEvent *e = (ReflectEvent *) ev;
778 (void)flags;
779
780 Tcl_NotifyChannel(e->rcPtr->chan, e->events);
781 return 1;
782 }
783
784 static int
785 ReflectEventDelete(
786 Tcl_Event *ev,
787 void *cd)
788 {
789 /* OWNER thread
790 *
791 * Invoked by DeleteThreadReflectedChannelMap() and ReflectClose(). The
792 * latter ensures that no pending events of this type are run on an
793 * invalid channel.
794 */
795
796 ReflectEvent *e = (ReflectEvent *) ev;
797
798 if ((ev->proc != ReflectEventRun) || ((cd != NULL) && (cd != e->rcPtr))) {
799 return 0;
800 }
801 return 1;
802 }
803 #endif
804
805 int
806 TclChanPostEventObjCmd(
807 void *dummy,
808 Tcl_Interp *interp,
809 int objc,
810 Tcl_Obj *const *objv)
811 {
812 /*
813 * Ensure -> HANDLER thread
814 *
815 * Syntax: chan postevent CHANNEL EVENTSPEC
816 * [0] [1] [2] [3]
817 *
818 * Actually: rPostevent CHANNEL EVENTSPEC
819 * [0] [1] [2]
820 *
821 * where EVENTSPEC = {read write ...} (Abbreviations allowed as well).
822 */
823
824 #define CHAN (1)
825 #define EVENT (2)
826
827 const char *chanId; /* Tcl level channel handle */
828 Tcl_Channel chan; /* Channel associated to the handle */
829 const Tcl_ChannelType *chanTypePtr;
830 /* Its associated driver structure */
831 ReflectedChannel *rcPtr; /* Associated instance data */
832 int events; /* Mask of events to post */
833 ReflectedChannelMap *rcmPtr;/* Map of reflected channels with handlers in
834 * this interp. */
835 Tcl_HashEntry *hPtr; /* Entry in the above map */
836 (void)dummy;
837
838 /*
839 * Number of arguments...
840 */
841
842 if (objc != 3) {
843 Tcl_WrongNumArgs(interp, 1, objv, "channel eventspec");
844 return TCL_ERROR;
845 }
846
847 /*
848 * First argument is a channel, a reflected channel, and the call of this
849 * command is done from the interp defining the channel handler cmd.
850 */
851
852 chanId = TclGetString(objv[CHAN]);
853
854 rcmPtr = GetReflectedChannelMap(interp);
855 hPtr = Tcl_FindHashEntry(&rcmPtr->map, chanId);
856
857 if (hPtr == NULL) {
858 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
859 "can not find reflected channel named \"%s\"", chanId));
860 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "CHANNEL", chanId, (char *)NULL);
861 return TCL_ERROR;
862 }
863
864 /*
865 * Note that the search above subsumes several of the older checks,
866 * namely:
867 *
868 * (1) Does the channel handle refer to a reflected channel?
869 * (2) Is the post event issued from the interpreter holding the handler
870 * of the reflected channel?
871 *
872 * A successful search answers yes to both. Because the map holds only
873 * handles of reflected channels, and only of such whose handler is
874 * defined in this interpreter.
875 *
876 * We keep the old checks for both, for paranoia, but abort now instead of
877 * throwing errors, as failure now means that our internal data structures
878 * have gone seriously haywire.
879 */
880
881 chan = (Tcl_Channel)Tcl_GetHashValue(hPtr);
882 chanTypePtr = Tcl_GetChannelType(chan);
883
884 /*
885 * We use a function referenced by the channel type as our cookie to
886 * detect calls to non-reflecting channels. The channel type itself is not
887 * suitable, as it might not be the static definition in this file, but a
888 * clone thereof. And while we have reserved the name of the type nothing
889 * in the core checks against violation, so someone else might have
890 * created a channel type using our name, clashing with ourselves.
891 */
892
893 if (chanTypePtr->watchProc != &ReflectWatch) {
894 Tcl_Panic("TclChanPostEventObjCmd: channel is not a reflected channel");
895 }
896
897 rcPtr = (ReflectedChannel *)Tcl_GetChannelInstanceData(chan);
898
899 if (rcPtr->interp != interp) {
900 Tcl_Panic("TclChanPostEventObjCmd: postevent accepted for call from outside interpreter");
901 }
902
903 /*
904 * Second argument is a list of events. Allowed entries are "read",
905 * "write". Expect at least one list element. Abbreviations are ok.
906 */
907
908 if (EncodeEventMask(interp, "event", objv[EVENT], &events) != TCL_OK) {
909 return TCL_ERROR;
910 }
911 if (events == 0) {
912 Tcl_SetObjResult(interp,
913 Tcl_NewStringObj("bad event list: is empty", -1));
914 return TCL_ERROR;
915 }
916
917 /*
918 * Check that the channel is actually interested in the provided events.
919 */
920
921 if (events & ~rcPtr->interest) {
922 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
923 "tried to post events channel \"%s\" is not interested in",
924 chanId));
925 return TCL_ERROR;
926 }
927
928 /*
929 * We have the channel and the events to post.
930 */
931
932 #ifdef TCL_THREADS
933 if (rcPtr->owner == rcPtr->thread) {
934 #endif
935 Tcl_NotifyChannel(chan, events);
936 #ifdef TCL_THREADS
937 } else {
938 ReflectEvent *ev = (ReflectEvent *)ckalloc(sizeof(ReflectEvent));
939
940 ev->header.proc = ReflectEventRun;
941 ev->events = events;
942 ev->rcPtr = rcPtr;
943
944 /*
945 * We are not preserving the structure here. When the channel is
946 * closed any pending events are deleted, see ReflectClose(), and
947 * ReflectEventDelete(). Trying to preserve and later release when the
948 * event is run may generate a situation where the channel structure
949 * is deleted but not our structure, crashing in
950 * FreeReflectedChannel().
951 *
952 * Force creation of the RCM, for proper cleanup on thread teardown.
953 * The teardown of unprocessed events is currently coupled to the
954 * thread reflected channel map
955 */
956
957 (void) GetThreadReflectedChannelMap();
958
959 /*
960 * XXX Race condition !!
961 * XXX The destination thread may not exist anymore already.
962 * XXX (Delayed postevent executed after channel got removed).
963 * XXX Can we detect this ? (check the validity of the owner threadid ?)
964 * XXX Actually, in that case the channel should be dead also !
965 */
966
967 Tcl_ThreadQueueEvent(rcPtr->owner, (Tcl_Event *) ev, TCL_QUEUE_TAIL);
968 Tcl_ThreadAlert(rcPtr->owner);
969 }
970 #endif
971
972 /*
973 * Squash interp results left by the event script.
974 */
975
976 Tcl_ResetResult(interp);
977 return TCL_OK;
978
979 #undef CHAN
980 #undef EVENT
981 }
982
983 /*
984 * Channel error message marshalling utilities.
985 */
986
987 static Tcl_Obj *
988 MarshallError(
989 Tcl_Interp *interp)
990 {
991 /*
992 * Capture the result status of the interpreter into a string. => List of
993 * options and values, followed by the error message. The result has
994 * refCount 0.
995 */
996
997 Tcl_Obj *returnOpt = Tcl_GetReturnOptions(interp, TCL_ERROR);
998
999 /*
1000 * => returnOpt.refCount == 0. We can append directly.
1001 */
1002
1003 Tcl_ListObjAppendElement(NULL, returnOpt, Tcl_GetObjResult(interp));
1004 return returnOpt;
1005 }
1006
1007 static void
1008 UnmarshallErrorResult(
1009 Tcl_Interp *interp,
1010 Tcl_Obj *msgObj)
1011 {
1012 int lc;
1013 Tcl_Obj **lv;
1014 int explicitResult;
1015 int numOptions;
1016
1017 /*
1018 * Process the caught message.
1019 *
1020 * Syntax = (option value)... ?message?
1021 *
1022 * Bad syntax causes a panic. This is OK because the other side uses
1023 * Tcl_GetReturnOptions and list construction functions to marshal the
1024 * information; if we panic here, something has gone badly wrong already.
1025 */
1026
1027 if (TclListObjGetElements(interp, msgObj, &lc, &lv) != TCL_OK) {
1028 Tcl_Panic("TclChanCaughtErrorBypass: Bad syntax of caught result");
1029 }
1030 if (interp == NULL) {
1031 return;
1032 }
1033
1034 explicitResult = lc & 1; /* Odd number of values? */
1035 numOptions = lc - explicitResult;
1036
1037 if (explicitResult) {
1038 Tcl_SetObjResult(interp, lv[lc-1]);
1039 }
1040
1041 (void) Tcl_SetReturnOptions(interp, Tcl_NewListObj(numOptions, lv));
1042 ((Interp *) interp)->flags &= ~ERR_ALREADY_LOGGED;
1043 }
1044
1045 int
1046 TclChanCaughtErrorBypass(
1047 Tcl_Interp *interp,
1048 Tcl_Channel chan)
1049 {
1050 Tcl_Obj *chanMsgObj = NULL;
1051 Tcl_Obj *interpMsgObj = NULL;
1052 Tcl_Obj *msgObj = NULL;
1053
1054 /*
1055 * Get a bypassed error message from channel and/or interpreter, save the
1056 * reference, then kill the returned objects, if there were any. If there
1057 * are messages in both the channel has preference.
1058 */
1059
1060 if ((chan == NULL) && (interp == NULL)) {
1061 return 0;
1062 }
1063
1064 if (chan != NULL) {
1065 Tcl_GetChannelError(chan, &chanMsgObj);
1066 }
1067 if (interp != NULL) {
1068 Tcl_GetChannelErrorInterp(interp, &interpMsgObj);
1069 }
1070
1071 if (chanMsgObj != NULL) {
1072 msgObj = chanMsgObj;
1073 } else if (interpMsgObj != NULL) {
1074 msgObj = interpMsgObj;
1075 }
1076 if (msgObj != NULL) {
1077 Tcl_IncrRefCount(msgObj);
1078 }
1079
1080 if (chanMsgObj != NULL) {
1081 Tcl_DecrRefCount(chanMsgObj);
1082 }
1083 if (interpMsgObj != NULL) {
1084 Tcl_DecrRefCount(interpMsgObj);
1085 }
1086
1087 /*
1088 * No message returned, nothing caught.
1089 */
1090
1091 if (msgObj == NULL) {
1092 return 0;
1093 }
1094
1095 UnmarshallErrorResult(interp, msgObj);
1096
1097 Tcl_DecrRefCount(msgObj);
1098 return 1;
1099 }
1100
1101 /*
1102 * Driver functions. ================================================
1103 */
1104
1105 /*
1106 *----------------------------------------------------------------------
1107 *
1108 * ReflectClose/ReflectClose2 --
1109 *
1110 * This function is invoked when the channel is closed, to delete the
1111 * driver-specific instance data.
1112 *
1113 * Results:
1114 * A Posix error.
1115 *
1116 * Side effects:
1117 * Releases memory. Arbitrary, as it calls upon a script.
1118 *
1119 *----------------------------------------------------------------------
1120 */
1121
1122 static int
1123 ReflectClose(
1124 void *clientData,
1125 Tcl_Interp *interp)
1126 {
1127 ReflectedChannel *rcPtr = (ReflectedChannel *)clientData;
1128 int result; /* Result code for 'close' */
1129 Tcl_Obj *resObj; /* Result data for 'close' */
1130 ReflectedChannelMap *rcmPtr;/* Map of reflected channels with handlers in
1131 * this interp */
1132 Tcl_HashEntry *hPtr; /* Entry in the above map */
1133 const Tcl_ChannelType *tctPtr;
1134
1135 if (TclInThreadExit()) {
1136 /*
1137 * This call comes from TclFinalizeIOSystem. There are no
1138 * interpreters, and therefore we cannot call upon the handler command
1139 * anymore. Threading is irrelevant as well. Simply clean up all
1140 * the C level data structures and leave the Tcl level to the other
1141 * finalization functions.
1142 */
1143
1144 /*
1145 * THREADED => Forward this to the origin thread
1146 *
1147 * Note: DeleteThreadReflectedChannelMap() is the thread exit handler
1148 * for the origin thread. Use this to clean up the structure? Except
1149 * if lost?
1150 */
1151
1152 #ifdef TCL_THREADS
1153 if (rcPtr->thread != Tcl_GetCurrentThread()) {
1154 ForwardParam p;
1155
1156 ForwardOpToHandlerThread(rcPtr, ForwardedClose, &p);
1157 result = p.base.code;
1158
1159 /*
1160 * Now squash the pending reflection events for this channel.
1161 */
1162
1163 Tcl_DeleteEvents(ReflectEventDelete, rcPtr);
1164
1165 if (result != TCL_OK) {
1166 FreeReceivedError(&p);
1167 }
1168 }
1169 #endif
1170
1171 tctPtr = ((Channel *)rcPtr->chan)->typePtr;
1172 if (tctPtr && tctPtr != &tclRChannelType) {
1173 ckfree((char *)tctPtr);
1174 ((Channel *)rcPtr->chan)->typePtr = NULL;
1175 }
1176 Tcl_EventuallyFree(rcPtr, FreeReflectedChannel);
1177 return EOK;
1178 }
1179
1180 /*
1181 * Are we in the correct thread?
1182 */
1183
1184 #ifdef TCL_THREADS
1185 if (rcPtr->thread != Tcl_GetCurrentThread()) {
1186 ForwardParam p;
1187
1188 ForwardOpToHandlerThread(rcPtr, ForwardedClose, &p);
1189 result = p.base.code;
1190
1191 /*
1192 * Now squash the pending reflection events for this channel.
1193 */
1194
1195 Tcl_DeleteEvents(ReflectEventDelete, rcPtr);
1196
1197 if (result != TCL_OK) {
1198 PassReceivedErrorInterp(interp, &p);
1199 }
1200 } else {
1201 #endif
1202 result = InvokeTclMethod(rcPtr, METH_FINAL, NULL, NULL, &resObj);
1203 if ((result != TCL_OK) && (interp != NULL)) {
1204 Tcl_SetChannelErrorInterp(interp, resObj);
1205 }
1206
1207 Tcl_DecrRefCount(resObj); /* Remove reference we held from the
1208 * invoke */
1209
1210 /*
1211 * Remove the channel from the map before releasing the memory, to
1212 * prevent future accesses (like by 'postevent') from finding and
1213 * dereferencing a dangling pointer.
1214 *
1215 * NOTE: The channel may not be in the map. This is ok, that happens
1216 * when the channel was created in a different interpreter and/or
1217 * thread and then was moved here.
1218 *
1219 * NOTE: The channel may have been removed from the map already via
1220 * the per-interp DeleteReflectedChannelMap exit-handler.
1221 */
1222
1223 if (!rcPtr->dead) {
1224 rcmPtr = GetReflectedChannelMap(rcPtr->interp);
1225 hPtr = Tcl_FindHashEntry(&rcmPtr->map,
1226 Tcl_GetChannelName(rcPtr->chan));
1227 if (hPtr) {
1228 Tcl_DeleteHashEntry(hPtr);
1229 }
1230 }
1231 #ifdef TCL_THREADS
1232 rcmPtr = GetThreadReflectedChannelMap();
1233 hPtr = Tcl_FindHashEntry(&rcmPtr->map,
1234 Tcl_GetChannelName(rcPtr->chan));
1235 if (hPtr) {
1236 Tcl_DeleteHashEntry(hPtr);
1237 }
1238 }
1239 #endif
1240 tctPtr = ((Channel *)rcPtr->chan)->typePtr;
1241 if (tctPtr && tctPtr != &tclRChannelType) {
1242 ckfree((char *)tctPtr);
1243 ((Channel *)rcPtr->chan)->typePtr = NULL;
1244 }
1245 Tcl_EventuallyFree(rcPtr, FreeReflectedChannel);
1246 return (result == TCL_OK) ? EOK : EINVAL;
1247 }
1248
1249 static int
1250 ReflectClose2(
1251 void *clientData,
1252 Tcl_Interp *interp,
1253 int flags)
1254 {
1255 if ((flags & (TCL_CLOSE_READ | TCL_CLOSE_WRITE)) == 0) {
1256 return ReflectClose(clientData, interp);
1257 }
1258 return EINVAL;
1259 }
1260
1261 /*
1262 *----------------------------------------------------------------------
1263 *
1264 * ReflectInput --
1265 *
1266 * This function is invoked when more data is requested from the channel.
1267 *
1268 * Results:
1269 * The number of bytes read.
1270 *
1271 * Side effects:
1272 * Allocates memory. Arbitrary, as it calls upon a script.
1273 *
1274 *----------------------------------------------------------------------
1275 */
1276
1277 static int
1278 ReflectInput(
1279 void *clientData,
1280 char *buf,
1281 int toRead,
1282 int *errorCodePtr)
1283 {
1284 ReflectedChannel *rcPtr = (ReflectedChannel *)clientData;
1285 Tcl_Obj *toReadObj;
1286 int bytec; /* Number of returned bytes */
1287 unsigned char *bytev; /* Array of returned bytes */
1288 Tcl_Obj *resObj; /* Result data for 'read' */
1289
1290 /*
1291 * Are we in the correct thread?
1292 */
1293
1294 #ifdef TCL_THREADS
1295 if (rcPtr->thread != Tcl_GetCurrentThread()) {
1296 ForwardParam p;
1297
1298 p.input.buf = buf;
1299 p.input.toRead = toRead;
1300
1301 ForwardOpToHandlerThread(rcPtr, ForwardedInput, &p);
1302
1303 if (p.base.code != TCL_OK) {
1304 if (p.base.code < 0) {
1305 /*
1306 * No error message, this is an errno signal.
1307 */
1308
1309 *errorCodePtr = -p.base.code;
1310 } else {
1311 PassReceivedError(rcPtr->chan, &p);
1312 *errorCodePtr = EINVAL;
1313 }
1314 p.input.toRead = -1;
1315 } else {
1316 *errorCodePtr = EOK;
1317 }
1318
1319 return p.input.toRead;
1320 }
1321 #endif
1322
1323 /* ASSERT: rcPtr->method & FLAG(METH_READ) */
1324 /* ASSERT: rcPtr->mode & TCL_READABLE */
1325
1326 Tcl_Preserve(rcPtr);
1327
1328 TclNewIntObj(toReadObj, toRead);
1329 Tcl_IncrRefCount(toReadObj);
1330
1331 if (InvokeTclMethod(rcPtr, METH_READ, toReadObj, NULL, &resObj)!=TCL_OK) {
1332 int code = ErrnoReturn(rcPtr, resObj);
1333
1334 if (code < 0) {
1335 *errorCodePtr = -code;
1336 goto error;
1337 }
1338
1339 Tcl_SetChannelError(rcPtr->chan, resObj);
1340 goto invalid;
1341 }
1342
1343 bytev = Tcl_GetByteArrayFromObj(resObj, &bytec);
1344
1345 if (toRead < bytec) {
1346 SetChannelErrorStr(rcPtr->chan, msg_read_toomuch);
1347 goto invalid;
1348 }
1349
1350 *errorCodePtr = EOK;
1351
1352 if (bytec > 0) {
1353 memcpy(buf, bytev, bytec);
1354 }
1355
1356 stop:
1357 Tcl_DecrRefCount(toReadObj);
1358 Tcl_DecrRefCount(resObj); /* Remove reference held from invoke */
1359 Tcl_Release(rcPtr);
1360 return bytec;
1361 invalid:
1362 *errorCodePtr = EINVAL;
1363 error:
1364 bytec = -1;
1365 goto stop;
1366 }
1367
1368 /*
1369 *----------------------------------------------------------------------
1370 *
1371 * ReflectOutput --
1372 *
1373 * This function is invoked when data is writen to the channel.
1374 *
1375 * Results:
1376 * The number of bytes actually written.
1377 *
1378 * Side effects:
1379 * Allocates memory. Arbitrary, as it calls upon a script.
1380 *
1381 *----------------------------------------------------------------------
1382 */
1383
1384 static int
1385 ReflectOutput(
1386 void *clientData,
1387 const char *buf,
1388 int toWrite,
1389 int *errorCodePtr)
1390 {
1391 ReflectedChannel *rcPtr = (ReflectedChannel *)clientData;
1392 Tcl_Obj *bufObj;
1393 Tcl_Obj *resObj; /* Result data for 'write' */
1394 int written;
1395
1396 /*
1397 * Are we in the correct thread?
1398 */
1399
1400 #ifdef TCL_THREADS
1401 if (rcPtr->thread != Tcl_GetCurrentThread()) {
1402 ForwardParam p;
1403
1404 p.output.buf = buf;
1405 p.output.toWrite = toWrite;
1406
1407 ForwardOpToHandlerThread(rcPtr, ForwardedOutput, &p);
1408
1409 if (p.base.code != TCL_OK) {
1410 if (p.base.code < 0) {
1411 /*
1412 * No error message, this is an errno signal.
1413 */
1414
1415 *errorCodePtr = -p.base.code;
1416 } else {
1417 PassReceivedError(rcPtr->chan, &p);
1418 *errorCodePtr = EINVAL;
1419 }
1420 p.output.toWrite = -1;
1421 } else {
1422 *errorCodePtr = EOK;
1423 }
1424
1425 return p.output.toWrite;
1426 }
1427 #endif
1428
1429 /* ASSERT: rcPtr->method & FLAG(METH_WRITE) */
1430 /* ASSERT: rcPtr->mode & TCL_WRITABLE */
1431
1432 Tcl_Preserve(rcPtr);
1433 Tcl_Preserve(rcPtr->interp);
1434
1435 bufObj = Tcl_NewByteArrayObj((unsigned char *) buf, toWrite);
1436 Tcl_IncrRefCount(bufObj);
1437
1438 if (InvokeTclMethod(rcPtr, METH_WRITE, bufObj, NULL, &resObj) != TCL_OK) {
1439 int code = ErrnoReturn(rcPtr, resObj);
1440
1441 if (code < 0) {
1442 *errorCodePtr = -code;
1443 goto error;
1444 }
1445
1446 Tcl_SetChannelError(rcPtr->chan, resObj);
1447 goto invalid;
1448 }
1449
1450 if (Tcl_InterpDeleted(rcPtr->interp)) {
1451 /*
1452 * The interp was destroyed during InvokeTclMethod().
1453 */
1454
1455 SetChannelErrorStr(rcPtr->chan, msg_send_dstlost);
1456 goto invalid;
1457 }
1458 if (Tcl_GetIntFromObj(rcPtr->interp, resObj, &written) != TCL_OK) {
1459 Tcl_SetChannelError(rcPtr->chan, MarshallError(rcPtr->interp));
1460 goto invalid;
1461 }
1462
1463 if ((written == 0) && (toWrite > 0)) {
1464 /*
1465 * The handler claims to have written nothing of what it was given.
1466 * That is bad.
1467 */
1468
1469 SetChannelErrorStr(rcPtr->chan, msg_write_nothing);
1470 goto invalid;
1471 }
1472 if (toWrite < written) {
1473 /*
1474 * The handler claims to have written more than it was given. That is
1475 * bad. Note that the I/O core would crash if we were to return this
1476 * information, trying to write -nnn bytes in the next iteration.
1477 */
1478
1479 SetChannelErrorStr(rcPtr->chan, msg_write_toomuch);
1480 goto invalid;
1481 }
1482
1483 *errorCodePtr = EOK;
1484 stop:
1485 Tcl_DecrRefCount(bufObj);
1486 Tcl_DecrRefCount(resObj); /* Remove reference held from invoke */
1487 Tcl_Release(rcPtr->interp);
1488 Tcl_Release(rcPtr);
1489 return written;
1490 invalid:
1491 *errorCodePtr = EINVAL;
1492 error:
1493 written = -1;
1494 goto stop;
1495 }
1496
1497 /*
1498 *----------------------------------------------------------------------
1499 *
1500 * ReflectSeekWide / ReflectSeek --
1501 *
1502 * This function is invoked when the user wishes to seek on the channel.
1503 *
1504 * Results:
1505 * The new location of the access point.
1506 *
1507 * Side effects:
1508 * Allocates memory. Arbitrary, as it calls upon a script.
1509 *
1510 *----------------------------------------------------------------------
1511 */
1512
1513 static Tcl_WideInt
1514 ReflectSeekWide(
1515 void *clientData,
1516 Tcl_WideInt offset,
1517 int seekMode,
1518 int *errorCodePtr)
1519 {
1520 ReflectedChannel *rcPtr = (ReflectedChannel *)clientData;
1521 Tcl_Obj *offObj, *baseObj;
1522 Tcl_Obj *resObj; /* Result for 'seek' */
1523 Tcl_WideInt newLoc;
1524
1525 /*
1526 * Are we in the correct thread?
1527 */
1528
1529 #ifdef TCL_THREADS
1530 if (rcPtr->thread != Tcl_GetCurrentThread()) {
1531 ForwardParam p;
1532
1533 p.seek.seekMode = seekMode;
1534 p.seek.offset = offset;
1535
1536 ForwardOpToHandlerThread(rcPtr, ForwardedSeek, &p);
1537
1538 if (p.base.code != TCL_OK) {
1539 PassReceivedError(rcPtr->chan, &p);
1540 *errorCodePtr = EINVAL;
1541 p.seek.offset = -1;
1542 } else {
1543 *errorCodePtr = EOK;
1544 }
1545
1546 return p.seek.offset;
1547 }
1548 #endif
1549
1550 /* ASSERT: rcPtr->method & FLAG(METH_SEEK) */
1551
1552 Tcl_Preserve(rcPtr);
1553
1554 offObj = Tcl_NewWideIntObj(offset);
1555 baseObj = Tcl_NewStringObj(
1556 (seekMode == SEEK_SET) ? "start" :
1557 (seekMode == SEEK_CUR) ? "current" : "end", -1);
1558 Tcl_IncrRefCount(offObj);
1559 Tcl_IncrRefCount(baseObj);
1560
1561 if (InvokeTclMethod(rcPtr, METH_SEEK, offObj, baseObj, &resObj)!=TCL_OK) {
1562 Tcl_SetChannelError(rcPtr->chan, resObj);
1563 goto invalid;
1564 }
1565
1566 if (TclGetWideIntFromObj(rcPtr->interp, resObj, &newLoc) != TCL_OK) {
1567 Tcl_SetChannelError(rcPtr->chan, MarshallError(rcPtr->interp));
1568 goto invalid;
1569 }
1570
1571 if (newLoc < 0) {
1572 SetChannelErrorStr(rcPtr->chan, msg_seek_beforestart);
1573 goto invalid;
1574 }
1575
1576 *errorCodePtr = EOK;
1577 stop:
1578 Tcl_DecrRefCount(offObj);
1579 Tcl_DecrRefCount(baseObj);
1580 Tcl_DecrRefCount(resObj); /* Remove reference held from invoke */
1581 Tcl_Release(rcPtr);
1582 return newLoc;
1583 invalid:
1584 *errorCodePtr = EINVAL;
1585 newLoc = -1;
1586 goto stop;
1587 }
1588
1589 static int
1590 ReflectSeek(
1591 void *clientData,
1592 long offset,
1593 int seekMode,
1594 int *errorCodePtr)
1595 {
1596 /*
1597 * This function can be invoked from a transformation which is based on
1598 * standard seeking, i.e. non-wide. Because of this we have to implement
1599 * it, a dummy is not enough. We simply delegate the call to the wide
1600 * routine.
1601 */
1602
1603 return (int) ReflectSeekWide(clientData, Tcl_LongAsWide(offset), seekMode,
1604 errorCodePtr);
1605 }
1606
1607 /*
1608 *----------------------------------------------------------------------
1609 *
1610 * ReflectWatch --
1611 *
1612 * This function is invoked to tell the channel what events the I/O
1613 * system is interested in.
1614 *
1615 * Results:
1616 * None.
1617 *
1618 * Side effects:
1619 * Allocates memory. Arbitrary, as it calls upon a script.
1620 *
1621 *----------------------------------------------------------------------
1622 */
1623
1624 static void
1625 ReflectWatch(
1626 void *clientData,
1627 int mask)
1628 {
1629 ReflectedChannel *rcPtr = (ReflectedChannel *)clientData;
1630 Tcl_Obj *maskObj;
1631
1632 /*
1633 * We restrict the interest to what the channel can support. IOW there
1634 * will never be write events for a channel which is not writable.
1635 * Analoguously for read events and non-readable channels.
1636 */
1637
1638 mask &= rcPtr->mode;
1639
1640 if (mask == rcPtr->interest) {
1641 /*
1642 * Same old, same old, why should we do something?
1643 */
1644
1645 return;
1646 }
1647
1648 /*
1649 * Are we in the correct thread?
1650 */
1651
1652 #ifdef TCL_THREADS
1653 if (rcPtr->thread != Tcl_GetCurrentThread()) {
1654 ForwardParam p;
1655
1656 p.watch.mask = mask;
1657 ForwardOpToHandlerThread(rcPtr, ForwardedWatch, &p);
1658
1659 /*
1660 * Any failure from the forward is ignored. We have no place to put
1661 * this.
1662 */
1663
1664 return;
1665 }
1666 #endif
1667
1668 Tcl_Preserve(rcPtr);
1669
1670 rcPtr->interest = mask;
1671 maskObj = DecodeEventMask(mask);
1672 /* assert maskObj.refCount == 1 */
1673 (void) InvokeTclMethod(rcPtr, METH_WATCH, maskObj, NULL, NULL);
1674 Tcl_DecrRefCount(maskObj);
1675
1676 Tcl_Release(rcPtr);
1677 }
1678
1679 /*
1680 *----------------------------------------------------------------------
1681 *
1682 * ReflectBlock --
1683 *
1684 * This function is invoked to tell the channel which blocking behaviour
1685 * is required of it.
1686 *
1687 * Results:
1688 * A Posix error number.
1689 *
1690 * Side effects:
1691 * Allocates memory. Arbitrary, as it calls upon a script.
1692 *
1693 *----------------------------------------------------------------------
1694 */
1695
1696 static int
1697 ReflectBlock(
1698 void *clientData,
1699 int nonblocking)
1700 {
1701 ReflectedChannel *rcPtr = (ReflectedChannel *)clientData;
1702 Tcl_Obj *blockObj;
1703 int errorNum; /* EINVAL or EOK (success). */
1704 Tcl_Obj *resObj; /* Result data for 'blocking' */
1705
1706 /*
1707 * Are we in the correct thread?
1708 */
1709
1710 #ifdef TCL_THREADS
1711 if (rcPtr->thread != Tcl_GetCurrentThread()) {
1712 ForwardParam p;
1713
1714 p.block.nonblocking = nonblocking;
1715
1716 ForwardOpToHandlerThread(rcPtr, ForwardedBlock, &p);
1717
1718 if (p.base.code != TCL_OK) {
1719 PassReceivedError(rcPtr->chan, &p);
1720 return EINVAL;
1721 }
1722
1723 return EOK;
1724 }
1725 #endif
1726
1727 blockObj = Tcl_NewBooleanObj(!nonblocking);
1728 Tcl_IncrRefCount(blockObj);
1729
1730 Tcl_Preserve(rcPtr);
1731
1732 if (InvokeTclMethod(rcPtr,METH_BLOCKING,blockObj,NULL,&resObj)!=TCL_OK) {
1733 Tcl_SetChannelError(rcPtr->chan, resObj);
1734 errorNum = EINVAL;
1735 } else {
1736 errorNum = EOK;
1737 }
1738
1739 Tcl_DecrRefCount(blockObj);
1740 Tcl_DecrRefCount(resObj); /* Remove reference held from invoke */
1741
1742 Tcl_Release(rcPtr);
1743 return errorNum;
1744 }
1745
1746 #ifdef TCL_THREADS
1747 /*
1748 *----------------------------------------------------------------------
1749 *
1750 * ReflectThread --
1751 *
1752 * This function is invoked to tell the channel about thread movements.
1753 *
1754 * Results:
1755 * None.
1756 *
1757 * Side effects:
1758 * Allocates memory. Arbitrary, as it calls upon a script.
1759 *
1760 *----------------------------------------------------------------------
1761 */
1762
1763 static void
1764 ReflectThread(
1765 void *clientData,
1766 int action)
1767 {
1768 ReflectedChannel *rcPtr = (ReflectedChannel *)clientData;
1769
1770 switch (action) {
1771 case TCL_CHANNEL_THREAD_INSERT:
1772 rcPtr->owner = Tcl_GetCurrentThread();
1773 break;
1774 case TCL_CHANNEL_THREAD_REMOVE:
1775 rcPtr->owner = NULL;
1776 break;
1777 default:
1778 Tcl_Panic("Unknown thread action code.");
1779 break;
1780 }
1781 }
1782
1783 #endif
1784 /*
1785 *----------------------------------------------------------------------
1786 *
1787 * ReflectSetOption --
1788 *
1789 * This function is invoked to configure a channel option.
1790 *
1791 * Results:
1792 * A standard Tcl result code.
1793 *
1794 * Side effects:
1795 * Arbitrary, as it calls upon a Tcl script.
1796 *
1797 *----------------------------------------------------------------------
1798 */
1799
1800 static int
1801 ReflectSetOption(
1802 void *clientData, /* Channel to query */
1803 Tcl_Interp *interp, /* Interpreter to leave error messages in */
1804 const char *optionName, /* Name of requested option */
1805 const char *newValue) /* The new value */
1806 {
1807 ReflectedChannel *rcPtr = (ReflectedChannel *)clientData;
1808 Tcl_Obj *optionObj, *valueObj;
1809 int result; /* Result code for 'configure' */
1810 Tcl_Obj *resObj; /* Result data for 'configure' */
1811
1812 /*
1813 * Are we in the correct thread?
1814 */
1815
1816 #ifdef TCL_THREADS
1817 if (rcPtr->thread != Tcl_GetCurrentThread()) {
1818 ForwardParam p;
1819
1820 p.setOpt.name = optionName;
1821 p.setOpt.value = newValue;
1822
1823 ForwardOpToHandlerThread(rcPtr, ForwardedSetOpt, &p);
1824
1825 if (p.base.code != TCL_OK) {
1826 Tcl_Obj *err = Tcl_NewStringObj(p.base.msgStr, -1);
1827
1828 UnmarshallErrorResult(interp, err);
1829 Tcl_DecrRefCount(err);
1830 FreeReceivedError(&p);
1831 }
1832
1833 return p.base.code;
1834 }
1835 #endif
1836 Tcl_Preserve(rcPtr);
1837
1838 optionObj = Tcl_NewStringObj(optionName, -1);
1839 valueObj = Tcl_NewStringObj(newValue, -1);
1840
1841 Tcl_IncrRefCount(optionObj);
1842 Tcl_IncrRefCount(valueObj);
1843
1844 result = InvokeTclMethod(rcPtr, METH_CONFIGURE,optionObj,valueObj, &resObj);
1845 if (result != TCL_OK) {
1846 UnmarshallErrorResult(interp, resObj);
1847 }
1848
1849 Tcl_DecrRefCount(optionObj);
1850 Tcl_DecrRefCount(valueObj);
1851 Tcl_DecrRefCount(resObj); /* Remove reference held from invoke */
1852 Tcl_Release(rcPtr);
1853 return result;
1854 }
1855
1856 /*
1857 *----------------------------------------------------------------------
1858 *
1859 * ReflectGetOption --
1860 *
1861 * This function is invoked to retrieve all or a channel option.
1862 *
1863 * Results:
1864 * A standard Tcl result code.
1865 *
1866 * Side effects:
1867 * Arbitrary, as it calls upon a Tcl script.
1868 *
1869 *----------------------------------------------------------------------
1870 */
1871
1872 static int
1873 ReflectGetOption(
1874 void *clientData, /* Channel to query */
1875 Tcl_Interp *interp, /* Interpreter to leave error messages in */
1876 const char *optionName, /* Name of reuqested option */
1877 Tcl_DString *dsPtr) /* String to place the result into */
1878 {
1879 /*
1880 * This code is special. It has regular passing of Tcl result, and errors.
1881 * The bypass functions are not required.
1882 */
1883
1884 ReflectedChannel *rcPtr = (ReflectedChannel *)clientData;
1885 Tcl_Obj *optionObj;
1886 Tcl_Obj *resObj; /* Result data for 'configure' */
1887 int listc;
1888 int result = TCL_OK;
1889 Tcl_Obj **listv;
1890 MethodName method;
1891
1892 /*
1893 * Are we in the correct thread?
1894 */
1895
1896 #ifdef TCL_THREADS
1897 if (rcPtr->thread != Tcl_GetCurrentThread()) {
1898 int opcode;
1899 ForwardParam p;
1900
1901 p.getOpt.name = optionName;
1902 p.getOpt.value = dsPtr;
1903
1904 if (optionName == NULL) {
1905 opcode = ForwardedGetOptAll;
1906 } else {
1907 opcode = ForwardedGetOpt;
1908 }
1909
1910 ForwardOpToHandlerThread(rcPtr, opcode, &p);
1911
1912 if (p.base.code != TCL_OK) {
1913 Tcl_Obj *err = Tcl_NewStringObj(p.base.msgStr, -1);
1914
1915 UnmarshallErrorResult(interp, err);
1916 Tcl_DecrRefCount(err);
1917 FreeReceivedError(&p);
1918 }
1919
1920 return p.base.code;
1921 }
1922 #endif
1923
1924 if (optionName == NULL) {
1925 /*
1926 * Retrieve all options.
1927 */
1928
1929 method = METH_CGETALL;
1930 optionObj = NULL;
1931 } else {
1932 /*
1933 * Retrieve the value of one option.
1934 */
1935
1936 method = METH_CGET;
1937 optionObj = Tcl_NewStringObj(optionName, -1);
1938 Tcl_IncrRefCount(optionObj);
1939 }
1940
1941 Tcl_Preserve(rcPtr);
1942
1943 if (InvokeTclMethod(rcPtr, method, optionObj, NULL, &resObj)!=TCL_OK) {
1944 UnmarshallErrorResult(interp, resObj);
1945 goto error;
1946 }
1947
1948 /*
1949 * The result has to go into the 'dsPtr' for propagation to the caller of
1950 * the driver.
1951 */
1952
1953 if (optionObj != NULL) {
1954 TclDStringAppendObj(dsPtr, resObj);
1955 goto ok;
1956 }
1957
1958 /*
1959 * Extract the list and append each item as element.
1960 */
1961
1962 /*
1963 * NOTE (4): If we extract the string rep we can assume a properly quoted
1964 * string. Together with a separating space this way of simply appending
1965 * the whole string rep might be faster. It also doesn't check if the
1966 * result is a valid list. Nor that the list has an even number elements.
1967 */
1968
1969 if (TclListObjGetElements(interp, resObj, &listc, &listv) != TCL_OK) {
1970 goto error;
1971 }
1972
1973 if ((listc % 2) == 1) {
1974 /*
1975 * Odd number of elements is wrong.
1976 */
1977
1978 Tcl_ResetResult(interp);
1979 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1980 "Expected list with even number of "
1981 "elements, got %d element%s instead", listc,
1982 (listc == 1 ? "" : "s")));
1983 goto error;
1984 } else {
1985 int len;
1986 const char *str = TclGetStringFromObj(resObj, &len);
1987
1988 if (len) {
1989 TclDStringAppendLiteral(dsPtr, " ");
1990 Tcl_DStringAppend(dsPtr, str, len);
1991 }
1992 goto ok;
1993 }
1994
1995 ok:
1996 result = TCL_OK;
1997 stop:
1998 if (optionObj) {
1999 Tcl_DecrRefCount(optionObj);
2000 }
2001 Tcl_DecrRefCount(resObj); /* Remove reference held from invoke */
2002 Tcl_Release(rcPtr);
2003 return result;
2004 error:
2005 result = TCL_ERROR;
2006 goto stop;
2007 }
2008
2009 /*
2010 * Helpers. =========================================================
2011 */
2012
2013 /*
2014 *----------------------------------------------------------------------
2015 *
2016 * EncodeEventMask --
2017 *
2018 * This function takes a list of event items and constructs the
2019 * equivalent internal bitmask. The list may be empty but will usually
2020 * contain at least one element. Valid elements are "read", "write", or
2021 * any unique abbreviation of them. Note that the bitmask is not changed
2022 * if problems are encountered.
2023 *
2024 * Results:
2025 * A standard Tcl error code. A bitmask where TCL_READABLE and/or
2026 * TCL_WRITABLE can be set.
2027 *
2028 * Side effects:
2029 * May shimmer 'obj' to a list representation. May place an error message
2030 * into the interp result.
2031 *
2032 *----------------------------------------------------------------------
2033 */
2034
2035 static int
2036 EncodeEventMask(
2037 Tcl_Interp *interp,
2038 const char *objName,
2039 Tcl_Obj *obj,
2040 int *mask)
2041 {
2042 int events; /* Mask of events to post */
2043 int listc; /* #elements in eventspec list */
2044 Tcl_Obj **listv; /* Elements of eventspec list */
2045 int evIndex; /* Id of event for an element of the eventspec
2046 * list. */
2047
2048 if (TclListObjGetElements(interp, obj, &listc, &listv) != TCL_OK) {
2049 return TCL_ERROR;
2050 }
2051
2052 events = 0;
2053 while (listc > 0) {
2054 if (Tcl_GetIndexFromObj(interp, listv[listc-1], eventOptions,
2055 objName, 0, &evIndex) != TCL_OK) {
2056 return TCL_ERROR;
2057 }
2058 switch (evIndex) {
2059 case EVENT_READ:
2060 events |= TCL_READABLE;
2061 break;
2062 case EVENT_WRITE:
2063 events |= TCL_WRITABLE;
2064 break;
2065 }
2066 listc --;
2067 }
2068
2069 *mask = events;
2070 return TCL_OK;
2071 }
2072
2073 /*
2074 *----------------------------------------------------------------------
2075 *
2076 * DecodeEventMask --
2077 *
2078 * This function takes an internal bitmask of events and constructs the
2079 * equivalent list of event items.
2080 *
2081 * Results, Contract:
2082 * A Tcl_Obj reference. The object will have a refCount of one. The user
2083 * has to decrement it to release the object.
2084 *
2085 * Side effects:
2086 * None.
2087 *
2088 *----------------------------------------------------------------------
2089 */
2090
2091 static Tcl_Obj *
2092 DecodeEventMask(
2093 int mask)
2094 {
2095 const char *eventStr;
2096 Tcl_Obj *evObj;
2097
2098 switch (mask & RANDW) {
2099 case RANDW:
2100 eventStr = "read write";
2101 break;
2102 case TCL_READABLE:
2103 eventStr = "read";
2104 break;
2105 case TCL_WRITABLE:
2106 eventStr = "write";
2107 break;
2108 default:
2109 eventStr = "";
2110 break;
2111 }
2112
2113 evObj = Tcl_NewStringObj(eventStr, -1);
2114 Tcl_IncrRefCount(evObj);
2115 /* assert evObj.refCount == 1 */
2116 return evObj;
2117 }
2118
2119 /*
2120 *----------------------------------------------------------------------
2121 *
2122 * NewReflectedChannel --
2123 *
2124 * This function is invoked to allocate and initialize the instance data
2125 * of a new reflected channel.
2126 *
2127 * Results:
2128 * A heap-allocated channel instance.
2129 *
2130 * Side effects:
2131 * Allocates memory.
2132 *
2133 *----------------------------------------------------------------------
2134 */
2135
2136 static ReflectedChannel *
2137 NewReflectedChannel(
2138 Tcl_Interp *interp,
2139 Tcl_Obj *cmdpfxObj,
2140 int mode,
2141 Tcl_Obj *handleObj)
2142 {
2143 ReflectedChannel *rcPtr;
2144 MethodName mn = METH_BLOCKING;
2145
2146 rcPtr = (ReflectedChannel *)ckalloc(sizeof(ReflectedChannel));
2147
2148 /* rcPtr->chan: Assigned by caller. Dummy data here. */
2149
2150 rcPtr->chan = NULL;
2151 rcPtr->interp = interp;
2152 rcPtr->dead = 0;
2153 #ifdef TCL_THREADS
2154 rcPtr->thread = Tcl_GetCurrentThread();
2155 #endif
2156 rcPtr->mode = mode;
2157 rcPtr->interest = 0; /* Initially no interest registered */
2158
2159 rcPtr->cmd = TclListObjCopy(NULL, cmdpfxObj);
2160 Tcl_IncrRefCount(rcPtr->cmd);
2161 rcPtr->methods = Tcl_NewListObj(METH_WRITE + 1, NULL);
2162 while (mn <= METH_WRITE) {
2163 Tcl_ListObjAppendElement(NULL, rcPtr->methods,
2164 Tcl_NewStringObj(methodNames[mn++], -1));
2165 }
2166 Tcl_IncrRefCount(rcPtr->methods);
2167 rcPtr->name = handleObj;
2168 Tcl_IncrRefCount(rcPtr->name);
2169 return rcPtr;
2170 }
2171
2172 /*
2173 *----------------------------------------------------------------------
2174 *
2175 * NextHandle --
2176 *
2177 * This function is invoked to generate a channel handle for a new
2178 * reflected channel.
2179 *
2180 * Results:
2181 * A Tcl_Obj containing the string of the new channel handle. The
2182 * refcount of the returned object is -- zero --.
2183 *
2184 * Side effects:
2185 * May allocate memory. Mutex-protected critical section locks out other
2186 * threads for a short time.
2187 *
2188 *----------------------------------------------------------------------
2189 */
2190
2191 static Tcl_Obj *
2192 NextHandle(void)
2193 {
2194 /*
2195 * Count number of generated reflected channels. Used for id generation.
2196 * Ids are never reclaimed and there is no dealing with wrap around. On
2197 * the other hand, "unsigned long" should be big enough except for
2198 * absolute longrunners (generate a 100 ids per second => overflow will
2199 * occur in 1 1/3 years).
2200 */
2201
2202 TCL_DECLARE_MUTEX(rcCounterMutex)
2203 static unsigned long rcCounter = 0;
2204 Tcl_Obj *resObj;
2205
2206 Tcl_MutexLock(&rcCounterMutex);
2207 resObj = Tcl_ObjPrintf("rc%lu", rcCounter);
2208 rcCounter++;
2209 Tcl_MutexUnlock(&rcCounterMutex);
2210
2211 return resObj;
2212 }
2213
2214 static inline void
2215 CleanRefChannelInstance(
2216 ReflectedChannel *rcPtr)
2217 {
2218 if (rcPtr->name) {
2219 /*
2220 * Reset obj-type (channel is deleted or dead anyway) to avoid leakage
2221 * by cyclic references (see bug [79474c58800cdf94]).
2222 */
2223 TclFreeIntRep(rcPtr->name);
2224 Tcl_DecrRefCount(rcPtr->name);
2225 rcPtr->name = NULL;
2226 }
2227 if (rcPtr->methods) {
2228 Tcl_DecrRefCount(rcPtr->methods);
2229 rcPtr->methods = NULL;
2230 }
2231 if (rcPtr->cmd) {
2232 Tcl_DecrRefCount(rcPtr->cmd);
2233 rcPtr->cmd = NULL;
2234 }
2235 }
2236 static void
2237 FreeReflectedChannel(
2238 char *blockPtr)
2239 {
2240 ReflectedChannel *rcPtr = (ReflectedChannel *) blockPtr;
2241 Channel *chanPtr = (Channel *) rcPtr->chan;
2242
2243 TclChannelRelease((Tcl_Channel)chanPtr);
2244 CleanRefChannelInstance(rcPtr);
2245 ckfree(rcPtr);
2246 }
2247
2248 /*
2249 *----------------------------------------------------------------------
2250 *
2251 * InvokeTclMethod --
2252 *
2253 * This function is used to invoke the Tcl level of a reflected channel.
2254 * It handles all the command assembly, invocation, and generic state and
2255 * result mgmt. It does *not* handle thread redirection; that is the
2256 * responsibility of clients of this function.
2257 *
2258 * Results:
2259 * Result code and data as returned by the method.
2260 *
2261 * Side effects:
2262 * Arbitrary, as it calls upon a Tcl script.
2263 *
2264 * Contract:
2265 * argOneObj.refCount >= 1 on entry and exit, if argOneObj != NULL
2266 * argTwoObj.refCount >= 1 on entry and exit, if argTwoObj != NULL
2267 * resObj.refCount in {0, 1, ...}
2268 *
2269 *----------------------------------------------------------------------
2270 */
2271
2272 static int
2273 InvokeTclMethod(
2274 ReflectedChannel *rcPtr,
2275 MethodName method,
2276 Tcl_Obj *argOneObj, /* NULL'able */
2277 Tcl_Obj *argTwoObj, /* NULL'able */
2278 Tcl_Obj **resultObjPtr) /* NULL'able */
2279 {
2280 Tcl_Obj *methObj = NULL; /* Method name in object form */
2281 Tcl_InterpState sr; /* State of handler interp */
2282 int result; /* Result code of method invocation */
2283 Tcl_Obj *resObj = NULL; /* Result of method invocation. */
2284 Tcl_Obj *cmd;
2285
2286 if (rcPtr->dead) {
2287 /*
2288 * The channel is marked as dead. Bail out immediately, with an
2289 * appropriate error.
2290 */
2291
2292 if (resultObjPtr != NULL) {
2293 resObj = Tcl_NewStringObj(msg_dstlost,-1);
2294 *resultObjPtr = resObj;
2295 Tcl_IncrRefCount(resObj);
2296 }
2297
2298 /*
2299 * Not touching argOneObj, argTwoObj, they have not been used.
2300 * See the contract as well.
2301 */
2302
2303 return TCL_ERROR;
2304 }
2305
2306 /*
2307 * Insert method into the callback command, after the command prefix,
2308 * before the channel id.
2309 */
2310
2311 cmd = TclListObjCopy(NULL, rcPtr->cmd);
2312 Tcl_ListObjIndex(NULL, rcPtr->methods, method, &methObj);
2313 Tcl_ListObjAppendElement(NULL, cmd, methObj);
2314 Tcl_ListObjAppendElement(NULL, cmd, rcPtr->name);
2315
2316 /*
2317 * Append the additional argument containing method specific details
2318 * behind the channel id. If specified.
2319 *
2320 * Because of the contract there is no need to increment the refcounts.
2321 * The objects will survive the Tcl_EvalObjv without change.
2322 */
2323
2324 if (argOneObj) {
2325 Tcl_ListObjAppendElement(NULL, cmd, argOneObj);
2326 if (argTwoObj) {
2327 Tcl_ListObjAppendElement(NULL, cmd, argTwoObj);
2328 }
2329 }
2330
2331 /*
2332 * And run the handler... This is done in auch a manner which leaves any
2333 * existing state intact.
2334 */
2335
2336 Tcl_IncrRefCount(cmd);
2337 sr = Tcl_SaveInterpState(rcPtr->interp, 0 /* Dummy */);
2338 Tcl_Preserve(rcPtr->interp);
2339 result = Tcl_EvalObjEx(rcPtr->interp, cmd, TCL_EVAL_GLOBAL);
2340
2341 /*
2342 * We do not try to extract the result information if the caller has no
2343 * interest in it. I.e. there is no need to put effort into creating
2344 * something which is discarded immediately after.
2345 */
2346
2347 if (resultObjPtr) {
2348 if (result == TCL_OK) {
2349 /*
2350 * Ok result taken as is, also if the caller requests that there
2351 * is no capture.
2352 */
2353
2354 resObj = Tcl_GetObjResult(rcPtr->interp);
2355 } else {
2356 /*
2357 * Non-ok result is always treated as an error. We have to capture
2358 * the full state of the result, including additional options.
2359 *
2360 * This is complex and ugly, and would be completely unnecessary
2361 * if we only added support for a TCL_FORBID_EXCEPTIONS flag.
2362 */
2363
2364 if (result != TCL_ERROR) {
2365 int cmdLen;
2366 const char *cmdString = TclGetStringFromObj(cmd, &cmdLen);
2367
2368 Tcl_IncrRefCount(cmd);
2369 Tcl_ResetResult(rcPtr->interp);
2370 Tcl_SetObjResult(rcPtr->interp, Tcl_ObjPrintf(
2371 "chan handler returned bad code: %d", result));
2372 Tcl_LogCommandInfo(rcPtr->interp, cmdString, cmdString,
2373 cmdLen);
2374 Tcl_DecrRefCount(cmd);
2375 result = TCL_ERROR;
2376 }
2377 Tcl_AppendObjToErrorInfo(rcPtr->interp, Tcl_ObjPrintf(
2378 "\n (chan handler subcommand \"%s\")",
2379 methodNames[method]));
2380 resObj = MarshallError(rcPtr->interp);
2381 }
2382 Tcl_IncrRefCount(resObj);
2383 }
2384 Tcl_DecrRefCount(cmd);
2385 Tcl_RestoreInterpState(rcPtr->interp, sr);
2386 Tcl_Release(rcPtr->interp);
2387
2388 /*
2389 * The resObj has a ref count of 1 at this location. This means that the
2390 * caller of InvokeTclMethod has to dispose of it (but only if it was
2391 * returned to it).
2392 */
2393
2394 if (resultObjPtr != NULL) {
2395 *resultObjPtr = resObj;
2396 }
2397
2398 /*
2399 * There no need to handle the case where nothing is returned, because for
2400 * that case resObj was not set anyway.
2401 */
2402
2403 return result;
2404 }
2405
2406 /*
2407 *----------------------------------------------------------------------
2408 *
2409 * ErrnoReturn --
2410 *
2411 * Checks a method error result if it returned an 'errno'.
2412 *
2413 * Results:
2414 * The negative errno found in the error result, or 0.
2415 *
2416 * Side effects:
2417 * None.
2418 *
2419 * Users:
2420 * ReflectInput/Output(), to enable the signaling of EAGAIN on 0-sized
2421 * short reads/writes.
2422 *
2423 *----------------------------------------------------------------------
2424 */
2425
2426 static int
2427 ErrnoReturn(
2428 ReflectedChannel *rcPtr,
2429 Tcl_Obj *resObj)
2430 {
2431 int code;
2432 Tcl_InterpState sr; /* State of handler interp */
2433
2434 if (rcPtr->dead) {
2435 return 0;
2436 }
2437
2438 sr = Tcl_SaveInterpState(rcPtr->interp, 0 /* Dummy */);
2439 UnmarshallErrorResult(rcPtr->interp, resObj);
2440
2441 resObj = Tcl_GetObjResult(rcPtr->interp);
2442
2443 if (((Tcl_GetIntFromObj(rcPtr->interp, resObj, &code) != TCL_OK)
2444 || (code >= 0))) {
2445 if (strcmp("EAGAIN", TclGetString(resObj)) == 0) {
2446 code = -EAGAIN;
2447 } else {
2448 code = 0;
2449 }
2450 }
2451
2452 Tcl_RestoreInterpState(rcPtr->interp, sr);
2453 return code;
2454 }
2455
2456 /*
2457 *----------------------------------------------------------------------
2458 *
2459 * GetReflectedChannelMap --
2460 *
2461 * Gets and potentially initializes the reflected channel map for an
2462 * interpreter.
2463 *
2464 * Results:
2465 * A pointer to the map created, for use by the caller.
2466 *
2467 * Side effects:
2468 * Initializes the reflected channel map for an interpreter.
2469 *
2470 *----------------------------------------------------------------------
2471 */
2472
2473 static ReflectedChannelMap *
2474 GetReflectedChannelMap(
2475 Tcl_Interp *interp)
2476 {
2477 ReflectedChannelMap *rcmPtr = (ReflectedChannelMap *)Tcl_GetAssocData(interp, RCMKEY, NULL);
2478
2479 if (rcmPtr == NULL) {
2480 rcmPtr = (ReflectedChannelMap *)ckalloc(sizeof(ReflectedChannelMap));
2481 Tcl_InitHashTable(&rcmPtr->map, TCL_STRING_KEYS);
2482 Tcl_SetAssocData(interp, RCMKEY, DeleteReflectedChannelMap, rcmPtr);
2483 }
2484 return rcmPtr;
2485 }
2486
2487 /*
2488 *----------------------------------------------------------------------
2489 *
2490 * DeleteReflectedChannelMap --
2491 *
2492 * Deletes the channel table for an interpreter, closing any open
2493 * channels whose refcount reaches zero. This procedure is invoked when
2494 * an interpreter is deleted, via the AssocData cleanup mechanism.
2495 *
2496 * Results:
2497 * None.
2498 *
2499 * Side effects:
2500 * Deletes the hash table of channels. May close channels. May flush
2501 * output on closed channels. Removes any channelEvent handlers that were
2502 * registered in this interpreter.
2503 *
2504 *----------------------------------------------------------------------
2505 */
2506
2507 static void
2508 MarkDead(
2509 ReflectedChannel *rcPtr)
2510 {
2511 if (rcPtr->dead) {
2512 return;
2513 }
2514 CleanRefChannelInstance(rcPtr);
2515 rcPtr->dead = 1;
2516 }
2517
2518 static void
2519 DeleteReflectedChannelMap(
2520 void *clientData, /* The per-interpreter data structure. */
2521 Tcl_Interp *interp) /* The interpreter being deleted. */
2522 {
2523 ReflectedChannelMap *rcmPtr = (ReflectedChannelMap *)clientData;
2524 /* The map */
2525 Tcl_HashSearch hSearch; /* Search variable. */
2526 Tcl_HashEntry *hPtr; /* Search variable. */
2527 ReflectedChannel *rcPtr;
2528 Tcl_Channel chan;
2529 #ifdef TCL_THREADS
2530 ForwardingResult *resultPtr;
2531 ForwardingEvent *evPtr;
2532 ForwardParam *paramPtr;
2533 #endif
2534
2535 /*
2536 * Delete all entries. The channels may have been closed already, or will
2537 * be closed later, by the standard IO finalization of an interpreter
2538 * under destruction. Except for the channels which were moved to a
2539 * different interpreter and/or thread. They do not exist from the IO
2540 * systems point of view and will not get closed. Therefore mark all as
2541 * dead so that any future access will cause a proper error. For channels
2542 * in a different thread we actually do the same as
2543 * DeleteThreadReflectedChannelMap(), just restricted to the channels of
2544 * this interp.
2545 */
2546
2547 for (hPtr = Tcl_FirstHashEntry(&rcmPtr->map, &hSearch);
2548 hPtr != NULL;
2549 hPtr = Tcl_FirstHashEntry(&rcmPtr->map, &hSearch)) {
2550 chan = (Tcl_Channel)Tcl_GetHashValue(hPtr);
2551 rcPtr = (ReflectedChannel *)Tcl_GetChannelInstanceData(chan);
2552
2553 MarkDead(rcPtr);
2554 Tcl_DeleteHashEntry(hPtr);
2555 }
2556 Tcl_DeleteHashTable(&rcmPtr->map);
2557 ckfree(&rcmPtr->map);
2558
2559 #ifdef TCL_THREADS
2560 /*
2561 * The origin interpreter for one or more reflected channels is gone.
2562 */
2563
2564 /*
2565 * Go through the list of pending results and cancel all whose events were
2566 * destined for this interpreter. While this is in progress we block any
2567 * other access to the list of pending results.
2568 */
2569
2570 Tcl_MutexLock(&rcForwardMutex);
2571
2572 for (resultPtr = forwardList;
2573 resultPtr != NULL;
2574 resultPtr = resultPtr->nextPtr) {
2575 if (resultPtr->dsti != interp) {
2576 /*
2577 * Ignore results/events for other interpreters.
2578 */
2579
2580 continue;
2581 }
2582
2583 /*
2584 * The receiver for the event exited, before processing the event. We
2585 * detach the result now, wake the originator up and signal failure.
2586 *
2587 * Attention: Results may have been detached already, by either the
2588 * receiver, or this thread, as part of other parts in the thread
2589 * teardown. Such results are ignored. See ticket [b47b176adf] for the
2590 * identical race condition in Tcl 8.6 IORTrans.
2591 */
2592
2593 evPtr = resultPtr->evPtr;
2594
2595 /*
2596 * Basic crash safety until this routine can get revised [3411310]
2597 */
2598
2599 if (evPtr == NULL) {
2600 continue;
2601 }
2602 paramPtr = evPtr->param;
2603 if (!evPtr) {
2604 continue;
2605 }
2606
2607 evPtr->resultPtr = NULL;
2608 resultPtr->evPtr = NULL;
2609 resultPtr->result = TCL_ERROR;
2610
2611 ForwardSetStaticError(paramPtr, msg_send_dstlost);
2612
2613 Tcl_ConditionNotify(&resultPtr->done);
2614 }
2615 Tcl_MutexUnlock(&rcForwardMutex);
2616
2617 /*
2618 * Get the map of all channels handled by the current thread. This is a
2619 * ReflectedChannelMap, but on a per-thread basis, not per-interp. Go
2620 * through the channels and remove all which were handled by this
2621 * interpreter. They have already been marked as dead.
2622 */
2623
2624 rcmPtr = GetThreadReflectedChannelMap();
2625 for (hPtr = Tcl_FirstHashEntry(&rcmPtr->map, &hSearch);
2626 hPtr != NULL;
2627 hPtr = Tcl_NextHashEntry(&hSearch)) {
2628 chan = (Tcl_Channel)Tcl_GetHashValue(hPtr);
2629 rcPtr = (ReflectedChannel *)Tcl_GetChannelInstanceData(chan);
2630
2631 if (rcPtr->interp != interp) {
2632 /*
2633 * Ignore entries for other interpreters.
2634 */
2635
2636 continue;
2637 }
2638
2639 MarkDead(rcPtr);
2640 Tcl_DeleteHashEntry(hPtr);
2641 }
2642 #endif
2643 }
2644
2645 #ifdef TCL_THREADS
2646 /*
2647 *----------------------------------------------------------------------
2648 *
2649 * GetThreadReflectedChannelMap --
2650 *
2651 * Gets and potentially initializes the reflected channel map for a
2652 * thread.
2653 *
2654 * Results:
2655 * A pointer to the map created, for use by the caller.
2656 *
2657 * Side effects:
2658 * Initializes the reflected channel map for a thread.
2659 *
2660 *----------------------------------------------------------------------
2661 */
2662
2663 static ReflectedChannelMap *
2664 GetThreadReflectedChannelMap(void)
2665 {
2666 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
2667
2668 if (!tsdPtr->rcmPtr) {
2669 tsdPtr->rcmPtr = (ReflectedChannelMap *)ckalloc(sizeof(ReflectedChannelMap));
2670 Tcl_InitHashTable(&tsdPtr->rcmPtr->map, TCL_STRING_KEYS);
2671 Tcl_CreateThreadExitHandler(DeleteThreadReflectedChannelMap, NULL);
2672 }
2673
2674 return tsdPtr->rcmPtr;
2675 }
2676
2677 /*
2678 *----------------------------------------------------------------------
2679 *
2680 * DeleteThreadReflectedChannelMap --
2681 *
2682 * Deletes the channel table for a thread. This procedure is invoked when
2683 * a thread is deleted. The channels have already been marked as dead, in
2684 * DeleteReflectedChannelMap().
2685 *
2686 * Results:
2687 * None.
2688 *
2689 * Side effects:
2690 * Deletes the hash table of channels.
2691 *
2692 *----------------------------------------------------------------------
2693 */
2694
2695 static void
2696 DeleteThreadReflectedChannelMap(
2697 void *dummy) /* The per-thread data structure. */
2698 {
2699 Tcl_HashSearch hSearch; /* Search variable. */
2700 Tcl_HashEntry *hPtr; /* Search variable. */
2701 Tcl_ThreadId self = Tcl_GetCurrentThread();
2702 ReflectedChannelMap *rcmPtr; /* The map */
2703 ForwardingResult *resultPtr;
2704 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
2705 (void)dummy;
2706
2707 /*
2708 * The origin thread for one or more reflected channels is gone.
2709 * NOTE: If this function is called due to a thread getting killed the
2710 * per-interp DeleteReflectedChannelMap is apparently not called.
2711 */
2712
2713 /*
2714 * Go through the list of pending results and cancel all whose events were
2715 * destined for this thread. While this is in progress we block any other
2716 * access to the list of pending results.
2717 */
2718
2719 Tcl_MutexLock(&rcForwardMutex);
2720
2721 for (resultPtr = forwardList;
2722 resultPtr != NULL;
2723 resultPtr = resultPtr->nextPtr) {
2724 ForwardingEvent *evPtr;
2725 ForwardParam *paramPtr;
2726
2727 if (resultPtr->dst != self) {
2728 /*
2729 * Ignore results/events for other threads.
2730 */
2731
2732 continue;
2733 }
2734
2735 /*
2736 * The receiver for the event exited, before processing the event. We
2737 * detach the result now, wake the originator up and signal failure.
2738 *
2739 * Attention: Results may have been detached already, by either the
2740 * receiver, or this thread, as part of other parts in the thread
2741 * teardown. Such results are ignored. See ticket [b47b176adf] for the
2742 * identical race condition in Tcl 8.6 IORTrans.
2743 */
2744
2745 evPtr = resultPtr->evPtr;
2746
2747 /*
2748 * Basic crash safety until this routine can get revised [3411310]
2749 */
2750
2751 if (evPtr == NULL ) {
2752 continue;
2753 }
2754 paramPtr = evPtr->param;
2755 if (!evPtr) {
2756 continue;
2757 }
2758
2759 evPtr->resultPtr = NULL;
2760 resultPtr->evPtr = NULL;
2761 resultPtr->result = TCL_ERROR;
2762
2763 ForwardSetStaticError(paramPtr, msg_send_dstlost);
2764
2765 Tcl_ConditionNotify(&resultPtr->done);
2766 }
2767 Tcl_MutexUnlock(&rcForwardMutex);
2768
2769 /*
2770 * Run over the event queue of this thread and remove all ReflectEvent's
2771 * still pending. These are inbound events for reflected channels this
2772 * thread owns but doesn't handle. The inverse of the channel map
2773 * actually.
2774 */
2775
2776 Tcl_DeleteEvents(ReflectEventDelete, NULL);
2777
2778 /*
2779 * Get the map of all channels handled by the current thread. This is a
2780 * ReflectedChannelMap, but on a per-thread basis, not per-interp. Go
2781 * through the channels, remove all, mark them as dead.
2782 */
2783
2784 rcmPtr = GetThreadReflectedChannelMap();
2785 tsdPtr->rcmPtr = NULL;
2786 for (hPtr = Tcl_FirstHashEntry(&rcmPtr->map, &hSearch);
2787 hPtr != NULL;
2788 hPtr = Tcl_FirstHashEntry(&rcmPtr->map, &hSearch)) {
2789 Tcl_Channel chan = (Tcl_Channel)Tcl_GetHashValue(hPtr);
2790 ReflectedChannel *rcPtr = (ReflectedChannel *)Tcl_GetChannelInstanceData(chan);
2791
2792 MarkDead(rcPtr);
2793 Tcl_DeleteHashEntry(hPtr);
2794 }
2795 ckfree(rcmPtr);
2796 }
2797
2798 static void
2799 ForwardOpToHandlerThread(
2800 ReflectedChannel *rcPtr, /* Channel instance */
2801 ForwardedOperation op, /* Forwarded driver operation */
2802 void *param) /* Arguments */
2803 {
2804 /*
2805 * Core of the communication from OWNER to HANDLER thread. The receiver is
2806 * ForwardProc() below.
2807 */
2808
2809 Tcl_ThreadId dst = rcPtr->thread;
2810 ForwardingEvent *evPtr;
2811 ForwardingResult *resultPtr;
2812
2813 /*
2814 * We gather the lock early. This allows us to check the liveness of the
2815 * channel without interference from DeleteThreadReflectedChannelMap().
2816 */
2817
2818 Tcl_MutexLock(&rcForwardMutex);
2819
2820 if (rcPtr->dead) {
2821 /*
2822 * The channel is marked as dead. Bail out immediately, with an
2823 * appropriate error. Do not forget to unlock the mutex on this path.
2824 */
2825
2826 ForwardSetStaticError((ForwardParam *) param, msg_send_dstlost);
2827 Tcl_MutexUnlock(&rcForwardMutex);
2828 return;
2829 }
2830
2831 /*
2832 * Create and initialize the event and data structures.
2833 */
2834
2835 evPtr = (ForwardingEvent *)ckalloc(sizeof(ForwardingEvent));
2836 resultPtr = (ForwardingResult *)ckalloc(sizeof(ForwardingResult));
2837
2838 evPtr->event.proc = ForwardProc;
2839 evPtr->resultPtr = resultPtr;
2840 evPtr->op = op;
2841 evPtr->rcPtr = rcPtr;
2842 evPtr->param = (ForwardParam *) param;
2843
2844 resultPtr->src = Tcl_GetCurrentThread();
2845 resultPtr->dst = dst;
2846 resultPtr->dsti = rcPtr->interp;
2847 resultPtr->done = NULL;
2848 resultPtr->result = -1;
2849 resultPtr->evPtr = evPtr;
2850
2851 /*
2852 * Now execute the forward.
2853 */
2854
2855 TclSpliceIn(resultPtr, forwardList);
2856
2857 /*
2858 * Do not unlock here. That is done by the ConditionWait.
2859 */
2860
2861 /*
2862 * Ensure cleanup of the event if the origin thread exits while this event
2863 * is pending or in progress. Exit of the destination thread is handled by
2864 * DeleteThreadReflectedChannelMap(), this is set up by
2865 * GetThreadReflectedChannelMap(). This is what we use the 'forwardList'
2866 * (see above) for.
2867 */
2868
2869 Tcl_CreateThreadExitHandler(SrcExitProc, evPtr);
2870
2871 /*
2872 * Queue the event and poke the other thread's notifier.
2873 */
2874
2875 Tcl_ThreadQueueEvent(dst, (Tcl_Event *) evPtr, TCL_QUEUE_TAIL);
2876 Tcl_ThreadAlert(dst);
2877
2878 /*
2879 * (*) Block until the handler thread has either processed the transfer or
2880 * rejected it.
2881 */
2882
2883 while (resultPtr->result < 0) {
2884 /*
2885 * NOTE (1): Is it possible that the current thread goes away while
2886 * waiting here? IOW Is it possible that "SrcExitProc" is called while
2887 * we are here? See complementary note (2) in "SrcExitProc"
2888 *
2889 * The ConditionWait unlocks the mutex during the wait and relocks it
2890 * immediately after.
2891 */
2892
2893 Tcl_ConditionWait(&resultPtr->done, &rcForwardMutex, NULL);
2894 }
2895
2896 /*
2897 * Unlink result from the forwarder list. No need to lock. Either still
2898 * locked, or locked by the ConditionWait
2899 */
2900
2901 TclSpliceOut(resultPtr, forwardList);
2902
2903 resultPtr->nextPtr = NULL;
2904 resultPtr->prevPtr = NULL;
2905
2906 Tcl_MutexUnlock(&rcForwardMutex);
2907 Tcl_ConditionFinalize(&resultPtr->done);
2908
2909 /*
2910 * Kill the cleanup handler now, and the result structure as well, before
2911 * returning the success code.
2912 *
2913 * Note: The event structure has already been deleted.
2914 */
2915
2916 Tcl_DeleteThreadExitHandler(SrcExitProc, evPtr);
2917
2918 ckfree(resultPtr);
2919 }
2920
2921 static int
2922 ForwardProc(
2923 Tcl_Event *evGPtr,
2924 int mask)
2925 {
2926 /*
2927 * HANDLER thread.
2928
2929 * The receiver part for the operations coming from the OWNER thread.
2930 * See ForwardOpToHandlerThread() for the transmitter.
2931 *
2932 * Notes regarding access to the referenced data.
2933 *
2934 * In principle the data belongs to the originating thread (see
2935 * evPtr->src), however this thread is currently blocked at (*), i.e.,
2936 * quiescent. Because of this we can treat the data as belonging to us,
2937 * without fear of race conditions. I.e. we can read and write as we like.
2938 *
2939 * The only thing we cannot be sure of is the resultPtr. This can be be
2940 * NULLed if the originating thread went away while the event is handled
2941 * here now.
2942 */
2943
2944 ForwardingEvent *evPtr = (ForwardingEvent *) evGPtr;
2945 ForwardingResult *resultPtr = evPtr->resultPtr;
2946 ReflectedChannel *rcPtr = evPtr->rcPtr;
2947 Tcl_Interp *interp = rcPtr->interp;
2948 ForwardParam *paramPtr = evPtr->param;
2949 Tcl_Obj *resObj = NULL; /* Interp result of InvokeTclMethod */
2950 ReflectedChannelMap *rcmPtr;/* Map of reflected channels with handlers in
2951 * this interp. */
2952 Tcl_HashEntry *hPtr; /* Entry in the above map */
2953 (void)mask;
2954
2955 /*
2956 * Ignore the event if no one is waiting for its result anymore.
2957 */
2958
2959 if (!resultPtr) {
2960 return 1;
2961 }
2962
2963 paramPtr->base.code = TCL_OK;
2964 paramPtr->base.msgStr = NULL;
2965 paramPtr->base.mustFree = 0;
2966
2967 switch (evPtr->op) {
2968 /*
2969 * The destination thread for the following operations is
2970 * rcPtr->thread, which contains rcPtr->interp, the interp we have to
2971 * call upon for the driver.
2972 */
2973
2974 case ForwardedClose: {
2975 /*
2976 * No parameters/results.
2977 */
2978
2979 if (InvokeTclMethod(rcPtr, METH_FINAL, NULL, NULL, &resObj)!=TCL_OK) {
2980 ForwardSetObjError(paramPtr, resObj);
2981 }
2982
2983 /*
2984 * Freeing is done here, in the origin thread, callback command
2985 * objects belong to this thread. Deallocating them in a different
2986 * thread is not allowed
2987 *
2988 * We remove the channel from both interpreter and thread maps before
2989 * releasing the memory, to prevent future accesses (like by
2990 * 'postevent') from finding and dereferencing a dangling pointer.
2991 */
2992
2993 rcmPtr = GetReflectedChannelMap(interp);
2994 hPtr = Tcl_FindHashEntry(&rcmPtr->map,
2995 Tcl_GetChannelName(rcPtr->chan));
2996 Tcl_DeleteHashEntry(hPtr);
2997
2998 rcmPtr = GetThreadReflectedChannelMap();
2999 hPtr = Tcl_FindHashEntry(&rcmPtr->map,
3000 Tcl_GetChannelName(rcPtr->chan));
3001 Tcl_DeleteHashEntry(hPtr);
3002 MarkDead(rcPtr);
3003 break;
3004 }
3005
3006 case ForwardedInput: {
3007 Tcl_Obj *toReadObj;
3008
3009 TclNewIntObj(toReadObj, paramPtr->input.toRead);
3010 Tcl_IncrRefCount(toReadObj);
3011
3012 Tcl_Preserve(rcPtr);
3013 if (InvokeTclMethod(rcPtr, METH_READ, toReadObj, NULL, &resObj)!=TCL_OK){
3014 int code = ErrnoReturn(rcPtr, resObj);
3015
3016 if (code < 0) {
3017 paramPtr->base.code = code;
3018 } else {
3019 ForwardSetObjError(paramPtr, resObj);
3020 }
3021 paramPtr->input.toRead = -1;
3022 } else {
3023 /*
3024 * Process a regular result.
3025 */
3026
3027 int bytec; /* Number of returned bytes */
3028 unsigned char *bytev; /* Array of returned bytes */
3029
3030 bytev = Tcl_GetByteArrayFromObj(resObj, &bytec);
3031
3032 if (paramPtr->input.toRead < bytec) {
3033 ForwardSetStaticError(paramPtr, msg_read_toomuch);
3034 paramPtr->input.toRead = -1;
3035 } else {
3036 if (bytec > 0) {
3037 memcpy(paramPtr->input.buf, bytev, bytec);
3038 }
3039 paramPtr->input.toRead = bytec;
3040 }
3041 }
3042 Tcl_Release(rcPtr);
3043 Tcl_DecrRefCount(toReadObj);
3044 break;
3045 }
3046
3047 case ForwardedOutput: {
3048 Tcl_Obj *bufObj = Tcl_NewByteArrayObj((unsigned char *)
3049 paramPtr->output.buf, paramPtr->output.toWrite);
3050 Tcl_IncrRefCount(bufObj);
3051
3052 Tcl_Preserve(rcPtr);
3053 if (InvokeTclMethod(rcPtr, METH_WRITE, bufObj, NULL, &resObj) != TCL_OK) {
3054 int code = ErrnoReturn(rcPtr, resObj);
3055
3056 if (code < 0) {
3057 paramPtr->base.code = code;
3058 } else {
3059 ForwardSetObjError(paramPtr, resObj);
3060 }
3061 paramPtr->output.toWrite = -1;
3062 } else {
3063 /*
3064 * Process a regular result.
3065 */
3066
3067 int written;
3068
3069 if (Tcl_GetIntFromObj(interp, resObj, &written) != TCL_OK) {
3070 Tcl_DecrRefCount(resObj);
3071 resObj = MarshallError(interp);
3072 ForwardSetObjError(paramPtr, resObj);
3073 paramPtr->output.toWrite = -1;
3074 } else if (written==0 || paramPtr->output.toWrite<written) {
3075 ForwardSetStaticError(paramPtr, msg_write_toomuch);
3076 paramPtr->output.toWrite = -1;
3077 } else {
3078 paramPtr->output.toWrite = written;
3079 }
3080 }
3081 Tcl_Release(rcPtr);
3082 Tcl_DecrRefCount(bufObj);
3083 break;
3084 }
3085
3086 case ForwardedSeek: {
3087 Tcl_Obj *offObj;
3088 Tcl_Obj *baseObj;
3089
3090 offObj = Tcl_NewWideIntObj(paramPtr->seek.offset);
3091 baseObj = Tcl_NewStringObj(
3092 (paramPtr->seek.seekMode==SEEK_SET) ? "start" :
3093 (paramPtr->seek.seekMode==SEEK_CUR) ? "current" : "end", -1);
3094
3095 Tcl_IncrRefCount(offObj);
3096 Tcl_IncrRefCount(baseObj);
3097
3098 Tcl_Preserve(rcPtr);
3099 if (InvokeTclMethod(rcPtr, METH_SEEK, offObj, baseObj, &resObj)!=TCL_OK){
3100 ForwardSetObjError(paramPtr, resObj);
3101 paramPtr->seek.offset = -1;
3102 } else {
3103 /*
3104 * Process a regular result. If the type is wrong this may change
3105 * into an error.
3106 */
3107
3108 Tcl_WideInt newLoc;
3109
3110 if (TclGetWideIntFromObj(interp, resObj, &newLoc) == TCL_OK) {
3111 if (newLoc < 0) {
3112 ForwardSetStaticError(paramPtr, msg_seek_beforestart);
3113 paramPtr->seek.offset = -1;
3114 } else {
3115 paramPtr->seek.offset = newLoc;
3116 }
3117 } else {
3118 Tcl_DecrRefCount(resObj);
3119 resObj = MarshallError(interp);
3120 ForwardSetObjError(paramPtr, resObj);
3121 paramPtr->seek.offset = -1;
3122 }
3123 }
3124 Tcl_Release(rcPtr);
3125 Tcl_DecrRefCount(offObj);
3126 Tcl_DecrRefCount(baseObj);
3127 break;
3128 }
3129
3130 case ForwardedWatch: {
3131 Tcl_Obj *maskObj = DecodeEventMask(paramPtr->watch.mask);
3132 /* assert maskObj.refCount == 1 */
3133
3134 Tcl_Preserve(rcPtr);
3135 rcPtr->interest = paramPtr->watch.mask;
3136 (void) InvokeTclMethod(rcPtr, METH_WATCH, maskObj, NULL, NULL);
3137 Tcl_DecrRefCount(maskObj);
3138 Tcl_Release(rcPtr);
3139 break;
3140 }
3141
3142 case ForwardedBlock: {
3143 Tcl_Obj *blockObj = Tcl_NewBooleanObj(!paramPtr->block.nonblocking);
3144
3145 Tcl_IncrRefCount(blockObj);
3146 Tcl_Preserve(rcPtr);
3147 if (InvokeTclMethod(rcPtr, METH_BLOCKING, blockObj, NULL,
3148 &resObj) != TCL_OK) {
3149 ForwardSetObjError(paramPtr, resObj);
3150 }
3151 Tcl_Release(rcPtr);
3152 Tcl_DecrRefCount(blockObj);
3153 break;
3154 }
3155
3156 case ForwardedSetOpt: {
3157 Tcl_Obj *optionObj = Tcl_NewStringObj(paramPtr->setOpt.name, -1);
3158 Tcl_Obj *valueObj = Tcl_NewStringObj(paramPtr->setOpt.value, -1);
3159
3160 Tcl_IncrRefCount(optionObj);
3161 Tcl_IncrRefCount(valueObj);
3162 Tcl_Preserve(rcPtr);
3163 if (InvokeTclMethod(rcPtr, METH_CONFIGURE, optionObj, valueObj,
3164 &resObj) != TCL_OK) {
3165 ForwardSetObjError(paramPtr, resObj);
3166 }
3167 Tcl_Release(rcPtr);
3168 Tcl_DecrRefCount(optionObj);
3169 Tcl_DecrRefCount(valueObj);
3170 break;
3171 }
3172
3173 case ForwardedGetOpt: {
3174 /*
3175 * Retrieve the value of one option.
3176 */
3177
3178 Tcl_Obj *optionObj = Tcl_NewStringObj(paramPtr->getOpt.name, -1);
3179
3180 Tcl_IncrRefCount(optionObj);
3181 Tcl_Preserve(rcPtr);
3182 if (InvokeTclMethod(rcPtr, METH_CGET, optionObj, NULL, &resObj)!=TCL_OK){
3183 ForwardSetObjError(paramPtr, resObj);
3184 } else {
3185 TclDStringAppendObj(paramPtr->getOpt.value, resObj);
3186 }
3187 Tcl_Release(rcPtr);
3188 Tcl_DecrRefCount(optionObj);
3189 break;
3190 }
3191
3192 case ForwardedGetOptAll:
3193 /*
3194 * Retrieve all options.
3195 */
3196
3197 Tcl_Preserve(rcPtr);
3198 if (InvokeTclMethod(rcPtr, METH_CGETALL, NULL, NULL, &resObj) != TCL_OK){
3199 ForwardSetObjError(paramPtr, resObj);
3200 } else {
3201 /*
3202 * Extract list, validate that it is a list, and #elements. See
3203 * NOTE (4) as well.
3204 */
3205
3206 int listc;
3207 Tcl_Obj **listv;
3208
3209 if (TclListObjGetElements(interp, resObj, &listc,
3210 &listv) != TCL_OK) {
3211 Tcl_DecrRefCount(resObj);
3212 resObj = MarshallError(interp);
3213 ForwardSetObjError(paramPtr, resObj);
3214 } else if ((listc % 2) == 1) {
3215 /*
3216 * Odd number of elements is wrong. [x].
3217 */
3218
3219 char *buf = (char *)ckalloc(200);
3220 snprintf(buf, 200,
3221 "{Expected list with even number of elements, got %d %s instead}",
3222 listc, (listc == 1 ? "element" : "elements"));
3223
3224 ForwardSetDynamicError(paramPtr, buf);
3225 } else {
3226 int len;
3227 const char *str = TclGetStringFromObj(resObj, &len);
3228
3229 if (len) {
3230 TclDStringAppendLiteral(paramPtr->getOpt.value, " ");
3231 Tcl_DStringAppend(paramPtr->getOpt.value, str, len);
3232 }
3233 }
3234 }
3235 Tcl_Release(rcPtr);
3236 break;
3237
3238 default:
3239 /*
3240 * Bad operation code.
3241 */
3242
3243 Tcl_Panic("Bad operation code in ForwardProc");
3244 break;
3245 }
3246
3247 /*
3248 * Remove the reference we held on the result of the invoke, if we had
3249 * such.
3250 */
3251
3252 if (resObj != NULL) {
3253 Tcl_DecrRefCount(resObj);
3254 }
3255
3256 if (resultPtr) {
3257 /*
3258 * Report the forwarding result synchronously to the waiting caller.
3259 * This unblocks (*) as well. This is wrapped into a conditional
3260 * because the caller may have exited in the mean time.
3261 */
3262
3263 Tcl_MutexLock(&rcForwardMutex);
3264 resultPtr->result = TCL_OK;
3265 Tcl_ConditionNotify(&resultPtr->done);
3266 Tcl_MutexUnlock(&rcForwardMutex);
3267 }
3268
3269 return 1;
3270 }
3271
3272 static void
3273 SrcExitProc(
3274 void *clientData)
3275 {
3276 ForwardingEvent *evPtr = (ForwardingEvent *)clientData;
3277 ForwardingResult *resultPtr;
3278 ForwardParam *paramPtr;
3279
3280 /*
3281 * NOTE (2): Can this handler be called with the originator blocked?
3282 */
3283
3284 /*
3285 * The originator for the event exited. It is not sure if this can happen,
3286 * as the originator should be blocked at (*) while the event is in
3287 * transit/pending.
3288 *
3289 * We make sure that the event cannot refer to the result anymore, remove
3290 * it from the list of pending results and free the structure. Locking the
3291 * access ensures that we cannot get in conflict with "ForwardProc",
3292 * should it already execute the event.
3293 */
3294
3295 Tcl_MutexLock(&rcForwardMutex);
3296
3297 resultPtr = evPtr->resultPtr;
3298 paramPtr = evPtr->param;
3299
3300 evPtr->resultPtr = NULL;
3301 resultPtr->evPtr = NULL;
3302 resultPtr->result = TCL_ERROR;
3303
3304 ForwardSetStaticError(paramPtr, msg_send_originlost);
3305
3306 /*
3307 * See below: TclSpliceOut(resultPtr, forwardList);
3308 */
3309
3310 Tcl_MutexUnlock(&rcForwardMutex);
3311
3312 /*
3313 * This unlocks (*). The structure will be spliced out and freed by
3314 * "ForwardProc". Maybe.
3315 */
3316
3317 Tcl_ConditionNotify(&resultPtr->done);
3318 }
3319
3320 static void
3321 ForwardSetObjError(
3322 ForwardParam *paramPtr,
3323 Tcl_Obj *obj)
3324 {
3325 int len;
3326 const char *msgStr = TclGetStringFromObj(obj, &len);
3327
3328 len++;
3329 ForwardSetDynamicError(paramPtr, ckalloc(len));
3330 memcpy(paramPtr->base.msgStr, msgStr, len);
3331 }
3332 #endif
3333
3334 /*
3335 * Local Variables:
3336 * mode: c
3337 * c-basic-offset: 4
3338 * fill-column: 78
3339 * tab-width: 8
3340 * indent-tabs-mode: nil
3341 * End:
3342 */