Debian Codegraph @

generic/tclIORTrans.c

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