Debian Codegraph @

generic/tclBasic.c

raw
1 /*
2 * tclBasic.c --
3 *
4 * Contains the basic facilities for TCL command interpretation,
5 * including interpreter creation and deletion, command creation and
6 * deletion, and command/script execution.
7 *
8 * Copyright (c) 1987-1994 The Regents of the University of California.
9 * Copyright (c) 1994-1997 Sun Microsystems, Inc.
10 * Copyright (c) 1998-1999 Scriptics Corporation.
11 * Copyright (c) 2001, 2002 Kevin B. Kenny. All rights reserved.
12 * Copyright (c) 2007 Daniel A. Steffen <[email protected]>
13 * Copyright (c) 2006-2008 Joe Mistachkin. All rights reserved.
14 * Copyright (c) 2008 Miguel Sofer <[email protected]>
15 *
16 * See the file "license.terms" for information on usage and redistribution of
17 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
18 */
19
20 #include "tclInt.h"
21 #include "tclOOInt.h"
22 #include "tclCompile.h"
23 #include "tommath.h"
24 #include <math.h>
25 #include <assert.h>
26
27 /*
28 * Bug 7371b6270b: to check C call stack depth, prefer an approach which is
29 * compatible with AddressSanitizer (ASan) use-after-return detection.
30 */
31
32 #if defined(_MSC_VER) && defined(HAVE_INTRIN_H)
33 #include <intrin.h> /* for _AddressOfReturnAddress() */
34 #endif
35
36 /*
37 * As suggested by
38 * https://clang.llvm.org/docs/LanguageExtensions.html#has-builtin
39 */
40 #ifndef __has_builtin
41 #define __has_builtin(x) 0 /* for non-clang compilers */
42 #endif
43
44 void *
45 TclGetCStackPtr(void)
46 {
47 #if defined( __GNUC__ ) || __has_builtin(__builtin_frame_address)
48 return __builtin_frame_address(0);
49 #elif defined(_MSC_VER) && defined(HAVE_INTRIN_H)
50 return _AddressOfReturnAddress();
51 #else
52 size_t unused = 0;
53 /*
54 * LLVM recommends using volatile:
55 * https://github.com/llvm/llvm-project/blob/llvmorg-10.0.0-rc1/clang/lib/Basic/Stack.cpp#L31
56 */
57 size_t *volatile stackLevel = &unused;
58 return (void *)stackLevel;
59 #endif
60 }
61
62 #define INTERP_STACK_INITIAL_SIZE 2000
63 #define CORO_STACK_INITIAL_SIZE 200
64
65 /*
66 * Determine whether we're using IEEE floating point
67 */
68
69 #if (FLT_RADIX == 2) && (DBL_MANT_DIG == 53) && (DBL_MAX_EXP == 1024)
70 # define IEEE_FLOATING_POINT
71 /* Largest odd integer that can be represented exactly in a double */
72 # define MAX_EXACT 9007199254740991.0
73 #endif
74
75 /*
76 * The following structure defines the client data for a math function
77 * registered with Tcl_CreateMathFunc
78 */
79
80 typedef struct OldMathFuncData {
81 Tcl_MathProc *proc; /* Handler function */
82 int numArgs; /* Number of args expected */
83 Tcl_ValueType *argTypes; /* Types of the args */
84 ClientData clientData; /* Client data for the handler function */
85 } OldMathFuncData;
86
87 /*
88 * This is the script cancellation struct and hash table. The hash table is
89 * used to keep track of the information necessary to process script
90 * cancellation requests, including the original interp, asynchronous handler
91 * tokens (created by Tcl_AsyncCreate), and the clientData and flags arguments
92 * passed to Tcl_CancelEval on a per-interp basis. The cancelLock mutex is
93 * used for protecting calls to Tcl_CancelEval as well as protecting access to
94 * the hash table below.
95 */
96
97 typedef struct {
98 Tcl_Interp *interp; /* Interp this struct belongs to. */
99 Tcl_AsyncHandler async; /* Async handler token for script
100 * cancellation. */
101 char *result; /* The script cancellation result or NULL for
102 * a default result. */
103 int length; /* Length of the above error message. */
104 ClientData clientData; /* Ignored */
105 int flags; /* Additional flags */
106 } CancelInfo;
107 static Tcl_HashTable cancelTable;
108 static int cancelTableInitialized = 0; /* 0 means not yet initialized. */
109 TCL_DECLARE_MUTEX(cancelLock);
110
111 /*
112 * Declarations for managing contexts for non-recursive coroutines. Contexts
113 * are used to save the evaluation state between NR calls to each coro.
114 */
115
116 #define SAVE_CONTEXT(context) \
117 (context).framePtr = iPtr->framePtr; \
118 (context).varFramePtr = iPtr->varFramePtr; \
119 (context).cmdFramePtr = iPtr->cmdFramePtr; \
120 (context).lineLABCPtr = iPtr->lineLABCPtr
121
122 #define RESTORE_CONTEXT(context) \
123 iPtr->framePtr = (context).framePtr; \
124 iPtr->varFramePtr = (context).varFramePtr; \
125 iPtr->cmdFramePtr = (context).cmdFramePtr; \
126 iPtr->lineLABCPtr = (context).lineLABCPtr
127
128 /*
129 * Static functions in this file:
130 */
131
132 static char * CallCommandTraces(Interp *iPtr, Command *cmdPtr,
133 const char *oldName, const char *newName,
134 int flags);
135 static int CancelEvalProc(ClientData clientData,
136 Tcl_Interp *interp, int code);
137 static int CheckDoubleResult(Tcl_Interp *interp, double dResult);
138 static void DeleteCoroutine(ClientData clientData);
139 static Tcl_FreeProc DeleteInterpProc;
140 static void DeleteOpCmdClientData(ClientData clientData);
141 #ifdef USE_DTRACE
142 static Tcl_ObjCmdProc DTraceObjCmd;
143 static Tcl_NRPostProc DTraceCmdReturn;
144 #else
145 # define DTraceCmdReturn NULL
146 #endif /* USE_DTRACE */
147 static Tcl_ObjCmdProc ExprAbsFunc;
148 static Tcl_ObjCmdProc ExprBinaryFunc;
149 static Tcl_ObjCmdProc ExprBoolFunc;
150 static Tcl_ObjCmdProc ExprCeilFunc;
151 static Tcl_ObjCmdProc ExprDoubleFunc;
152 static Tcl_ObjCmdProc ExprEntierFunc;
153 static Tcl_ObjCmdProc ExprFloorFunc;
154 static Tcl_ObjCmdProc ExprIntFunc;
155 static Tcl_ObjCmdProc ExprIsqrtFunc;
156 static Tcl_ObjCmdProc ExprRandFunc;
157 static Tcl_ObjCmdProc ExprRoundFunc;
158 static Tcl_ObjCmdProc ExprSqrtFunc;
159 static Tcl_ObjCmdProc ExprSrandFunc;
160 static Tcl_ObjCmdProc ExprUnaryFunc;
161 static Tcl_ObjCmdProc ExprWideFunc;
162 static void MathFuncWrongNumArgs(Tcl_Interp *interp, int expected,
163 int actual, Tcl_Obj *const *objv);
164 static Tcl_NRPostProc NRCoroutineCallerCallback;
165 static Tcl_NRPostProc NRCoroutineExitCallback;
166 static Tcl_NRPostProc NRCommand;
167
168 static Tcl_ObjCmdProc OldMathFuncProc;
169 static void OldMathFuncDeleteProc(ClientData clientData);
170 static void ProcessUnexpectedResult(Tcl_Interp *interp,
171 int returnCode);
172 static int RewindCoroutine(CoroutineData *corPtr, int result);
173 static void TEOV_SwitchVarFrame(Tcl_Interp *interp);
174 static void TEOV_PushExceptionHandlers(Tcl_Interp *interp,
175 int objc, Tcl_Obj *const objv[], int flags);
176 static inline Command * TEOV_LookupCmdFromObj(Tcl_Interp *interp,
177 Tcl_Obj *namePtr, Namespace *lookupNsPtr);
178 static int TEOV_NotFound(Tcl_Interp *interp, int objc,
179 Tcl_Obj *const objv[], Namespace *lookupNsPtr);
180 static int TEOV_RunEnterTraces(Tcl_Interp *interp,
181 Command **cmdPtrPtr, Tcl_Obj *commandPtr, int objc,
182 Tcl_Obj *const objv[]);
183 static Tcl_NRPostProc RewindCoroutineCallback;
184 static Tcl_NRPostProc TEOEx_ByteCodeCallback;
185 static Tcl_NRPostProc TEOEx_ListCallback;
186 static Tcl_NRPostProc TEOV_Error;
187 static Tcl_NRPostProc TEOV_Exception;
188 static Tcl_NRPostProc TEOV_NotFoundCallback;
189 static Tcl_NRPostProc TEOV_RestoreVarFrame;
190 static Tcl_NRPostProc TEOV_RunLeaveTraces;
191 static Tcl_NRPostProc EvalObjvCore;
192 static Tcl_NRPostProc Dispatch;
193
194 static Tcl_ObjCmdProc NRCoroInjectObjCmd;
195 static Tcl_NRPostProc NRPostInvoke;
196 static Tcl_ObjCmdProc CoroTypeObjCmd;
197
198 MODULE_SCOPE const TclStubs tclStubs;
199
200 /*
201 * Magical counts for the number of arguments accepted by a coroutine command
202 * after particular kinds of [yield].
203 */
204
205 #define CORO_ACTIVATE_YIELD PTR2INT(NULL)
206 #define CORO_ACTIVATE_YIELDM PTR2INT(NULL)+1
207
208 #define COROUTINE_ARGUMENTS_SINGLE_OPTIONAL (-1)
209 #define COROUTINE_ARGUMENTS_ARBITRARY (-2)
210
211 /*
212 * The following structure define the commands in the Tcl core.
213 */
214
215 typedef struct {
216 const char *name; /* Name of object-based command. */
217 Tcl_ObjCmdProc *objProc; /* Object-based function for command. */
218 CompileProc *compileProc; /* Function called to compile command. */
219 Tcl_ObjCmdProc *nreProc; /* NR-based function for command */
220 int flags; /* Various flag bits, as defined below. */
221 } CmdInfo;
222
223 #define CMD_IS_SAFE 1 /* Whether this command is part of the set of
224 * commands present by default in a safe
225 * interpreter. */
226 /* CMD_COMPILES_EXPANDED - Whether the compiler for this command can handle
227 * expansion for itself rather than needing the generic layer to take care of
228 * it for it. Defined in tclInt.h. */
229
230 /*
231 * The built-in commands, and the functions that implement them:
232 */
233
234 static const CmdInfo builtInCmds[] = {
235 /*
236 * Commands in the generic core.
237 */
238
239 {"append", Tcl_AppendObjCmd, TclCompileAppendCmd, NULL, CMD_IS_SAFE},
240 {"apply", Tcl_ApplyObjCmd, NULL, TclNRApplyObjCmd, CMD_IS_SAFE},
241 {"break", Tcl_BreakObjCmd, TclCompileBreakCmd, NULL, CMD_IS_SAFE},
242 #ifndef EXCLUDE_OBSOLETE_COMMANDS
243 {"case", Tcl_CaseObjCmd, NULL, NULL, CMD_IS_SAFE},
244 #endif
245 {"catch", Tcl_CatchObjCmd, TclCompileCatchCmd, TclNRCatchObjCmd, CMD_IS_SAFE},
246 {"concat", Tcl_ConcatObjCmd, TclCompileConcatCmd, NULL, CMD_IS_SAFE},
247 {"continue", Tcl_ContinueObjCmd, TclCompileContinueCmd, NULL, CMD_IS_SAFE},
248 {"coroutine", NULL, NULL, TclNRCoroutineObjCmd, CMD_IS_SAFE},
249 {"error", Tcl_ErrorObjCmd, TclCompileErrorCmd, NULL, CMD_IS_SAFE},
250 {"eval", Tcl_EvalObjCmd, NULL, TclNREvalObjCmd, CMD_IS_SAFE},
251 {"expr", Tcl_ExprObjCmd, TclCompileExprCmd, TclNRExprObjCmd, CMD_IS_SAFE},
252 {"for", Tcl_ForObjCmd, TclCompileForCmd, TclNRForObjCmd, CMD_IS_SAFE},
253 {"foreach", Tcl_ForeachObjCmd, TclCompileForeachCmd, TclNRForeachCmd, CMD_IS_SAFE},
254 {"format", Tcl_FormatObjCmd, TclCompileFormatCmd, NULL, CMD_IS_SAFE},
255 {"global", Tcl_GlobalObjCmd, TclCompileGlobalCmd, NULL, CMD_IS_SAFE},
256 {"if", Tcl_IfObjCmd, TclCompileIfCmd, TclNRIfObjCmd, CMD_IS_SAFE},
257 {"incr", Tcl_IncrObjCmd, TclCompileIncrCmd, NULL, CMD_IS_SAFE},
258 {"join", Tcl_JoinObjCmd, NULL, NULL, CMD_IS_SAFE},
259 {"lappend", Tcl_LappendObjCmd, TclCompileLappendCmd, NULL, CMD_IS_SAFE},
260 {"lassign", Tcl_LassignObjCmd, TclCompileLassignCmd, NULL, CMD_IS_SAFE},
261 {"lindex", Tcl_LindexObjCmd, TclCompileLindexCmd, NULL, CMD_IS_SAFE},
262 {"linsert", Tcl_LinsertObjCmd, TclCompileLinsertCmd, NULL, CMD_IS_SAFE},
263 {"list", Tcl_ListObjCmd, TclCompileListCmd, NULL, CMD_IS_SAFE|CMD_COMPILES_EXPANDED},
264 {"llength", Tcl_LlengthObjCmd, TclCompileLlengthCmd, NULL, CMD_IS_SAFE},
265 {"lmap", Tcl_LmapObjCmd, TclCompileLmapCmd, TclNRLmapCmd, CMD_IS_SAFE},
266 {"lrange", Tcl_LrangeObjCmd, TclCompileLrangeCmd, NULL, CMD_IS_SAFE},
267 {"lrepeat", Tcl_LrepeatObjCmd, NULL, NULL, CMD_IS_SAFE},
268 {"lreplace", Tcl_LreplaceObjCmd, TclCompileLreplaceCmd, NULL, CMD_IS_SAFE},
269 {"lreverse", Tcl_LreverseObjCmd, NULL, NULL, CMD_IS_SAFE},
270 {"lsearch", Tcl_LsearchObjCmd, NULL, NULL, CMD_IS_SAFE},
271 {"lset", Tcl_LsetObjCmd, TclCompileLsetCmd, NULL, CMD_IS_SAFE},
272 {"lsort", Tcl_LsortObjCmd, NULL, NULL, CMD_IS_SAFE},
273 {"package", Tcl_PackageObjCmd, NULL, TclNRPackageObjCmd, CMD_IS_SAFE},
274 {"proc", Tcl_ProcObjCmd, NULL, NULL, CMD_IS_SAFE},
275 {"regexp", Tcl_RegexpObjCmd, TclCompileRegexpCmd, NULL, CMD_IS_SAFE},
276 {"regsub", Tcl_RegsubObjCmd, TclCompileRegsubCmd, NULL, CMD_IS_SAFE},
277 {"rename", Tcl_RenameObjCmd, NULL, NULL, CMD_IS_SAFE},
278 {"return", Tcl_ReturnObjCmd, TclCompileReturnCmd, NULL, CMD_IS_SAFE},
279 {"scan", Tcl_ScanObjCmd, NULL, NULL, CMD_IS_SAFE},
280 {"set", Tcl_SetObjCmd, TclCompileSetCmd, NULL, CMD_IS_SAFE},
281 {"split", Tcl_SplitObjCmd, NULL, NULL, CMD_IS_SAFE},
282 {"subst", Tcl_SubstObjCmd, TclCompileSubstCmd, TclNRSubstObjCmd, CMD_IS_SAFE},
283 {"switch", Tcl_SwitchObjCmd, TclCompileSwitchCmd, TclNRSwitchObjCmd, CMD_IS_SAFE},
284 {"tailcall", NULL, TclCompileTailcallCmd, TclNRTailcallObjCmd, CMD_IS_SAFE},
285 {"throw", Tcl_ThrowObjCmd, TclCompileThrowCmd, NULL, CMD_IS_SAFE},
286 {"trace", Tcl_TraceObjCmd, NULL, NULL, CMD_IS_SAFE},
287 {"try", Tcl_TryObjCmd, TclCompileTryCmd, TclNRTryObjCmd, CMD_IS_SAFE},
288 {"unset", Tcl_UnsetObjCmd, TclCompileUnsetCmd, NULL, CMD_IS_SAFE},
289 {"uplevel", Tcl_UplevelObjCmd, NULL, TclNRUplevelObjCmd, CMD_IS_SAFE},
290 {"upvar", Tcl_UpvarObjCmd, TclCompileUpvarCmd, NULL, CMD_IS_SAFE},
291 {"variable", Tcl_VariableObjCmd, TclCompileVariableCmd, NULL, CMD_IS_SAFE},
292 {"while", Tcl_WhileObjCmd, TclCompileWhileCmd, TclNRWhileObjCmd, CMD_IS_SAFE},
293 {"yield", NULL, TclCompileYieldCmd, TclNRYieldObjCmd, CMD_IS_SAFE},
294 {"yieldto", NULL, TclCompileYieldToCmd, TclNRYieldToObjCmd, CMD_IS_SAFE},
295
296 /*
297 * Commands in the OS-interface. Note that many of these are unsafe.
298 */
299
300 {"after", Tcl_AfterObjCmd, NULL, NULL, CMD_IS_SAFE},
301 {"cd", Tcl_CdObjCmd, NULL, NULL, 0},
302 {"close", Tcl_CloseObjCmd, NULL, NULL, CMD_IS_SAFE},
303 {"eof", Tcl_EofObjCmd, NULL, NULL, CMD_IS_SAFE},
304 {"exec", Tcl_ExecObjCmd, NULL, NULL, 0},
305 {"exit", Tcl_ExitObjCmd, NULL, NULL, 0},
306 {"fblocked", Tcl_FblockedObjCmd, NULL, NULL, CMD_IS_SAFE},
307 {"fconfigure", Tcl_FconfigureObjCmd, NULL, NULL, 0},
308 {"fcopy", Tcl_FcopyObjCmd, NULL, NULL, CMD_IS_SAFE},
309 {"fileevent", Tcl_FileEventObjCmd, NULL, NULL, CMD_IS_SAFE},
310 {"flush", Tcl_FlushObjCmd, NULL, NULL, CMD_IS_SAFE},
311 {"gets", Tcl_GetsObjCmd, NULL, NULL, CMD_IS_SAFE},
312 {"glob", Tcl_GlobObjCmd, NULL, NULL, 0},
313 {"load", Tcl_LoadObjCmd, NULL, NULL, 0},
314 {"open", Tcl_OpenObjCmd, NULL, NULL, 0},
315 {"pid", Tcl_PidObjCmd, NULL, NULL, CMD_IS_SAFE},
316 {"puts", Tcl_PutsObjCmd, NULL, NULL, CMD_IS_SAFE},
317 {"pwd", Tcl_PwdObjCmd, NULL, NULL, 0},
318 {"read", Tcl_ReadObjCmd, NULL, NULL, CMD_IS_SAFE},
319 {"seek", Tcl_SeekObjCmd, NULL, NULL, CMD_IS_SAFE},
320 {"socket", Tcl_SocketObjCmd, NULL, NULL, 0},
321 {"source", Tcl_SourceObjCmd, NULL, TclNRSourceObjCmd, 0},
322 {"tell", Tcl_TellObjCmd, NULL, NULL, CMD_IS_SAFE},
323 {"time", Tcl_TimeObjCmd, NULL, NULL, CMD_IS_SAFE},
324 #ifdef TCL_TIMERATE
325 {"timerate", Tcl_TimeRateObjCmd, NULL, NULL, CMD_IS_SAFE},
326 #endif
327 {"unload", Tcl_UnloadObjCmd, NULL, NULL, 0},
328 {"update", Tcl_UpdateObjCmd, NULL, NULL, CMD_IS_SAFE},
329 {"vwait", Tcl_VwaitObjCmd, NULL, NULL, CMD_IS_SAFE},
330 {NULL, NULL, NULL, NULL, 0}
331 };
332
333 /*
334 * Math functions. All are safe.
335 */
336
337 typedef struct {
338 const char *name; /* Name of the function. The full name is
339 * "::tcl::mathfunc::<name>". */
340 Tcl_ObjCmdProc *objCmdProc; /* Function that evaluates the function */
341 ClientData clientData; /* Client data for the function */
342 } BuiltinFuncDef;
343 static const BuiltinFuncDef BuiltinFuncTable[] = {
344 { "abs", ExprAbsFunc, NULL },
345 { "acos", ExprUnaryFunc, (void *)acos },
346 { "asin", ExprUnaryFunc, (void *)asin },
347 { "atan", ExprUnaryFunc, (void *)atan },
348 { "atan2", ExprBinaryFunc, (void *)atan2 },
349 { "bool", ExprBoolFunc, NULL },
350 { "ceil", ExprCeilFunc, NULL },
351 { "cos", ExprUnaryFunc, (void *)cos },
352 { "cosh", ExprUnaryFunc, (void *)cosh },
353 { "double", ExprDoubleFunc, NULL },
354 { "entier", ExprEntierFunc, NULL },
355 { "exp", ExprUnaryFunc, (void *)exp },
356 { "floor", ExprFloorFunc, NULL },
357 { "fmod", ExprBinaryFunc, (void *)fmod },
358 { "hypot", ExprBinaryFunc, (void *)hypot },
359 { "int", ExprIntFunc, NULL },
360 { "isqrt", ExprIsqrtFunc, NULL },
361 { "log", ExprUnaryFunc, (void *)log },
362 { "log10", ExprUnaryFunc, (void *)log10 },
363 { "pow", ExprBinaryFunc, (void *)pow },
364 { "rand", ExprRandFunc, NULL },
365 { "round", ExprRoundFunc, NULL },
366 { "sin", ExprUnaryFunc, (void *)sin },
367 { "sinh", ExprUnaryFunc, (void *)sinh },
368 { "sqrt", ExprSqrtFunc, NULL },
369 { "srand", ExprSrandFunc, NULL },
370 { "tan", ExprUnaryFunc, (void *)tan },
371 { "tanh", ExprUnaryFunc, (void *)tanh },
372 { "wide", ExprWideFunc, NULL },
373 { NULL, NULL, NULL }
374 };
375
376 /*
377 * TIP#174's math operators. All are safe.
378 */
379
380 typedef struct {
381 const char *name; /* Name of object-based command. */
382 Tcl_ObjCmdProc *objProc; /* Object-based function for command. */
383 CompileProc *compileProc; /* Function called to compile command. */
384 union {
385 int numArgs;
386 int identity;
387 } i;
388 const char *expected; /* For error message, what argument(s)
389 * were expected. */
390 } OpCmdInfo;
391 static const OpCmdInfo mathOpCmds[] = {
392 { "~", TclSingleOpCmd, TclCompileInvertOpCmd,
393 /* numArgs */ {1}, "integer"},
394 { "!", TclSingleOpCmd, TclCompileNotOpCmd,
395 /* numArgs */ {1}, "boolean"},
396 { "+", TclVariadicOpCmd, TclCompileAddOpCmd,
397 /* identity */ {0}, NULL},
398 { "*", TclVariadicOpCmd, TclCompileMulOpCmd,
399 /* identity */ {1}, NULL},
400 { "&", TclVariadicOpCmd, TclCompileAndOpCmd,
401 /* identity */ {-1}, NULL},
402 { "|", TclVariadicOpCmd, TclCompileOrOpCmd,
403 /* identity */ {0}, NULL},
404 { "^", TclVariadicOpCmd, TclCompileXorOpCmd,
405 /* identity */ {0}, NULL},
406 { "**", TclVariadicOpCmd, TclCompilePowOpCmd,
407 /* identity */ {1}, NULL},
408 { "<<", TclSingleOpCmd, TclCompileLshiftOpCmd,
409 /* numArgs */ {2}, "integer shift"},
410 { ">>", TclSingleOpCmd, TclCompileRshiftOpCmd,
411 /* numArgs */ {2}, "integer shift"},
412 { "%", TclSingleOpCmd, TclCompileModOpCmd,
413 /* numArgs */ {2}, "integer integer"},
414 { "!=", TclSingleOpCmd, TclCompileNeqOpCmd,
415 /* numArgs */ {2}, "value value"},
416 { "ne", TclSingleOpCmd, TclCompileStrneqOpCmd,
417 /* numArgs */ {2}, "value value"},
418 { "in", TclSingleOpCmd, TclCompileInOpCmd,
419 /* numArgs */ {2}, "value list"},
420 { "ni", TclSingleOpCmd, TclCompileNiOpCmd,
421 /* numArgs */ {2}, "value list"},
422 { "-", TclNoIdentOpCmd, TclCompileMinusOpCmd,
423 /* unused */ {0}, "value ?value ...?"},
424 { "/", TclNoIdentOpCmd, TclCompileDivOpCmd,
425 /* unused */ {0}, "value ?value ...?"},
426 { "<", TclSortingOpCmd, TclCompileLessOpCmd,
427 /* unused */ {0}, NULL},
428 { "<=", TclSortingOpCmd, TclCompileLeqOpCmd,
429 /* unused */ {0}, NULL},
430 { ">", TclSortingOpCmd, TclCompileGreaterOpCmd,
431 /* unused */ {0}, NULL},
432 { ">=", TclSortingOpCmd, TclCompileGeqOpCmd,
433 /* unused */ {0}, NULL},
434 { "==", TclSortingOpCmd, TclCompileEqOpCmd,
435 /* unused */ {0}, NULL},
436 { "eq", TclSortingOpCmd, TclCompileStreqOpCmd,
437 /* unused */ {0}, NULL},
438 { NULL, NULL, NULL,
439 {0}, NULL}
440 };
441
442 /*
443 *----------------------------------------------------------------------
444 *
445 * TclFinalizeEvaluation --
446 *
447 * Finalizes the script cancellation hash table.
448 *
449 * Results:
450 * None.
451 *
452 * Side effects:
453 * None.
454 *
455 *----------------------------------------------------------------------
456 */
457
458 void
459 TclFinalizeEvaluation(void)
460 {
461 Tcl_MutexLock(&cancelLock);
462 if (cancelTableInitialized == 1) {
463 Tcl_DeleteHashTable(&cancelTable);
464 cancelTableInitialized = 0;
465 }
466 Tcl_MutexUnlock(&cancelLock);
467 }
468
469 /*
470 *----------------------------------------------------------------------
471 *
472 * Tcl_CreateInterp --
473 *
474 * Create a new TCL command interpreter.
475 *
476 * Results:
477 * The return value is a token for the interpreter, which may be used in
478 * calls to functions like Tcl_CreateCmd, Tcl_Eval, or Tcl_DeleteInterp.
479 *
480 * Side effects:
481 * The command interpreter is initialized with the built-in commands and
482 * with the variables documented in tclvars(n).
483 *
484 *----------------------------------------------------------------------
485 */
486
487 Tcl_Interp *
488 Tcl_CreateInterp(void)
489 {
490 Interp *iPtr;
491 Tcl_Interp *interp;
492 Command *cmdPtr;
493 const BuiltinFuncDef *builtinFuncPtr;
494 const OpCmdInfo *opcmdInfoPtr;
495 const CmdInfo *cmdInfoPtr;
496 Tcl_Namespace *nsPtr;
497 Tcl_HashEntry *hPtr;
498 int isNew;
499 CancelInfo *cancelInfo;
500 union {
501 char c[sizeof(short)];
502 short s;
503 } order;
504 #ifdef TCL_COMPILE_STATS
505 ByteCodeStats *statsPtr;
506 #endif /* TCL_COMPILE_STATS */
507 char mathFuncName[32];
508 CallFrame *framePtr;
509 const char *version = TclInitSubsystems();
510
511 /*
512 * Panic if someone updated the CallFrame structure without also updating
513 * the Tcl_CallFrame structure (or vice versa).
514 */
515
516 if (sizeof(Tcl_CallFrame) < sizeof(CallFrame)) {
517 Tcl_Panic("Tcl_CallFrame must not be smaller than CallFrame");
518 }
519
520 #if defined(_WIN32) && !defined(_WIN64) && !defined(_USE_64BIT_TIME_T)
521 /* If Tcl is compiled on Win32 using -D_USE_64BIT_TIME_T
522 * the result is a binary incompatible with the 'standard' build of
523 * Tcl: All extensions using Tcl_StatBuf need to be recompiled in
524 * the same way. Therefore, this is not officially supported.
525 * In stead, it is recommended to use Win64 or Tcl 9.0 (not released yet)
526 */
527 if ((TclOffset(Tcl_StatBuf,st_atime) != 32)
528 || (TclOffset(Tcl_StatBuf,st_ctime) != 40)) {
529 Tcl_Panic("<sys/stat.h> is not compatible with MSVC");
530 }
531 #endif
532
533 if (cancelTableInitialized == 0) {
534 Tcl_MutexLock(&cancelLock);
535 if (cancelTableInitialized == 0) {
536 Tcl_InitHashTable(&cancelTable, TCL_ONE_WORD_KEYS);
537 cancelTableInitialized = 1;
538 }
539
540 Tcl_MutexUnlock(&cancelLock);
541 }
542
543 /*
544 * Initialize support for namespaces and create the global namespace
545 * (whose name is ""; an alias is "::"). This also initializes the Tcl
546 * object type table and other object management code.
547 */
548
549 iPtr = (Interp *)ckalloc(sizeof(Interp));
550 interp = (Tcl_Interp *) iPtr;
551
552 iPtr->result = iPtr->resultSpace;
553 iPtr->freeProc = NULL;
554 iPtr->errorLine = 0;
555 TclNewObj(iPtr->objResultPtr);
556 Tcl_IncrRefCount(iPtr->objResultPtr);
557 iPtr->handle = TclHandleCreate(iPtr);
558 iPtr->globalNsPtr = NULL;
559 iPtr->hiddenCmdTablePtr = NULL;
560 iPtr->interpInfo = NULL;
561
562 TCL_CT_ASSERT(sizeof(iPtr->extra) <= sizeof(Tcl_HashTable));
563 iPtr->extra.optimizer = TclOptimizeBytecode;
564
565 iPtr->numLevels = 0;
566 iPtr->maxNestingDepth = MAX_NESTING_DEPTH;
567 iPtr->framePtr = NULL; /* Initialise as soon as :: is available */
568 iPtr->varFramePtr = NULL; /* Initialise as soon as :: is available */
569
570 /*
571 * TIP #280 - Initialize the arrays used to extend the ByteCode and Proc
572 * structures.
573 */
574
575 iPtr->cmdFramePtr = NULL;
576 iPtr->linePBodyPtr = (Tcl_HashTable *)ckalloc(sizeof(Tcl_HashTable));
577 iPtr->lineBCPtr = (Tcl_HashTable *)ckalloc(sizeof(Tcl_HashTable));
578 iPtr->lineLAPtr = (Tcl_HashTable *)ckalloc(sizeof(Tcl_HashTable));
579 iPtr->lineLABCPtr = (Tcl_HashTable *)ckalloc(sizeof(Tcl_HashTable));
580 Tcl_InitHashTable(iPtr->linePBodyPtr, TCL_ONE_WORD_KEYS);
581 Tcl_InitHashTable(iPtr->lineBCPtr, TCL_ONE_WORD_KEYS);
582 Tcl_InitHashTable(iPtr->lineLAPtr, TCL_ONE_WORD_KEYS);
583 Tcl_InitHashTable(iPtr->lineLABCPtr, TCL_ONE_WORD_KEYS);
584 iPtr->scriptCLLocPtr = NULL;
585
586 iPtr->activeVarTracePtr = NULL;
587
588 iPtr->returnOpts = NULL;
589 iPtr->errorInfo = NULL;
590 TclNewLiteralStringObj(iPtr->eiVar, "::errorInfo");
591 Tcl_IncrRefCount(iPtr->eiVar);
592 iPtr->errorStack = Tcl_NewListObj(0, NULL);
593 Tcl_IncrRefCount(iPtr->errorStack);
594 iPtr->resetErrorStack = 1;
595 TclNewLiteralStringObj(iPtr->upLiteral,"UP");
596 Tcl_IncrRefCount(iPtr->upLiteral);
597 TclNewLiteralStringObj(iPtr->callLiteral,"CALL");
598 Tcl_IncrRefCount(iPtr->callLiteral);
599 TclNewLiteralStringObj(iPtr->innerLiteral,"INNER");
600 Tcl_IncrRefCount(iPtr->innerLiteral);
601 iPtr->innerContext = Tcl_NewListObj(0, NULL);
602 Tcl_IncrRefCount(iPtr->innerContext);
603 iPtr->errorCode = NULL;
604 TclNewLiteralStringObj(iPtr->ecVar, "::errorCode");
605 Tcl_IncrRefCount(iPtr->ecVar);
606 iPtr->returnLevel = 1;
607 iPtr->returnCode = TCL_OK;
608
609 iPtr->rootFramePtr = NULL; /* Initialise as soon as :: is available */
610 iPtr->lookupNsPtr = NULL;
611
612 iPtr->appendResult = NULL;
613 iPtr->appendAvl = 0;
614 iPtr->appendUsed = 0;
615
616 Tcl_InitHashTable(&iPtr->packageTable, TCL_STRING_KEYS);
617 iPtr->packageUnknown = NULL;
618
619 #ifdef _WIN32
620 # define getenv(x) _wgetenv(L##x) /* On Windows, use _wgetenv below */
621 #endif
622
623 /* TIP #268 */
624 if (getenv("TCL_PKG_PREFER_LATEST") == NULL) {
625 iPtr->packagePrefer = PKG_PREFER_STABLE;
626 } else {
627 iPtr->packagePrefer = PKG_PREFER_LATEST;
628 }
629
630 iPtr->cmdCount = 0;
631 TclInitLiteralTable(&iPtr->literalTable);
632 iPtr->compileEpoch = 0;
633 iPtr->compiledProcPtr = NULL;
634 iPtr->resolverPtr = NULL;
635 iPtr->evalFlags = 0;
636 iPtr->scriptFile = NULL;
637 iPtr->flags = 0;
638 iPtr->tracePtr = NULL;
639 iPtr->tracesForbiddingInline = 0;
640 iPtr->activeCmdTracePtr = NULL;
641 iPtr->activeInterpTracePtr = NULL;
642 iPtr->assocData = NULL;
643 iPtr->execEnvPtr = NULL; /* Set after namespaces initialized. */
644 TclNewObj(iPtr->emptyObjPtr);
645 /* Another empty object. */
646 Tcl_IncrRefCount(iPtr->emptyObjPtr);
647 iPtr->resultSpace[0] = 0;
648 iPtr->threadId = Tcl_GetCurrentThread();
649
650 /* TIP #378 */
651 #ifdef TCL_INTERP_DEBUG_FRAME
652 iPtr->flags |= INTERP_DEBUG_FRAME;
653 #else
654 if (getenv("TCL_INTERP_DEBUG_FRAME") != NULL) {
655 iPtr->flags |= INTERP_DEBUG_FRAME;
656 }
657 #endif
658
659 /*
660 * Initialise the tables for variable traces and searches *before*
661 * creating the global ns - so that the trace on errorInfo can be
662 * recorded.
663 */
664
665 Tcl_InitHashTable(&iPtr->varTraces, TCL_ONE_WORD_KEYS);
666 Tcl_InitHashTable(&iPtr->varSearches, TCL_ONE_WORD_KEYS);
667
668 iPtr->globalNsPtr = NULL; /* Force creation of global ns below. */
669 iPtr->globalNsPtr = (Namespace *) Tcl_CreateNamespace(interp, "",
670 NULL, NULL);
671 if (iPtr->globalNsPtr == NULL) {
672 Tcl_Panic("Tcl_CreateInterp: can't create global namespace");
673 }
674
675 /*
676 * Initialise the rootCallframe. It cannot be allocated on the stack, as
677 * it has to be in place before TclCreateExecEnv tries to use a variable.
678 */
679
680 /* This is needed to satisfy GCC 3.3's strict aliasing rules */
681 framePtr = (CallFrame *)ckalloc(sizeof(CallFrame));
682 (void) Tcl_PushCallFrame(interp, (Tcl_CallFrame *) framePtr,
683 (Tcl_Namespace *) iPtr->globalNsPtr, /*isProcCallFrame*/ 0);
684 framePtr->objc = 0;
685
686 iPtr->framePtr = framePtr;
687 iPtr->varFramePtr = framePtr;
688 iPtr->rootFramePtr = framePtr;
689
690 /*
691 * Initialize support for code compilation and execution. We call
692 * TclCreateExecEnv after initializing namespaces since it tries to
693 * reference a Tcl variable (it links to the Tcl "tcl_traceExec"
694 * variable).
695 */
696
697 iPtr->execEnvPtr = TclCreateExecEnv(interp, INTERP_STACK_INITIAL_SIZE);
698
699 /*
700 * TIP #219, Tcl Channel Reflection API support.
701 */
702
703 iPtr->chanMsg = NULL;
704
705 /*
706 * TIP #285, Script cancellation support.
707 */
708
709 TclNewObj(iPtr->asyncCancelMsg);
710
711 cancelInfo = (CancelInfo *)ckalloc(sizeof(CancelInfo));
712 cancelInfo->interp = interp;
713
714 iPtr->asyncCancel = Tcl_AsyncCreate(CancelEvalProc, cancelInfo);
715 cancelInfo->async = iPtr->asyncCancel;
716 cancelInfo->result = NULL;
717 cancelInfo->length = 0;
718
719 Tcl_MutexLock(&cancelLock);
720 hPtr = Tcl_CreateHashEntry(&cancelTable, iPtr, &isNew);
721 Tcl_SetHashValue(hPtr, cancelInfo);
722 Tcl_MutexUnlock(&cancelLock);
723
724 /*
725 * Initialize the compilation and execution statistics kept for this
726 * interpreter.
727 */
728
729 #ifdef TCL_COMPILE_STATS
730 statsPtr = &iPtr->stats;
731 statsPtr->numExecutions = 0;
732 statsPtr->numCompilations = 0;
733 statsPtr->numByteCodesFreed = 0;
734 memset(statsPtr->instructionCount, 0,
735 sizeof(statsPtr->instructionCount));
736
737 statsPtr->totalSrcBytes = 0.0;
738 statsPtr->totalByteCodeBytes = 0.0;
739 statsPtr->currentSrcBytes = 0.0;
740 statsPtr->currentByteCodeBytes = 0.0;
741 memset(statsPtr->srcCount, 0, sizeof(statsPtr->srcCount));
742 memset(statsPtr->byteCodeCount, 0, sizeof(statsPtr->byteCodeCount));
743 memset(statsPtr->lifetimeCount, 0, sizeof(statsPtr->lifetimeCount));
744
745 statsPtr->currentInstBytes = 0.0;
746 statsPtr->currentLitBytes = 0.0;
747 statsPtr->currentExceptBytes = 0.0;
748 statsPtr->currentAuxBytes = 0.0;
749 statsPtr->currentCmdMapBytes = 0.0;
750
751 statsPtr->numLiteralsCreated = 0;
752 statsPtr->totalLitStringBytes = 0.0;
753 statsPtr->currentLitStringBytes = 0.0;
754 memset(statsPtr->literalCount, 0, sizeof(statsPtr->literalCount));
755 #endif /* TCL_COMPILE_STATS */
756
757 /*
758 * Initialise the stub table pointer.
759 */
760
761 iPtr->stubTable = &tclStubs;
762
763 /*
764 * Initialize the ensemble error message rewriting support.
765 */
766
767 TclResetRewriteEnsemble(interp, 1);
768
769 /*
770 * TIP#143: Initialise the resource limit support.
771 */
772
773 TclInitLimitSupport(interp);
774
775 /*
776 * Initialise the thread-specific data ekeko. Note that the thread's alloc
777 * cache was already initialised by the call to alloc the interp struct.
778 */
779
780 #if defined(TCL_THREADS) && defined(USE_THREAD_ALLOC)
781 iPtr->allocCache = (AllocCache *)TclpGetAllocCache();
782 #else
783 iPtr->allocCache = NULL;
784 #endif
785 iPtr->pendingObjDataPtr = NULL;
786 iPtr->asyncReadyPtr = TclGetAsyncReadyPtr();
787 iPtr->deferredCallbacks = NULL;
788
789 /*
790 * Create the core commands. Do it here, rather than calling
791 * Tcl_CreateCommand, because it's faster (there's no need to check for a
792 * preexisting command by the same name). If a command has a Tcl_CmdProc
793 * but no Tcl_ObjCmdProc, set the Tcl_ObjCmdProc to
794 * TclInvokeStringCommand. This is an object-based wrapper function that
795 * extracts strings, calls the string function, and creates an object for
796 * the result. Similarly, if a command has a Tcl_ObjCmdProc but no
797 * Tcl_CmdProc, set the Tcl_CmdProc to TclInvokeObjectCommand.
798 */
799
800 for (cmdInfoPtr = builtInCmds; cmdInfoPtr->name != NULL; cmdInfoPtr++) {
801 if ((cmdInfoPtr->objProc == NULL)
802 && (cmdInfoPtr->compileProc == NULL)
803 && (cmdInfoPtr->nreProc == NULL)) {
804 Tcl_Panic("builtin command with NULL object command proc and a NULL compile proc");
805 }
806
807 hPtr = Tcl_CreateHashEntry(&iPtr->globalNsPtr->cmdTable,
808 cmdInfoPtr->name, &isNew);
809 if (isNew) {
810 cmdPtr = (Command *)ckalloc(sizeof(Command));
811 cmdPtr->hPtr = hPtr;
812 cmdPtr->nsPtr = iPtr->globalNsPtr;
813 cmdPtr->refCount = 1;
814 cmdPtr->cmdEpoch = 0;
815 cmdPtr->compileProc = cmdInfoPtr->compileProc;
816 cmdPtr->proc = TclInvokeObjectCommand;
817 cmdPtr->clientData = cmdPtr;
818 cmdPtr->objProc = cmdInfoPtr->objProc;
819 cmdPtr->objClientData = NULL;
820 cmdPtr->deleteProc = NULL;
821 cmdPtr->deleteData = NULL;
822 cmdPtr->flags = 0;
823 if (cmdInfoPtr->flags & CMD_COMPILES_EXPANDED) {
824 cmdPtr->flags |= CMD_COMPILES_EXPANDED;
825 }
826 cmdPtr->importRefPtr = NULL;
827 cmdPtr->tracePtr = NULL;
828 cmdPtr->nreProc = cmdInfoPtr->nreProc;
829 Tcl_SetHashValue(hPtr, cmdPtr);
830 }
831 }
832
833 /*
834 * Create the "array", "binary", "chan", "clock", "dict", "encoding",
835 * "file", "info", "namespace" and "string" ensembles. Note that all these
836 * commands (and their subcommands that are not present in the global
837 * namespace) are wholly safe *except* for "clock", "encoding" and "file".
838 */
839
840 TclInitArrayCmd(interp);
841 TclInitBinaryCmd(interp);
842 TclInitChanCmd(interp);
843 TclInitDictCmd(interp);
844 TclInitEncodingCmd(interp);
845 TclInitFileCmd(interp);
846 TclInitInfoCmd(interp);
847 TclInitNamespaceCmd(interp);
848 TclInitStringCmd(interp);
849 TclInitPrefixCmd(interp);
850
851 /*
852 * Register "clock" subcommands. These *do* go through
853 * Tcl_CreateObjCommand, since they aren't in the global namespace and
854 * involve ensembles.
855 */
856
857 TclClockInit(interp);
858
859 /*
860 * Register the built-in functions. This is empty now that they are
861 * implemented as commands in the ::tcl::mathfunc namespace.
862 */
863
864 /*
865 * Register the default [interp bgerror] handler.
866 */
867
868 Tcl_CreateObjCommand(interp, "::tcl::Bgerror",
869 TclDefaultBgErrorHandlerObjCmd, NULL, NULL);
870
871 /*
872 * Create unsupported commands for debugging bytecode and objects.
873 */
874
875 Tcl_CreateObjCommand(interp, "::tcl::unsupported::disassemble",
876 Tcl_DisassembleObjCmd, INT2PTR(0), NULL);
877 Tcl_CreateObjCommand(interp, "::tcl::unsupported::getbytecode",
878 Tcl_DisassembleObjCmd, INT2PTR(1), NULL);
879 Tcl_CreateObjCommand(interp, "::tcl::unsupported::representation",
880 Tcl_RepresentationCmd, NULL, NULL);
881
882 /* Adding the bytecode assembler command */
883 cmdPtr = (Command *) Tcl_NRCreateCommand(interp,
884 "::tcl::unsupported::assemble", Tcl_AssembleObjCmd,
885 TclNRAssembleObjCmd, NULL, NULL);
886 cmdPtr->compileProc = &TclCompileAssembleCmd;
887
888 /* Coroutine monkeybusiness */
889 Tcl_NRCreateCommand(interp, "::tcl::unsupported::inject", NULL,
890 NRCoroInjectObjCmd, NULL, NULL);
891 Tcl_CreateObjCommand(interp, "::tcl::unsupported::corotype",
892 CoroTypeObjCmd, NULL, NULL);
893
894 /* Create an unsupported command for timerate */
895 Tcl_CreateObjCommand(interp, "::tcl::unsupported::timerate",
896 Tcl_TimeRateObjCmd, NULL, NULL);
897
898 /* Export unsupported commands */
899 nsPtr = Tcl_FindNamespace(interp, "::tcl::unsupported", NULL, 0);
900 if (nsPtr) {
901 Tcl_Export(interp, nsPtr, "*", 1);
902 }
903
904 #ifdef USE_DTRACE
905 /*
906 * Register the tcl::dtrace command.
907 */
908
909 Tcl_CreateObjCommand(interp, "::tcl::dtrace", DTraceObjCmd, NULL, NULL);
910 #endif /* USE_DTRACE */
911
912 /*
913 * Register the builtin math functions.
914 */
915
916 nsPtr = Tcl_CreateNamespace(interp, "::tcl::mathfunc", NULL,NULL);
917 if (nsPtr == NULL) {
918 Tcl_Panic("Can't create math function namespace");
919 }
920 #define MATH_FUNC_PREFIX_LEN 17 /* == strlen("::tcl::mathfunc::") */
921 memcpy(mathFuncName, "::tcl::mathfunc::", MATH_FUNC_PREFIX_LEN);
922 for (builtinFuncPtr = BuiltinFuncTable; builtinFuncPtr->name != NULL;
923 builtinFuncPtr++) {
924 strcpy(mathFuncName + MATH_FUNC_PREFIX_LEN, builtinFuncPtr->name);
925 Tcl_CreateObjCommand(interp, mathFuncName,
926 builtinFuncPtr->objCmdProc, builtinFuncPtr->clientData, NULL);
927 Tcl_Export(interp, nsPtr, builtinFuncPtr->name, 0);
928 }
929
930 /*
931 * Register the mathematical "operator" commands. [TIP #174]
932 */
933
934 nsPtr = Tcl_CreateNamespace(interp, "::tcl::mathop", NULL, NULL);
935 if (nsPtr == NULL) {
936 Tcl_Panic("can't create math operator namespace");
937 }
938 Tcl_Export(interp, nsPtr, "*", 1);
939 #define MATH_OP_PREFIX_LEN 15 /* == strlen("::tcl::mathop::") */
940 memcpy(mathFuncName, "::tcl::mathop::", MATH_OP_PREFIX_LEN);
941 for (opcmdInfoPtr=mathOpCmds ; opcmdInfoPtr->name!=NULL ; opcmdInfoPtr++){
942 TclOpCmdClientData *occdPtr = (TclOpCmdClientData *)ckalloc(sizeof(TclOpCmdClientData));
943
944 occdPtr->op = opcmdInfoPtr->name;
945 occdPtr->i.numArgs = opcmdInfoPtr->i.numArgs;
946 occdPtr->expected = opcmdInfoPtr->expected;
947 strcpy(mathFuncName + MATH_OP_PREFIX_LEN, opcmdInfoPtr->name);
948 cmdPtr = (Command *) Tcl_CreateObjCommand(interp, mathFuncName,
949 opcmdInfoPtr->objProc, occdPtr, DeleteOpCmdClientData);
950 if (cmdPtr == NULL) {
951 Tcl_Panic("failed to create math operator %s",
952 opcmdInfoPtr->name);
953 } else if (opcmdInfoPtr->compileProc != NULL) {
954 cmdPtr->compileProc = opcmdInfoPtr->compileProc;
955 }
956 }
957
958 /*
959 * Do Multiple/Safe Interps Tcl init stuff
960 */
961
962 TclInterpInit(interp);
963 TclSetupEnv(interp);
964
965 /*
966 * TIP #59: Make embedded configuration information available.
967 */
968
969 TclInitEmbeddedConfigurationInformation(interp);
970
971 /*
972 * TIP #440: Declare the name of the script engine to be "Tcl".
973 */
974
975 Tcl_SetVar2(interp, "tcl_platform", "engine", "Tcl",
976 TCL_GLOBAL_ONLY);
977
978 /*
979 * Compute the byte order of this machine.
980 */
981
982 order.s = 1;
983 Tcl_SetVar2(interp, "tcl_platform", "byteOrder",
984 ((order.c[0] == 1) ? "littleEndian" : "bigEndian"),
985 TCL_GLOBAL_ONLY);
986
987 Tcl_SetVar2Ex(interp, "tcl_platform", "wordSize",
988 Tcl_NewLongObj((long)sizeof(long)), TCL_GLOBAL_ONLY);
989
990 /* TIP #291 */
991 Tcl_SetVar2Ex(interp, "tcl_platform", "pointerSize",
992 Tcl_NewLongObj((long)sizeof(void *)), TCL_GLOBAL_ONLY);
993
994 /*
995 * Set up other variables such as tcl_version and tcl_library
996 */
997
998 Tcl_SetVar(interp, "tcl_patchLevel", TCL_PATCH_LEVEL, TCL_GLOBAL_ONLY);
999 Tcl_SetVar(interp, "tcl_version", TCL_VERSION, TCL_GLOBAL_ONLY);
1000 Tcl_TraceVar2(interp, "tcl_precision", NULL,
1001 TCL_GLOBAL_ONLY|TCL_TRACE_READS|TCL_TRACE_WRITES|TCL_TRACE_UNSETS,
1002 TclPrecTraceProc, NULL);
1003 TclpSetVariables(interp);
1004
1005 #ifdef TCL_THREADS
1006 /*
1007 * The existence of the "threaded" element of the tcl_platform array
1008 * indicates that this particular Tcl shell has been compiled with threads
1009 * turned on. Using "info exists tcl_platform(threaded)" a Tcl script can
1010 * introspect on the interpreter level of thread safety.
1011 */
1012
1013 Tcl_SetVar2(interp, "tcl_platform", "threaded", "1", TCL_GLOBAL_ONLY);
1014 #endif
1015
1016 /*
1017 * Register Tcl's version number.
1018 * TIP #268: Full patchlevel instead of just major.minor
1019 */
1020
1021 Tcl_PkgProvideEx(interp, "Tcl", version, &tclStubs);
1022
1023 if (TclTommath_Init(interp) != TCL_OK) {
1024 Tcl_Panic("%s", Tcl_GetString(Tcl_GetObjResult(interp)));
1025 }
1026
1027 if (TclOOInit(interp) != TCL_OK) {
1028 Tcl_Panic("%s", Tcl_GetString(Tcl_GetObjResult(interp)));
1029 }
1030
1031 /*
1032 * Only build in zlib support if we've successfully detected a library to
1033 * compile and link against.
1034 */
1035
1036 #ifdef HAVE_ZLIB
1037 if (TclZlibInit(interp) != TCL_OK) {
1038 Tcl_Panic("%s", Tcl_GetString(Tcl_GetObjResult(interp)));
1039 }
1040 #endif
1041
1042 TOP_CB(iPtr) = NULL;
1043 return interp;
1044 }
1045
1046 static void
1047 DeleteOpCmdClientData(
1048 ClientData clientData)
1049 {
1050 TclOpCmdClientData *occdPtr = (TclOpCmdClientData *)clientData;
1051
1052 ckfree(occdPtr);
1053 }
1054
1055 /*
1056 *----------------------------------------------------------------------
1057 *
1058 * TclHideUnsafeCommands --
1059 *
1060 * Hides base commands that are not marked as safe from this interpreter.
1061 *
1062 * Results:
1063 * TCL_OK if it succeeds, TCL_ERROR else.
1064 *
1065 * Side effects:
1066 * Hides functionality in an interpreter.
1067 *
1068 *----------------------------------------------------------------------
1069 */
1070
1071 int
1072 TclHideUnsafeCommands(
1073 Tcl_Interp *interp) /* Hide commands in this interpreter. */
1074 {
1075 const CmdInfo *cmdInfoPtr;
1076
1077 if (interp == NULL) {
1078 return TCL_ERROR;
1079 }
1080 for (cmdInfoPtr = builtInCmds; cmdInfoPtr->name != NULL; cmdInfoPtr++) {
1081 if (!(cmdInfoPtr->flags & CMD_IS_SAFE)) {
1082 Tcl_HideCommand(interp, cmdInfoPtr->name, cmdInfoPtr->name);
1083 }
1084 }
1085 TclMakeEncodingCommandSafe(interp); /* Ugh! */
1086 TclMakeFileCommandSafe(interp); /* Ugh! */
1087 return TCL_OK;
1088 }
1089
1090 /*
1091 *--------------------------------------------------------------
1092 *
1093 * Tcl_CallWhenDeleted --
1094 *
1095 * Arrange for a function to be called before a given interpreter is
1096 * deleted. The function is called as soon as Tcl_DeleteInterp is called;
1097 * if Tcl_CallWhenDeleted is called on an interpreter that has already
1098 * been deleted, the function will be called when the last Tcl_Release is
1099 * done on the interpreter.
1100 *
1101 * Results:
1102 * None.
1103 *
1104 * Side effects:
1105 * When Tcl_DeleteInterp is invoked to delete interp, proc will be
1106 * invoked. See the manual entry for details.
1107 *
1108 *--------------------------------------------------------------
1109 */
1110
1111 void
1112 Tcl_CallWhenDeleted(
1113 Tcl_Interp *interp, /* Interpreter to watch. */
1114 Tcl_InterpDeleteProc *proc, /* Function to call when interpreter is about
1115 * to be deleted. */
1116 ClientData clientData) /* One-word value to pass to proc. */
1117 {
1118 Interp *iPtr = (Interp *) interp;
1119 static Tcl_ThreadDataKey assocDataCounterKey;
1120 int *assocDataCounterPtr = (int *)
1121 Tcl_GetThreadData(&assocDataCounterKey, sizeof(int));
1122 int isNew;
1123 char buffer[32 + TCL_INTEGER_SPACE];
1124 AssocData *dPtr = (AssocData *)ckalloc(sizeof(AssocData));
1125 Tcl_HashEntry *hPtr;
1126
1127 snprintf(buffer, sizeof(buffer), "Assoc Data Key #%d", *assocDataCounterPtr);
1128 (*assocDataCounterPtr)++;
1129
1130 if (iPtr->assocData == NULL) {
1131 iPtr->assocData = (Tcl_HashTable *)ckalloc(sizeof(Tcl_HashTable));
1132 Tcl_InitHashTable(iPtr->assocData, TCL_STRING_KEYS);
1133 }
1134 hPtr = Tcl_CreateHashEntry(iPtr->assocData, buffer, &isNew);
1135 dPtr->proc = proc;
1136 dPtr->clientData = clientData;
1137 Tcl_SetHashValue(hPtr, dPtr);
1138 }
1139
1140 /*
1141 *--------------------------------------------------------------
1142 *
1143 * Tcl_DontCallWhenDeleted --
1144 *
1145 * Cancel the arrangement for a function to be called when a given
1146 * interpreter is deleted.
1147 *
1148 * Results:
1149 * None.
1150 *
1151 * Side effects:
1152 * If proc and clientData were previously registered as a callback via
1153 * Tcl_CallWhenDeleted, they are unregistered. If they weren't previously
1154 * registered then nothing happens.
1155 *
1156 *--------------------------------------------------------------
1157 */
1158
1159 void
1160 Tcl_DontCallWhenDeleted(
1161 Tcl_Interp *interp, /* Interpreter to watch. */
1162 Tcl_InterpDeleteProc *proc, /* Function to call when interpreter is about
1163 * to be deleted. */
1164 ClientData clientData) /* One-word value to pass to proc. */
1165 {
1166 Interp *iPtr = (Interp *) interp;
1167 Tcl_HashTable *hTablePtr;
1168 Tcl_HashSearch hSearch;
1169 Tcl_HashEntry *hPtr;
1170 AssocData *dPtr;
1171
1172 hTablePtr = iPtr->assocData;
1173 if (hTablePtr == NULL) {
1174 return;
1175 }
1176 for (hPtr = Tcl_FirstHashEntry(hTablePtr, &hSearch); hPtr != NULL;
1177 hPtr = Tcl_NextHashEntry(&hSearch)) {
1178 dPtr = (AssocData *)Tcl_GetHashValue(hPtr);
1179 if ((dPtr->proc == proc) && (dPtr->clientData == clientData)) {
1180 ckfree(dPtr);
1181 Tcl_DeleteHashEntry(hPtr);
1182 return;
1183 }
1184 }
1185 }
1186
1187 /*
1188 *----------------------------------------------------------------------
1189 *
1190 * Tcl_SetAssocData --
1191 *
1192 * Creates a named association between user-specified data, a delete
1193 * function and this interpreter. If the association already exists the
1194 * data is overwritten with the new data. The delete function will be
1195 * invoked when the interpreter is deleted.
1196 *
1197 * Results:
1198 * None.
1199 *
1200 * Side effects:
1201 * Sets the associated data, creates the association if needed.
1202 *
1203 *----------------------------------------------------------------------
1204 */
1205
1206 void
1207 Tcl_SetAssocData(
1208 Tcl_Interp *interp, /* Interpreter to associate with. */
1209 const char *name, /* Name for association. */
1210 Tcl_InterpDeleteProc *proc, /* Proc to call when interpreter is about to
1211 * be deleted. */
1212 ClientData clientData) /* One-word value to pass to proc. */
1213 {
1214 Interp *iPtr = (Interp *) interp;
1215 AssocData *dPtr;
1216 Tcl_HashEntry *hPtr;
1217 int isNew;
1218
1219 if (iPtr->assocData == NULL) {
1220 iPtr->assocData = (Tcl_HashTable *)ckalloc(sizeof(Tcl_HashTable));
1221 Tcl_InitHashTable(iPtr->assocData, TCL_STRING_KEYS);
1222 }
1223 hPtr = Tcl_CreateHashEntry(iPtr->assocData, name, &isNew);
1224 if (isNew == 0) {
1225 dPtr = (AssocData *)Tcl_GetHashValue(hPtr);
1226 } else {
1227 dPtr = (AssocData *)ckalloc(sizeof(AssocData));
1228 }
1229 dPtr->proc = proc;
1230 dPtr->clientData = clientData;
1231
1232 Tcl_SetHashValue(hPtr, dPtr);
1233 }
1234
1235 /*
1236 *----------------------------------------------------------------------
1237 *
1238 * Tcl_DeleteAssocData --
1239 *
1240 * Deletes a named association of user-specified data with the specified
1241 * interpreter.
1242 *
1243 * Results:
1244 * None.
1245 *
1246 * Side effects:
1247 * Deletes the association.
1248 *
1249 *----------------------------------------------------------------------
1250 */
1251
1252 void
1253 Tcl_DeleteAssocData(
1254 Tcl_Interp *interp, /* Interpreter to associate with. */
1255 const char *name) /* Name of association. */
1256 {
1257 Interp *iPtr = (Interp *) interp;
1258 AssocData *dPtr;
1259 Tcl_HashEntry *hPtr;
1260
1261 if (iPtr->assocData == NULL) {
1262 return;
1263 }
1264 hPtr = Tcl_FindHashEntry(iPtr->assocData, name);
1265 if (hPtr == NULL) {
1266 return;
1267 }
1268 dPtr = (AssocData *)Tcl_GetHashValue(hPtr);
1269 Tcl_DeleteHashEntry(hPtr);
1270 if (dPtr->proc != NULL) {
1271 dPtr->proc(dPtr->clientData, interp);
1272 }
1273 ckfree(dPtr);
1274 }
1275
1276 /*
1277 *----------------------------------------------------------------------
1278 *
1279 * Tcl_GetAssocData --
1280 *
1281 * Returns the client data associated with this name in the specified
1282 * interpreter.
1283 *
1284 * Results:
1285 * The client data in the AssocData record denoted by the named
1286 * association, or NULL.
1287 *
1288 * Side effects:
1289 * None.
1290 *
1291 *----------------------------------------------------------------------
1292 */
1293
1294 ClientData
1295 Tcl_GetAssocData(
1296 Tcl_Interp *interp, /* Interpreter associated with. */
1297 const char *name, /* Name of association. */
1298 Tcl_InterpDeleteProc **procPtr)
1299 /* Pointer to place to store address of
1300 * current deletion callback. */
1301 {
1302 Interp *iPtr = (Interp *) interp;
1303 AssocData *dPtr;
1304 Tcl_HashEntry *hPtr;
1305
1306 if (iPtr->assocData == NULL) {
1307 return NULL;
1308 }
1309 hPtr = Tcl_FindHashEntry(iPtr->assocData, name);
1310 if (hPtr == NULL) {
1311 return NULL;
1312 }
1313 dPtr = (AssocData *)Tcl_GetHashValue(hPtr);
1314 if (procPtr != NULL) {
1315 *procPtr = dPtr->proc;
1316 }
1317 return dPtr->clientData;
1318 }
1319
1320 /*
1321 *----------------------------------------------------------------------
1322 *
1323 * Tcl_InterpDeleted --
1324 *
1325 * Returns nonzero if the interpreter has been deleted with a call to
1326 * Tcl_DeleteInterp.
1327 *
1328 * Results:
1329 * Nonzero if the interpreter is deleted, zero otherwise.
1330 *
1331 * Side effects:
1332 * None.
1333 *
1334 *----------------------------------------------------------------------
1335 */
1336
1337 int
1338 Tcl_InterpDeleted(
1339 Tcl_Interp *interp)
1340 {
1341 return (((Interp *) interp)->flags & DELETED) ? 1 : 0;
1342 }
1343
1344 /*
1345 *----------------------------------------------------------------------
1346 *
1347 * Tcl_DeleteInterp --
1348 *
1349 * Ensures that the interpreter will be deleted eventually. If there are
1350 * no Tcl_Preserve calls in effect for this interpreter, it is deleted
1351 * immediately, otherwise the interpreter is deleted when the last
1352 * Tcl_Preserve is matched by a call to Tcl_Release. In either case, the
1353 * function runs the currently registered deletion callbacks.
1354 *
1355 * Results:
1356 * None.
1357 *
1358 * Side effects:
1359 * The interpreter is marked as deleted. The caller may still use it
1360 * safely if there are calls to Tcl_Preserve in effect for the
1361 * interpreter, but further calls to Tcl_Eval etc in this interpreter
1362 * will fail.
1363 *
1364 *----------------------------------------------------------------------
1365 */
1366
1367 void
1368 Tcl_DeleteInterp(
1369 Tcl_Interp *interp) /* Token for command interpreter (returned by
1370 * a previous call to Tcl_CreateInterp). */
1371 {
1372 Interp *iPtr = (Interp *) interp;
1373
1374 /*
1375 * If the interpreter has already been marked deleted, just punt.
1376 */
1377
1378 if (iPtr->flags & DELETED) {
1379 return;
1380 }
1381
1382 /*
1383 * Mark the interpreter as deleted. No further evals will be allowed.
1384 * Increase the compileEpoch as a signal to compiled bytecodes.
1385 */
1386
1387 iPtr->flags |= DELETED;
1388 iPtr->compileEpoch++;
1389
1390 /*
1391 * Ensure that the interpreter is eventually deleted.
1392 */
1393
1394 Tcl_EventuallyFree(interp, DeleteInterpProc);
1395 }
1396
1397 /*
1398 *----------------------------------------------------------------------
1399 *
1400 * DeleteInterpProc --
1401 *
1402 * Helper function to delete an interpreter. This function is called when
1403 * the last call to Tcl_Preserve on this interpreter is matched by a call
1404 * to Tcl_Release. The function cleans up all resources used in the
1405 * interpreter and calls all currently registered interpreter deletion
1406 * callbacks.
1407 *
1408 * Results:
1409 * None.
1410 *
1411 * Side effects:
1412 * Whatever the interpreter deletion callbacks do. Frees resources used
1413 * by the interpreter.
1414 *
1415 *----------------------------------------------------------------------
1416 */
1417
1418 static void
1419 DeleteInterpProc(
1420 char *blockPtr) /* Interpreter to delete. */
1421 {
1422 Tcl_Interp *interp = (Tcl_Interp *) blockPtr;
1423 Interp *iPtr = (Interp *) interp;
1424 Tcl_HashEntry *hPtr;
1425 Tcl_HashSearch search;
1426 Tcl_HashTable *hTablePtr;
1427 ResolverScheme *resPtr, *nextResPtr;
1428 int i;
1429
1430 /*
1431 * Punt if there is an error in the Tcl_Release/Tcl_Preserve matchup,
1432 * unless we are exiting.
1433 */
1434
1435 if ((iPtr->numLevels > 0) && !TclInExit()) {
1436 Tcl_Panic("DeleteInterpProc called with active evals");
1437 }
1438
1439 /*
1440 * The interpreter should already be marked deleted; otherwise how did we
1441 * get here?
1442 */
1443
1444 if (!(iPtr->flags & DELETED)) {
1445 Tcl_Panic("DeleteInterpProc called on interpreter not marked deleted");
1446 }
1447
1448 /*
1449 * TIP #219, Tcl Channel Reflection API. Discard a leftover state.
1450 */
1451
1452 if (iPtr->chanMsg != NULL) {
1453 Tcl_DecrRefCount(iPtr->chanMsg);
1454 iPtr->chanMsg = NULL;
1455 }
1456
1457 /*
1458 * TIP #285, Script cancellation support. Delete this interp from the
1459 * global hash table of CancelInfo structs.
1460 */
1461
1462 Tcl_MutexLock(&cancelLock);
1463 hPtr = Tcl_FindHashEntry(&cancelTable, (char *)iPtr);
1464 if (hPtr != NULL) {
1465 CancelInfo *cancelInfo = (CancelInfo *)Tcl_GetHashValue(hPtr);
1466
1467 if (cancelInfo != NULL) {
1468 if (cancelInfo->result != NULL) {
1469 ckfree(cancelInfo->result);
1470 }
1471 ckfree(cancelInfo);
1472 }
1473
1474 Tcl_DeleteHashEntry(hPtr);
1475 }
1476
1477 if (iPtr->asyncCancel != NULL) {
1478 Tcl_AsyncDelete(iPtr->asyncCancel);
1479 iPtr->asyncCancel = NULL;
1480 }
1481
1482 if (iPtr->asyncCancelMsg != NULL) {
1483 Tcl_DecrRefCount(iPtr->asyncCancelMsg);
1484 iPtr->asyncCancelMsg = NULL;
1485 }
1486 Tcl_MutexUnlock(&cancelLock);
1487
1488 /*
1489 * Shut down all limit handler callback scripts that call back into this
1490 * interpreter. Then eliminate all limit handlers for this interpreter.
1491 */
1492
1493 TclRemoveScriptLimitCallbacks(interp);
1494 TclLimitRemoveAllHandlers(interp);
1495
1496 /*
1497 * Dismantle the namespace here, before we clear the assocData. If any
1498 * background errors occur here, they will be deleted below.
1499 *
1500 * Dismantle the namespace after freeing the iPtr->handle so that each
1501 * bytecode releases its literals without caring to update the literal
1502 * table, as it will be freed later in this function without further use.
1503 */
1504
1505 TclHandleFree(iPtr->handle);
1506 TclTeardownNamespace(iPtr->globalNsPtr);
1507
1508 /*
1509 * Delete all the hidden commands.
1510 */
1511
1512 hTablePtr = iPtr->hiddenCmdTablePtr;
1513 if (hTablePtr != NULL) {
1514 /*
1515 * Non-pernicious deletion. The deletion callbacks will not be allowed
1516 * to create any new hidden or non-hidden commands.
1517 * Tcl_DeleteCommandFromToken will remove the entry from the
1518 * hiddenCmdTablePtr.
1519 */
1520
1521 hPtr = Tcl_FirstHashEntry(hTablePtr, &search);
1522 for (; hPtr != NULL; hPtr = Tcl_NextHashEntry(&search)) {
1523 Tcl_DeleteCommandFromToken(interp, (Tcl_Command)Tcl_GetHashValue(hPtr));
1524 }
1525 Tcl_DeleteHashTable(hTablePtr);
1526 ckfree(hTablePtr);
1527 }
1528
1529 /*
1530 * Invoke deletion callbacks; note that a callback can create new
1531 * callbacks, so we iterate.
1532 */
1533
1534 while (iPtr->assocData != NULL) {
1535 AssocData *dPtr;
1536
1537 hTablePtr = iPtr->assocData;
1538 iPtr->assocData = NULL;
1539 for (hPtr = Tcl_FirstHashEntry(hTablePtr, &search);
1540 hPtr != NULL;
1541 hPtr = Tcl_FirstHashEntry(hTablePtr, &search)) {
1542 dPtr = (AssocData *)Tcl_GetHashValue(hPtr);
1543 Tcl_DeleteHashEntry(hPtr);
1544 if (dPtr->proc != NULL) {
1545 dPtr->proc(dPtr->clientData, interp);
1546 }
1547 ckfree(dPtr);
1548 }
1549 Tcl_DeleteHashTable(hTablePtr);
1550 ckfree(hTablePtr);
1551 }
1552
1553 /*
1554 * Pop the root frame pointer and finish deleting the global
1555 * namespace. The order is important [Bug 1658572].
1556 */
1557
1558 if ((iPtr->framePtr != iPtr->rootFramePtr) && !TclInExit()) {
1559 Tcl_Panic("DeleteInterpProc: popping rootCallFrame with other frames on top");
1560 }
1561 Tcl_PopCallFrame(interp);
1562 ckfree(iPtr->rootFramePtr);
1563 iPtr->rootFramePtr = NULL;
1564 Tcl_DeleteNamespace((Tcl_Namespace *) iPtr->globalNsPtr);
1565
1566 /*
1567 * Free up the result *after* deleting variables, since variable deletion
1568 * could have transferred ownership of the result string to Tcl.
1569 */
1570
1571 Tcl_FreeResult(interp);
1572 iPtr->result = NULL;
1573 Tcl_DecrRefCount(iPtr->objResultPtr);
1574 iPtr->objResultPtr = NULL;
1575 Tcl_DecrRefCount(iPtr->ecVar);
1576 if (iPtr->errorCode) {
1577 Tcl_DecrRefCount(iPtr->errorCode);
1578 iPtr->errorCode = NULL;
1579 }
1580 Tcl_DecrRefCount(iPtr->eiVar);
1581 if (iPtr->errorInfo) {
1582 Tcl_DecrRefCount(iPtr->errorInfo);
1583 iPtr->errorInfo = NULL;
1584 }
1585 Tcl_DecrRefCount(iPtr->errorStack);
1586 iPtr->errorStack = NULL;
1587 Tcl_DecrRefCount(iPtr->upLiteral);
1588 Tcl_DecrRefCount(iPtr->callLiteral);
1589 Tcl_DecrRefCount(iPtr->innerLiteral);
1590 Tcl_DecrRefCount(iPtr->innerContext);
1591 if (iPtr->returnOpts) {
1592 Tcl_DecrRefCount(iPtr->returnOpts);
1593 }
1594 if (iPtr->appendResult != NULL) {
1595 ckfree(iPtr->appendResult);
1596 iPtr->appendResult = NULL;
1597 }
1598 TclFreePackageInfo(iPtr);
1599 while (iPtr->tracePtr != NULL) {
1600 Tcl_DeleteTrace((Tcl_Interp *) iPtr, (Tcl_Trace) iPtr->tracePtr);
1601 }
1602 if (iPtr->execEnvPtr != NULL) {
1603 TclDeleteExecEnv(iPtr->execEnvPtr);
1604 }
1605 if (iPtr->scriptFile) {
1606 Tcl_DecrRefCount(iPtr->scriptFile);
1607 iPtr->scriptFile = NULL;
1608 }
1609 Tcl_DecrRefCount(iPtr->emptyObjPtr);
1610 iPtr->emptyObjPtr = NULL;
1611
1612 resPtr = iPtr->resolverPtr;
1613 while (resPtr) {
1614 nextResPtr = resPtr->nextPtr;
1615 ckfree(resPtr->name);
1616 ckfree(resPtr);
1617 resPtr = nextResPtr;
1618 }
1619
1620 /*
1621 * Free up literal objects created for scripts compiled by the
1622 * interpreter.
1623 */
1624
1625 TclDeleteLiteralTable(interp, &iPtr->literalTable);
1626
1627 /*
1628 * TIP #280 - Release the arrays for ByteCode/Proc extension, and
1629 * contents.
1630 */
1631
1632 for (hPtr = Tcl_FirstHashEntry(iPtr->linePBodyPtr, &search);
1633 hPtr != NULL;
1634 hPtr = Tcl_NextHashEntry(&search)) {
1635 CmdFrame *cfPtr = (CmdFrame *)Tcl_GetHashValue(hPtr);
1636 Proc *procPtr = (Proc *) Tcl_GetHashKey(iPtr->linePBodyPtr, hPtr);
1637
1638 procPtr->iPtr = NULL;
1639 if (cfPtr) {
1640 if (cfPtr->type == TCL_LOCATION_SOURCE) {
1641 Tcl_DecrRefCount(cfPtr->data.eval.path);
1642 }
1643 ckfree(cfPtr->line);
1644 ckfree(cfPtr);
1645 }
1646 Tcl_DeleteHashEntry(hPtr);
1647 }
1648 Tcl_DeleteHashTable(iPtr->linePBodyPtr);
1649 ckfree(iPtr->linePBodyPtr);
1650 iPtr->linePBodyPtr = NULL;
1651
1652 /*
1653 * See also tclCompile.c, TclCleanupByteCode
1654 */
1655
1656 for (hPtr = Tcl_FirstHashEntry(iPtr->lineBCPtr, &search);
1657 hPtr != NULL;
1658 hPtr = Tcl_NextHashEntry(&search)) {
1659 ExtCmdLoc *eclPtr = (ExtCmdLoc *)Tcl_GetHashValue(hPtr);
1660
1661 if (eclPtr->type == TCL_LOCATION_SOURCE) {
1662 Tcl_DecrRefCount(eclPtr->path);
1663 }
1664 for (i=0; i<eclPtr->nuloc; i++) {
1665 ckfree(eclPtr->loc[i].line);
1666 }
1667
1668 if (eclPtr->loc != NULL) {
1669 ckfree(eclPtr->loc);
1670 }
1671
1672 ckfree(eclPtr);
1673 Tcl_DeleteHashEntry(hPtr);
1674 }
1675 Tcl_DeleteHashTable(iPtr->lineBCPtr);
1676 ckfree(iPtr->lineBCPtr);
1677 iPtr->lineBCPtr = NULL;
1678
1679 /*
1680 * Location stack for uplevel/eval/... scripts which were passed through
1681 * proc arguments. Actually we track all arguments as we do not and cannot
1682 * know which arguments will be used as scripts and which will not.
1683 */
1684
1685 if (iPtr->lineLAPtr->numEntries && !TclInExit()) {
1686 /*
1687 * When the interp goes away we have nothing on the stack, so there
1688 * are no arguments, so this table has to be empty.
1689 */
1690
1691 Tcl_Panic("Argument location tracking table not empty");
1692 }
1693
1694 Tcl_DeleteHashTable(iPtr->lineLAPtr);
1695 ckfree((char *)iPtr->lineLAPtr);
1696 iPtr->lineLAPtr = NULL;
1697
1698 if (iPtr->lineLABCPtr->numEntries && !TclInExit()) {
1699 /*
1700 * When the interp goes away we have nothing on the stack, so there
1701 * are no arguments, so this table has to be empty.
1702 */
1703
1704 Tcl_Panic("Argument location tracking table not empty");
1705 }
1706
1707 Tcl_DeleteHashTable(iPtr->lineLABCPtr);
1708 ckfree(iPtr->lineLABCPtr);
1709 iPtr->lineLABCPtr = NULL;
1710
1711 /*
1712 * Squelch the tables of traces on variables and searches over arrays in
1713 * the in the interpreter.
1714 */
1715
1716 Tcl_DeleteHashTable(&iPtr->varTraces);
1717 Tcl_DeleteHashTable(&iPtr->varSearches);
1718
1719 ckfree(iPtr);
1720 }
1721
1722 /*
1723 *---------------------------------------------------------------------------
1724 *
1725 * Tcl_HideCommand --
1726 *
1727 * Makes a command hidden so that it cannot be invoked from within an
1728 * interpreter, only from within an ancestor.
1729 *
1730 * Results:
1731 * A standard Tcl result; also leaves a message in the interp's result if
1732 * an error occurs.
1733 *
1734 * Side effects:
1735 * Removes a command from the command table and create an entry into the
1736 * hidden command table under the specified token name.
1737 *
1738 *---------------------------------------------------------------------------
1739 */
1740
1741 int
1742 Tcl_HideCommand(
1743 Tcl_Interp *interp, /* Interpreter in which to hide command. */
1744 const char *cmdName, /* Name of command to hide. */
1745 const char *hiddenCmdToken) /* Token name of the to-be-hidden command. */
1746 {
1747 Interp *iPtr = (Interp *) interp;
1748 Tcl_Command cmd;
1749 Command *cmdPtr;
1750 Tcl_HashTable *hiddenCmdTablePtr;
1751 Tcl_HashEntry *hPtr;
1752 int isNew;
1753
1754 if (iPtr->flags & DELETED) {
1755 /*
1756 * The interpreter is being deleted. Do not create any new structures,
1757 * because it is not safe to modify the interpreter.
1758 */
1759
1760 return TCL_ERROR;
1761 }
1762
1763 /*
1764 * Disallow hiding of commands that are currently in a namespace or
1765 * renaming (as part of hiding) into a namespace (because the current
1766 * implementation with a single global table and the needed uniqueness of
1767 * names cause problems with namespaces).
1768 *
1769 * We don't need to check for "::" in cmdName because the real check is on
1770 * the nsPtr below.
1771 *
1772 * hiddenCmdToken is just a string which is not interpreted in any way. It
1773 * may contain :: but the string is not interpreted as a namespace
1774 * qualifier command name. Thus, hiding foo::bar to foo::bar and then
1775 * trying to expose or invoke ::foo::bar will NOT work; but if the
1776 * application always uses the same strings it will get consistent
1777 * behaviour.
1778 *
1779 * But as we currently limit ourselves to the global namespace only for
1780 * the source, in order to avoid potential confusion, lets prevent "::" in
1781 * the token too. - dl
1782 */
1783
1784 if (strstr(hiddenCmdToken, "::") != NULL) {
1785 Tcl_SetObjResult(interp, Tcl_NewStringObj(
1786 "cannot use namespace qualifiers in hidden command"
1787 " token (rename)", -1));
1788 Tcl_SetErrorCode(interp, "TCL", "VALUE", "HIDDENTOKEN", (char *)NULL);
1789 return TCL_ERROR;
1790 }
1791
1792 /*
1793 * Find the command to hide. An error is returned if cmdName can't be
1794 * found. Look up the command only from the global namespace. Full path of
1795 * the command must be given if using namespaces.
1796 */
1797
1798 cmd = Tcl_FindCommand(interp, cmdName, NULL,
1799 /*flags*/ TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY);
1800 if (cmd == (Tcl_Command) NULL) {
1801 return TCL_ERROR;
1802 }
1803 cmdPtr = (Command *) cmd;
1804
1805 /*
1806 * Check that the command is really in global namespace
1807 */
1808
1809 if (cmdPtr->nsPtr != iPtr->globalNsPtr) {
1810 Tcl_SetObjResult(interp, Tcl_NewStringObj(
1811 "can only hide global namespace commands (use rename then hide)",
1812 -1));
1813 Tcl_SetErrorCode(interp, "TCL", "HIDE", "NON_GLOBAL", (char *)NULL);
1814 return TCL_ERROR;
1815 }
1816
1817 /*
1818 * Initialize the hidden command table if necessary.
1819 */
1820
1821 hiddenCmdTablePtr = iPtr->hiddenCmdTablePtr;
1822 if (hiddenCmdTablePtr == NULL) {
1823 hiddenCmdTablePtr = (Tcl_HashTable *)ckalloc(sizeof(Tcl_HashTable));
1824 Tcl_InitHashTable(hiddenCmdTablePtr, TCL_STRING_KEYS);
1825 iPtr->hiddenCmdTablePtr = hiddenCmdTablePtr;
1826 }
1827
1828 /*
1829 * It is an error to move an exposed command to a hidden command with
1830 * hiddenCmdToken if a hidden command with the name hiddenCmdToken already
1831 * exists.
1832 */
1833
1834 hPtr = Tcl_CreateHashEntry(hiddenCmdTablePtr, hiddenCmdToken, &isNew);
1835 if (!isNew) {
1836 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1837 "hidden command named \"%s\" already exists",
1838 hiddenCmdToken));
1839 Tcl_SetErrorCode(interp, "TCL", "HIDE", "ALREADY_HIDDEN", (char *)NULL);
1840 return TCL_ERROR;
1841 }
1842
1843 /*
1844 * NB: This code is currently 'like' a rename to a special separate name
1845 * table. Changes here and in TclRenameCommand must be kept in synch until
1846 * the common parts are actually factorized out.
1847 */
1848
1849 /*
1850 * Remove the hash entry for the command from the interpreter command
1851 * table. This is like deleting the command, so bump its command epoch
1852 * to invalidate any cached references that point to the command.
1853 */
1854
1855 if (cmdPtr->hPtr != NULL) {
1856 Tcl_DeleteHashEntry(cmdPtr->hPtr);
1857 cmdPtr->hPtr = NULL;
1858 cmdPtr->cmdEpoch++;
1859 }
1860
1861 /*
1862 * The list of command exported from the namespace might have changed.
1863 * However, we do not need to recompute this just yet; next time we need
1864 * the info will be soon enough.
1865 */
1866
1867 TclInvalidateNsCmdLookup(cmdPtr->nsPtr);
1868
1869 /*
1870 * Now link the hash table entry with the command structure. We ensured
1871 * above that the nsPtr was right.
1872 */
1873
1874 cmdPtr->hPtr = hPtr;
1875 Tcl_SetHashValue(hPtr, cmdPtr);
1876
1877 /*
1878 * If the command being hidden has a compile function, increment the
1879 * interpreter's compileEpoch to invalidate its compiled code. This makes
1880 * sure that we don't later try to execute old code compiled with
1881 * command-specific (i.e., inline) bytecodes for the now-hidden command.
1882 * This field is checked in Tcl_EvalObj and ObjInterpProc, and code whose
1883 * compilation epoch doesn't match is recompiled.
1884 */
1885
1886 if (cmdPtr->compileProc != NULL) {
1887 iPtr->compileEpoch++;
1888 }
1889 return TCL_OK;
1890 }
1891
1892 /*
1893 *----------------------------------------------------------------------
1894 *
1895 * Tcl_ExposeCommand --
1896 *
1897 * Makes a previously hidden command callable from inside the interpreter
1898 * instead of only by its ancestors.
1899 *
1900 * Results:
1901 * A standard Tcl result. If an error occurs, a message is left in the
1902 * interp's result.
1903 *
1904 * Side effects:
1905 * Moves commands from one hash table to another.
1906 *
1907 *----------------------------------------------------------------------
1908 */
1909
1910 int
1911 Tcl_ExposeCommand(
1912 Tcl_Interp *interp, /* Interpreter in which to make command
1913 * callable. */
1914 const char *hiddenCmdToken, /* Name of hidden command. */
1915 const char *cmdName) /* Name of to-be-exposed command. */
1916 {
1917 Interp *iPtr = (Interp *) interp;
1918 Command *cmdPtr;
1919 Namespace *nsPtr;
1920 Tcl_HashEntry *hPtr;
1921 Tcl_HashTable *hiddenCmdTablePtr;
1922 int isNew;
1923
1924 if (iPtr->flags & DELETED) {
1925 /*
1926 * The interpreter is being deleted. Do not create any new structures,
1927 * because it is not safe to modify the interpreter.
1928 */
1929
1930 return TCL_ERROR;
1931 }
1932
1933 /*
1934 * Check that we have a regular name for the command (that the user is not
1935 * trying to do an expose and a rename (to another namespace) at the same
1936 * time).
1937 */
1938
1939 if (strstr(cmdName, "::") != NULL) {
1940 Tcl_SetObjResult(interp, Tcl_NewStringObj(
1941 "cannot expose to a namespace (use expose to toplevel, then rename)",
1942 -1));
1943 Tcl_SetErrorCode(interp, "TCL", "EXPOSE", "NON_GLOBAL", (char *)NULL);
1944 return TCL_ERROR;
1945 }
1946
1947 /*
1948 * Get the command from the hidden command table:
1949 */
1950
1951 hPtr = NULL;
1952 hiddenCmdTablePtr = iPtr->hiddenCmdTablePtr;
1953 if (hiddenCmdTablePtr != NULL) {
1954 hPtr = Tcl_FindHashEntry(hiddenCmdTablePtr, hiddenCmdToken);
1955 }
1956 if (hPtr == NULL) {
1957 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1958 "unknown hidden command \"%s\"", hiddenCmdToken));
1959 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "HIDDENTOKEN",
1960 hiddenCmdToken, (char *)NULL);
1961 return TCL_ERROR;
1962 }
1963 cmdPtr = (Command *)Tcl_GetHashValue(hPtr);
1964
1965 /*
1966 * Check that we have a true global namespace command (enforced by
1967 * Tcl_HideCommand but let's double check. (If it was not, we would not
1968 * really know how to handle it).
1969 */
1970
1971 if (cmdPtr->nsPtr != iPtr->globalNsPtr) {
1972 /*
1973 * This case is theoretically impossible, we might rather Tcl_Panic
1974 * than 'nicely' erroring out ?
1975 */
1976
1977 Tcl_SetObjResult(interp, Tcl_NewStringObj(
1978 "trying to expose a non-global command namespace command",
1979 -1));
1980 return TCL_ERROR;
1981 }
1982
1983 /*
1984 * This is the global table.
1985 */
1986
1987 nsPtr = cmdPtr->nsPtr;
1988
1989 /*
1990 * It is an error to overwrite an existing exposed command as a result of
1991 * exposing a previously hidden command.
1992 */
1993
1994 hPtr = Tcl_CreateHashEntry(&nsPtr->cmdTable, cmdName, &isNew);
1995 if (!isNew) {
1996 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1997 "exposed command \"%s\" already exists", cmdName));
1998 Tcl_SetErrorCode(interp, "TCL", "EXPOSE", "COMMAND_EXISTS", (char *)NULL);
1999 return TCL_ERROR;
2000 }
2001
2002 /*
2003 * Command resolvers (per-interp, per-namespace) might have resolved to a
2004 * command for the given namespace scope with this command not being
2005 * registered with the namespace's command table. During BC compilation,
2006 * the so-resolved command turns into a CmdName literal. Without
2007 * invalidating a possible CmdName literal here explicitly, such literals
2008 * keep being reused while pointing to overhauled commands.
2009 */
2010
2011 TclInvalidateCmdLiteral(interp, cmdName, nsPtr);
2012
2013 /*
2014 * The list of command exported from the namespace might have changed.
2015 * However, we do not need to recompute this just yet; next time we need
2016 * the info will be soon enough.
2017 */
2018
2019 TclInvalidateNsCmdLookup(nsPtr);
2020
2021 /*
2022 * Remove the hash entry for the command from the interpreter hidden
2023 * command table.
2024 */
2025
2026 if (cmdPtr->hPtr != NULL) {
2027 Tcl_DeleteHashEntry(cmdPtr->hPtr);
2028 cmdPtr->hPtr = NULL;
2029 }
2030
2031 /*
2032 * Now link the hash table entry with the command structure. This is like
2033 * creating a new command, so deal with any shadowing of commands in the
2034 * global namespace.
2035 */
2036
2037 cmdPtr->hPtr = hPtr;
2038
2039 Tcl_SetHashValue(hPtr, cmdPtr);
2040
2041 /*
2042 * Not needed as we are only in the global namespace (but would be needed
2043 * again if we supported namespace command hiding)
2044 *
2045 * TclResetShadowedCmdRefs(interp, cmdPtr);
2046 */
2047
2048 /*
2049 * If the command being exposed has a compile function, increment
2050 * interpreter's compileEpoch to invalidate its compiled code. This makes
2051 * sure that we don't later try to execute old code compiled assuming the
2052 * command is hidden. This field is checked in Tcl_EvalObj and
2053 * ObjInterpProc, and code whose compilation epoch doesn't match is
2054 * recompiled.
2055 */
2056
2057 if (cmdPtr->compileProc != NULL) {
2058 iPtr->compileEpoch++;
2059 }
2060 return TCL_OK;
2061 }
2062
2063 /*
2064 *----------------------------------------------------------------------
2065 *
2066 * Tcl_CreateCommand --
2067 *
2068 * Define a new command in a command table.
2069 *
2070 * Results:
2071 * The return value is a token for the command, which can be used in
2072 * future calls to Tcl_GetCommandName.
2073 *
2074 * Side effects:
2075 * If a command named cmdName already exists for interp, it is deleted.
2076 * In the future, when cmdName is seen as the name of a command by
2077 * Tcl_Eval, proc will be called. To support the bytecode interpreter,
2078 * the command is created with a wrapper Tcl_ObjCmdProc
2079 * (TclInvokeStringCommand) that eventually calls proc. When the command
2080 * is deleted from the table, deleteProc will be called. See the manual
2081 * entry for details on the calling sequence.
2082 *
2083 *----------------------------------------------------------------------
2084 */
2085
2086 Tcl_Command
2087 Tcl_CreateCommand(
2088 Tcl_Interp *interp, /* Token for command interpreter returned by a
2089 * previous call to Tcl_CreateInterp. */
2090 const char *cmdName, /* Name of command. If it contains namespace
2091 * qualifiers, the new command is put in the
2092 * specified namespace; otherwise it is put in
2093 * the global namespace. */
2094 Tcl_CmdProc *proc, /* Function to associate with cmdName. */
2095 ClientData clientData, /* Arbitrary value passed to string proc. */
2096 Tcl_CmdDeleteProc *deleteProc)
2097 /* If not NULL, gives a function to call when
2098 * this command is deleted. */
2099 {
2100 Interp *iPtr = (Interp *) interp;
2101 ImportRef *oldRefPtr = NULL;
2102 Namespace *nsPtr;
2103 Command *cmdPtr;
2104 Tcl_HashEntry *hPtr;
2105 const char *tail;
2106 int isNew = 0, deleted = 0;
2107 ImportedCmdData *dataPtr;
2108
2109 if (iPtr->flags & DELETED) {
2110 /*
2111 * The interpreter is being deleted. Don't create any new commands;
2112 * it's not safe to muck with the interpreter anymore.
2113 */
2114
2115 return (Tcl_Command) NULL;
2116 }
2117
2118 /*
2119 * If the command name we seek to create already exists, we need to
2120 * delete that first. That can be tricky in the presence of traces.
2121 * Loop until we no longer find an existing command in the way, or
2122 * until we've deleted one command and that didn't finish the job.
2123 */
2124
2125 while (1) {
2126 /*
2127 * Determine where the command should reside. If its name contains
2128 * namespace qualifiers, we put it in the specified namespace;
2129 * otherwise, we always put it in the global namespace.
2130 */
2131
2132 if (strstr(cmdName, "::") != NULL) {
2133 Namespace *dummy1, *dummy2;
2134
2135 TclGetNamespaceForQualName(interp, cmdName, NULL,
2136 TCL_CREATE_NS_IF_UNKNOWN, &nsPtr, &dummy1, &dummy2, &tail);
2137 if ((nsPtr == NULL) || (tail == NULL)) {
2138 return (Tcl_Command) NULL;
2139 }
2140 } else {
2141 nsPtr = iPtr->globalNsPtr;
2142 tail = cmdName;
2143 }
2144
2145 hPtr = Tcl_CreateHashEntry(&nsPtr->cmdTable, tail, &isNew);
2146
2147 if (isNew || deleted) {
2148 /*
2149 * isNew - No conflict with existing command.
2150 * deleted - We've already deleted a conflicting command
2151 */
2152 break;
2153 }
2154
2155 /*
2156 * An existing command conflicts. Try to delete it...
2157 */
2158
2159 cmdPtr = (Command *)Tcl_GetHashValue(hPtr);
2160
2161 /*
2162 * Be careful to preserve any existing import links so we can restore
2163 * them down below. That way, you can redefine a command and its
2164 * import status will remain intact.
2165 */
2166
2167 cmdPtr->refCount++;
2168 if (cmdPtr->importRefPtr) {
2169 cmdPtr->flags |= CMD_REDEF_IN_PROGRESS;
2170 }
2171
2172 Tcl_DeleteCommandFromToken(interp, (Tcl_Command) cmdPtr);
2173
2174 if (cmdPtr->flags & CMD_REDEF_IN_PROGRESS) {
2175 oldRefPtr = cmdPtr->importRefPtr;
2176 cmdPtr->importRefPtr = NULL;
2177 }
2178 TclCleanupCommandMacro(cmdPtr);
2179 deleted = 1;
2180 }
2181
2182 if (!isNew) {
2183 /*
2184 * If the deletion callback recreated the command, just throw away the
2185 * new command (if we try to delete it again, we could get stuck in an
2186 * infinite loop).
2187 */
2188
2189 ckfree(Tcl_GetHashValue(hPtr));
2190 }
2191
2192 if (!deleted) {
2193 /*
2194 * Command resolvers (per-interp, per-namespace) might have resolved
2195 * to a command for the given namespace scope with this command not
2196 * being registered with the namespace's command table. During BC
2197 * compilation, the so-resolved command turns into a CmdName literal.
2198 * Without invalidating a possible CmdName literal here explicitly,
2199 * such literals keep being reused while pointing to overhauled
2200 * commands.
2201 */
2202
2203 TclInvalidateCmdLiteral(interp, tail, nsPtr);
2204
2205 /*
2206 * The list of command exported from the namespace might have changed.
2207 * However, we do not need to recompute this just yet; next time we
2208 * need the info will be soon enough.
2209 */
2210
2211 TclInvalidateNsCmdLookup(nsPtr);
2212 TclInvalidateNsPath(nsPtr);
2213 }
2214 cmdPtr = (Command *)ckalloc(sizeof(Command));
2215 Tcl_SetHashValue(hPtr, cmdPtr);
2216 cmdPtr->hPtr = hPtr;
2217 cmdPtr->nsPtr = nsPtr;
2218 cmdPtr->refCount = 1;
2219 cmdPtr->cmdEpoch = 0;
2220 cmdPtr->compileProc = NULL;
2221 cmdPtr->objProc = TclInvokeStringCommand;
2222 cmdPtr->objClientData = cmdPtr;
2223 cmdPtr->proc = proc;
2224 cmdPtr->clientData = clientData;
2225 cmdPtr->deleteProc = deleteProc;
2226 cmdPtr->deleteData = clientData;
2227 cmdPtr->flags = 0;
2228 cmdPtr->importRefPtr = NULL;
2229 cmdPtr->tracePtr = NULL;
2230 cmdPtr->nreProc = NULL;
2231
2232 /*
2233 * Plug in any existing import references found above. Be sure to update
2234 * all of these references to point to the new command.
2235 */
2236
2237 if (oldRefPtr != NULL) {
2238 cmdPtr->importRefPtr = oldRefPtr;
2239 while (oldRefPtr != NULL) {
2240 Command *refCmdPtr = oldRefPtr->importedCmdPtr;
2241 dataPtr = (ImportedCmdData *)refCmdPtr->objClientData;
2242 dataPtr->realCmdPtr = cmdPtr;
2243 oldRefPtr = oldRefPtr->nextPtr;
2244 }
2245 }
2246
2247 /*
2248 * We just created a command, so in its namespace and all of its parent
2249 * namespaces, it may shadow global commands with the same name. If any
2250 * shadowed commands are found, invalidate all cached command references
2251 * in the affected namespaces.
2252 */
2253
2254 TclResetShadowedCmdRefs(interp, cmdPtr);
2255 return (Tcl_Command) cmdPtr;
2256 }
2257
2258 /*
2259 *----------------------------------------------------------------------
2260 *
2261 * Tcl_CreateObjCommand --
2262 *
2263 * Define a new object-based command in a command table.
2264 *
2265 * Results:
2266 * The return value is a token for the command, which can be used in
2267 * future calls to Tcl_GetCommandName.
2268 *
2269 * Side effects:
2270 * If a command named "cmdName" already exists for interp, it is
2271 * first deleted. Then the new command is created from the arguments.
2272 * [***] (See below for exception).
2273 *
2274 * In the future, during bytecode evaluation when "cmdName" is seen as
2275 * the name of a command by Tcl_EvalObj or Tcl_Eval, the object-based
2276 * Tcl_ObjCmdProc proc will be called. When the command is deleted from
2277 * the table, deleteProc will be called. See the manual entry for details
2278 * on the calling sequence.
2279 *
2280 *----------------------------------------------------------------------
2281 */
2282
2283 Tcl_Command
2284 Tcl_CreateObjCommand(
2285 Tcl_Interp *interp, /* Token for command interpreter (returned by
2286 * previous call to Tcl_CreateInterp). */
2287 const char *cmdName, /* Name of command. If it contains namespace
2288 * qualifiers, the new command is put in the
2289 * specified namespace; otherwise it is put in
2290 * the global namespace. */
2291 Tcl_ObjCmdProc *proc, /* Object-based function to associate with
2292 * name. */
2293 ClientData clientData, /* Arbitrary value to pass to object
2294 * function. */
2295 Tcl_CmdDeleteProc *deleteProc)
2296 /* If not NULL, gives a function to call when
2297 * this command is deleted. */
2298 {
2299 Interp *iPtr = (Interp *) interp;
2300 Namespace *nsPtr;
2301 const char *tail;
2302
2303 if (iPtr->flags & DELETED) {
2304 /*
2305 * The interpreter is being deleted. Don't create any new commands;
2306 * it's not safe to muck with the interpreter anymore.
2307 */
2308 return (Tcl_Command) NULL;
2309 }
2310
2311 /*
2312 * Determine where the command should reside. If its name contains
2313 * namespace qualifiers, we put it in the specified namespace;
2314 * otherwise, we always put it in the global namespace.
2315 */
2316
2317 if (strstr(cmdName, "::") != NULL) {
2318 Namespace *dummy1, *dummy2;
2319
2320 TclGetNamespaceForQualName(interp, cmdName, NULL,
2321 TCL_CREATE_NS_IF_UNKNOWN, &nsPtr, &dummy1, &dummy2, &tail);
2322 if ((nsPtr == NULL) || (tail == NULL)) {
2323 return (Tcl_Command) NULL;
2324 }
2325 } else {
2326 nsPtr = iPtr->globalNsPtr;
2327 tail = cmdName;
2328 }
2329
2330 return TclCreateObjCommandInNs(interp, tail, (Tcl_Namespace *) nsPtr,
2331 proc, clientData, deleteProc);
2332 }
2333
2334 Tcl_Command
2335 TclCreateObjCommandInNs(
2336 Tcl_Interp *interp,
2337 const char *cmdName, /* Name of command, without any namespace
2338 * components. */
2339 Tcl_Namespace *namesp, /* The namespace to create the command in */
2340 Tcl_ObjCmdProc *proc, /* Object-based function to associate with
2341 * name. */
2342 ClientData clientData, /* Arbitrary value to pass to object
2343 * function. */
2344 Tcl_CmdDeleteProc *deleteProc)
2345 /* If not NULL, gives a function to call when
2346 * this command is deleted. */
2347 {
2348 int deleted = 0, isNew = 0;
2349 Command *cmdPtr;
2350 ImportRef *oldRefPtr = NULL;
2351 ImportedCmdData *dataPtr;
2352 Tcl_HashEntry *hPtr;
2353 Namespace *nsPtr = (Namespace *) namesp;
2354
2355 /*
2356 * If the command name we seek to create already exists, we need to delete
2357 * that first. That can be tricky in the presence of traces. Loop until we
2358 * no longer find an existing command in the way, or until we've deleted
2359 * one command and that didn't finish the job.
2360 */
2361
2362 while (1) {
2363 hPtr = Tcl_CreateHashEntry(&nsPtr->cmdTable, cmdName, &isNew);
2364
2365 if (isNew || deleted) {
2366 /*
2367 * isNew - No conflict with existing command.
2368 * deleted - We've already deleted a conflicting command
2369 */
2370 break;
2371 }
2372
2373 /*
2374 * An existing command conflicts. Try to delete it...
2375 */
2376
2377 cmdPtr = (Command *)Tcl_GetHashValue(hPtr);
2378
2379 /*
2380 * [***] This is wrong. See Tcl Bug a16752c252.
2381 * However, this buggy behavior is kept under particular circumstances
2382 * to accommodate deployed binaries of the "tclcompiler" program
2383 * <http://sourceforge.net/projects/tclpro/> that crash if the bug is
2384 * fixed.
2385 */
2386
2387 if (cmdPtr->objProc == TclInvokeStringCommand
2388 && cmdPtr->clientData == clientData
2389 && cmdPtr->deleteData == clientData
2390 && cmdPtr->deleteProc == deleteProc) {
2391 cmdPtr->objProc = proc;
2392 cmdPtr->objClientData = clientData;
2393 return (Tcl_Command)cmdPtr;
2394 }
2395
2396 /*
2397 * Otherwise, we delete the old command. Be careful to preserve any
2398 * existing import links so we can restore them down below. That way,
2399 * you can redefine a command and its import status will remain
2400 * intact.
2401 */
2402
2403 cmdPtr->refCount++;
2404 if (cmdPtr->importRefPtr) {
2405 cmdPtr->flags |= CMD_REDEF_IN_PROGRESS;
2406 }
2407
2408 /*
2409 * Make sure namespace doesn't get deallocated.
2410 */
2411
2412 cmdPtr->nsPtr->refCount++;
2413
2414 Tcl_DeleteCommandFromToken(interp, (Tcl_Command) cmdPtr);
2415 nsPtr = (Namespace *) TclEnsureNamespace(interp,
2416 (Tcl_Namespace *) cmdPtr->nsPtr);
2417 /* Note nsPtr may or may not be same as cmdPtr->nsPtr */
2418 TclNsDecrRefCount(cmdPtr->nsPtr);
2419
2420 if (cmdPtr->flags & CMD_REDEF_IN_PROGRESS) {
2421 oldRefPtr = cmdPtr->importRefPtr;
2422 cmdPtr->importRefPtr = NULL;
2423 }
2424 TclCleanupCommandMacro(cmdPtr);
2425 deleted = 1;
2426 }
2427 if (!isNew) {
2428 /*
2429 * If the deletion callback recreated the command, just throw away the
2430 * new command (if we try to delete it again, we could get stuck in an
2431 * infinite loop).
2432 */
2433
2434 ckfree(Tcl_GetHashValue(hPtr));
2435 }
2436
2437 if (!deleted) {
2438 /*
2439 * Command resolvers (per-interp, per-namespace) might have resolved
2440 * to a command for the given namespace scope with this command not
2441 * being registered with the namespace's command table. During BC
2442 * compilation, the so-resolved command turns into a CmdName literal.
2443 * Without invalidating a possible CmdName literal here explicitly,
2444 * such literals keep being reused while pointing to overhauled
2445 * commands.
2446 */
2447
2448 TclInvalidateCmdLiteral(interp, cmdName, nsPtr);
2449
2450 /*
2451 * The list of command exported from the namespace might have changed.
2452 * However, we do not need to recompute this just yet; next time we
2453 * need the info will be soon enough.
2454 */
2455
2456 TclInvalidateNsCmdLookup(nsPtr);
2457 TclInvalidateNsPath(nsPtr);
2458 }
2459 cmdPtr = (Command *)ckalloc(sizeof(Command));
2460 Tcl_SetHashValue(hPtr, cmdPtr);
2461 cmdPtr->hPtr = hPtr;
2462 cmdPtr->nsPtr = nsPtr;
2463 cmdPtr->refCount = 1;
2464 cmdPtr->cmdEpoch = 0;
2465 cmdPtr->compileProc = NULL;
2466 cmdPtr->objProc = proc;
2467 cmdPtr->objClientData = clientData;
2468 cmdPtr->proc = TclInvokeObjectCommand;
2469 cmdPtr->clientData = cmdPtr;
2470 cmdPtr->deleteProc = deleteProc;
2471 cmdPtr->deleteData = clientData;
2472 cmdPtr->flags = 0;
2473 cmdPtr->importRefPtr = NULL;
2474 cmdPtr->tracePtr = NULL;
2475 cmdPtr->nreProc = NULL;
2476
2477 /*
2478 * Plug in any existing import references found above. Be sure to update
2479 * all of these references to point to the new command.
2480 */
2481
2482 if (oldRefPtr != NULL) {
2483 cmdPtr->importRefPtr = oldRefPtr;
2484 while (oldRefPtr != NULL) {
2485 Command *refCmdPtr = oldRefPtr->importedCmdPtr;
2486
2487 dataPtr = (ImportedCmdData*)refCmdPtr->objClientData;
2488 dataPtr->realCmdPtr = cmdPtr;
2489 oldRefPtr = oldRefPtr->nextPtr;
2490 }
2491 }
2492
2493 /*
2494 * We just created a command, so in its namespace and all of its parent
2495 * namespaces, it may shadow global commands with the same name. If any
2496 * shadowed commands are found, invalidate all cached command references
2497 * in the affected namespaces.
2498 */
2499
2500 TclResetShadowedCmdRefs(interp, cmdPtr);
2501 return (Tcl_Command) cmdPtr;
2502 }
2503
2504 /*
2505 *----------------------------------------------------------------------
2506 *
2507 * TclInvokeStringCommand --
2508 *
2509 * "Wrapper" Tcl_ObjCmdProc used to call an existing string-based
2510 * Tcl_CmdProc if no object-based function exists for a command. A
2511 * pointer to this function is stored as the Tcl_ObjCmdProc in a Command
2512 * structure. It simply turns around and calls the string Tcl_CmdProc in
2513 * the Command structure.
2514 *
2515 * Results:
2516 * A standard Tcl object result value.
2517 *
2518 * Side effects:
2519 * Besides those side effects of the called Tcl_CmdProc,
2520 * TclInvokeStringCommand allocates and frees storage.
2521 *
2522 *----------------------------------------------------------------------
2523 */
2524
2525 int
2526 TclInvokeStringCommand(
2527 ClientData clientData, /* Points to command's Command structure. */
2528 Tcl_Interp *interp, /* Current interpreter. */
2529 int objc, /* Number of arguments. */
2530 Tcl_Obj *const objv[]) /* Argument objects. */
2531 {
2532 Command *cmdPtr = (Command *)clientData;
2533 int i, result;
2534 const char **argv = (const char **)
2535 TclStackAlloc(interp, (objc + 1) * sizeof(char *));
2536
2537 for (i = 0; i < objc; i++) {
2538 argv[i] = TclGetString(objv[i]);
2539 }
2540 argv[objc] = 0;
2541
2542 /*
2543 * Invoke the command's string-based Tcl_CmdProc.
2544 */
2545
2546 result = cmdPtr->proc(cmdPtr->clientData, interp, objc, argv);
2547
2548 TclStackFree(interp, (void *) argv);
2549 return result;
2550 }
2551
2552 /*
2553 *----------------------------------------------------------------------
2554 *
2555 * TclInvokeObjectCommand --
2556 *
2557 * "Wrapper" Tcl_CmdProc used to call an existing object-based
2558 * Tcl_ObjCmdProc if no string-based function exists for a command. A
2559 * pointer to this function is stored as the Tcl_CmdProc in a Command
2560 * structure. It simply turns around and calls the object Tcl_ObjCmdProc
2561 * in the Command structure.
2562 *
2563 * Results:
2564 * A standard Tcl result value.
2565 *
2566 * Side effects:
2567 * Besides those side effects of the called Tcl_ObjCmdProc,
2568 * TclInvokeObjectCommand allocates and frees storage.
2569 *
2570 *----------------------------------------------------------------------
2571 */
2572
2573 int
2574 TclInvokeObjectCommand(
2575 ClientData clientData, /* Points to command's Command structure. */
2576 Tcl_Interp *interp, /* Current interpreter. */
2577 int argc, /* Number of arguments. */
2578 const char **argv) /* Argument strings. */
2579 {
2580 Command *cmdPtr = ( Command *) clientData;
2581 Tcl_Obj *objPtr;
2582 int i, length, result;
2583 Tcl_Obj **objv = (Tcl_Obj **)
2584 TclStackAlloc(interp, (argc * sizeof(Tcl_Obj *)));
2585
2586 for (i = 0; i < argc; i++) {
2587 length = strlen(argv[i]);
2588 TclNewStringObj(objPtr, argv[i], length);
2589 Tcl_IncrRefCount(objPtr);
2590 objv[i] = objPtr;
2591 }
2592
2593 /*
2594 * Invoke the command's object-based Tcl_ObjCmdProc.
2595 */
2596
2597 if (cmdPtr->objProc != NULL) {
2598 result = cmdPtr->objProc(cmdPtr->objClientData, interp, argc, objv);
2599 } else {
2600 result = Tcl_NRCallObjProc(interp, cmdPtr->nreProc,
2601 cmdPtr->objClientData, argc, objv);
2602 }
2603
2604 /*
2605 * Move the interpreter's object result to the string result, then reset
2606 * the object result.
2607 */
2608
2609 (void) Tcl_GetStringResult(interp);
2610
2611 /*
2612 * Decrement the ref counts for the argument objects created above, then
2613 * free the objv array if malloc'ed storage was used.
2614 */
2615
2616 for (i = 0; i < argc; i++) {
2617 objPtr = objv[i];
2618 Tcl_DecrRefCount(objPtr);
2619 }
2620 TclStackFree(interp, objv);
2621 return result;
2622 }
2623
2624 /*
2625 *----------------------------------------------------------------------
2626 *
2627 * TclRenameCommand --
2628 *
2629 * Called to give an existing Tcl command a different name. Both the old
2630 * command name and the new command name can have "::" namespace
2631 * qualifiers. If the new command has a different namespace context, the
2632 * command will be moved to that namespace and will execute in the
2633 * context of that new namespace.
2634 *
2635 * If the new command name is NULL or the null string, the command is
2636 * deleted.
2637 *
2638 * Results:
2639 * Returns TCL_OK if successful, and TCL_ERROR if anything goes wrong.
2640 *
2641 * Side effects:
2642 * If anything goes wrong, an error message is returned in the
2643 * interpreter's result object.
2644 *
2645 *----------------------------------------------------------------------
2646 */
2647
2648 int
2649 TclRenameCommand(
2650 Tcl_Interp *interp, /* Current interpreter. */
2651 const char *oldName, /* Existing command name. */
2652 const char *newName) /* New command name. */
2653 {
2654 Interp *iPtr = (Interp *) interp;
2655 const char *newTail;
2656 Namespace *cmdNsPtr, *newNsPtr, *dummy1, *dummy2;
2657 Tcl_Command cmd;
2658 Command *cmdPtr;
2659 Tcl_HashEntry *hPtr, *oldHPtr;
2660 int isNew, result;
2661 Tcl_Obj *oldFullName;
2662 Tcl_DString newFullName;
2663
2664 /*
2665 * Find the existing command. An error is returned if cmdName can't be
2666 * found.
2667 */
2668
2669 cmd = Tcl_FindCommand(interp, oldName, NULL, /*flags*/ 0);
2670 cmdPtr = (Command *) cmd;
2671 if (cmdPtr == NULL) {
2672 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2673 "can't %s \"%s\": command doesn't exist",
2674 ((newName == NULL) || (*newName == '\0')) ? "delete" : "rename",
2675 oldName));
2676 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "COMMAND", oldName, (char *)NULL);
2677 return TCL_ERROR;
2678 }
2679
2680 /*
2681 * If the new command name is NULL or empty, delete the command. Do this
2682 * with Tcl_DeleteCommandFromToken, since we already have the command.
2683 */
2684
2685 if ((newName == NULL) || (*newName == '\0')) {
2686 Tcl_DeleteCommandFromToken(interp, cmd);
2687 return TCL_OK;
2688 }
2689
2690 cmdNsPtr = cmdPtr->nsPtr;
2691 TclNewObj(oldFullName);
2692 Tcl_IncrRefCount(oldFullName);
2693 Tcl_GetCommandFullName(interp, cmd, oldFullName);
2694
2695 /*
2696 * Make sure that the destination command does not already exist. The
2697 * rename operation is like creating a command, so we should automatically
2698 * create the containing namespaces just like Tcl_CreateCommand would.
2699 */
2700
2701 TclGetNamespaceForQualName(interp, newName, NULL,
2702 TCL_CREATE_NS_IF_UNKNOWN, &newNsPtr, &dummy1, &dummy2, &newTail);
2703
2704 if ((newNsPtr == NULL) || (newTail == NULL)) {
2705 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2706 "can't rename to \"%s\": bad command name", newName));
2707 Tcl_SetErrorCode(interp, "TCL", "VALUE", "COMMAND", (char *)NULL);
2708 result = TCL_ERROR;
2709 goto done;
2710 }
2711 if (Tcl_FindHashEntry(&newNsPtr->cmdTable, newTail) != NULL) {
2712 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2713 "can't rename to \"%s\": command already exists", newName));
2714 Tcl_SetErrorCode(interp, "TCL", "OPERATION", "RENAME",
2715 "TARGET_EXISTS", (char *)NULL);
2716 result = TCL_ERROR;
2717 goto done;
2718 }
2719
2720 /*
2721 * Warning: any changes done in the code here are likely to be needed in
2722 * Tcl_HideCommand code too (until the common parts are extracted out).
2723 * - dl
2724 */
2725
2726 /*
2727 * Put the command in the new namespace so we can check for an alias loop.
2728 * Since we are adding a new command to a namespace, we must handle any
2729 * shadowing of the global commands that this might create.
2730 */
2731
2732 oldHPtr = cmdPtr->hPtr;
2733 hPtr = Tcl_CreateHashEntry(&newNsPtr->cmdTable, newTail, &isNew);
2734 Tcl_SetHashValue(hPtr, cmdPtr);
2735 cmdPtr->hPtr = hPtr;
2736 cmdPtr->nsPtr = newNsPtr;
2737 TclResetShadowedCmdRefs(interp, cmdPtr);
2738
2739 /*
2740 * Now check for an alias loop. If we detect one, put everything back the
2741 * way it was and report the error.
2742 */
2743
2744 result = TclPreventAliasLoop(interp, interp, (Tcl_Command) cmdPtr);
2745 if (result != TCL_OK) {
2746 Tcl_DeleteHashEntry(cmdPtr->hPtr);
2747 cmdPtr->hPtr = oldHPtr;
2748 cmdPtr->nsPtr = cmdNsPtr;
2749 goto done;
2750 }
2751
2752 /*
2753 * The list of command exported from the namespace might have changed.
2754 * However, we do not need to recompute this just yet; next time we need
2755 * the info will be soon enough. These might refer to the same variable,
2756 * but that's no big deal.
2757 */
2758
2759 TclInvalidateNsCmdLookup(cmdNsPtr);
2760 TclInvalidateNsCmdLookup(cmdPtr->nsPtr);
2761
2762 /*
2763 * Command resolvers (per-interp, per-namespace) might have resolved to a
2764 * command for the given namespace scope with this command not being
2765 * registered with the namespace's command table. During BC compilation,
2766 * the so-resolved command turns into a CmdName literal. Without
2767 * invalidating a possible CmdName literal here explicitly, such literals
2768 * keep being reused while pointing to overhauled commands.
2769 */
2770
2771 TclInvalidateCmdLiteral(interp, newTail, cmdPtr->nsPtr);
2772
2773 /*
2774 * Script for rename traces can delete the command "oldName". Therefore
2775 * increment the reference count for cmdPtr so that it's Command structure
2776 * is freed only towards the end of this function by calling
2777 * TclCleanupCommand.
2778 *
2779 * The trace function needs to get a fully qualified name for old and new
2780 * commands [Tcl bug #651271], or else there's no way for the trace
2781 * function to get the namespace from which the old command is being
2782 * renamed!
2783 */
2784
2785 Tcl_DStringInit(&newFullName);
2786 Tcl_DStringAppend(&newFullName, newNsPtr->fullName, -1);
2787 if (newNsPtr != iPtr->globalNsPtr) {
2788 TclDStringAppendLiteral(&newFullName, "::");
2789 }
2790 Tcl_DStringAppend(&newFullName, newTail, -1);
2791 cmdPtr->refCount++;
2792 CallCommandTraces(iPtr, cmdPtr, TclGetString(oldFullName),
2793 Tcl_DStringValue(&newFullName), TCL_TRACE_RENAME);
2794 Tcl_DStringFree(&newFullName);
2795
2796 /*
2797 * The new command name is okay, so remove the command from its current
2798 * namespace. This is like deleting the command, so bump the cmdEpoch to
2799 * invalidate any cached references to the command.
2800 */
2801
2802 Tcl_DeleteHashEntry(oldHPtr);
2803 cmdPtr->cmdEpoch++;
2804
2805 /*
2806 * If the command being renamed has a compile function, increment the
2807 * interpreter's compileEpoch to invalidate its compiled code. This makes
2808 * sure that we don't later try to execute old code compiled for the
2809 * now-renamed command.
2810 */
2811
2812 if (cmdPtr->compileProc != NULL) {
2813 iPtr->compileEpoch++;
2814 }
2815
2816 /*
2817 * Now free the Command structure, if the "oldName" command has been
2818 * deleted by invocation of rename traces.
2819 */
2820
2821 TclCleanupCommandMacro(cmdPtr);
2822 result = TCL_OK;
2823
2824 done:
2825 TclDecrRefCount(oldFullName);
2826 return result;
2827 }
2828
2829 /*
2830 *----------------------------------------------------------------------
2831 *
2832 * Tcl_SetCommandInfo --
2833 *
2834 * Modifies various information about a Tcl command. Note that this
2835 * function will not change a command's namespace; use TclRenameCommand
2836 * to do that. Also, the isNativeObjectProc member of *infoPtr is
2837 * ignored.
2838 *
2839 * Results:
2840 * If cmdName exists in interp, then the information at *infoPtr is
2841 * stored with the command in place of the current information and 1 is
2842 * returned. If the command doesn't exist then 0 is returned.
2843 *
2844 * Side effects:
2845 * None.
2846 *
2847 *----------------------------------------------------------------------
2848 */
2849
2850 int
2851 Tcl_SetCommandInfo(
2852 Tcl_Interp *interp, /* Interpreter in which to look for
2853 * command. */
2854 const char *cmdName, /* Name of desired command. */
2855 const Tcl_CmdInfo *infoPtr) /* Where to find information to store in the
2856 * command. */
2857 {
2858 Tcl_Command cmd;
2859
2860 cmd = Tcl_FindCommand(interp, cmdName, NULL, /*flags*/ 0);
2861 return Tcl_SetCommandInfoFromToken(cmd, infoPtr);
2862 }
2863
2864 /*
2865 *----------------------------------------------------------------------
2866 *
2867 * Tcl_SetCommandInfoFromToken --
2868 *
2869 * Modifies various information about a Tcl command. Note that this
2870 * function will not change a command's namespace; use TclRenameCommand
2871 * to do that. Also, the isNativeObjectProc member of *infoPtr is
2872 * ignored.
2873 *
2874 * Results:
2875 * If cmdName exists in interp, then the information at *infoPtr is
2876 * stored with the command in place of the current information and 1 is
2877 * returned. If the command doesn't exist then 0 is returned.
2878 *
2879 * Side effects:
2880 * None.
2881 *
2882 *----------------------------------------------------------------------
2883 */
2884
2885 int
2886 Tcl_SetCommandInfoFromToken(
2887 Tcl_Command cmd,
2888 const Tcl_CmdInfo *infoPtr)
2889 {
2890 Command *cmdPtr; /* Internal representation of the command */
2891
2892 if (cmd == NULL) {
2893 return 0;
2894 }
2895
2896 /*
2897 * The isNativeObjectProc and nsPtr members of *infoPtr are ignored.
2898 */
2899
2900 cmdPtr = (Command *)cmd;
2901 cmdPtr->proc = infoPtr->proc;
2902 cmdPtr->clientData = infoPtr->clientData;
2903 if (infoPtr->objProc == NULL) {
2904 cmdPtr->objProc = TclInvokeStringCommand;
2905 cmdPtr->objClientData = cmdPtr;
2906 cmdPtr->nreProc = NULL;
2907 } else {
2908 if (infoPtr->objProc != cmdPtr->objProc) {
2909 cmdPtr->nreProc = NULL;
2910 cmdPtr->objProc = infoPtr->objProc;
2911 }
2912 cmdPtr->objClientData = infoPtr->objClientData;
2913 }
2914 cmdPtr->deleteProc = infoPtr->deleteProc;
2915 cmdPtr->deleteData = infoPtr->deleteData;
2916 return 1;
2917 }
2918
2919 /*
2920 *----------------------------------------------------------------------
2921 *
2922 * Tcl_GetCommandInfo --
2923 *
2924 * Returns various information about a Tcl command.
2925 *
2926 * Results:
2927 * If cmdName exists in interp, then *infoPtr is modified to hold
2928 * information about cmdName and 1 is returned. If the command doesn't
2929 * exist then 0 is returned and *infoPtr isn't modified.
2930 *
2931 * Side effects:
2932 * None.
2933 *
2934 *----------------------------------------------------------------------
2935 */
2936
2937 int
2938 Tcl_GetCommandInfo(
2939 Tcl_Interp *interp, /* Interpreter in which to look for
2940 * command. */
2941 const char *cmdName, /* Name of desired command. */
2942 Tcl_CmdInfo *infoPtr) /* Where to store information about
2943 * command. */
2944 {
2945 Tcl_Command cmd;
2946
2947 cmd = Tcl_FindCommand(interp, cmdName, NULL, /*flags*/ 0);
2948 return Tcl_GetCommandInfoFromToken(cmd, infoPtr);
2949 }
2950
2951 /*
2952 *----------------------------------------------------------------------
2953 *
2954 * Tcl_GetCommandInfoFromToken --
2955 *
2956 * Returns various information about a Tcl command.
2957 *
2958 * Results:
2959 * Copies information from the command identified by 'cmd' into a
2960 * caller-supplied structure and returns 1. If the 'cmd' is NULL, leaves
2961 * the structure untouched and returns 0.
2962 *
2963 * Side effects:
2964 * None.
2965 *
2966 *----------------------------------------------------------------------
2967 */
2968
2969 int
2970 Tcl_GetCommandInfoFromToken(
2971 Tcl_Command cmd,
2972 Tcl_CmdInfo *infoPtr)
2973 {
2974 Command *cmdPtr; /* Internal representation of the command */
2975
2976 if (cmd == NULL) {
2977 return 0;
2978 }
2979
2980 /*
2981 * Set isNativeObjectProc 1 if objProc was registered by a call to
2982 * Tcl_CreateObjCommand. Otherwise set it to 0.
2983 */
2984
2985 cmdPtr = (Command *) cmd;
2986 infoPtr->isNativeObjectProc =
2987 (cmdPtr->objProc != TclInvokeStringCommand);
2988 infoPtr->objProc = cmdPtr->objProc;
2989 infoPtr->objClientData = cmdPtr->objClientData;
2990 infoPtr->proc = cmdPtr->proc;
2991 infoPtr->clientData = cmdPtr->clientData;
2992 infoPtr->deleteProc = cmdPtr->deleteProc;
2993 infoPtr->deleteData = cmdPtr->deleteData;
2994 infoPtr->namespacePtr = (Tcl_Namespace *) cmdPtr->nsPtr;
2995 return 1;
2996 }
2997
2998 /*
2999 *----------------------------------------------------------------------
3000 *
3001 * Tcl_GetCommandName --
3002 *
3003 * Given a token returned by Tcl_CreateCommand, this function returns the
3004 * current name of the command (which may have changed due to renaming).
3005 *
3006 * Results:
3007 * The return value is the name of the given command.
3008 *
3009 * Side effects:
3010 * None.
3011 *
3012 *----------------------------------------------------------------------
3013 */
3014
3015 const char *
3016 Tcl_GetCommandName(
3017 Tcl_Interp *interp, /* Interpreter containing the command. */
3018 Tcl_Command command) /* Token for command returned by a previous
3019 * call to Tcl_CreateCommand. The command must
3020 * not have been deleted. */
3021 {
3022 Command *cmdPtr = (Command *) command;
3023
3024 if ((cmdPtr == NULL) || (cmdPtr->hPtr == NULL)) {
3025 /*
3026 * This should only happen if command was "created" after the
3027 * interpreter began to be deleted, so there isn't really any command.
3028 * Just return an empty string.
3029 */
3030
3031 return "";
3032 }
3033
3034 return (const char *)Tcl_GetHashKey(cmdPtr->hPtr->tablePtr, cmdPtr->hPtr);
3035 }
3036
3037 /*
3038 *----------------------------------------------------------------------
3039 *
3040 * Tcl_GetCommandFullName --
3041 *
3042 * Given a token returned by, e.g., Tcl_CreateCommand or Tcl_FindCommand,
3043 * this function appends to an object the command's full name, qualified
3044 * by a sequence of parent namespace names. The command's fully-qualified
3045 * name may have changed due to renaming.
3046 *
3047 * Results:
3048 * None.
3049 *
3050 * Side effects:
3051 * The command's fully-qualified name is appended to the string
3052 * representation of objPtr.
3053 *
3054 *----------------------------------------------------------------------
3055 */
3056
3057 void
3058 Tcl_GetCommandFullName(
3059 Tcl_Interp *interp, /* Interpreter containing the command. */
3060 Tcl_Command command, /* Token for command returned by a previous
3061 * call to Tcl_CreateCommand. The command must
3062 * not have been deleted. */
3063 Tcl_Obj *objPtr) /* Points to the object onto which the
3064 * command's full name is appended. */
3065
3066 {
3067 Interp *iPtr = (Interp *) interp;
3068 Command *cmdPtr = (Command *) command;
3069 char *name;
3070
3071 /*
3072 * Add the full name of the containing namespace, followed by the "::"
3073 * separator, and the command name.
3074 */
3075
3076 if (cmdPtr != NULL) {
3077 if (cmdPtr->nsPtr != NULL) {
3078 Tcl_AppendToObj(objPtr, cmdPtr->nsPtr->fullName, -1);
3079 if (cmdPtr->nsPtr != iPtr->globalNsPtr) {
3080 Tcl_AppendToObj(objPtr, "::", 2);
3081 }
3082 }
3083 if (cmdPtr->hPtr != NULL) {
3084 name = (char *)Tcl_GetHashKey(cmdPtr->hPtr->tablePtr, cmdPtr->hPtr);
3085 Tcl_AppendToObj(objPtr, name, -1);
3086 }
3087 }
3088 }
3089
3090 /*
3091 *----------------------------------------------------------------------
3092 *
3093 * Tcl_DeleteCommand --
3094 *
3095 * Remove the given command from the given interpreter.
3096 *
3097 * Results:
3098 * 0 is returned if the command was deleted successfully. -1 is returned
3099 * if there didn't exist a command by that name.
3100 *
3101 * Side effects:
3102 * cmdName will no longer be recognized as a valid command for interp.
3103 *
3104 *----------------------------------------------------------------------
3105 */
3106
3107 int
3108 Tcl_DeleteCommand(
3109 Tcl_Interp *interp, /* Token for command interpreter (returned by
3110 * a previous Tcl_CreateInterp call). */
3111 const char *cmdName) /* Name of command to remove. */
3112 {
3113 Tcl_Command cmd;
3114
3115 /*
3116 * Find the desired command and delete it.
3117 */
3118
3119 cmd = Tcl_FindCommand(interp, cmdName, NULL, /*flags*/ 0);
3120 if (cmd == NULL) {
3121 return -1;
3122 }
3123 return Tcl_DeleteCommandFromToken(interp, cmd);
3124 }
3125
3126 /*
3127 *----------------------------------------------------------------------
3128 *
3129 * Tcl_DeleteCommandFromToken --
3130 *
3131 * Removes the given command from the given interpreter. This function
3132 * resembles Tcl_DeleteCommand, but takes a Tcl_Command token instead of
3133 * a command name for efficiency.
3134 *
3135 * Results:
3136 * 0 is returned if the command was deleted successfully. -1 is returned
3137 * if there didn't exist a command by that name.
3138 *
3139 * Side effects:
3140 * The command specified by "cmd" will no longer be recognized as a valid
3141 * command for "interp".
3142 *
3143 *----------------------------------------------------------------------
3144 */
3145
3146 int
3147 Tcl_DeleteCommandFromToken(
3148 Tcl_Interp *interp, /* Token for command interpreter returned by a
3149 * previous call to Tcl_CreateInterp. */
3150 Tcl_Command cmd) /* Token for command to delete. */
3151 {
3152 Interp *iPtr = (Interp *) interp;
3153 Command *cmdPtr = (Command *) cmd;
3154 ImportRef *refPtr, *nextRefPtr;
3155 Tcl_Command importCmd;
3156
3157 /*
3158 * Bump the command epoch counter. This will invalidate all cached
3159 * references that point to this command.
3160 */
3161
3162 cmdPtr->cmdEpoch++;
3163
3164 /*
3165 * The code here is tricky. We can't delete the hash table entry before
3166 * invoking the deletion callback because there are cases where the
3167 * deletion callback needs to invoke the command (e.g. object systems such
3168 * as OTcl). However, this means that the callback could try to delete or
3169 * rename the command. The deleted flag allows us to detect these cases
3170 * and skip nested deletes.
3171 */
3172
3173 if (cmdPtr->flags & CMD_IS_DELETED) {
3174 /*
3175 * Another deletion is already in progress. Remove the hash table
3176 * entry now, but don't invoke a callback or free the command
3177 * structure. Take care to only remove the hash entry if it has not
3178 * already been removed; otherwise if we manage to hit this function
3179 * three times, everything goes up in smoke. [Bug 1220058]
3180 */
3181
3182 if (cmdPtr->hPtr != NULL) {
3183 Tcl_DeleteHashEntry(cmdPtr->hPtr);
3184 cmdPtr->hPtr = NULL;
3185 }
3186 return 0;
3187 }
3188
3189 /*
3190 * We must delete this command, even though both traces and delete procs
3191 * may try to avoid this (renaming the command etc). Also traces and
3192 * delete procs may try to delete the command themselves. This flag
3193 * declares that a delete is in progress and that recursive deletes should
3194 * be ignored.
3195 */
3196
3197 cmdPtr->flags |= CMD_IS_DELETED;
3198
3199 /*
3200 * Call trace functions for the command being deleted. Then delete its
3201 * traces.
3202 */
3203
3204 cmdPtr->nsPtr->refCount++;
3205
3206 if (cmdPtr->tracePtr != NULL) {
3207 CommandTrace *tracePtr;
3208 CallCommandTraces(iPtr,cmdPtr,NULL,NULL,TCL_TRACE_DELETE);
3209
3210 /*
3211 * Now delete these traces.
3212 */
3213
3214 tracePtr = cmdPtr->tracePtr;
3215 while (tracePtr != NULL) {
3216 CommandTrace *nextPtr = tracePtr->nextPtr;
3217
3218 if (tracePtr->refCount-- <= 1) {
3219 ckfree(tracePtr);
3220 }
3221 tracePtr = nextPtr;
3222 }
3223 cmdPtr->tracePtr = NULL;
3224 }
3225
3226 /*
3227 * The list of commands exported from the namespace might have changed.
3228 * However, we do not need to recompute this just yet; next time we need
3229 * the info will be soon enough.
3230 */
3231
3232 TclInvalidateNsCmdLookup(cmdPtr->nsPtr);
3233 TclNsDecrRefCount(cmdPtr->nsPtr);
3234
3235 /*
3236 * If the command being deleted has a compile function, increment the
3237 * interpreter's compileEpoch to invalidate its compiled code. This makes
3238 * sure that we don't later try to execute old code compiled with
3239 * command-specific (i.e., inline) bytecodes for the now-deleted command.
3240 * This field is checked in Tcl_EvalObj and ObjInterpProc, and code whose
3241 * compilation epoch doesn't match is recompiled.
3242 */
3243
3244 if (cmdPtr->compileProc != NULL) {
3245 iPtr->compileEpoch++;
3246 }
3247
3248 if (!(cmdPtr->flags & CMD_REDEF_IN_PROGRESS)) {
3249 /*
3250 * Delete any imports of this routine before deleting this routine itself.
3251 * See issue 688fcc7082fa.
3252 */
3253 for (refPtr = cmdPtr->importRefPtr; refPtr != NULL;
3254 refPtr = nextRefPtr) {
3255 nextRefPtr = refPtr->nextPtr;
3256 importCmd = (Tcl_Command) refPtr->importedCmdPtr;
3257 Tcl_DeleteCommandFromToken(interp, importCmd);
3258 }
3259 }
3260
3261 if (cmdPtr->deleteProc != NULL) {
3262 /*
3263 * Delete the command's client data. If this was an imported command
3264 * created when a command was imported into a namespace, this client
3265 * data will be a pointer to a ImportedCmdData structure describing
3266 * the "real" command that this imported command refers to.
3267 *
3268 * If you are getting a crash during the call to deleteProc and
3269 * cmdPtr->deleteProc is a pointer to the function free(), the most
3270 * likely cause is that your extension allocated memory for the
3271 * clientData argument to Tcl_CreateObjCommand with the ckalloc()
3272 * macro and you are now trying to deallocate this memory with free()
3273 * instead of ckfree(). You should pass a pointer to your own method
3274 * that calls ckfree().
3275 */
3276
3277 cmdPtr->deleteProc(cmdPtr->deleteData);
3278 }
3279
3280 /*
3281 * Don't use hPtr to delete the hash entry here, because it's possible
3282 * that the deletion callback renamed the command. Instead, use
3283 * cmdPtr->hptr, and make sure that no-one else has already deleted the
3284 * hash entry.
3285 */
3286
3287 if (cmdPtr->hPtr != NULL) {
3288 Tcl_DeleteHashEntry(cmdPtr->hPtr);
3289 cmdPtr->hPtr = NULL;
3290
3291 /*
3292 * Bump the command epoch counter. This will invalidate all cached
3293 * references that point to this command.
3294 */
3295
3296 cmdPtr->cmdEpoch++;
3297 }
3298
3299 /*
3300 * A number of tests for particular kinds of commands are done by checking
3301 * whether the objProc field holds a known value. Set the field to NULL so
3302 * that such tests won't have false positives when applied to deleted
3303 * commands.
3304 */
3305
3306 cmdPtr->objProc = NULL;
3307
3308 /*
3309 * Now free the Command structure, unless there is another reference to it
3310 * from a CmdName Tcl object in some ByteCode code sequence. In that case,
3311 * delay the cleanup until all references are either discarded (when a
3312 * ByteCode is freed) or replaced by a new reference (when a cached
3313 * CmdName Command reference is found to be invalid and
3314 * TclNRExecuteByteCode looks up the command in the command hashtable).
3315 */
3316
3317 cmdPtr->flags |= CMD_DEAD;
3318 TclCleanupCommandMacro(cmdPtr);
3319 return 0;
3320 }
3321
3322 /*
3323 *----------------------------------------------------------------------
3324 *
3325 * CallCommandTraces --
3326 *
3327 * Abstraction of the code to call traces on a command.
3328 *
3329 * Results:
3330 * Currently always NULL.
3331 *
3332 * Side effects:
3333 * Anything; this may recursively evaluate scripts and code exists to do
3334 * just that.
3335 *
3336 *----------------------------------------------------------------------
3337 */
3338
3339 static char *
3340 CallCommandTraces(
3341 Interp *iPtr, /* Interpreter containing command. */
3342 Command *cmdPtr, /* Command whose traces are to be invoked. */
3343 const char *oldName, /* Command's old name, or NULL if we must get
3344 * the name from cmdPtr */
3345 const char *newName, /* Command's new name, or NULL if the command
3346 * is not being renamed */
3347 int flags) /* Flags indicating the type of traces to
3348 * trigger, either TCL_TRACE_DELETE or
3349 * TCL_TRACE_RENAME. */
3350 {
3351 CommandTrace *tracePtr;
3352 ActiveCommandTrace active;
3353 char *result;
3354 Tcl_Obj *oldNamePtr = NULL;
3355 Tcl_InterpState state = NULL;
3356
3357 if (cmdPtr->flags & CMD_TRACE_ACTIVE) {
3358 /*
3359 * While a rename trace is active, we will not process any more rename
3360 * traces; while a delete trace is active we will never reach here -
3361 * because Tcl_DeleteCommandFromToken checks for the condition
3362 * (cmdPtr->flags & CMD_IS_DELETED) and returns immediately when a
3363 * command deletion is in progress. For all other traces, delete
3364 * traces will not be invoked but a call to TraceCommandProc will
3365 * ensure that tracePtr->clientData is freed whenever the command
3366 * "oldName" is deleted.
3367 */
3368
3369 if (cmdPtr->flags & TCL_TRACE_RENAME) {
3370 flags &= ~TCL_TRACE_RENAME;
3371 }
3372 if (flags == 0) {
3373 return NULL;
3374 }
3375 }
3376 cmdPtr->flags |= CMD_TRACE_ACTIVE;
3377
3378 result = NULL;
3379 active.nextPtr = iPtr->activeCmdTracePtr;
3380 active.reverseScan = 0;
3381 iPtr->activeCmdTracePtr = &active;
3382
3383 if (flags & TCL_TRACE_DELETE) {
3384 flags |= TCL_TRACE_DESTROYED;
3385 }
3386 active.cmdPtr = cmdPtr;
3387
3388 Tcl_Preserve(iPtr);
3389
3390 for (tracePtr = cmdPtr->tracePtr; tracePtr != NULL;
3391 tracePtr = active.nextTracePtr) {
3392 active.nextTracePtr = tracePtr->nextPtr;
3393 if (!(tracePtr->flags & flags)) {
3394 continue;
3395 }
3396 cmdPtr->flags |= tracePtr->flags;
3397 if (oldName == NULL) {
3398 TclNewObj(oldNamePtr);
3399 Tcl_IncrRefCount(oldNamePtr);
3400 Tcl_GetCommandFullName((Tcl_Interp *) iPtr,
3401 (Tcl_Command) cmdPtr, oldNamePtr);
3402 oldName = TclGetString(oldNamePtr);
3403 }
3404 tracePtr->refCount++;
3405 if (state == NULL) {
3406 state = Tcl_SaveInterpState((Tcl_Interp *) iPtr, TCL_OK);
3407 }
3408 tracePtr->traceProc(tracePtr->clientData, (Tcl_Interp *) iPtr,
3409 oldName, newName, flags);
3410 cmdPtr->flags &= ~tracePtr->flags;
3411 if (tracePtr->refCount-- <= 1) {
3412 ckfree(tracePtr);
3413 }
3414 }
3415
3416 if (state) {
3417 Tcl_RestoreInterpState((Tcl_Interp *) iPtr, state);
3418 }
3419
3420 /*
3421 * If a new object was created to hold the full oldName, free it now.
3422 */
3423
3424 if (oldNamePtr != NULL) {
3425 TclDecrRefCount(oldNamePtr);
3426 }
3427
3428 /*
3429 * Restore the variable's flags, remove the record of our active traces,
3430 * and then return.
3431 */
3432
3433 cmdPtr->flags &= ~CMD_TRACE_ACTIVE;
3434 iPtr->activeCmdTracePtr = active.nextPtr;
3435 Tcl_Release(iPtr);
3436 return result;
3437 }
3438
3439 /*
3440 *----------------------------------------------------------------------
3441 *
3442 * CancelEvalProc --
3443 *
3444 * Marks this interpreter as being canceled. This causes current
3445 * executions to be unwound as the interpreter enters a state where it
3446 * refuses to execute more commands or handle [catch] or [try], yet the
3447 * interpreter is still able to execute further commands after the
3448 * cancelation is cleared (unlike if it is deleted).
3449 *
3450 * Results:
3451 * The value given for the code argument.
3452 *
3453 * Side effects:
3454 * Transfers a message from the cancellation message to the interpreter.
3455 *
3456 *----------------------------------------------------------------------
3457 */
3458
3459 static int
3460 CancelEvalProc(
3461 ClientData clientData, /* Interp to cancel the script in progress. */
3462 Tcl_Interp *interp, /* Ignored */
3463 int code) /* Current return code from command. */
3464 {
3465 CancelInfo *cancelInfo = (CancelInfo *)clientData;
3466 Interp *iPtr;
3467
3468 if (cancelInfo != NULL) {
3469 Tcl_MutexLock(&cancelLock);
3470 iPtr = (Interp *) cancelInfo->interp;
3471
3472 if (iPtr != NULL) {
3473 /*
3474 * Setting the CANCELED flag will cause the script in progress to
3475 * be canceled as soon as possible. The core honors this flag at
3476 * all the necessary places to ensure script cancellation is
3477 * responsive. Extensions can check for this flag by calling
3478 * Tcl_Canceled and checking if TCL_ERROR is returned or they can
3479 * choose to ignore the script cancellation flag and the
3480 * associated functionality altogether. Currently, the only other
3481 * flag we care about here is the TCL_CANCEL_UNWIND flag (from
3482 * Tcl_CancelEval). We do not want to simply combine all the flags
3483 * from original Tcl_CancelEval call with the interp flags here
3484 * just in case the caller passed flags that might cause behaviour
3485 * unrelated to script cancellation.
3486 */
3487
3488 TclSetCancelFlags(iPtr, cancelInfo->flags | CANCELED);
3489
3490 /*
3491 * Now, we must set the script cancellation flags on all the child
3492 * interpreters belonging to this one.
3493 */
3494
3495 TclSetChildCancelFlags((Tcl_Interp *) iPtr,
3496 cancelInfo->flags | CANCELED, 0);
3497
3498 /*
3499 * Create the result object now so that Tcl_Canceled can avoid
3500 * locking the cancelLock mutex.
3501 */
3502
3503 if (cancelInfo->result != NULL) {
3504 Tcl_SetStringObj(iPtr->asyncCancelMsg, cancelInfo->result,
3505 cancelInfo->length);
3506 } else {
3507 Tcl_SetObjLength(iPtr->asyncCancelMsg, 0);
3508 }
3509 }
3510 Tcl_MutexUnlock(&cancelLock);
3511 }
3512
3513 return code;
3514 }
3515
3516 /*
3517 *----------------------------------------------------------------------
3518 *
3519 * TclCleanupCommand --
3520 *
3521 * This function frees up a Command structure unless it is still
3522 * referenced from an interpreter's command hashtable or from a CmdName
3523 * Tcl object representing the name of a command in a ByteCode
3524 * instruction sequence.
3525 *
3526 * Results:
3527 * None.
3528 *
3529 * Side effects:
3530 * Memory gets freed unless a reference to the Command structure still
3531 * exists. In that case the cleanup is delayed until the command is
3532 * deleted or when the last ByteCode referring to it is freed.
3533 *
3534 *----------------------------------------------------------------------
3535 */
3536
3537 void
3538 TclCleanupCommand(
3539 Command *cmdPtr) /* Points to the Command structure to
3540 * be freed. */
3541 {
3542 if (cmdPtr->refCount-- <= 1) {
3543 ckfree(cmdPtr);
3544 }
3545 }
3546
3547 /*
3548 *----------------------------------------------------------------------
3549 *
3550 * Tcl_CreateMathFunc --
3551 *
3552 * Creates a new math function for expressions in a given interpreter.
3553 *
3554 * Results:
3555 * None.
3556 *
3557 * Side effects:
3558 * The Tcl function defined by "name" is created or redefined. If the
3559 * function already exists then its definition is replaced; this includes
3560 * the builtin functions. Redefining a builtin function forces all
3561 * existing code to be invalidated since that code may be compiled using
3562 * an instruction specific to the replaced function. In addition,
3563 * redefining a non-builtin function will force existing code to be
3564 * invalidated if the number of arguments has changed.
3565 *
3566 *----------------------------------------------------------------------
3567 */
3568
3569 void
3570 Tcl_CreateMathFunc(
3571 Tcl_Interp *interp, /* Interpreter in which function is to be
3572 * available. */
3573 const char *name, /* Name of function (e.g. "sin"). */
3574 int numArgs, /* Number of arguments required by
3575 * function. */
3576 Tcl_ValueType *argTypes, /* Array of types acceptable for each
3577 * argument. */
3578 Tcl_MathProc *proc, /* C function that implements the math
3579 * function. */
3580 ClientData clientData) /* Additional value to pass to the
3581 * function. */
3582 {
3583 Tcl_DString bigName;
3584 OldMathFuncData *data = (OldMathFuncData *)ckalloc(sizeof(OldMathFuncData));
3585
3586 data->proc = proc;
3587 data->numArgs = numArgs;
3588 data->argTypes = (Tcl_ValueType *)ckalloc(numArgs * sizeof(Tcl_ValueType));
3589 if ((numArgs > 0) && (argTypes != NULL)) {
3590 memcpy(data->argTypes, argTypes, numArgs * sizeof(Tcl_ValueType));
3591 }
3592 data->clientData = clientData;
3593
3594 Tcl_DStringInit(&bigName);
3595 TclDStringAppendLiteral(&bigName, "::tcl::mathfunc::");
3596 Tcl_DStringAppend(&bigName, name, -1);
3597
3598 Tcl_CreateObjCommand(interp, Tcl_DStringValue(&bigName),
3599 OldMathFuncProc, data, OldMathFuncDeleteProc);
3600 Tcl_DStringFree(&bigName);
3601 }
3602
3603 /*
3604 *----------------------------------------------------------------------
3605 *
3606 * OldMathFuncProc --
3607 *
3608 * Dispatch to a math function created with Tcl_CreateMathFunc
3609 *
3610 * Results:
3611 * Returns a standard Tcl result.
3612 *
3613 * Side effects:
3614 * Whatever the math function does.
3615 *
3616 *----------------------------------------------------------------------
3617 */
3618
3619 static int
3620 OldMathFuncProc(
3621 ClientData clientData, /* Pointer to OldMathFuncData describing the
3622 * function being called */
3623 Tcl_Interp *interp, /* Tcl interpreter */
3624 int objc, /* Actual parameter count */
3625 Tcl_Obj *const *objv) /* Parameter vector */
3626 {
3627 Tcl_Obj *valuePtr;
3628 OldMathFuncData *dataPtr = (OldMathFuncData *)clientData;
3629 Tcl_Value funcResult, *args;
3630 int result;
3631 int j, k;
3632 double d;
3633
3634 /*
3635 * Check argument count.
3636 */
3637
3638 if (objc != dataPtr->numArgs + 1) {
3639 MathFuncWrongNumArgs(interp, dataPtr->numArgs+1, objc, objv);
3640 return TCL_ERROR;
3641 }
3642
3643 /*
3644 * Convert arguments from Tcl_Obj's to Tcl_Value's.
3645 */
3646
3647 args = (Tcl_Value *)ckalloc(dataPtr->numArgs * sizeof(Tcl_Value));
3648 for (j = 1, k = 0; j < objc; ++j, ++k) {
3649 /* TODO: Convert to TclGetNumberFromObj? */
3650 valuePtr = objv[j];
3651 result = Tcl_GetDoubleFromObj(NULL, valuePtr, &d);
3652 #ifdef ACCEPT_NAN
3653 if ((result != TCL_OK) && (valuePtr->typePtr == &tclDoubleType)) {
3654 d = valuePtr->internalRep.doubleValue;
3655 result = TCL_OK;
3656 }
3657 #endif
3658 if (result != TCL_OK) {
3659 /*
3660 * We have a non-numeric argument.
3661 */
3662
3663 Tcl_SetObjResult(interp, Tcl_NewStringObj(
3664 "argument to math function didn't have numeric value",
3665 -1));
3666 TclCheckBadOctal(interp, TclGetString(valuePtr));
3667 ckfree(args);
3668 return TCL_ERROR;
3669 }
3670
3671 /*
3672 * Copy the object's numeric value to the argument record, converting
3673 * it if necessary.
3674 *
3675 * NOTE: no bignum support; use the new mathfunc interface for that.
3676 */
3677
3678 args[k].type = dataPtr->argTypes[k];
3679 switch (args[k].type) {
3680 case TCL_EITHER:
3681 if (Tcl_GetLongFromObj(NULL, valuePtr, &args[k].intValue)
3682 == TCL_OK) {
3683 args[k].type = TCL_INT;
3684 break;
3685 }
3686 if (TclGetWideIntFromObj(interp, valuePtr, &args[k].wideValue)
3687 == TCL_OK) {
3688 args[k].type = TCL_WIDE_INT;
3689 break;
3690 }
3691 args[k].type = TCL_DOUBLE;
3692 /* FALLTHROUGH */
3693
3694 case TCL_DOUBLE:
3695 args[k].doubleValue = d;
3696 break;
3697 case TCL_INT:
3698 if (ExprIntFunc(NULL, interp, 2, &objv[j-1]) != TCL_OK) {
3699 ckfree(args);
3700 return TCL_ERROR;
3701 }
3702 valuePtr = Tcl_GetObjResult(interp);
3703 Tcl_GetLongFromObj(NULL, valuePtr, &args[k].intValue);
3704 Tcl_ResetResult(interp);
3705 break;
3706 case TCL_WIDE_INT:
3707 if (ExprWideFunc(NULL, interp, 2, &objv[j-1]) != TCL_OK) {
3708 ckfree(args);
3709 return TCL_ERROR;
3710 }
3711 valuePtr = Tcl_GetObjResult(interp);
3712 TclGetWideIntFromObj(NULL, valuePtr, &args[k].wideValue);
3713 Tcl_ResetResult(interp);
3714 break;
3715 }
3716 }
3717
3718 /*
3719 * Call the function.
3720 */
3721
3722 errno = 0;
3723 result = dataPtr->proc(dataPtr->clientData, interp, args, &funcResult);
3724 ckfree(args);
3725 if (result != TCL_OK) {
3726 return result;
3727 }
3728
3729 /*
3730 * Return the result of the call.
3731 */
3732
3733 if (funcResult.type == TCL_INT) {
3734 TclNewLongObj(valuePtr, funcResult.intValue);
3735 } else if (funcResult.type == TCL_WIDE_INT) {
3736 valuePtr = Tcl_NewWideIntObj(funcResult.wideValue);
3737 } else {
3738 return CheckDoubleResult(interp, funcResult.doubleValue);
3739 }
3740 Tcl_SetObjResult(interp, valuePtr);
3741 return TCL_OK;
3742 }
3743
3744 /*
3745 *----------------------------------------------------------------------
3746 *
3747 * OldMathFuncDeleteProc --
3748 *
3749 * Cleans up after deleting a math function registered with
3750 * Tcl_CreateMathFunc
3751 *
3752 * Results:
3753 * None.
3754 *
3755 * Side effects:
3756 * Frees allocated memory.
3757 *
3758 *----------------------------------------------------------------------
3759 */
3760
3761 static void
3762 OldMathFuncDeleteProc(
3763 ClientData clientData)
3764 {
3765 OldMathFuncData *dataPtr = (OldMathFuncData *)clientData;
3766
3767 ckfree(dataPtr->argTypes);
3768 ckfree(dataPtr);
3769 }
3770
3771 /*
3772 *----------------------------------------------------------------------
3773 *
3774 * Tcl_GetMathFuncInfo --
3775 *
3776 * Discovers how a particular math function was created in a given
3777 * interpreter.
3778 *
3779 * Results:
3780 * TCL_OK if it succeeds, TCL_ERROR else (leaving an error message in the
3781 * interpreter result if that happens.)
3782 *
3783 * Side effects:
3784 * If this function succeeds, the variables pointed to by the numArgsPtr
3785 * and argTypePtr arguments will be updated to detail the arguments
3786 * allowed by the function. The variable pointed to by the procPtr
3787 * argument will be set to NULL if the function is a builtin function,
3788 * and will be set to the address of the C function used to implement the
3789 * math function otherwise (in which case the variable pointed to by the
3790 * clientDataPtr argument will also be updated.)
3791 *
3792 *----------------------------------------------------------------------
3793 */
3794
3795 int
3796 Tcl_GetMathFuncInfo(
3797 Tcl_Interp *interp,
3798 const char *name,
3799 int *numArgsPtr,
3800 Tcl_ValueType **argTypesPtr,
3801 Tcl_MathProc **procPtr,
3802 ClientData *clientDataPtr)
3803 {
3804 Tcl_Obj *cmdNameObj;
3805 Command *cmdPtr;
3806
3807 /*
3808 * Get the command that implements the math function.
3809 */
3810
3811 TclNewLiteralStringObj(cmdNameObj, "tcl::mathfunc::");
3812 Tcl_AppendToObj(cmdNameObj, name, -1);
3813 Tcl_IncrRefCount(cmdNameObj);
3814 cmdPtr = (Command *) Tcl_GetCommandFromObj(interp, cmdNameObj);
3815 Tcl_DecrRefCount(cmdNameObj);
3816
3817 /*
3818 * Report unknown functions.
3819 */
3820
3821 if (cmdPtr == NULL) {
3822 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
3823 "unknown math function \"%s\"", name));
3824 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "MATHFUNC", name, (char *)NULL);
3825 *numArgsPtr = -1;
3826 *argTypesPtr = NULL;
3827 *procPtr = NULL;
3828 *clientDataPtr = NULL;
3829 return TCL_ERROR;
3830 }
3831
3832 /*
3833 * Retrieve function info for user defined functions; return dummy
3834 * information for builtins.
3835 */
3836
3837 if (cmdPtr->objProc == &OldMathFuncProc) {
3838 OldMathFuncData *dataPtr = (OldMathFuncData *)cmdPtr->clientData;
3839
3840 *procPtr = dataPtr->proc;
3841 *numArgsPtr = dataPtr->numArgs;
3842 *argTypesPtr = dataPtr->argTypes;
3843 *clientDataPtr = dataPtr->clientData;
3844 } else {
3845 *procPtr = NULL;
3846 *numArgsPtr = -1;
3847 *argTypesPtr = NULL;
3848 *procPtr = NULL;
3849 *clientDataPtr = NULL;
3850 }
3851 return TCL_OK;
3852 }
3853
3854 /*
3855 *----------------------------------------------------------------------
3856 *
3857 * Tcl_ListMathFuncs --
3858 *
3859 * Produces a list of all the math functions defined in a given
3860 * interpreter.
3861 *
3862 * Results:
3863 * A pointer to a Tcl_Obj structure with a reference count of zero, or
3864 * NULL in the case of an error (in which case a suitable error message
3865 * will be left in the interpreter result.)
3866 *
3867 * Side effects:
3868 * None.
3869 *
3870 *----------------------------------------------------------------------
3871 */
3872
3873 Tcl_Obj *
3874 Tcl_ListMathFuncs(
3875 Tcl_Interp *interp,
3876 const char *pattern)
3877 {
3878 Tcl_Obj *script = Tcl_NewStringObj("::info functions ", -1);
3879 Tcl_Obj *result;
3880 Tcl_InterpState state;
3881
3882 if (pattern) {
3883 Tcl_Obj *patternObj = Tcl_NewStringObj(pattern, -1);
3884 Tcl_Obj *arg = Tcl_NewListObj(1, &patternObj);
3885
3886 Tcl_AppendObjToObj(script, arg);
3887 Tcl_DecrRefCount(arg); /* Should tear down patternObj too */
3888 }
3889
3890 state = Tcl_SaveInterpState(interp, TCL_OK);
3891 Tcl_IncrRefCount(script);
3892 if (TCL_OK == Tcl_EvalObjEx(interp, script, 0)) {
3893 result = Tcl_DuplicateObj(Tcl_GetObjResult(interp));
3894 } else {
3895 TclNewObj(result);
3896 }
3897 Tcl_DecrRefCount(script);
3898 Tcl_RestoreInterpState(interp, state);
3899
3900 return result;
3901 }
3902
3903 /*
3904 *----------------------------------------------------------------------
3905 *
3906 * TclInterpReady --
3907 *
3908 * Check if an interpreter is ready to eval commands or scripts, i.e., if
3909 * it was not deleted and if the nesting level is not too high.
3910 *
3911 * Results:
3912 * The return value is TCL_OK if it the interpreter is ready, TCL_ERROR
3913 * otherwise.
3914 *
3915 * Side effects:
3916 * The interpreters object and string results are cleared.
3917 *
3918 *----------------------------------------------------------------------
3919 */
3920
3921 int
3922 TclInterpReady(
3923 Tcl_Interp *interp)
3924 {
3925 Interp *iPtr = (Interp *) interp;
3926
3927 /*
3928 * Reset both the interpreter's string and object results and clear out
3929 * any previous error information.
3930 */
3931
3932 Tcl_ResetResult(interp);
3933
3934 /*
3935 * If the interpreter has been deleted, return an error.
3936 */
3937
3938 if (iPtr->flags & DELETED) {
3939 Tcl_SetObjResult(interp, Tcl_NewStringObj(
3940 "attempt to call eval in deleted interpreter", -1));
3941 Tcl_SetErrorCode(interp, "TCL", "IDELETE",
3942 "attempt to call eval in deleted interpreter", (char *)NULL);
3943 return TCL_ERROR;
3944 }
3945
3946 if (iPtr->execEnvPtr->rewind) {
3947 return TCL_ERROR;
3948 }
3949
3950 /*
3951 * Make sure the script being evaluated (if any) has not been canceled.
3952 */
3953
3954 if (TclCanceled(iPtr) &&
3955 (TCL_OK != Tcl_Canceled(interp, TCL_LEAVE_ERR_MSG))) {
3956 return TCL_ERROR;
3957 }
3958
3959 /*
3960 * Check depth of nested calls to Tcl_Eval: if this gets too large, it's
3961 * probably because of an infinite loop somewhere.
3962 */
3963
3964 if (iPtr->numLevels <= iPtr->maxNestingDepth) {
3965 return TCL_OK;
3966 }
3967
3968 Tcl_SetObjResult(interp, Tcl_NewStringObj(
3969 "too many nested evaluations (infinite loop?)", -1));
3970 Tcl_SetErrorCode(interp, "TCL", "LIMIT", "STACK", (char *)NULL);
3971 return TCL_ERROR;
3972 }
3973
3974 /*
3975 *----------------------------------------------------------------------
3976 *
3977 * TclResetCancellation --
3978 *
3979 * Reset the script cancellation flags if the nesting level
3980 * (iPtr->numLevels) for the interp is zero or argument force is
3981 * non-zero.
3982 *
3983 * Results:
3984 * A standard Tcl result.
3985 *
3986 * Side effects:
3987 * The script cancellation flags for the interp may be reset.
3988 *
3989 *----------------------------------------------------------------------
3990 */
3991
3992 int
3993 TclResetCancellation(
3994 Tcl_Interp *interp,
3995 int force)
3996 {
3997 Interp *iPtr = (Interp *) interp;
3998
3999 if (iPtr == NULL) {
4000 return TCL_ERROR;
4001 }
4002
4003 if (force || (iPtr->numLevels == 0)) {
4004 TclUnsetCancelFlags(iPtr);
4005 }
4006 return TCL_OK;
4007 }
4008
4009 /*
4010 *----------------------------------------------------------------------
4011 *
4012 * Tcl_Canceled --
4013 *
4014 * Check if the script in progress has been canceled, i.e.,
4015 * Tcl_CancelEval was called for this interpreter or any of its parent
4016 * interpreters.
4017 *
4018 * Results:
4019 * The return value is TCL_OK if the script evaluation has not been
4020 * canceled, TCL_ERROR otherwise.
4021 *
4022 * If "flags" contains TCL_LEAVE_ERR_MSG, an error message is returned in
4023 * the interpreter's result object. Otherwise, the interpreter's result
4024 * object is left unchanged. If "flags" contains TCL_CANCEL_UNWIND,
4025 * TCL_ERROR will only be returned if the script evaluation is being
4026 * completely unwound.
4027 *
4028 * Side effects:
4029 * The CANCELED flag for the interp will be reset if it is set.
4030 *
4031 *----------------------------------------------------------------------
4032 */
4033
4034 int
4035 Tcl_Canceled(
4036 Tcl_Interp *interp,
4037 int flags)
4038 {
4039 Interp *iPtr = (Interp *) interp;
4040
4041 /*
4042 * Has the current script in progress for this interpreter been canceled
4043 * or is the stack being unwound due to the previous script cancellation?
4044 */
4045
4046 if (!TclCanceled(iPtr)) {
4047 return TCL_OK;
4048 }
4049
4050 /*
4051 * The CANCELED flag is a one-shot flag that is reset immediately upon
4052 * being detected; however, if the TCL_CANCEL_UNWIND flag is set we will
4053 * continue to report that the script in progress has been canceled
4054 * thereby allowing the evaluation stack for the interp to be fully
4055 * unwound.
4056 */
4057
4058 iPtr->flags &= ~CANCELED;
4059
4060 /*
4061 * The CANCELED flag was detected and reset; however, if the caller
4062 * specified the TCL_CANCEL_UNWIND flag, we only return TCL_ERROR
4063 * (indicating that the script in progress has been canceled) if the
4064 * evaluation stack for the interp is being fully unwound.
4065 */
4066
4067 if ((flags & TCL_CANCEL_UNWIND) && !(iPtr->flags & TCL_CANCEL_UNWIND)) {
4068 return TCL_OK;
4069 }
4070
4071 /*
4072 * If the TCL_LEAVE_ERR_MSG flags bit is set, place an error in the
4073 * interp's result; otherwise, we leave it alone.
4074 */
4075
4076 if (flags & TCL_LEAVE_ERR_MSG) {
4077 const char *id, *message = NULL;
4078 int length;
4079
4080 /*
4081 * Setup errorCode variables so that we can differentiate between
4082 * being canceled and unwound.
4083 */
4084
4085 if (iPtr->asyncCancelMsg != NULL) {
4086 message = TclGetStringFromObj(iPtr->asyncCancelMsg, &length);
4087 } else {
4088 length = 0;
4089 }
4090
4091 if (iPtr->flags & TCL_CANCEL_UNWIND) {
4092 id = "IUNWIND";
4093 if (length == 0) {
4094 message = "eval unwound";
4095 }
4096 } else {
4097 id = "ICANCEL";
4098 if (length == 0) {
4099 message = "eval canceled";
4100 }
4101 }
4102
4103 Tcl_SetObjResult(interp, Tcl_NewStringObj(message, -1));
4104 Tcl_SetErrorCode(interp, "TCL", "CANCEL", id, message, (char *)NULL);
4105 }
4106
4107 /*
4108 * Return TCL_ERROR to the caller (not necessarily just the Tcl core
4109 * itself) that indicates further processing of the script or command in
4110 * progress should halt gracefully and as soon as possible.
4111 */
4112
4113 return TCL_ERROR;
4114 }
4115
4116 /*
4117 *----------------------------------------------------------------------
4118 *
4119 * Tcl_CancelEval --
4120 *
4121 * This function schedules the cancellation of the current script in the
4122 * given interpreter.
4123 *
4124 * Results:
4125 * The return value is a standard Tcl completion code such as TCL_OK or
4126 * TCL_ERROR. Since the interp may belong to a different thread, no error
4127 * message can be left in the interp's result.
4128 *
4129 * Side effects:
4130 * The script in progress in the specified interpreter will be canceled
4131 * with TCL_ERROR after asynchronous handlers are invoked at the next
4132 * Tcl_Canceled check.
4133 *
4134 *----------------------------------------------------------------------
4135 */
4136
4137 int
4138 Tcl_CancelEval(
4139 Tcl_Interp *interp, /* Interpreter in which to cancel the
4140 * script. */
4141 Tcl_Obj *resultObjPtr, /* The script cancellation error message or
4142 * NULL for a default error message. */
4143 ClientData clientData, /* Passed to CancelEvalProc. */
4144 int flags) /* Collection of OR-ed bits that control
4145 * the cancellation of the script. Only
4146 * TCL_CANCEL_UNWIND is currently
4147 * supported. */
4148 {
4149 Tcl_HashEntry *hPtr;
4150 CancelInfo *cancelInfo;
4151 int code = TCL_ERROR;
4152 const char *result;
4153
4154 if (interp == NULL) {
4155 return TCL_ERROR;
4156 }
4157
4158 Tcl_MutexLock(&cancelLock);
4159 if (cancelTableInitialized != 1) {
4160 /*
4161 * No CancelInfo hash table (Tcl_CreateInterp has never been called?)
4162 */
4163
4164 goto done;
4165 }
4166 hPtr = Tcl_FindHashEntry(&cancelTable, (char *)interp);
4167 if (hPtr == NULL) {
4168 /*
4169 * No CancelInfo record for this interpreter.
4170 */
4171
4172 goto done;
4173 }
4174 cancelInfo = (CancelInfo *)Tcl_GetHashValue(hPtr);
4175
4176 /*
4177 * Populate information needed by the interpreter thread to fulfill the
4178 * cancellation request. Currently, clientData is ignored. If the
4179 * TCL_CANCEL_UNWIND flags bit is set, the script in progress is not
4180 * allowed to catch the script cancellation because the evaluation stack
4181 * for the interp is completely unwound.
4182 */
4183
4184 if (resultObjPtr != NULL) {
4185 result = TclGetStringFromObj(resultObjPtr, &cancelInfo->length);
4186 cancelInfo->result = (char *)ckrealloc(cancelInfo->result, cancelInfo->length);
4187 memcpy(cancelInfo->result, result, cancelInfo->length);
4188 TclDecrRefCount(resultObjPtr); /* Discard their result object. */
4189 } else {
4190 cancelInfo->result = NULL;
4191 cancelInfo->length = 0;
4192 }
4193 cancelInfo->clientData = clientData;
4194 cancelInfo->flags = flags;
4195 Tcl_AsyncMark(cancelInfo->async);
4196 code = TCL_OK;
4197
4198 done:
4199 Tcl_MutexUnlock(&cancelLock);
4200 return code;
4201 }
4202
4203 /*
4204 *----------------------------------------------------------------------
4205 *
4206 * Tcl_InterpActive --
4207 *
4208 * Returns non-zero if the specified interpreter is in use, i.e. if there
4209 * is an evaluation currently active in the interpreter.
4210 *
4211 * Results:
4212 * See above.
4213 *
4214 * Side effects:
4215 * None.
4216 *
4217 *----------------------------------------------------------------------
4218 */
4219
4220 int
4221 Tcl_InterpActive(
4222 Tcl_Interp *interp)
4223 {
4224 return ((Interp *) interp)->numLevels > 0;
4225 }
4226
4227 /*
4228 *----------------------------------------------------------------------
4229 *
4230 * Tcl_EvalObjv --
4231 *
4232 * This function evaluates a Tcl command that has already been parsed
4233 * into words, with one Tcl_Obj holding each word.
4234 *
4235 * Results:
4236 * The return value is a standard Tcl completion code such as TCL_OK or
4237 * TCL_ERROR. A result or error message is left in interp's result.
4238 *
4239 * Side effects:
4240 * Always pushes a callback. Other side effects depend on the command.
4241 *
4242 *----------------------------------------------------------------------
4243 */
4244
4245 int
4246 Tcl_EvalObjv(
4247 Tcl_Interp *interp, /* Interpreter in which to evaluate the
4248 * command. Also used for error reporting. */
4249 int objc, /* Number of words in command. */
4250 Tcl_Obj *const objv[], /* An array of pointers to objects that are
4251 * the words that make up the command. */
4252 int flags) /* Collection of OR-ed bits that control the
4253 * evaluation of the script. Only
4254 * TCL_EVAL_GLOBAL, TCL_EVAL_INVOKE and
4255 * TCL_EVAL_NOERR are currently supported. */
4256 {
4257 int result;
4258 NRE_callback *rootPtr = TOP_CB(interp);
4259
4260 result = TclNREvalObjv(interp, objc, objv, flags, NULL);
4261 return TclNRRunCallbacks(interp, result, rootPtr);
4262 }
4263
4264 int
4265 TclNREvalObjv(
4266 Tcl_Interp *interp, /* Interpreter in which to evaluate the
4267 * command. Also used for error reporting. */
4268 int objc, /* Number of words in command. */
4269 Tcl_Obj *const objv[], /* An array of pointers to objects that are
4270 * the words that make up the command. */
4271 int flags, /* Collection of OR-ed bits that control the
4272 * evaluation of the script. Only
4273 * TCL_EVAL_GLOBAL, TCL_EVAL_INVOKE and
4274 * TCL_EVAL_NOERR are currently supported. */
4275 Command *cmdPtr) /* NULL if the Command is to be looked up
4276 * here, otherwise the pointer to the
4277 * requested Command struct to be invoked. */
4278 {
4279 Interp *iPtr = (Interp *) interp;
4280
4281 /*
4282 * data[1] stores a marker for use by tailcalls; it will be set to 1 by
4283 * command redirectors (imports, alias, ensembles) so that tailcall skips
4284 * this callback (that marks the end of the target command) and goes back
4285 * to the end of the source command.
4286 */
4287
4288 if (iPtr->deferredCallbacks) {
4289 iPtr->deferredCallbacks = NULL;
4290 } else {
4291 TclNRAddCallback(interp, NRCommand, NULL, NULL, NULL, NULL);
4292 }
4293
4294 iPtr->numLevels++;
4295 TclNRAddCallback(interp, EvalObjvCore, cmdPtr, INT2PTR(flags),
4296 INT2PTR(objc), objv);
4297 return TCL_OK;
4298 }
4299
4300 static int
4301 EvalObjvCore(
4302 ClientData data[],
4303 Tcl_Interp *interp,
4304 int result)
4305 {
4306 Command *cmdPtr = NULL, *preCmdPtr = (Command *)data[0];
4307 int flags = PTR2INT(data[1]);
4308 int objc = PTR2INT(data[2]);
4309 Tcl_Obj **objv = (Tcl_Obj **)data[3];
4310 Interp *iPtr = (Interp *) interp;
4311 Namespace *lookupNsPtr = NULL;
4312 int enterTracesDone = 0;
4313
4314 /*
4315 * Push records for task to be done on return, in INVERSE order. First, if
4316 * needed, the exception handlers (as they should happen last).
4317 */
4318
4319 if (!(flags & TCL_EVAL_NOERR)) {
4320 TEOV_PushExceptionHandlers(interp, objc, objv, flags);
4321 }
4322
4323 if (TCL_OK != TclInterpReady(interp)) {
4324 return TCL_ERROR;
4325 }
4326
4327 if (objc == 0) {
4328 return TCL_OK;
4329 }
4330
4331 if (TclLimitExceeded(iPtr->limit)) {
4332 /* generate error message if not yet already logged at this stage */
4333 if (!(iPtr->flags & ERR_ALREADY_LOGGED)) {
4334 Tcl_LimitCheck(interp);
4335 }
4336 return TCL_ERROR;
4337 }
4338
4339 /*
4340 * Configure evaluation context to match the requested flags.
4341 */
4342
4343 if (iPtr->lookupNsPtr) {
4344
4345 /*
4346 * Capture the namespace we should do command name resolution in, as
4347 * instructed by our caller sneaking it in to us in a private interp
4348 * field. Clear that field right away so we cannot possibly have its
4349 * use leak where it should not. The sneaky message pass is done.
4350 *
4351 * Use of this mechanism overrides the TCL_EVAL_GLOBAL flag.
4352 * TODO: Is that a bug?
4353 */
4354
4355 lookupNsPtr = iPtr->lookupNsPtr;
4356 iPtr->lookupNsPtr = NULL;
4357 } else if (flags & TCL_EVAL_INVOKE) {
4358 lookupNsPtr = iPtr->globalNsPtr;
4359 } else {
4360
4361 /*
4362 * TCL_EVAL_INVOKE was not set: clear rewrite rules
4363 */
4364
4365 TclResetRewriteEnsemble(interp, 1);
4366
4367 if (flags & TCL_EVAL_GLOBAL) {
4368 TEOV_SwitchVarFrame(interp);
4369 lookupNsPtr = iPtr->globalNsPtr;
4370 }
4371 }
4372
4373 /*
4374 * Lookup the Command to dispatch.
4375 */
4376
4377 reresolve:
4378 assert(cmdPtr == NULL);
4379 if (preCmdPtr) {
4380 /*
4381 * Caller gave it to us.
4382 */
4383
4384 if (!(preCmdPtr->flags & CMD_DEAD)) {
4385 /*
4386 * So long as it exists, use it.
4387 */
4388
4389 cmdPtr = preCmdPtr;
4390 } else if (flags & TCL_EVAL_NORESOLVE) {
4391 /*
4392 * When it's been deleted, and we're told not to attempt resolving
4393 * it ourselves, all we can do is raise an error.
4394 */
4395
4396 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
4397 "attempt to invoke a deleted command"));
4398 Tcl_SetErrorCode(interp, "TCL", "EVAL", "DELETEDCOMMAND", (char *)NULL);
4399 return TCL_ERROR;
4400 }
4401 }
4402 if (cmdPtr == NULL) {
4403 cmdPtr = TEOV_LookupCmdFromObj(interp, objv[0], lookupNsPtr);
4404 if (!cmdPtr) {
4405 return TEOV_NotFound(interp, objc, objv, lookupNsPtr);
4406 }
4407 }
4408
4409 if (enterTracesDone || iPtr->tracePtr
4410 || (cmdPtr->flags & CMD_HAS_EXEC_TRACES)) {
4411 Tcl_Obj *commandPtr = TclGetSourceFromFrame(
4412 flags & TCL_EVAL_SOURCE_IN_FRAME ? iPtr->cmdFramePtr : NULL,
4413 objc, objv);
4414
4415 Tcl_IncrRefCount(commandPtr);
4416 if (!enterTracesDone) {
4417 int code = TEOV_RunEnterTraces(interp, &cmdPtr, commandPtr,
4418 objc, objv);
4419
4420 /*
4421 * Send any exception from enter traces back as an exception
4422 * raised by the traced command.
4423 * TODO: Is this a bug? Letting an execution trace BREAK or
4424 * CONTINUE or RETURN in the place of the traced command? Would
4425 * either converting all exceptions to TCL_ERROR, or just
4426 * swallowing them be better? (Swallowing them has the problem of
4427 * permanently hiding program errors.)
4428 */
4429
4430 if (code != TCL_OK) {
4431 Tcl_DecrRefCount(commandPtr);
4432 return code;
4433 }
4434
4435 /*
4436 * If the enter traces made the resolved cmdPtr unusable, go back
4437 * and resolve again, but next time don't run enter traces again.
4438 */
4439
4440 if (cmdPtr == NULL) {
4441 enterTracesDone = 1;
4442 Tcl_DecrRefCount(commandPtr);
4443 goto reresolve;
4444 }
4445 }
4446
4447 /*
4448 * Schedule leave traces. Raise the refCount on the resolved cmdPtr,
4449 * so that when it passes to the leave traces we know it's still
4450 * valid.
4451 */
4452
4453 cmdPtr->refCount++;
4454 TclNRAddCallback(interp, TEOV_RunLeaveTraces, INT2PTR(objc),
4455 commandPtr, cmdPtr, objv);
4456 }
4457
4458 TclNRAddCallback(interp, Dispatch,
4459 cmdPtr->nreProc ? cmdPtr->nreProc : cmdPtr->objProc,
4460 cmdPtr->objClientData, INT2PTR(objc), objv);
4461 return TCL_OK;
4462 }
4463
4464 static int
4465 Dispatch(
4466 ClientData data[],
4467 Tcl_Interp *interp,
4468 int result)
4469 {
4470 Tcl_ObjCmdProc *objProc = (Tcl_ObjCmdProc *)data[0];
4471 ClientData clientData = data[1];
4472 int objc = PTR2INT(data[2]);
4473 Tcl_Obj **objv = (Tcl_Obj **)data[3];
4474 Interp *iPtr = (Interp *) interp;
4475
4476 #ifdef USE_DTRACE
4477 if (TCL_DTRACE_CMD_ARGS_ENABLED()) {
4478 const char *a[10];
4479 int i = 0;
4480
4481 while (i < 10) {
4482 a[i] = i < objc ? TclGetString(objv[i]) : NULL; i++;
4483 }
4484 TCL_DTRACE_CMD_ARGS(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7],
4485 a[8], a[9]);
4486 }
4487 if (TCL_DTRACE_CMD_INFO_ENABLED() && iPtr->cmdFramePtr) {
4488 Tcl_Obj *info = TclInfoFrame(interp, iPtr->cmdFramePtr);
4489 const char *a[6]; int i[2];
4490
4491 TclDTraceInfo(info, a, i);
4492 TCL_DTRACE_CMD_INFO(a[0], a[1], a[2], a[3], i[0], i[1], a[4], a[5]);
4493 TclDecrRefCount(info);
4494 }
4495 if ((TCL_DTRACE_CMD_RETURN_ENABLED() || TCL_DTRACE_CMD_RESULT_ENABLED())
4496 && objc) {
4497 TclNRAddCallback(interp, DTraceCmdReturn, objv[0], NULL, NULL, NULL);
4498 }
4499 if (TCL_DTRACE_CMD_ENTRY_ENABLED() && objc) {
4500 TCL_DTRACE_CMD_ENTRY(TclGetString(objv[0]), objc - 1,
4501 (Tcl_Obj **)(objv + 1));
4502 }
4503 #endif /* USE_DTRACE */
4504
4505 iPtr->cmdCount++;
4506 return objProc(clientData, interp, objc, objv);
4507 }
4508
4509 int
4510 TclNRRunCallbacks(
4511 Tcl_Interp *interp,
4512 int result,
4513 struct NRE_callback *rootPtr)
4514 /* All callbacks down to rootPtr not inclusive
4515 * are to be run. */
4516 {
4517 Interp *iPtr = (Interp *) interp;
4518
4519 /*
4520 * If the interpreter has a non-empty string result, the result object is
4521 * either empty or stale because some function set interp->result
4522 * directly. If so, move the string result to the result object, then
4523 * reset the string result.
4524 *
4525 * This only needs to be done for the first item in the list: all other
4526 * are for NR function calls, and those are Tcl_Obj based.
4527 */
4528
4529 if (*(iPtr->result) != 0) {
4530 (void) Tcl_GetObjResult(interp);
4531 }
4532
4533 /*
4534 * This is the trampoline.
4535 */
4536
4537 while (TOP_CB(interp) != rootPtr) {
4538 NRE_callback *callbackPtr = TOP_CB(interp);
4539 Tcl_NRPostProc *procPtr = callbackPtr->procPtr;
4540
4541 TOP_CB(interp) = callbackPtr->nextPtr;
4542 result = procPtr(callbackPtr->data, interp, result);
4543 TCLNR_FREE(interp, callbackPtr);
4544 }
4545 return result;
4546 }
4547
4548 static int
4549 NRCommand(
4550 ClientData data[],
4551 Tcl_Interp *interp,
4552 int result)
4553 {
4554 Interp *iPtr = (Interp *) interp;
4555
4556 iPtr->numLevels--;
4557
4558 /*
4559 * If there is a tailcall, schedule it next
4560 */
4561
4562 if (data[1] && (data[1] != INT2PTR(1))) {
4563 TclNRAddCallback(interp, TclNRTailcallEval, data[1], NULL, NULL, NULL);
4564 }
4565
4566 /* OPT ??
4567 * Do not interrupt a series of cleanups with async or limit checks:
4568 * just check at the end?
4569 */
4570
4571 if (TclAsyncReady(iPtr)) {
4572 result = Tcl_AsyncInvoke(interp, result);
4573 }
4574 if ((result == TCL_OK) && TclCanceled(iPtr)) {
4575 result = Tcl_Canceled(interp, TCL_LEAVE_ERR_MSG);
4576 }
4577 if (result == TCL_OK && TclLimitReady(iPtr->limit)) {
4578 result = Tcl_LimitCheck(interp);
4579 }
4580
4581 return result;
4582 }
4583
4584 /*
4585 *----------------------------------------------------------------------
4586 *
4587 * TEOV_Exception -
4588 * TEOV_LookupCmdFromObj -
4589 * TEOV_RunEnterTraces -
4590 * TEOV_RunLeaveTraces -
4591 * TEOV_NotFound -
4592 *
4593 * These are helper functions for Tcl_EvalObjv.
4594 *
4595 *----------------------------------------------------------------------
4596 */
4597
4598 static void
4599 TEOV_PushExceptionHandlers(
4600 Tcl_Interp *interp,
4601 int objc,
4602 Tcl_Obj *const objv[],
4603 int flags)
4604 {
4605 Interp *iPtr = (Interp *) interp;
4606
4607 /*
4608 * If any error processing is necessary, push the appropriate records.
4609 * Note that we have to push them in the inverse order: first the one that
4610 * has to run last.
4611 */
4612
4613 if (!(flags & TCL_EVAL_INVOKE)) {
4614 /*
4615 * Error messages
4616 */
4617
4618 TclNRAddCallback(interp, TEOV_Error, INT2PTR(objc),
4619 objv, NULL, NULL);
4620 }
4621
4622 if (iPtr->numLevels == 1) {
4623 /*
4624 * No CONTINUE or BREAK at level 0, manage RETURN
4625 */
4626
4627 TclNRAddCallback(interp, TEOV_Exception, INT2PTR(iPtr->evalFlags),
4628 NULL, NULL, NULL);
4629 }
4630 }
4631
4632 static void
4633 TEOV_SwitchVarFrame(
4634 Tcl_Interp *interp)
4635 {
4636 Interp *iPtr = (Interp *) interp;
4637
4638 /*
4639 * Change the varFrame to be the rootVarFrame, and push a record to
4640 * restore things at the end.
4641 */
4642
4643 TclNRAddCallback(interp, TEOV_RestoreVarFrame, iPtr->varFramePtr, NULL,
4644 NULL, NULL);
4645 iPtr->varFramePtr = iPtr->rootFramePtr;
4646 }
4647
4648 static int
4649 TEOV_RestoreVarFrame(
4650 ClientData data[],
4651 Tcl_Interp *interp,
4652 int result)
4653 {
4654 ((Interp *) interp)->varFramePtr = (CallFrame *)data[0];
4655 return result;
4656 }
4657
4658 static int
4659 TEOV_Exception(
4660 ClientData data[],
4661 Tcl_Interp *interp,
4662 int result)
4663 {
4664 Interp *iPtr = (Interp *) interp;
4665 int allowExceptions = (PTR2INT(data[0]) & TCL_ALLOW_EXCEPTIONS);
4666
4667 if (result != TCL_OK) {
4668 if (result == TCL_RETURN) {
4669 result = TclUpdateReturnInfo(iPtr);
4670 }
4671 if ((result != TCL_OK) && (result != TCL_ERROR) && !allowExceptions) {
4672 ProcessUnexpectedResult(interp, result);
4673 result = TCL_ERROR;
4674 }
4675 }
4676
4677 /*
4678 * We are returning to level 0, so should process TclResetCancellation. As
4679 * numLevels has not *yet* been decreased, do not call it: do the thing
4680 * here directly.
4681 */
4682
4683 TclUnsetCancelFlags(iPtr);
4684 return result;
4685 }
4686
4687 static int
4688 TEOV_Error(
4689 ClientData data[],
4690 Tcl_Interp *interp,
4691 int result)
4692 {
4693 Interp *iPtr = (Interp *) interp;
4694 Tcl_Obj *listPtr;
4695 const char *cmdString;
4696 int cmdLen;
4697 int objc = PTR2INT(data[0]);
4698 Tcl_Obj **objv = (Tcl_Obj **)data[1];
4699
4700 if ((result == TCL_ERROR) && !(iPtr->flags & ERR_ALREADY_LOGGED)) {
4701 /*
4702 * If there was an error, a command string will be needed for the
4703 * error log: get it out of the itemPtr. The details depend on the
4704 * type.
4705 */
4706
4707 listPtr = Tcl_NewListObj(objc, objv);
4708 cmdString = TclGetStringFromObj(listPtr, &cmdLen);
4709 Tcl_LogCommandInfo(interp, cmdString, cmdString, cmdLen);
4710 Tcl_DecrRefCount(listPtr);
4711 }
4712 iPtr->flags &= ~ERR_ALREADY_LOGGED;
4713 return result;
4714 }
4715
4716 static int
4717 TEOV_NotFound(
4718 Tcl_Interp *interp,
4719 int objc,
4720 Tcl_Obj *const objv[],
4721 Namespace *lookupNsPtr)
4722 {
4723 Command * cmdPtr;
4724 Interp *iPtr = (Interp *) interp;
4725 int i, newObjc, handlerObjc;
4726 Tcl_Obj **newObjv, **handlerObjv;
4727 CallFrame *varFramePtr = iPtr->varFramePtr;
4728 Namespace *currNsPtr = NULL;/* Used to check for and invoke any registered
4729 * unknown command handler for the current
4730 * namespace (TIP 181). */
4731 Namespace *savedNsPtr = NULL;
4732
4733 currNsPtr = varFramePtr->nsPtr;
4734 if ((currNsPtr == NULL) || (currNsPtr->unknownHandlerPtr == NULL)) {
4735 currNsPtr = iPtr->globalNsPtr;
4736 if (currNsPtr == NULL) {
4737 Tcl_Panic("Tcl_EvalObjv: NULL global namespace pointer");
4738 }
4739 }
4740
4741 /*
4742 * Check to see if the resolution namespace has lost its unknown handler.
4743 * If so, reset it to "::unknown".
4744 */
4745
4746 if (currNsPtr->unknownHandlerPtr == NULL) {
4747 TclNewLiteralStringObj(currNsPtr->unknownHandlerPtr, "::unknown");
4748 Tcl_IncrRefCount(currNsPtr->unknownHandlerPtr);
4749 }
4750
4751 /*
4752 * Get the list of words for the unknown handler and allocate enough space
4753 * to hold both the handler prefix and all words of the command invocation
4754 * itself.
4755 */
4756
4757 TclListObjGetElements(NULL, currNsPtr->unknownHandlerPtr,
4758 &handlerObjc, &handlerObjv);
4759 newObjc = objc + handlerObjc;
4760 newObjv = (Tcl_Obj **)TclStackAlloc(interp, sizeof(Tcl_Obj *) * newObjc);
4761
4762 /*
4763 * Copy command prefix from unknown handler and add on the real command's
4764 * full argument list. Note that we only use memcpy() once because we have
4765 * to increment the reference count of all the handler arguments anyway.
4766 */
4767
4768 for (i = 0; i < handlerObjc; ++i) {
4769 newObjv[i] = handlerObjv[i];
4770 Tcl_IncrRefCount(newObjv[i]);
4771 }
4772 memcpy(newObjv + handlerObjc, objv, sizeof(Tcl_Obj *) * objc);
4773
4774 /*
4775 * Look up and invoke the handler (by recursive call to this function). If
4776 * there is no handler at all, instead of doing the recursive call we just
4777 * generate a generic error message; it would be an infinite-recursion
4778 * nightmare otherwise.
4779 *
4780 * In this case we worry a bit less about recursion for now, and call the
4781 * "blocking" interface.
4782 */
4783
4784 cmdPtr = TEOV_LookupCmdFromObj(interp, newObjv[0], lookupNsPtr);
4785 if (cmdPtr == NULL) {
4786 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
4787 "invalid command name \"%s\"", TclGetString(objv[0])));
4788 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "COMMAND",
4789 TclGetString(objv[0]), (char *)NULL);
4790
4791 /*
4792 * Release any resources we locked and allocated during the handler
4793 * call.
4794 */
4795
4796 for (i = 0; i < handlerObjc; ++i) {
4797 Tcl_DecrRefCount(newObjv[i]);
4798 }
4799 TclStackFree(interp, newObjv);
4800 return TCL_ERROR;
4801 }
4802
4803 if (lookupNsPtr) {
4804 savedNsPtr = varFramePtr->nsPtr;
4805 varFramePtr->nsPtr = lookupNsPtr;
4806 }
4807 TclSkipTailcall(interp);
4808 TclNRAddCallback(interp, TEOV_NotFoundCallback, INT2PTR(handlerObjc),
4809 newObjv, savedNsPtr, NULL);
4810 return TclNREvalObjv(interp, newObjc, newObjv, TCL_EVAL_NOERR, NULL);
4811 }
4812
4813 static int
4814 TEOV_NotFoundCallback(
4815 ClientData data[],
4816 Tcl_Interp *interp,
4817 int result)
4818 {
4819 Interp *iPtr = (Interp *) interp;
4820 int objc = PTR2INT(data[0]);
4821 Tcl_Obj **objv = (Tcl_Obj **)data[1];
4822 Namespace *savedNsPtr = (Namespace *)data[2];
4823
4824 int i;
4825
4826 if (savedNsPtr) {
4827 iPtr->varFramePtr->nsPtr = savedNsPtr;
4828 }
4829
4830 /*
4831 * Release any resources we locked and allocated during the handler call.
4832 */
4833
4834 for (i = 0; i < objc; ++i) {
4835 Tcl_DecrRefCount(objv[i]);
4836 }
4837 TclStackFree(interp, objv);
4838
4839 return result;
4840 }
4841
4842 static int
4843 TEOV_RunEnterTraces(
4844 Tcl_Interp *interp,
4845 Command **cmdPtrPtr,
4846 Tcl_Obj *commandPtr,
4847 int objc,
4848 Tcl_Obj *const objv[])
4849 {
4850 Interp *iPtr = (Interp *) interp;
4851 Command *cmdPtr = *cmdPtrPtr;
4852 int length, newEpoch, cmdEpoch = cmdPtr->cmdEpoch;
4853 int traceCode = TCL_OK;
4854 const char *command = TclGetStringFromObj(commandPtr, &length);
4855
4856 /*
4857 * Call trace functions.
4858 * Execute any command or execution traces. Note that we bump up the
4859 * command's reference count for the duration of the calling of the
4860 * traces so that the structure doesn't go away underneath our feet.
4861 */
4862
4863 cmdPtr->refCount++;
4864 if (iPtr->tracePtr) {
4865 traceCode = TclCheckInterpTraces(interp, command, length,
4866 cmdPtr, TCL_OK, TCL_TRACE_ENTER_EXEC, objc, objv);
4867 }
4868 if ((cmdPtr->flags & CMD_HAS_EXEC_TRACES) && (traceCode == TCL_OK)) {
4869 traceCode = TclCheckExecutionTraces(interp, command, length,
4870 cmdPtr, TCL_OK, TCL_TRACE_ENTER_EXEC, objc, objv);
4871 }
4872 newEpoch = cmdPtr->cmdEpoch;
4873 TclCleanupCommandMacro(cmdPtr);
4874
4875 if (traceCode != TCL_OK) {
4876 if (traceCode == TCL_ERROR) {
4877 Tcl_Obj *info;
4878
4879 TclNewLiteralStringObj(info, "\n (enter trace on \"");
4880 Tcl_AppendLimitedToObj(info, command, length, 55, "...");
4881 Tcl_AppendToObj(info, "\")", 2);
4882 Tcl_AppendObjToErrorInfo(interp, info);
4883 iPtr->flags |= ERR_ALREADY_LOGGED;
4884 }
4885 return traceCode;
4886 }
4887 if (cmdEpoch != newEpoch) {
4888 *cmdPtrPtr = NULL;
4889 }
4890 return TCL_OK;
4891 }
4892
4893 static int
4894 TEOV_RunLeaveTraces(
4895 ClientData data[],
4896 Tcl_Interp *interp,
4897 int result)
4898 {
4899 Interp *iPtr = (Interp *) interp;
4900 int traceCode = TCL_OK;
4901 int objc = PTR2INT(data[0]);
4902 Tcl_Obj *commandPtr = (Tcl_Obj *)data[1];
4903 Command *cmdPtr = (Command *)data[2];
4904 Tcl_Obj **objv = (Tcl_Obj **)data[3];
4905 int length;
4906 const char *command = TclGetStringFromObj(commandPtr, &length);
4907
4908 if (!(cmdPtr->flags & CMD_IS_DELETED)) {
4909 if (cmdPtr->flags & CMD_HAS_EXEC_TRACES) {
4910 traceCode = TclCheckExecutionTraces(interp, command, length,
4911 cmdPtr, result, TCL_TRACE_LEAVE_EXEC, objc, objv);
4912 }
4913 if (iPtr->tracePtr != NULL && traceCode == TCL_OK) {
4914 traceCode = TclCheckInterpTraces(interp, command, length,
4915 cmdPtr, result, TCL_TRACE_LEAVE_EXEC, objc, objv);
4916 }
4917 }
4918
4919 /*
4920 * As cmdPtr is set, TclNRRunCallbacks is about to reduce the numlevels.
4921 * Prevent that by resetting the cmdPtr field and dealing right here with
4922 * cmdPtr->refCount.
4923 */
4924
4925 TclCleanupCommandMacro(cmdPtr);
4926
4927 if (traceCode != TCL_OK) {
4928 if (traceCode == TCL_ERROR) {
4929 Tcl_Obj *info;
4930
4931 TclNewLiteralStringObj(info, "\n (leave trace on \"");
4932 Tcl_AppendLimitedToObj(info, command, length, 55, "...");
4933 Tcl_AppendToObj(info, "\")", 2);
4934 Tcl_AppendObjToErrorInfo(interp, info);
4935 iPtr->flags |= ERR_ALREADY_LOGGED;
4936 }
4937 result = traceCode;
4938 }
4939 Tcl_DecrRefCount(commandPtr);
4940 return result;
4941 }
4942
4943 static inline Command *
4944 TEOV_LookupCmdFromObj(
4945 Tcl_Interp *interp,
4946 Tcl_Obj *namePtr,
4947 Namespace *lookupNsPtr)
4948 {
4949 Interp *iPtr = (Interp *) interp;
4950 Command *cmdPtr;
4951 Namespace *savedNsPtr = iPtr->varFramePtr->nsPtr;
4952
4953 if (lookupNsPtr) {
4954 iPtr->varFramePtr->nsPtr = lookupNsPtr;
4955 }
4956 cmdPtr = (Command *) Tcl_GetCommandFromObj(interp, namePtr);
4957 iPtr->varFramePtr->nsPtr = savedNsPtr;
4958 return cmdPtr;
4959 }
4960
4961 /*
4962 *----------------------------------------------------------------------
4963 *
4964 * Tcl_EvalTokensStandard --
4965 *
4966 * Given an array of tokens parsed from a Tcl command (e.g., the tokens
4967 * that make up a word or the index for an array variable) this function
4968 * evaluates the tokens and concatenates their values to form a single
4969 * result value.
4970 *
4971 * Results:
4972 * The return value is a standard Tcl completion code such as TCL_OK or
4973 * TCL_ERROR. A result or error message is left in interp's result.
4974 *
4975 * Side effects:
4976 * Depends on the array of tokens being evaled.
4977 *
4978 *----------------------------------------------------------------------
4979 */
4980
4981 int
4982 Tcl_EvalTokensStandard(
4983 Tcl_Interp *interp, /* Interpreter in which to lookup variables,
4984 * execute nested commands, and report
4985 * errors. */
4986 Tcl_Token *tokenPtr, /* Pointer to first in an array of tokens to
4987 * evaluate and concatenate. */
4988 int count) /* Number of tokens to consider at tokenPtr.
4989 * Must be at least 1. */
4990 {
4991 return TclSubstTokens(interp, tokenPtr, count, /* numLeftPtr */ NULL, 1,
4992 NULL, NULL);
4993 }
4994
4995 /*
4996 *----------------------------------------------------------------------
4997 *
4998 * Tcl_EvalTokens --
4999 *
5000 * Given an array of tokens parsed from a Tcl command (e.g., the tokens
5001 * that make up a word or the index for an array variable) this function
5002 * evaluates the tokens and concatenates their values to form a single
5003 * result value.
5004 *
5005 * Results:
5006 * The return value is a pointer to a newly allocated Tcl_Obj containing
5007 * the value of the array of tokens. The reference count of the returned
5008 * object has been incremented. If an error occurs in evaluating the
5009 * tokens then a NULL value is returned and an error message is left in
5010 * interp's result.
5011 *
5012 * Side effects:
5013 * A new object is allocated to hold the result.
5014 *
5015 *----------------------------------------------------------------------
5016 *
5017 * This uses a non-standard return convention; its use is now deprecated. It
5018 * is a wrapper for the new function Tcl_EvalTokensStandard, and is not used
5019 * in the core any longer. It is only kept for backward compatibility.
5020 */
5021
5022 Tcl_Obj *
5023 Tcl_EvalTokens(
5024 Tcl_Interp *interp, /* Interpreter in which to lookup variables,
5025 * execute nested commands, and report
5026 * errors. */
5027 Tcl_Token *tokenPtr, /* Pointer to first in an array of tokens to
5028 * evaluate and concatenate. */
5029 int count) /* Number of tokens to consider at tokenPtr.
5030 * Must be at least 1. */
5031 {
5032 Tcl_Obj *resPtr;
5033
5034 if (Tcl_EvalTokensStandard(interp, tokenPtr, count) != TCL_OK) {
5035 return NULL;
5036 }
5037 resPtr = Tcl_GetObjResult(interp);
5038 Tcl_IncrRefCount(resPtr);
5039 Tcl_ResetResult(interp);
5040 return resPtr;
5041 }
5042
5043 /*
5044 *----------------------------------------------------------------------
5045 *
5046 * Tcl_EvalEx, TclEvalEx --
5047 *
5048 * This function evaluates a Tcl script without using the compiler or
5049 * byte-code interpreter. It just parses the script, creates values for
5050 * each word of each command, then calls EvalObjv to execute each
5051 * command.
5052 *
5053 * Results:
5054 * The return value is a standard Tcl completion code such as TCL_OK or
5055 * TCL_ERROR. A result or error message is left in interp's result.
5056 *
5057 * Side effects:
5058 * Depends on the script.
5059 *
5060 * TIP #280 : Keep public API, internally extended API.
5061 *----------------------------------------------------------------------
5062 */
5063
5064 int
5065 Tcl_EvalEx(
5066 Tcl_Interp *interp, /* Interpreter in which to evaluate the
5067 * script. Also used for error reporting. */
5068 const char *script, /* First character of script to evaluate. */
5069 int numBytes, /* Number of bytes in script. If < 0, the
5070 * script consists of all bytes up to the
5071 * first null character. */
5072 int flags) /* Collection of OR-ed bits that control the
5073 * evaluation of the script. Only
5074 * TCL_EVAL_GLOBAL is currently supported. */
5075 {
5076 return TclEvalEx(interp, script, numBytes, flags, 1, NULL, script);
5077 }
5078
5079 int
5080 TclEvalEx(
5081 Tcl_Interp *interp, /* Interpreter in which to evaluate the
5082 * script. Also used for error reporting. */
5083 const char *script, /* First character of script to evaluate. */
5084 int numBytes, /* Number of bytes in script. If < 0, the
5085 * script consists of all bytes up to the
5086 * first NUL character. */
5087 int flags, /* Collection of OR-ed bits that control the
5088 * evaluation of the script. Only
5089 * TCL_EVAL_GLOBAL is currently supported. */
5090 int line, /* The line the script starts on. */
5091 int *clNextOuter, /* Information about an outer context for */
5092 const char *outerScript) /* continuation line data. This is set only in
5093 * TclSubstTokens(), to properly handle
5094 * [...]-nested commands. The 'outerScript'
5095 * refers to the most-outer script containing
5096 * the embedded command, which is referred to
5097 * by 'script'. The 'clNextOuter' refers to
5098 * the current entry in the table of
5099 * continuation lines in this "main script",
5100 * and the character offsets are relative to
5101 * the 'outerScript' as well.
5102 *
5103 * If outerScript == script, then this call is
5104 * for the outer-most script/command. See
5105 * Tcl_EvalEx() and TclEvalObjEx() for places
5106 * generating arguments for which this is
5107 * true. */
5108 {
5109 Interp *iPtr = (Interp *) interp;
5110 const char *p, *next;
5111 const unsigned int minObjs = 20;
5112 Tcl_Obj **objv, **objvSpace;
5113 int *expand, *lines, *lineSpace;
5114 Tcl_Token *tokenPtr;
5115 int commandLength, bytesLeft, expandRequested, code = TCL_OK;
5116 CallFrame *savedVarFramePtr;/* Saves old copy of iPtr->varFramePtr in case
5117 * TCL_EVAL_GLOBAL was set. */
5118 int allowExceptions = (iPtr->evalFlags & TCL_ALLOW_EXCEPTIONS);
5119 int gotParse = 0;
5120 unsigned int i, objectsUsed = 0;
5121 /* These variables keep track of how much
5122 * state has been allocated while evaluating
5123 * the script, so that it can be freed
5124 * properly if an error occurs. */
5125 Tcl_Parse *parsePtr = (Tcl_Parse *)TclStackAlloc(interp, sizeof(Tcl_Parse));
5126 CmdFrame *eeFramePtr = (CmdFrame *)TclStackAlloc(interp, sizeof(CmdFrame));
5127 Tcl_Obj **stackObjArray = (Tcl_Obj **)
5128 TclStackAlloc(interp, minObjs * sizeof(Tcl_Obj *));
5129 int *expandStack = (int *)TclStackAlloc(interp, minObjs * sizeof(int));
5130 int *linesStack = (int *)TclStackAlloc(interp, minObjs * sizeof(int));
5131 /* TIP #280 Structures for tracking of command
5132 * locations. */
5133 int *clNext = NULL; /* Pointer for the tracking of invisible
5134 * continuation lines. Initialized only if the
5135 * caller gave us a table of locations to
5136 * track, via scriptCLLocPtr. It always refers
5137 * to the table entry holding the location of
5138 * the next invisible continuation line to
5139 * look for, while parsing the script. */
5140
5141 if (iPtr->scriptCLLocPtr) {
5142 if (clNextOuter) {
5143 clNext = clNextOuter;
5144 } else {
5145 clNext = &iPtr->scriptCLLocPtr->loc[0];
5146 }
5147 }
5148
5149 if (numBytes < 0) {
5150 numBytes = strlen(script);
5151 }
5152 Tcl_ResetResult(interp);
5153
5154 savedVarFramePtr = iPtr->varFramePtr;
5155 if (flags & TCL_EVAL_GLOBAL) {
5156 iPtr->varFramePtr = iPtr->rootFramePtr;
5157 }
5158
5159 /*
5160 * Each iteration through the following loop parses the next command from
5161 * the script and then executes it.
5162 */
5163
5164 objv = objvSpace = stackObjArray;
5165 lines = lineSpace = linesStack;
5166 expand = expandStack;
5167 p = script;
5168 bytesLeft = numBytes;
5169
5170 /*
5171 * TIP #280 Initialize tracking. Do not push on the frame stack yet.
5172 *
5173 * We open a new context, either for a sourced script, or 'eval'.
5174 * For sourced files we always have a path object, even if nothing was
5175 * specified in the interp itself. That makes code using it simpler as
5176 * NULL checks can be left out. Sourced file without path in the
5177 * 'scriptFile' is possible during Tcl initialization.
5178 */
5179
5180 eeFramePtr->level = iPtr->cmdFramePtr ? iPtr->cmdFramePtr->level + 1 : 1;
5181 eeFramePtr->framePtr = iPtr->framePtr;
5182 eeFramePtr->nextPtr = iPtr->cmdFramePtr;
5183 eeFramePtr->nline = 0;
5184 eeFramePtr->line = NULL;
5185 eeFramePtr->cmdObj = NULL;
5186
5187 iPtr->cmdFramePtr = eeFramePtr;
5188 if (iPtr->evalFlags & TCL_EVAL_FILE) {
5189 /*
5190 * Set up for a sourced file.
5191 */
5192
5193 eeFramePtr->type = TCL_LOCATION_SOURCE;
5194
5195 if (iPtr->scriptFile) {
5196 /*
5197 * Normalization here, to have the correct pwd. Should have
5198 * negligible impact on performance, as the norm should have been
5199 * done already by the 'source' invoking us, and it caches the
5200 * result.
5201 */
5202
5203 Tcl_Obj *norm = Tcl_FSGetNormalizedPath(interp, iPtr->scriptFile);
5204
5205 if (norm == NULL) {
5206 /*
5207 * Error message in the interp result.
5208 */
5209
5210 code = TCL_ERROR;
5211 goto error;
5212 }
5213 eeFramePtr->data.eval.path = norm;
5214 } else {
5215 TclNewLiteralStringObj(eeFramePtr->data.eval.path, "");
5216 }
5217 Tcl_IncrRefCount(eeFramePtr->data.eval.path);
5218 } else {
5219 /*
5220 * Set up for plain eval.
5221 */
5222
5223 eeFramePtr->type = TCL_LOCATION_EVAL;
5224 eeFramePtr->data.eval.path = NULL;
5225 }
5226
5227 iPtr->evalFlags = 0;
5228 do {
5229 if (Tcl_ParseCommand(interp, p, bytesLeft, 0, parsePtr) != TCL_OK) {
5230 code = TCL_ERROR;
5231 Tcl_LogCommandInfo(interp, script, parsePtr->commandStart,
5232 parsePtr->term + 1 - parsePtr->commandStart);
5233 goto posterror;
5234 }
5235
5236 /*
5237 * TIP #280 Track lines. The parser may have skipped text till it
5238 * found the command we are now at. We have to count the lines in this
5239 * block, and do not forget invisible continuation lines.
5240 */
5241
5242 TclAdvanceLines(&line, p, parsePtr->commandStart);
5243 TclAdvanceContinuations(&line, &clNext,
5244 parsePtr->commandStart - outerScript);
5245
5246 gotParse = 1;
5247 if (parsePtr->numWords > 0) {
5248 /*
5249 * TIP #280. Track lines within the words of the current
5250 * command. We use a separate pointer into the table of
5251 * continuation line locations to not lose our position for the
5252 * per-command parsing.
5253 */
5254
5255 int wordLine = line;
5256 const char *wordStart = parsePtr->commandStart;
5257 int *wordCLNext = clNext;
5258 unsigned int objectsNeeded = 0;
5259 unsigned int numWords = parsePtr->numWords;
5260
5261 /*
5262 * Generate an array of objects for the words of the command.
5263 */
5264
5265 if (numWords > minObjs) {
5266 expand = (int *)ckalloc(numWords * sizeof(int));
5267 objvSpace = (Tcl_Obj **)ckalloc(numWords * sizeof(Tcl_Obj *));
5268 lineSpace = (int *)ckalloc(numWords * sizeof(int));
5269 }
5270 expandRequested = 0;
5271 objv = objvSpace;
5272 lines = lineSpace;
5273
5274 iPtr->cmdFramePtr = eeFramePtr->nextPtr;
5275 for (objectsUsed = 0, tokenPtr = parsePtr->tokenPtr;
5276 objectsUsed < numWords;
5277 objectsUsed++, tokenPtr += tokenPtr->numComponents + 1) {
5278 /*
5279 * TIP #280. Track lines to current word. Save the information
5280 * on a per-word basis, signaling dynamic words as needed.
5281 * Make the information available to the recursively called
5282 * evaluator as well, including the type of context (source
5283 * vs. eval).
5284 */
5285
5286 TclAdvanceLines(&wordLine, wordStart, tokenPtr->start);
5287 TclAdvanceContinuations(&wordLine, &wordCLNext,
5288 tokenPtr->start - outerScript);
5289 wordStart = tokenPtr->start;
5290
5291 lines[objectsUsed] = TclWordKnownAtCompileTime(tokenPtr, NULL)
5292 ? wordLine : -1;
5293
5294 if (eeFramePtr->type == TCL_LOCATION_SOURCE) {
5295 iPtr->evalFlags |= TCL_EVAL_FILE;
5296 }
5297
5298 code = TclSubstTokens(interp, tokenPtr + 1,
5299 tokenPtr->numComponents, NULL, wordLine,
5300 wordCLNext, outerScript);
5301
5302 iPtr->evalFlags = 0;
5303
5304 if (code != TCL_OK) {
5305 break;
5306 }
5307 objv[objectsUsed] = Tcl_GetObjResult(interp);
5308 Tcl_IncrRefCount(objv[objectsUsed]);
5309 if (tokenPtr->type == TCL_TOKEN_EXPAND_WORD) {
5310 int numElements;
5311
5312 code = TclListObjLength(interp, objv[objectsUsed],
5313 &numElements);
5314 if (code == TCL_ERROR) {
5315 /*
5316 * Attempt to expand a non-list.
5317 */
5318
5319 Tcl_AppendObjToErrorInfo(interp, Tcl_ObjPrintf(
5320 "\n (expanding word %d)", objectsUsed));
5321 Tcl_DecrRefCount(objv[objectsUsed]);
5322 break;
5323 }
5324 expandRequested = 1;
5325 expand[objectsUsed] = 1;
5326
5327 objectsNeeded += (numElements ? numElements : 1);
5328 } else {
5329 expand[objectsUsed] = 0;
5330 objectsNeeded++;
5331 }
5332
5333 if (wordCLNext) {
5334 TclContinuationsEnterDerived(objv[objectsUsed],
5335 wordStart - outerScript, wordCLNext);
5336 }
5337 } /* for loop */
5338 iPtr->cmdFramePtr = eeFramePtr;
5339 if (code != TCL_OK) {
5340 goto error;
5341 }
5342 if (expandRequested) {
5343 /*
5344 * Some word expansion was requested. Check for objv resize.
5345 */
5346
5347 Tcl_Obj **copy = objvSpace;
5348 int *lcopy = lineSpace;
5349 int wordIdx = numWords;
5350 int objIdx = objectsNeeded - 1;
5351
5352 if ((numWords > minObjs) || (objectsNeeded > minObjs)) {
5353 objv = objvSpace = (Tcl_Obj **)ckalloc(objectsNeeded * sizeof(Tcl_Obj *));
5354 lines = lineSpace = (int *)ckalloc(objectsNeeded * sizeof(int));
5355 }
5356
5357 objectsUsed = 0;
5358 while (wordIdx--) {
5359 if (expand[wordIdx]) {
5360 int numElements;
5361 Tcl_Obj **elements, *temp = copy[wordIdx];
5362
5363 TclListObjGetElements(NULL, temp, &numElements,
5364 &elements);
5365 objectsUsed += numElements;
5366 while (numElements--) {
5367 lines[objIdx] = -1;
5368 objv[objIdx--] = elements[numElements];
5369 Tcl_IncrRefCount(elements[numElements]);
5370 }
5371 Tcl_DecrRefCount(temp);
5372 } else {
5373 lines[objIdx] = lcopy[wordIdx];
5374 objv[objIdx--] = copy[wordIdx];
5375 objectsUsed++;
5376 }
5377 }
5378 objv += objIdx + 1;
5379
5380 if (copy != stackObjArray) {
5381 ckfree(copy);
5382 }
5383 if (lcopy != linesStack) {
5384 ckfree(lcopy);
5385 }
5386 }
5387
5388 /*
5389 * Execute the command and free the objects for its words.
5390 *
5391 * TIP #280: Remember the command itself for 'info frame'. We
5392 * shorten the visible command by one char to exclude the
5393 * termination character, if necessary. Here is where we put our
5394 * frame on the stack of frames too. _After_ the nested commands
5395 * have been executed.
5396 */
5397
5398 eeFramePtr->cmd = parsePtr->commandStart;
5399 eeFramePtr->len = parsePtr->commandSize;
5400
5401 if (parsePtr->term ==
5402 parsePtr->commandStart + parsePtr->commandSize - 1) {
5403 eeFramePtr->len--;
5404 }
5405
5406 eeFramePtr->nline = objectsUsed;
5407 eeFramePtr->line = lines;
5408
5409 TclArgumentEnter(interp, objv, objectsUsed, eeFramePtr);
5410 code = Tcl_EvalObjv(interp, objectsUsed, objv,
5411 TCL_EVAL_NOERR | TCL_EVAL_SOURCE_IN_FRAME);
5412 TclArgumentRelease(interp, objv, objectsUsed);
5413
5414 eeFramePtr->line = NULL;
5415 eeFramePtr->nline = 0;
5416 if (eeFramePtr->cmdObj) {
5417 Tcl_DecrRefCount(eeFramePtr->cmdObj);
5418 eeFramePtr->cmdObj = NULL;
5419 }
5420
5421 if (code != TCL_OK) {
5422 goto error;
5423 }
5424 for (i = 0; i < objectsUsed; i++) {
5425 Tcl_DecrRefCount(objv[i]);
5426 }
5427 objectsUsed = 0;
5428 if (objvSpace != stackObjArray) {
5429 ckfree(objvSpace);
5430 objvSpace = stackObjArray;
5431 ckfree(lineSpace);
5432 lineSpace = linesStack;
5433 }
5434
5435 /*
5436 * Free expand separately since objvSpace could have been
5437 * reallocated above.
5438 */
5439
5440 if (expand != expandStack) {
5441 ckfree(expand);
5442 expand = expandStack;
5443 }
5444 }
5445
5446 /*
5447 * Advance to the next command in the script.
5448 *
5449 * TIP #280 Track Lines. Now we track how many lines were in the
5450 * executed command.
5451 */
5452
5453 next = parsePtr->commandStart + parsePtr->commandSize;
5454 bytesLeft -= next - p;
5455 p = next;
5456 TclAdvanceLines(&line, parsePtr->commandStart, p);
5457 Tcl_FreeParse(parsePtr);
5458 gotParse = 0;
5459 } while (bytesLeft > 0);
5460 iPtr->varFramePtr = savedVarFramePtr;
5461 code = TCL_OK;
5462 goto cleanup_return;
5463
5464 error:
5465 /*
5466 * Generate and log various pieces of error information.
5467 */
5468
5469 if (iPtr->numLevels == 0) {
5470 if (code == TCL_RETURN) {
5471 code = TclUpdateReturnInfo(iPtr);
5472 }
5473 if ((code != TCL_OK) && (code != TCL_ERROR) && !allowExceptions) {
5474 ProcessUnexpectedResult(interp, code);
5475 code = TCL_ERROR;
5476 }
5477 }
5478 if ((code == TCL_ERROR) && !(iPtr->flags & ERR_ALREADY_LOGGED)) {
5479 commandLength = parsePtr->commandSize;
5480 if (parsePtr->term == parsePtr->commandStart + commandLength - 1) {
5481 /*
5482 * The terminator character (such as ; or ]) of the command where
5483 * the error occurred is the last character in the parsed command.
5484 * Reduce the length by one so that the error message doesn't
5485 * include the terminator character.
5486 */
5487
5488 commandLength -= 1;
5489 }
5490 Tcl_LogCommandInfo(interp, script, parsePtr->commandStart,
5491 commandLength);
5492 }
5493 posterror:
5494 iPtr->flags &= ~ERR_ALREADY_LOGGED;
5495
5496 /*
5497 * Then free resources that had been allocated to the command.
5498 */
5499
5500 for (i = 0; i < objectsUsed; i++) {
5501 Tcl_DecrRefCount(objv[i]);
5502 }
5503 if (gotParse) {
5504 Tcl_FreeParse(parsePtr);
5505 }
5506 if (objvSpace != stackObjArray) {
5507 ckfree(objvSpace);
5508 ckfree(lineSpace);
5509 }
5510 if (expand != expandStack) {
5511 ckfree(expand);
5512 }
5513 iPtr->varFramePtr = savedVarFramePtr;
5514
5515 cleanup_return:
5516 /*
5517 * TIP #280. Release the local CmdFrame, and its contents.
5518 */
5519
5520 iPtr->cmdFramePtr = iPtr->cmdFramePtr->nextPtr;
5521 if (eeFramePtr->type == TCL_LOCATION_SOURCE) {
5522 Tcl_DecrRefCount(eeFramePtr->data.eval.path);
5523 }
5524 TclStackFree(interp, linesStack);
5525 TclStackFree(interp, expandStack);
5526 TclStackFree(interp, stackObjArray);
5527 TclStackFree(interp, eeFramePtr);
5528 TclStackFree(interp, parsePtr);
5529
5530 return code;
5531 }
5532
5533 /*
5534 *----------------------------------------------------------------------
5535 *
5536 * TclAdvanceLines --
5537 *
5538 * This function is a helper which counts the number of lines in a block
5539 * of text and advances an external counter.
5540 *
5541 * Results:
5542 * None.
5543 *
5544 * Side effects:
5545 * The specified counter is advanced per the number of lines found.
5546 *
5547 * TIP #280
5548 *----------------------------------------------------------------------
5549 */
5550
5551 void
5552 TclAdvanceLines(
5553 int *line,
5554 const char *start,
5555 const char *end)
5556 {
5557 const char *p;
5558
5559 for (p = start; p < end; p++) {
5560 if (*p == '\n') {
5561 (*line)++;
5562 }
5563 }
5564 }
5565
5566 /*
5567 *----------------------------------------------------------------------
5568 *
5569 * TclAdvanceContinuations --
5570 *
5571 * This procedure is a helper which counts the number of continuation
5572 * lines (CL) in a block of text using a table of CL locations and
5573 * advances an external counter, and the pointer into the table.
5574 *
5575 * Results:
5576 * None.
5577 *
5578 * Side effects:
5579 * The specified counter is advanced per the number of continuation lines
5580 * found.
5581 *
5582 * TIP #280
5583 *----------------------------------------------------------------------
5584 */
5585
5586 void
5587 TclAdvanceContinuations(
5588 int *line,
5589 int **clNextPtrPtr,
5590 int loc)
5591 {
5592 /*
5593 * Track the invisible continuation lines embedded in a script, if any.
5594 * Here they are just spaces (already). They were removed by
5595 * TclSubstTokens via TclParseBackslash.
5596 *
5597 * *clNextPtrPtr <=> We have continuation lines to track.
5598 * **clNextPtrPtr >= 0 <=> We are not beyond the last possible location.
5599 * loc >= **clNextPtrPtr <=> We stepped beyond the current cont. line.
5600 */
5601
5602 while (*clNextPtrPtr && (**clNextPtrPtr >= 0)
5603 && (loc >= **clNextPtrPtr)) {
5604 /*
5605 * We just stepped over an invisible continuation line. Adjust the
5606 * line counter and step to the table entry holding the location of
5607 * the next continuation line to track.
5608 */
5609
5610 (*line)++;
5611 (*clNextPtrPtr)++;
5612 }
5613 }
5614
5615 /*
5616 *----------------------------------------------------------------------
5617 * Note: The whole data structure access for argument location tracking is
5618 * hidden behind these three functions. The only parts open are the lineLAPtr
5619 * field in the Interp structure. The CFWord definition is internal to here.
5620 * Should make it easier to redo the data structures if we find something more
5621 * space/time efficient.
5622 */
5623
5624 /*
5625 *----------------------------------------------------------------------
5626 *
5627 * TclArgumentEnter --
5628 *
5629 * This procedure is a helper for the TIP #280 uplevel extension. It
5630 * enters location references for the arguments of a command to be
5631 * invoked. Only the first entry has the actual data, further entries
5632 * simply count the usage up.
5633 *
5634 * Results:
5635 * None.
5636 *
5637 * Side effects:
5638 * May allocate memory.
5639 *
5640 * TIP #280
5641 *----------------------------------------------------------------------
5642 */
5643
5644 void
5645 TclArgumentEnter(
5646 Tcl_Interp *interp,
5647 Tcl_Obj **objv,
5648 int objc,
5649 CmdFrame *cfPtr)
5650 {
5651 Interp *iPtr = (Interp *) interp;
5652 int isNew;
5653 int i;
5654 Tcl_HashEntry *hPtr;
5655 CFWord *cfwPtr;
5656
5657 for (i = 1; i < objc; i++) {
5658 /*
5659 * Ignore argument words without line information (= dynamic). If they
5660 * are variables they may have location information associated with
5661 * that, either through globally recorded 'set' invocations, or
5662 * literals in bytecode. Either way there is no need to record
5663 * something here.
5664 */
5665
5666 if (cfPtr->line[i] < 0) {
5667 continue;
5668 }
5669 hPtr = Tcl_CreateHashEntry(iPtr->lineLAPtr, objv[i], &isNew);
5670 if (isNew) {
5671 /*
5672 * The word is not on the stack yet, remember the current location
5673 * and initialize references.
5674 */
5675
5676 cfwPtr = (CFWord *)ckalloc(sizeof(CFWord));
5677 cfwPtr->framePtr = cfPtr;
5678 cfwPtr->word = i;
5679 cfwPtr->refCount = 1;
5680 Tcl_SetHashValue(hPtr, cfwPtr);
5681 } else {
5682 /*
5683 * The word is already on the stack, its current location is not
5684 * relevant. Just remember the reference to prevent early removal.
5685 */
5686
5687 cfwPtr = (CFWord *)Tcl_GetHashValue(hPtr);
5688 cfwPtr->refCount++;
5689 }
5690 }
5691 }
5692
5693 /*
5694 *----------------------------------------------------------------------
5695 *
5696 * TclArgumentRelease --
5697 *
5698 * This procedure is a helper for the TIP #280 uplevel extension. It
5699 * removes the location references for the arguments of a command just
5700 * done. Usage is counted down, the data is removed only when no user is
5701 * left over.
5702 *
5703 * Results:
5704 * None.
5705 *
5706 * Side effects:
5707 * May release memory.
5708 *
5709 * TIP #280
5710 *----------------------------------------------------------------------
5711 */
5712
5713 void
5714 TclArgumentRelease(
5715 Tcl_Interp *interp,
5716 Tcl_Obj **objv,
5717 int objc)
5718 {
5719 Interp *iPtr = (Interp *) interp;
5720 int i;
5721
5722 for (i = 1; i < objc; i++) {
5723 CFWord *cfwPtr;
5724 Tcl_HashEntry *hPtr = Tcl_FindHashEntry(iPtr->lineLAPtr, (char *)objv[i]);
5725
5726 if (!hPtr) {
5727 continue;
5728 }
5729 cfwPtr = (CFWord *)Tcl_GetHashValue(hPtr);
5730
5731 if (cfwPtr->refCount-- > 1) {
5732 continue;
5733 }
5734
5735 ckfree(cfwPtr);
5736 Tcl_DeleteHashEntry(hPtr);
5737 }
5738 }
5739
5740 /*
5741 *----------------------------------------------------------------------
5742 *
5743 * TclArgumentBCEnter --
5744 *
5745 * This procedure is a helper for the TIP #280 uplevel extension. It
5746 * enters location references for the literal arguments of commands in
5747 * bytecode about to be invoked. Only the first entry has the actual
5748 * data, further entries simply count the usage up.
5749 *
5750 * Results:
5751 * None.
5752 *
5753 * Side effects:
5754 * May allocate memory.
5755 *
5756 * TIP #280
5757 *----------------------------------------------------------------------
5758 */
5759
5760 void
5761 TclArgumentBCEnter(
5762 Tcl_Interp *interp,
5763 Tcl_Obj *objv[],
5764 int objc,
5765 void *codePtr,
5766 CmdFrame *cfPtr,
5767 int cmd,
5768 int pc)
5769 {
5770 ExtCmdLoc *eclPtr;
5771 int word;
5772 ECL *ePtr;
5773 CFWordBC *lastPtr = NULL;
5774 Interp *iPtr = (Interp *) interp;
5775 Tcl_HashEntry *hePtr = Tcl_FindHashEntry(iPtr->lineBCPtr, (char *)codePtr);
5776
5777 if (!hePtr) {
5778 return;
5779 }
5780 eclPtr = (ExtCmdLoc *)Tcl_GetHashValue(hePtr);
5781 ePtr = &eclPtr->loc[cmd];
5782
5783 /*
5784 * ePtr->nline is the number of words originally parsed.
5785 *
5786 * objc is the number of elements getting invoked.
5787 *
5788 * If they are not the same, we arrived here by compiling an
5789 * ensemble dispatch. Ensemble subcommands that lead to script
5790 * evaluation are not supposed to get compiled, because a command
5791 * such as [info level] in the script can expose some of the dispatch
5792 * shenanigans. This means that we don't have to tend to the
5793 * housekeeping, and can escape now.
5794 */
5795
5796 if (ePtr->nline != objc) {
5797 return;
5798 }
5799
5800 /*
5801 * Having disposed of the ensemble cases, we can state...
5802 * A few truths ...
5803 * (1) ePtr->nline == objc
5804 * (2) (ePtr->line[word] < 0) => !literal, for all words
5805 * (3) (word == 0) => !literal
5806 *
5807 * Item (2) is why we can use objv to get the literals, and do not
5808 * have to save them at compile time.
5809 */
5810
5811 for (word = 1; word < objc; word++) {
5812 if (ePtr->line[word] >= 0) {
5813 int isNew;
5814 Tcl_HashEntry *hPtr = Tcl_CreateHashEntry(iPtr->lineLABCPtr,
5815 objv[word], &isNew);
5816 CFWordBC *cfwPtr = (CFWordBC *)ckalloc(sizeof(CFWordBC));
5817
5818 cfwPtr->framePtr = cfPtr;
5819 cfwPtr->obj = objv[word];
5820 cfwPtr->pc = pc;
5821 cfwPtr->word = word;
5822 cfwPtr->nextPtr = lastPtr;
5823 lastPtr = cfwPtr;
5824
5825 if (isNew) {
5826 /*
5827 * The word is not on the stack yet, remember the current
5828 * location and initialize references.
5829 */
5830
5831 cfwPtr->prevPtr = NULL;
5832 } else {
5833 /*
5834 * The object is already on the stack, however it may have
5835 * a different location now (literal sharing may map
5836 * multiple location to a single Tcl_Obj*. Save the old
5837 * information in the new structure.
5838 */
5839
5840 cfwPtr->prevPtr = (CFWordBC *)Tcl_GetHashValue(hPtr);
5841 }
5842
5843 Tcl_SetHashValue(hPtr, cfwPtr);
5844 }
5845 } /* for */
5846
5847 cfPtr->litarg = lastPtr;
5848 }
5849
5850 /*
5851 *----------------------------------------------------------------------
5852 *
5853 * TclArgumentBCRelease --
5854 *
5855 * This procedure is a helper for the TIP #280 uplevel extension. It
5856 * removes the location references for the literal arguments of commands
5857 * in bytecode just done. Usage is counted down, the data is removed only
5858 * when no user is left over.
5859 *
5860 * Results:
5861 * None.
5862 *
5863 * Side effects:
5864 * May release memory.
5865 *
5866 * TIP #280
5867 *----------------------------------------------------------------------
5868 */
5869
5870 void
5871 TclArgumentBCRelease(
5872 Tcl_Interp *interp,
5873 CmdFrame *cfPtr)
5874 {
5875 Interp *iPtr = (Interp *) interp;
5876 CFWordBC *cfwPtr = (CFWordBC *) cfPtr->litarg;
5877
5878 while (cfwPtr) {
5879 CFWordBC *nextPtr = cfwPtr->nextPtr;
5880 Tcl_HashEntry *hPtr =
5881 Tcl_FindHashEntry(iPtr->lineLABCPtr, (char *)cfwPtr->obj);
5882 CFWordBC *xPtr = (CFWordBC *)Tcl_GetHashValue(hPtr);
5883
5884 if (xPtr != cfwPtr) {
5885 Tcl_Panic("TclArgumentBC Enter/Release Mismatch");
5886 }
5887
5888 if (cfwPtr->prevPtr) {
5889 Tcl_SetHashValue(hPtr, cfwPtr->prevPtr);
5890 } else {
5891 Tcl_DeleteHashEntry(hPtr);
5892 }
5893
5894 ckfree(cfwPtr);
5895 cfwPtr = nextPtr;
5896 }
5897
5898 cfPtr->litarg = NULL;
5899 }
5900
5901 /*
5902 *----------------------------------------------------------------------
5903 *
5904 * TclArgumentGet --
5905 *
5906 * This procedure is a helper for the TIP #280 uplevel extension. It
5907 * finds the location references for a Tcl_Obj, if any.
5908 *
5909 * Results:
5910 * None.
5911 *
5912 * Side effects:
5913 * Writes found location information into the result arguments.
5914 *
5915 * TIP #280
5916 *----------------------------------------------------------------------
5917 */
5918
5919 void
5920 TclArgumentGet(
5921 Tcl_Interp *interp,
5922 Tcl_Obj *obj,
5923 CmdFrame **cfPtrPtr,
5924 int *wordPtr)
5925 {
5926 Interp *iPtr = (Interp *) interp;
5927 Tcl_HashEntry *hPtr;
5928 CmdFrame *framePtr;
5929
5930 /*
5931 * An object which either has no string rep or else is a canonical list is
5932 * guaranteed to have been generated dynamically: bail out, this cannot
5933 * have a usable absolute location. _Do not touch_ the information the set
5934 * up by the caller. It knows better than us.
5935 */
5936
5937 if ((obj->bytes == NULL) || TclListObjIsCanonical(obj)) {
5938 return;
5939 }
5940
5941 /*
5942 * First look for location information recorded in the argument
5943 * stack. That is nearest.
5944 */
5945
5946 hPtr = Tcl_FindHashEntry(iPtr->lineLAPtr, (char *)obj);
5947 if (hPtr) {
5948 CFWord *cfwPtr = (CFWord *)Tcl_GetHashValue(hPtr);
5949
5950 *wordPtr = cfwPtr->word;
5951 *cfPtrPtr = cfwPtr->framePtr;
5952 return;
5953 }
5954
5955 /*
5956 * Check if the Tcl_Obj has location information as a bytecode literal, in
5957 * that stack.
5958 */
5959
5960 hPtr = Tcl_FindHashEntry(iPtr->lineLABCPtr, (char *)obj);
5961 if (hPtr) {
5962 CFWordBC *cfwPtr = (CFWordBC *)Tcl_GetHashValue(hPtr);
5963
5964 framePtr = cfwPtr->framePtr;
5965 framePtr->data.tebc.pc = (char *)(((ByteCode *)
5966 framePtr->data.tebc.codePtr)->codeStart + cfwPtr->pc);
5967 *cfPtrPtr = cfwPtr->framePtr;
5968 *wordPtr = cfwPtr->word;
5969 return;
5970 }
5971 }
5972
5973 /*
5974 *----------------------------------------------------------------------
5975 *
5976 * Tcl_Eval --
5977 *
5978 * Execute a Tcl command in a string. This function executes the script
5979 * directly, rather than compiling it to bytecodes. Before the arrival of
5980 * the bytecode compiler in Tcl 8.0 Tcl_Eval was the main function used
5981 * for executing Tcl commands, but nowadays it isn't used much.
5982 *
5983 * Results:
5984 * The return value is one of the return codes defined in tcl.h (such as
5985 * TCL_OK), and interp's result contains a value to supplement the return
5986 * code. The value of the result will persist only until the next call to
5987 * Tcl_Eval or Tcl_EvalObj: you must copy it or lose it!
5988 *
5989 * Side effects:
5990 * Can be almost arbitrary, depending on the commands in the script.
5991 *
5992 *----------------------------------------------------------------------
5993 */
5994
5995 #undef Tcl_Eval
5996 int
5997 Tcl_Eval(
5998 Tcl_Interp *interp, /* Token for command interpreter (returned by
5999 * previous call to Tcl_CreateInterp). */
6000 const char *script) /* Pointer to TCL command to execute. */
6001 {
6002 int code = Tcl_EvalEx(interp, script, -1, 0);
6003
6004 /*
6005 * For backwards compatibility with old C code that predates the object
6006 * system in Tcl 8.0, we have to mirror the object result back into the
6007 * string result (some callers may expect it there).
6008 */
6009
6010 (void)Tcl_GetStringResult(interp);
6011 return code;
6012 }
6013
6014 /*
6015 *----------------------------------------------------------------------
6016 *
6017 * Tcl_EvalObj, Tcl_GlobalEvalObj --
6018 *
6019 * These functions are deprecated but we keep them around for backwards
6020 * compatibility reasons.
6021 *
6022 * Results:
6023 * See the functions they call.
6024 *
6025 * Side effects:
6026 * See the functions they call.
6027 *
6028 *----------------------------------------------------------------------
6029 */
6030
6031 #undef Tcl_EvalObj
6032 int
6033 Tcl_EvalObj(
6034 Tcl_Interp *interp,
6035 Tcl_Obj *objPtr)
6036 {
6037 return Tcl_EvalObjEx(interp, objPtr, 0);
6038 }
6039 #undef Tcl_GlobalEvalObj
6040 int
6041 Tcl_GlobalEvalObj(
6042 Tcl_Interp *interp,
6043 Tcl_Obj *objPtr)
6044 {
6045 return Tcl_EvalObjEx(interp, objPtr, TCL_EVAL_GLOBAL);
6046 }
6047
6048 /*
6049 *----------------------------------------------------------------------
6050 *
6051 * Tcl_EvalObjEx, TclEvalObjEx --
6052 *
6053 * Execute Tcl commands stored in a Tcl object. These commands are
6054 * compiled into bytecodes if necessary, unless TCL_EVAL_DIRECT is
6055 * specified.
6056 *
6057 * If the flag TCL_EVAL_DIRECT is passed in, the value of invoker
6058 * must be NULL. Support for non-NULL invokers in that mode has
6059 * been removed since it was unused and untested. Failure to
6060 * follow this limitation will lead to an assertion panic.
6061 *
6062 * Results:
6063 * The return value is one of the return codes defined in tcl.h (such as
6064 * TCL_OK), and the interpreter's result contains a value to supplement
6065 * the return code.
6066 *
6067 * Side effects:
6068 * The object is converted, if necessary, to a ByteCode object that holds
6069 * the bytecode instructions for the commands. Executing the commands
6070 * will almost certainly have side effects that depend on those commands.
6071 *
6072 * TIP #280 : Keep public API, internally extended API.
6073 *----------------------------------------------------------------------
6074 */
6075
6076 int
6077 Tcl_EvalObjEx(
6078 Tcl_Interp *interp, /* Token for command interpreter (returned by
6079 * a previous call to Tcl_CreateInterp). */
6080 Tcl_Obj *objPtr, /* Pointer to object containing commands to
6081 * execute. */
6082 int flags) /* Collection of OR-ed bits that control the
6083 * evaluation of the script. Supported values
6084 * are TCL_EVAL_GLOBAL and TCL_EVAL_DIRECT. */
6085 {
6086 return TclEvalObjEx(interp, objPtr, flags, NULL, 0);
6087 }
6088
6089 int
6090 TclEvalObjEx(
6091 Tcl_Interp *interp, /* Token for command interpreter (returned by
6092 * a previous call to Tcl_CreateInterp). */
6093 Tcl_Obj *objPtr, /* Pointer to object containing commands to
6094 * execute. */
6095 int flags, /* Collection of OR-ed bits that control the
6096 * evaluation of the script. Supported values
6097 * are TCL_EVAL_GLOBAL and TCL_EVAL_DIRECT. */
6098 const CmdFrame *invoker, /* Frame of the command doing the eval. */
6099 int word) /* Index of the word which is in objPtr. */
6100 {
6101 int result = TCL_OK;
6102 NRE_callback *rootPtr = TOP_CB(interp);
6103
6104 result = TclNREvalObjEx(interp, objPtr, flags, invoker, word);
6105 return TclNRRunCallbacks(interp, result, rootPtr);
6106 }
6107
6108 int
6109 TclNREvalObjEx(
6110 Tcl_Interp *interp, /* Token for command interpreter (returned by
6111 * a previous call to Tcl_CreateInterp). */
6112 Tcl_Obj *objPtr, /* Pointer to object containing commands to
6113 * execute. */
6114 int flags, /* Collection of OR-ed bits that control the
6115 * evaluation of the script. Supported values
6116 * are TCL_EVAL_GLOBAL and TCL_EVAL_DIRECT. */
6117 const CmdFrame *invoker, /* Frame of the command doing the eval. */
6118 int word) /* Index of the word which is in objPtr. */
6119 {
6120 Interp *iPtr = (Interp *) interp;
6121 int result;
6122
6123 /*
6124 * This function consists of three independent blocks for: direct
6125 * evaluation of canonical lists, compilation and bytecode execution and
6126 * finally direct evaluation. Precisely one of these blocks will be run.
6127 */
6128
6129 if (TclListObjIsCanonical(objPtr)) {
6130 CmdFrame *eoFramePtr = NULL;
6131 int objc;
6132 Tcl_Obj *listPtr, **objv;
6133
6134 /*
6135 * Canonical List Optimization: In this case, we
6136 * can safely use Tcl_EvalObjv instead and get an appreciable
6137 * improvement in execution speed. This is because it allows us to
6138 * avoid a setFromAny step that would just pack everything into a
6139 * string and back out again.
6140 *
6141 * This also preserves any associations between list elements and
6142 * location information for such elements.
6143 */
6144
6145 /*
6146 * Shimmer protection! Always pass an unshared obj. The caller could
6147 * incr the refCount of objPtr AFTER calling us! To be completely safe
6148 * we always make a copy. The callback takes care of the refCounts for
6149 * both listPtr and objPtr.
6150 *
6151 * TODO: Create a test to demo this need, or eliminate it.
6152 * FIXME OPT: preserve just the internal rep?
6153 */
6154
6155 Tcl_IncrRefCount(objPtr);
6156 listPtr = TclListObjCopy(interp, objPtr);
6157 Tcl_IncrRefCount(listPtr);
6158
6159 if (word != INT_MIN) {
6160 /*
6161 * TIP #280 Structures for tracking lines. As we know that this is
6162 * dynamic execution we ignore the invoker, even if known.
6163 *
6164 * TIP #280. We do _not_ compute all the line numbers for the
6165 * words in the command. For the eval of a pure list the most
6166 * sensible choice is to put all words on line 1. Given that we
6167 * neither need memory for them nor compute anything. 'line' is
6168 * left NULL. The two places using this information (TclInfoFrame,
6169 * and TclInitCompileEnv), are special-cased to use the proper
6170 * line number directly instead of accessing the 'line' array.
6171 *
6172 * Note that we use (word==INTMIN) to signal that no command frame
6173 * should be pushed, as needed by alias and ensemble redirections.
6174 */
6175
6176 eoFramePtr = (CmdFrame *)TclStackAlloc(interp, sizeof(CmdFrame));
6177 eoFramePtr->nline = 0;
6178 eoFramePtr->line = NULL;
6179
6180 eoFramePtr->type = TCL_LOCATION_EVAL;
6181 eoFramePtr->level = (iPtr->cmdFramePtr == NULL?
6182 1 : iPtr->cmdFramePtr->level + 1);
6183 eoFramePtr->framePtr = iPtr->framePtr;
6184 eoFramePtr->nextPtr = iPtr->cmdFramePtr;
6185
6186 eoFramePtr->cmdObj = objPtr;
6187 eoFramePtr->cmd = NULL;
6188 eoFramePtr->len = 0;
6189 eoFramePtr->data.eval.path = NULL;
6190
6191 iPtr->cmdFramePtr = eoFramePtr;
6192
6193 flags |= TCL_EVAL_SOURCE_IN_FRAME;
6194 }
6195
6196 TclMarkTailcall(interp);
6197 TclNRAddCallback(interp, TEOEx_ListCallback, listPtr, eoFramePtr,
6198 objPtr, NULL);
6199
6200 ListObjGetElements(listPtr, objc, objv);
6201 return TclNREvalObjv(interp, objc, objv, flags, NULL);
6202 }
6203
6204 if (!(flags & TCL_EVAL_DIRECT)) {
6205 /*
6206 * Let the compiler/engine subsystem do the evaluation.
6207 *
6208 * TIP #280 The invoker provides us with the context for the script.
6209 * We transfer this to the byte code compiler.
6210 */
6211
6212 int allowExceptions = (iPtr->evalFlags & TCL_ALLOW_EXCEPTIONS);
6213 ByteCode *codePtr;
6214 CallFrame *savedVarFramePtr = NULL; /* Saves old copy of
6215 * iPtr->varFramePtr in case
6216 * TCL_EVAL_GLOBAL was set. */
6217
6218 if (TclInterpReady(interp) != TCL_OK) {
6219 return TCL_ERROR;
6220 }
6221 if (flags & TCL_EVAL_GLOBAL) {
6222 savedVarFramePtr = iPtr->varFramePtr;
6223 iPtr->varFramePtr = iPtr->rootFramePtr;
6224 }
6225 Tcl_IncrRefCount(objPtr);
6226 codePtr = TclCompileObj(interp, objPtr, invoker, word);
6227
6228 TclNRAddCallback(interp, TEOEx_ByteCodeCallback, savedVarFramePtr,
6229 objPtr, INT2PTR(allowExceptions), NULL);
6230 return TclNRExecuteByteCode(interp, codePtr);
6231 }
6232
6233 {
6234 /*
6235 * We're not supposed to use the compiler or byte-code
6236 * interpreter. Let Tcl_EvalEx evaluate the command directly (and
6237 * probably more slowly).
6238 */
6239
6240 const char *script;
6241 int numSrcBytes;
6242
6243 /*
6244 * Now we check if we have data about invisible continuation lines for
6245 * the script, and make it available to the direct script parser and
6246 * evaluator we are about to call, if so.
6247 *
6248 * It may be possible that the script Tcl_Obj* can be free'd while the
6249 * evaluator is using it, leading to the release of the associated
6250 * ContLineLoc structure as well. To ensure that the latter doesn't
6251 * happen we set a lock on it. We release this lock later in this
6252 * function, after the evaluator is done. The relevant "lineCLPtr"
6253 * hashtable is managed in the file "tclObj.c".
6254 *
6255 * Another important action is to save (and later restore) the
6256 * continuation line information of the caller, in case we are
6257 * executing nested commands in the eval/direct path.
6258 */
6259
6260 ContLineLoc *saveCLLocPtr = iPtr->scriptCLLocPtr;
6261
6262 assert(invoker == NULL);
6263
6264 iPtr->scriptCLLocPtr = TclContinuationsGet(objPtr);
6265
6266 Tcl_IncrRefCount(objPtr);
6267
6268 script = TclGetStringFromObj(objPtr, &numSrcBytes);
6269 result = Tcl_EvalEx(interp, script, numSrcBytes, flags);
6270
6271 TclDecrRefCount(objPtr);
6272
6273 iPtr->scriptCLLocPtr = saveCLLocPtr;
6274 return result;
6275 }
6276 }
6277
6278 static int
6279 TEOEx_ByteCodeCallback(
6280 ClientData data[],
6281 Tcl_Interp *interp,
6282 int result)
6283 {
6284 Interp *iPtr = (Interp *) interp;
6285 CallFrame *savedVarFramePtr = (CallFrame *)data[0];
6286 Tcl_Obj *objPtr = (Tcl_Obj *)data[1];
6287 int allowExceptions = PTR2INT(data[2]);
6288
6289 if (iPtr->numLevels == 0) {
6290 if (result == TCL_RETURN) {
6291 result = TclUpdateReturnInfo(iPtr);
6292 }
6293 if ((result != TCL_OK) && (result != TCL_ERROR) && !allowExceptions) {
6294 const char *script;
6295 int numSrcBytes;
6296
6297 ProcessUnexpectedResult(interp, result);
6298 result = TCL_ERROR;
6299 script = TclGetStringFromObj(objPtr, &numSrcBytes);
6300 Tcl_LogCommandInfo(interp, script, script, numSrcBytes);
6301 }
6302
6303 /*
6304 * We are returning to level 0, so should call TclResetCancellation.
6305 * Let us just unset the flags inline.
6306 */
6307
6308 TclUnsetCancelFlags(iPtr);
6309 }
6310 iPtr->evalFlags = 0;
6311
6312 /*
6313 * Restore the callFrame if this was a TCL_EVAL_GLOBAL.
6314 */
6315
6316 if (savedVarFramePtr) {
6317 iPtr->varFramePtr = savedVarFramePtr;
6318 }
6319
6320 TclDecrRefCount(objPtr);
6321 return result;
6322 }
6323
6324 static int
6325 TEOEx_ListCallback(
6326 ClientData data[],
6327 Tcl_Interp *interp,
6328 int result)
6329 {
6330 Interp *iPtr = (Interp *) interp;
6331 Tcl_Obj *listPtr = (Tcl_Obj *)data[0];
6332 CmdFrame *eoFramePtr = (CmdFrame *)data[1];
6333 Tcl_Obj *objPtr = (Tcl_Obj *)data[2];
6334
6335 /*
6336 * Remove the cmdFrame
6337 */
6338
6339 if (eoFramePtr) {
6340 iPtr->cmdFramePtr = eoFramePtr->nextPtr;
6341 TclStackFree(interp, eoFramePtr);
6342 }
6343 TclDecrRefCount(objPtr);
6344 TclDecrRefCount(listPtr);
6345
6346 return result;
6347 }
6348
6349 /*
6350 *----------------------------------------------------------------------
6351 *
6352 * ProcessUnexpectedResult --
6353 *
6354 * Function called by Tcl_EvalObj to set the interpreter's result value
6355 * to an appropriate error message when the code it evaluates returns an
6356 * unexpected result code (not TCL_OK and not TCL_ERROR) to the topmost
6357 * evaluation level.
6358 *
6359 * Results:
6360 * None.
6361 *
6362 * Side effects:
6363 * The interpreter result is set to an error message appropriate to the
6364 * result code.
6365 *
6366 *----------------------------------------------------------------------
6367 */
6368
6369 static void
6370 ProcessUnexpectedResult(
6371 Tcl_Interp *interp, /* The interpreter in which the unexpected
6372 * result code was returned. */
6373 int returnCode) /* The unexpected result code. */
6374 {
6375 char buf[TCL_INTEGER_SPACE];
6376
6377 Tcl_ResetResult(interp);
6378 if (returnCode == TCL_BREAK) {
6379 Tcl_SetObjResult(interp, Tcl_NewStringObj(
6380 "invoked \"break\" outside of a loop", -1));
6381 } else if (returnCode == TCL_CONTINUE) {
6382 Tcl_SetObjResult(interp, Tcl_NewStringObj(
6383 "invoked \"continue\" outside of a loop", -1));
6384 } else {
6385 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
6386 "command returned bad code: %d", returnCode));
6387 }
6388 snprintf(buf, sizeof(buf), "%d", returnCode);
6389 Tcl_SetErrorCode(interp, "TCL", "UNEXPECTED_RESULT_CODE", buf, (char *)NULL);
6390 }
6391
6392 /*
6393 *---------------------------------------------------------------------------
6394 *
6395 * Tcl_ExprLong, Tcl_ExprDouble, Tcl_ExprBoolean --
6396 *
6397 * Functions to evaluate an expression and return its value in a
6398 * particular form.
6399 *
6400 * Results:
6401 * Each of the functions below returns a standard Tcl result. If an error
6402 * occurs then an error message is left in the interp's result. Otherwise
6403 * the value of the expression, in the appropriate form, is stored at
6404 * *ptr. If the expression had a result that was incompatible with the
6405 * desired form then an error is returned.
6406 *
6407 * Side effects:
6408 * None.
6409 *
6410 *---------------------------------------------------------------------------
6411 */
6412
6413 int
6414 Tcl_ExprLong(
6415 Tcl_Interp *interp, /* Context in which to evaluate the
6416 * expression. */
6417 const char *exprstring, /* Expression to evaluate. */
6418 long *ptr) /* Where to store result. */
6419 {
6420 Tcl_Obj *exprPtr;
6421 int result = TCL_OK;
6422 if (*exprstring == '\0') {
6423 /*
6424 * Legacy compatibility - return 0 for the zero-length string.
6425 */
6426
6427 *ptr = 0;
6428 } else {
6429 exprPtr = Tcl_NewStringObj(exprstring, -1);
6430 Tcl_IncrRefCount(exprPtr);
6431 result = Tcl_ExprLongObj(interp, exprPtr, ptr);
6432 Tcl_DecrRefCount(exprPtr);
6433 if (result != TCL_OK) {
6434 (void) Tcl_GetStringResult(interp);
6435 }
6436 }
6437 return result;
6438 }
6439
6440 int
6441 Tcl_ExprDouble(
6442 Tcl_Interp *interp, /* Context in which to evaluate the
6443 * expression. */
6444 const char *exprstring, /* Expression to evaluate. */
6445 double *ptr) /* Where to store result. */
6446 {
6447 Tcl_Obj *exprPtr;
6448 int result = TCL_OK;
6449
6450 if (*exprstring == '\0') {
6451 /*
6452 * Legacy compatibility - return 0 for the zero-length string.
6453 */
6454
6455 *ptr = 0.0;
6456 } else {
6457 exprPtr = Tcl_NewStringObj(exprstring, -1);
6458 Tcl_IncrRefCount(exprPtr);
6459 result = Tcl_ExprDoubleObj(interp, exprPtr, ptr);
6460 Tcl_DecrRefCount(exprPtr);
6461 /* Discard the expression object. */
6462 if (result != TCL_OK) {
6463 (void) Tcl_GetStringResult(interp);
6464 }
6465 }
6466 return result;
6467 }
6468
6469 int
6470 Tcl_ExprBoolean(
6471 Tcl_Interp *interp, /* Context in which to evaluate the
6472 * expression. */
6473 const char *exprstring, /* Expression to evaluate. */
6474 int *ptr) /* Where to store 0/1 result. */
6475 {
6476 if (*exprstring == '\0') {
6477 /*
6478 * An empty string. Just set the result boolean to 0 (false).
6479 */
6480
6481 *ptr = 0;
6482 return TCL_OK;
6483 } else {
6484 int result;
6485 Tcl_Obj *exprPtr = Tcl_NewStringObj(exprstring, -1);
6486
6487 Tcl_IncrRefCount(exprPtr);
6488 result = Tcl_ExprBooleanObj(interp, exprPtr, ptr);
6489 Tcl_DecrRefCount(exprPtr);
6490 if (result != TCL_OK) {
6491 /*
6492 * Move the interpreter's object result to the string result, then
6493 * reset the object result.
6494 */
6495
6496 (void) Tcl_GetStringResult(interp);
6497 }
6498 return result;
6499 }
6500 }
6501
6502 /*
6503 *--------------------------------------------------------------
6504 *
6505 * Tcl_ExprLongObj, Tcl_ExprDoubleObj, Tcl_ExprBooleanObj --
6506 *
6507 * Functions to evaluate an expression in an object and return its value
6508 * in a particular form.
6509 *
6510 * Results:
6511 * Each of the functions below returns a standard Tcl result object. If
6512 * an error occurs then an error message is left in the interpreter's
6513 * result. Otherwise the value of the expression, in the appropriate
6514 * form, is stored at *ptr. If the expression had a result that was
6515 * incompatible with the desired form then an error is returned.
6516 *
6517 * Side effects:
6518 * None.
6519 *
6520 *--------------------------------------------------------------
6521 */
6522
6523 int
6524 Tcl_ExprLongObj(
6525 Tcl_Interp *interp, /* Context in which to evaluate the
6526 * expression. */
6527 Tcl_Obj *objPtr, /* Expression to evaluate. */
6528 long *ptr) /* Where to store long result. */
6529 {
6530 Tcl_Obj *resultPtr;
6531 int result, type;
6532 double d;
6533 ClientData internalPtr;
6534
6535 result = Tcl_ExprObj(interp, objPtr, &resultPtr);
6536 if (result != TCL_OK) {
6537 return TCL_ERROR;
6538 }
6539
6540 if (TclGetNumberFromObj(interp, resultPtr, &internalPtr, &type)!=TCL_OK) {
6541 return TCL_ERROR;
6542 }
6543
6544 switch (type) {
6545 case TCL_NUMBER_DOUBLE: {
6546 mp_int big;
6547
6548 d = *((const double *) internalPtr);
6549 Tcl_DecrRefCount(resultPtr);
6550 if (Tcl_InitBignumFromDouble(interp, d, &big) != TCL_OK) {
6551 return TCL_ERROR;
6552 }
6553 resultPtr = Tcl_NewBignumObj(&big);
6554 }
6555 /* FALLTHRU */
6556 case TCL_NUMBER_LONG:
6557 case TCL_NUMBER_WIDE:
6558 case TCL_NUMBER_BIG:
6559 result = TclGetLongFromObj(interp, resultPtr, ptr);
6560 break;
6561
6562 case TCL_NUMBER_NAN:
6563 Tcl_GetDoubleFromObj(interp, resultPtr, &d);
6564 result = TCL_ERROR;
6565 }
6566
6567 Tcl_DecrRefCount(resultPtr);/* Discard the result object. */
6568 return result;
6569 }
6570
6571 int
6572 Tcl_ExprDoubleObj(
6573 Tcl_Interp *interp, /* Context in which to evaluate the
6574 * expression. */
6575 Tcl_Obj *objPtr, /* Expression to evaluate. */
6576 double *ptr) /* Where to store double result. */
6577 {
6578 Tcl_Obj *resultPtr;
6579 int result, type;
6580 ClientData internalPtr;
6581
6582 result = Tcl_ExprObj(interp, objPtr, &resultPtr);
6583 if (result != TCL_OK) {
6584 return TCL_ERROR;
6585 }
6586
6587 result = TclGetNumberFromObj(interp, resultPtr, &internalPtr, &type);
6588 if (result == TCL_OK) {
6589 switch (type) {
6590 case TCL_NUMBER_NAN:
6591 #ifndef ACCEPT_NAN
6592 result = Tcl_GetDoubleFromObj(interp, resultPtr, ptr);
6593 break;
6594 #endif
6595 case TCL_NUMBER_DOUBLE:
6596 *ptr = *((const double *) internalPtr);
6597 result = TCL_OK;
6598 break;
6599 default:
6600 result = Tcl_GetDoubleFromObj(interp, resultPtr, ptr);
6601 }
6602 }
6603 Tcl_DecrRefCount(resultPtr);/* Discard the result object. */
6604 return result;
6605 }
6606
6607 int
6608 Tcl_ExprBooleanObj(
6609 Tcl_Interp *interp, /* Context in which to evaluate the
6610 * expression. */
6611 Tcl_Obj *objPtr, /* Expression to evaluate. */
6612 int *ptr) /* Where to store 0/1 result. */
6613 {
6614 Tcl_Obj *resultPtr;
6615 int result;
6616
6617 result = Tcl_ExprObj(interp, objPtr, &resultPtr);
6618 if (result == TCL_OK) {
6619 result = Tcl_GetBooleanFromObj(interp, resultPtr, ptr);
6620 Tcl_DecrRefCount(resultPtr);
6621 /* Discard the result object. */
6622 }
6623 return result;
6624 }
6625
6626 /*
6627 *----------------------------------------------------------------------
6628 *
6629 * TclObjInvokeNamespace --
6630 *
6631 * Object version: Invokes a Tcl command, given an objv/objc, from either
6632 * the exposed or hidden set of commands in the given interpreter.
6633 *
6634 * NOTE: The command is invoked in the global stack frame of the
6635 * interpreter or namespace, thus it cannot see any current state on the
6636 * stack of that interpreter.
6637 *
6638 * Results:
6639 * A standard Tcl result.
6640 *
6641 * Side effects:
6642 * Whatever the command does.
6643 *
6644 *----------------------------------------------------------------------
6645 */
6646
6647 int
6648 TclObjInvokeNamespace(
6649 Tcl_Interp *interp, /* Interpreter in which command is to be
6650 * invoked. */
6651 int objc, /* Count of arguments. */
6652 Tcl_Obj *const objv[], /* Argument objects; objv[0] points to the
6653 * name of the command to invoke. */
6654 Tcl_Namespace *nsPtr, /* The namespace to use. */
6655 int flags) /* Combination of flags controlling the call:
6656 * TCL_INVOKE_HIDDEN, TCL_INVOKE_NO_UNKNOWN,
6657 * or TCL_INVOKE_NO_TRACEBACK. */
6658 {
6659 int result;
6660 Tcl_CallFrame *framePtr;
6661
6662 /*
6663 * Make the specified namespace the current namespace and invoke the
6664 * command.
6665 */
6666
6667 (void) TclPushStackFrame(interp, &framePtr, nsPtr, /*isProcFrame*/0);
6668 result = TclObjInvoke(interp, objc, objv, flags);
6669
6670 TclPopStackFrame(interp);
6671 return result;
6672 }
6673
6674 /*
6675 *----------------------------------------------------------------------
6676 *
6677 * TclObjInvoke --
6678 *
6679 * Invokes a Tcl command, given an objv/objc, from either the exposed or
6680 * the hidden sets of commands in the given interpreter.
6681 *
6682 * Results:
6683 * A standard Tcl object result.
6684 *
6685 * Side effects:
6686 * Whatever the command does.
6687 *
6688 *----------------------------------------------------------------------
6689 */
6690
6691 int
6692 TclObjInvoke(
6693 Tcl_Interp *interp, /* Interpreter in which command is to be
6694 * invoked. */
6695 int objc, /* Count of arguments. */
6696 Tcl_Obj *const objv[], /* Argument objects; objv[0] points to the
6697 * name of the command to invoke. */
6698 int flags) /* Combination of flags controlling the call:
6699 * TCL_INVOKE_HIDDEN, TCL_INVOKE_NO_UNKNOWN,
6700 * or TCL_INVOKE_NO_TRACEBACK. */
6701 {
6702 if (interp == NULL) {
6703 return TCL_ERROR;
6704 }
6705 if ((objc < 1) || (objv == NULL)) {
6706 Tcl_SetObjResult(interp, Tcl_NewStringObj(
6707 "illegal argument vector", -1));
6708 return TCL_ERROR;
6709 }
6710 if ((flags & TCL_INVOKE_HIDDEN) == 0) {
6711 Tcl_Panic("TclObjInvoke: called without TCL_INVOKE_HIDDEN");
6712 }
6713 return Tcl_NRCallObjProc(interp, TclNRInvoke, NULL, objc, objv);
6714 }
6715
6716 int
6717 TclNRInvoke(
6718 ClientData clientData,
6719 Tcl_Interp *interp,
6720 int objc,
6721 Tcl_Obj *const objv[])
6722 {
6723 Interp *iPtr = (Interp *) interp;
6724 Tcl_HashTable *hTblPtr; /* Table of hidden commands. */
6725 const char *cmdName; /* Name of the command from objv[0]. */
6726 Tcl_HashEntry *hPtr = NULL;
6727 Command *cmdPtr;
6728
6729 cmdName = TclGetString(objv[0]);
6730 hTblPtr = iPtr->hiddenCmdTablePtr;
6731 if (hTblPtr != NULL) {
6732 hPtr = Tcl_FindHashEntry(hTblPtr, cmdName);
6733 }
6734 if (hPtr == NULL) {
6735 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
6736 "invalid hidden command name \"%s\"", cmdName));
6737 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "HIDDENTOKEN", cmdName,
6738 (char *)NULL);
6739 return TCL_ERROR;
6740 }
6741 cmdPtr = (Command *)Tcl_GetHashValue(hPtr);
6742
6743 /*
6744 * Avoid the exception-handling brain damage when numLevels == 0
6745 */
6746
6747 iPtr->numLevels++;
6748 Tcl_NRAddCallback(interp, NRPostInvoke, NULL, NULL, NULL, NULL);
6749
6750 /*
6751 * Normal command resolution of objv[0] isn't going to find cmdPtr.
6752 * That's the whole point of **hidden** commands. So tell the Eval core
6753 * machinery not to even try (and risk finding something wrong).
6754 */
6755
6756 return TclNREvalObjv(interp, objc, objv, TCL_EVAL_NORESOLVE, cmdPtr);
6757 }
6758
6759 static int
6760 NRPostInvoke(
6761 ClientData clientData[],
6762 Tcl_Interp *interp,
6763 int result)
6764 {
6765 Interp *iPtr = (Interp *)interp;
6766
6767 iPtr->numLevels--;
6768 return result;
6769 }
6770
6771 /*
6772 *---------------------------------------------------------------------------
6773 *
6774 * Tcl_ExprString --
6775 *
6776 * Evaluate an expression in a string and return its value in string
6777 * form.
6778 *
6779 * Results:
6780 * A standard Tcl result. If the result is TCL_OK, then the interp's
6781 * result is set to the string value of the expression. If the result is
6782 * TCL_ERROR, then the interp's result contains an error message.
6783 *
6784 * Side effects:
6785 * A Tcl object is allocated to hold a copy of the expression string.
6786 * This expression object is passed to Tcl_ExprObj and then deallocated.
6787 *
6788 *---------------------------------------------------------------------------
6789 */
6790
6791 int
6792 Tcl_ExprString(
6793 Tcl_Interp *interp, /* Context in which to evaluate the
6794 * expression. */
6795 const char *expr) /* Expression to evaluate. */
6796 {
6797 int code = TCL_OK;
6798
6799 if (expr[0] == '\0') {
6800 /*
6801 * An empty string. Just set the interpreter's result to 0.
6802 */
6803
6804 Tcl_SetObjResult(interp, Tcl_NewIntObj(0));
6805 } else {
6806 Tcl_Obj *resultPtr, *exprObj = Tcl_NewStringObj(expr, -1);
6807
6808 Tcl_IncrRefCount(exprObj);
6809 code = Tcl_ExprObj(interp, exprObj, &resultPtr);
6810 Tcl_DecrRefCount(exprObj);
6811 if (code == TCL_OK) {
6812 Tcl_SetObjResult(interp, resultPtr);
6813 Tcl_DecrRefCount(resultPtr);
6814 }
6815 }
6816
6817 /*
6818 * Force the string rep of the interp result.
6819 */
6820
6821 (void) Tcl_GetStringResult(interp);
6822 return code;
6823 }
6824
6825 /*
6826 *----------------------------------------------------------------------
6827 *
6828 * Tcl_AppendObjToErrorInfo --
6829 *
6830 * Add a Tcl_Obj value to the errorInfo field that describes the current
6831 * error.
6832 *
6833 * Results:
6834 * None.
6835 *
6836 * Side effects:
6837 * The value of the Tcl_obj is appended to the errorInfo field. If we are
6838 * just starting to log an error, errorInfo is initialized from the error
6839 * message in the interpreter's result.
6840 *
6841 *----------------------------------------------------------------------
6842 */
6843
6844 #undef Tcl_AddObjErrorInfo
6845 void
6846 Tcl_AppendObjToErrorInfo(
6847 Tcl_Interp *interp, /* Interpreter to which error information
6848 * pertains. */
6849 Tcl_Obj *objPtr) /* Message to record. */
6850 {
6851 int length;
6852 const char *message = TclGetStringFromObj(objPtr, &length);
6853
6854 Tcl_IncrRefCount(objPtr);
6855 Tcl_AddObjErrorInfo(interp, message, length);
6856 Tcl_DecrRefCount(objPtr);
6857 }
6858
6859 /*
6860 *----------------------------------------------------------------------
6861 *
6862 * Tcl_AddErrorInfo --
6863 *
6864 * Add information to the errorInfo field that describes the current
6865 * error.
6866 *
6867 * Results:
6868 * None.
6869 *
6870 * Side effects:
6871 * The contents of message are appended to the errorInfo field. If we are
6872 * just starting to log an error, errorInfo is initialized from the error
6873 * message in the interpreter's result.
6874 *
6875 *----------------------------------------------------------------------
6876 */
6877
6878 #undef Tcl_AddErrorInfo
6879 void
6880 Tcl_AddErrorInfo(
6881 Tcl_Interp *interp, /* Interpreter to which error information
6882 * pertains. */
6883 const char *message) /* Message to record. */
6884 {
6885 Tcl_AddObjErrorInfo(interp, message, -1);
6886 }
6887
6888 /*
6889 *----------------------------------------------------------------------
6890 *
6891 * Tcl_AddObjErrorInfo --
6892 *
6893 * Add information to the errorInfo field that describes the current
6894 * error. This routine differs from Tcl_AddErrorInfo by taking a byte
6895 * pointer and length.
6896 *
6897 * Results:
6898 * None.
6899 *
6900 * Side effects:
6901 * "length" bytes from "message" are appended to the errorInfo field. If
6902 * "length" is negative, use bytes up to the first NULL byte. If we are
6903 * just starting to log an error, errorInfo is initialized from the error
6904 * message in the interpreter's result.
6905 *
6906 *----------------------------------------------------------------------
6907 */
6908
6909 void
6910 Tcl_AddObjErrorInfo(
6911 Tcl_Interp *interp, /* Interpreter to which error information
6912 * pertains. */
6913 const char *message, /* Points to the first byte of an array of
6914 * bytes of the message. */
6915 int length) /* The number of bytes in the message. If < 0,
6916 * then append all bytes up to a NULL byte. */
6917 {
6918 Interp *iPtr = (Interp *) interp;
6919
6920 /*
6921 * If we are just starting to log an error, errorInfo is initialized from
6922 * the error message in the interpreter's result.
6923 */
6924
6925 iPtr->flags |= ERR_LEGACY_COPY;
6926 if (iPtr->errorInfo == NULL) {
6927 if (iPtr->result[0] != 0) {
6928 /*
6929 * The interp's string result is set, apparently by some extension
6930 * making a deprecated direct write to it. That extension may
6931 * expect interp->result to continue to be set, so we'll take
6932 * special pains to avoid clearing it, until we drop support for
6933 * interp->result completely.
6934 */
6935
6936 iPtr->errorInfo = Tcl_NewStringObj(iPtr->result, -1);
6937 } else {
6938 iPtr->errorInfo = iPtr->objResultPtr;
6939 }
6940 Tcl_IncrRefCount(iPtr->errorInfo);
6941 if (!iPtr->errorCode) {
6942 Tcl_SetErrorCode(interp, "NONE", (char *)NULL);
6943 }
6944 }
6945
6946 /*
6947 * Now append "message" to the end of errorInfo.
6948 */
6949
6950 if (length != 0) {
6951 if (Tcl_IsShared(iPtr->errorInfo)) {
6952 Tcl_DecrRefCount(iPtr->errorInfo);
6953 iPtr->errorInfo = Tcl_DuplicateObj(iPtr->errorInfo);
6954 Tcl_IncrRefCount(iPtr->errorInfo);
6955 }
6956 Tcl_AppendToObj(iPtr->errorInfo, message, length);
6957 }
6958 }
6959
6960 /*
6961 *----------------------------------------------------------------------
6962 *
6963 * Tcl_VarEvalVA --
6964 *
6965 * Given a variable number of string arguments, concatenate them all
6966 * together and execute the result as a Tcl command.
6967 *
6968 * Results:
6969 * A standard Tcl return result. An error message or other result may be
6970 * left in the interp.
6971 *
6972 * Side effects:
6973 * Depends on what was done by the command.
6974 *
6975 *----------------------------------------------------------------------
6976 */
6977
6978 int
6979 Tcl_VarEvalVA(
6980 Tcl_Interp *interp, /* Interpreter in which to evaluate command */
6981 va_list argList) /* Variable argument list. */
6982 {
6983 Tcl_DString buf;
6984 char *string;
6985 int result;
6986
6987 /*
6988 * Copy the strings one after the other into a single larger string. Use
6989 * stack-allocated space for small commands, but if the command gets too
6990 * large than call ckalloc to create the space.
6991 */
6992
6993 Tcl_DStringInit(&buf);
6994 while (1) {
6995 string = va_arg(argList, char *);
6996 if (string == NULL) {
6997 break;
6998 }
6999 Tcl_DStringAppend(&buf, string, -1);
7000 }
7001
7002 result = Tcl_Eval(interp, Tcl_DStringValue(&buf));
7003 Tcl_DStringFree(&buf);
7004 return result;
7005 }
7006
7007 /*
7008 *----------------------------------------------------------------------
7009 *
7010 * Tcl_VarEval --
7011 *
7012 * Given a variable number of string arguments, concatenate them all
7013 * together and execute the result as a Tcl command.
7014 *
7015 * Results:
7016 * A standard Tcl return result. An error message or other result may be
7017 * left in the interp.
7018 *
7019 * Side effects:
7020 * Depends on what was done by the command.
7021 *
7022 *----------------------------------------------------------------------
7023 */
7024
7025 int
7026 Tcl_VarEval(
7027 Tcl_Interp *interp,
7028 ...)
7029 {
7030 va_list argList;
7031 int result;
7032
7033 va_start(argList, interp);
7034 result = Tcl_VarEvalVA(interp, argList);
7035 va_end(argList);
7036
7037 return result;
7038 }
7039
7040 /*
7041 *----------------------------------------------------------------------
7042 *
7043 * Tcl_GlobalEval --
7044 *
7045 * Evaluate a command at global level in an interpreter.
7046 *
7047 * Results:
7048 * A standard Tcl result is returned, and the interp's result is modified
7049 * accordingly.
7050 *
7051 * Side effects:
7052 * The command string is executed in interp, and the execution is carried
7053 * out in the variable context of global level (no functions active),
7054 * just as if an "uplevel #0" command were being executed.
7055 *
7056 *----------------------------------------------------------------------
7057 */
7058
7059 #undef Tcl_GlobalEval
7060 int
7061 Tcl_GlobalEval(
7062 Tcl_Interp *interp, /* Interpreter in which to evaluate
7063 * command. */
7064 const char *command) /* Command to evaluate. */
7065 {
7066 Interp *iPtr = (Interp *) interp;
7067 int result;
7068 CallFrame *savedVarFramePtr;
7069
7070 savedVarFramePtr = iPtr->varFramePtr;
7071 iPtr->varFramePtr = iPtr->rootFramePtr;
7072 result = Tcl_Eval(interp, command);
7073 iPtr->varFramePtr = savedVarFramePtr;
7074 return result;
7075 }
7076
7077 /*
7078 *----------------------------------------------------------------------
7079 *
7080 * Tcl_SetRecursionLimit --
7081 *
7082 * Set the maximum number of recursive calls that may be active for an
7083 * interpreter at once.
7084 *
7085 * Results:
7086 * The return value is the old limit on nesting for interp.
7087 *
7088 * Side effects:
7089 * None.
7090 *
7091 *----------------------------------------------------------------------
7092 */
7093
7094 int
7095 Tcl_SetRecursionLimit(
7096 Tcl_Interp *interp, /* Interpreter whose nesting limit is to be
7097 * set. */
7098 int depth) /* New value for maximum depth. */
7099 {
7100 Interp *iPtr = (Interp *) interp;
7101 int old;
7102
7103 old = iPtr->maxNestingDepth;
7104 if (depth > 0) {
7105 iPtr->maxNestingDepth = depth;
7106 }
7107 return old;
7108 }
7109
7110 /*
7111 *----------------------------------------------------------------------
7112 *
7113 * Tcl_AllowExceptions --
7114 *
7115 * Sets a flag in an interpreter so that exceptions can occur in the next
7116 * call to Tcl_Eval without them being turned into errors.
7117 *
7118 * Results:
7119 * None.
7120 *
7121 * Side effects:
7122 * The TCL_ALLOW_EXCEPTIONS flag gets set in the interpreter's evalFlags
7123 * structure. See the reference documentation for more details.
7124 *
7125 *----------------------------------------------------------------------
7126 */
7127
7128 void
7129 Tcl_AllowExceptions(
7130 Tcl_Interp *interp) /* Interpreter in which to set flag. */
7131 {
7132 Interp *iPtr = (Interp *) interp;
7133
7134 iPtr->evalFlags |= TCL_ALLOW_EXCEPTIONS;
7135 }
7136
7137 /*
7138 *----------------------------------------------------------------------
7139 *
7140 * Tcl_GetVersion --
7141 *
7142 * Get the Tcl major, minor, and patchlevel version numbers and the
7143 * release type. A patch is a release type TCL_FINAL_RELEASE with a
7144 * patchLevel > 0.
7145 *
7146 * Results:
7147 * None.
7148 *
7149 * Side effects:
7150 * None.
7151 *
7152 *----------------------------------------------------------------------
7153 */
7154
7155 void
7156 Tcl_GetVersion(
7157 int *majorV,
7158 int *minorV,
7159 int *patchLevelV,
7160 int *type)
7161 {
7162 if (majorV != NULL) {
7163 *majorV = TCL_MAJOR_VERSION;
7164 }
7165 if (minorV != NULL) {
7166 *minorV = TCL_MINOR_VERSION;
7167 }
7168 if (patchLevelV != NULL) {
7169 *patchLevelV = TCL_RELEASE_SERIAL;
7170 }
7171 if (type != NULL) {
7172 *type = TCL_RELEASE_LEVEL;
7173 }
7174 }
7175
7176 /*
7177 *----------------------------------------------------------------------
7178 *
7179 * Math Functions --
7180 *
7181 * This page contains the functions that implement all of the built-in
7182 * math functions for expressions.
7183 *
7184 * Results:
7185 * Each function returns TCL_OK if it succeeds and pushes an Tcl object
7186 * holding the result. If it fails it returns TCL_ERROR and leaves an
7187 * error message in the interpreter's result.
7188 *
7189 * Side effects:
7190 * None.
7191 *
7192 *----------------------------------------------------------------------
7193 */
7194
7195 static int
7196 ExprCeilFunc(
7197 ClientData clientData, /* Ignored */
7198 Tcl_Interp *interp, /* The interpreter in which to execute the
7199 * function. */
7200 int objc, /* Actual parameter count. */
7201 Tcl_Obj *const *objv) /* Actual parameter list. */
7202 {
7203 int code;
7204 double d;
7205 mp_int big;
7206
7207 if (objc != 2) {
7208 MathFuncWrongNumArgs(interp, 2, objc, objv);
7209 return TCL_ERROR;
7210 }
7211 code = Tcl_GetDoubleFromObj(interp, objv[1], &d);
7212 #ifdef ACCEPT_NAN
7213 if ((code != TCL_OK) && (objv[1]->typePtr == &tclDoubleType)) {
7214 Tcl_SetObjResult(interp, objv[1]);
7215 return TCL_OK;
7216 }
7217 #endif
7218 if (code != TCL_OK) {
7219 return TCL_ERROR;
7220 }
7221
7222 if (Tcl_GetBignumFromObj(NULL, objv[1], &big) == TCL_OK) {
7223 Tcl_SetObjResult(interp, Tcl_NewDoubleObj(TclCeil(&big)));
7224 mp_clear(&big);
7225 } else {
7226 Tcl_SetObjResult(interp, Tcl_NewDoubleObj(ceil(d)));
7227 }
7228 return TCL_OK;
7229 }
7230
7231 static int
7232 ExprFloorFunc(
7233 ClientData clientData, /* Ignored */
7234 Tcl_Interp *interp, /* The interpreter in which to execute the
7235 * function. */
7236 int objc, /* Actual parameter count. */
7237 Tcl_Obj *const *objv) /* Actual parameter list. */
7238 {
7239 int code;
7240 double d;
7241 mp_int big;
7242
7243 if (objc != 2) {
7244 MathFuncWrongNumArgs(interp, 2, objc, objv);
7245 return TCL_ERROR;
7246 }
7247 code = Tcl_GetDoubleFromObj(interp, objv[1], &d);
7248 #ifdef ACCEPT_NAN
7249 if ((code != TCL_OK) && (objv[1]->typePtr == &tclDoubleType)) {
7250 Tcl_SetObjResult(interp, objv[1]);
7251 return TCL_OK;
7252 }
7253 #endif
7254 if (code != TCL_OK) {
7255 return TCL_ERROR;
7256 }
7257
7258 if (Tcl_GetBignumFromObj(NULL, objv[1], &big) == TCL_OK) {
7259 Tcl_SetObjResult(interp, Tcl_NewDoubleObj(TclFloor(&big)));
7260 mp_clear(&big);
7261 } else {
7262 Tcl_SetObjResult(interp, Tcl_NewDoubleObj(floor(d)));
7263 }
7264 return TCL_OK;
7265 }
7266
7267 static int
7268 ExprIsqrtFunc(
7269 ClientData clientData, /* Ignored */
7270 Tcl_Interp *interp, /* The interpreter in which to execute. */
7271 int objc, /* Actual parameter count. */
7272 Tcl_Obj *const *objv) /* Actual parameter list. */
7273 {
7274 ClientData ptr;
7275 int type;
7276 double d;
7277 Tcl_WideInt w;
7278 mp_int big;
7279 int exact = 0; /* Flag ==1 if the argument can be represented
7280 * in a double as an exact integer. */
7281
7282 /*
7283 * Check syntax.
7284 */
7285
7286 if (objc != 2) {
7287 MathFuncWrongNumArgs(interp, 2, objc, objv);
7288 return TCL_ERROR;
7289 }
7290
7291 /*
7292 * Make sure that the arg is a number.
7293 */
7294
7295 if (TclGetNumberFromObj(interp, objv[1], &ptr, &type) != TCL_OK) {
7296 return TCL_ERROR;
7297 }
7298
7299 switch (type) {
7300 case TCL_NUMBER_NAN:
7301 Tcl_GetDoubleFromObj(interp, objv[1], &d);
7302 return TCL_ERROR;
7303 case TCL_NUMBER_DOUBLE:
7304 d = *((const double *) ptr);
7305 if (d < 0) {
7306 goto negarg;
7307 }
7308 #ifdef IEEE_FLOATING_POINT
7309 if (d <= MAX_EXACT) {
7310 exact = 1;
7311 }
7312 #endif
7313 if (!exact) {
7314 if (Tcl_InitBignumFromDouble(interp, d, &big) != TCL_OK) {
7315 return TCL_ERROR;
7316 }
7317 }
7318 break;
7319 case TCL_NUMBER_BIG:
7320 if (Tcl_GetBignumFromObj(interp, objv[1], &big) != TCL_OK) {
7321 return TCL_ERROR;
7322 }
7323 if (mp_isneg(&big)) {
7324 mp_clear(&big);
7325 goto negarg;
7326 }
7327 break;
7328 default:
7329 if (TclGetWideIntFromObj(interp, objv[1], &w) != TCL_OK) {
7330 return TCL_ERROR;
7331 }
7332 if (w < 0) {
7333 goto negarg;
7334 }
7335 d = (double) w;
7336 #ifdef IEEE_FLOATING_POINT
7337 if (d < MAX_EXACT) {
7338 exact = 1;
7339 }
7340 #endif
7341 if (!exact) {
7342 Tcl_GetBignumFromObj(interp, objv[1], &big);
7343 }
7344 break;
7345 }
7346
7347 if (exact) {
7348 Tcl_SetObjResult(interp, Tcl_NewWideIntObj((Tcl_WideInt)sqrt(d)));
7349 } else {
7350 mp_int root;
7351
7352 mp_init(&root);
7353 mp_sqrt(&big, &root);
7354 mp_clear(&big);
7355 Tcl_SetObjResult(interp, Tcl_NewBignumObj(&root));
7356 }
7357 return TCL_OK;
7358
7359 negarg:
7360 Tcl_SetObjResult(interp, Tcl_NewStringObj(
7361 "square root of negative argument", -1));
7362 Tcl_SetErrorCode(interp, "ARITH", "DOMAIN",
7363 "domain error: argument not in valid range", (char *)NULL);
7364 return TCL_ERROR;
7365 }
7366
7367 static int
7368 ExprSqrtFunc(
7369 ClientData clientData, /* Ignored */
7370 Tcl_Interp *interp, /* The interpreter in which to execute the
7371 * function. */
7372 int objc, /* Actual parameter count. */
7373 Tcl_Obj *const *objv) /* Actual parameter list. */
7374 {
7375 int code;
7376 double d;
7377 mp_int big;
7378
7379 if (objc != 2) {
7380 MathFuncWrongNumArgs(interp, 2, objc, objv);
7381 return TCL_ERROR;
7382 }
7383 code = Tcl_GetDoubleFromObj(interp, objv[1], &d);
7384 #ifdef ACCEPT_NAN
7385 if ((code != TCL_OK) && (objv[1]->typePtr == &tclDoubleType)) {
7386 Tcl_SetObjResult(interp, objv[1]);
7387 return TCL_OK;
7388 }
7389 #endif
7390 if (code != TCL_OK) {
7391 return TCL_ERROR;
7392 }
7393 if ((d >= 0.0) && TclIsInfinite(d)
7394 && (Tcl_GetBignumFromObj(NULL, objv[1], &big) == TCL_OK)) {
7395 mp_int root;
7396
7397 mp_init(&root);
7398 mp_sqrt(&big, &root);
7399 mp_clear(&big);
7400 Tcl_SetObjResult(interp, Tcl_NewDoubleObj(TclBignumToDouble(&root)));
7401 mp_clear(&root);
7402 } else {
7403 Tcl_SetObjResult(interp, Tcl_NewDoubleObj(sqrt(d)));
7404 }
7405 return TCL_OK;
7406 }
7407
7408 static int
7409 ExprUnaryFunc(
7410 ClientData clientData, /* Contains the address of a function that
7411 * takes one double argument and returns a
7412 * double result. */
7413 Tcl_Interp *interp, /* The interpreter in which to execute the
7414 * function. */
7415 int objc, /* Actual parameter count */
7416 Tcl_Obj *const *objv) /* Actual parameter list */
7417 {
7418 int code;
7419 double d;
7420 double (*func)(double) = (double (*)(double)) clientData;
7421
7422 if (objc != 2) {
7423 MathFuncWrongNumArgs(interp, 2, objc, objv);
7424 return TCL_ERROR;
7425 }
7426 code = Tcl_GetDoubleFromObj(interp, objv[1], &d);
7427 #ifdef ACCEPT_NAN
7428 if ((code != TCL_OK) && (objv[1]->typePtr == &tclDoubleType)) {
7429 d = objv[1]->internalRep.doubleValue;
7430 Tcl_ResetResult(interp);
7431 code = TCL_OK;
7432 }
7433 #endif
7434 if (code != TCL_OK) {
7435 return TCL_ERROR;
7436 }
7437 errno = 0;
7438 return CheckDoubleResult(interp, func(d));
7439 }
7440
7441 static int
7442 CheckDoubleResult(
7443 Tcl_Interp *interp,
7444 double dResult)
7445 {
7446 #ifndef ACCEPT_NAN
7447 if (TclIsNaN(dResult)) {
7448 TclExprFloatError(interp, dResult);
7449 return TCL_ERROR;
7450 }
7451 #endif
7452 if ((errno == ERANGE) && ((dResult == 0.0) || TclIsInfinite(dResult))) {
7453 /*
7454 * When ERANGE signals under/overflow, just accept 0.0 or +/-Inf
7455 */
7456 } else if (errno != 0) {
7457 /*
7458 * Report other errno values as errors.
7459 */
7460
7461 TclExprFloatError(interp, dResult);
7462 return TCL_ERROR;
7463 }
7464 Tcl_SetObjResult(interp, Tcl_NewDoubleObj(dResult));
7465 return TCL_OK;
7466 }
7467
7468 static int
7469 ExprBinaryFunc(
7470 ClientData clientData, /* Contains the address of a function that
7471 * takes two double arguments and returns a
7472 * double result. */
7473 Tcl_Interp *interp, /* The interpreter in which to execute the
7474 * function. */
7475 int objc, /* Actual parameter count. */
7476 Tcl_Obj *const *objv) /* Parameter vector. */
7477 {
7478 int code;
7479 double d1, d2;
7480 double (*func)(double, double) = (double (*)(double, double)) clientData;
7481
7482 if (objc != 3) {
7483 MathFuncWrongNumArgs(interp, 3, objc, objv);
7484 return TCL_ERROR;
7485 }
7486 code = Tcl_GetDoubleFromObj(interp, objv[1], &d1);
7487 #ifdef ACCEPT_NAN
7488 if ((code != TCL_OK) && (objv[1]->typePtr == &tclDoubleType)) {
7489 d1 = objv[1]->internalRep.doubleValue;
7490 Tcl_ResetResult(interp);
7491 code = TCL_OK;
7492 }
7493 #endif
7494 if (code != TCL_OK) {
7495 return TCL_ERROR;
7496 }
7497 code = Tcl_GetDoubleFromObj(interp, objv[2], &d2);
7498 #ifdef ACCEPT_NAN
7499 if ((code != TCL_OK) && (objv[2]->typePtr == &tclDoubleType)) {
7500 d2 = objv[2]->internalRep.doubleValue;
7501 Tcl_ResetResult(interp);
7502 code = TCL_OK;
7503 }
7504 #endif
7505 if (code != TCL_OK) {
7506 return TCL_ERROR;
7507 }
7508 errno = 0;
7509 return CheckDoubleResult(interp, func(d1, d2));
7510 }
7511
7512 static int
7513 ExprAbsFunc(
7514 ClientData clientData, /* Ignored. */
7515 Tcl_Interp *interp, /* The interpreter in which to execute the
7516 * function. */
7517 int objc, /* Actual parameter count. */
7518 Tcl_Obj *const *objv) /* Parameter vector. */
7519 {
7520 ClientData ptr;
7521 int type;
7522 mp_int big;
7523
7524 if (objc != 2) {
7525 MathFuncWrongNumArgs(interp, 2, objc, objv);
7526 return TCL_ERROR;
7527 }
7528
7529 if (TclGetNumberFromObj(interp, objv[1], &ptr, &type) != TCL_OK) {
7530 return TCL_ERROR;
7531 }
7532
7533 if (type == TCL_NUMBER_LONG) {
7534 long l = *((const long *) ptr);
7535
7536 if (l > (long)0) {
7537 goto unChanged;
7538 } else if (l == (long)0) {
7539 const char *string = objv[1]->bytes;
7540 if (string) {
7541 while (*string != '0') {
7542 if (*string == '-') {
7543 Tcl_SetObjResult(interp, Tcl_NewLongObj(0));
7544 return TCL_OK;
7545 }
7546 string++;
7547 }
7548 }
7549 goto unChanged;
7550 } else if (l == LONG_MIN) {
7551 TclBNInitBignumFromLong(&big, l);
7552 goto tooLarge;
7553 }
7554 Tcl_SetObjResult(interp, Tcl_NewLongObj(-l));
7555 return TCL_OK;
7556 }
7557
7558 if (type == TCL_NUMBER_DOUBLE) {
7559 double d = *((const double *) ptr);
7560 static const double poszero = 0.0;
7561
7562 /*
7563 * We need to distinguish here between positive 0.0 and negative -0.0.
7564 * [Bug 2954959]
7565 */
7566
7567 if (d == -0.0) {
7568 if (!memcmp(&d, &poszero, sizeof(double))) {
7569 goto unChanged;
7570 }
7571 } else if (d > -0.0) {
7572 goto unChanged;
7573 }
7574 Tcl_SetObjResult(interp, Tcl_NewDoubleObj(-d));
7575 return TCL_OK;
7576 }
7577
7578 #ifndef TCL_WIDE_INT_IS_LONG
7579 if (type == TCL_NUMBER_WIDE) {
7580 Tcl_WideInt w = *((const Tcl_WideInt *) ptr);
7581
7582 if (w >= 0) {
7583 goto unChanged;
7584 }
7585 if (w == LLONG_MIN) {
7586 TclBNInitBignumFromWideInt(&big, w);
7587 goto tooLarge;
7588 }
7589 Tcl_SetObjResult(interp, Tcl_NewWideIntObj(-w));
7590 return TCL_OK;
7591 }
7592 #endif
7593
7594 if (type == TCL_NUMBER_BIG) {
7595 if (mp_isneg((const mp_int *)ptr)) {
7596 Tcl_GetBignumFromObj(NULL, objv[1], &big);
7597 tooLarge:
7598 (void)mp_neg(&big, &big);
7599 Tcl_SetObjResult(interp, Tcl_NewBignumObj(&big));
7600 } else {
7601 unChanged:
7602 Tcl_SetObjResult(interp, objv[1]);
7603 }
7604 return TCL_OK;
7605 }
7606
7607 if (type == TCL_NUMBER_NAN) {
7608 #ifdef ACCEPT_NAN
7609 Tcl_SetObjResult(interp, objv[1]);
7610 return TCL_OK;
7611 #else
7612 double d;
7613
7614 Tcl_GetDoubleFromObj(interp, objv[1], &d);
7615 return TCL_ERROR;
7616 #endif
7617 }
7618 return TCL_OK;
7619 }
7620
7621 static int
7622 ExprBoolFunc(
7623 ClientData clientData, /* Ignored. */
7624 Tcl_Interp *interp, /* The interpreter in which to execute the
7625 * function. */
7626 int objc, /* Actual parameter count. */
7627 Tcl_Obj *const *objv) /* Actual parameter vector. */
7628 {
7629 int value;
7630
7631 if (objc != 2) {
7632 MathFuncWrongNumArgs(interp, 2, objc, objv);
7633 return TCL_ERROR;
7634 }
7635 if (Tcl_GetBooleanFromObj(interp, objv[1], &value) != TCL_OK) {
7636 return TCL_ERROR;
7637 }
7638 Tcl_SetObjResult(interp, Tcl_NewBooleanObj(value));
7639 return TCL_OK;
7640 }
7641
7642 static int
7643 ExprDoubleFunc(
7644 ClientData clientData, /* Ignored. */
7645 Tcl_Interp *interp, /* The interpreter in which to execute the
7646 * function. */
7647 int objc, /* Actual parameter count. */
7648 Tcl_Obj *const *objv) /* Actual parameter vector. */
7649 {
7650 double dResult;
7651
7652 if (objc != 2) {
7653 MathFuncWrongNumArgs(interp, 2, objc, objv);
7654 return TCL_ERROR;
7655 }
7656 if (Tcl_GetDoubleFromObj(interp, objv[1], &dResult) != TCL_OK) {
7657 #ifdef ACCEPT_NAN
7658 if (objv[1]->typePtr == &tclDoubleType) {
7659 Tcl_SetObjResult(interp, objv[1]);
7660 return TCL_OK;
7661 }
7662 #endif
7663 return TCL_ERROR;
7664 }
7665 Tcl_SetObjResult(interp, Tcl_NewDoubleObj(dResult));
7666 return TCL_OK;
7667 }
7668
7669 static int
7670 ExprEntierFunc(
7671 ClientData clientData, /* Ignored. */
7672 Tcl_Interp *interp, /* The interpreter in which to execute the
7673 * function. */
7674 int objc, /* Actual parameter count. */
7675 Tcl_Obj *const *objv) /* Actual parameter vector. */
7676 {
7677 double d;
7678 int type;
7679 ClientData ptr;
7680
7681 if (objc != 2) {
7682 MathFuncWrongNumArgs(interp, 2, objc, objv);
7683 return TCL_ERROR;
7684 }
7685 if (TclGetNumberFromObj(interp, objv[1], &ptr, &type) != TCL_OK) {
7686 return TCL_ERROR;
7687 }
7688
7689 if (type == TCL_NUMBER_DOUBLE) {
7690 d = *((const double *) ptr);
7691 if ((d < (double)LONG_MAX) && (d > (double)LONG_MIN)) {
7692 long result = (long) d;
7693
7694 Tcl_SetObjResult(interp, Tcl_NewLongObj(result));
7695 return TCL_OK;
7696 #ifndef TCL_WIDE_INT_IS_LONG
7697 } else if ((d < (double)LLONG_MAX) && (d > (double)LLONG_MIN)) {
7698 Tcl_WideInt result = (Tcl_WideInt)d;
7699
7700 Tcl_SetObjResult(interp, Tcl_NewWideIntObj(result));
7701 return TCL_OK;
7702 #endif
7703 } else {
7704 mp_int big;
7705
7706 if (Tcl_InitBignumFromDouble(interp, d, &big) != TCL_OK) {
7707 /* Infinity */
7708 return TCL_ERROR;
7709 }
7710 Tcl_SetObjResult(interp, Tcl_NewBignumObj(&big));
7711 return TCL_OK;
7712 }
7713 }
7714
7715 if (type != TCL_NUMBER_NAN) {
7716 /*
7717 * All integers are already of integer type.
7718 */
7719
7720 Tcl_SetObjResult(interp, objv[1]);
7721 return TCL_OK;
7722 }
7723
7724 /*
7725 * Get the error message for NaN.
7726 */
7727
7728 Tcl_GetDoubleFromObj(interp, objv[1], &d);
7729 return TCL_ERROR;
7730 }
7731
7732 static int
7733 ExprIntFunc(
7734 ClientData clientData, /* Ignored. */
7735 Tcl_Interp *interp, /* The interpreter in which to execute the
7736 * function. */
7737 int objc, /* Actual parameter count. */
7738 Tcl_Obj *const *objv) /* Actual parameter vector. */
7739 {
7740 long iResult;
7741 Tcl_Obj *objPtr;
7742 if (ExprEntierFunc(NULL, interp, objc, objv) != TCL_OK) {
7743 return TCL_ERROR;
7744 }
7745 objPtr = Tcl_GetObjResult(interp);
7746 if (TclGetLongFromObj(NULL, objPtr, &iResult) != TCL_OK) {
7747 /*
7748 * Truncate the bignum; keep only bits in long range.
7749 */
7750
7751 mp_int big;
7752
7753 Tcl_GetBignumFromObj(NULL, objPtr, &big);
7754 mp_mod_2d(&big, (int) CHAR_BIT * sizeof(long), &big);
7755 objPtr = Tcl_NewBignumObj(&big);
7756 Tcl_IncrRefCount(objPtr);
7757 TclGetLongFromObj(NULL, objPtr, &iResult);
7758 Tcl_DecrRefCount(objPtr);
7759 }
7760 Tcl_SetObjResult(interp, Tcl_NewLongObj(iResult));
7761 return TCL_OK;
7762 }
7763
7764 static int
7765 ExprWideFunc(
7766 ClientData clientData, /* Ignored. */
7767 Tcl_Interp *interp, /* The interpreter in which to execute the
7768 * function. */
7769 int objc, /* Actual parameter count. */
7770 Tcl_Obj *const *objv) /* Actual parameter vector. */
7771 {
7772 Tcl_WideInt wResult;
7773 Tcl_Obj *objPtr;
7774
7775 if (ExprEntierFunc(NULL, interp, objc, objv) != TCL_OK) {
7776 return TCL_ERROR;
7777 }
7778 objPtr = Tcl_GetObjResult(interp);
7779 if (TclGetWideIntFromObj(NULL, objPtr, &wResult) != TCL_OK) {
7780 /*
7781 * Truncate the bignum; keep only bits in wide int range.
7782 */
7783
7784 mp_int big;
7785
7786 Tcl_GetBignumFromObj(NULL, objPtr, &big);
7787 mp_mod_2d(&big, (int) CHAR_BIT * sizeof(Tcl_WideInt), &big);
7788 objPtr = Tcl_NewBignumObj(&big);
7789 Tcl_IncrRefCount(objPtr);
7790 TclGetWideIntFromObj(NULL, objPtr, &wResult);
7791 Tcl_DecrRefCount(objPtr);
7792 }
7793 Tcl_SetObjResult(interp, Tcl_NewWideIntObj(wResult));
7794 return TCL_OK;
7795 }
7796
7797 static int
7798 ExprRandFunc(
7799 ClientData clientData, /* Ignored. */
7800 Tcl_Interp *interp, /* The interpreter in which to execute the
7801 * function. */
7802 int objc, /* Actual parameter count. */
7803 Tcl_Obj *const *objv) /* Actual parameter vector. */
7804 {
7805 Interp *iPtr = (Interp *) interp;
7806 double dResult;
7807 long tmp; /* Algorithm assumes at least 32 bits. Only
7808 * long guarantees that. See below. */
7809 Tcl_Obj *oResult;
7810
7811 if (objc != 1) {
7812 MathFuncWrongNumArgs(interp, 1, objc, objv);
7813 return TCL_ERROR;
7814 }
7815
7816 if (!(iPtr->flags & RAND_SEED_INITIALIZED)) {
7817 iPtr->flags |= RAND_SEED_INITIALIZED;
7818
7819 /*
7820 * To ensure different seeds in different threads (bug #416643),
7821 * take into consideration the thread this interp is running in.
7822 */
7823
7824 iPtr->randSeed = TclpGetClicks() + PTR2UINT(Tcl_GetCurrentThread()) * 4093U;
7825
7826 /*
7827 * Make sure 1 <= randSeed <= (2^31) - 2. See below.
7828 */
7829
7830 iPtr->randSeed &= 0x7FFFFFFFL;
7831 if ((iPtr->randSeed == 0) || (iPtr->randSeed == 0x7FFFFFFFL)) {
7832 iPtr->randSeed ^= 123459876L;
7833 }
7834 }
7835
7836 /*
7837 * Generate the random number using the linear congruential generator
7838 * defined by the following recurrence:
7839 * seed = ( IA * seed ) mod IM
7840 * where IA is 16807 and IM is (2^31) - 1. The recurrence maps a seed in
7841 * the range [1, IM - 1] to a new seed in that same range. The recurrence
7842 * maps IM to 0, and maps 0 back to 0, so those two values must not be
7843 * allowed as initial values of seed.
7844 *
7845 * In order to avoid potential problems with integer overflow, the
7846 * recurrence is implemented in terms of additional constants IQ and IR
7847 * such that
7848 * IM = IA*IQ + IR
7849 * None of the operations in the implementation overflows a 32-bit signed
7850 * integer, and the C type long is guaranteed to be at least 32 bits wide.
7851 *
7852 * For more details on how this algorithm works, refer to the following
7853 * papers:
7854 *
7855 * S.K. Park & K.W. Miller, "Random number generators: good ones are hard
7856 * to find," Comm ACM 31(10):1192-1201, Oct 1988
7857 *
7858 * W.H. Press & S.A. Teukolsky, "Portable random number generators,"
7859 * Computers in Physics 6(5):522-524, Sep/Oct 1992.
7860 */
7861
7862 #define RAND_IA 16807
7863 #define RAND_IM 2147483647
7864 #define RAND_IQ 127773
7865 #define RAND_IR 2836
7866 #define RAND_MASK 123459876
7867
7868 tmp = iPtr->randSeed/RAND_IQ;
7869 iPtr->randSeed = RAND_IA*(iPtr->randSeed - tmp*RAND_IQ) - RAND_IR*tmp;
7870 if (iPtr->randSeed < 0) {
7871 iPtr->randSeed += RAND_IM;
7872 }
7873
7874 /*
7875 * Since the recurrence keeps seed values in the range [1, RAND_IM - 1],
7876 * dividing by RAND_IM yields a double in the range (0, 1).
7877 */
7878
7879 dResult = iPtr->randSeed * (1.0/RAND_IM);
7880
7881 /*
7882 * Push a Tcl object with the result.
7883 */
7884
7885 TclNewDoubleObj(oResult, dResult);
7886 Tcl_SetObjResult(interp, oResult);
7887 return TCL_OK;
7888 }
7889
7890 static int
7891 ExprRoundFunc(
7892 ClientData clientData, /* Ignored. */
7893 Tcl_Interp *interp, /* The interpreter in which to execute the
7894 * function. */
7895 int objc, /* Actual parameter count. */
7896 Tcl_Obj *const *objv) /* Parameter vector. */
7897 {
7898 double d;
7899 ClientData ptr;
7900 int type;
7901
7902 if (objc != 2) {
7903 MathFuncWrongNumArgs(interp, 2, objc, objv);
7904 return TCL_ERROR;
7905 }
7906
7907 if (TclGetNumberFromObj(interp, objv[1], &ptr, &type) != TCL_OK) {
7908 return TCL_ERROR;
7909 }
7910
7911 if (type == TCL_NUMBER_DOUBLE) {
7912 double fractPart, intPart;
7913 long max = LONG_MAX, min = LONG_MIN;
7914
7915 fractPart = modf(*((const double *) ptr), &intPart);
7916 if (fractPart <= -0.5) {
7917 min++;
7918 } else if (fractPart >= 0.5) {
7919 max--;
7920 }
7921 if ((intPart >= (double)max) || (intPart <= (double)min)) {
7922 mp_int big;
7923
7924 if (Tcl_InitBignumFromDouble(interp, intPart, &big) != TCL_OK) {
7925 /* Infinity */
7926 return TCL_ERROR;
7927 }
7928 if (fractPart <= -0.5) {
7929 mp_sub_d(&big, 1, &big);
7930 } else if (fractPart >= 0.5) {
7931 mp_add_d(&big, 1, &big);
7932 }
7933 Tcl_SetObjResult(interp, Tcl_NewBignumObj(&big));
7934 return TCL_OK;
7935 } else {
7936 long result = (long)intPart;
7937
7938 if (fractPart <= -0.5) {
7939 result--;
7940 } else if (fractPart >= 0.5) {
7941 result++;
7942 }
7943 Tcl_SetObjResult(interp, Tcl_NewLongObj(result));
7944 return TCL_OK;
7945 }
7946 }
7947
7948 if (type != TCL_NUMBER_NAN) {
7949 /*
7950 * All integers are already rounded
7951 */
7952
7953 Tcl_SetObjResult(interp, objv[1]);
7954 return TCL_OK;
7955 }
7956
7957 /*
7958 * Get the error message for NaN.
7959 */
7960
7961 Tcl_GetDoubleFromObj(interp, objv[1], &d);
7962 return TCL_ERROR;
7963 }
7964
7965 static int
7966 ExprSrandFunc(
7967 ClientData clientData, /* Ignored. */
7968 Tcl_Interp *interp, /* The interpreter in which to execute the
7969 * function. */
7970 int objc, /* Actual parameter count. */
7971 Tcl_Obj *const *objv) /* Parameter vector. */
7972 {
7973 Interp *iPtr = (Interp *) interp;
7974 long i = 0; /* Initialized to avoid compiler warning. */
7975
7976 /*
7977 * Convert argument and use it to reset the seed.
7978 */
7979
7980 if (objc != 2) {
7981 MathFuncWrongNumArgs(interp, 2, objc, objv);
7982 return TCL_ERROR;
7983 }
7984
7985 if (TclGetLongFromObj(NULL, objv[1], &i) != TCL_OK) {
7986 Tcl_Obj *objPtr;
7987 mp_int big;
7988
7989 if (Tcl_GetBignumFromObj(interp, objv[1], &big) != TCL_OK) {
7990 /* TODO: more ::errorInfo here? or in caller? */
7991 return TCL_ERROR;
7992 }
7993
7994 mp_mod_2d(&big, (int) CHAR_BIT * sizeof(long), &big);
7995 objPtr = Tcl_NewBignumObj(&big);
7996 Tcl_IncrRefCount(objPtr);
7997 TclGetLongFromObj(NULL, objPtr, &i);
7998 Tcl_DecrRefCount(objPtr);
7999 }
8000
8001 /*
8002 * Reset the seed. Make sure 1 <= randSeed <= 2^31 - 2. See comments in
8003 * ExprRandFunc for more details.
8004 */
8005
8006 iPtr->flags |= RAND_SEED_INITIALIZED;
8007 iPtr->randSeed = i;
8008 iPtr->randSeed &= (unsigned long) 0x7FFFFFFF;
8009 if ((iPtr->randSeed == 0) || (iPtr->randSeed == 0x7FFFFFFF)) {
8010 iPtr->randSeed ^= 123459876;
8011 }
8012
8013 /*
8014 * To avoid duplicating the random number generation code we simply clean
8015 * up our state and call the real random number function. That function
8016 * will always succeed.
8017 */
8018
8019 return ExprRandFunc(clientData, interp, 1, objv);
8020 }
8021
8022 /*
8023 *----------------------------------------------------------------------
8024 *
8025 * MathFuncWrongNumArgs --
8026 *
8027 * Generate an error message when a math function presents the wrong
8028 * number of arguments.
8029 *
8030 * Results:
8031 * None.
8032 *
8033 * Side effects:
8034 * An error message is stored in the interpreter result.
8035 *
8036 *----------------------------------------------------------------------
8037 */
8038
8039 static void
8040 MathFuncWrongNumArgs(
8041 Tcl_Interp *interp, /* Tcl interpreter */
8042 int expected, /* Formal parameter count. */
8043 int found, /* Actual parameter count. */
8044 Tcl_Obj *const *objv) /* Actual parameter vector. */
8045 {
8046 const char *name = TclGetString(objv[0]);
8047 const char *tail = name + strlen(name);
8048
8049 while (tail > name + 1) {
8050 tail--;
8051 if (*tail == ':' && tail[-1] == ':') {
8052 name = tail + 1;
8053 break;
8054 }
8055 }
8056 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
8057 "%s arguments for math function \"%s\"",
8058 (found < expected ? "not enough" : "too many"), name));
8059 Tcl_SetErrorCode(interp, "TCL", "WRONGARGS", (char *)NULL);
8060 }
8061
8062 #ifdef USE_DTRACE
8063 /*
8064 *----------------------------------------------------------------------
8065 *
8066 * DTraceObjCmd --
8067 *
8068 * This function is invoked to process the "::tcl::dtrace" Tcl command.
8069 *
8070 * Results:
8071 * A standard Tcl object result.
8072 *
8073 * Side effects:
8074 * The 'tcl-probe' DTrace probe is triggered (if it is enabled).
8075 *
8076 *----------------------------------------------------------------------
8077 */
8078
8079 static int
8080 DTraceObjCmd(
8081 ClientData dummy, /* Not used. */
8082 Tcl_Interp *interp, /* Current interpreter. */
8083 int objc, /* Number of arguments. */
8084 Tcl_Obj *const objv[]) /* Argument objects. */
8085 {
8086 if (TCL_DTRACE_TCL_PROBE_ENABLED()) {
8087 char *a[10];
8088 int i = 0;
8089
8090 while (i++ < 10) {
8091 a[i-1] = i < objc ? TclGetString(objv[i]) : NULL;
8092 }
8093 TCL_DTRACE_TCL_PROBE(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7],
8094 a[8], a[9]);
8095 }
8096 return TCL_OK;
8097 }
8098
8099 /*
8100 *----------------------------------------------------------------------
8101 *
8102 * TclDTraceInfo --
8103 *
8104 * Extract information from a TIP280 dict for use by DTrace probes.
8105 *
8106 * Results:
8107 * None.
8108 *
8109 * Side effects:
8110 * None.
8111 *
8112 *----------------------------------------------------------------------
8113 */
8114
8115 void
8116 TclDTraceInfo(
8117 Tcl_Obj *info,
8118 const char **args,
8119 int *argsi)
8120 {
8121 static Tcl_Obj *keys[10] = { NULL };
8122 Tcl_Obj **k = keys, *val;
8123 int i = 0;
8124
8125 if (!*k) {
8126 #define kini(s) TclNewLiteralStringObj(keys[i], s); i++
8127 kini("cmd"); kini("type"); kini("proc"); kini("file");
8128 kini("method"); kini("class"); kini("lambda"); kini("object");
8129 kini("line"); kini("level");
8130 #undef kini
8131 }
8132 for (i = 0; i < 6; i++) {
8133 Tcl_DictObjGet(NULL, info, *k++, &val);
8134 args[i] = val ? TclGetString(val) : NULL;
8135 }
8136
8137 /*
8138 * no "proc" -> use "lambda"
8139 */
8140
8141 if (!args[2]) {
8142 Tcl_DictObjGet(NULL, info, *k, &val);
8143 args[2] = val ? TclGetString(val) : NULL;
8144 }
8145 k++;
8146
8147 /*
8148 * no "class" -> use "object"
8149 */
8150
8151 if (!args[5]) {
8152 Tcl_DictObjGet(NULL, info, *k, &val);
8153 args[5] = val ? TclGetString(val) : NULL;
8154 }
8155 k++;
8156 for (i = 0; i < 2; i++) {
8157 Tcl_DictObjGet(NULL, info, *k++, &val);
8158 if (val) {
8159 TclGetIntFromObj(NULL, val, &argsi[i]);
8160 } else {
8161 argsi[i] = 0;
8162 }
8163 }
8164 }
8165
8166 /*
8167 *----------------------------------------------------------------------
8168 *
8169 * DTraceCmdReturn --
8170 *
8171 * NR callback for DTrace command return probes.
8172 *
8173 * Results:
8174 * None.
8175 *
8176 * Side effects:
8177 * None.
8178 *
8179 *----------------------------------------------------------------------
8180 */
8181
8182 static int
8183 DTraceCmdReturn(
8184 ClientData data[],
8185 Tcl_Interp *interp,
8186 int result)
8187 {
8188 char *cmdName = TclGetString((Tcl_Obj *) data[0]);
8189
8190 if (TCL_DTRACE_CMD_RETURN_ENABLED()) {
8191 TCL_DTRACE_CMD_RETURN(cmdName, result);
8192 }
8193 if (TCL_DTRACE_CMD_RESULT_ENABLED()) {
8194 Tcl_Obj *r = Tcl_GetObjResult(interp);
8195
8196 TCL_DTRACE_CMD_RESULT(cmdName, result, TclGetString(r), r);
8197 }
8198 return result;
8199 }
8200
8201 TCL_DTRACE_DEBUG_LOG()
8202
8203 #endif /* USE_DTRACE */
8204
8205 /*
8206 *----------------------------------------------------------------------
8207 *
8208 * Tcl_NRCallObjProc --
8209 *
8210 * This function calls an objProc directly while managing things properly
8211 * if it happens to be an NR objProc. It is meant to be used by extenders
8212 * that provide an NR implementation of a command, as this function
8213 * permits a trivial coding of the non-NR objProc.
8214 *
8215 * Results:
8216 * The return value is a standard Tcl completion code such as TCL_OK or
8217 * TCL_ERROR. A result or error message is left in interp's result.
8218 *
8219 * Side effects:
8220 * Depends on the objProc.
8221 *
8222 *----------------------------------------------------------------------
8223 */
8224
8225 int
8226 Tcl_NRCallObjProc(
8227 Tcl_Interp *interp,
8228 Tcl_ObjCmdProc *objProc,
8229 ClientData clientData,
8230 int objc,
8231 Tcl_Obj *const objv[])
8232 {
8233 NRE_callback *rootPtr = TOP_CB(interp);
8234
8235 TclNRAddCallback(interp, Dispatch, objProc, clientData,
8236 INT2PTR(objc), objv);
8237 return TclNRRunCallbacks(interp, TCL_OK, rootPtr);
8238 }
8239
8240 /*
8241 *----------------------------------------------------------------------
8242 *
8243 * Tcl_NRCreateCommand --
8244 *
8245 * Define a new NRE-enabled object-based command in a command table.
8246 *
8247 * Results:
8248 * The return value is a token for the command, which can be used in
8249 * future calls to Tcl_GetCommandName.
8250 *
8251 * Side effects:
8252 * If no command named "cmdName" already exists for interp, one is
8253 * created. Otherwise, if a command does exist, then if the object-based
8254 * Tcl_ObjCmdProc is TclInvokeStringCommand, we assume Tcl_CreateCommand
8255 * was called previously for the same command and just set its
8256 * Tcl_ObjCmdProc to the argument "proc"; otherwise, we delete the old
8257 * command.
8258 *
8259 * In the future, during bytecode evaluation when "cmdName" is seen as
8260 * the name of a command by Tcl_EvalObj or Tcl_Eval, the object-based
8261 * Tcl_ObjCmdProc proc will be called. When the command is deleted from
8262 * the table, deleteProc will be called. See the manual entry for details
8263 * on the calling sequence.
8264 *
8265 *----------------------------------------------------------------------
8266 */
8267
8268 Tcl_Command
8269 Tcl_NRCreateCommand(
8270 Tcl_Interp *interp, /* Token for command interpreter (returned by
8271 * previous call to Tcl_CreateInterp). */
8272 const char *cmdName, /* Name of command. If it contains namespace
8273 * qualifiers, the new command is put in the
8274 * specified namespace; otherwise it is put in
8275 * the global namespace. */
8276 Tcl_ObjCmdProc *proc, /* Object-based function to associate with
8277 * name, provides direct access for direct
8278 * calls. */
8279 Tcl_ObjCmdProc *nreProc, /* Object-based function to associate with
8280 * name, provides NR implementation */
8281 ClientData clientData, /* Arbitrary value to pass to object
8282 * function. */
8283 Tcl_CmdDeleteProc *deleteProc)
8284 /* If not NULL, gives a function to call when
8285 * this command is deleted. */
8286 {
8287 Command *cmdPtr = (Command *)
8288 Tcl_CreateObjCommand(interp, cmdName, proc, clientData,
8289 deleteProc);
8290
8291 cmdPtr->nreProc = nreProc;
8292 return (Tcl_Command) cmdPtr;
8293 }
8294
8295 Tcl_Command
8296 TclNRCreateCommandInNs(
8297 Tcl_Interp *interp,
8298 const char *cmdName,
8299 Tcl_Namespace *nsPtr,
8300 Tcl_ObjCmdProc *proc,
8301 Tcl_ObjCmdProc *nreProc,
8302 ClientData clientData,
8303 Tcl_CmdDeleteProc *deleteProc)
8304 {
8305 Command *cmdPtr = (Command *)
8306 TclCreateObjCommandInNs(interp, cmdName, nsPtr, proc, clientData,
8307 deleteProc);
8308
8309 cmdPtr->nreProc = nreProc;
8310 return (Tcl_Command) cmdPtr;
8311 }
8312
8313 /****************************************************************************
8314 * Stuff for the public api
8315 ****************************************************************************/
8316
8317 int
8318 Tcl_NREvalObj(
8319 Tcl_Interp *interp,
8320 Tcl_Obj *objPtr,
8321 int flags)
8322 {
8323 return TclNREvalObjEx(interp, objPtr, flags, NULL, INT_MIN);
8324 }
8325
8326 int
8327 Tcl_NREvalObjv(
8328 Tcl_Interp *interp, /* Interpreter in which to evaluate the
8329 * command. Also used for error reporting. */
8330 int objc, /* Number of words in command. */
8331 Tcl_Obj *const objv[], /* An array of pointers to objects that are
8332 * the words that make up the command. */
8333 int flags) /* Collection of OR-ed bits that control the
8334 * evaluation of the script. Only
8335 * TCL_EVAL_GLOBAL, TCL_EVAL_INVOKE and
8336 * TCL_EVAL_NOERR are currently supported. */
8337 {
8338 return TclNREvalObjv(interp, objc, objv, flags, NULL);
8339 }
8340
8341 int
8342 Tcl_NRCmdSwap(
8343 Tcl_Interp *interp,
8344 Tcl_Command cmd,
8345 int objc,
8346 Tcl_Obj *const objv[],
8347 int flags)
8348 {
8349 return TclNREvalObjv(interp, objc, objv, flags|TCL_EVAL_NOERR,
8350 (Command *) cmd);
8351 }
8352
8353 /*****************************************************************************
8354 * Tailcall related code
8355 *****************************************************************************
8356 *
8357 * The steps of the tailcall dance are as follows:
8358 *
8359 * 1. when [tailcall] is invoked, it stores the corresponding callback in
8360 * the current CallFrame and returns TCL_RETURN
8361 * 2. when the CallFrame is popped, it calls TclSetTailcall to store the
8362 * callback in the proper NRCommand callback - the spot where the command
8363 * that pushed the CallFrame is completely cleaned up
8364 * 3. when the NRCommand callback runs, it schedules the tailcall callback
8365 * to run immediately after it returns
8366 *
8367 * One delicate point is to properly define the NRCommand where the tailcall
8368 * will execute. There are functions whose purpose is to help define the
8369 * precise spot:
8370 * TclMarkTailcall: if the NEXT command to be pushed tailcalls, execution
8371 * should continue right here
8372 * TclSkipTailcall: if the NEXT command to be pushed tailcalls, execution
8373 * should continue after the CURRENT command is fully returned ("skip
8374 * the next command: we are redirecting to it, tailcalls should run
8375 * after WE return")
8376 * TclPushTailcallPoint: the search for a tailcalling spot cannot traverse
8377 * this point. This is special for OO, as some of the oo constructs
8378 * that behave like commands may not push an NRCommand callback.
8379 */
8380
8381 void
8382 TclMarkTailcall(
8383 Tcl_Interp *interp)
8384 {
8385 Interp *iPtr = (Interp *) interp;
8386
8387 if (iPtr->deferredCallbacks == NULL) {
8388 TclNRAddCallback(interp, NRCommand, NULL, NULL,
8389 NULL, NULL);
8390 iPtr->deferredCallbacks = TOP_CB(interp);
8391 }
8392 }
8393
8394 void
8395 TclSkipTailcall(
8396 Tcl_Interp *interp)
8397 {
8398 Interp *iPtr = (Interp *) interp;
8399
8400 TclMarkTailcall(interp);
8401 iPtr->deferredCallbacks->data[1] = INT2PTR(1);
8402 }
8403
8404 void
8405 TclPushTailcallPoint(
8406 Tcl_Interp *interp)
8407 {
8408 TclNRAddCallback(interp, NRCommand, NULL, NULL, NULL, NULL);
8409 ((Interp *) interp)->numLevels++;
8410 }
8411
8412 /*
8413 *----------------------------------------------------------------------
8414 *
8415 * TclSetTailcall --
8416 *
8417 * Splice a tailcall command in the proper spot of the NRE callback
8418 * stack, so that it runs at the right time.
8419 *
8420 *----------------------------------------------------------------------
8421 */
8422
8423 void
8424 TclSetTailcall(
8425 Tcl_Interp *interp,
8426 Tcl_Obj *listPtr)
8427 {
8428 /*
8429 * Find the splicing spot: right before the NRCommand of the thing
8430 * being tailcalled. Note that we skip NRCommands marked by a 1 in data[1]
8431 * (used by command redirectors).
8432 */
8433
8434 NRE_callback *runPtr;
8435
8436 for (runPtr = TOP_CB(interp); runPtr; runPtr = runPtr->nextPtr) {
8437 if (((runPtr->procPtr) == NRCommand) && !runPtr->data[1]) {
8438 break;
8439 }
8440 }
8441 if (!runPtr) {
8442 Tcl_Panic("tailcall cannot find the right splicing spot: should not happen!");
8443 }
8444 runPtr->data[1] = listPtr;
8445 }
8446
8447 /*
8448 *----------------------------------------------------------------------
8449 *
8450 * TclNRTailcallObjCmd --
8451 *
8452 * Prepare the tailcall as a list and store it in the current
8453 * varFrame. When the frame is later popped the tailcall will be spliced
8454 * at the proper place.
8455 *
8456 * Results:
8457 * The first NRCommand callback that is not marked to be skipped is
8458 * updated so that its data[1] field contains the tailcall list.
8459 *
8460 *----------------------------------------------------------------------
8461 */
8462
8463 int
8464 TclNRTailcallObjCmd(
8465 ClientData clientData,
8466 Tcl_Interp *interp,
8467 int objc,
8468 Tcl_Obj *const objv[])
8469 {
8470 Interp *iPtr = (Interp *) interp;
8471
8472 if (objc < 1) {
8473 Tcl_WrongNumArgs(interp, 1, objv, "?command? ?arg ...?");
8474 return TCL_ERROR;
8475 }
8476
8477 if (!(iPtr->varFramePtr->isProcCallFrame & 1)) {
8478 Tcl_SetObjResult(interp, Tcl_NewStringObj(
8479 "tailcall can only be called from a proc, lambda or method", -1));
8480 Tcl_SetErrorCode(interp, "TCL", "TAILCALL", "ILLEGAL", (char *)NULL);
8481 return TCL_ERROR;
8482 }
8483
8484 /*
8485 * Invocation without args just clears a scheduled tailcall; invocation
8486 * with an argument replaces any previously scheduled tailcall.
8487 */
8488
8489 if (iPtr->varFramePtr->tailcallPtr) {
8490 Tcl_DecrRefCount(iPtr->varFramePtr->tailcallPtr);
8491 iPtr->varFramePtr->tailcallPtr = NULL;
8492 }
8493
8494 /*
8495 * Create the callback to actually evaluate the tailcalled
8496 * command, then set it in the varFrame so that PopCallFrame can use it
8497 * at the proper time.
8498 */
8499
8500 if (objc > 1) {
8501 Tcl_Obj *listPtr, *nsObjPtr;
8502 Tcl_Namespace *nsPtr = (Tcl_Namespace *) iPtr->varFramePtr->nsPtr;
8503
8504 /*
8505 * The tailcall data is in a Tcl list: the first element is the
8506 * namespace, the rest the command to be tailcalled.
8507 */
8508
8509 nsObjPtr = Tcl_NewStringObj(nsPtr->fullName, -1);
8510 listPtr = Tcl_NewListObj(objc, objv);
8511 TclListObjSetElement(interp, listPtr, 0, nsObjPtr);
8512
8513 iPtr->varFramePtr->tailcallPtr = listPtr;
8514 }
8515 return TCL_RETURN;
8516 }
8517
8518 /*
8519 *----------------------------------------------------------------------
8520 *
8521 * TclNRTailcallEval --
8522 *
8523 * This NREcallback actually causes the tailcall to be evaluated.
8524 *
8525 *----------------------------------------------------------------------
8526 */
8527
8528 int
8529 TclNRTailcallEval(
8530 ClientData data[],
8531 Tcl_Interp *interp,
8532 int result)
8533 {
8534 Interp *iPtr = (Interp *) interp;
8535 Tcl_Obj *listPtr = (Tcl_Obj *)data[0], *nsObjPtr;
8536 Tcl_Namespace *nsPtr;
8537 int objc;
8538 Tcl_Obj **objv;
8539
8540 TclListObjGetElements(interp, listPtr, &objc, &objv);
8541 nsObjPtr = objv[0];
8542
8543 if (result == TCL_OK) {
8544 result = TclGetNamespaceFromObj(interp, nsObjPtr, &nsPtr);
8545 }
8546
8547 if (result != TCL_OK) {
8548 /*
8549 * Tailcall execution was preempted, eg by an intervening catch or by
8550 * a now-gone namespace: cleanup and return.
8551 */
8552
8553 Tcl_DecrRefCount(listPtr);
8554 return result;
8555 }
8556
8557 /*
8558 * Perform the tailcall
8559 */
8560
8561 TclMarkTailcall(interp);
8562 TclNRAddCallback(interp, TclNRReleaseValues, listPtr, NULL, NULL,NULL);
8563 iPtr->lookupNsPtr = (Namespace *) nsPtr;
8564 return TclNREvalObjv(interp, objc - 1, objv + 1, 0, NULL);
8565 }
8566
8567 int
8568 TclNRReleaseValues(
8569 ClientData data[],
8570 Tcl_Interp *interp,
8571 int result)
8572 {
8573 int i = 0;
8574
8575 while (i < 4) {
8576 if (data[i]) {
8577 Tcl_DecrRefCount((Tcl_Obj *) data[i]);
8578 } else {
8579 break;
8580 }
8581 i++;
8582 }
8583 return result;
8584 }
8585
8586 void
8587 Tcl_NRAddCallback(
8588 Tcl_Interp *interp,
8589 Tcl_NRPostProc *postProcPtr,
8590 ClientData data0,
8591 ClientData data1,
8592 ClientData data2,
8593 ClientData data3)
8594 {
8595 if (!(postProcPtr)) {
8596 Tcl_Panic("Adding a callback without an objProc?!");
8597 }
8598 TclNRAddCallback(interp, postProcPtr, data0, data1, data2, data3);
8599 }
8600
8601 /*
8602 *----------------------------------------------------------------------
8603 *
8604 * TclNRCoroutineObjCmd -- (and friends)
8605 *
8606 * This object-based function is invoked to process the "coroutine" Tcl
8607 * command. It is heavily based on "apply".
8608 *
8609 * Results:
8610 * A standard Tcl object result value.
8611 *
8612 * Side effects:
8613 * A new procedure gets created.
8614 *
8615 * ** FIRST EXPERIMENTAL IMPLEMENTATION **
8616 *
8617 * It is fairly amateurish and not up to our standards - mainly in terms of
8618 * error messages and [info] interaction. Just to test the infrastructure in
8619 * teov and tebc.
8620 *----------------------------------------------------------------------
8621 */
8622
8623 #define iPtr ((Interp *) interp)
8624
8625 int
8626 TclNRYieldObjCmd(
8627 ClientData clientData,
8628 Tcl_Interp *interp,
8629 int objc,
8630 Tcl_Obj *const objv[])
8631 {
8632 CoroutineData *corPtr = iPtr->execEnvPtr->corPtr;
8633
8634 if (objc > 2) {
8635 Tcl_WrongNumArgs(interp, 1, objv, "?returnValue?");
8636 return TCL_ERROR;
8637 }
8638
8639 if (!corPtr) {
8640 Tcl_SetObjResult(interp, Tcl_NewStringObj(
8641 "yield can only be called in a coroutine", -1));
8642 Tcl_SetErrorCode(interp, "TCL", "COROUTINE", "ILLEGAL_YIELD", (char *)NULL);
8643 return TCL_ERROR;
8644 }
8645
8646 if (objc == 2) {
8647 Tcl_SetObjResult(interp, objv[1]);
8648 }
8649
8650 NRE_ASSERT(!COR_IS_SUSPENDED(corPtr));
8651 TclNRAddCallback(interp, TclNRCoroutineActivateCallback, corPtr,
8652 clientData, NULL, NULL);
8653 return TCL_OK;
8654 }
8655
8656 int
8657 TclNRYieldToObjCmd(
8658 ClientData clientData,
8659 Tcl_Interp *interp,
8660 int objc,
8661 Tcl_Obj *const objv[])
8662 {
8663 CoroutineData *corPtr = iPtr->execEnvPtr->corPtr;
8664 Tcl_Obj *listPtr, *nsObjPtr;
8665 Tcl_Namespace *nsPtr = TclGetCurrentNamespace(interp);
8666
8667 if (objc < 2) {
8668 Tcl_WrongNumArgs(interp, 1, objv, "command ?arg ...?");
8669 return TCL_ERROR;
8670 }
8671
8672 if (!corPtr) {
8673 Tcl_SetObjResult(interp, Tcl_NewStringObj(
8674 "yieldto can only be called in a coroutine", -1));
8675 Tcl_SetErrorCode(interp, "TCL", "COROUTINE", "ILLEGAL_YIELD", (char *)NULL);
8676 return TCL_ERROR;
8677 }
8678
8679 if (((Namespace *) nsPtr)->flags & NS_DYING) {
8680 Tcl_SetObjResult(interp, Tcl_NewStringObj(
8681 "yieldto called in deleted namespace", -1));
8682 Tcl_SetErrorCode(interp, "TCL", "COROUTINE", "YIELDTO_IN_DELETED",
8683 (char *)NULL);
8684 return TCL_ERROR;
8685 }
8686
8687 /*
8688 * Add the tailcall in the caller env, then just yield.
8689 *
8690 * This is essentially code from TclNRTailcallObjCmd
8691 */
8692
8693 listPtr = Tcl_NewListObj(objc, objv);
8694 nsObjPtr = Tcl_NewStringObj(nsPtr->fullName, -1);
8695 TclListObjSetElement(interp, listPtr, 0, nsObjPtr);
8696
8697 /*
8698 * Add the callback in the caller's env, then instruct TEBC to yield.
8699 */
8700
8701 iPtr->execEnvPtr = corPtr->callerEEPtr;
8702 TclSetTailcall(interp, listPtr);
8703 iPtr->execEnvPtr = corPtr->eePtr;
8704
8705 return TclNRYieldObjCmd(INT2PTR(CORO_ACTIVATE_YIELDM), interp, 1, objv);
8706 }
8707
8708 static int
8709 RewindCoroutineCallback(
8710 ClientData data[],
8711 Tcl_Interp *interp,
8712 int result)
8713 {
8714 return Tcl_RestoreInterpState(interp, (Tcl_InterpState)data[0]);
8715 }
8716
8717 static int
8718 RewindCoroutine(
8719 CoroutineData *corPtr,
8720 int result)
8721 {
8722 Tcl_Interp *interp = corPtr->eePtr->interp;
8723 Tcl_InterpState state = Tcl_SaveInterpState(interp, result);
8724
8725 NRE_ASSERT(COR_IS_SUSPENDED(corPtr));
8726 NRE_ASSERT(corPtr->eePtr != NULL);
8727 NRE_ASSERT(corPtr->eePtr != iPtr->execEnvPtr);
8728
8729 corPtr->eePtr->rewind = 1;
8730 TclNRAddCallback(interp, RewindCoroutineCallback, state,
8731 NULL, NULL, NULL);
8732 return TclNRInterpCoroutine(corPtr, interp, 0, NULL);
8733 }
8734
8735 static void
8736 DeleteCoroutine(
8737 ClientData clientData)
8738 {
8739 CoroutineData *corPtr = (CoroutineData *)clientData;
8740 Tcl_Interp *interp = corPtr->eePtr->interp;
8741 NRE_callback *rootPtr = TOP_CB(interp);
8742
8743 if (COR_IS_SUSPENDED(corPtr)) {
8744 TclNRRunCallbacks(interp, RewindCoroutine(corPtr,TCL_OK), rootPtr);
8745 }
8746 }
8747
8748 static int
8749 NRCoroutineCallerCallback(
8750 ClientData data[],
8751 Tcl_Interp *interp,
8752 int result)
8753 {
8754 CoroutineData *corPtr = (CoroutineData *)data[0];
8755 Command *cmdPtr = corPtr->cmdPtr;
8756
8757 /*
8758 * This is the last callback in the caller execEnv, right before switching
8759 * to the coroutine's
8760 */
8761
8762 NRE_ASSERT(iPtr->execEnvPtr == corPtr->callerEEPtr);
8763
8764 if (!corPtr->eePtr) {
8765 /*
8766 * The execEnv was wound down but not deleted for our sake. We finish
8767 * the job here. The caller context has already been restored.
8768 */
8769
8770 NRE_ASSERT(iPtr->varFramePtr == corPtr->caller.varFramePtr);
8771 NRE_ASSERT(iPtr->framePtr == corPtr->caller.framePtr);
8772 NRE_ASSERT(iPtr->cmdFramePtr == corPtr->caller.cmdFramePtr);
8773 ckfree(corPtr);
8774 return result;
8775 }
8776
8777 NRE_ASSERT(COR_IS_SUSPENDED(corPtr));
8778 SAVE_CONTEXT(corPtr->running);
8779 RESTORE_CONTEXT(corPtr->caller);
8780
8781 if (cmdPtr->flags & CMD_IS_DELETED) {
8782 /*
8783 * The command was deleted while it was running: wind down the
8784 * execEnv, this will do the complete cleanup. RewindCoroutine will
8785 * restore both the caller's context and interp state.
8786 */
8787
8788 return RewindCoroutine(corPtr, result);
8789 }
8790
8791 return result;
8792 }
8793
8794 static int
8795 NRCoroutineExitCallback(
8796 ClientData data[],
8797 Tcl_Interp *interp,
8798 int result)
8799 {
8800 CoroutineData *corPtr = (CoroutineData *)data[0];
8801 Command *cmdPtr = corPtr->cmdPtr;
8802
8803 /*
8804 * This runs at the bottom of the Coroutine's execEnv: it will be executed
8805 * when the coroutine returns or is wound down, but not when it yields. It
8806 * deletes the coroutine and restores the caller's environment.
8807 */
8808
8809 NRE_ASSERT(interp == corPtr->eePtr->interp);
8810 NRE_ASSERT(TOP_CB(interp) == NULL);
8811 NRE_ASSERT(iPtr->execEnvPtr == corPtr->eePtr);
8812 NRE_ASSERT(!COR_IS_SUSPENDED(corPtr));
8813 NRE_ASSERT((corPtr->callerEEPtr->callbackPtr->procPtr == NRCoroutineCallerCallback));
8814
8815 cmdPtr->deleteProc = NULL;
8816 Tcl_DeleteCommandFromToken(interp, (Tcl_Command) cmdPtr);
8817 TclCleanupCommandMacro(cmdPtr);
8818
8819 corPtr->eePtr->corPtr = NULL;
8820 TclDeleteExecEnv(corPtr->eePtr);
8821 corPtr->eePtr = NULL;
8822
8823 corPtr->stackLevel = NULL;
8824
8825 /*
8826 * #280.
8827 * Drop the coroutine-owned copy of the lineLABCPtr hashtable for literal
8828 * command arguments in bytecode.
8829 */
8830
8831 Tcl_DeleteHashTable(corPtr->lineLABCPtr);
8832 ckfree(corPtr->lineLABCPtr);
8833 corPtr->lineLABCPtr = NULL;
8834
8835 RESTORE_CONTEXT(corPtr->caller);
8836 iPtr->execEnvPtr = corPtr->callerEEPtr;
8837 iPtr->numLevels++;
8838
8839 return result;
8840 }
8841
8842 /*
8843 *----------------------------------------------------------------------
8844 *
8845 * TclNRCoroutineActivateCallback --
8846 *
8847 * This is the workhorse for coroutines: it implements both yield and
8848 * resume.
8849 *
8850 * It is important that both be implemented in the same callback: the
8851 * detection of the impossibility to suspend due to a busy C-stack relies
8852 * on the precise position of a local variable in the stack. We do not
8853 * want the compiler to play tricks on us, either by moving things around
8854 * or inlining.
8855 *
8856 *----------------------------------------------------------------------
8857 */
8858
8859 int
8860 TclNRCoroutineActivateCallback(
8861 ClientData data[],
8862 Tcl_Interp *interp,
8863 int result /*result*/)
8864 {
8865 CoroutineData *corPtr = (CoroutineData *)data[0];
8866 int type = PTR2INT(data[1]);
8867 int numLevels;
8868 void *stackLevel = TclGetCStackPtr();
8869
8870 if (!corPtr->stackLevel) {
8871 /*
8872 * -- Coroutine is suspended --
8873 * Push the callback to restore the caller's context on yield or
8874 * return.
8875 */
8876
8877 TclNRAddCallback(interp, NRCoroutineCallerCallback, corPtr,
8878 NULL, NULL, NULL);
8879
8880 /*
8881 * Record the stackLevel at which the resume is happening, then swap
8882 * the interp's environment to make it suitable to run this coroutine.
8883 */
8884
8885 corPtr->stackLevel = stackLevel;
8886 numLevels = corPtr->auxNumLevels;
8887 corPtr->auxNumLevels = iPtr->numLevels;
8888
8889 SAVE_CONTEXT(corPtr->caller);
8890 corPtr->callerEEPtr = iPtr->execEnvPtr;
8891 RESTORE_CONTEXT(corPtr->running);
8892 iPtr->execEnvPtr = corPtr->eePtr;
8893 iPtr->numLevels += numLevels;
8894 } else {
8895 /*
8896 * Coroutine is active: yield
8897 */
8898
8899 if (corPtr->stackLevel != stackLevel) {
8900 Tcl_SetObjResult(interp, Tcl_NewStringObj(
8901 "cannot yield: C stack busy", -1));
8902 Tcl_SetErrorCode(interp, "TCL", "COROUTINE", "CANT_YIELD",
8903 (char *)NULL);
8904 return TCL_ERROR;
8905 }
8906
8907 if (type == CORO_ACTIVATE_YIELD) {
8908 corPtr->nargs = COROUTINE_ARGUMENTS_SINGLE_OPTIONAL;
8909 } else if (type == CORO_ACTIVATE_YIELDM) {
8910 corPtr->nargs = COROUTINE_ARGUMENTS_ARBITRARY;
8911 } else {
8912 Tcl_Panic("Yield received an option which is not implemented");
8913 }
8914
8915 corPtr->stackLevel = NULL;
8916
8917 numLevels = iPtr->numLevels;
8918 iPtr->numLevels = corPtr->auxNumLevels;
8919 corPtr->auxNumLevels = numLevels - corPtr->auxNumLevels;
8920
8921 iPtr->execEnvPtr = corPtr->callerEEPtr;
8922 }
8923
8924 return TCL_OK;
8925 }
8926
8927 /*
8928 *----------------------------------------------------------------------
8929 *
8930 * TclNREvalList --
8931 *
8932 * Callback to invoke command as list, used in order to delayed
8933 * processing of canonical list command in sane environment.
8934 *
8935 *----------------------------------------------------------------------
8936 */
8937
8938 static int
8939 TclNREvalList(
8940 ClientData data[],
8941 Tcl_Interp *interp,
8942 int result /*result*/)
8943 {
8944 int objc;
8945 Tcl_Obj **objv;
8946 Tcl_Obj *listPtr = (Tcl_Obj *)data[0];
8947
8948 Tcl_IncrRefCount(listPtr);
8949
8950 TclMarkTailcall(interp);
8951 TclNRAddCallback(interp, TclNRReleaseValues, listPtr, NULL, NULL,NULL);
8952 TclListObjGetElements(NULL, listPtr, &objc, &objv);
8953 return TclNREvalObjv(interp, objc, objv, 0, NULL);
8954 }
8955
8956 /*
8957 *----------------------------------------------------------------------
8958 *
8959 * CoroTypeObjCmd --
8960 *
8961 * Implementation of [::tcl::unsupported::corotype] command.
8962 *
8963 *----------------------------------------------------------------------
8964 */
8965
8966 static int
8967 CoroTypeObjCmd(
8968 ClientData clientData,
8969 Tcl_Interp *interp,
8970 int objc,
8971 Tcl_Obj *const objv[])
8972 {
8973 Command *cmdPtr;
8974 CoroutineData *corPtr;
8975
8976 if (objc != 2) {
8977 Tcl_WrongNumArgs(interp, 1, objv, "coroName");
8978 return TCL_ERROR;
8979 }
8980
8981 /*
8982 * Look up the coroutine.
8983 */
8984
8985 cmdPtr = (Command *) Tcl_GetCommandFromObj(interp, objv[1]);
8986 if ((!cmdPtr) || (cmdPtr->nreProc != TclNRInterpCoroutine)) {
8987 Tcl_SetObjResult(interp, Tcl_NewStringObj(
8988 "can only get coroutine type of a coroutine", -1));
8989 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "COROUTINE",
8990 TclGetString(objv[1]), (char *)NULL);
8991 return TCL_ERROR;
8992 }
8993
8994 /*
8995 * An active coroutine is "active". Can't tell what it might do in the
8996 * future.
8997 */
8998
8999 corPtr = (CoroutineData *)cmdPtr->objClientData;
9000 if (!COR_IS_SUSPENDED(corPtr)) {
9001 Tcl_SetObjResult(interp, Tcl_NewStringObj("active", -1));
9002 return TCL_OK;
9003 }
9004
9005 /*
9006 * Inactive coroutines are classified by the (effective) command used to
9007 * suspend them, which matters when you're injecting a probe.
9008 */
9009
9010 switch (corPtr->nargs) {
9011 case COROUTINE_ARGUMENTS_SINGLE_OPTIONAL:
9012 Tcl_SetObjResult(interp, Tcl_NewStringObj("yield", -1));
9013 return TCL_OK;
9014 case COROUTINE_ARGUMENTS_ARBITRARY:
9015 Tcl_SetObjResult(interp, Tcl_NewStringObj("yieldto", -1));
9016 return TCL_OK;
9017 default:
9018 Tcl_SetObjResult(interp, Tcl_NewStringObj(
9019 "unknown coroutine type", -1));
9020 Tcl_SetErrorCode(interp, "TCL", "COROUTINE", "BAD_TYPE", (char *)NULL);
9021 return TCL_ERROR;
9022 }
9023 }
9024
9025 /*
9026 *----------------------------------------------------------------------
9027 *
9028 * NRCoroInjectObjCmd --
9029 *
9030 * Implementation of [::tcl::unsupported::inject] command.
9031 *
9032 *----------------------------------------------------------------------
9033 */
9034
9035 static int
9036 NRCoroInjectObjCmd(
9037 ClientData clientData,
9038 Tcl_Interp *interp,
9039 int objc,
9040 Tcl_Obj *const objv[])
9041 {
9042 Command *cmdPtr;
9043 CoroutineData *corPtr;
9044 ExecEnv *savedEEPtr = iPtr->execEnvPtr;
9045
9046 /*
9047 * Usage more or less like tailcall:
9048 * inject coroName cmd ?arg1 arg2 ...?
9049 */
9050
9051 if (objc < 3) {
9052 Tcl_WrongNumArgs(interp, 1, objv, "coroName cmd ?arg1 arg2 ...?");
9053 return TCL_ERROR;
9054 }
9055
9056 cmdPtr = (Command *)Tcl_GetCommandFromObj(interp, objv[1]);
9057 if ((!cmdPtr) || (cmdPtr->nreProc != TclNRInterpCoroutine)) {
9058 Tcl_SetObjResult(interp, Tcl_NewStringObj(
9059 "can only inject a command into a coroutine", -1));
9060 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "COROUTINE",
9061 TclGetString(objv[1]), (char *)NULL);
9062 return TCL_ERROR;
9063 }
9064
9065 corPtr = (CoroutineData *)cmdPtr->objClientData;
9066 if (!COR_IS_SUSPENDED(corPtr)) {
9067 Tcl_SetObjResult(interp, Tcl_NewStringObj(
9068 "can only inject a command into a suspended coroutine", -1));
9069 Tcl_SetErrorCode(interp, "TCL", "COROUTINE", "ACTIVE", (char *)NULL);
9070 return TCL_ERROR;
9071 }
9072
9073 /*
9074 * Add the callback to the coro's execEnv, so that it is the first thing
9075 * to happen when the coro is resumed.
9076 */
9077
9078 iPtr->execEnvPtr = corPtr->eePtr;
9079 TclNRAddCallback(interp, TclNREvalList, Tcl_NewListObj(objc - 2, objv + 2),
9080 NULL, NULL, NULL);
9081 iPtr->execEnvPtr = savedEEPtr;
9082
9083 return TCL_OK;
9084 }
9085
9086 int
9087 TclNRInterpCoroutine(
9088 ClientData clientData,
9089 Tcl_Interp *interp, /* Current interpreter. */
9090 int objc, /* Number of arguments. */
9091 Tcl_Obj *const objv[]) /* Argument objects. */
9092 {
9093 CoroutineData *corPtr = (CoroutineData *)clientData;
9094
9095 if (!COR_IS_SUSPENDED(corPtr)) {
9096 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
9097 "coroutine \"%s\" is already running",
9098 TclGetString(objv[0])));
9099 Tcl_SetErrorCode(interp, "TCL", "COROUTINE", "BUSY", (char *)NULL);
9100 return TCL_ERROR;
9101 }
9102
9103 /*
9104 * Parse all the arguments to work out what to feed as the result of the
9105 * [yield]. TRICKY POINT: objc==0 happens here! It occurs when a coroutine
9106 * is deleted!
9107 */
9108
9109 switch (corPtr->nargs) {
9110 case COROUTINE_ARGUMENTS_SINGLE_OPTIONAL:
9111 if (objc == 2) {
9112 Tcl_SetObjResult(interp, objv[1]);
9113 } else if (objc > 2) {
9114 Tcl_WrongNumArgs(interp, 1, objv, "?arg?");
9115 return TCL_ERROR;
9116 }
9117 break;
9118 default:
9119 if (corPtr->nargs + 1 != objc) {
9120 Tcl_SetObjResult(interp,
9121 Tcl_NewStringObj("wrong coro nargs; how did we get here? "
9122 "not implemented!", -1));
9123 Tcl_SetErrorCode(interp, "TCL", "WRONGARGS", (char *)NULL);
9124 return TCL_ERROR;
9125 }
9126 /* fallthrough */
9127 case COROUTINE_ARGUMENTS_ARBITRARY:
9128 if (objc > 1) {
9129 Tcl_SetObjResult(interp, Tcl_NewListObj(objc - 1, objv + 1));
9130 }
9131 break;
9132 }
9133
9134 TclNRAddCallback(interp, TclNRCoroutineActivateCallback, corPtr,
9135 NULL, NULL, NULL);
9136 return TCL_OK;
9137 }
9138
9139 /*
9140 *----------------------------------------------------------------------
9141 *
9142 * TclNRCoroutineObjCmd --
9143 *
9144 * Implementation of [coroutine] command; see documentation for
9145 * description of what this does.
9146 *
9147 *----------------------------------------------------------------------
9148 */
9149
9150 int
9151 TclNRCoroutineObjCmd(
9152 ClientData dummy, /* Not used. */
9153 Tcl_Interp *interp, /* Current interpreter. */
9154 int objc, /* Number of arguments. */
9155 Tcl_Obj *const objv[]) /* Argument objects. */
9156 {
9157 Command *cmdPtr;
9158 CoroutineData *corPtr;
9159 const char *procName, *simpleName;
9160 Namespace *nsPtr, *altNsPtr, *cxtNsPtr,
9161 *inNsPtr = (Namespace *)TclGetCurrentNamespace(interp);
9162 Namespace *lookupNsPtr = iPtr->varFramePtr->nsPtr;
9163
9164 if (objc < 3) {
9165 Tcl_WrongNumArgs(interp, 1, objv, "name cmd ?arg ...?");
9166 return TCL_ERROR;
9167 }
9168
9169 procName = TclGetString(objv[1]);
9170 TclGetNamespaceForQualName(interp, procName, inNsPtr, 0,
9171 &nsPtr, &altNsPtr, &cxtNsPtr, &simpleName);
9172
9173 if (nsPtr == NULL) {
9174 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
9175 "can't create procedure \"%s\": unknown namespace",
9176 procName));
9177 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "NAMESPACE", (char *)NULL);
9178 return TCL_ERROR;
9179 }
9180 if (simpleName == NULL) {
9181 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
9182 "can't create procedure \"%s\": bad procedure name",
9183 procName));
9184 Tcl_SetErrorCode(interp, "TCL", "VALUE", "COMMAND", procName, (char *)NULL);
9185 return TCL_ERROR;
9186 }
9187
9188 /*
9189 * We ARE creating the coroutine command: allocate the corresponding
9190 * struct and create the corresponding command.
9191 */
9192
9193 corPtr = (CoroutineData *)ckalloc(sizeof(CoroutineData));
9194
9195 cmdPtr = (Command *) TclNRCreateCommandInNs(interp, simpleName,
9196 (Tcl_Namespace *)nsPtr, /*objProc*/ NULL, TclNRInterpCoroutine,
9197 corPtr, DeleteCoroutine);
9198
9199 corPtr->cmdPtr = cmdPtr;
9200 cmdPtr->refCount++;
9201
9202 /*
9203 * #280.
9204 * Provide the new coroutine with its own copy of the lineLABCPtr
9205 * hashtable for literal command arguments in bytecode. Note that that
9206 * CFWordBC chains are not duplicated, only the entrypoints to them. This
9207 * means that in the presence of coroutines each chain is potentially a
9208 * tree. Like the chain -> tree conversion of the CmdFrame stack.
9209 */
9210
9211 {
9212 Tcl_HashSearch hSearch;
9213 Tcl_HashEntry *hePtr;
9214
9215 corPtr->lineLABCPtr = (Tcl_HashTable *)ckalloc(sizeof(Tcl_HashTable));
9216 Tcl_InitHashTable(corPtr->lineLABCPtr, TCL_ONE_WORD_KEYS);
9217
9218 for (hePtr = Tcl_FirstHashEntry(iPtr->lineLABCPtr,&hSearch);
9219 hePtr; hePtr = Tcl_NextHashEntry(&hSearch)) {
9220 int isNew;
9221 Tcl_HashEntry *newPtr =
9222 Tcl_CreateHashEntry(corPtr->lineLABCPtr,
9223 Tcl_GetHashKey(iPtr->lineLABCPtr, hePtr),
9224 &isNew);
9225
9226 Tcl_SetHashValue(newPtr, Tcl_GetHashValue(hePtr));
9227 }
9228 }
9229
9230 /*
9231 * Create the base context.
9232 */
9233
9234 corPtr->running.framePtr = iPtr->rootFramePtr;
9235 corPtr->running.varFramePtr = iPtr->rootFramePtr;
9236 corPtr->running.cmdFramePtr = NULL;
9237 corPtr->running.lineLABCPtr = corPtr->lineLABCPtr;
9238 corPtr->stackLevel = NULL;
9239 corPtr->auxNumLevels = 0;
9240
9241 /*
9242 * Create the coro's execEnv, switch to it to push the exit and coro
9243 * command callbacks, then switch back.
9244 */
9245
9246 corPtr->eePtr = TclCreateExecEnv(interp, CORO_STACK_INITIAL_SIZE);
9247 corPtr->callerEEPtr = iPtr->execEnvPtr;
9248 corPtr->eePtr->corPtr = corPtr;
9249
9250 SAVE_CONTEXT(corPtr->caller);
9251 corPtr->callerEEPtr = iPtr->execEnvPtr;
9252 RESTORE_CONTEXT(corPtr->running);
9253 iPtr->execEnvPtr = corPtr->eePtr;
9254
9255 TclNRAddCallback(interp, NRCoroutineExitCallback, corPtr,
9256 NULL, NULL, NULL);
9257
9258 /*
9259 * Ensure that the command is looked up in the correct namespace.
9260 */
9261
9262 iPtr->lookupNsPtr = lookupNsPtr;
9263 Tcl_NREvalObj(interp, Tcl_NewListObj(objc - 2, objv + 2), 0);
9264 iPtr->numLevels--;
9265
9266 SAVE_CONTEXT(corPtr->running);
9267 RESTORE_CONTEXT(corPtr->caller);
9268 iPtr->execEnvPtr = corPtr->callerEEPtr;
9269
9270 /*
9271 * Now just resume the coroutine.
9272 */
9273
9274 TclNRAddCallback(interp, TclNRCoroutineActivateCallback, corPtr,
9275 NULL, NULL, NULL);
9276 return TCL_OK;
9277 }
9278
9279 /*
9280 * This is used in the [info] ensemble
9281 */
9282
9283 int
9284 TclInfoCoroutineCmd(
9285 ClientData dummy,
9286 Tcl_Interp *interp,
9287 int objc,
9288 Tcl_Obj *const objv[])
9289 {
9290 CoroutineData *corPtr = iPtr->execEnvPtr->corPtr;
9291
9292 if (objc != 1) {
9293 Tcl_WrongNumArgs(interp, 1, objv, NULL);
9294 return TCL_ERROR;
9295 }
9296
9297 if (corPtr && !(corPtr->cmdPtr->flags & CMD_IS_DELETED)) {
9298 Tcl_Obj *namePtr;
9299
9300 TclNewObj(namePtr);
9301 Tcl_GetCommandFullName(interp, (Tcl_Command) corPtr->cmdPtr, namePtr);
9302 Tcl_SetObjResult(interp, namePtr);
9303 }
9304 return TCL_OK;
9305 }
9306
9307 #undef iPtr
9308
9309 /*
9310 * Local Variables:
9311 * mode: c
9312 * c-basic-offset: 4
9313 * fill-column: 78
9314 * tab-width: 8
9315 * indent-tabs-mode: nil
9316 * End:
9317 */