Debian Codegraph @

pTk/mTk/tclGeneric/tclEvent.c

raw symbols SCIP
1 /*
2 * tclEvent.c --
3 *
4 * This file implements some general event related interfaces including
5 * background errors, exit handlers, and the "vwait" and "update"
6 * command procedures.
7 *
8 * Copyright (c) 1990-1994 The Regents of the University of California.
9 * Copyright (c) 1994-1998 Sun Microsystems, Inc.
10 *
11 * See the file "license.terms" for information on usage and redistribution
12 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
13 *
14 * RCS: @(#) $Id: tclEvent.c,v 1.28.2.1 2003/05/13 12:44:07 dkf Exp $
15 */
16 #include "tkPort.h"
17 #include "tkInt.h"
18 #include "Lang.h"
19
20 /*
21 * The data structure below is used to report background errors. One
22 * such structure is allocated for each error; it holds information
23 * about the interpreter and the error until bgerror can be invoked
24 * later as an idle handler.
25 */
26
27 typedef struct BgError {
28 Tcl_Interp *interp; /* Interpreter in which error occurred. NULL
29 * means this error report has been cancelled
30 * (a previous report generated a break). */
31 char *errorMsg; /* Copy of the error message (the interp's
32 * result when the error occurred).
33 * Malloc-ed. */
34 char *errorInfo; /* Value of the errorInfo variable
35 * (malloc-ed). */
36 char *errorCode; /* Value of the errorCode variable
37 * (malloc-ed). */
38 struct BgError *nextPtr; /* Next in list of all pending error
39 * reports for this interpreter, or NULL
40 * for end of list. */
41 } BgError;
42
43 /*
44 * One of the structures below is associated with the "tclBgError"
45 * assoc data for each interpreter. It keeps track of the head and
46 * tail of the list of pending background errors for the interpreter.
47 */
48
49 typedef struct ErrAssocData {
50 BgError *firstBgPtr; /* First in list of all background errors
51 * waiting to be processed for this
52 * interpreter (NULL if none). */
53 BgError *lastBgPtr; /* Last in list of all background errors
54 * waiting to be processed for this
55 * interpreter (NULL if none). */
56 } ErrAssocData;
57
58 /*
59 * For each exit handler created with a call to Tcl_CreateExitHandler
60 * there is a structure of the following type:
61 */
62
63 typedef struct ExitHandler {
64 Tcl_ExitProc *proc; /* Procedure to call when process exits. */
65 ClientData clientData; /* One word of information to pass to proc. */
66 struct ExitHandler *nextPtr;/* Next in list of all exit handlers for
67 * this application, or NULL for end of list. */
68 } ExitHandler;
69
70 #ifdef TCL_EVENT_IMPLEMENT
71 /*
72 * There is both per-process and per-thread exit handlers.
73 * The first list is controlled by a mutex. The other is in
74 * thread local storage.
75 */
76
77 static ExitHandler *firstExitPtr = NULL;
78 /* First in list of all exit handlers for
79 * application. */
80 TCL_DECLARE_MUTEX(exitMutex)
81
82 /*
83 * This variable is set to 1 when Tcl_Finalize is called, and at the end of
84 * its work, it is reset to 0. The variable is checked by TclInExit() to
85 * allow different behavior for exit-time processing, e.g. in closing of
86 * files and pipes.
87 */
88
89 static int inFinalize = 0;
90 static int subsystemsInitialized = 0;
91
92 typedef struct ThreadSpecificData {
93 ExitHandler *firstExitPtr; /* First in list of all exit handlers for
94 * this thread. */
95 int inExit; /* True when this thread is exiting. This
96 * is used as a hack to decide to close
97 * the standard channels. */
98 Tcl_Obj *tclLibraryPath; /* Path(s) to the Tcl library */
99 } ThreadSpecificData;
100 static Tcl_ThreadDataKey dataKey;
101
102 /*
103 * Common string for the library path for sharing across threads.
104 */
105 char *tclLibraryPathStr;
106
107 /*
108 * Prototypes for procedures referenced only in this file:
109 */
110
111 static void BgErrorDeleteProc _ANSI_ARGS_((ClientData clientData,
112 Tcl_Interp *interp));
113 static void HandleBgErrors _ANSI_ARGS_((ClientData clientData));
114 #else
115 static char * VwaitVarProc _ANSI_ARGS_((ClientData clientData,
116 Tcl_Interp *interp, Var name1, CONST char *name2,
117 int flags));
118
119 #endif
120 #ifdef TCL_EVENT_IMPLEMENT
121
122
123 #if 0
124 /*
125 *----------------------------------------------------------------------
126 *
127 * Tcl_BackgroundError --
128 *
129 * This procedure is invoked to handle errors that occur in Tcl
130 * commands that are invoked in "background" (e.g. from event or
131 * timer bindings).
132 *
133 * Results:
134 * None.
135 *
136 * Side effects:
137 * The command "bgerror" is invoked later as an idle handler to
138 * process the error, passing it the error message. If that fails,
139 * then an error message is output on stderr.
140 *
141 *----------------------------------------------------------------------
142 */
143
144 void
145 Tcl_BackgroundError(interp)
146 Tcl_Interp *interp; /* Interpreter in which an error has
147 * occurred. */
148 {
149 BgError *errPtr;
150 CONST char *errResult, *varValue;
151 ErrAssocData *assocPtr;
152 int length;
153
154 /*
155 * The Tcl_AddErrorInfo call below (with an empty string) ensures that
156 * errorInfo gets properly set. It's needed in cases where the error
157 * came from a utility procedure like Tcl_GetVar instead of Tcl_Eval;
158 * in these cases errorInfo still won't have been set when this
159 * procedure is called.
160 */
161
162 Tcl_AddErrorInfo(interp, "");
163
164 errResult = Tcl_GetStringFromObj(Tcl_GetObjResult(interp), &length);
165
166 errPtr = (BgError *) ckalloc(sizeof(BgError));
167 errPtr->interp = interp;
168 errPtr->errorMsg = (char *) ckalloc((unsigned) (length + 1));
169 memcpy(errPtr->errorMsg, errResult, (size_t) (length + 1));
170 varValue = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
171 if (varValue == NULL) {
172 varValue = errPtr->errorMsg;
173 }
174 errPtr->errorInfo = (char *) ckalloc((unsigned) (strlen(varValue) + 1));
175 strcpy(errPtr->errorInfo, varValue);
176 varValue = Tcl_GetVar(interp, "errorCode", TCL_GLOBAL_ONLY);
177 if (varValue == NULL) {
178 varValue = "";
179 }
180 errPtr->errorCode = (char *) ckalloc((unsigned) (strlen(varValue) + 1));
181 strcpy(errPtr->errorCode, varValue);
182 errPtr->nextPtr = NULL;
183
184 assocPtr = (ErrAssocData *) Tcl_GetAssocData(interp, "tclBgError",
185 (Tcl_InterpDeleteProc **) NULL);
186 if (assocPtr == NULL) {
187
188 /*
189 * This is the first time a background error has occurred in
190 * this interpreter. Create associated data to keep track of
191 * pending error reports.
192 */
193
194 assocPtr = (ErrAssocData *) ckalloc(sizeof(ErrAssocData));
195 assocPtr->firstBgPtr = NULL;
196 assocPtr->lastBgPtr = NULL;
197 Tcl_SetAssocData(interp, "tclBgError", BgErrorDeleteProc,
198 (ClientData) assocPtr);
199 }
200 if (assocPtr->firstBgPtr == NULL) {
201 assocPtr->firstBgPtr = errPtr;
202 Tcl_DoWhenIdle(HandleBgErrors, (ClientData) assocPtr);
203 } else {
204 assocPtr->lastBgPtr->nextPtr = errPtr;
205 }
206 assocPtr->lastBgPtr = errPtr;
207 Tcl_ResetResult(interp);
208 }
209
210 /*
211 *----------------------------------------------------------------------
212 *
213 * HandleBgErrors --
214 *
215 * This procedure is invoked as an idle handler to process all of
216 * the accumulated background errors.
217 *
218 * Results:
219 * None.
220 *
221 * Side effects:
222 * Depends on what actions "bgerror" takes for the errors.
223 *
224 *----------------------------------------------------------------------
225 */
226
227 static void
228 HandleBgErrors(clientData)
229 ClientData clientData; /* Pointer to ErrAssocData structure. */
230 {
231 Tcl_Interp *interp;
232 CONST char *argv[2];
233 int code;
234 BgError *errPtr;
235 ErrAssocData *assocPtr = (ErrAssocData *) clientData;
236 Tcl_Channel errChannel;
237
238 Tcl_Preserve((ClientData) assocPtr);
239
240 while (assocPtr->firstBgPtr != NULL) {
241 interp = assocPtr->firstBgPtr->interp;
242 if (interp == NULL) {
243 goto doneWithInterp;
244 }
245
246 /*
247 * Restore important state variables to what they were at
248 * the time the error occurred.
249 */
250
251 Tcl_SetVar(interp, "errorInfo", assocPtr->firstBgPtr->errorInfo,
252 TCL_GLOBAL_ONLY);
253 Tcl_SetVar(interp, "errorCode", assocPtr->firstBgPtr->errorCode,
254 TCL_GLOBAL_ONLY);
255
256 /*
257 * Create and invoke the bgerror command.
258 */
259
260 argv[0] = "bgerror";
261 argv[1] = assocPtr->firstBgPtr->errorMsg;
262
263 Tcl_AllowExceptions(interp);
264 Tcl_Preserve((ClientData) interp);
265 code = TclGlobalInvoke(interp, 2, argv, 0);
266 if (code == TCL_ERROR) {
267
268 /*
269 * If the interpreter is safe, we look for a hidden command
270 * named "bgerror" and call that with the error information.
271 * Otherwise, simply ignore the error. The rationale is that
272 * this could be an error caused by a malicious applet trying
273 * to cause an infinite barrage of error messages. The hidden
274 * "bgerror" command can be used by a security policy to
275 * interpose on such attacks and e.g. kill the applet after a
276 * few attempts.
277 */
278
279 if (Tcl_IsSafe(interp)) {
280 Tcl_SavedResult save;
281
282 Tcl_SaveResult(interp, &save);
283 TclGlobalInvoke(interp, 2, argv, TCL_INVOKE_HIDDEN);
284 Tcl_RestoreResult(interp, &save);
285
286 goto doneWithInterp;
287 }
288
289 /*
290 * We have to get the error output channel at the latest possible
291 * time, because the eval (above) might have changed the channel.
292 */
293
294 errChannel = Tcl_GetStdChannel(TCL_STDERR);
295 if (errChannel != (Tcl_Channel) NULL) {
296 char *string;
297 int len;
298
299 string = Tcl_GetStringFromObj(Tcl_GetObjResult(interp), &len);
300 if (Tcl_FindCommand(interp, "bgerror", NULL, TCL_GLOBAL_ONLY) == NULL) {
301 Tcl_WriteChars(errChannel, assocPtr->firstBgPtr->errorInfo, -1);
302 Tcl_WriteChars(errChannel, "\n", -1);
303 } else {
304 Tcl_WriteChars(errChannel,
305 "bgerror failed to handle background error.\n",
306 -1);
307 Tcl_WriteChars(errChannel, " Original error: ", -1);
308 Tcl_WriteChars(errChannel, assocPtr->firstBgPtr->errorMsg,
309 -1);
310 Tcl_WriteChars(errChannel, "\n", -1);
311 Tcl_WriteChars(errChannel, " Error in bgerror: ", -1);
312 Tcl_WriteChars(errChannel, string, len);
313 Tcl_WriteChars(errChannel, "\n", -1);
314 }
315 Tcl_Flush(errChannel);
316 }
317 } else if (code == TCL_BREAK) {
318
319 /*
320 * Break means cancel any remaining error reports for this
321 * interpreter.
322 */
323
324 for (errPtr = assocPtr->firstBgPtr; errPtr != NULL;
325 errPtr = errPtr->nextPtr) {
326 if (errPtr->interp == interp) {
327 errPtr->interp = NULL;
328 }
329 }
330 }
331
332 /*
333 * Discard the command and the information about the error report.
334 */
335
336 doneWithInterp:
337
338 if (assocPtr->firstBgPtr) {
339 ckfree(assocPtr->firstBgPtr->errorMsg);
340 ckfree(assocPtr->firstBgPtr->errorInfo);
341 ckfree(assocPtr->firstBgPtr->errorCode);
342 errPtr = assocPtr->firstBgPtr->nextPtr;
343 ckfree((char *) assocPtr->firstBgPtr);
344 assocPtr->firstBgPtr = errPtr;
345 }
346
347 if (interp != NULL) {
348 Tcl_Release((ClientData) interp);
349 }
350 }
351 assocPtr->lastBgPtr = NULL;
352
353 Tcl_Release((ClientData) assocPtr);
354 }
355
356 /*
357 *----------------------------------------------------------------------
358 *
359 * BgErrorDeleteProc --
360 *
361 * This procedure is associated with the "tclBgError" assoc data
362 * for an interpreter; it is invoked when the interpreter is
363 * deleted in order to free the information assoicated with any
364 * pending error reports.
365 *
366 * Results:
367 * None.
368 *
369 * Side effects:
370 * Background error information is freed: if there were any
371 * pending error reports, they are cancelled.
372 *
373 *----------------------------------------------------------------------
374 */
375
376 static void
377 BgErrorDeleteProc(clientData, interp)
378 ClientData clientData; /* Pointer to ErrAssocData structure. */
379 Tcl_Interp *interp; /* Interpreter being deleted. */
380 {
381 ErrAssocData *assocPtr = (ErrAssocData *) clientData;
382 BgError *errPtr;
383
384 while (assocPtr->firstBgPtr != NULL) {
385 errPtr = assocPtr->firstBgPtr;
386 assocPtr->firstBgPtr = errPtr->nextPtr;
387 ckfree(errPtr->errorMsg);
388 ckfree(errPtr->errorInfo);
389 ckfree(errPtr->errorCode);
390 ckfree((char *) errPtr);
391 }
392 Tcl_CancelIdleCall(HandleBgErrors, (ClientData) assocPtr);
393 Tcl_EventuallyFree((ClientData) assocPtr, TCL_DYNAMIC);
394 }
395
396 #endif
397 /*
398 *----------------------------------------------------------------------
399 *
400 * Tcl_CreateExitHandler --
401 *
402 * Arrange for a given procedure to be invoked just before the
403 * application exits.
404 *
405 * Results:
406 * None.
407 *
408 * Side effects:
409 * Proc will be invoked with clientData as argument when the
410 * application exits.
411 *
412 *----------------------------------------------------------------------
413 */
414
415
416 void
417 Tcl_CreateExitHandler(proc, clientData)
418 Tcl_ExitProc *proc; /* Procedure to invoke. */
419 ClientData clientData; /* Arbitrary value to pass to proc. */
420 {
421 ExitHandler *exitPtr;
422
423 exitPtr = (ExitHandler *) ckalloc(sizeof(ExitHandler));
424 exitPtr->proc = proc;
425 exitPtr->clientData = clientData;
426 Tcl_MutexLock(&exitMutex);
427 exitPtr->nextPtr = firstExitPtr;
428 firstExitPtr = exitPtr;
429 Tcl_MutexUnlock(&exitMutex);
430 }
431
432 /*
433 *----------------------------------------------------------------------
434 *
435 * Tcl_DeleteExitHandler --
436 *
437 * This procedure cancels an existing exit handler matching proc
438 * and clientData, if such a handler exits.
439 *
440 * Results:
441 * None.
442 *
443 * Side effects:
444 * If there is an exit handler corresponding to proc and clientData
445 * then it is cancelled; if no such handler exists then nothing
446 * happens.
447 *
448 *----------------------------------------------------------------------
449 */
450
451 void
452 Tcl_DeleteExitHandler(proc, clientData)
453 Tcl_ExitProc *proc; /* Procedure that was previously registered. */
454 ClientData clientData; /* Arbitrary value to pass to proc. */
455 {
456 ExitHandler *exitPtr, *prevPtr;
457
458 Tcl_MutexLock(&exitMutex);
459 for (prevPtr = NULL, exitPtr = firstExitPtr; exitPtr != NULL;
460 prevPtr = exitPtr, exitPtr = exitPtr->nextPtr) {
461 if ((exitPtr->proc == proc)
462 && (exitPtr->clientData == clientData)) {
463 if (prevPtr == NULL) {
464 firstExitPtr = exitPtr->nextPtr;
465 } else {
466 prevPtr->nextPtr = exitPtr->nextPtr;
467 }
468 ckfree((char *) exitPtr);
469 break;
470 }
471 }
472 Tcl_MutexUnlock(&exitMutex);
473 return;
474 }
475
476 /*
477 *----------------------------------------------------------------------
478 *
479 * Tcl_CreateThreadExitHandler --
480 *
481 * Arrange for a given procedure to be invoked just before the
482 * current thread exits.
483 *
484 * Results:
485 * None.
486 *
487 * Side effects:
488 * Proc will be invoked with clientData as argument when the
489 * application exits.
490 *
491 *----------------------------------------------------------------------
492 */
493
494 void
495 Tcl_CreateThreadExitHandler(proc, clientData)
496 Tcl_ExitProc *proc; /* Procedure to invoke. */
497 ClientData clientData; /* Arbitrary value to pass to proc. */
498 {
499 ExitHandler *exitPtr;
500 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
501
502 exitPtr = (ExitHandler *) ckalloc(sizeof(ExitHandler));
503 exitPtr->proc = proc;
504 exitPtr->clientData = clientData;
505 exitPtr->nextPtr = tsdPtr->firstExitPtr;
506 tsdPtr->firstExitPtr = exitPtr;
507 }
508
509 /*
510 *----------------------------------------------------------------------
511 *
512 * Tcl_DeleteThreadExitHandler --
513 *
514 * This procedure cancels an existing exit handler matching proc
515 * and clientData, if such a handler exits.
516 *
517 * Results:
518 * None.
519 *
520 * Side effects:
521 * If there is an exit handler corresponding to proc and clientData
522 * then it is cancelled; if no such handler exists then nothing
523 * happens.
524 *
525 *----------------------------------------------------------------------
526 */
527
528 void
529 Tcl_DeleteThreadExitHandler(proc, clientData)
530 Tcl_ExitProc *proc; /* Procedure that was previously registered. */
531 ClientData clientData; /* Arbitrary value to pass to proc. */
532 {
533 ExitHandler *exitPtr, *prevPtr;
534 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
535
536 for (prevPtr = NULL, exitPtr = tsdPtr->firstExitPtr; exitPtr != NULL;
537 prevPtr = exitPtr, exitPtr = exitPtr->nextPtr) {
538 if ((exitPtr->proc == proc)
539 && (exitPtr->clientData == clientData)) {
540 if (prevPtr == NULL) {
541 tsdPtr->firstExitPtr = exitPtr->nextPtr;
542 } else {
543 prevPtr->nextPtr = exitPtr->nextPtr;
544 }
545 ckfree((char *) exitPtr);
546 return;
547 }
548 }
549 }
550
551 /*
552 *----------------------------------------------------------------------
553 *
554 * Tcl_Exit --
555 *
556 * This procedure is called to terminate the application.
557 *
558 * Results:
559 * None.
560 *
561 * Side effects:
562 * All existing exit handlers are invoked, then the application
563 * ends.
564 *
565 *----------------------------------------------------------------------
566 */
567
568 void
569 Tcl_Exit(status)
570 int status; /* Exit status for application; typically
571 * 0 for normal return, 1 for error return. */
572 {
573 Tcl_Finalize();
574 TclpExit(status);
575 }
576
577 /*
578 *-------------------------------------------------------------------------
579 *
580 * TclSetLibraryPath --
581 *
582 * Set the path that will be used for searching for init.tcl and
583 * encodings when an interp is being created.
584 *
585 * Results:
586 * None.
587 *
588 * Side effects:
589 * Changing the library path will affect what directories are
590 * examined when looking for encodings for all interps from that
591 * point forward.
592 *
593 * The refcount of the new library path is incremented and the
594 * refcount of the old path is decremented.
595 *
596 *-------------------------------------------------------------------------
597 */
598
599 #ifndef _LANG
600 void
601 TclSetLibraryPath(pathPtr)
602 Tcl_Obj *pathPtr; /* A Tcl list object whose elements are
603 * the new library path. */
604 {
605 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
606
607 if (pathPtr != NULL) {
608 Tcl_IncrRefCount(pathPtr);
609 }
610 if (tsdPtr->tclLibraryPath != NULL) {
611 Tcl_DecrRefCount(tsdPtr->tclLibraryPath);
612 }
613 tsdPtr->tclLibraryPath = pathPtr;
614
615 /*
616 * No mutex locking is needed here as up the stack we're within
617 * TclpInitLock().
618 */
619 tclLibraryPathStr = Tcl_GetStringFromObj(pathPtr, NULL);
620 }
621
622 #endif
623 /*
624 *-------------------------------------------------------------------------
625 *
626 * TclGetLibraryPath --
627 *
628 * Return a Tcl list object whose elements are the library path.
629 * The caller should not modify the contents of the returned object.
630 *
631 * Results:
632 * As above.
633 *
634 * Side effects:
635 * None.
636 *
637 *-------------------------------------------------------------------------
638 */
639
640 #ifndef _LANG
641 Tcl_Obj *
642 TclGetLibraryPath()
643 {
644 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
645
646 if (tsdPtr->tclLibraryPath == NULL) {
647 /*
648 * Grab the shared string and place it into a new thread specific
649 * Tcl_Obj.
650 */
651 tsdPtr->tclLibraryPath = Tcl_NewStringObj(tclLibraryPathStr, -1);
652
653 /* take ownership */
654 Tcl_IncrRefCount(tsdPtr->tclLibraryPath);
655 }
656 return tsdPtr->tclLibraryPath;
657 }
658
659 #endif
660 /*
661 *-------------------------------------------------------------------------
662 *
663 * TclInitSubsystems --
664 *
665 * Initialize various subsytems in Tcl. This should be called the
666 * first time an interp is created, or before any of the subsystems
667 * are used. This function ensures an order for the initialization
668 * of subsystems:
669 *
670 * 1. that cannot be initialized in lazy order because they are
671 * mutually dependent.
672 *
673 * 2. so that they can be finalized in a known order w/o causing
674 * the subsequent re-initialization of a subsystem in the act of
675 * shutting down another.
676 *
677 * Results:
678 * None.
679 *
680 * Side effects:
681 * Varied, see the respective initialization routines.
682 *
683 *-------------------------------------------------------------------------
684 */
685
686 void
687 TclInitSubsystems(argv0)
688 CONST char *argv0; /* Name of executable from argv[0] to main()
689 * in native multi-byte encoding. */
690 {
691 ThreadSpecificData *tsdPtr;
692
693
694 if (inFinalize != 0) {
695 panic("TclInitSubsystems called while finalizing");
696 }
697
698 /*
699 * Grab the thread local storage pointer before doing anything because
700 * the initialization routines will be registering exit handlers.
701 * We use this pointer to detect if this is the first time this
702 * thread has created an interpreter.
703 */
704
705 tsdPtr = (ThreadSpecificData *) TclThreadDataKeyGet(&dataKey);
706
707 if (subsystemsInitialized == 0) {
708 /*
709 * Double check inside the mutex. There are definitly calls
710 * back into this routine from some of the procedures below.
711 */
712
713 TclpInitLock();
714 if (subsystemsInitialized == 0) {
715 /*
716 * Have to set this bit here to avoid deadlock with the
717 * routines below us that call into TclInitSubsystems.
718 */
719
720 subsystemsInitialized = 1;
721
722 #ifndef _LANG
723 tclExecutableName = NULL;
724
725 /*
726 * Initialize locks used by the memory allocators before anything
727 * interesting happens so we can use the allocators in the
728 * implementation of self-initializing locks.
729 */
730 #if USE_TCLALLOC
731 TclInitAlloc(); /* process wide mutex init */
732 #endif
733 #ifdef TCL_MEM_DEBUG
734 TclInitDbCkalloc(); /* process wide mutex init */
735 #endif
736
737 #endif
738 TclpInitPlatform(); /* creates signal handler(s) */
739 TclInitObjSubsystem(); /* register obj types, create mutexes */
740 TclInitIOSubsystem(); /* inits a tsd key (noop) */
741 #ifndef _LANG
742 TclInitEncodingSubsystem(); /* process wide encoding init */
743 TclInitNamespaceSubsystem(); /* register ns obj type (mutexed) */
744 #endif
745 }
746 TclpInitUnlock();
747 }
748
749 if (tsdPtr == NULL) {
750 /*
751 * First time this thread has created an interpreter.
752 * We fetch the key again just in case no exit handlers were
753 * registered by this point.
754 */
755
756 (void) TCL_TSD_INIT(&dataKey);
757 TclInitNotifier();
758 }
759 }
760
761 /*
762 *----------------------------------------------------------------------
763 *
764 * Tcl_Finalize --
765 *
766 * Shut down Tcl. First calls registered exit handlers, then
767 * carefully shuts down various subsystems.
768 * Called by Tcl_Exit or when the Tcl shared library is being
769 * unloaded.
770 *
771 * Results:
772 * None.
773 *
774 * Side effects:
775 * Varied, see the respective finalization routines.
776 *
777 *----------------------------------------------------------------------
778 */
779
780 void
781 Tcl_Finalize()
782 {
783 ExitHandler *exitPtr;
784
785 TclpInitLock();
786 if (subsystemsInitialized != 0) {
787 subsystemsInitialized = 0;
788
789 /*
790 * Ensure the thread-specific data is initialised as it is
791 * used in Tcl_FinalizeThread()
792 */
793
794 (void) TCL_TSD_INIT(&dataKey);
795
796 /*
797 * Invoke exit handlers first.
798 */
799
800 Tcl_MutexLock(&exitMutex);
801 inFinalize = 1;
802 for (exitPtr = firstExitPtr; exitPtr != NULL; exitPtr = firstExitPtr) {
803 /*
804 * Be careful to remove the handler from the list before
805 * invoking its callback. This protects us against
806 * double-freeing if the callback should call
807 * Tcl_DeleteExitHandler on itself.
808 */
809
810 firstExitPtr = exitPtr->nextPtr;
811 Tcl_MutexUnlock(&exitMutex);
812 (*exitPtr->proc)(exitPtr->clientData);
813 ckfree((char *) exitPtr);
814 Tcl_MutexLock(&exitMutex);
815 }
816 firstExitPtr = NULL;
817 Tcl_MutexUnlock(&exitMutex);
818
819
820 /*
821 * Clean up after the current thread now, after exit handlers.
822 * In particular, the testexithandler command sets up something
823 * that writes to standard output, which gets closed.
824 * Note that there is no thread-local storage after this call.
825 */
826
827 Tcl_FinalizeThread();
828
829 #ifndef _LANG
830 /*
831 * Now finalize the Tcl execution environment. Note that this
832 * must be done after the exit handlers, because there are
833 * order dependencies.
834 */
835
836 TclFinalizeCompExecEnv();
837 TclFinalizeEnvironment();
838
839 /*
840 * Finalizing the filesystem must come after anything which
841 * might conceivably interact with the 'Tcl_FS' API.
842 */
843 TclFinalizeFilesystem();
844
845 /*
846 * We must be sure the encoding finalization doesn't need
847 * to examine the filesystem in any way. Since it only
848 * needs to clean up internal data structures, this is
849 * fine.
850 */
851 TclFinalizeEncodingSubsystem();
852
853 if (tclExecutableName != NULL) {
854 ckfree(tclExecutableName);
855 tclExecutableName = NULL;
856 }
857 if (tclNativeExecutableName != NULL) {
858 ckfree(tclNativeExecutableName);
859 tclNativeExecutableName = NULL;
860 }
861 if (tclDefaultEncodingDir != NULL) {
862 ckfree(tclDefaultEncodingDir);
863 tclDefaultEncodingDir = NULL;
864 }
865
866 Tcl_SetPanicProc(NULL);
867
868 /*
869 * Free synchronization objects. There really should only be one
870 * thread alive at this moment.
871 */
872
873 TclFinalizeSynchronization();
874
875 /*
876 * We defer unloading of packages until very late
877 * to avoid memory access issues. Both exit callbacks and
878 * synchronization variables may be stored in packages.
879 *
880 * Note that TclFinalizeLoad unloads packages in the reverse
881 * of the order they were loaded in (i.e. last to be loaded
882 * is the first to be unloaded). This can be important for
883 * correct unloading when dependencies exist.
884 *
885 * Once load has been finalized, we will have deleted any
886 * temporary copies of shared libraries and can therefore
887 * reset the filesystem to its original state.
888 */
889
890 TclFinalizeLoad();
891 TclResetFilesystem();
892
893 /*
894 * There shouldn't be any malloc'ed memory after this.
895 */
896
897 TclFinalizeMemorySubsystem();
898 #endif
899 inFinalize = 0;
900 }
901 TclpInitUnlock();
902 }
903
904 /*
905 *----------------------------------------------------------------------
906 *
907 * Tcl_FinalizeThread --
908 *
909 * Runs the exit handlers to allow Tcl to clean up its state
910 * about a particular thread.
911 *
912 * Results:
913 * None.
914 *
915 * Side effects:
916 * Varied, see the respective finalization routines.
917 *
918 *----------------------------------------------------------------------
919 */
920
921 void
922 Tcl_FinalizeThread()
923 {
924 #ifndef _LANG
925 ExitHandler *exitPtr;
926 ThreadSpecificData *tsdPtr =
927 (ThreadSpecificData *)TclThreadDataKeyGet(&dataKey);
928
929 if (tsdPtr != NULL) {
930 tsdPtr->inExit = 1;
931
932 /*
933 * Clean up the library path now, before we invalidate thread-local
934 * storage or calling thread exit handlers.
935 */
936
937 if (tsdPtr->tclLibraryPath != NULL) {
938 Tcl_DecrRefCount(tsdPtr->tclLibraryPath);
939 tsdPtr->tclLibraryPath = NULL;
940 }
941
942 for (exitPtr = tsdPtr->firstExitPtr; exitPtr != NULL;
943 exitPtr = tsdPtr->firstExitPtr) {
944 /*
945 * Be careful to remove the handler from the list before invoking
946 * its callback. This protects us against double-freeing if the
947 * callback should call Tcl_DeleteThreadExitHandler on itself.
948 */
949
950 tsdPtr->firstExitPtr = exitPtr->nextPtr;
951 (*exitPtr->proc)(exitPtr->clientData);
952 ckfree((char *) exitPtr);
953 }
954 TclFinalizeIOSubsystem();
955 TclFinalizeNotifier();
956 TclFinalizeAsync();
957 }
958
959 /*
960 * Blow away all thread local storage blocks.
961 *
962 * Note that Tcl API allows creation of threads which do not use any
963 * Tcl interp or other Tcl subsytems. Those threads might, however,
964 * use thread local storage, so we must unconditionally finalize it.
965 *
966 * Fix [Bug #571002]
967 */
968
969 TclFinalizeThreadData();
970 #endif
971 }
972
973 /*
974 *----------------------------------------------------------------------
975 *
976 * TclInExit --
977 *
978 * Determines if we are in the middle of exit-time cleanup.
979 *
980 * Results:
981 * If we are in the middle of exiting, 1, otherwise 0.
982 *
983 * Side effects:
984 * None.
985 *
986 *----------------------------------------------------------------------
987 */
988
989 int
990 TclInExit()
991 {
992 return inFinalize;
993 }
994
995 /*
996 *----------------------------------------------------------------------
997 *
998 * TclInThreadExit --
999 *
1000 * Determines if we are in the middle of thread exit-time cleanup.
1001 *
1002 * Results:
1003 * If we are in the middle of exiting this thread, 1, otherwise 0.
1004 *
1005 * Side effects:
1006 * None.
1007 *
1008 *----------------------------------------------------------------------
1009 */
1010
1011 int
1012 TclInThreadExit()
1013 {
1014 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
1015 TclThreadDataKeyGet(&dataKey);
1016 if (tsdPtr == NULL) {
1017 return 0;
1018 } else {
1019 return tsdPtr->inExit;
1020 }
1021 }
1022
1023 #else /* TCL_EVENT_IMPLEMENT */
1024 /*
1025 *----------------------------------------------------------------------
1026 *
1027 * Tcl_VwaitObjCmd --
1028 *
1029 * This procedure is invoked to process the "vwait" Tcl command.
1030 * See the user documentation for details on what it does.
1031 *
1032 * Results:
1033 * A standard Tcl result.
1034 *
1035 * Side effects:
1036 * See the user documentation.
1037 *
1038 *----------------------------------------------------------------------
1039 */
1040
1041 /* ARGSUSED */
1042 int
1043 Tcl_VwaitObjCmd(clientData, interp, objc, objv)
1044 ClientData clientData; /* Not used. */
1045 Tcl_Interp *interp; /* Current interpreter. */
1046 int objc; /* Number of arguments. */
1047 Tcl_Obj *CONST objv[]; /* Argument objects. */
1048 {
1049 int done, foundEvent;
1050
1051 if (objc != 2) {
1052 Tcl_WrongNumArgs(interp, 1, objv, "name");
1053 return TCL_ERROR;
1054 }
1055 if (Lang_TraceVar(interp, objv[1],
1056 TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS,
1057 VwaitVarProc, (ClientData) &done) != TCL_OK) {
1058 return TCL_ERROR;
1059 };
1060 done = 0;
1061 foundEvent = 1;
1062 while (!done && foundEvent) {
1063 foundEvent = Tcl_DoOneEvent(TCL_ALL_EVENTS);
1064 }
1065 Lang_UntraceVar(interp, objv[1],
1066 TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS,
1067 VwaitVarProc, (ClientData) &done);
1068
1069 /*
1070 * Clear out the interpreter's result, since it may have been set
1071 * by event handlers.
1072 */
1073
1074 Tcl_ResetResult(interp);
1075 if (!foundEvent) {
1076 Tcl_AppendResult(interp, "can't wait for variable \"", Tcl_GetString(objv[1]),
1077 "\": would wait forever", (char *) NULL);
1078 return TCL_ERROR;
1079 }
1080 return TCL_OK;
1081 }
1082
1083 /* ARGSUSED */
1084 static char *
1085 VwaitVarProc(clientData, interp, name1, name2, flags)
1086 ClientData clientData; /* Pointer to integer to set to 1. */
1087 Tcl_Interp *interp; /* Interpreter containing variable. */
1088 Var name1; /* Name of variable. */
1089 CONST char *name2; /* Second part of variable name. */
1090 int flags; /* Information about what happened. */
1091 {
1092 int *donePtr = (int *) clientData;
1093
1094 *donePtr = 1;
1095 return (char *) NULL;
1096 }
1097
1098 /*
1099 *----------------------------------------------------------------------
1100 *
1101 * Tcl_UpdateObjCmd --
1102 *
1103 * This procedure is invoked to process the "update" Tcl command.
1104 * See the user documentation for details on what it does.
1105 *
1106 * Results:
1107 * A standard Tcl result.
1108 *
1109 * Side effects:
1110 * See the user documentation.
1111 *
1112 *----------------------------------------------------------------------
1113 */
1114
1115 /* ARGSUSED */
1116 int
1117 Tcl_UpdateObjCmd(clientData, interp, objc, objv)
1118 ClientData clientData; /* Not used. */
1119 Tcl_Interp *interp; /* Current interpreter. */
1120 int objc; /* Number of arguments. */
1121 Tcl_Obj *CONST objv[]; /* Argument objects. */
1122 {
1123 int optionIndex;
1124 int flags = 0; /* Initialized to avoid compiler warning. */
1125 static CONST char *updateOptions[] = {"idletasks", (char *) NULL};
1126 enum updateOptions {REGEXP_IDLETASKS};
1127
1128 if (objc == 1) {
1129 flags = TCL_ALL_EVENTS|TCL_DONT_WAIT;
1130 } else if (objc == 2) {
1131 if (Tcl_GetIndexFromObj(interp, objv[1], updateOptions,
1132 "option", 0, &optionIndex) != TCL_OK) {
1133 return TCL_ERROR;
1134 }
1135 switch ((enum updateOptions) optionIndex) {
1136 case REGEXP_IDLETASKS: {
1137 flags = TCL_WINDOW_EVENTS|TCL_IDLE_EVENTS|TCL_DONT_WAIT;
1138 break;
1139 }
1140 default: {
1141 panic("Tcl_UpdateObjCmd: bad option index to UpdateOptions");
1142 }
1143 }
1144 } else {
1145 Tcl_WrongNumArgs(interp, 1, objv, "?idletasks?");
1146 return TCL_ERROR;
1147 }
1148
1149 while (Tcl_DoOneEvent(flags) != 0) {
1150 /* Empty loop body */
1151 }
1152
1153 /*
1154 * Must clear the interpreter's result because event handlers could
1155 * have executed commands.
1156 */
1157
1158 Tcl_ResetResult(interp);
1159 return TCL_OK;
1160 }
1161
1162 #endif /* TCL_EVENT_IMPLEMENT */
1163
1164
1165