Debian Codegraph @

generic/tclExecute.c

raw
1 /*
2 * tclExecute.c --
3 *
4 * This file contains procedures that execute byte-compiled Tcl commands.
5 *
6 * Copyright (c) 1996-1997 Sun Microsystems, Inc.
7 * Copyright (c) 1998-2000 Scriptics Corporation.
8 * Copyright (c) 2001 Kevin B. Kenny. All rights reserved.
9 * Copyright (c) 2002-2010 Miguel Sofer.
10 * Copyright (c) 2005-2007 Donal K. Fellows.
11 * Copyright (c) 2007 Daniel A. Steffen <[email protected]>
12 * Copyright (c) 2006-2008 Joe Mistachkin. All rights reserved.
13 *
14 * See the file "license.terms" for information on usage and redistribution of
15 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
16 */
17
18 #include "tclInt.h"
19 #include "tclCompile.h"
20 #include "tclOOInt.h"
21 #include "tommath.h"
22 #include <math.h>
23 #include <assert.h>
24
25 /*
26 * Hack to determine whether we may expect IEEE floating point. The hack is
27 * formally incorrect in that non-IEEE platforms might have the same precision
28 * and range, but VAX, IBM, and Cray do not; are there any other floating
29 * point units that we might care about?
30 */
31
32 #if (FLT_RADIX == 2) && (DBL_MANT_DIG == 53) && (DBL_MAX_EXP == 1024)
33 #define IEEE_FLOATING_POINT
34 #endif
35
36 /*
37 * A mask (should be 2**n-1) that is used to work out when the bytecode engine
38 * should call Tcl_AsyncReady() to see whether there is a signal that needs
39 * handling.
40 */
41
42 #ifndef ASYNC_CHECK_COUNT_MASK
43 # define ASYNC_CHECK_COUNT_MASK 63
44 #endif /* !ASYNC_CHECK_COUNT_MASK */
45
46 /*
47 * Boolean flag indicating whether the Tcl bytecode interpreter has been
48 * initialized.
49 */
50
51 static int execInitialized = 0;
52 TCL_DECLARE_MUTEX(execMutex)
53
54 static int cachedInExit = 0;
55
56 #ifdef TCL_COMPILE_DEBUG
57 /*
58 * Variable that controls whether execution tracing is enabled and, if so,
59 * what level of tracing is desired:
60 * 0: no execution tracing
61 * 1: trace invocations of Tcl procs only
62 * 2: trace invocations of all (not compiled away) commands
63 * 3: display each instruction executed
64 * This variable is linked to the Tcl variable "tcl_traceExec".
65 */
66
67 int tclTraceExec = 0;
68 #endif
69
70 /*
71 * Mapping from expression instruction opcodes to strings; used for error
72 * messages. Note that these entries must match the order and number of the
73 * expression opcodes (e.g., INST_LOR) in tclCompile.h.
74 *
75 * Does not include the string for INST_EXPON (and beyond), as that is
76 * disjoint for backward-compatibility reasons.
77 */
78
79 static const char *const operatorStrings[] = {
80 "||", "&&", "|", "^", "&", "==", "!=", "<", ">", "<=", ">=", "<<", ">>",
81 "+", "-", "*", "/", "%", "+", "-", "~", "!"
82 };
83
84 /*
85 * Mapping from Tcl result codes to strings; used for error and debugging
86 * messages.
87 */
88
89 #ifdef TCL_COMPILE_DEBUG
90 static const char *const resultStrings[] = {
91 "TCL_OK", "TCL_ERROR", "TCL_RETURN", "TCL_BREAK", "TCL_CONTINUE"
92 };
93 #endif
94
95 /*
96 * These are used by evalstats to monitor object usage in Tcl.
97 */
98
99 #ifdef TCL_COMPILE_STATS
100 long tclObjsAlloced = 0;
101 long tclObjsFreed = 0;
102 long tclObjsShared[TCL_MAX_SHARED_OBJ_STATS] = { 0, 0, 0, 0, 0 };
103 #endif /* TCL_COMPILE_STATS */
104
105 /*
106 * Support pre-8.5 bytecodes unless specifically requested otherwise.
107 */
108
109 #ifndef TCL_SUPPORT_84_BYTECODE
110 #define TCL_SUPPORT_84_BYTECODE 1
111 #endif
112
113 #if TCL_SUPPORT_84_BYTECODE
114 /*
115 * We need to know the tclBuiltinFuncTable to support translation of pre-8.5
116 * math functions to the namespace-based ::tcl::mathfunc::op in 8.5+.
117 */
118
119 typedef struct {
120 const char *name; /* Name of function. */
121 int numArgs; /* Number of arguments for function. */
122 } BuiltinFunc;
123
124 /*
125 * Table describing the built-in math functions. Entries in this table are
126 * indexed by the values of the INST_CALL_BUILTIN_FUNC instruction's
127 * operand byte.
128 */
129
130 static BuiltinFunc const tclBuiltinFuncTable[] = {
131 {"acos", 1},
132 {"asin", 1},
133 {"atan", 1},
134 {"atan2", 2},
135 {"ceil", 1},
136 {"cos", 1},
137 {"cosh", 1},
138 {"exp", 1},
139 {"floor", 1},
140 {"fmod", 2},
141 {"hypot", 2},
142 {"log", 1},
143 {"log10", 1},
144 {"pow", 2},
145 {"sin", 1},
146 {"sinh", 1},
147 {"sqrt", 1},
148 {"tan", 1},
149 {"tanh", 1},
150 {"abs", 1},
151 {"double", 1},
152 {"int", 1},
153 {"rand", 0},
154 {"round", 1},
155 {"srand", 1},
156 {"wide", 1},
157 {NULL, 0},
158 };
159
160 #define LAST_BUILTIN_FUNC 25
161 #endif
162
163 /*
164 * NR_TEBC
165 * Helpers for NR - non-recursive calls to TEBC
166 * Minimal data required to fully reconstruct the execution state.
167 */
168
169 typedef struct TEBCdata {
170 ByteCode *codePtr; /* Constant until the BC returns */
171 /* -----------------------------------------*/
172 ptrdiff_t *catchTop; /* These fields are used on return TO this */
173 Tcl_Obj *auxObjList; /* this level: they record the state when a */
174 CmdFrame cmdFrame; /* new codePtr was received for NR */
175 /* execution. */
176 void *stack[1]; /* Start of the actual combined catch and obj
177 * stacks; the struct will be expanded as
178 * necessary */
179 } TEBCdata;
180
181 #define TEBC_YIELD() \
182 do { \
183 esPtr->tosPtr = tosPtr; \
184 TclNRAddCallback(interp, TEBCresume, \
185 TD, pc, INT2PTR(cleanup), NULL); \
186 } while (0)
187
188 #define TEBC_DATA_DIG() \
189 do { \
190 tosPtr = esPtr->tosPtr; \
191 } while (0)
192
193 #define PUSH_TAUX_OBJ(objPtr) \
194 do { \
195 if (auxObjList) { \
196 (objPtr)->length += auxObjList->length; \
197 } \
198 (objPtr)->internalRep.twoPtrValue.ptr1 = auxObjList; \
199 auxObjList = (objPtr); \
200 } while (0)
201
202 #define POP_TAUX_OBJ() \
203 do { \
204 tmpPtr = auxObjList; \
205 auxObjList = tmpPtr->internalRep.twoPtrValue.ptr1; \
206 Tcl_DecrRefCount(tmpPtr); \
207 } while (0)
208
209 /*
210 * These variable-access macros have to coincide with those in tclVar.c
211 */
212
213 #define VarHashGetValue(hPtr) \
214 ((Var *) ((char *)hPtr - TclOffset(VarInHash, entry)))
215
216 static inline Var *
217 VarHashCreateVar(
218 TclVarHashTable *tablePtr,
219 Tcl_Obj *key,
220 int *newPtr)
221 {
222 Tcl_HashEntry *hPtr = Tcl_CreateHashEntry(&tablePtr->table,
223 key, newPtr);
224
225 if (!hPtr) {
226 return NULL;
227 }
228 return VarHashGetValue(hPtr);
229 }
230
231 #define VarHashFindVar(tablePtr, key) \
232 VarHashCreateVar((tablePtr), (key), NULL)
233
234 /*
235 * The new macro for ending an instruction; note that a reasonable C-optimiser
236 * will resolve all branches at compile time. (result) is always a constant;
237 * the macro NEXT_INST_F handles constant (nCleanup), NEXT_INST_V is resolved
238 * at runtime for variable (nCleanup).
239 *
240 * ARGUMENTS:
241 * pcAdjustment: how much to increment pc
242 * nCleanup: how many objects to remove from the stack
243 * resultHandling: 0 indicates no object should be pushed on the stack;
244 * otherwise, push objResultPtr. If (result < 0), objResultPtr already
245 * has the correct reference count.
246 *
247 * We use the new compile-time assertions to check that nCleanup is constant
248 * and within range.
249 */
250
251 /* Verify the stack depth, only when no expansion is in progress */
252
253 #ifdef TCL_COMPILE_DEBUG
254 #define CHECK_STACK() \
255 do { \
256 ValidatePcAndStackTop(codePtr, pc, CURR_DEPTH, \
257 /*checkStack*/ !(starting || auxObjList)); \
258 starting = 0; \
259 } while (0)
260 #else
261 #define CHECK_STACK()
262 #endif
263
264 #define NEXT_INST_F(pcAdjustment, nCleanup, resultHandling) \
265 do { \
266 TCL_CT_ASSERT((nCleanup >= 0) && (nCleanup <= 2)); \
267 CHECK_STACK(); \
268 if (nCleanup == 0) { \
269 if (resultHandling != 0) { \
270 if ((resultHandling) > 0) { \
271 PUSH_OBJECT(objResultPtr); \
272 } else { \
273 *(++tosPtr) = objResultPtr; \
274 } \
275 } \
276 pc += (pcAdjustment); \
277 goto cleanup0; \
278 } else if (resultHandling != 0) { \
279 if ((resultHandling) > 0) { \
280 Tcl_IncrRefCount(objResultPtr); \
281 } \
282 pc += (pcAdjustment); \
283 switch (nCleanup) { \
284 case 1: goto cleanup1_pushObjResultPtr; \
285 case 2: goto cleanup2_pushObjResultPtr; \
286 case 0: break; \
287 } \
288 } else { \
289 pc += (pcAdjustment); \
290 switch (nCleanup) { \
291 case 1: goto cleanup1; \
292 case 2: goto cleanup2; \
293 case 0: break; \
294 } \
295 } \
296 } while (0)
297
298 #define NEXT_INST_V(pcAdjustment, nCleanup, resultHandling) \
299 CHECK_STACK(); \
300 do { \
301 pc += (pcAdjustment); \
302 cleanup = (nCleanup); \
303 if (resultHandling) { \
304 if ((resultHandling) > 0) { \
305 Tcl_IncrRefCount(objResultPtr); \
306 } \
307 goto cleanupV_pushObjResultPtr; \
308 } else { \
309 goto cleanupV; \
310 } \
311 } while (0)
312
313 #ifndef TCL_COMPILE_DEBUG
314 #define JUMP_PEEPHOLE_F(condition, pcAdjustment, cleanup) \
315 do { \
316 pc += (pcAdjustment); \
317 switch (*pc) { \
318 case INST_JUMP_FALSE1: \
319 NEXT_INST_F(((condition)? 2 : TclGetInt1AtPtr(pc+1)), (cleanup), 0); \
320 break; \
321 case INST_JUMP_TRUE1: \
322 NEXT_INST_F(((condition)? TclGetInt1AtPtr(pc+1) : 2), (cleanup), 0); \
323 break; \
324 case INST_JUMP_FALSE4: \
325 NEXT_INST_F(((condition)? 5 : TclGetInt4AtPtr(pc+1)), (cleanup), 0); \
326 break; \
327 case INST_JUMP_TRUE4: \
328 NEXT_INST_F(((condition)? TclGetInt4AtPtr(pc+1) : 5), (cleanup), 0); \
329 break; \
330 default: \
331 if ((condition) < 0) { \
332 TclNewIntObj(objResultPtr, -1); \
333 } else { \
334 objResultPtr = TCONST((condition) > 0); \
335 } \
336 NEXT_INST_F(0, (cleanup), 1); \
337 break; \
338 } \
339 } while (0)
340 #define JUMP_PEEPHOLE_V(condition, pcAdjustment, cleanup) \
341 do { \
342 pc += (pcAdjustment); \
343 switch (*pc) { \
344 case INST_JUMP_FALSE1: \
345 NEXT_INST_V(((condition)? 2 : TclGetInt1AtPtr(pc+1)), (cleanup), 0); \
346 break; \
347 case INST_JUMP_TRUE1: \
348 NEXT_INST_V(((condition)? TclGetInt1AtPtr(pc+1) : 2), (cleanup), 0); \
349 break; \
350 case INST_JUMP_FALSE4: \
351 NEXT_INST_V(((condition)? 5 : TclGetInt4AtPtr(pc+1)), (cleanup), 0); \
352 break; \
353 case INST_JUMP_TRUE4: \
354 NEXT_INST_V(((condition)? TclGetInt4AtPtr(pc+1) : 5), (cleanup), 0); \
355 break; \
356 default: \
357 if ((condition) < 0) { \
358 TclNewIntObj(objResultPtr, -1); \
359 } else { \
360 objResultPtr = TCONST((condition) > 0); \
361 } \
362 NEXT_INST_V(0, (cleanup), 1); \
363 break; \
364 } \
365 } while (0)
366 #else /* TCL_COMPILE_DEBUG */
367 #define JUMP_PEEPHOLE_F(condition, pcAdjustment, cleanup) \
368 do{ \
369 if ((condition) < 0) { \
370 TclNewIntObj(objResultPtr, -1); \
371 } else { \
372 objResultPtr = TCONST((condition) > 0); \
373 } \
374 NEXT_INST_F((pcAdjustment), (cleanup), 1); \
375 } while (0)
376 #define JUMP_PEEPHOLE_V(condition, pcAdjustment, cleanup) \
377 do{ \
378 if ((condition) < 0) { \
379 TclNewIntObj(objResultPtr, -1); \
380 } else { \
381 objResultPtr = TCONST((condition) > 0); \
382 } \
383 NEXT_INST_V((pcAdjustment), (cleanup), 1); \
384 } while (0)
385 #endif
386
387 /*
388 * Macros used to cache often-referenced Tcl evaluation stack information
389 * in local variables. Note that a DECACHE_STACK_INFO()-CACHE_STACK_INFO()
390 * pair must surround any call inside TclNRExecuteByteCode (and a few other
391 * procedures that use this scheme) that could result in a recursive call
392 * to TclNRExecuteByteCode.
393 */
394
395 #define CACHE_STACK_INFO() \
396 checkInterp = 1
397
398 #define DECACHE_STACK_INFO() \
399 esPtr->tosPtr = tosPtr
400
401 /*
402 * Macros used to access items on the Tcl evaluation stack. PUSH_OBJECT
403 * increments the object's ref count since it makes the stack have another
404 * reference pointing to the object. However, POP_OBJECT does not decrement
405 * the ref count. This is because the stack may hold the only reference to the
406 * object, so the object would be destroyed if its ref count were decremented
407 * before the caller had a chance to, e.g., store it in a variable. It is the
408 * caller's responsibility to decrement the ref count when it is finished with
409 * an object.
410 *
411 * WARNING! It is essential that objPtr only appear once in the PUSH_OBJECT
412 * macro. The actual parameter might be an expression with side effects, and
413 * this ensures that it will be executed only once.
414 */
415
416 #define PUSH_OBJECT(objPtr) \
417 Tcl_IncrRefCount(*(++tosPtr) = (objPtr))
418
419 #define POP_OBJECT() *(tosPtr--)
420
421 #define OBJ_AT_TOS *tosPtr
422
423 #define OBJ_UNDER_TOS *(tosPtr-1)
424
425 #define OBJ_AT_DEPTH(n) *(tosPtr-(n))
426
427 #define CURR_DEPTH ((ptrdiff_t) (tosPtr - initTosPtr))
428
429 #define STACK_BASE(esPtr) ((esPtr)->stackWords - 1)
430
431 /*
432 * Macros used to trace instruction execution. The macros TRACE,
433 * TRACE_WITH_OBJ, and O2S are only used inside TclNRExecuteByteCode. O2S is
434 * only used in TRACE* calls to get a string from an object.
435 */
436
437 #ifdef TCL_COMPILE_DEBUG
438 # define TRACE(a) \
439 while (traceInstructions) { \
440 fprintf(stdout, "%2d: %2d (%u) %s ", iPtr->numLevels, \
441 (int) CURR_DEPTH, \
442 (unsigned) (pc - codePtr->codeStart), \
443 GetOpcodeName(pc)); \
444 printf a; \
445 break; \
446 }
447 # define TRACE_APPEND(a) \
448 while (traceInstructions) { \
449 printf a; \
450 break; \
451 }
452 # define TRACE_ERROR(interp) \
453 TRACE_APPEND(("ERROR: %.30s\n", O2S(Tcl_GetObjResult(interp))));
454 # define TRACE_WITH_OBJ(a, objPtr) \
455 while (traceInstructions) { \
456 fprintf(stdout, "%2d: %2d (%u) %s ", iPtr->numLevels, \
457 (int) CURR_DEPTH, \
458 (unsigned) (pc - codePtr->codeStart), \
459 GetOpcodeName(pc)); \
460 printf a; \
461 TclPrintObject(stdout, objPtr, 30); \
462 fprintf(stdout, "\n"); \
463 break; \
464 }
465 # define O2S(objPtr) \
466 (objPtr ? TclGetString(objPtr) : "")
467 #else /* !TCL_COMPILE_DEBUG */
468 # define TRACE(a)
469 # define TRACE_APPEND(a)
470 # define TRACE_ERROR(interp)
471 # define TRACE_WITH_OBJ(a, objPtr)
472 # define O2S(objPtr)
473 #endif /* TCL_COMPILE_DEBUG */
474
475 /*
476 * DTrace instruction probe macros.
477 */
478
479 #define TCL_DTRACE_INST_NEXT() \
480 do { \
481 if (TCL_DTRACE_INST_DONE_ENABLED()) { \
482 if (curInstName) { \
483 TCL_DTRACE_INST_DONE(curInstName, (int) CURR_DEPTH, \
484 tosPtr); \
485 } \
486 curInstName = tclInstructionTable[*pc].name; \
487 if (TCL_DTRACE_INST_START_ENABLED()) { \
488 TCL_DTRACE_INST_START(curInstName, (int) CURR_DEPTH, \
489 tosPtr); \
490 } \
491 } else if (TCL_DTRACE_INST_START_ENABLED()) { \
492 TCL_DTRACE_INST_START(tclInstructionTable[*pc].name, \
493 (int) CURR_DEPTH, tosPtr); \
494 } \
495 } while (0)
496 #define TCL_DTRACE_INST_LAST() \
497 do { \
498 if (TCL_DTRACE_INST_DONE_ENABLED() && curInstName) { \
499 TCL_DTRACE_INST_DONE(curInstName, (int) CURR_DEPTH, tosPtr);\
500 } \
501 } while (0)
502
503 /*
504 * Macro used in this file to save a function call for common uses of
505 * TclGetNumberFromObj(). The ANSI C "prototype" is:
506 *
507 * MODULE_SCOPE int GetNumberFromObj(Tcl_Interp *interp, Tcl_Obj *objPtr,
508 * ClientData *ptrPtr, int *tPtr);
509 */
510
511 #ifdef TCL_WIDE_INT_IS_LONG
512 #define GetNumberFromObj(interp, objPtr, ptrPtr, tPtr) \
513 (((objPtr)->typePtr == &tclIntType) \
514 ? (*(tPtr) = TCL_NUMBER_LONG, \
515 *(ptrPtr) = (ClientData) \
516 (&((objPtr)->internalRep.longValue)), TCL_OK) : \
517 ((objPtr)->typePtr == &tclDoubleType) \
518 ? (((TclIsNaN((objPtr)->internalRep.doubleValue)) \
519 ? (*(tPtr) = TCL_NUMBER_NAN) \
520 : (*(tPtr) = TCL_NUMBER_DOUBLE)), \
521 *(ptrPtr) = (ClientData) \
522 (&((objPtr)->internalRep.doubleValue)), TCL_OK) : \
523 (((objPtr)->bytes != NULL) && ((objPtr)->length == 0)) \
524 ? (*(tPtr) = TCL_NUMBER_LONG),TCL_ERROR : \
525 TclGetNumberFromObj((interp), (objPtr), (ptrPtr), (tPtr)))
526 #else /* !TCL_WIDE_INT_IS_LONG */
527 #define GetNumberFromObj(interp, objPtr, ptrPtr, tPtr) \
528 (((objPtr)->typePtr == &tclIntType) \
529 ? (*(tPtr) = TCL_NUMBER_LONG, \
530 *(ptrPtr) = (ClientData) \
531 (&((objPtr)->internalRep.longValue)), TCL_OK) : \
532 ((objPtr)->typePtr == &tclWideIntType) \
533 ? (*(tPtr) = TCL_NUMBER_WIDE, \
534 *(ptrPtr) = (ClientData) \
535 (&((objPtr)->internalRep.wideValue)), TCL_OK) : \
536 ((objPtr)->typePtr == &tclDoubleType) \
537 ? (((TclIsNaN((objPtr)->internalRep.doubleValue)) \
538 ? (*(tPtr) = TCL_NUMBER_NAN) \
539 : (*(tPtr) = TCL_NUMBER_DOUBLE)), \
540 *(ptrPtr) = (ClientData) \
541 (&((objPtr)->internalRep.doubleValue)), TCL_OK) : \
542 (((objPtr)->bytes != NULL) && ((objPtr)->length == 0)) \
543 ? (*(tPtr) = TCL_NUMBER_LONG),TCL_ERROR : \
544 TclGetNumberFromObj((interp), (objPtr), (ptrPtr), (tPtr)))
545 #endif /* TCL_WIDE_INT_IS_LONG */
546
547 /*
548 * Macro used in this file to save a function call for common uses of
549 * Tcl_GetBooleanFromObj(). The ANSI C "prototype" is:
550 *
551 * MODULE_SCOPE int TclGetBooleanFromObj(Tcl_Interp *interp, Tcl_Obj *objPtr,
552 * int *intPtr);
553 */
554
555 #define TclGetBooleanFromObj(interp, objPtr, intPtr) \
556 ((((objPtr)->typePtr == &tclIntType) \
557 || ((objPtr)->typePtr == &tclBooleanType)) \
558 ? (*(intPtr) = ((objPtr)->internalRep.longValue!=0), TCL_OK) \
559 : Tcl_GetBooleanFromObj((interp), (objPtr), (intPtr)))
560
561 /*
562 * Macro used to make the check for type overflow more mnemonic. This works by
563 * comparing sign bits; the rest of the word is irrelevant. The ANSI C
564 * "prototype" (where inttype_t is any integer type) is:
565 *
566 * MODULE_SCOPE int Overflowing(inttype_t a, inttype_t b, inttype_t sum);
567 *
568 * Check first the condition most likely to fail in usual code (at least for
569 * usage in [incr]: do the first summand and the sum have != signs?
570 */
571
572 #define Overflowing(a,b,sum) ((((a)^(sum)) < 0) && (((a)^(b)) >= 0))
573
574 /*
575 * Macro for checking whether the type is NaN, used when we're thinking about
576 * throwing an error for supplying a non-number number.
577 */
578
579 #ifndef ACCEPT_NAN
580 #define IsErroringNaNType(type) ((type) == TCL_NUMBER_NAN)
581 #else
582 #define IsErroringNaNType(type) 0
583 #endif
584
585 /*
586 * Auxiliary tables used to compute powers of small integers.
587 */
588
589 #if (LONG_MAX == 0x7FFFFFFF)
590
591 /*
592 * Maximum base that, when raised to powers 2, 3, ... 8, fits in a 32-bit
593 * signed integer.
594 */
595
596 static const long MaxBase32[] = {46340, 1290, 215, 73, 35, 21, 14};
597 static const size_t MaxBase32Size = sizeof(MaxBase32)/sizeof(long);
598
599 /*
600 * Table giving 3, 4, ..., 11, raised to the powers 9, 10, ..., as far as they
601 * fit in a 32-bit signed integer. Exp32Index[i] gives the starting index of
602 * powers of i+3; Exp32Value[i] gives the corresponding powers.
603 */
604
605 static const unsigned short Exp32Index[] = {
606 0, 11, 18, 23, 26, 29, 31, 32, 33
607 };
608 static const size_t Exp32IndexSize =
609 sizeof(Exp32Index) / sizeof(unsigned short);
610 static const long Exp32Value[] = {
611 19683, 59049, 177147, 531441, 1594323, 4782969, 14348907, 43046721,
612 129140163, 387420489, 1162261467, 262144, 1048576, 4194304,
613 16777216, 67108864, 268435456, 1073741824, 1953125, 9765625,
614 48828125, 244140625, 1220703125, 10077696, 60466176, 362797056,
615 40353607, 282475249, 1977326743, 134217728, 1073741824, 387420489,
616 1000000000
617 };
618 static const size_t Exp32ValueSize = sizeof(Exp32Value)/sizeof(long);
619 #endif /* LONG_MAX == 0x7FFFFFFF -- 32 bit machine */
620
621 #if (LONG_MAX > 0x7FFFFFFF) || !defined(TCL_WIDE_INT_IS_LONG)
622
623 /*
624 * Maximum base that, when raised to powers 2, 3, ..., 16, fits in a
625 * Tcl_WideInt.
626 */
627
628 static const Tcl_WideInt MaxBase64[] = {
629 (Tcl_WideInt)46340*65536+62259, /* 3037000499 == isqrt(2**63-1) */
630 (Tcl_WideInt)2097151, (Tcl_WideInt)55108, (Tcl_WideInt)6208,
631 (Tcl_WideInt)1448, (Tcl_WideInt)511, (Tcl_WideInt)234, (Tcl_WideInt)127,
632 (Tcl_WideInt)78, (Tcl_WideInt)52, (Tcl_WideInt)38, (Tcl_WideInt)28,
633 (Tcl_WideInt)22, (Tcl_WideInt)18, (Tcl_WideInt)15
634 };
635 static const size_t MaxBase64Size = sizeof(MaxBase64)/sizeof(Tcl_WideInt);
636
637 /*
638 * Table giving 3, 4, ..., 13 raised to powers greater than 16 when the
639 * results fit in a 64-bit signed integer.
640 */
641
642 static const unsigned short Exp64Index[] = {
643 0, 23, 38, 49, 57, 63, 67, 70, 72, 74, 75, 76
644 };
645 static const size_t Exp64IndexSize =
646 sizeof(Exp64Index) / sizeof(unsigned short);
647 static const Tcl_WideInt Exp64Value[] = {
648 (Tcl_WideInt)243*243*243*3*3,
649 (Tcl_WideInt)243*243*243*3*3*3,
650 (Tcl_WideInt)243*243*243*3*3*3*3,
651 (Tcl_WideInt)243*243*243*243,
652 (Tcl_WideInt)243*243*243*243*3,
653 (Tcl_WideInt)243*243*243*243*3*3,
654 (Tcl_WideInt)243*243*243*243*3*3*3,
655 (Tcl_WideInt)243*243*243*243*3*3*3*3,
656 (Tcl_WideInt)243*243*243*243*243,
657 (Tcl_WideInt)243*243*243*243*243*3,
658 (Tcl_WideInt)243*243*243*243*243*3*3,
659 (Tcl_WideInt)243*243*243*243*243*3*3*3,
660 (Tcl_WideInt)243*243*243*243*243*3*3*3*3,
661 (Tcl_WideInt)243*243*243*243*243*243,
662 (Tcl_WideInt)243*243*243*243*243*243*3,
663 (Tcl_WideInt)243*243*243*243*243*243*3*3,
664 (Tcl_WideInt)243*243*243*243*243*243*3*3*3,
665 (Tcl_WideInt)243*243*243*243*243*243*3*3*3*3,
666 (Tcl_WideInt)243*243*243*243*243*243*243,
667 (Tcl_WideInt)243*243*243*243*243*243*243*3,
668 (Tcl_WideInt)243*243*243*243*243*243*243*3*3,
669 (Tcl_WideInt)243*243*243*243*243*243*243*3*3*3,
670 (Tcl_WideInt)243*243*243*243*243*243*243*3*3*3*3,
671 (Tcl_WideInt)1024*1024*1024*4*4,
672 (Tcl_WideInt)1024*1024*1024*4*4*4,
673 (Tcl_WideInt)1024*1024*1024*4*4*4*4,
674 (Tcl_WideInt)1024*1024*1024*1024,
675 (Tcl_WideInt)1024*1024*1024*1024*4,
676 (Tcl_WideInt)1024*1024*1024*1024*4*4,
677 (Tcl_WideInt)1024*1024*1024*1024*4*4*4,
678 (Tcl_WideInt)1024*1024*1024*1024*4*4*4*4,
679 (Tcl_WideInt)1024*1024*1024*1024*1024,
680 (Tcl_WideInt)1024*1024*1024*1024*1024*4,
681 (Tcl_WideInt)1024*1024*1024*1024*1024*4*4,
682 (Tcl_WideInt)1024*1024*1024*1024*1024*4*4*4,
683 (Tcl_WideInt)1024*1024*1024*1024*1024*4*4*4*4,
684 (Tcl_WideInt)1024*1024*1024*1024*1024*1024,
685 (Tcl_WideInt)1024*1024*1024*1024*1024*1024*4,
686 (Tcl_WideInt)3125*3125*3125*5*5,
687 (Tcl_WideInt)3125*3125*3125*5*5*5,
688 (Tcl_WideInt)3125*3125*3125*5*5*5*5,
689 (Tcl_WideInt)3125*3125*3125*3125,
690 (Tcl_WideInt)3125*3125*3125*3125*5,
691 (Tcl_WideInt)3125*3125*3125*3125*5*5,
692 (Tcl_WideInt)3125*3125*3125*3125*5*5*5,
693 (Tcl_WideInt)3125*3125*3125*3125*5*5*5*5,
694 (Tcl_WideInt)3125*3125*3125*3125*3125,
695 (Tcl_WideInt)3125*3125*3125*3125*3125*5,
696 (Tcl_WideInt)3125*3125*3125*3125*3125*5*5,
697 (Tcl_WideInt)7776*7776*7776*6*6,
698 (Tcl_WideInt)7776*7776*7776*6*6*6,
699 (Tcl_WideInt)7776*7776*7776*6*6*6*6,
700 (Tcl_WideInt)7776*7776*7776*7776,
701 (Tcl_WideInt)7776*7776*7776*7776*6,
702 (Tcl_WideInt)7776*7776*7776*7776*6*6,
703 (Tcl_WideInt)7776*7776*7776*7776*6*6*6,
704 (Tcl_WideInt)7776*7776*7776*7776*6*6*6*6,
705 (Tcl_WideInt)16807*16807*16807*7*7,
706 (Tcl_WideInt)16807*16807*16807*7*7*7,
707 (Tcl_WideInt)16807*16807*16807*7*7*7*7,
708 (Tcl_WideInt)16807*16807*16807*16807,
709 (Tcl_WideInt)16807*16807*16807*16807*7,
710 (Tcl_WideInt)16807*16807*16807*16807*7*7,
711 (Tcl_WideInt)32768*32768*32768*8*8,
712 (Tcl_WideInt)32768*32768*32768*8*8*8,
713 (Tcl_WideInt)32768*32768*32768*8*8*8*8,
714 (Tcl_WideInt)32768*32768*32768*32768,
715 (Tcl_WideInt)59049*59049*59049*9*9,
716 (Tcl_WideInt)59049*59049*59049*9*9*9,
717 (Tcl_WideInt)59049*59049*59049*9*9*9*9,
718 (Tcl_WideInt)100000*100000*100000*10*10,
719 (Tcl_WideInt)100000*100000*100000*10*10*10,
720 (Tcl_WideInt)161051*161051*161051*11*11,
721 (Tcl_WideInt)161051*161051*161051*11*11*11,
722 (Tcl_WideInt)248832*248832*248832*12*12,
723 (Tcl_WideInt)371293*371293*371293*13*13
724 };
725 static const size_t Exp64ValueSize = sizeof(Exp64Value) / sizeof(Tcl_WideInt);
726 #endif /* (LONG_MAX > 0x7FFFFFFF) || !defined(TCL_WIDE_INT_IS_LONG) */
727
728 /*
729 * Markers for ExecuteExtendedBinaryMathOp.
730 */
731
732 #define DIVIDED_BY_ZERO ((Tcl_Obj *) -1)
733 #define EXPONENT_OF_ZERO ((Tcl_Obj *) -2)
734 #define GENERAL_ARITHMETIC_ERROR ((Tcl_Obj *) -3)
735
736 /*
737 * Declarations for local procedures to this file:
738 */
739
740 #ifdef TCL_COMPILE_STATS
741 static int EvalStatsCmd(ClientData clientData,
742 Tcl_Interp *interp, int objc,
743 Tcl_Obj *const objv[]);
744 #endif /* TCL_COMPILE_STATS */
745 #ifdef TCL_COMPILE_DEBUG
746 static const char * GetOpcodeName(const unsigned char *pc);
747 static void PrintByteCodeInfo(ByteCode *codePtr);
748 static const char * StringForResultCode(int result);
749 static void ValidatePcAndStackTop(ByteCode *codePtr,
750 const unsigned char *pc, int stackTop,
751 int checkStack);
752 #endif /* TCL_COMPILE_DEBUG */
753 static ByteCode * CompileExprObj(Tcl_Interp *interp, Tcl_Obj *objPtr);
754 static void DeleteExecStack(ExecStack *esPtr);
755 static void DupExprCodeInternalRep(Tcl_Obj *srcPtr,
756 Tcl_Obj *copyPtr);
757 static int CompareTwoNumbers(Tcl_Obj *valuePtr,
758 Tcl_Obj *value2Ptr);
759 static Tcl_Obj * ExecuteExtendedBinaryMathOp(Tcl_Interp *interp,
760 int opcode, Tcl_Obj **constants,
761 Tcl_Obj *valuePtr, Tcl_Obj *value2Ptr);
762 static Tcl_Obj * ExecuteExtendedUnaryMathOp(int opcode,
763 Tcl_Obj *valuePtr);
764 static void FreeExprCodeInternalRep(Tcl_Obj *objPtr);
765 static ExceptionRange * GetExceptRangeForPc(const unsigned char *pc,
766 int searchMode, ByteCode *codePtr);
767 static const char * GetSrcInfoForPc(const unsigned char *pc,
768 ByteCode *codePtr, int *lengthPtr,
769 const unsigned char **pcBeg, int *cmdIdxPtr);
770 static Tcl_Obj ** GrowEvaluationStack(ExecEnv *eePtr, int growth,
771 int move);
772 static void IllegalExprOperandType(Tcl_Interp *interp,
773 const unsigned char *pc, Tcl_Obj *opndPtr);
774 static void InitByteCodeExecution(Tcl_Interp *interp);
775 static inline int wordSkip(void *ptr);
776 static void ReleaseDictIterator(Tcl_Obj *objPtr);
777 /* Useful elsewhere, make available in tclInt.h or stubs? */
778 static Tcl_Obj ** StackAllocWords(Tcl_Interp *interp, int numWords);
779 static Tcl_Obj ** StackReallocWords(Tcl_Interp *interp, int numWords);
780 static Tcl_NRPostProc CopyCallback;
781 static Tcl_NRPostProc ExprObjCallback;
782 static Tcl_NRPostProc FinalizeOONext;
783 static Tcl_NRPostProc FinalizeOONextFilter;
784 static Tcl_NRPostProc TEBCresume;
785
786 /*
787 * The structure below defines a bytecode Tcl object type to hold the
788 * compiled bytecode for Tcl expressions.
789 */
790
791 static const Tcl_ObjType exprCodeType = {
792 "exprcode",
793 FreeExprCodeInternalRep, /* freeIntRepProc */
794 DupExprCodeInternalRep, /* dupIntRepProc */
795 NULL, /* updateStringProc */
796 NULL /* setFromAnyProc */
797 };
798
799 /*
800 * Custom object type only used in this file; values of its type should never
801 * be seen by user scripts.
802 */
803
804 static const Tcl_ObjType dictIteratorType = {
805 "dictIterator",
806 ReleaseDictIterator,
807 NULL, NULL, NULL
808 };
809
810 /*
811 *----------------------------------------------------------------------
812 *
813 * ReleaseDictIterator --
814 *
815 * This takes apart a dictionary iterator that is stored in the given Tcl
816 * object.
817 *
818 * Results:
819 * None.
820 *
821 * Side effects:
822 * Deallocates memory, marks the object as being untyped.
823 *
824 *----------------------------------------------------------------------
825 */
826
827 static void
828 ReleaseDictIterator(
829 Tcl_Obj *objPtr)
830 {
831 Tcl_DictSearch *searchPtr;
832 Tcl_Obj *dictPtr;
833
834 /*
835 * First kill the search, and then release the reference to the dictionary
836 * that we were holding.
837 */
838
839 searchPtr = (Tcl_DictSearch *)objPtr->internalRep.twoPtrValue.ptr1;
840 Tcl_DictObjDone(searchPtr);
841 ckfree(searchPtr);
842
843 dictPtr = (Tcl_Obj *)objPtr->internalRep.twoPtrValue.ptr2;
844 TclDecrRefCount(dictPtr);
845
846 objPtr->typePtr = NULL;
847 }
848
849 /*
850 *----------------------------------------------------------------------
851 *
852 * InitByteCodeExecution --
853 *
854 * This procedure is called once to initialize the Tcl bytecode
855 * interpreter.
856 *
857 * Results:
858 * None.
859 *
860 * Side effects:
861 * This procedure initializes the array of instruction names. If
862 * compiling with the TCL_COMPILE_STATS flag, it initializes the array
863 * that counts the executions of each instruction and it creates the
864 * "evalstats" command. It also establishes the link between the Tcl
865 * "tcl_traceExec" and C "tclTraceExec" variables.
866 *
867 *----------------------------------------------------------------------
868 */
869
870 static void
871 InitByteCodeExecution(
872 Tcl_Interp *interp) /* Interpreter for which the Tcl variable
873 * "tcl_traceExec" is linked to control
874 * instruction tracing. */
875 {
876 #ifdef TCL_COMPILE_DEBUG
877 if (Tcl_LinkVar(interp, "tcl_traceExec", (char *) &tclTraceExec,
878 TCL_LINK_INT) != TCL_OK) {
879 Tcl_Panic("InitByteCodeExecution: can't create link for tcl_traceExec variable");
880 }
881 #endif
882 #ifdef TCL_COMPILE_STATS
883 Tcl_CreateObjCommand(interp, "evalstats", EvalStatsCmd, NULL, NULL);
884 #endif /* TCL_COMPILE_STATS */
885 }
886
887 /*
888 *----------------------------------------------------------------------
889 *
890 * TclCreateExecEnv --
891 *
892 * This procedure creates a new execution environment for Tcl bytecode
893 * execution. An ExecEnv points to a Tcl evaluation stack. An ExecEnv is
894 * typically created once for each Tcl interpreter (Interp structure) and
895 * recursively passed to TclNRExecuteByteCode to execute ByteCode sequences
896 * for nested commands.
897 *
898 * Results:
899 * A newly allocated ExecEnv is returned. This points to an empty
900 * evaluation stack of the standard initial size.
901 *
902 * Side effects:
903 * The bytecode interpreter is also initialized here, as this procedure
904 * will be called before any call to TclNRExecuteByteCode.
905 *
906 *----------------------------------------------------------------------
907 */
908
909 ExecEnv *
910 TclCreateExecEnv(
911 Tcl_Interp *interp, /* Interpreter for which the execution
912 * environment is being created. */
913 int size) /* The initial stack size, in number of words
914 * [sizeof(Tcl_Obj*)] */
915 {
916 ExecEnv *eePtr = (ExecEnv *)ckalloc(sizeof(ExecEnv));
917 ExecStack *esPtr = (ExecStack *)ckalloc(TclOffset(ExecStack, stackWords)
918 + size * sizeof(Tcl_Obj *));
919
920 eePtr->execStackPtr = esPtr;
921 TclNewBooleanObj(eePtr->constants[0], 0);
922 Tcl_IncrRefCount(eePtr->constants[0]);
923 TclNewBooleanObj(eePtr->constants[1], 1);
924 Tcl_IncrRefCount(eePtr->constants[1]);
925 eePtr->interp = interp;
926 eePtr->callbackPtr = NULL;
927 eePtr->corPtr = NULL;
928 eePtr->rewind = 0;
929
930 esPtr->prevPtr = NULL;
931 esPtr->nextPtr = NULL;
932 esPtr->markerPtr = NULL;
933 esPtr->endPtr = &esPtr->stackWords[size-1];
934 esPtr->tosPtr = STACK_BASE(esPtr);
935
936 Tcl_MutexLock(&execMutex);
937 if (!execInitialized) {
938 InitByteCodeExecution(interp);
939 execInitialized = 1;
940 }
941 Tcl_MutexUnlock(&execMutex);
942
943 return eePtr;
944 }
945
946 /*
947 *----------------------------------------------------------------------
948 *
949 * TclDeleteExecEnv --
950 *
951 * Frees the storage for an ExecEnv.
952 *
953 * Results:
954 * None.
955 *
956 * Side effects:
957 * Storage for an ExecEnv and its contained storage (e.g. the evaluation
958 * stack) is freed.
959 *
960 *----------------------------------------------------------------------
961 */
962
963 static void
964 DeleteExecStack(
965 ExecStack *esPtr)
966 {
967 if (esPtr->markerPtr && !cachedInExit) {
968 Tcl_Panic("freeing an execStack which is still in use");
969 }
970
971 if (esPtr->prevPtr) {
972 esPtr->prevPtr->nextPtr = esPtr->nextPtr;
973 }
974 if (esPtr->nextPtr) {
975 esPtr->nextPtr->prevPtr = esPtr->prevPtr;
976 }
977 ckfree(esPtr);
978 }
979
980 void
981 TclDeleteExecEnv(
982 ExecEnv *eePtr) /* Execution environment to free. */
983 {
984 ExecStack *esPtr = eePtr->execStackPtr, *tmpPtr;
985
986 cachedInExit = TclInExit();
987
988 /*
989 * Delete all stacks in this exec env.
990 */
991
992 while (esPtr->nextPtr) {
993 esPtr = esPtr->nextPtr;
994 }
995 while (esPtr) {
996 tmpPtr = esPtr;
997 esPtr = tmpPtr->prevPtr;
998 DeleteExecStack(tmpPtr);
999 }
1000
1001 TclDecrRefCount(eePtr->constants[0]);
1002 TclDecrRefCount(eePtr->constants[1]);
1003 if (eePtr->callbackPtr && !cachedInExit) {
1004 Tcl_Panic("Deleting execEnv with pending TEOV callbacks!");
1005 }
1006 if (eePtr->corPtr && !cachedInExit) {
1007 Tcl_Panic("Deleting execEnv with existing coroutine");
1008 }
1009 ckfree(eePtr);
1010 }
1011
1012 /*
1013 *----------------------------------------------------------------------
1014 *
1015 * TclFinalizeExecution --
1016 *
1017 * Finalizes the execution environment setup so that it can be later
1018 * reinitialized.
1019 *
1020 * Results:
1021 * None.
1022 *
1023 * Side effects:
1024 * After this call, the next time TclCreateExecEnv will be called it will
1025 * call InitByteCodeExecution.
1026 *
1027 *----------------------------------------------------------------------
1028 */
1029
1030 void
1031 TclFinalizeExecution(void)
1032 {
1033 Tcl_MutexLock(&execMutex);
1034 execInitialized = 0;
1035 Tcl_MutexUnlock(&execMutex);
1036 }
1037
1038 /*
1039 * Auxiliary code to insure that GrowEvaluationStack always returns correctly
1040 * aligned memory.
1041 *
1042 * WALLOCALIGN represents the alignment reqs in words, just as TCL_ALLOCALIGN
1043 * represents the reqs in bytes. This assumes that TCL_ALLOCALIGN is a
1044 * multiple of the wordsize 'sizeof(Tcl_Obj *)'.
1045 */
1046
1047 #define WALLOCALIGN \
1048 (TCL_ALLOCALIGN/sizeof(Tcl_Obj *))
1049
1050 /*
1051 * wordSkip computes how many words have to be skipped until the next aligned
1052 * word. Note that we are only interested in the low order bits of ptr, so
1053 * that any possible information loss in PTR2INT is of no consequence.
1054 */
1055
1056 static inline int
1057 wordSkip(
1058 void *ptr)
1059 {
1060 int mask = TCL_ALLOCALIGN-1;
1061 int base = PTR2INT(ptr) & mask;
1062 return (TCL_ALLOCALIGN - base)/sizeof(Tcl_Obj *);
1063 }
1064
1065 /*
1066 * Given a marker, compute where the following aligned memory starts.
1067 */
1068
1069 #define MEMSTART(markerPtr) \
1070 ((markerPtr) + wordSkip(markerPtr))
1071
1072 /*
1073 *----------------------------------------------------------------------
1074 *
1075 * GrowEvaluationStack --
1076 *
1077 * This procedure grows a Tcl evaluation stack stored in an ExecEnv,
1078 * copying over the words since the last mark if so requested. A mark is
1079 * set at the beginning of the new area when no copying is requested.
1080 *
1081 * Results:
1082 * Returns a pointer to the first usable word in the (possibly) grown
1083 * stack.
1084 *
1085 * Side effects:
1086 * The size of the evaluation stack may be grown, a marker is set
1087 *
1088 *----------------------------------------------------------------------
1089 */
1090
1091 static Tcl_Obj **
1092 GrowEvaluationStack(
1093 ExecEnv *eePtr, /* Points to the ExecEnv with an evaluation
1094 * stack to enlarge. */
1095 int growth, /* How much larger than the current used
1096 * size. */
1097 int move) /* 1 if move words since last marker. */
1098 {
1099 ExecStack *esPtr = eePtr->execStackPtr, *oldPtr = NULL;
1100 int newBytes, newElems, currElems;
1101 int needed = growth - (esPtr->endPtr - esPtr->tosPtr);
1102 Tcl_Obj **markerPtr = esPtr->markerPtr, **memStart;
1103 int moveWords = 0;
1104
1105 if (move) {
1106 if (!markerPtr) {
1107 Tcl_Panic("STACK: Reallocating with no previous alloc");
1108 }
1109 if (needed <= 0) {
1110 return MEMSTART(markerPtr);
1111 }
1112 } else {
1113 #ifndef PURIFY
1114 Tcl_Obj **tmpMarkerPtr = esPtr->tosPtr + 1;
1115 int offset = wordSkip(tmpMarkerPtr);
1116
1117 if (needed + offset < 0) {
1118 /*
1119 * Put a marker pointing to the previous marker in this stack, and
1120 * store it in esPtr as the current marker. Return a pointer to
1121 * the start of aligned memory.
1122 */
1123
1124 esPtr->markerPtr = tmpMarkerPtr;
1125 memStart = tmpMarkerPtr + offset;
1126 esPtr->tosPtr = memStart - 1;
1127 *esPtr->markerPtr = (Tcl_Obj *) markerPtr;
1128 return memStart;
1129 }
1130 #endif
1131 }
1132
1133 /*
1134 * Reset move to hold the number of words to be moved to new stack (if
1135 * any) and growth to hold the complete stack requirements: add one for
1136 * the marker, (WALLOCALIGN-1) for the maximal possible offset.
1137 */
1138
1139 if (move) {
1140 moveWords = esPtr->tosPtr - MEMSTART(markerPtr) + 1;
1141 }
1142 needed = growth + moveWords + WALLOCALIGN;
1143
1144
1145 /*
1146 * Check if there is enough room in the next stack (if there is one, it
1147 * should be both empty and the last one!)
1148 */
1149
1150 if (esPtr->nextPtr) {
1151 oldPtr = esPtr;
1152 esPtr = oldPtr->nextPtr;
1153 currElems = esPtr->endPtr - STACK_BASE(esPtr);
1154 if (esPtr->markerPtr || (esPtr->tosPtr != STACK_BASE(esPtr))) {
1155 Tcl_Panic("STACK: Stack after current is in use");
1156 }
1157 if (esPtr->nextPtr) {
1158 Tcl_Panic("STACK: Stack after current is not last");
1159 }
1160 if (needed <= currElems) {
1161 goto newStackReady;
1162 }
1163 DeleteExecStack(esPtr);
1164 esPtr = oldPtr;
1165 } else {
1166 currElems = esPtr->endPtr - STACK_BASE(esPtr);
1167 }
1168
1169 /*
1170 * We need to allocate a new stack! It needs to store 'growth' words,
1171 * including the elements to be copied over and the new marker.
1172 */
1173
1174 #ifndef PURIFY
1175 newElems = 2*currElems;
1176 while (needed > newElems) {
1177 newElems *= 2;
1178 }
1179 #else
1180 newElems = needed;
1181 #endif
1182
1183 newBytes = TclOffset(ExecStack, stackWords) + newElems * sizeof(Tcl_Obj *);
1184
1185 oldPtr = esPtr;
1186 esPtr = (ExecStack *)ckalloc(newBytes);
1187
1188 oldPtr->nextPtr = esPtr;
1189 esPtr->prevPtr = oldPtr;
1190 esPtr->nextPtr = NULL;
1191 esPtr->endPtr = &esPtr->stackWords[newElems-1];
1192
1193 newStackReady:
1194 eePtr->execStackPtr = esPtr;
1195
1196 /*
1197 * Store a NULL marker at the beginning of the stack, to indicate that
1198 * this is the first marker in this stack and that rewinding to here
1199 * should actually be a return to the previous stack.
1200 */
1201
1202 esPtr->stackWords[0] = NULL;
1203 esPtr->markerPtr = &esPtr->stackWords[0];
1204 memStart = MEMSTART(esPtr->markerPtr);
1205 esPtr->tosPtr = memStart - 1;
1206
1207 if (move) {
1208 memcpy(memStart, MEMSTART(markerPtr), moveWords*sizeof(Tcl_Obj *));
1209 esPtr->tosPtr += moveWords;
1210 oldPtr->markerPtr = (Tcl_Obj **) *markerPtr;
1211 oldPtr->tosPtr = markerPtr-1;
1212 }
1213
1214 /*
1215 * Free the old stack if it is now unused.
1216 */
1217
1218 if (!oldPtr->markerPtr) {
1219 DeleteExecStack(oldPtr);
1220 }
1221
1222 return memStart;
1223 }
1224
1225 /*
1226 *--------------------------------------------------------------
1227 *
1228 * TclStackAlloc, TclStackRealloc, TclStackFree --
1229 *
1230 * Allocate memory from the execution stack; it has to be returned later
1231 * with a call to TclStackFree.
1232 *
1233 * Results:
1234 * A pointer to the first byte allocated, or panics if the allocation did
1235 * not succeed.
1236 *
1237 * Side effects:
1238 * The execution stack may be grown.
1239 *
1240 *--------------------------------------------------------------
1241 */
1242
1243 static Tcl_Obj **
1244 StackAllocWords(
1245 Tcl_Interp *interp,
1246 int numWords)
1247 {
1248 /*
1249 * Note that GrowEvaluationStack sets a marker in the stack. This marker
1250 * is read when rewinding, e.g., by TclStackFree.
1251 */
1252
1253 Interp *iPtr = (Interp *) interp;
1254 ExecEnv *eePtr = iPtr->execEnvPtr;
1255 Tcl_Obj **resPtr = GrowEvaluationStack(eePtr, numWords, 0);
1256
1257 eePtr->execStackPtr->tosPtr += numWords;
1258 return resPtr;
1259 }
1260
1261 static Tcl_Obj **
1262 StackReallocWords(
1263 Tcl_Interp *interp,
1264 int numWords)
1265 {
1266 Interp *iPtr = (Interp *) interp;
1267 ExecEnv *eePtr = iPtr->execEnvPtr;
1268 Tcl_Obj **resPtr = GrowEvaluationStack(eePtr, numWords, 1);
1269
1270 eePtr->execStackPtr->tosPtr += numWords;
1271 return resPtr;
1272 }
1273
1274 void
1275 TclStackFree(
1276 Tcl_Interp *interp,
1277 void *freePtr)
1278 {
1279 Interp *iPtr = (Interp *) interp;
1280 ExecEnv *eePtr;
1281 ExecStack *esPtr;
1282 Tcl_Obj **markerPtr, *marker;
1283
1284 if (iPtr == NULL || iPtr->execEnvPtr == NULL) {
1285 ckfree((char *) freePtr);
1286 return;
1287 }
1288
1289 /*
1290 * Rewind the stack to the previous marker position. The current marker,
1291 * as set in the last call to GrowEvaluationStack, contains a pointer to
1292 * the previous marker.
1293 */
1294
1295 eePtr = iPtr->execEnvPtr;
1296 esPtr = eePtr->execStackPtr;
1297 markerPtr = esPtr->markerPtr;
1298 marker = *markerPtr;
1299
1300 if ((freePtr != NULL) && (MEMSTART(markerPtr) != (Tcl_Obj **)freePtr)) {
1301 Tcl_Panic("TclStackFree: incorrect freePtr (%p != %p). Call out of sequence?",
1302 freePtr, MEMSTART(markerPtr));
1303 }
1304
1305 esPtr->tosPtr = markerPtr - 1;
1306 esPtr->markerPtr = (Tcl_Obj **) marker;
1307 if (marker) {
1308 return;
1309 }
1310
1311 /*
1312 * Return to previous active stack. Note that repeated expansions or
1313 * reallocs could have generated several unused intervening stacks: free
1314 * them too.
1315 */
1316
1317 while (esPtr->nextPtr) {
1318 esPtr = esPtr->nextPtr;
1319 }
1320 esPtr->tosPtr = STACK_BASE(esPtr);
1321 while (esPtr->prevPtr) {
1322 ExecStack *tmpPtr = esPtr->prevPtr;
1323 if (tmpPtr->tosPtr == STACK_BASE(tmpPtr)) {
1324 DeleteExecStack(tmpPtr);
1325 } else {
1326 break;
1327 }
1328 }
1329 if (esPtr->prevPtr) {
1330 eePtr->execStackPtr = esPtr->prevPtr;
1331 #ifdef PURIFY
1332 eePtr->execStackPtr->nextPtr = NULL;
1333 DeleteExecStack(esPtr);
1334 #endif
1335 } else {
1336 eePtr->execStackPtr = esPtr;
1337 }
1338 }
1339
1340 void *
1341 TclStackAlloc(
1342 Tcl_Interp *interp,
1343 int numBytes)
1344 {
1345 Interp *iPtr = (Interp *) interp;
1346 int numWords;
1347
1348 if (iPtr == NULL || iPtr->execEnvPtr == NULL) {
1349 return (void *) ckalloc(numBytes);
1350 }
1351 numWords = (numBytes + (sizeof(Tcl_Obj *) - 1))/sizeof(Tcl_Obj *);
1352 return (void *) StackAllocWords(interp, numWords);
1353 }
1354
1355 void *
1356 TclStackRealloc(
1357 Tcl_Interp *interp,
1358 void *ptr,
1359 int numBytes)
1360 {
1361 Interp *iPtr = (Interp *) interp;
1362 ExecEnv *eePtr;
1363 ExecStack *esPtr;
1364 Tcl_Obj **markerPtr;
1365 int numWords;
1366
1367 if (iPtr == NULL || iPtr->execEnvPtr == NULL) {
1368 return (void *) ckrealloc((char *) ptr, numBytes);
1369 }
1370
1371 eePtr = iPtr->execEnvPtr;
1372 esPtr = eePtr->execStackPtr;
1373 markerPtr = esPtr->markerPtr;
1374
1375 if (MEMSTART(markerPtr) != (Tcl_Obj **)ptr) {
1376 Tcl_Panic("TclStackRealloc: incorrect ptr. Call out of sequence?");
1377 }
1378
1379 numWords = (numBytes + (sizeof(Tcl_Obj *) - 1))/sizeof(Tcl_Obj *);
1380 return (void *) StackReallocWords(interp, numWords);
1381 }
1382
1383 /*
1384 *--------------------------------------------------------------
1385 *
1386 * Tcl_ExprObj --
1387 *
1388 * Evaluate an expression in a Tcl_Obj.
1389 *
1390 * Results:
1391 * A standard Tcl object result. If the result is other than TCL_OK, then
1392 * the interpreter's result contains an error message. If the result is
1393 * TCL_OK, then a pointer to the expression's result value object is
1394 * stored in resultPtrPtr. In that case, the object's ref count is
1395 * incremented to reflect the reference returned to the caller; the
1396 * caller is then responsible for the resulting object and must, for
1397 * example, decrement the ref count when it is finished with the object.
1398 *
1399 * Side effects:
1400 * Any side effects caused by subcommands in the expression, if any. The
1401 * interpreter result is not modified unless there is an error.
1402 *
1403 *--------------------------------------------------------------
1404 */
1405
1406 int
1407 Tcl_ExprObj(
1408 Tcl_Interp *interp, /* Context in which to evaluate the
1409 * expression. */
1410 Tcl_Obj *objPtr, /* Points to Tcl object containing expression
1411 * to evaluate. */
1412 Tcl_Obj **resultPtrPtr) /* Where the Tcl_Obj* that is the expression
1413 * result is stored if no errors occur. */
1414 {
1415 NRE_callback *rootPtr = TOP_CB(interp);
1416 Tcl_Obj *resultPtr;
1417
1418 TclNewObj(resultPtr);
1419 TclNRAddCallback(interp, CopyCallback, resultPtrPtr, resultPtr,
1420 NULL, NULL);
1421 Tcl_NRExprObj(interp, objPtr, resultPtr);
1422 return TclNRRunCallbacks(interp, TCL_OK, rootPtr);
1423 }
1424
1425 static int
1426 CopyCallback(
1427 ClientData data[],
1428 Tcl_Interp *interp,
1429 int result)
1430 {
1431 Tcl_Obj **resultPtrPtr = (Tcl_Obj **)data[0];
1432 Tcl_Obj *resultPtr = (Tcl_Obj *)data[1];
1433
1434 if (result == TCL_OK) {
1435 *resultPtrPtr = resultPtr;
1436 Tcl_IncrRefCount(resultPtr);
1437 } else {
1438 Tcl_DecrRefCount(resultPtr);
1439 }
1440 return result;
1441 }
1442
1443 /*
1444 *--------------------------------------------------------------
1445 *
1446 * Tcl_NRExprObj --
1447 *
1448 * Request evaluation of the expression in a Tcl_Obj by the NR stack.
1449 *
1450 * Results:
1451 * Returns TCL_OK.
1452 *
1453 * Side effects:
1454 * Compiles objPtr as a Tcl expression and places callbacks on the
1455 * NR stack to execute the bytecode and store the result in resultPtr.
1456 * If bytecode execution raises an exception, nothing is written
1457 * to resultPtr, and the exceptional return code flows up the NR
1458 * stack. If the exception is TCL_ERROR, an error message is left
1459 * in the interp result and the interp's return options dictionary
1460 * holds additional error information too. Execution of the bytecode
1461 * may have other side effects, depending on the expression.
1462 *
1463 *--------------------------------------------------------------
1464 */
1465
1466 int
1467 Tcl_NRExprObj(
1468 Tcl_Interp *interp,
1469 Tcl_Obj *objPtr,
1470 Tcl_Obj *resultPtr)
1471 {
1472 ByteCode *codePtr;
1473 Tcl_InterpState state = Tcl_SaveInterpState(interp, TCL_OK);
1474
1475 Tcl_ResetResult(interp);
1476 codePtr = CompileExprObj(interp, objPtr);
1477
1478 Tcl_NRAddCallback(interp, ExprObjCallback, state, resultPtr,
1479 NULL, NULL);
1480 return TclNRExecuteByteCode(interp, codePtr);
1481 }
1482
1483 static int
1484 ExprObjCallback(
1485 ClientData data[],
1486 Tcl_Interp *interp,
1487 int result)
1488 {
1489 Tcl_InterpState state = (Tcl_InterpState)data[0];
1490 Tcl_Obj *resultPtr = (Tcl_Obj *)data[1];
1491
1492 if (result == TCL_OK) {
1493 TclSetDuplicateObj(resultPtr, Tcl_GetObjResult(interp));
1494 (void) Tcl_RestoreInterpState(interp, state);
1495 } else {
1496 Tcl_DiscardInterpState(state);
1497 }
1498 return result;
1499 }
1500
1501 /*
1502 *----------------------------------------------------------------------
1503 *
1504 * CompileExprObj --
1505 * Compile a Tcl expression value into ByteCode.
1506 *
1507 * Results:
1508 * A (ByteCode *) is returned pointing to the resulting ByteCode.
1509 * The caller must manage its refCount and arrange for a call to
1510 * TclCleanupByteCode() when the last reference disappears.
1511 *
1512 * Side effects:
1513 * The Tcl_ObjType of objPtr is changed to the "bytecode" type,
1514 * and the ByteCode is kept in the internal rep (along with context
1515 * data for checking validity) for faster operations the next time
1516 * CompileExprObj is called on the same value.
1517 *
1518 *----------------------------------------------------------------------
1519 */
1520
1521 static ByteCode *
1522 CompileExprObj(
1523 Tcl_Interp *interp,
1524 Tcl_Obj *objPtr)
1525 {
1526 Interp *iPtr = (Interp *) interp;
1527 CompileEnv compEnv; /* Compilation environment structure allocated
1528 * in frame. */
1529 ByteCode *codePtr = NULL;
1530 /* Tcl Internal type of bytecode. Initialized
1531 * to avoid compiler warning. */
1532
1533 /*
1534 * Get the expression ByteCode from the object. If it exists, make sure it
1535 * is valid in the current context.
1536 */
1537 if (objPtr->typePtr == &exprCodeType) {
1538 Namespace *namespacePtr = iPtr->varFramePtr->nsPtr;
1539
1540 codePtr = (ByteCode *)objPtr->internalRep.twoPtrValue.ptr1;
1541 if (((Interp *) *codePtr->interpHandle != iPtr)
1542 || (codePtr->compileEpoch != iPtr->compileEpoch)
1543 || (codePtr->nsPtr != namespacePtr)
1544 || (codePtr->nsEpoch != namespacePtr->resolverEpoch)
1545 || (codePtr->localCachePtr != iPtr->varFramePtr->localCachePtr)) {
1546 FreeExprCodeInternalRep(objPtr);
1547 }
1548 }
1549 if (objPtr->typePtr != &exprCodeType) {
1550 /*
1551 * TIP #280: No invoker (yet) - Expression compilation.
1552 */
1553
1554 int length;
1555 const char *string = TclGetStringFromObj(objPtr, &length);
1556
1557 TclInitCompileEnv(interp, &compEnv, string, length, NULL, 0);
1558 TclCompileExpr(interp, string, length, &compEnv, 0);
1559
1560 /*
1561 * Successful compilation. If the expression yielded no instructions,
1562 * push an zero object as the expression's result.
1563 */
1564
1565 if (compEnv.codeNext == compEnv.codeStart) {
1566 TclEmitPush(TclRegisterNewLiteral(&compEnv, "0", 1),
1567 &compEnv);
1568 }
1569
1570 /*
1571 * Add a "done" instruction as the last instruction and change the
1572 * object into a ByteCode object. Ownership of the literal objects and
1573 * aux data items is given to the ByteCode object.
1574 */
1575
1576 TclEmitOpcode(INST_DONE, &compEnv);
1577 TclInitByteCodeObj(objPtr, &compEnv);
1578 objPtr->typePtr = &exprCodeType;
1579 TclFreeCompileEnv(&compEnv);
1580 codePtr = (ByteCode *)objPtr->internalRep.twoPtrValue.ptr1;
1581 if (iPtr->varFramePtr->localCachePtr) {
1582 codePtr->localCachePtr = iPtr->varFramePtr->localCachePtr;
1583 codePtr->localCachePtr->refCount++;
1584 }
1585 TclDebugPrintByteCodeObj(objPtr);
1586 }
1587 return codePtr;
1588 }
1589
1590 /*
1591 *----------------------------------------------------------------------
1592 *
1593 * DupExprCodeInternalRep --
1594 *
1595 * Part of the Tcl object type implementation for Tcl expression
1596 * bytecode. We do not copy the bytecode internalrep. Instead, we return
1597 * without setting copyPtr->typePtr, so the copy is a plain string copy
1598 * of the expression value, and if it is to be used as a compiled
1599 * expression, it will just need a recompile.
1600 *
1601 * This makes sense, because with Tcl's copy-on-write practices, the
1602 * usual (only?) time Tcl_DuplicateObj() will be called is when the copy
1603 * is about to be modified, which would invalidate any copied bytecode
1604 * anyway. The only reason it might make sense to copy the bytecode is if
1605 * we had some modifying routines that operated directly on the internalrep,
1606 * like we do for lists and dicts.
1607 *
1608 * Results:
1609 * None.
1610 *
1611 * Side effects:
1612 * None.
1613 *
1614 *----------------------------------------------------------------------
1615 */
1616
1617 static void
1618 DupExprCodeInternalRep(
1619 Tcl_Obj *srcPtr,
1620 Tcl_Obj *copyPtr)
1621 {
1622 return;
1623 }
1624
1625 /*
1626 *----------------------------------------------------------------------
1627 *
1628 * FreeExprCodeInternalRep --
1629 *
1630 * Part of the Tcl object type implementation for Tcl expression
1631 * bytecode. Frees the storage allocated to hold the internal rep, unless
1632 * ref counts indicate bytecode execution is still in progress.
1633 *
1634 * Results:
1635 * None.
1636 *
1637 * Side effects:
1638 * May free allocated memory. Leaves objPtr untyped.
1639 *
1640 *----------------------------------------------------------------------
1641 */
1642
1643 static void
1644 FreeExprCodeInternalRep(
1645 Tcl_Obj *objPtr)
1646 {
1647 ByteCode *codePtr = (ByteCode *)objPtr->internalRep.twoPtrValue.ptr1;
1648
1649 objPtr->typePtr = NULL;
1650 if (codePtr->refCount-- <= 1) {
1651 TclCleanupByteCode(codePtr);
1652 }
1653 }
1654
1655 /*
1656 *----------------------------------------------------------------------
1657 *
1658 * TclCompileObj --
1659 *
1660 * This procedure compiles the script contained in a Tcl_Obj.
1661 *
1662 * Results:
1663 * A pointer to the corresponding ByteCode, never NULL.
1664 *
1665 * Side effects:
1666 * The object is shimmered to bytecode type.
1667 *
1668 *----------------------------------------------------------------------
1669 */
1670
1671 ByteCode *
1672 TclCompileObj(
1673 Tcl_Interp *interp,
1674 Tcl_Obj *objPtr,
1675 const CmdFrame *invoker,
1676 int word)
1677 {
1678 Interp *iPtr = (Interp *) interp;
1679 ByteCode *codePtr; /* Tcl Internal type of bytecode. */
1680 Namespace *namespacePtr = iPtr->varFramePtr->nsPtr;
1681
1682 /*
1683 * If the object is not already of tclByteCodeType, compile it (and reset
1684 * the compilation flags in the interpreter; this should be done after any
1685 * compilation). Otherwise, check that it is "fresh" enough.
1686 */
1687
1688 if (objPtr->typePtr == &tclByteCodeType) {
1689 /*
1690 * Make sure the Bytecode hasn't been invalidated by, e.g., someone
1691 * redefining a command with a compile procedure (this might make the
1692 * compiled code wrong). The object needs to be recompiled if it was
1693 * compiled in/for a different interpreter, or for a different
1694 * namespace, or for the same namespace but with different name
1695 * resolution rules. Precompiled objects, however, are immutable and
1696 * therefore they are not recompiled, even if the epoch has changed.
1697 *
1698 * To be pedantically correct, we should also check that the
1699 * originating procPtr is the same as the current context procPtr
1700 * (assuming one exists at all - none for global level). This code is
1701 * #def'ed out because [info body] was changed to never return a
1702 * bytecode type object, which should obviate us from the extra checks
1703 * here.
1704 */
1705
1706 codePtr = objPtr->internalRep.twoPtrValue.ptr1;
1707 if (((Interp *) *codePtr->interpHandle != iPtr)
1708 || (codePtr->compileEpoch != iPtr->compileEpoch)
1709 || (codePtr->nsPtr != namespacePtr)
1710 || (codePtr->nsEpoch != namespacePtr->resolverEpoch)) {
1711 if (!(codePtr->flags & TCL_BYTECODE_PRECOMPILED)) {
1712 goto recompileObj;
1713 }
1714 if ((Interp *) *codePtr->interpHandle != iPtr) {
1715 Tcl_Panic("Tcl_EvalObj: compiled script jumped interps");
1716 }
1717 codePtr->compileEpoch = iPtr->compileEpoch;
1718 }
1719
1720 /*
1721 * Check that any compiled locals do refer to the current proc
1722 * environment! If not, recompile.
1723 */
1724
1725 if (!(codePtr->flags & TCL_BYTECODE_PRECOMPILED) &&
1726 (codePtr->procPtr == NULL) &&
1727 (codePtr->localCachePtr != iPtr->varFramePtr->localCachePtr)){
1728 goto recompileObj;
1729 }
1730
1731 /*
1732 * #280.
1733 * Literal sharing fix. This part of the fix is not required by 8.4
1734 * nor 8.5, because they eval-direct any literals, so just saving the
1735 * argument locations per command in bytecode is enough, embedded
1736 * 'eval' commands, etc. get the correct information.
1737 *
1738 * But in 8.6 all the embedded script are compiled, and the resulting
1739 * bytecode stored in the literal. Now the shared literal has bytecode
1740 * with location data for _one_ particular location this literal is
1741 * found at. If we get executed from a different location the bytecode
1742 * has to be recompiled to get the correct locations. Not doing this
1743 * will execute the saved bytecode with data for a different location,
1744 * causing 'info frame' to point to the wrong place in the sources.
1745 *
1746 * Future optimizations ...
1747 * (1) Save the location data (ExtCmdLoc) keyed by start line. In that
1748 * case we recompile once per location of the literal, but not
1749 * continuously, because the moment we have all locations we do not
1750 * need to recompile any longer.
1751 *
1752 * (2) Alternative: Do not recompile, tell the execution engine the
1753 * offset between saved starting line and actual one. Then modify
1754 * the users to adjust the locations they have by this offset.
1755 *
1756 * (3) Alternative 2: Do not fully recompile, adjust just the location
1757 * information.
1758 */
1759
1760 if (invoker == NULL) {
1761 return codePtr;
1762 } else {
1763 Tcl_HashEntry *hePtr =
1764 Tcl_FindHashEntry(iPtr->lineBCPtr, codePtr);
1765 ExtCmdLoc *eclPtr;
1766 CmdFrame *ctxCopyPtr;
1767 int redo;
1768
1769 if (!hePtr) {
1770 return codePtr;
1771 }
1772
1773 eclPtr = Tcl_GetHashValue(hePtr);
1774 redo = 0;
1775 ctxCopyPtr = TclStackAlloc(interp, sizeof(CmdFrame));
1776 *ctxCopyPtr = *invoker;
1777
1778 if (invoker->type == TCL_LOCATION_BC) {
1779 /*
1780 * Note: Type BC => ctx.data.eval.path is not used.
1781 * ctx.data.tebc.codePtr used instead
1782 */
1783
1784 TclGetSrcInfoForPc(ctxCopyPtr);
1785 if (ctxCopyPtr->type == TCL_LOCATION_SOURCE) {
1786 /*
1787 * The reference made by 'TclGetSrcInfoForPc' is dead.
1788 */
1789
1790 Tcl_DecrRefCount(ctxCopyPtr->data.eval.path);
1791 ctxCopyPtr->data.eval.path = NULL;
1792 }
1793 }
1794
1795 if (word < ctxCopyPtr->nline) {
1796 /*
1797 * Note: We do not care if the line[word] is -1. This is a
1798 * difference and requires a recompile (location changed from
1799 * absolute to relative, literal is used fixed and through
1800 * variable)
1801 *
1802 * Example:
1803 * test info-32.0 using literal of info-24.8
1804 * (dict with ... vs set body ...).
1805 */
1806
1807 redo = ((eclPtr->type == TCL_LOCATION_SOURCE)
1808 && (eclPtr->start != ctxCopyPtr->line[word]))
1809 || ((eclPtr->type == TCL_LOCATION_BC)
1810 && (ctxCopyPtr->type == TCL_LOCATION_SOURCE));
1811 }
1812
1813 TclStackFree(interp, ctxCopyPtr);
1814 if (!redo) {
1815 return codePtr;
1816 }
1817 }
1818 }
1819
1820 recompileObj:
1821 iPtr->errorLine = 1;
1822
1823 /*
1824 * TIP #280. Remember the invoker for a moment in the interpreter
1825 * structures so that the byte code compiler can pick it up when
1826 * initializing the compilation environment, i.e. the extended location
1827 * information.
1828 */
1829
1830 iPtr->invokeCmdFramePtr = invoker;
1831 iPtr->invokeWord = word;
1832 TclSetByteCodeFromAny(interp, objPtr, NULL, NULL);
1833 iPtr->invokeCmdFramePtr = NULL;
1834 codePtr = objPtr->internalRep.twoPtrValue.ptr1;
1835 if (iPtr->varFramePtr->localCachePtr) {
1836 codePtr->localCachePtr = iPtr->varFramePtr->localCachePtr;
1837 codePtr->localCachePtr->refCount++;
1838 }
1839 return codePtr;
1840 }
1841
1842 /*
1843 *----------------------------------------------------------------------
1844 *
1845 * TclIncrObj --
1846 *
1847 * Increment an integral value in a Tcl_Obj by an integral value held
1848 * in another Tcl_Obj. Caller is responsible for making sure we can
1849 * update the first object.
1850 *
1851 * Results:
1852 * TCL_ERROR if either object is non-integer, and TCL_OK otherwise. On
1853 * error, an error message is left in the interpreter (if it is not NULL,
1854 * of course).
1855 *
1856 * Side effects:
1857 * valuePtr gets the new incremented value.
1858 *
1859 *----------------------------------------------------------------------
1860 */
1861
1862 int
1863 TclIncrObj(
1864 Tcl_Interp *interp,
1865 Tcl_Obj *valuePtr,
1866 Tcl_Obj *incrPtr)
1867 {
1868 ClientData ptr1, ptr2;
1869 int type1, type2;
1870 mp_int value, incr;
1871
1872 if (Tcl_IsShared(valuePtr)) {
1873 Tcl_Panic("%s called with shared object", "TclIncrObj");
1874 }
1875
1876 if (GetNumberFromObj(NULL, valuePtr, &ptr1, &type1) != TCL_OK) {
1877 /*
1878 * Produce error message (reparse?!)
1879 */
1880
1881 return TclGetIntFromObj(interp, valuePtr, &type1);
1882 }
1883 if (GetNumberFromObj(NULL, incrPtr, &ptr2, &type2) != TCL_OK) {
1884 /*
1885 * Produce error message (reparse?!)
1886 */
1887
1888 TclGetIntFromObj(interp, incrPtr, &type1);
1889 Tcl_AddErrorInfo(interp, "\n (reading increment)");
1890 return TCL_ERROR;
1891 }
1892
1893 if ((type1 == TCL_NUMBER_LONG) && (type2 == TCL_NUMBER_LONG)) {
1894 long augend = *((const long *) ptr1);
1895 long addend = *((const long *) ptr2);
1896 long sum = (long)((unsigned long)augend + (unsigned long)addend);
1897
1898 /*
1899 * Overflow when (augend and sum have different sign) and (augend and
1900 * addend have the same sign). This is encapsulated in the Overflowing
1901 * macro.
1902 */
1903
1904 if (!Overflowing(augend, addend, sum)) {
1905 TclSetLongObj(valuePtr, sum);
1906 return TCL_OK;
1907 }
1908 #ifndef TCL_WIDE_INT_IS_LONG
1909 {
1910 Tcl_WideInt w1 = (Tcl_WideInt)augend;
1911 Tcl_WideInt w2 = (Tcl_WideInt)addend;
1912
1913 /*
1914 * We know the sum value is outside the long range, so we use the
1915 * macro form that doesn't range test again.
1916 */
1917
1918 TclSetWideIntObj(valuePtr, w1 + w2);
1919 return TCL_OK;
1920 }
1921 #endif
1922 }
1923
1924 if ((type1 == TCL_NUMBER_DOUBLE) || (type1 == TCL_NUMBER_NAN)) {
1925 /*
1926 * Produce error message (reparse?!)
1927 */
1928
1929 return TclGetIntFromObj(interp, valuePtr, &type1);
1930 }
1931 if ((type2 == TCL_NUMBER_DOUBLE) || (type2 == TCL_NUMBER_NAN)) {
1932 /*
1933 * Produce error message (reparse?!)
1934 */
1935
1936 TclGetIntFromObj(interp, incrPtr, &type1);
1937 Tcl_AddErrorInfo(interp, "\n (reading increment)");
1938 return TCL_ERROR;
1939 }
1940
1941 #ifndef TCL_WIDE_INT_IS_LONG
1942 if ((type1 != TCL_NUMBER_BIG) && (type2 != TCL_NUMBER_BIG)) {
1943 Tcl_WideInt w1, w2, sum;
1944
1945 TclGetWideIntFromObj(NULL, valuePtr, &w1);
1946 TclGetWideIntFromObj(NULL, incrPtr, &w2);
1947 sum = (Tcl_WideInt)((Tcl_WideUInt)w1 + (Tcl_WideUInt)w2);
1948
1949 /*
1950 * Check for overflow.
1951 */
1952
1953 if (!Overflowing(w1, w2, sum)) {
1954 Tcl_SetWideIntObj(valuePtr, sum);
1955 return TCL_OK;
1956 }
1957 }
1958 #endif
1959
1960 Tcl_TakeBignumFromObj(interp, valuePtr, &value);
1961 Tcl_GetBignumFromObj(interp, incrPtr, &incr);
1962 mp_add(&value, &incr, &value);
1963 mp_clear(&incr);
1964 Tcl_SetBignumObj(valuePtr, &value);
1965 return TCL_OK;
1966 }
1967
1968 /*
1969 *----------------------------------------------------------------------
1970 *
1971 * ArgumentBCEnter --
1972 *
1973 * This is a helper for TclNRExecuteByteCode/TEBCresume that encapsulates
1974 * a code sequence that is fairly common in the code but *not* commonly
1975 * called.
1976 *
1977 * Results:
1978 * None
1979 *
1980 * Side effects:
1981 * May register information about the bytecode in the command frame.
1982 *
1983 *----------------------------------------------------------------------
1984 */
1985
1986 static void
1987 ArgumentBCEnter(
1988 Tcl_Interp *interp,
1989 ByteCode *codePtr,
1990 TEBCdata *tdPtr,
1991 const unsigned char *pc,
1992 int objc,
1993 Tcl_Obj **objv)
1994 {
1995 int cmd;
1996
1997 if (GetSrcInfoForPc(pc, codePtr, NULL, NULL, &cmd)) {
1998 TclArgumentBCEnter(interp, objv, objc, codePtr, &tdPtr->cmdFrame, cmd,
1999 pc - codePtr->codeStart);
2000 }
2001 }
2002
2003 /*
2004 *----------------------------------------------------------------------
2005 *
2006 * TclNRExecuteByteCode --
2007 *
2008 * This procedure executes the instructions of a ByteCode structure. It
2009 * returns when a "done" instruction is executed or an error occurs.
2010 *
2011 * Results:
2012 * The return value is one of the return codes defined in tcl.h (such as
2013 * TCL_OK), and interp->objResultPtr refers to a Tcl object that either
2014 * contains the result of executing the code or an error message.
2015 *
2016 * Side effects:
2017 * Almost certainly, depending on the ByteCode's instructions.
2018 *
2019 *----------------------------------------------------------------------
2020 */
2021 #define bcFramePtr (&TD->cmdFrame)
2022 #define initCatchTop ((ptrdiff_t *) (TD->stack-1))
2023 #define initTosPtr ((Tcl_Obj **) (initCatchTop+codePtr->maxExceptDepth))
2024 #define esPtr (iPtr->execEnvPtr->execStackPtr)
2025
2026 int
2027 TclNRExecuteByteCode(
2028 Tcl_Interp *interp, /* Token for command interpreter. */
2029 ByteCode *codePtr) /* The bytecode sequence to interpret. */
2030 {
2031 Interp *iPtr = (Interp *) interp;
2032 TEBCdata *TD;
2033 int size = sizeof(TEBCdata) - 1
2034 + (codePtr->maxStackDepth + codePtr->maxExceptDepth)
2035 * sizeof(void *);
2036 int numWords = (size + sizeof(Tcl_Obj *) - 1) / sizeof(Tcl_Obj *);
2037
2038 codePtr->refCount++;
2039
2040 /*
2041 * Reserve the stack, setup the TEBCdataPtr (TD) and CallFrame
2042 *
2043 * The execution uses a unified stack: first a TEBCdata, immediately
2044 * above it a CmdFrame, then the catch stack, then the execution stack.
2045 *
2046 * Make sure the catch stack is large enough to hold the maximum number of
2047 * catch commands that could ever be executing at the same time (this will
2048 * be no more than the exception range array's depth). Make sure the
2049 * execution stack is large enough to execute this ByteCode.
2050 */
2051
2052 TD = (TEBCdata *) GrowEvaluationStack(iPtr->execEnvPtr, numWords, 0);
2053 esPtr->tosPtr = initTosPtr;
2054
2055 TD->codePtr = codePtr;
2056 TD->catchTop = initCatchTop;
2057 TD->auxObjList = NULL;
2058
2059 /*
2060 * TIP #280: Initialize the frame. Do not push it yet: it will be pushed
2061 * every time that we call out from this TD, popped when we return to it.
2062 */
2063
2064 bcFramePtr->type = ((codePtr->flags & TCL_BYTECODE_PRECOMPILED)
2065 ? TCL_LOCATION_PREBC : TCL_LOCATION_BC);
2066 bcFramePtr->level = (iPtr->cmdFramePtr ? iPtr->cmdFramePtr->level+1 : 1);
2067 bcFramePtr->framePtr = iPtr->framePtr;
2068 bcFramePtr->nextPtr = iPtr->cmdFramePtr;
2069 bcFramePtr->nline = 0;
2070 bcFramePtr->line = NULL;
2071 bcFramePtr->litarg = NULL;
2072 bcFramePtr->data.tebc.codePtr = codePtr;
2073 bcFramePtr->data.tebc.pc = NULL;
2074 bcFramePtr->cmdObj = NULL;
2075 bcFramePtr->cmd = NULL;
2076 bcFramePtr->len = 0;
2077
2078 #ifdef TCL_COMPILE_STATS
2079 iPtr->stats.numExecutions++;
2080 #endif
2081
2082 /*
2083 * Test namespace-50.9 demonstrates the need for this call.
2084 * Use a --enable-symbols=mem bug to see.
2085 */
2086
2087 TclResetRewriteEnsemble(interp, 1);
2088
2089 /*
2090 * Push the callback for bytecode execution
2091 */
2092
2093 TclNRAddCallback(interp, TEBCresume, TD, /* pc */ NULL,
2094 /* cleanup */ INT2PTR(0), INT2PTR(iPtr->evalFlags));
2095
2096 /*
2097 * Reset discard result flag - because it is applicable for this call only,
2098 * and should not affect all the nested invocations may return result.
2099 */
2100 iPtr->evalFlags &= ~TCL_EVAL_DISCARD_RESULT;
2101
2102 return TCL_OK;
2103 }
2104
2105 static int
2106 TEBCresume(
2107 ClientData data[],
2108 Tcl_Interp *interp,
2109 int result)
2110 {
2111 /*
2112 * Compiler cast directive - not a real variable.
2113 * Interp *iPtr = (Interp *) interp;
2114 */
2115 #define iPtr ((Interp *) interp)
2116
2117 /*
2118 * Check just the read-traced/write-traced bit of a variable.
2119 */
2120
2121 #define ReadTraced(varPtr) ((varPtr)->flags & VAR_TRACED_READ)
2122 #define WriteTraced(varPtr) ((varPtr)->flags & VAR_TRACED_WRITE)
2123 #define UnsetTraced(varPtr) ((varPtr)->flags & VAR_TRACED_UNSET)
2124
2125 /*
2126 * Bottom of allocated stack holds the NR data
2127 */
2128
2129 /*
2130 * Constants: variables that do not change during the execution, used
2131 * sporadically: no special need for speed.
2132 */
2133
2134 int instructionCount = 0; /* Counter that is used to work out when to
2135 * call Tcl_AsyncReady() */
2136 const char *curInstName;
2137 #ifdef TCL_COMPILE_DEBUG
2138 int traceInstructions; /* Whether we are doing instruction-level
2139 * tracing or not. */
2140 #endif
2141
2142 Var *compiledLocals = iPtr->varFramePtr->compiledLocals;
2143 Tcl_Obj **constants = &iPtr->execEnvPtr->constants[0];
2144
2145 #define LOCAL(i) (&compiledLocals[(i)])
2146 #define TCONST(i) (constants[(i)])
2147
2148 /*
2149 * These macros are just meant to save some global variables that are not
2150 * used too frequently
2151 */
2152
2153 TEBCdata *TD = data[0];
2154 #define auxObjList (TD->auxObjList)
2155 #define catchTop (TD->catchTop)
2156 #define codePtr (TD->codePtr)
2157 #define curEvalFlags PTR2INT(data[3]) /* calling iPtr->evalFlags */
2158
2159 /*
2160 * Globals: variables that store state, must remain valid at all times.
2161 */
2162
2163 Tcl_Obj **tosPtr; /* Cached pointer to top of evaluation
2164 * stack. */
2165 const unsigned char *pc = data[1];
2166 /* The current program counter. */
2167 unsigned char inst; /* The currently running instruction */
2168
2169 /*
2170 * Transfer variables - needed only between opcodes, but not while
2171 * executing an instruction.
2172 */
2173
2174 int cleanup = PTR2INT(data[2]);
2175 Tcl_Obj *objResultPtr;
2176 int checkInterp = 0; /* Indicates when a check of interp readyness
2177 * is necessary. Set by CACHE_STACK_INFO() */
2178
2179 /*
2180 * Locals - variables that are used within opcodes or bounded sections of
2181 * the file (jumps between opcodes within a family).
2182 * NOTE: These are now mostly defined locally where needed.
2183 */
2184
2185 Tcl_Obj *objPtr, *valuePtr, *value2Ptr, *part1Ptr, *part2Ptr, *tmpPtr;
2186 Tcl_Obj **objv = NULL;
2187 int objc = 0;
2188 int opnd, length, pcAdjustment;
2189 Var *varPtr, *arrayPtr;
2190 #ifdef TCL_COMPILE_DEBUG
2191 char cmdNameBuf[21];
2192 #endif
2193
2194 #ifdef TCL_COMPILE_DEBUG
2195 int starting = 1;
2196 traceInstructions = (tclTraceExec == 3);
2197 #endif
2198
2199 TEBC_DATA_DIG();
2200
2201 #ifdef TCL_COMPILE_DEBUG
2202 if (!pc && (tclTraceExec >= 2)) {
2203 PrintByteCodeInfo(codePtr);
2204 fprintf(stdout, " Starting stack top=%d\n", (int) CURR_DEPTH);
2205 fflush(stdout);
2206 }
2207 #endif
2208
2209 if (!pc) {
2210 /* bytecode is starting from scratch */
2211 pc = codePtr->codeStart;
2212
2213 /*
2214 * Reset the interp's result to avoid possible duplications of large
2215 * objects [3c6e47363e], [781585], [804681], This can happen by start
2216 * also in nested compiled blocks (enclosed in parent cycle).
2217 * See else branch below for opposite handling by continuation/resume.
2218 */
2219
2220 objPtr = iPtr->objResultPtr;
2221 if (objPtr->refCount > 1) {
2222 TclDecrRefCount(objPtr);
2223 TclNewObj(objPtr);
2224 Tcl_IncrRefCount(objPtr);
2225 iPtr->objResultPtr = objPtr;
2226 }
2227
2228 goto cleanup0;
2229 } else {
2230 /* resume from invocation */
2231 CACHE_STACK_INFO();
2232
2233 NRE_ASSERT(iPtr->cmdFramePtr == bcFramePtr);
2234 if (bcFramePtr->cmdObj) {
2235 Tcl_DecrRefCount(bcFramePtr->cmdObj);
2236 bcFramePtr->cmdObj = NULL;
2237 bcFramePtr->cmd = NULL;
2238 }
2239 iPtr->cmdFramePtr = bcFramePtr->nextPtr;
2240 if (iPtr->flags & INTERP_DEBUG_FRAME) {
2241 TclArgumentBCRelease(interp, bcFramePtr);
2242 }
2243 if (iPtr->execEnvPtr->rewind) {
2244 result = TCL_ERROR;
2245 goto abnormalReturn;
2246 }
2247 if (codePtr->flags & TCL_BYTECODE_RECOMPILE) {
2248 codePtr->flags &= ~TCL_BYTECODE_RECOMPILE;
2249 checkInterp = 1;
2250 iPtr->flags |= ERR_ALREADY_LOGGED;
2251 }
2252
2253 if (result != TCL_OK) {
2254 pc--;
2255 goto processExceptionReturn;
2256 }
2257
2258 /*
2259 * Push the call's object result and continue execution with the next
2260 * instruction.
2261 */
2262
2263 TRACE_WITH_OBJ(("%u => ... after \"%.20s\": TCL_OK, result=",
2264 objc, cmdNameBuf), Tcl_GetObjResult(interp));
2265
2266 /*
2267 * Obtain and reset interp's result to avoid possible duplications of
2268 * objects [Bug 781585]. We do not call Tcl_ResetResult to avoid any
2269 * side effects caused by the resetting of errorInfo and errorCode
2270 * [Bug 804681], which are not needed here. We chose instead to
2271 * manipulate the interp's object result directly.
2272 *
2273 * Note that the result object is now in objResultPtr, it keeps the
2274 * refCount it had in its role of iPtr->objResultPtr.
2275 */
2276
2277 objResultPtr = Tcl_GetObjResult(interp);
2278 TclNewObj(objPtr);
2279 Tcl_IncrRefCount(objPtr);
2280 iPtr->objResultPtr = objPtr;
2281 #ifndef TCL_COMPILE_DEBUG
2282 if (*pc == INST_POP) {
2283 TclDecrRefCount(objResultPtr);
2284 NEXT_INST_V(1, cleanup, 0);
2285 }
2286 #endif
2287 NEXT_INST_V(0, cleanup, -1);
2288 }
2289
2290 /*
2291 * Targets for standard instruction endings; unrolled for speed in the
2292 * most frequent cases (instructions that consume up to two stack
2293 * elements).
2294 *
2295 * This used to be a "for(;;)" loop, with each instruction doing its own
2296 * cleanup.
2297 */
2298
2299 cleanupV_pushObjResultPtr:
2300 switch (cleanup) {
2301 case 0:
2302 *(++tosPtr) = (objResultPtr);
2303 goto cleanup0;
2304 default:
2305 cleanup -= 2;
2306 while (cleanup--) {
2307 objPtr = POP_OBJECT();
2308 TclDecrRefCount(objPtr);
2309 }
2310 /* FALLTHRU */
2311 case 2:
2312 cleanup2_pushObjResultPtr:
2313 objPtr = POP_OBJECT();
2314 TclDecrRefCount(objPtr);
2315 /* FALLTHRU */
2316 case 1:
2317 cleanup1_pushObjResultPtr:
2318 objPtr = OBJ_AT_TOS;
2319 TclDecrRefCount(objPtr);
2320 }
2321 OBJ_AT_TOS = objResultPtr;
2322 goto cleanup0;
2323
2324 cleanupV:
2325 switch (cleanup) {
2326 default:
2327 cleanup -= 2;
2328 while (cleanup--) {
2329 objPtr = POP_OBJECT();
2330 TclDecrRefCount(objPtr);
2331 }
2332 /* FALLTHRU */
2333 case 2:
2334 cleanup2:
2335 objPtr = POP_OBJECT();
2336 TclDecrRefCount(objPtr);
2337 /* FALLTHRU */
2338 case 1:
2339 cleanup1:
2340 objPtr = POP_OBJECT();
2341 TclDecrRefCount(objPtr);
2342 /* FALLTHRU */
2343 case 0:
2344 /*
2345 * We really want to do nothing now, but this is needed for some
2346 * compilers (SunPro CC).
2347 */
2348
2349 break;
2350 }
2351 cleanup0:
2352
2353 /*
2354 * Check for asynchronous handlers [Bug 746722]; we do the check every
2355 * ASYNC_CHECK_COUNT_MASK instruction, of the form (2**n-1).
2356 */
2357
2358 if ((instructionCount++ & ASYNC_CHECK_COUNT_MASK) == 0) {
2359 DECACHE_STACK_INFO();
2360 if (TclAsyncReady(iPtr)) {
2361 result = Tcl_AsyncInvoke(interp, result);
2362 if (result == TCL_ERROR) {
2363 CACHE_STACK_INFO();
2364 goto gotError;
2365 }
2366 }
2367
2368 if (TclCanceled(iPtr)) {
2369 if (Tcl_Canceled(interp, TCL_LEAVE_ERR_MSG) == TCL_ERROR) {
2370 CACHE_STACK_INFO();
2371 goto gotError;
2372 }
2373 }
2374
2375 if (TclLimitReady(iPtr->limit)) {
2376 if (Tcl_LimitCheck(interp) == TCL_ERROR) {
2377 CACHE_STACK_INFO();
2378 goto gotError;
2379 }
2380 }
2381 CACHE_STACK_INFO();
2382 }
2383
2384 /*
2385 * These two instructions account for 26% of all instructions (according
2386 * to measurements on tclbench by Ben Vitale
2387 * [http://www.cs.toronto.edu/syslab/pubs/tcl2005-vitale-zaleski.pdf]
2388 * Resolving them before the switch reduces the cost of branch
2389 * mispredictions, seems to improve runtime by 5% to 15%, and (amazingly!)
2390 * reduces total obj size.
2391 */
2392
2393 inst = *pc;
2394
2395 peepholeStart:
2396 #ifdef TCL_COMPILE_STATS
2397 iPtr->stats.instructionCount[*pc]++;
2398 #endif
2399
2400 #ifdef TCL_COMPILE_DEBUG
2401 /*
2402 * Skip the stack depth check if an expansion is in progress.
2403 */
2404
2405 CHECK_STACK();
2406 if (traceInstructions) {
2407 fprintf(stdout, "%2d: %2d ", iPtr->numLevels, (int) CURR_DEPTH);
2408 TclPrintInstruction(codePtr, pc);
2409 fflush(stdout);
2410 }
2411 #endif /* TCL_COMPILE_DEBUG */
2412
2413 TCL_DTRACE_INST_NEXT();
2414
2415 if (inst == INST_LOAD_SCALAR1) {
2416 goto instLoadScalar1;
2417 } else if (inst == INST_PUSH1) {
2418 PUSH_OBJECT(codePtr->objArrayPtr[TclGetUInt1AtPtr(pc+1)]);
2419 TRACE_WITH_OBJ(("%u => ", TclGetUInt1AtPtr(pc+1)), OBJ_AT_TOS);
2420 inst = *(pc += 2);
2421 goto peepholeStart;
2422 } else if (inst == INST_START_CMD) {
2423 /*
2424 * Peephole: do not run INST_START_CMD, just skip it
2425 */
2426
2427 iPtr->cmdCount += TclGetUInt4AtPtr(pc+5);
2428 if (checkInterp) {
2429 if (((codePtr->compileEpoch != iPtr->compileEpoch) ||
2430 (codePtr->nsEpoch != iPtr->varFramePtr->nsPtr->resolverEpoch)) &&
2431 !(codePtr->flags & TCL_BYTECODE_PRECOMPILED)) {
2432 goto instStartCmdFailed;
2433 }
2434 checkInterp = 0;
2435 }
2436 inst = *(pc += 9);
2437 goto peepholeStart;
2438 } else if (inst == INST_NOP) {
2439 #ifndef TCL_COMPILE_DEBUG
2440 while (inst == INST_NOP)
2441 #endif
2442 {
2443 inst = *++pc;
2444 }
2445 goto peepholeStart;
2446 }
2447
2448 switch (inst) {
2449 case INST_SYNTAX:
2450 case INST_RETURN_IMM: {
2451 int code = TclGetInt4AtPtr(pc+1);
2452 int level = TclGetUInt4AtPtr(pc+5);
2453
2454 /*
2455 * OBJ_AT_TOS is returnOpts, OBJ_UNDER_TOS is resultObjPtr.
2456 */
2457
2458 TRACE(("%u %u => ", code, level));
2459 result = TclProcessReturn(interp, code, level, OBJ_AT_TOS);
2460 if (result == TCL_OK) {
2461 TRACE_APPEND(("continuing to next instruction (result=\"%.30s\")\n",
2462 O2S(objResultPtr)));
2463 NEXT_INST_F(9, 1, 0);
2464 }
2465 Tcl_SetObjResult(interp, OBJ_UNDER_TOS);
2466 if (*pc == INST_SYNTAX) {
2467 iPtr->flags &= ~ERR_ALREADY_LOGGED;
2468 }
2469 cleanup = 2;
2470 TRACE_APPEND(("\n"));
2471 goto processExceptionReturn;
2472 }
2473
2474 case INST_RETURN_STK:
2475 TRACE(("=> "));
2476 objResultPtr = POP_OBJECT();
2477 result = Tcl_SetReturnOptions(interp, OBJ_AT_TOS);
2478 if (result == TCL_OK) {
2479 Tcl_DecrRefCount(OBJ_AT_TOS);
2480 OBJ_AT_TOS = objResultPtr;
2481 TRACE_APPEND(("continuing to next instruction (result=\"%.30s\")\n",
2482 O2S(objResultPtr)));
2483 NEXT_INST_F(1, 0, 0);
2484 } else if (result == TCL_ERROR) {
2485 /*
2486 * BEWARE! Must do this in this order, because an error in the
2487 * option dictionary overrides the result (and can be verified by
2488 * test).
2489 */
2490
2491 Tcl_SetObjResult(interp, objResultPtr);
2492 Tcl_SetReturnOptions(interp, OBJ_AT_TOS);
2493 Tcl_DecrRefCount(OBJ_AT_TOS);
2494 OBJ_AT_TOS = objResultPtr;
2495 } else {
2496 Tcl_DecrRefCount(OBJ_AT_TOS);
2497 OBJ_AT_TOS = objResultPtr;
2498 Tcl_SetObjResult(interp, objResultPtr);
2499 }
2500 cleanup = 1;
2501 TRACE_APPEND(("\n"));
2502 goto processExceptionReturn;
2503
2504 {
2505 CoroutineData *corPtr;
2506 int yieldParameter;
2507
2508 case INST_YIELD:
2509 corPtr = iPtr->execEnvPtr->corPtr;
2510 TRACE(("%.30s => ", O2S(OBJ_AT_TOS)));
2511 if (!corPtr) {
2512 TRACE_APPEND(("ERROR: yield outside coroutine\n"));
2513 Tcl_SetObjResult(interp, Tcl_NewStringObj(
2514 "yield can only be called in a coroutine", -1));
2515 DECACHE_STACK_INFO();
2516 Tcl_SetErrorCode(interp, "TCL", "COROUTINE", "ILLEGAL_YIELD",
2517 (char *)NULL);
2518 CACHE_STACK_INFO();
2519 goto gotError;
2520 }
2521
2522 #ifdef TCL_COMPILE_DEBUG
2523 if (tclTraceExec >= 2) {
2524 if (traceInstructions) {
2525 TRACE_APPEND(("YIELD...\n"));
2526 } else {
2527 fprintf(stdout, "%d: (%u) yielding value \"%.30s\"\n",
2528 iPtr->numLevels, (unsigned)(pc - codePtr->codeStart),
2529 TclGetString(OBJ_AT_TOS));
2530 }
2531 fflush(stdout);
2532 }
2533 #endif
2534 yieldParameter = 0;
2535 Tcl_SetObjResult(interp, OBJ_AT_TOS);
2536 goto doYield;
2537
2538 case INST_YIELD_TO_INVOKE:
2539 corPtr = iPtr->execEnvPtr->corPtr;
2540 valuePtr = OBJ_AT_TOS;
2541 if (!corPtr) {
2542 TRACE(("[%.30s] => ERROR: yield outside coroutine\n",
2543 O2S(valuePtr)));
2544 Tcl_SetObjResult(interp, Tcl_NewStringObj(
2545 "yieldto can only be called in a coroutine", -1));
2546 DECACHE_STACK_INFO();
2547 Tcl_SetErrorCode(interp, "TCL", "COROUTINE", "ILLEGAL_YIELD",
2548 (char *)NULL);
2549 CACHE_STACK_INFO();
2550 goto gotError;
2551 }
2552 if (((Namespace *)TclGetCurrentNamespace(interp))->flags & NS_DYING) {
2553 TRACE(("[%.30s] => ERROR: yield in deleted\n",
2554 O2S(valuePtr)));
2555 Tcl_SetObjResult(interp, Tcl_NewStringObj(
2556 "yieldto called in deleted namespace", -1));
2557 DECACHE_STACK_INFO();
2558 Tcl_SetErrorCode(interp, "TCL", "COROUTINE", "YIELDTO_IN_DELETED",
2559 (char *)NULL);
2560 CACHE_STACK_INFO();
2561 goto gotError;
2562 }
2563
2564 #ifdef TCL_COMPILE_DEBUG
2565 if (tclTraceExec >= 2) {
2566 if (traceInstructions) {
2567 TRACE(("[%.30s] => YIELD...\n", O2S(valuePtr)));
2568 } else {
2569 /* FIXME: What is the right thing to trace? */
2570 fprintf(stdout, "%d: (%u) yielding to [%.30s]\n",
2571 iPtr->numLevels, (unsigned)(pc - codePtr->codeStart),
2572 TclGetString(valuePtr));
2573 }
2574 fflush(stdout);
2575 }
2576 #endif
2577
2578 /*
2579 * Install a tailcall record in the caller and continue with the
2580 * yield. The yield is switched into multi-return mode (via the
2581 * 'yieldParameter').
2582 */
2583
2584 Tcl_IncrRefCount(valuePtr);
2585 iPtr->execEnvPtr = corPtr->callerEEPtr;
2586 TclSetTailcall(interp, valuePtr);
2587 iPtr->execEnvPtr = corPtr->eePtr;
2588 yieldParameter = (PTR2INT(NULL)+1); /*==CORO_ACTIVATE_YIELDM*/
2589
2590 doYield:
2591 /* TIP #280: Record the last piece of info needed by
2592 * 'TclGetSrcInfoForPc', and push the frame.
2593 */
2594
2595 bcFramePtr->data.tebc.pc = (char *) pc;
2596 iPtr->cmdFramePtr = bcFramePtr;
2597
2598 if (iPtr->flags & INTERP_DEBUG_FRAME) {
2599 ArgumentBCEnter(interp, codePtr, TD, pc, objc, objv);
2600 }
2601
2602 pc++;
2603 cleanup = 1;
2604 TEBC_YIELD();
2605 TclNRAddCallback(interp, TclNRCoroutineActivateCallback, corPtr,
2606 INT2PTR(yieldParameter), NULL, NULL);
2607 return TCL_OK;
2608 }
2609
2610 case INST_TAILCALL: {
2611 Tcl_Obj *listPtr, *nsObjPtr;
2612
2613 opnd = TclGetUInt1AtPtr(pc+1);
2614
2615 if (!(iPtr->varFramePtr->isProcCallFrame & 1)) {
2616 TRACE(("%d => ERROR: tailcall in non-proc context\n", opnd));
2617 Tcl_SetObjResult(interp, Tcl_NewStringObj(
2618 "tailcall can only be called from a proc or lambda", -1));
2619 DECACHE_STACK_INFO();
2620 Tcl_SetErrorCode(interp, "TCL", "TAILCALL", "ILLEGAL", (char *)NULL);
2621 CACHE_STACK_INFO();
2622 goto gotError;
2623 }
2624
2625 #ifdef TCL_COMPILE_DEBUG
2626 /* FIXME: What is the right thing to trace? */
2627 {
2628 int i;
2629
2630 TRACE(("%d [", opnd));
2631 for (i=opnd-1 ; i>=0 ; i--) {
2632 TRACE_APPEND(("\"%.30s\"", O2S(OBJ_AT_DEPTH(i))));
2633 if (i > 0) {
2634 TRACE_APPEND((" "));
2635 }
2636 }
2637 TRACE_APPEND(("] => RETURN..."));
2638 }
2639 #endif
2640
2641 /*
2642 * Push the evaluation of the called command into the NR callback
2643 * stack.
2644 */
2645
2646 listPtr = Tcl_NewListObj(opnd, &OBJ_AT_DEPTH(opnd-1));
2647 nsObjPtr = Tcl_NewStringObj(iPtr->varFramePtr->nsPtr->fullName, -1);
2648 TclListObjSetElement(interp, listPtr, 0, nsObjPtr);
2649 if (iPtr->varFramePtr->tailcallPtr) {
2650 Tcl_DecrRefCount(iPtr->varFramePtr->tailcallPtr);
2651 }
2652 iPtr->varFramePtr->tailcallPtr = listPtr;
2653
2654 result = TCL_RETURN;
2655 cleanup = opnd;
2656 goto processExceptionReturn;
2657 }
2658
2659 case INST_DONE:
2660 if (tosPtr > initTosPtr) {
2661
2662 if ((curEvalFlags & TCL_EVAL_DISCARD_RESULT) && (result == TCL_OK)) {
2663 /* simulate pop & fast done (like it does continue in loop) */
2664 TRACE_WITH_OBJ(("=> discarding "), OBJ_AT_TOS);
2665 objPtr = POP_OBJECT();
2666 TclDecrRefCount(objPtr);
2667 goto abnormalReturn;
2668 }
2669 /*
2670 * Set the interpreter's object result to point to the topmost
2671 * object from the stack, and check for a possible [catch]. The
2672 * stackTop's level and refCount will be handled by "processCatch"
2673 * or "abnormalReturn".
2674 */
2675
2676 Tcl_SetObjResult(interp, OBJ_AT_TOS);
2677 #ifdef TCL_COMPILE_DEBUG
2678 TRACE_WITH_OBJ(("=> return code=%d, result=", result),
2679 iPtr->objResultPtr);
2680 if (traceInstructions) {
2681 fprintf(stdout, "\n");
2682 }
2683 #endif
2684 goto checkForCatch;
2685 }
2686 (void) POP_OBJECT();
2687 goto abnormalReturn;
2688
2689 case INST_PUSH4:
2690 objResultPtr = codePtr->objArrayPtr[TclGetUInt4AtPtr(pc+1)];
2691 TRACE_WITH_OBJ(("%u => ", TclGetUInt4AtPtr(pc+1)), objResultPtr);
2692 NEXT_INST_F(5, 0, 1);
2693 break;
2694
2695 case INST_POP:
2696 TRACE_WITH_OBJ(("=> discarding "), OBJ_AT_TOS);
2697 objPtr = POP_OBJECT();
2698 TclDecrRefCount(objPtr);
2699 NEXT_INST_F(1, 0, 0);
2700 break;
2701
2702 case INST_DUP:
2703 objResultPtr = OBJ_AT_TOS;
2704 TRACE_WITH_OBJ(("=> "), objResultPtr);
2705 NEXT_INST_F(1, 0, 1);
2706 break;
2707
2708 case INST_OVER:
2709 opnd = TclGetUInt4AtPtr(pc+1);
2710 objResultPtr = OBJ_AT_DEPTH(opnd);
2711 TRACE_WITH_OBJ(("%u => ", opnd), objResultPtr);
2712 NEXT_INST_F(5, 0, 1);
2713 break;
2714
2715 case INST_REVERSE: {
2716 Tcl_Obj **a, **b;
2717
2718 opnd = TclGetUInt4AtPtr(pc+1);
2719 a = tosPtr-(opnd-1);
2720 b = tosPtr;
2721 while (a<b) {
2722 tmpPtr = *a;
2723 *a = *b;
2724 *b = tmpPtr;
2725 a++; b--;
2726 }
2727 TRACE(("%u => OK\n", opnd));
2728 NEXT_INST_F(5, 0, 0);
2729 }
2730 break;
2731
2732 case INST_STR_CONCAT1: {
2733 int appendLen = 0;
2734 char *bytes, *p;
2735 Tcl_Obj **currPtr;
2736 int onlyb = 1;
2737
2738 opnd = TclGetUInt1AtPtr(pc+1);
2739
2740 /*
2741 * Detect only-bytearray-or-null case.
2742 */
2743
2744 for (currPtr=&OBJ_AT_DEPTH(opnd-1); currPtr<=&OBJ_AT_TOS; currPtr++) {
2745 if (((*currPtr)->typePtr != &tclByteArrayType)
2746 && ((*currPtr)->bytes != tclEmptyStringRep)) {
2747 onlyb = 0;
2748 break;
2749 } else if (((*currPtr)->typePtr == &tclByteArrayType) &&
2750 ((*currPtr)->bytes != NULL)) {
2751 onlyb = 0;
2752 break;
2753 }
2754 }
2755
2756 /*
2757 * Compute the length to be appended.
2758 */
2759
2760 if (onlyb) {
2761 for (currPtr = &OBJ_AT_DEPTH(opnd-2);
2762 appendLen >= 0 && currPtr <= &OBJ_AT_TOS; currPtr++) {
2763 if ((*currPtr)->bytes != tclEmptyStringRep) {
2764 Tcl_GetByteArrayFromObj(*currPtr, &length);
2765 appendLen += length;
2766 }
2767 }
2768 } else {
2769 for (currPtr = &OBJ_AT_DEPTH(opnd-2);
2770 appendLen >= 0 && currPtr <= &OBJ_AT_TOS; currPtr++) {
2771 bytes = TclGetStringFromObj(*currPtr, &length);
2772 if (bytes != NULL) {
2773 appendLen += length;
2774 }
2775 }
2776 }
2777
2778 if (appendLen < 0) {
2779 /* TODO: convert panic to error ? */
2780 Tcl_Panic("max size for a Tcl value (%d bytes) exceeded", INT_MAX);
2781 }
2782
2783 /*
2784 * If nothing is to be appended, just return the first object by
2785 * dropping all the others from the stack; this saves both the
2786 * computation and copy of the string rep of the first object,
2787 * enabling the fast '$x[set x {}]' idiom for 'K $x [set x {}]'.
2788 */
2789
2790 if (appendLen == 0) {
2791 TRACE_WITH_OBJ(("%u => ", opnd), objResultPtr);
2792 NEXT_INST_V(2, (opnd-1), 0);
2793 }
2794
2795 /*
2796 * If the first object is shared, we need a new obj for the result;
2797 * otherwise, we can reuse the first object. In any case, make sure it
2798 * has enough room to accommodate all the concatenated bytes. Note that
2799 * if it is unshared its bytes are copied by ckrealloc, so that we set
2800 * the loop parameters to avoid copying them again: p points to the
2801 * end of the already copied bytes, currPtr to the second object.
2802 */
2803
2804 objResultPtr = OBJ_AT_DEPTH(opnd-1);
2805 if (!onlyb) {
2806 bytes = TclGetStringFromObj(objResultPtr, &length);
2807 if (length + appendLen < 0) {
2808 /* TODO: convert panic to error ? */
2809 Tcl_Panic("max size for a Tcl value (%d bytes) exceeded",
2810 INT_MAX);
2811 }
2812 #ifndef TCL_COMPILE_DEBUG
2813 if (bytes != tclEmptyStringRep && !Tcl_IsShared(objResultPtr)) {
2814 TclFreeIntRep(objResultPtr);
2815 objResultPtr->bytes = ckrealloc(bytes, length+appendLen+1);
2816 objResultPtr->length = length + appendLen;
2817 p = TclGetString(objResultPtr) + length;
2818 currPtr = &OBJ_AT_DEPTH(opnd - 2);
2819 } else
2820 #endif
2821 {
2822 p = ckalloc(length + appendLen + 1);
2823 TclNewObj(objResultPtr);
2824 objResultPtr->bytes = p;
2825 objResultPtr->length = length + appendLen;
2826 currPtr = &OBJ_AT_DEPTH(opnd - 1);
2827 }
2828
2829 /*
2830 * Append the remaining characters.
2831 */
2832
2833 for (; currPtr <= &OBJ_AT_TOS; currPtr++) {
2834 bytes = TclGetStringFromObj(*currPtr, &length);
2835 if (bytes != NULL) {
2836 memcpy(p, bytes, length);
2837 p += length;
2838 }
2839 }
2840 *p = '\0';
2841 } else {
2842 bytes = (char *) Tcl_GetByteArrayFromObj(objResultPtr, &length);
2843 if (length + appendLen < 0) {
2844 /* TODO: convert panic to error ? */
2845 Tcl_Panic("max size for a Tcl value (%d bytes) exceeded",
2846 INT_MAX);
2847 }
2848 #ifndef TCL_COMPILE_DEBUG
2849 if (!Tcl_IsShared(objResultPtr)) {
2850 bytes = (char *) Tcl_SetByteArrayLength(objResultPtr,
2851 length + appendLen);
2852 p = bytes + length;
2853 currPtr = &OBJ_AT_DEPTH(opnd - 2);
2854 } else
2855 #endif
2856 {
2857 TclNewObj(objResultPtr);
2858 bytes = (char *) Tcl_SetByteArrayLength(objResultPtr,
2859 length + appendLen);
2860 p = bytes;
2861 currPtr = &OBJ_AT_DEPTH(opnd - 1);
2862 }
2863
2864 /*
2865 * Append the remaining characters.
2866 */
2867
2868 for (; currPtr <= &OBJ_AT_TOS; currPtr++) {
2869 if ((*currPtr)->bytes != tclEmptyStringRep) {
2870 bytes = (char *) Tcl_GetByteArrayFromObj(*currPtr,&length);
2871 memcpy(p, bytes, length);
2872 p += length;
2873 }
2874 }
2875 }
2876
2877 TRACE_WITH_OBJ(("%u => ", opnd), objResultPtr);
2878 NEXT_INST_V(2, opnd, 1);
2879 }
2880
2881 case INST_CONCAT_STK:
2882 /*
2883 * Pop the opnd (objc) top stack elements, run through Tcl_ConcatObj,
2884 * and then decrement their ref counts.
2885 */
2886
2887 opnd = TclGetUInt4AtPtr(pc+1);
2888 objResultPtr = Tcl_ConcatObj(opnd, &OBJ_AT_DEPTH(opnd-1));
2889 TRACE_WITH_OBJ(("%u => ", opnd), objResultPtr);
2890 NEXT_INST_V(5, opnd, 1);
2891
2892 case INST_EXPAND_START:
2893 /*
2894 * Push an element to the auxObjList. This records the current
2895 * stack depth - i.e., the point in the stack where the expanded
2896 * command starts.
2897 *
2898 * Use a Tcl_Obj as linked list element; slight mem waste, but faster
2899 * allocation than ckalloc. This also abuses the Tcl_Obj structure, as
2900 * we do not define a special tclObjType for it. It is not dangerous
2901 * as the obj is never passed anywhere, so that all manipulations are
2902 * performed here and in INST_INVOKE_EXPANDED (in case of an expansion
2903 * error, also in INST_EXPAND_STKTOP).
2904 */
2905
2906 TclNewObj(objPtr);
2907 objPtr->internalRep.twoPtrValue.ptr2 = INT2PTR(CURR_DEPTH);
2908 objPtr->length = 0;
2909 PUSH_TAUX_OBJ(objPtr);
2910 TRACE(("=> mark depth as %d\n", (int) CURR_DEPTH));
2911 NEXT_INST_F(1, 0, 0);
2912 break;
2913
2914 case INST_EXPAND_DROP:
2915 /*
2916 * Drops an element of the auxObjList, popping stack elements to
2917 * restore the stack to the state before the point where the aux
2918 * element was created.
2919 */
2920
2921 CLANG_ASSERT(auxObjList);
2922 objc = CURR_DEPTH - PTR2INT(auxObjList->internalRep.twoPtrValue.ptr2);
2923 POP_TAUX_OBJ();
2924 #ifdef TCL_COMPILE_DEBUG
2925 /* Ugly abuse! */
2926 starting = 1;
2927 #endif
2928 TRACE(("=> drop %d items\n", objc));
2929 NEXT_INST_V(1, objc, 0);
2930
2931 case INST_EXPAND_STKTOP: {
2932 int i;
2933 ptrdiff_t moved;
2934
2935 /*
2936 * Make sure that the element at stackTop is a list; if not, just
2937 * leave with an error. Note that the element from the expand list
2938 * will be removed at checkForCatch.
2939 */
2940
2941 objPtr = OBJ_AT_TOS;
2942 TRACE(("\"%.30s\" => ", O2S(objPtr)));
2943 if (TclListObjGetElements(interp, objPtr, &objc, &objv) != TCL_OK) {
2944 TRACE_ERROR(interp);
2945 goto gotError;
2946 }
2947 (void) POP_OBJECT();
2948
2949 /*
2950 * Make sure there is enough room in the stack to expand this list
2951 * *and* process the rest of the command (at least up to the next
2952 * argument expansion or command end). The operand is the current
2953 * stack depth, as seen by the compiler.
2954 */
2955
2956 auxObjList->length += objc - 1;
2957 if ((objc > 1) && (auxObjList->length > 0)) {
2958 length = auxObjList->length /* Total expansion room we need */
2959 + codePtr->maxStackDepth /* Beyond the original max */
2960 - CURR_DEPTH; /* Relative to where we are */
2961 DECACHE_STACK_INFO();
2962 moved = GrowEvaluationStack(iPtr->execEnvPtr, length, 1)
2963 - (Tcl_Obj **) TD;
2964 if (moved) {
2965 /*
2966 * Change the global data to point to the new stack: move the
2967 * TEBCdataPtr TD, recompute the position of every other
2968 * stack-allocated parameter, update the stack pointers.
2969 */
2970
2971 TD = (TEBCdata *) (((Tcl_Obj **)TD) + moved);
2972
2973 catchTop += moved;
2974 tosPtr += moved;
2975 }
2976 }
2977
2978 /*
2979 * Expand the list at stacktop onto the stack; free the list. Knowing
2980 * that it has a freeIntRepProc we use Tcl_DecrRefCount().
2981 */
2982
2983 for (i = 0; i < objc; i++) {
2984 PUSH_OBJECT(objv[i]);
2985 }
2986
2987 TRACE_APPEND(("OK\n"));
2988 Tcl_DecrRefCount(objPtr);
2989 NEXT_INST_F(5, 0, 0);
2990 }
2991 break;
2992
2993 case INST_EXPR_STK: {
2994 ByteCode *newCodePtr;
2995
2996 bcFramePtr->data.tebc.pc = (char *) pc;
2997 iPtr->cmdFramePtr = bcFramePtr;
2998 DECACHE_STACK_INFO();
2999 newCodePtr = CompileExprObj(interp, OBJ_AT_TOS);
3000 CACHE_STACK_INFO();
3001 cleanup = 1;
3002 pc++;
3003 TEBC_YIELD();
3004 return TclNRExecuteByteCode(interp, newCodePtr);
3005 }
3006
3007 /*
3008 * INVOCATION BLOCK
3009 */
3010
3011 case INST_EVAL_STK:
3012 instEvalStk:
3013 bcFramePtr->data.tebc.pc = (char *) pc;
3014 iPtr->cmdFramePtr = bcFramePtr;
3015
3016 cleanup = 1;
3017 pc += 1;
3018 /* yield next instruction */
3019 TEBC_YIELD();
3020 /* add TEBCResume for object at top of stack */
3021 return TclNRExecuteByteCode(interp,
3022 TclCompileObj(interp, OBJ_AT_TOS, NULL, 0));
3023
3024 case INST_INVOKE_EXPANDED:
3025 CLANG_ASSERT(auxObjList);
3026 objc = CURR_DEPTH - PTR2INT(auxObjList->internalRep.twoPtrValue.ptr2);
3027 POP_TAUX_OBJ();
3028 if (objc) {
3029 pcAdjustment = 1;
3030 goto doInvocation;
3031 }
3032
3033 /*
3034 * Nothing was expanded, return {}.
3035 */
3036
3037 TclNewObj(objResultPtr);
3038 NEXT_INST_F(1, 0, 1);
3039 break;
3040
3041 case INST_INVOKE_STK4:
3042 objc = TclGetUInt4AtPtr(pc+1);
3043 pcAdjustment = 5;
3044 goto doInvocation;
3045
3046 case INST_INVOKE_STK1:
3047 objc = TclGetUInt1AtPtr(pc+1);
3048 pcAdjustment = 2;
3049
3050 doInvocation:
3051 objv = &OBJ_AT_DEPTH(objc-1);
3052 cleanup = objc;
3053
3054 #ifdef TCL_COMPILE_DEBUG
3055 if (tclTraceExec >= 2) {
3056 int i;
3057
3058 if (traceInstructions) {
3059 strncpy(cmdNameBuf, TclGetString(objv[0]), 20);
3060 TRACE(("%u => call ", objc));
3061 } else {
3062 fprintf(stdout, "%d: (%u) invoking ", iPtr->numLevels,
3063 (unsigned)(pc - codePtr->codeStart));
3064 }
3065 for (i = 0; i < objc; i++) {
3066 TclPrintObject(stdout, objv[i], 15);
3067 fprintf(stdout, " ");
3068 }
3069 fprintf(stdout, "\n");
3070 fflush(stdout);
3071 }
3072 #endif /*TCL_COMPILE_DEBUG*/
3073
3074 /*
3075 * Finally, let TclEvalObjv handle the command.
3076 *
3077 * TIP #280: Record the last piece of info needed by
3078 * 'TclGetSrcInfoForPc', and push the frame.
3079 */
3080
3081 bcFramePtr->data.tebc.pc = (char *) pc;
3082 iPtr->cmdFramePtr = bcFramePtr;
3083
3084 if (iPtr->flags & INTERP_DEBUG_FRAME) {
3085 ArgumentBCEnter(interp, codePtr, TD, pc, objc, objv);
3086 }
3087
3088 DECACHE_STACK_INFO();
3089
3090 pc += pcAdjustment;
3091 TEBC_YIELD();
3092 return TclNREvalObjv(interp, objc, objv,
3093 TCL_EVAL_NOERR | TCL_EVAL_SOURCE_IN_FRAME, NULL);
3094
3095 #if TCL_SUPPORT_84_BYTECODE
3096 case INST_CALL_BUILTIN_FUNC1:
3097 /*
3098 * Call one of the built-in pre-8.5 Tcl math functions. This
3099 * translates to INST_INVOKE_STK1 with the first argument of
3100 * ::tcl::mathfunc::$objv[0]. We need to insert the named math
3101 * function into the stack.
3102 */
3103
3104 opnd = TclGetUInt1AtPtr(pc+1);
3105 if ((opnd < 0) || (opnd > LAST_BUILTIN_FUNC)) {
3106 TRACE(("UNRECOGNIZED BUILTIN FUNC CODE %d\n", opnd));
3107 Tcl_Panic("TclNRExecuteByteCode: unrecognized builtin function code %d", opnd);
3108 }
3109
3110 TclNewLiteralStringObj(objPtr, "::tcl::mathfunc::");
3111 Tcl_AppendToObj(objPtr, tclBuiltinFuncTable[opnd].name, -1);
3112
3113 /*
3114 * Only 0, 1 or 2 args.
3115 */
3116
3117 {
3118 int numArgs = tclBuiltinFuncTable[opnd].numArgs;
3119 Tcl_Obj *tmpPtr1, *tmpPtr2;
3120
3121 if (numArgs == 0) {
3122 PUSH_OBJECT(objPtr);
3123 } else if (numArgs == 1) {
3124 tmpPtr1 = POP_OBJECT();
3125 PUSH_OBJECT(objPtr);
3126 PUSH_OBJECT(tmpPtr1);
3127 Tcl_DecrRefCount(tmpPtr1);
3128 } else {
3129 tmpPtr2 = POP_OBJECT();
3130 tmpPtr1 = POP_OBJECT();
3131 PUSH_OBJECT(objPtr);
3132 PUSH_OBJECT(tmpPtr1);
3133 PUSH_OBJECT(tmpPtr2);
3134 Tcl_DecrRefCount(tmpPtr1);
3135 Tcl_DecrRefCount(tmpPtr2);
3136 }
3137 objc = numArgs + 1;
3138 }
3139 pcAdjustment = 2;
3140 goto doInvocation;
3141
3142 case INST_CALL_FUNC1:
3143 /*
3144 * Call a non-builtin Tcl math function previously registered by a
3145 * call to Tcl_CreateMathFunc pre-8.5. This is essentially
3146 * INST_INVOKE_STK1 converting the first arg to
3147 * ::tcl::mathfunc::$objv[0].
3148 */
3149
3150 objc = TclGetUInt1AtPtr(pc+1); /* Number of arguments. The function
3151 * name is the 0-th argument. */
3152
3153 objPtr = OBJ_AT_DEPTH(objc-1);
3154 TclNewLiteralStringObj(tmpPtr, "::tcl::mathfunc::");
3155 Tcl_AppendObjToObj(tmpPtr, objPtr);
3156 Tcl_DecrRefCount(objPtr);
3157
3158 /*
3159 * Variation of PUSH_OBJECT.
3160 */
3161
3162 OBJ_AT_DEPTH(objc-1) = tmpPtr;
3163 Tcl_IncrRefCount(tmpPtr);
3164
3165 pcAdjustment = 2;
3166 goto doInvocation;
3167 #else
3168 /*
3169 * INST_CALL_BUILTIN_FUNC1 and INST_CALL_FUNC1 were made obsolete by the
3170 * changes to add a ::tcl::mathfunc namespace in 8.5. Optional support
3171 * remains for existing bytecode precompiled files.
3172 */
3173
3174 case INST_CALL_BUILTIN_FUNC1:
3175 Tcl_Panic("TclNRExecuteByteCode: obsolete INST_CALL_BUILTIN_FUNC1 found");
3176 case INST_CALL_FUNC1:
3177 Tcl_Panic("TclNRExecuteByteCode: obsolete INST_CALL_FUNC1 found");
3178 #endif
3179
3180 case INST_INVOKE_REPLACE:
3181 objc = TclGetUInt4AtPtr(pc+1);
3182 opnd = TclGetUInt1AtPtr(pc+5);
3183 objPtr = POP_OBJECT();
3184 objv = &OBJ_AT_DEPTH(objc-1);
3185 cleanup = objc;
3186 #ifdef TCL_COMPILE_DEBUG
3187 if (tclTraceExec >= 2) {
3188 int i;
3189
3190 if (traceInstructions) {
3191 strncpy(cmdNameBuf, TclGetString(objv[0]), 20);
3192 TRACE(("%u => call (implementation %s) ", objc, O2S(objPtr)));
3193 } else {
3194 fprintf(stdout,
3195 "%d: (%u) invoking (using implementation %s) ",
3196 iPtr->numLevels, (unsigned)(pc - codePtr->codeStart),
3197 O2S(objPtr));
3198 }
3199 for (i = 0; i < objc; i++) {
3200 if (i < opnd) {
3201 fprintf(stdout, "<");
3202 TclPrintObject(stdout, objv[i], 15);
3203 fprintf(stdout, ">");
3204 } else {
3205 TclPrintObject(stdout, objv[i], 15);
3206 }
3207 fprintf(stdout, " ");
3208 }
3209 fprintf(stdout, "\n");
3210 fflush(stdout);
3211 }
3212 #endif /*TCL_COMPILE_DEBUG*/
3213
3214 bcFramePtr->data.tebc.pc = (char *) pc;
3215 iPtr->cmdFramePtr = bcFramePtr;
3216 if (iPtr->flags & INTERP_DEBUG_FRAME) {
3217 ArgumentBCEnter(interp, codePtr, TD, pc, objc, objv);
3218 }
3219
3220 TclInitRewriteEnsemble(interp, opnd, 1, objv);
3221
3222 {
3223 Tcl_Obj *copyPtr = Tcl_NewListObj(objc - opnd + 1, NULL);
3224
3225 Tcl_ListObjAppendElement(NULL, copyPtr, objPtr);
3226 Tcl_ListObjReplace(NULL, copyPtr, LIST_MAX, 0,
3227 objc - opnd, objv + opnd);
3228 Tcl_DecrRefCount(objPtr);
3229 objPtr = copyPtr;
3230 }
3231
3232 DECACHE_STACK_INFO();
3233 pc += 6;
3234 TEBC_YIELD();
3235
3236 TclMarkTailcall(interp);
3237 TclNRAddCallback(interp, TclClearRootEnsemble, NULL, NULL, NULL, NULL);
3238 TclListObjGetElements(NULL, objPtr, &objc, &objv);
3239 TclNRAddCallback(interp, TclNRReleaseValues, objPtr, NULL, NULL, NULL);
3240 return TclNREvalObjv(interp, objc, objv, TCL_EVAL_INVOKE, NULL);
3241
3242 /*
3243 * -----------------------------------------------------------------
3244 * Start of INST_LOAD instructions.
3245 *
3246 * WARNING: more 'goto' here than your doctor recommended! The different
3247 * instructions set the value of some variables and then jump to some
3248 * common execution code.
3249 */
3250
3251 case INST_LOAD_SCALAR1:
3252 instLoadScalar1:
3253 opnd = TclGetUInt1AtPtr(pc+1);
3254 varPtr = LOCAL(opnd);
3255 while (TclIsVarLink(varPtr)) {
3256 varPtr = varPtr->value.linkPtr;
3257 }
3258 TRACE(("%u => ", opnd));
3259 if (TclIsVarDirectReadable(varPtr)) {
3260 /*
3261 * No errors, no traces: just get the value.
3262 */
3263
3264 objResultPtr = varPtr->value.objPtr;
3265 TRACE_APPEND(("%.30s\n", O2S(objResultPtr)));
3266 NEXT_INST_F(2, 0, 1);
3267 }
3268 pcAdjustment = 2;
3269 cleanup = 0;
3270 arrayPtr = NULL;
3271 part1Ptr = part2Ptr = NULL;
3272 goto doCallPtrGetVar;
3273
3274 case INST_LOAD_SCALAR4:
3275 opnd = TclGetUInt4AtPtr(pc+1);
3276 varPtr = LOCAL(opnd);
3277 while (TclIsVarLink(varPtr)) {
3278 varPtr = varPtr->value.linkPtr;
3279 }
3280 TRACE(("%u => ", opnd));
3281 if (TclIsVarDirectReadable(varPtr)) {
3282 /*
3283 * No errors, no traces: just get the value.
3284 */
3285
3286 objResultPtr = varPtr->value.objPtr;
3287 TRACE_APPEND(("%.30s\n", O2S(objResultPtr)));
3288 NEXT_INST_F(5, 0, 1);
3289 }
3290 pcAdjustment = 5;
3291 cleanup = 0;
3292 arrayPtr = NULL;
3293 part1Ptr = part2Ptr = NULL;
3294 goto doCallPtrGetVar;
3295
3296 case INST_LOAD_ARRAY4:
3297 opnd = TclGetUInt4AtPtr(pc+1);
3298 pcAdjustment = 5;
3299 goto doLoadArray;
3300
3301 case INST_LOAD_ARRAY1:
3302 opnd = TclGetUInt1AtPtr(pc+1);
3303 pcAdjustment = 2;
3304
3305 doLoadArray:
3306 part1Ptr = NULL;
3307 part2Ptr = OBJ_AT_TOS;
3308 arrayPtr = LOCAL(opnd);
3309 while (TclIsVarLink(arrayPtr)) {
3310 arrayPtr = arrayPtr->value.linkPtr;
3311 }
3312 TRACE(("%u \"%.30s\" => ", opnd, O2S(part2Ptr)));
3313 if (TclIsVarArray(arrayPtr) && !ReadTraced(arrayPtr)) {
3314 varPtr = VarHashFindVar(arrayPtr->value.tablePtr, part2Ptr);
3315 if (varPtr && TclIsVarDirectReadable(varPtr)) {
3316 /*
3317 * No errors, no traces: just get the value.
3318 */
3319
3320 objResultPtr = varPtr->value.objPtr;
3321 TRACE_APPEND(("%.30s\n", O2S(objResultPtr)));
3322 NEXT_INST_F(pcAdjustment, 1, 1);
3323 }
3324 }
3325 varPtr = TclLookupArrayElement(interp, part1Ptr, part2Ptr,
3326 TCL_LEAVE_ERR_MSG, "read", 0, 1, arrayPtr, opnd);
3327 if (varPtr == NULL) {
3328 TRACE_ERROR(interp);
3329 goto gotError;
3330 }
3331 cleanup = 1;
3332 goto doCallPtrGetVar;
3333
3334 case INST_LOAD_ARRAY_STK:
3335 cleanup = 2;
3336 part2Ptr = OBJ_AT_TOS; /* element name */
3337 objPtr = OBJ_UNDER_TOS; /* array name */
3338 TRACE(("\"%.30s(%.30s)\" => ", O2S(objPtr), O2S(part2Ptr)));
3339 goto doLoadStk;
3340
3341 case INST_LOAD_STK:
3342 case INST_LOAD_SCALAR_STK:
3343 cleanup = 1;
3344 part2Ptr = NULL;
3345 objPtr = OBJ_AT_TOS; /* variable name */
3346 TRACE(("\"%.30s\" => ", O2S(objPtr)));
3347
3348 doLoadStk:
3349 part1Ptr = objPtr;
3350 varPtr = TclObjLookupVarEx(interp, part1Ptr, part2Ptr,
3351 TCL_LEAVE_ERR_MSG, "read", /*createPart1*/0, /*createPart2*/1,
3352 &arrayPtr);
3353 if (!varPtr) {
3354 TRACE_ERROR(interp);
3355 goto gotError;
3356 }
3357
3358 if (TclIsVarDirectReadable2(varPtr, arrayPtr)) {
3359 /*
3360 * No errors, no traces: just get the value.
3361 */
3362
3363 objResultPtr = varPtr->value.objPtr;
3364 TRACE_APPEND(("%.30s\n", O2S(objResultPtr)));
3365 NEXT_INST_V(1, cleanup, 1);
3366 }
3367 pcAdjustment = 1;
3368 opnd = -1;
3369
3370 doCallPtrGetVar:
3371 /*
3372 * There are either errors or the variable is traced: call
3373 * TclPtrGetVar to process fully.
3374 */
3375
3376 DECACHE_STACK_INFO();
3377 objResultPtr = TclPtrGetVarIdx(interp, varPtr, arrayPtr,
3378 part1Ptr, part2Ptr, TCL_LEAVE_ERR_MSG, opnd);
3379 CACHE_STACK_INFO();
3380 if (!objResultPtr) {
3381 TRACE_ERROR(interp);
3382 goto gotError;
3383 }
3384 TRACE_APPEND(("%.30s\n", O2S(objResultPtr)));
3385 NEXT_INST_V(pcAdjustment, cleanup, 1);
3386
3387 /*
3388 * End of INST_LOAD instructions.
3389 * -----------------------------------------------------------------
3390 * Start of INST_STORE and related instructions.
3391 *
3392 * WARNING: more 'goto' here than your doctor recommended! The different
3393 * instructions set the value of some variables and then jump to somme
3394 * common execution code.
3395 */
3396
3397 {
3398 int storeFlags, len;
3399
3400 case INST_STORE_ARRAY4:
3401 opnd = TclGetUInt4AtPtr(pc+1);
3402 pcAdjustment = 5;
3403 goto doStoreArrayDirect;
3404
3405 case INST_STORE_ARRAY1:
3406 opnd = TclGetUInt1AtPtr(pc+1);
3407 pcAdjustment = 2;
3408
3409 doStoreArrayDirect:
3410 valuePtr = OBJ_AT_TOS;
3411 part2Ptr = OBJ_UNDER_TOS;
3412 arrayPtr = LOCAL(opnd);
3413 TRACE(("%u \"%.30s\" <- \"%.30s\" => ", opnd, O2S(part2Ptr),
3414 O2S(valuePtr)));
3415 while (TclIsVarLink(arrayPtr)) {
3416 arrayPtr = arrayPtr->value.linkPtr;
3417 }
3418 if (TclIsVarArray(arrayPtr) && !WriteTraced(arrayPtr)) {
3419 varPtr = VarHashFindVar(arrayPtr->value.tablePtr, part2Ptr);
3420 if (varPtr && TclIsVarDirectWritable(varPtr)) {
3421 tosPtr--;
3422 Tcl_DecrRefCount(OBJ_AT_TOS);
3423 OBJ_AT_TOS = valuePtr;
3424 goto doStoreVarDirect;
3425 }
3426 }
3427 cleanup = 2;
3428 storeFlags = TCL_LEAVE_ERR_MSG;
3429 part1Ptr = NULL;
3430 goto doStoreArrayDirectFailed;
3431
3432 case INST_STORE_SCALAR4:
3433 opnd = TclGetUInt4AtPtr(pc+1);
3434 pcAdjustment = 5;
3435 goto doStoreScalarDirect;
3436
3437 case INST_STORE_SCALAR1:
3438 opnd = TclGetUInt1AtPtr(pc+1);
3439 pcAdjustment = 2;
3440
3441 doStoreScalarDirect:
3442 valuePtr = OBJ_AT_TOS;
3443 varPtr = LOCAL(opnd);
3444 TRACE(("%u <- \"%.30s\" => ", opnd, O2S(valuePtr)));
3445 while (TclIsVarLink(varPtr)) {
3446 varPtr = varPtr->value.linkPtr;
3447 }
3448 if (!TclIsVarDirectWritable(varPtr)) {
3449 storeFlags = TCL_LEAVE_ERR_MSG;
3450 part1Ptr = NULL;
3451 goto doStoreScalar;
3452 }
3453
3454 /*
3455 * No traces, no errors, plain 'set': we can safely inline. The value
3456 * *will* be set to what's requested, so that the stack top remains
3457 * pointing to the same Tcl_Obj.
3458 */
3459
3460 doStoreVarDirect:
3461 valuePtr = varPtr->value.objPtr;
3462 if (valuePtr != NULL) {
3463 TclDecrRefCount(valuePtr);
3464 }
3465 objResultPtr = OBJ_AT_TOS;
3466 varPtr->value.objPtr = objResultPtr;
3467 #ifndef TCL_COMPILE_DEBUG
3468 if (*(pc+pcAdjustment) == INST_POP) {
3469 tosPtr--;
3470 NEXT_INST_F((pcAdjustment+1), 0, 0);
3471 }
3472 #else
3473 TRACE_APPEND(("%.30s\n", O2S(objResultPtr)));
3474 #endif
3475 Tcl_IncrRefCount(objResultPtr);
3476 NEXT_INST_F(pcAdjustment, 0, 0);
3477
3478 case INST_LAPPEND_STK:
3479 valuePtr = OBJ_AT_TOS; /* value to append */
3480 part2Ptr = NULL;
3481 storeFlags = (TCL_LEAVE_ERR_MSG | TCL_APPEND_VALUE
3482 | TCL_LIST_ELEMENT);
3483 goto doStoreStk;
3484
3485 case INST_LAPPEND_ARRAY_STK:
3486 valuePtr = OBJ_AT_TOS; /* value to append */
3487 part2Ptr = OBJ_UNDER_TOS;
3488 storeFlags = (TCL_LEAVE_ERR_MSG | TCL_APPEND_VALUE
3489 | TCL_LIST_ELEMENT);
3490 goto doStoreStk;
3491
3492 case INST_APPEND_STK:
3493 valuePtr = OBJ_AT_TOS; /* value to append */
3494 part2Ptr = NULL;
3495 storeFlags = (TCL_LEAVE_ERR_MSG | TCL_APPEND_VALUE);
3496 goto doStoreStk;
3497
3498 case INST_APPEND_ARRAY_STK:
3499 valuePtr = OBJ_AT_TOS; /* value to append */
3500 part2Ptr = OBJ_UNDER_TOS;
3501 storeFlags = (TCL_LEAVE_ERR_MSG | TCL_APPEND_VALUE);
3502 goto doStoreStk;
3503
3504 case INST_STORE_ARRAY_STK:
3505 valuePtr = OBJ_AT_TOS;
3506 part2Ptr = OBJ_UNDER_TOS;
3507 storeFlags = TCL_LEAVE_ERR_MSG;
3508 goto doStoreStk;
3509
3510 case INST_STORE_STK:
3511 case INST_STORE_SCALAR_STK:
3512 valuePtr = OBJ_AT_TOS;
3513 part2Ptr = NULL;
3514 storeFlags = TCL_LEAVE_ERR_MSG;
3515
3516 doStoreStk:
3517 objPtr = OBJ_AT_DEPTH(1 + (part2Ptr != NULL)); /* variable name */
3518 part1Ptr = objPtr;
3519 #ifdef TCL_COMPILE_DEBUG
3520 if (part2Ptr == NULL) {
3521 TRACE(("\"%.30s\" <- \"%.30s\" =>", O2S(part1Ptr),O2S(valuePtr)));
3522 } else {
3523 TRACE(("\"%.30s(%.30s)\" <- \"%.30s\" => ",
3524 O2S(part1Ptr), O2S(part2Ptr), O2S(valuePtr)));
3525 }
3526 #endif
3527 varPtr = TclObjLookupVarEx(interp, objPtr,part2Ptr, TCL_LEAVE_ERR_MSG,
3528 "set", /*createPart1*/ 1, /*createPart2*/ 1, &arrayPtr);
3529 if (!varPtr) {
3530 TRACE_ERROR(interp);
3531 goto gotError;
3532 }
3533 cleanup = ((part2Ptr == NULL)? 2 : 3);
3534 pcAdjustment = 1;
3535 opnd = -1;
3536 goto doCallPtrSetVar;
3537
3538 case INST_LAPPEND_ARRAY4:
3539 opnd = TclGetUInt4AtPtr(pc+1);
3540 pcAdjustment = 5;
3541 storeFlags = (TCL_LEAVE_ERR_MSG | TCL_APPEND_VALUE
3542 | TCL_LIST_ELEMENT);
3543 goto doStoreArray;
3544
3545 case INST_LAPPEND_ARRAY1:
3546 opnd = TclGetUInt1AtPtr(pc+1);
3547 pcAdjustment = 2;
3548 storeFlags = (TCL_LEAVE_ERR_MSG | TCL_APPEND_VALUE
3549 | TCL_LIST_ELEMENT);
3550 goto doStoreArray;
3551
3552 case INST_APPEND_ARRAY4:
3553 opnd = TclGetUInt4AtPtr(pc+1);
3554 pcAdjustment = 5;
3555 storeFlags = (TCL_LEAVE_ERR_MSG | TCL_APPEND_VALUE);
3556 goto doStoreArray;
3557
3558 case INST_APPEND_ARRAY1:
3559 opnd = TclGetUInt1AtPtr(pc+1);
3560 pcAdjustment = 2;
3561 storeFlags = (TCL_LEAVE_ERR_MSG | TCL_APPEND_VALUE);
3562 goto doStoreArray;
3563
3564 doStoreArray:
3565 valuePtr = OBJ_AT_TOS;
3566 part2Ptr = OBJ_UNDER_TOS;
3567 arrayPtr = LOCAL(opnd);
3568 TRACE(("%u \"%.30s\" <- \"%.30s\" => ", opnd, O2S(part2Ptr),
3569 O2S(valuePtr)));
3570 while (TclIsVarLink(arrayPtr)) {
3571 arrayPtr = arrayPtr->value.linkPtr;
3572 }
3573 cleanup = 2;
3574 part1Ptr = NULL;
3575
3576 doStoreArrayDirectFailed:
3577 varPtr = TclLookupArrayElement(interp, part1Ptr, part2Ptr,
3578 TCL_LEAVE_ERR_MSG, "set", 1, 1, arrayPtr, opnd);
3579 if (!varPtr) {
3580 TRACE_ERROR(interp);
3581 goto gotError;
3582 }
3583 goto doCallPtrSetVar;
3584
3585 case INST_LAPPEND_SCALAR4:
3586 opnd = TclGetUInt4AtPtr(pc+1);
3587 pcAdjustment = 5;
3588 storeFlags = (TCL_LEAVE_ERR_MSG | TCL_APPEND_VALUE
3589 | TCL_LIST_ELEMENT);
3590 goto doStoreScalar;
3591
3592 case INST_LAPPEND_SCALAR1:
3593 opnd = TclGetUInt1AtPtr(pc+1);
3594 pcAdjustment = 2;
3595 storeFlags = (TCL_LEAVE_ERR_MSG | TCL_APPEND_VALUE
3596 | TCL_LIST_ELEMENT);
3597 goto doStoreScalar;
3598
3599 case INST_APPEND_SCALAR4:
3600 opnd = TclGetUInt4AtPtr(pc+1);
3601 pcAdjustment = 5;
3602 storeFlags = (TCL_LEAVE_ERR_MSG | TCL_APPEND_VALUE);
3603 goto doStoreScalar;
3604
3605 case INST_APPEND_SCALAR1:
3606 opnd = TclGetUInt1AtPtr(pc+1);
3607 pcAdjustment = 2;
3608 storeFlags = (TCL_LEAVE_ERR_MSG | TCL_APPEND_VALUE);
3609 goto doStoreScalar;
3610
3611 doStoreScalar:
3612 valuePtr = OBJ_AT_TOS;
3613 varPtr = LOCAL(opnd);
3614 TRACE(("%u <- \"%.30s\" => ", opnd, O2S(valuePtr)));
3615 while (TclIsVarLink(varPtr)) {
3616 varPtr = varPtr->value.linkPtr;
3617 }
3618 cleanup = 1;
3619 arrayPtr = NULL;
3620 part1Ptr = part2Ptr = NULL;
3621
3622 doCallPtrSetVar:
3623 DECACHE_STACK_INFO();
3624 objResultPtr = TclPtrSetVarIdx(interp, varPtr, arrayPtr,
3625 part1Ptr, part2Ptr, valuePtr, storeFlags, opnd);
3626 CACHE_STACK_INFO();
3627 if (!objResultPtr) {
3628 TRACE_ERROR(interp);
3629 goto gotError;
3630 }
3631 #ifndef TCL_COMPILE_DEBUG
3632 if (*(pc+pcAdjustment) == INST_POP) {
3633 NEXT_INST_V((pcAdjustment+1), cleanup, 0);
3634 }
3635 #endif
3636 TRACE_APPEND(("%.30s\n", O2S(objResultPtr)));
3637 NEXT_INST_V(pcAdjustment, cleanup, 1);
3638
3639 case INST_LAPPEND_LIST:
3640 opnd = TclGetUInt4AtPtr(pc+1);
3641 valuePtr = OBJ_AT_TOS;
3642 varPtr = LOCAL(opnd);
3643 cleanup = 1;
3644 pcAdjustment = 5;
3645 while (TclIsVarLink(varPtr)) {
3646 varPtr = varPtr->value.linkPtr;
3647 }
3648 TRACE(("%u <- \"%.30s\" => ", opnd, O2S(valuePtr)));
3649 if (TclListObjGetElements(interp, valuePtr, &objc, &objv)
3650 != TCL_OK) {
3651 TRACE_ERROR(interp);
3652 goto gotError;
3653 }
3654 if (TclIsVarDirectReadable(varPtr)
3655 && TclIsVarDirectWritable(varPtr)) {
3656 goto lappendListDirect;
3657 }
3658 arrayPtr = NULL;
3659 part1Ptr = part2Ptr = NULL;
3660 goto lappendListPtr;
3661
3662 case INST_LAPPEND_LIST_ARRAY:
3663 opnd = TclGetUInt4AtPtr(pc+1);
3664 valuePtr = OBJ_AT_TOS;
3665 part1Ptr = NULL;
3666 part2Ptr = OBJ_UNDER_TOS;
3667 arrayPtr = LOCAL(opnd);
3668 cleanup = 2;
3669 pcAdjustment = 5;
3670 while (TclIsVarLink(arrayPtr)) {
3671 arrayPtr = arrayPtr->value.linkPtr;
3672 }
3673 TRACE(("%u \"%.30s\" \"%.30s\" => ",
3674 opnd, O2S(part2Ptr), O2S(valuePtr)));
3675 if (TclListObjGetElements(interp, valuePtr, &objc, &objv)
3676 != TCL_OK) {
3677 TRACE_ERROR(interp);
3678 goto gotError;
3679 }
3680 if (TclIsVarArray(arrayPtr) && !ReadTraced(arrayPtr)
3681 && !WriteTraced(arrayPtr)) {
3682 varPtr = VarHashFindVar(arrayPtr->value.tablePtr, part2Ptr);
3683 if (varPtr && TclIsVarDirectReadable(varPtr)
3684 && TclIsVarDirectWritable(varPtr)) {
3685 goto lappendListDirect;
3686 }
3687 }
3688 varPtr = TclLookupArrayElement(interp, part1Ptr, part2Ptr,
3689 TCL_LEAVE_ERR_MSG, "set", 1, 1, arrayPtr, opnd);
3690 if (varPtr == NULL) {
3691 TRACE_ERROR(interp);
3692 goto gotError;
3693 }
3694 goto lappendListPtr;
3695
3696 case INST_LAPPEND_LIST_ARRAY_STK:
3697 pcAdjustment = 1;
3698 cleanup = 3;
3699 valuePtr = OBJ_AT_TOS;
3700 part2Ptr = OBJ_UNDER_TOS; /* element name */
3701 part1Ptr = OBJ_AT_DEPTH(2); /* array name */
3702 TRACE(("\"%.30s(%.30s)\" \"%.30s\" => ",
3703 O2S(part1Ptr), O2S(part2Ptr), O2S(valuePtr)));
3704 goto lappendList;
3705
3706 case INST_LAPPEND_LIST_STK:
3707 pcAdjustment = 1;
3708 cleanup = 2;
3709 valuePtr = OBJ_AT_TOS;
3710 part2Ptr = NULL;
3711 part1Ptr = OBJ_UNDER_TOS; /* variable name */
3712 TRACE(("\"%.30s\" \"%.30s\" => ", O2S(part1Ptr), O2S(valuePtr)));
3713 goto lappendList;
3714
3715 lappendListDirect:
3716 objResultPtr = varPtr->value.objPtr;
3717 if (TclListObjLength(interp, objResultPtr, &len) != TCL_OK) {
3718 TRACE_ERROR(interp);
3719 goto gotError;
3720 }
3721 if (Tcl_IsShared(objResultPtr)) {
3722 Tcl_Obj *newValue = Tcl_DuplicateObj(objResultPtr);
3723
3724 TclDecrRefCount(objResultPtr);
3725 varPtr->value.objPtr = objResultPtr = newValue;
3726 Tcl_IncrRefCount(newValue);
3727 }
3728 if (Tcl_ListObjReplace(interp, objResultPtr, len, 0, objc, objv)
3729 != TCL_OK) {
3730 TRACE_ERROR(interp);
3731 goto gotError;
3732 }
3733 TRACE_APPEND(("%.30s\n", O2S(objResultPtr)));
3734 NEXT_INST_V(pcAdjustment, cleanup, 1);
3735
3736 lappendList:
3737 opnd = -1;
3738 if (TclListObjGetElements(interp, valuePtr, &objc, &objv)
3739 != TCL_OK) {
3740 TRACE_ERROR(interp);
3741 goto gotError;
3742 }
3743 DECACHE_STACK_INFO();
3744 varPtr = TclObjLookupVarEx(interp, part1Ptr, part2Ptr,
3745 TCL_LEAVE_ERR_MSG, "set", 1, 1, &arrayPtr);
3746 CACHE_STACK_INFO();
3747 if (!varPtr) {
3748 TRACE_ERROR(interp);
3749 goto gotError;
3750 }
3751
3752 lappendListPtr:
3753 if (TclIsVarInHash(varPtr)) {
3754 VarHashRefCount(varPtr)++;
3755 }
3756 if (arrayPtr && TclIsVarInHash(arrayPtr)) {
3757 VarHashRefCount(arrayPtr)++;
3758 }
3759 DECACHE_STACK_INFO();
3760 objResultPtr = TclPtrGetVarIdx(interp, varPtr, arrayPtr,
3761 part1Ptr, part2Ptr, TCL_LEAVE_ERR_MSG, opnd);
3762 CACHE_STACK_INFO();
3763 if (TclIsVarInHash(varPtr)) {
3764 VarHashRefCount(varPtr)--;
3765 }
3766 if (arrayPtr && TclIsVarInHash(arrayPtr)) {
3767 VarHashRefCount(arrayPtr)--;
3768 }
3769
3770 {
3771 int createdNewObj = 0;
3772 Tcl_Obj *valueToAssign;
3773
3774 if (!objResultPtr) {
3775 valueToAssign = valuePtr;
3776 } else if (TclListObjLength(interp, objResultPtr, &len)!=TCL_OK) {
3777 TRACE_ERROR(interp);
3778 goto gotError;
3779 } else {
3780 if (Tcl_IsShared(objResultPtr)) {
3781 valueToAssign = Tcl_DuplicateObj(objResultPtr);
3782 createdNewObj = 1;
3783 } else {
3784 valueToAssign = objResultPtr;
3785 }
3786 if (Tcl_ListObjReplace(interp, valueToAssign, len, 0,
3787 objc, objv) != TCL_OK) {
3788 if (createdNewObj) {
3789 TclDecrRefCount(valueToAssign);
3790 }
3791 goto errorInLappendListPtr;
3792 }
3793 }
3794 DECACHE_STACK_INFO();
3795 Tcl_IncrRefCount(valueToAssign);
3796 objResultPtr = TclPtrSetVarIdx(interp, varPtr, arrayPtr, part1Ptr,
3797 part2Ptr, valueToAssign, TCL_LEAVE_ERR_MSG, opnd);
3798 TclDecrRefCount(valueToAssign);
3799 CACHE_STACK_INFO();
3800 if (!objResultPtr) {
3801 errorInLappendListPtr:
3802 TRACE_ERROR(interp);
3803 goto gotError;
3804 }
3805 }
3806 TRACE_APPEND(("%.30s\n", O2S(objResultPtr)));
3807 NEXT_INST_V(pcAdjustment, cleanup, 1);
3808 }
3809
3810 /*
3811 * End of INST_STORE and related instructions.
3812 * -----------------------------------------------------------------
3813 * Start of INST_INCR instructions.
3814 *
3815 * WARNING: more 'goto' here than your doctor recommended! The different
3816 * instructions set the value of some variables and then jump to some
3817 * common execution code.
3818 */
3819
3820 /*TODO: Consider more untangling here; merge with LOAD and STORE ? */
3821
3822 {
3823 Tcl_Obj *incrPtr;
3824 #ifndef TCL_WIDE_INT_IS_LONG
3825 Tcl_WideInt w;
3826 #endif
3827 long increment;
3828
3829 case INST_INCR_SCALAR1:
3830 case INST_INCR_ARRAY1:
3831 case INST_INCR_ARRAY_STK:
3832 case INST_INCR_SCALAR_STK:
3833 case INST_INCR_STK:
3834 opnd = TclGetUInt1AtPtr(pc+1);
3835 incrPtr = POP_OBJECT();
3836 switch (*pc) {
3837 case INST_INCR_SCALAR1:
3838 pcAdjustment = 2;
3839 goto doIncrScalar;
3840 case INST_INCR_ARRAY1:
3841 pcAdjustment = 2;
3842 goto doIncrArray;
3843 default:
3844 pcAdjustment = 1;
3845 goto doIncrStk;
3846 }
3847
3848 case INST_INCR_ARRAY_STK_IMM:
3849 case INST_INCR_SCALAR_STK_IMM:
3850 case INST_INCR_STK_IMM:
3851 increment = TclGetInt1AtPtr(pc+1);
3852 TclNewIntObj(incrPtr, increment);
3853 Tcl_IncrRefCount(incrPtr);
3854 pcAdjustment = 2;
3855
3856 doIncrStk:
3857 if ((*pc == INST_INCR_ARRAY_STK_IMM)
3858 || (*pc == INST_INCR_ARRAY_STK)) {
3859 part2Ptr = OBJ_AT_TOS;
3860 objPtr = OBJ_UNDER_TOS;
3861 TRACE(("\"%.30s(%.30s)\" (by %ld) => ",
3862 O2S(objPtr), O2S(part2Ptr), increment));
3863 } else {
3864 part2Ptr = NULL;
3865 objPtr = OBJ_AT_TOS;
3866 TRACE(("\"%.30s\" (by %ld) => ", O2S(objPtr), increment));
3867 }
3868 part1Ptr = objPtr;
3869 opnd = -1;
3870 varPtr = TclObjLookupVarEx(interp, objPtr, part2Ptr,
3871 TCL_LEAVE_ERR_MSG, "read", 1, 1, &arrayPtr);
3872 if (!varPtr) {
3873 DECACHE_STACK_INFO();
3874 Tcl_AddErrorInfo(interp,
3875 "\n (reading value of variable to increment)");
3876 CACHE_STACK_INFO();
3877 TRACE_ERROR(interp);
3878 Tcl_DecrRefCount(incrPtr);
3879 goto gotError;
3880 }
3881 cleanup = ((part2Ptr == NULL)? 1 : 2);
3882 goto doIncrVar;
3883
3884 case INST_INCR_ARRAY1_IMM:
3885 opnd = TclGetUInt1AtPtr(pc+1);
3886 increment = TclGetInt1AtPtr(pc+2);
3887 TclNewIntObj(incrPtr, increment);
3888 Tcl_IncrRefCount(incrPtr);
3889 pcAdjustment = 3;
3890
3891 doIncrArray:
3892 part1Ptr = NULL;
3893 part2Ptr = OBJ_AT_TOS;
3894 arrayPtr = LOCAL(opnd);
3895 cleanup = 1;
3896 while (TclIsVarLink(arrayPtr)) {
3897 arrayPtr = arrayPtr->value.linkPtr;
3898 }
3899 TRACE(("%u \"%.30s\" (by %ld) => ", opnd, O2S(part2Ptr), increment));
3900 varPtr = TclLookupArrayElement(interp, part1Ptr, part2Ptr,
3901 TCL_LEAVE_ERR_MSG, "read", 1, 1, arrayPtr, opnd);
3902 if (!varPtr) {
3903 TRACE_ERROR(interp);
3904 Tcl_DecrRefCount(incrPtr);
3905 goto gotError;
3906 }
3907 goto doIncrVar;
3908
3909 case INST_INCR_SCALAR1_IMM:
3910 opnd = TclGetUInt1AtPtr(pc+1);
3911 increment = TclGetInt1AtPtr(pc+2);
3912 pcAdjustment = 3;
3913 cleanup = 0;
3914 varPtr = LOCAL(opnd);
3915 while (TclIsVarLink(varPtr)) {
3916 varPtr = varPtr->value.linkPtr;
3917 }
3918
3919 if (TclIsVarDirectModifyable(varPtr)) {
3920 ClientData ptr;
3921 int type;
3922
3923 objPtr = varPtr->value.objPtr;
3924 if (GetNumberFromObj(NULL, objPtr, &ptr, &type) == TCL_OK) {
3925 if (type == TCL_NUMBER_LONG) {
3926 long augend = *((const long *)ptr);
3927 long sum = (long)((unsigned long)augend + (unsigned long)increment);
3928
3929 /*
3930 * Overflow when (augend and sum have different sign) and
3931 * (augend and increment have the same sign). This is
3932 * encapsulated in the Overflowing macro.
3933 */
3934
3935 if (!Overflowing(augend, increment, sum)) {
3936 TRACE(("%u %ld => ", opnd, increment));
3937 if (Tcl_IsShared(objPtr)) {
3938 objPtr->refCount--; /* We know it's shared. */
3939 TclNewLongObj(objResultPtr, sum);
3940 Tcl_IncrRefCount(objResultPtr);
3941 varPtr->value.objPtr = objResultPtr;
3942 } else {
3943 objResultPtr = objPtr;
3944 TclSetLongObj(objPtr, sum);
3945 }
3946 goto doneIncr;
3947 }
3948 #ifndef TCL_WIDE_INT_IS_LONG
3949 w = (Tcl_WideInt)augend;
3950
3951 TRACE(("%u %ld => ", opnd, increment));
3952 if (Tcl_IsShared(objPtr)) {
3953 objPtr->refCount--; /* We know it's shared. */
3954 objResultPtr = Tcl_NewWideIntObj(w+increment);
3955 Tcl_IncrRefCount(objResultPtr);
3956 varPtr->value.objPtr = objResultPtr;
3957 } else {
3958 objResultPtr = objPtr;
3959
3960 /*
3961 * We know the sum value is outside the long range;
3962 * use macro form that doesn't range test again.
3963 */
3964
3965 TclSetWideIntObj(objPtr, w+increment);
3966 }
3967 goto doneIncr;
3968 #endif
3969 } /* end if (type == TCL_NUMBER_LONG) */
3970 #ifndef TCL_WIDE_INT_IS_LONG
3971 if (type == TCL_NUMBER_WIDE) {
3972 Tcl_WideInt sum;
3973
3974 w = *((const Tcl_WideInt *) ptr);
3975 sum = (Tcl_WideInt)((Tcl_WideUInt)w + (Tcl_WideUInt)increment);
3976
3977 /*
3978 * Check for overflow.
3979 */
3980
3981 if (!Overflowing(w, increment, sum)) {
3982 TRACE(("%u %ld => ", opnd, increment));
3983 if (Tcl_IsShared(objPtr)) {
3984 objPtr->refCount--; /* We know it's shared. */
3985 objResultPtr = Tcl_NewWideIntObj(sum);
3986 Tcl_IncrRefCount(objResultPtr);
3987 varPtr->value.objPtr = objResultPtr;
3988 } else {
3989 objResultPtr = objPtr;
3990
3991 /*
3992 * We *do not* know the sum value is outside the
3993 * long range (wide + long can yield long); use
3994 * the function call that checks range.
3995 */
3996
3997 Tcl_SetWideIntObj(objPtr, sum);
3998 }
3999 goto doneIncr;
4000 }
4001 }
4002 #endif
4003 }
4004 if (Tcl_IsShared(objPtr)) {
4005 objPtr->refCount--; /* We know it's shared */
4006 objResultPtr = Tcl_DuplicateObj(objPtr);
4007 Tcl_IncrRefCount(objResultPtr);
4008 varPtr->value.objPtr = objResultPtr;
4009 } else {
4010 objResultPtr = objPtr;
4011 }
4012 TclNewLongObj(incrPtr, increment);
4013 if (TclIncrObj(interp, objResultPtr, incrPtr) != TCL_OK) {
4014 Tcl_DecrRefCount(incrPtr);
4015 TRACE_ERROR(interp);
4016 goto gotError;
4017 }
4018 Tcl_DecrRefCount(incrPtr);
4019 goto doneIncr;
4020 }
4021
4022 /*
4023 * All other cases, flow through to generic handling.
4024 */
4025
4026 TclNewLongObj(incrPtr, increment);
4027 Tcl_IncrRefCount(incrPtr);
4028
4029 doIncrScalar:
4030 varPtr = LOCAL(opnd);
4031 while (TclIsVarLink(varPtr)) {
4032 varPtr = varPtr->value.linkPtr;
4033 }
4034 arrayPtr = NULL;
4035 part1Ptr = part2Ptr = NULL;
4036 cleanup = 0;
4037 TRACE(("%u %s => ", opnd, TclGetString(incrPtr)));
4038
4039 doIncrVar:
4040 if (TclIsVarDirectModifyable2(varPtr, arrayPtr)) {
4041 objPtr = varPtr->value.objPtr;
4042 if (Tcl_IsShared(objPtr)) {
4043 objPtr->refCount--; /* We know it's shared */
4044 objResultPtr = Tcl_DuplicateObj(objPtr);
4045 Tcl_IncrRefCount(objResultPtr);
4046 varPtr->value.objPtr = objResultPtr;
4047 } else {
4048 objResultPtr = objPtr;
4049 }
4050 if (TclIncrObj(interp, objResultPtr, incrPtr) != TCL_OK) {
4051 Tcl_DecrRefCount(incrPtr);
4052 TRACE_ERROR(interp);
4053 goto gotError;
4054 }
4055 Tcl_DecrRefCount(incrPtr);
4056 } else {
4057 DECACHE_STACK_INFO();
4058 objResultPtr = TclPtrIncrObjVarIdx(interp, varPtr, arrayPtr,
4059 part1Ptr, part2Ptr, incrPtr, TCL_LEAVE_ERR_MSG, opnd);
4060 CACHE_STACK_INFO();
4061 Tcl_DecrRefCount(incrPtr);
4062 if (objResultPtr == NULL) {
4063 TRACE_ERROR(interp);
4064 goto gotError;
4065 }
4066 }
4067 doneIncr:
4068 TRACE_APPEND(("%.30s\n", O2S(objResultPtr)));
4069 #ifndef TCL_COMPILE_DEBUG
4070 if (*(pc+pcAdjustment) == INST_POP) {
4071 NEXT_INST_V((pcAdjustment+1), cleanup, 0);
4072 }
4073 #endif
4074 NEXT_INST_V(pcAdjustment, cleanup, 1);
4075 }
4076
4077 /*
4078 * End of INST_INCR instructions.
4079 * -----------------------------------------------------------------
4080 * Start of INST_EXIST instructions.
4081 */
4082
4083 case INST_EXIST_SCALAR:
4084 cleanup = 0;
4085 pcAdjustment = 5;
4086 opnd = TclGetUInt4AtPtr(pc+1);
4087 varPtr = LOCAL(opnd);
4088 while (TclIsVarLink(varPtr)) {
4089 varPtr = varPtr->value.linkPtr;
4090 }
4091 TRACE(("%u => ", opnd));
4092 if (ReadTraced(varPtr)) {
4093 DECACHE_STACK_INFO();
4094 TclObjCallVarTraces(iPtr, NULL, varPtr, NULL, NULL,
4095 TCL_TRACE_READS, 0, opnd);
4096 CACHE_STACK_INFO();
4097 if (TclIsVarUndefined(varPtr)) {
4098 TclCleanupVar(varPtr, NULL);
4099 varPtr = NULL;
4100 }
4101 }
4102 goto afterExistsPeephole;
4103
4104 case INST_EXIST_ARRAY:
4105 cleanup = 1;
4106 pcAdjustment = 5;
4107 opnd = TclGetUInt4AtPtr(pc+1);
4108 part2Ptr = OBJ_AT_TOS;
4109 arrayPtr = LOCAL(opnd);
4110 while (TclIsVarLink(arrayPtr)) {
4111 arrayPtr = arrayPtr->value.linkPtr;
4112 }
4113 TRACE(("%u \"%.30s\" => ", opnd, O2S(part2Ptr)));
4114 if (TclIsVarArray(arrayPtr) && !ReadTraced(arrayPtr)) {
4115 varPtr = VarHashFindVar(arrayPtr->value.tablePtr, part2Ptr);
4116 if (!varPtr || !ReadTraced(varPtr)) {
4117 goto afterExistsPeephole;
4118 }
4119 }
4120 varPtr = TclLookupArrayElement(interp, NULL, part2Ptr, 0, "access",
4121 0, 1, arrayPtr, opnd);
4122 if (varPtr) {
4123 if (ReadTraced(varPtr) || (arrayPtr && ReadTraced(arrayPtr))) {
4124 DECACHE_STACK_INFO();
4125 TclObjCallVarTraces(iPtr, arrayPtr, varPtr, NULL, part2Ptr,
4126 TCL_TRACE_READS, 0, opnd);
4127 CACHE_STACK_INFO();
4128 }
4129 if (TclIsVarUndefined(varPtr)) {
4130 TclCleanupVar(varPtr, arrayPtr);
4131 varPtr = NULL;
4132 }
4133 }
4134 goto afterExistsPeephole;
4135
4136 case INST_EXIST_ARRAY_STK:
4137 cleanup = 2;
4138 pcAdjustment = 1;
4139 part2Ptr = OBJ_AT_TOS; /* element name */
4140 part1Ptr = OBJ_UNDER_TOS; /* array name */
4141 TRACE(("\"%.30s(%.30s)\" => ", O2S(part1Ptr), O2S(part2Ptr)));
4142 goto doExistStk;
4143
4144 case INST_EXIST_STK:
4145 cleanup = 1;
4146 pcAdjustment = 1;
4147 part2Ptr = NULL;
4148 part1Ptr = OBJ_AT_TOS; /* variable name */
4149 TRACE(("\"%.30s\" => ", O2S(part1Ptr)));
4150
4151 doExistStk:
4152 varPtr = TclObjLookupVarEx(interp, part1Ptr, part2Ptr, 0, "access",
4153 /*createPart1*/0, /*createPart2*/1, &arrayPtr);
4154 if (varPtr) {
4155 if (ReadTraced(varPtr) || (arrayPtr && ReadTraced(arrayPtr))) {
4156 DECACHE_STACK_INFO();
4157 TclObjCallVarTraces(iPtr, arrayPtr, varPtr, part1Ptr,part2Ptr,
4158 TCL_TRACE_READS, 0, -1);
4159 CACHE_STACK_INFO();
4160 }
4161 if (TclIsVarUndefined(varPtr)) {
4162 TclCleanupVar(varPtr, arrayPtr);
4163 varPtr = NULL;
4164 }
4165 }
4166
4167 /*
4168 * Peep-hole optimisation: if you're about to jump, do jump from here.
4169 */
4170
4171 afterExistsPeephole: {
4172 int found = (varPtr && !TclIsVarUndefined(varPtr));
4173
4174 TRACE_APPEND(("%d\n", found ? 1 : 0));
4175 JUMP_PEEPHOLE_V(found, pcAdjustment, cleanup);
4176 }
4177
4178 /*
4179 * End of INST_EXIST instructions.
4180 * -----------------------------------------------------------------
4181 * Start of INST_UNSET instructions.
4182 */
4183
4184 {
4185 int flags;
4186
4187 case INST_UNSET_SCALAR:
4188 flags = TclGetUInt1AtPtr(pc+1) ? TCL_LEAVE_ERR_MSG : 0;
4189 opnd = TclGetUInt4AtPtr(pc+2);
4190 varPtr = LOCAL(opnd);
4191 while (TclIsVarLink(varPtr)) {
4192 varPtr = varPtr->value.linkPtr;
4193 }
4194 TRACE(("%s %u => ", (flags ? "normal" : "noerr"), opnd));
4195 if (TclIsVarDirectUnsettable(varPtr) && !TclIsVarInHash(varPtr)) {
4196 /*
4197 * No errors, no traces, no searches: just make the variable cease
4198 * to exist.
4199 */
4200
4201 if (!TclIsVarUndefined(varPtr)) {
4202 TclDecrRefCount(varPtr->value.objPtr);
4203 } else if (flags & TCL_LEAVE_ERR_MSG) {
4204 goto slowUnsetScalar;
4205 }
4206 varPtr->value.objPtr = NULL;
4207 TRACE_APPEND(("OK\n"));
4208 NEXT_INST_F(6, 0, 0);
4209 }
4210
4211 slowUnsetScalar:
4212 DECACHE_STACK_INFO();
4213 if (TclPtrUnsetVarIdx(interp, varPtr, NULL, NULL, NULL, flags,
4214 opnd) != TCL_OK && flags) {
4215 goto errorInUnset;
4216 }
4217 CACHE_STACK_INFO();
4218 NEXT_INST_F(6, 0, 0);
4219
4220 case INST_UNSET_ARRAY:
4221 flags = TclGetUInt1AtPtr(pc+1) ? TCL_LEAVE_ERR_MSG : 0;
4222 opnd = TclGetUInt4AtPtr(pc+2);
4223 part2Ptr = OBJ_AT_TOS;
4224 arrayPtr = LOCAL(opnd);
4225 while (TclIsVarLink(arrayPtr)) {
4226 arrayPtr = arrayPtr->value.linkPtr;
4227 }
4228 TRACE(("%s %u \"%.30s\" => ",
4229 (flags ? "normal" : "noerr"), opnd, O2S(part2Ptr)));
4230 if (TclIsVarArray(arrayPtr) && !UnsetTraced(arrayPtr)
4231 && !(arrayPtr->flags & VAR_SEARCH_ACTIVE)) {
4232 varPtr = VarHashFindVar(arrayPtr->value.tablePtr, part2Ptr);
4233 if (varPtr && TclIsVarDirectUnsettable(varPtr)) {
4234 /*
4235 * No nasty traces and element exists, so we can proceed to
4236 * unset it. Might still not exist though...
4237 */
4238
4239 if (!TclIsVarUndefined(varPtr)) {
4240 TclDecrRefCount(varPtr->value.objPtr);
4241 TclSetVarUndefined(varPtr);
4242 TclClearVarNamespaceVar(varPtr);
4243 TclCleanupVar(varPtr, arrayPtr);
4244 } else if (flags & TCL_LEAVE_ERR_MSG) {
4245 goto slowUnsetArray;
4246 }
4247 TRACE_APPEND(("OK\n"));
4248 NEXT_INST_F(6, 1, 0);
4249 } else if (!varPtr && !(flags & TCL_LEAVE_ERR_MSG)) {
4250 /*
4251 * Don't need to do anything here.
4252 */
4253
4254 TRACE_APPEND(("OK\n"));
4255 NEXT_INST_F(6, 1, 0);
4256 }
4257 }
4258 slowUnsetArray:
4259 DECACHE_STACK_INFO();
4260 varPtr = TclLookupArrayElement(interp, NULL, part2Ptr, flags, "unset",
4261 0, 0, arrayPtr, opnd);
4262 if (!varPtr) {
4263 if (flags & TCL_LEAVE_ERR_MSG) {
4264 goto errorInUnset;
4265 }
4266 } else if (TclPtrUnsetVarIdx(interp, varPtr, arrayPtr, NULL, part2Ptr,
4267 flags, opnd) != TCL_OK && (flags & TCL_LEAVE_ERR_MSG)) {
4268 goto errorInUnset;
4269 }
4270 CACHE_STACK_INFO();
4271 NEXT_INST_F(6, 1, 0);
4272
4273 case INST_UNSET_ARRAY_STK:
4274 flags = TclGetUInt1AtPtr(pc+1) ? TCL_LEAVE_ERR_MSG : 0;
4275 cleanup = 2;
4276 part2Ptr = OBJ_AT_TOS; /* element name */
4277 part1Ptr = OBJ_UNDER_TOS; /* array name */
4278 TRACE(("%s \"%.30s(%.30s)\" => ", (flags ? "normal" : "noerr"),
4279 O2S(part1Ptr), O2S(part2Ptr)));
4280 goto doUnsetStk;
4281
4282 case INST_UNSET_STK:
4283 flags = TclGetUInt1AtPtr(pc+1) ? TCL_LEAVE_ERR_MSG : 0;
4284 cleanup = 1;
4285 part2Ptr = NULL;
4286 part1Ptr = OBJ_AT_TOS; /* variable name */
4287 TRACE(("%s \"%.30s\" => ", (flags ? "normal" : "noerr"),
4288 O2S(part1Ptr)));
4289
4290 doUnsetStk:
4291 DECACHE_STACK_INFO();
4292 if (TclObjUnsetVar2(interp, part1Ptr, part2Ptr, flags) != TCL_OK
4293 && (flags & TCL_LEAVE_ERR_MSG)) {
4294 goto errorInUnset;
4295 }
4296 CACHE_STACK_INFO();
4297 TRACE_APPEND(("OK\n"));
4298 NEXT_INST_V(2, cleanup, 0);
4299
4300 errorInUnset:
4301 CACHE_STACK_INFO();
4302 TRACE_ERROR(interp);
4303 goto gotError;
4304
4305 /*
4306 * This is really an unset operation these days. Do not issue.
4307 */
4308
4309 case INST_DICT_DONE:
4310 opnd = TclGetUInt4AtPtr(pc+1);
4311 TRACE(("%u => OK\n", opnd));
4312 varPtr = LOCAL(opnd);
4313 while (TclIsVarLink(varPtr)) {
4314 varPtr = varPtr->value.linkPtr;
4315 }
4316 if (TclIsVarDirectUnsettable(varPtr) && !TclIsVarInHash(varPtr)) {
4317 if (!TclIsVarUndefined(varPtr)) {
4318 TclDecrRefCount(varPtr->value.objPtr);
4319 }
4320 varPtr->value.objPtr = NULL;
4321 } else {
4322 DECACHE_STACK_INFO();
4323 TclPtrUnsetVarIdx(interp, varPtr, NULL, NULL, NULL, 0, opnd);
4324 CACHE_STACK_INFO();
4325 }
4326 NEXT_INST_F(5, 0, 0);
4327 }
4328 break;
4329
4330 /*
4331 * End of INST_UNSET instructions.
4332 * -----------------------------------------------------------------
4333 * Start of INST_ARRAY instructions.
4334 */
4335
4336 case INST_ARRAY_EXISTS_IMM:
4337 opnd = TclGetUInt4AtPtr(pc+1);
4338 pcAdjustment = 5;
4339 cleanup = 0;
4340 part1Ptr = NULL;
4341 arrayPtr = NULL;
4342 TRACE(("%u => ", opnd));
4343 varPtr = LOCAL(opnd);
4344 while (TclIsVarLink(varPtr)) {
4345 varPtr = varPtr->value.linkPtr;
4346 }
4347 goto doArrayExists;
4348 case INST_ARRAY_EXISTS_STK:
4349 opnd = -1;
4350 pcAdjustment = 1;
4351 cleanup = 1;
4352 part1Ptr = OBJ_AT_TOS;
4353 TRACE(("\"%.30s\" => ", O2S(part1Ptr)));
4354 varPtr = TclObjLookupVarEx(interp, part1Ptr, NULL, 0, NULL,
4355 /*createPart1*/0, /*createPart2*/0, &arrayPtr);
4356 doArrayExists:
4357 DECACHE_STACK_INFO();
4358 result = TclCheckArrayTraces(interp, varPtr, arrayPtr, part1Ptr, opnd);
4359 CACHE_STACK_INFO();
4360 if (result == TCL_ERROR) {
4361 TRACE_ERROR(interp);
4362 goto gotError;
4363 }
4364 if (varPtr && TclIsVarArray(varPtr) && !TclIsVarUndefined(varPtr)) {
4365 objResultPtr = TCONST(1);
4366 } else {
4367 objResultPtr = TCONST(0);
4368 }
4369 TRACE_APPEND(("%.30s\n", O2S(objResultPtr)));
4370 NEXT_INST_V(pcAdjustment, cleanup, 1);
4371
4372 case INST_ARRAY_MAKE_IMM:
4373 opnd = TclGetUInt4AtPtr(pc+1);
4374 pcAdjustment = 5;
4375 cleanup = 0;
4376 part1Ptr = NULL;
4377 arrayPtr = NULL;
4378 TRACE(("%u => ", opnd));
4379 varPtr = LOCAL(opnd);
4380 while (TclIsVarLink(varPtr)) {
4381 varPtr = varPtr->value.linkPtr;
4382 }
4383 goto doArrayMake;
4384 case INST_ARRAY_MAKE_STK:
4385 opnd = -1;
4386 pcAdjustment = 1;
4387 cleanup = 1;
4388 part1Ptr = OBJ_AT_TOS;
4389 TRACE(("\"%.30s\" => ", O2S(part1Ptr)));
4390 varPtr = TclObjLookupVarEx(interp, part1Ptr, NULL, TCL_LEAVE_ERR_MSG,
4391 "set", /*createPart1*/1, /*createPart2*/0, &arrayPtr);
4392 if (varPtr == NULL) {
4393 TRACE_ERROR(interp);
4394 goto gotError;
4395 }
4396 doArrayMake:
4397 if (varPtr && !TclIsVarArray(varPtr)) {
4398 if (TclIsVarArrayElement(varPtr) || !TclIsVarUndefined(varPtr)) {
4399 /*
4400 * Either an array element, or a scalar: lose!
4401 */
4402
4403 TclObjVarErrMsg(interp, part1Ptr, NULL, "array set",
4404 "variable isn't array", opnd);
4405 DECACHE_STACK_INFO();
4406 Tcl_SetErrorCode(interp, "TCL", "WRITE", "ARRAY", (char *)NULL);
4407 CACHE_STACK_INFO();
4408 TRACE_ERROR(interp);
4409 goto gotError;
4410 }
4411 TclSetVarArray(varPtr);
4412 varPtr->value.tablePtr = ckalloc(sizeof(TclVarHashTable));
4413 TclInitVarHashTable(varPtr->value.tablePtr,
4414 TclGetVarNsPtr(varPtr));
4415 #ifdef TCL_COMPILE_DEBUG
4416 TRACE_APPEND(("done\n"));
4417 } else {
4418 TRACE_APPEND(("nothing to do\n"));
4419 #endif
4420 }
4421 NEXT_INST_V(pcAdjustment, cleanup, 0);
4422
4423 /*
4424 * End of INST_ARRAY instructions.
4425 * -----------------------------------------------------------------
4426 * Start of variable linking instructions.
4427 */
4428
4429 {
4430 Var *otherPtr;
4431 CallFrame *framePtr, *savedFramePtr;
4432 Tcl_Namespace *nsPtr;
4433 Namespace *savedNsPtr;
4434
4435 case INST_UPVAR:
4436 TRACE(("%d %.30s %.30s => ", TclGetInt4AtPtr(pc+1),
4437 O2S(OBJ_UNDER_TOS), O2S(OBJ_AT_TOS)));
4438
4439 if (TclObjGetFrame(interp, OBJ_UNDER_TOS, &framePtr) == -1) {
4440 TRACE_ERROR(interp);
4441 goto gotError;
4442 }
4443
4444 /*
4445 * Locate the other variable.
4446 */
4447
4448 savedFramePtr = iPtr->varFramePtr;
4449 iPtr->varFramePtr = framePtr;
4450 otherPtr = TclObjLookupVarEx(interp, OBJ_AT_TOS, NULL,
4451 TCL_LEAVE_ERR_MSG, "access", /*createPart1*/ 1,
4452 /*createPart2*/ 1, &varPtr);
4453 iPtr->varFramePtr = savedFramePtr;
4454 if (!otherPtr) {
4455 TRACE_ERROR(interp);
4456 goto gotError;
4457 }
4458 goto doLinkVars;
4459
4460 case INST_NSUPVAR:
4461 TRACE(("%d %.30s %.30s => ", TclGetInt4AtPtr(pc+1),
4462 O2S(OBJ_UNDER_TOS), O2S(OBJ_AT_TOS)));
4463 if (TclGetNamespaceFromObj(interp, OBJ_UNDER_TOS, &nsPtr) != TCL_OK) {
4464 TRACE_ERROR(interp);
4465 goto gotError;
4466 }
4467
4468 /*
4469 * Locate the other variable.
4470 */
4471
4472 savedNsPtr = iPtr->varFramePtr->nsPtr;
4473 iPtr->varFramePtr->nsPtr = (Namespace *) nsPtr;
4474 otherPtr = TclObjLookupVarEx(interp, OBJ_AT_TOS, NULL,
4475 (TCL_NAMESPACE_ONLY|TCL_LEAVE_ERR_MSG|TCL_AVOID_RESOLVERS),
4476 "access", /*createPart1*/ 1, /*createPart2*/ 1, &varPtr);
4477 iPtr->varFramePtr->nsPtr = savedNsPtr;
4478 if (!otherPtr) {
4479 TRACE_ERROR(interp);
4480 goto gotError;
4481 }
4482 goto doLinkVars;
4483
4484 case INST_VARIABLE:
4485 TRACE(("%d, %.30s => ", TclGetInt4AtPtr(pc+1), O2S(OBJ_AT_TOS)));
4486 otherPtr = TclObjLookupVarEx(interp, OBJ_AT_TOS, NULL,
4487 (TCL_NAMESPACE_ONLY | TCL_LEAVE_ERR_MSG), "access",
4488 /*createPart1*/ 1, /*createPart2*/ 1, &varPtr);
4489 if (!otherPtr) {
4490 TRACE_ERROR(interp);
4491 goto gotError;
4492 }
4493
4494 /*
4495 * Do the [variable] magic.
4496 */
4497
4498 TclSetVarNamespaceVar(otherPtr);
4499
4500 doLinkVars:
4501
4502 /*
4503 * If we are here, the local variable has already been created: do the
4504 * little work of TclPtrMakeUpvar that remains to be done right here
4505 * if there are no errors; otherwise, let it handle the case.
4506 */
4507
4508 opnd = TclGetInt4AtPtr(pc+1);
4509 varPtr = LOCAL(opnd);
4510 if ((varPtr != otherPtr) && !TclIsVarTraced(varPtr)
4511 && (TclIsVarUndefined(varPtr) || TclIsVarLink(varPtr))) {
4512 if (!TclIsVarUndefined(varPtr)) {
4513 /*
4514 * Then it is a defined link.
4515 */
4516
4517 Var *linkPtr = varPtr->value.linkPtr;
4518
4519 if (linkPtr == otherPtr) {
4520 TRACE_APPEND(("already linked\n"));
4521 NEXT_INST_F(5, 1, 0);
4522 }
4523 if (TclIsVarInHash(linkPtr)) {
4524 VarHashRefCount(linkPtr)--;
4525 if (TclIsVarUndefined(linkPtr)) {
4526 TclCleanupVar(linkPtr, NULL);
4527 }
4528 }
4529 }
4530 TclSetVarLink(varPtr);
4531 varPtr->value.linkPtr = otherPtr;
4532 if (TclIsVarInHash(otherPtr)) {
4533 VarHashRefCount(otherPtr)++;
4534 }
4535 } else if (TclPtrObjMakeUpvarIdx(interp, otherPtr, NULL, 0,
4536 opnd) != TCL_OK) {
4537 TRACE_ERROR(interp);
4538 goto gotError;
4539 }
4540
4541 /*
4542 * Do not pop the namespace or frame index, it may be needed for other
4543 * variables - and [variable] did not push it at all.
4544 */
4545
4546 TRACE_APPEND(("link made\n"));
4547 NEXT_INST_F(5, 1, 0);
4548 }
4549 break;
4550
4551 /*
4552 * End of variable linking instructions.
4553 * -----------------------------------------------------------------
4554 */
4555
4556 case INST_JUMP1:
4557 opnd = TclGetInt1AtPtr(pc+1);
4558 TRACE(("%d => new pc %u\n", opnd,
4559 (unsigned)(pc + opnd - codePtr->codeStart)));
4560 NEXT_INST_F(opnd, 0, 0);
4561 break;
4562
4563 case INST_JUMP4:
4564 opnd = TclGetInt4AtPtr(pc+1);
4565 TRACE(("%d => new pc %u\n", opnd,
4566 (unsigned)(pc + opnd - codePtr->codeStart)));
4567 NEXT_INST_F(opnd, 0, 0);
4568
4569 {
4570 int jmpOffset[2], b;
4571
4572 /* TODO: consider rewrite so we don't compute the offset we're not
4573 * going to take. */
4574 case INST_JUMP_FALSE4:
4575 jmpOffset[0] = TclGetInt4AtPtr(pc+1); /* FALSE offset */
4576 jmpOffset[1] = 5; /* TRUE offset */
4577 goto doCondJump;
4578
4579 case INST_JUMP_TRUE4:
4580 jmpOffset[0] = 5;
4581 jmpOffset[1] = TclGetInt4AtPtr(pc+1);
4582 goto doCondJump;
4583
4584 case INST_JUMP_FALSE1:
4585 jmpOffset[0] = TclGetInt1AtPtr(pc+1);
4586 jmpOffset[1] = 2;
4587 goto doCondJump;
4588
4589 case INST_JUMP_TRUE1:
4590 jmpOffset[0] = 2;
4591 jmpOffset[1] = TclGetInt1AtPtr(pc+1);
4592
4593 doCondJump:
4594 valuePtr = OBJ_AT_TOS;
4595 TRACE(("%d => ", jmpOffset[
4596 (*pc==INST_JUMP_FALSE1 || *pc==INST_JUMP_FALSE4) ? 0 : 1]));
4597
4598 /* TODO - check claim that taking address of b harms performance */
4599 /* TODO - consider optimization search for constants */
4600 if (TclGetBooleanFromObj(interp, valuePtr, &b) != TCL_OK) {
4601 TRACE_ERROR(interp);
4602 goto gotError;
4603 }
4604
4605 #ifdef TCL_COMPILE_DEBUG
4606 if (b) {
4607 if ((*pc == INST_JUMP_TRUE1) || (*pc == INST_JUMP_TRUE4)) {
4608 TRACE_APPEND(("%.20s true, new pc %u\n", O2S(valuePtr),
4609 (unsigned)(pc + jmpOffset[1] - codePtr->codeStart)));
4610 } else {
4611 TRACE_APPEND(("%.20s true\n", O2S(valuePtr)));
4612 }
4613 } else {
4614 if ((*pc == INST_JUMP_TRUE1) || (*pc == INST_JUMP_TRUE4)) {
4615 TRACE_APPEND(("%.20s false\n", O2S(valuePtr)));
4616 } else {
4617 TRACE_APPEND(("%.20s false, new pc %u\n", O2S(valuePtr),
4618 (unsigned)(pc + jmpOffset[0] - codePtr->codeStart)));
4619 }
4620 }
4621 #endif
4622 NEXT_INST_F(jmpOffset[b], 1, 0);
4623 }
4624 break;
4625
4626 case INST_JUMP_TABLE: {
4627 Tcl_HashEntry *hPtr;
4628 JumptableInfo *jtPtr;
4629
4630 /*
4631 * Jump to location looked up in a hashtable; fall through to next
4632 * instr if lookup fails.
4633 */
4634
4635 opnd = TclGetInt4AtPtr(pc+1);
4636 jtPtr = (JumptableInfo *) codePtr->auxDataArrayPtr[opnd].clientData;
4637 TRACE(("%d \"%.20s\" => ", opnd, O2S(OBJ_AT_TOS)));
4638 hPtr = Tcl_FindHashEntry(&jtPtr->hashTable, TclGetString(OBJ_AT_TOS));
4639 if (hPtr != NULL) {
4640 int jumpOffset = PTR2INT(Tcl_GetHashValue(hPtr));
4641
4642 TRACE_APPEND(("found in table, new pc %u\n",
4643 (unsigned)(pc - codePtr->codeStart + jumpOffset)));
4644 NEXT_INST_F(jumpOffset, 1, 0);
4645 } else {
4646 TRACE_APPEND(("not found in table\n"));
4647 NEXT_INST_F(5, 1, 0);
4648 }
4649 }
4650 break;
4651
4652 /*
4653 * These two instructions are now redundant: the complete logic of the LOR
4654 * and LAND is now handled by the expression compiler.
4655 */
4656
4657 case INST_LOR:
4658 case INST_LAND: {
4659 /*
4660 * Operands must be boolean or numeric. No int->double conversions are
4661 * performed.
4662 */
4663
4664 int i1, i2, iResult;
4665
4666 value2Ptr = OBJ_AT_TOS;
4667 valuePtr = OBJ_UNDER_TOS;
4668 if (TclGetBooleanFromObj(NULL, valuePtr, &i1) != TCL_OK) {
4669 TRACE(("\"%.20s\" => ILLEGAL TYPE %s \n", O2S(valuePtr),
4670 (valuePtr->typePtr? valuePtr->typePtr->name : "null")));
4671 DECACHE_STACK_INFO();
4672 IllegalExprOperandType(interp, pc, valuePtr);
4673 CACHE_STACK_INFO();
4674 goto gotError;
4675 }
4676
4677 if (TclGetBooleanFromObj(NULL, value2Ptr, &i2) != TCL_OK) {
4678 TRACE(("\"%.20s\" => ILLEGAL TYPE %s \n", O2S(value2Ptr),
4679 (value2Ptr->typePtr? value2Ptr->typePtr->name : "null")));
4680 DECACHE_STACK_INFO();
4681 IllegalExprOperandType(interp, pc, value2Ptr);
4682 CACHE_STACK_INFO();
4683 goto gotError;
4684 }
4685
4686 if (*pc == INST_LOR) {
4687 iResult = (i1 || i2);
4688 } else {
4689 iResult = (i1 && i2);
4690 }
4691 objResultPtr = TCONST(iResult);
4692 TRACE(("%.20s %.20s => %d\n", O2S(valuePtr),O2S(value2Ptr),iResult));
4693 NEXT_INST_F(1, 2, 1);
4694 }
4695 break;
4696
4697 /*
4698 * -----------------------------------------------------------------
4699 * Start of general introspector instructions.
4700 */
4701
4702 case INST_NS_CURRENT: {
4703 Namespace *currNsPtr = (Namespace *) TclGetCurrentNamespace(interp);
4704
4705 if (currNsPtr == (Namespace *) TclGetGlobalNamespace(interp)) {
4706 TclNewLiteralStringObj(objResultPtr, "::");
4707 } else {
4708 TclNewStringObj(objResultPtr, currNsPtr->fullName,
4709 strlen(currNsPtr->fullName));
4710 }
4711 TRACE_WITH_OBJ(("=> "), objResultPtr);
4712 NEXT_INST_F(1, 0, 1);
4713 }
4714 break;
4715 case INST_COROUTINE_NAME: {
4716 CoroutineData *corPtr = iPtr->execEnvPtr->corPtr;
4717
4718 TclNewObj(objResultPtr);
4719 if (corPtr && !(corPtr->cmdPtr->flags & CMD_IS_DELETED)) {
4720 Tcl_GetCommandFullName(interp, (Tcl_Command) corPtr->cmdPtr,
4721 objResultPtr);
4722 }
4723 TRACE_WITH_OBJ(("=> "), objResultPtr);
4724 NEXT_INST_F(1, 0, 1);
4725 }
4726 break;
4727 case INST_INFO_LEVEL_NUM:
4728 TclNewIntObj(objResultPtr, iPtr->varFramePtr->level);
4729 TRACE_WITH_OBJ(("=> "), objResultPtr);
4730 NEXT_INST_F(1, 0, 1);
4731 break;
4732 case INST_INFO_LEVEL_ARGS: {
4733 int level;
4734 CallFrame *framePtr = iPtr->varFramePtr;
4735 CallFrame *rootFramePtr = iPtr->rootFramePtr;
4736
4737 TRACE(("\"%.30s\" => ", O2S(OBJ_AT_TOS)));
4738 if (TclGetIntFromObj(interp, OBJ_AT_TOS, &level) != TCL_OK) {
4739 TRACE_ERROR(interp);
4740 goto gotError;
4741 }
4742 if (level <= 0) {
4743 level += framePtr->level;
4744 }
4745 for (; (framePtr->level!=level) && (framePtr!=rootFramePtr) ;
4746 framePtr = framePtr->callerVarPtr) {
4747 /* Empty loop body */
4748 }
4749 if (framePtr == rootFramePtr) {
4750 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
4751 "bad level \"%s\"", TclGetString(OBJ_AT_TOS)));
4752 TRACE_ERROR(interp);
4753 DECACHE_STACK_INFO();
4754 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "STACK_LEVEL",
4755 TclGetString(OBJ_AT_TOS), (char *)NULL);
4756 CACHE_STACK_INFO();
4757 goto gotError;
4758 }
4759 objResultPtr = Tcl_NewListObj(framePtr->objc, framePtr->objv);
4760 TRACE_APPEND(("%.30s\n", O2S(objResultPtr)));
4761 NEXT_INST_F(1, 1, 1);
4762 }
4763 {
4764 Tcl_Command cmd, origCmd;
4765
4766 case INST_RESOLVE_COMMAND:
4767 cmd = Tcl_GetCommandFromObj(interp, OBJ_AT_TOS);
4768 TclNewObj(objResultPtr);
4769 if (cmd != NULL) {
4770 Tcl_GetCommandFullName(interp, cmd, objResultPtr);
4771 }
4772 TRACE_WITH_OBJ(("\"%.20s\" => ", O2S(OBJ_AT_TOS)), objResultPtr);
4773 NEXT_INST_F(1, 1, 1);
4774
4775 case INST_ORIGIN_COMMAND:
4776 TRACE(("\"%.30s\" => ", O2S(OBJ_AT_TOS)));
4777 cmd = Tcl_GetCommandFromObj(interp, OBJ_AT_TOS);
4778 if (cmd == NULL) {
4779 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
4780 "invalid command name \"%s\"", TclGetString(OBJ_AT_TOS)));
4781 DECACHE_STACK_INFO();
4782 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "COMMAND",
4783 TclGetString(OBJ_AT_TOS), (char *)NULL);
4784 CACHE_STACK_INFO();
4785 TRACE_APPEND(("ERROR: not command\n"));
4786 goto gotError;
4787 }
4788 origCmd = TclGetOriginalCommand(cmd);
4789 if (origCmd == NULL) {
4790 origCmd = cmd;
4791 }
4792 TclNewObj(objResultPtr);
4793 Tcl_GetCommandFullName(interp, origCmd, objResultPtr);
4794 TRACE_APPEND(("\"%.30s\"", O2S(OBJ_AT_TOS)));
4795 NEXT_INST_F(1, 1, 1);
4796 }
4797
4798 /*
4799 * -----------------------------------------------------------------
4800 * Start of TclOO support instructions.
4801 */
4802
4803 {
4804 Object *oPtr;
4805 CallFrame *framePtr;
4806 CallContext *contextPtr;
4807 int skip, newDepth;
4808
4809 case INST_TCLOO_SELF:
4810 framePtr = iPtr->varFramePtr;
4811 if (framePtr == NULL ||
4812 !(framePtr->isProcCallFrame & FRAME_IS_METHOD)) {
4813 TRACE(("=> ERROR: no TclOO call context\n"));
4814 Tcl_SetObjResult(interp, Tcl_NewStringObj(
4815 "self may only be called from inside a method",
4816 -1));
4817 DECACHE_STACK_INFO();
4818 Tcl_SetErrorCode(interp, "TCL", "OO", "CONTEXT_REQUIRED", (char *)NULL);
4819 CACHE_STACK_INFO();
4820 goto gotError;
4821 }
4822 contextPtr = framePtr->clientData;
4823
4824 /*
4825 * Call out to get the name; it's expensive to compute but cached.
4826 */
4827
4828 objResultPtr = TclOOObjectName(interp, contextPtr->oPtr);
4829 TRACE_WITH_OBJ(("=> "), objResultPtr);
4830 NEXT_INST_F(1, 0, 1);
4831
4832 case INST_TCLOO_NEXT_CLASS:
4833 opnd = TclGetUInt1AtPtr(pc+1);
4834 framePtr = iPtr->varFramePtr;
4835 valuePtr = OBJ_AT_DEPTH(opnd - 2);
4836 objv = &OBJ_AT_DEPTH(opnd - 1);
4837 skip = 2;
4838 TRACE(("%d => ", opnd));
4839 if (framePtr == NULL ||
4840 !(framePtr->isProcCallFrame & FRAME_IS_METHOD)) {
4841 TRACE_APPEND(("ERROR: no TclOO call context\n"));
4842 Tcl_SetObjResult(interp, Tcl_NewStringObj(
4843 "nextto may only be called from inside a method",
4844 -1));
4845 DECACHE_STACK_INFO();
4846 Tcl_SetErrorCode(interp, "TCL", "OO", "CONTEXT_REQUIRED", (char *)NULL);
4847 CACHE_STACK_INFO();
4848 goto gotError;
4849 }
4850 contextPtr = framePtr->clientData;
4851
4852 oPtr = (Object *) Tcl_GetObjectFromObj(interp, valuePtr);
4853 if (oPtr == NULL) {
4854 TRACE_APPEND(("ERROR: \"%.30s\" not object\n", O2S(valuePtr)));
4855 goto gotError;
4856 } else {
4857 Class *classPtr = oPtr->classPtr;
4858 struct MInvoke *miPtr;
4859 int i;
4860 const char *methodType;
4861
4862 if (classPtr == NULL) {
4863 TRACE_APPEND(("ERROR: \"%.30s\" not class\n", O2S(valuePtr)));
4864 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
4865 "\"%s\" is not a class", TclGetString(valuePtr)));
4866 DECACHE_STACK_INFO();
4867 Tcl_SetErrorCode(interp, "TCL", "OO", "CLASS_REQUIRED", (char *)NULL);
4868 CACHE_STACK_INFO();
4869 goto gotError;
4870 }
4871
4872 for (i=contextPtr->index+1 ; i<contextPtr->callPtr->numChain ; i++) {
4873 miPtr = contextPtr->callPtr->chain + i;
4874 if (!miPtr->isFilter &&
4875 miPtr->mPtr->declaringClassPtr == classPtr) {
4876 newDepth = i;
4877 #ifdef TCL_COMPILE_DEBUG
4878 if (tclTraceExec >= 2) {
4879 if (traceInstructions) {
4880 strncpy(cmdNameBuf, TclGetString(objv[0]), 20);
4881 } else {
4882 fprintf(stdout, "%d: (%u) invoking ",
4883 iPtr->numLevels,
4884 (unsigned)(pc - codePtr->codeStart));
4885 }
4886 for (i = 0; i < opnd; i++) {
4887 TclPrintObject(stdout, objv[i], 15);
4888 fprintf(stdout, " ");
4889 }
4890 fprintf(stdout, "\n");
4891 fflush(stdout);
4892 }
4893 #endif /*TCL_COMPILE_DEBUG*/
4894 goto doInvokeNext;
4895 }
4896 }
4897
4898 if (contextPtr->callPtr->flags & CONSTRUCTOR) {
4899 methodType = "constructor";
4900 } else if (contextPtr->callPtr->flags & DESTRUCTOR) {
4901 methodType = "destructor";
4902 } else {
4903 methodType = "method";
4904 }
4905
4906 TRACE_APPEND(("ERROR: \"%.30s\" not on reachable chain\n",
4907 O2S(valuePtr)));
4908 for (i=contextPtr->index ; i>=0 ; i--) {
4909 miPtr = contextPtr->callPtr->chain + i;
4910 if (miPtr->isFilter
4911 || miPtr->mPtr->declaringClassPtr != classPtr) {
4912 continue;
4913 }
4914 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
4915 "%s implementation by \"%s\" not reachable from here",
4916 methodType, TclGetString(valuePtr)));
4917 DECACHE_STACK_INFO();
4918 Tcl_SetErrorCode(interp, "TCL", "OO", "CLASS_NOT_REACHABLE",
4919 (char *)NULL);
4920 CACHE_STACK_INFO();
4921 goto gotError;
4922 }
4923 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
4924 "%s has no non-filter implementation by \"%s\"",
4925 methodType, TclGetString(valuePtr)));
4926 DECACHE_STACK_INFO();
4927 Tcl_SetErrorCode(interp, "TCL", "OO", "CLASS_NOT_THERE", (char *)NULL);
4928 CACHE_STACK_INFO();
4929 goto gotError;
4930 }
4931
4932 case INST_TCLOO_NEXT:
4933 opnd = TclGetUInt1AtPtr(pc+1);
4934 objv = &OBJ_AT_DEPTH(opnd - 1);
4935 framePtr = iPtr->varFramePtr;
4936 skip = 1;
4937 TRACE(("%d => ", opnd));
4938 if (framePtr == NULL ||
4939 !(framePtr->isProcCallFrame & FRAME_IS_METHOD)) {
4940 TRACE_APPEND(("ERROR: no TclOO call context\n"));
4941 Tcl_SetObjResult(interp, Tcl_NewStringObj(
4942 "next may only be called from inside a method",
4943 -1));
4944 DECACHE_STACK_INFO();
4945 Tcl_SetErrorCode(interp, "TCL", "OO", "CONTEXT_REQUIRED", (char *)NULL);
4946 CACHE_STACK_INFO();
4947 goto gotError;
4948 }
4949 contextPtr = framePtr->clientData;
4950
4951 newDepth = contextPtr->index + 1;
4952 if (newDepth >= contextPtr->callPtr->numChain) {
4953 /*
4954 * We're at the end of the chain; generate an error message unless
4955 * the interpreter is being torn down, in which case we might be
4956 * getting here because of methods/destructors doing a [next] (or
4957 * equivalent) unexpectedly.
4958 */
4959
4960 const char *methodType;
4961
4962 if (contextPtr->callPtr->flags & CONSTRUCTOR) {
4963 methodType = "constructor";
4964 } else if (contextPtr->callPtr->flags & DESTRUCTOR) {
4965 methodType = "destructor";
4966 } else {
4967 methodType = "method";
4968 }
4969
4970 TRACE_APPEND(("ERROR: no TclOO next impl\n"));
4971 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
4972 "no next %s implementation", methodType));
4973 DECACHE_STACK_INFO();
4974 Tcl_SetErrorCode(interp, "TCL", "OO", "NOTHING_NEXT", (char *)NULL);
4975 CACHE_STACK_INFO();
4976 goto gotError;
4977 #ifdef TCL_COMPILE_DEBUG
4978 } else if (tclTraceExec >= 2) {
4979 int i;
4980
4981 if (traceInstructions) {
4982 strncpy(cmdNameBuf, TclGetString(objv[0]), 20);
4983 } else {
4984 fprintf(stdout, "%d: (%u) invoking ",
4985 iPtr->numLevels, (unsigned)(pc - codePtr->codeStart));
4986 }
4987 for (i = 0; i < opnd; i++) {
4988 TclPrintObject(stdout, objv[i], 15);
4989 fprintf(stdout, " ");
4990 }
4991 fprintf(stdout, "\n");
4992 fflush(stdout);
4993 #endif /*TCL_COMPILE_DEBUG*/
4994 }
4995
4996 doInvokeNext:
4997 bcFramePtr->data.tebc.pc = (char *) pc;
4998 iPtr->cmdFramePtr = bcFramePtr;
4999
5000 if (iPtr->flags & INTERP_DEBUG_FRAME) {
5001 ArgumentBCEnter(interp, codePtr, TD, pc, opnd, objv);
5002 }
5003
5004 pcAdjustment = 2;
5005 cleanup = opnd;
5006 DECACHE_STACK_INFO();
5007 iPtr->varFramePtr = framePtr->callerVarPtr;
5008 pc += pcAdjustment;
5009 TEBC_YIELD();
5010
5011 TclPushTailcallPoint(interp);
5012 oPtr = contextPtr->oPtr;
5013 if (oPtr->flags & FILTER_HANDLING) {
5014 TclNRAddCallback(interp, FinalizeOONextFilter,
5015 framePtr, contextPtr, INT2PTR(contextPtr->index),
5016 INT2PTR(contextPtr->skip));
5017 } else {
5018 TclNRAddCallback(interp, FinalizeOONext,
5019 framePtr, contextPtr, INT2PTR(contextPtr->index),
5020 INT2PTR(contextPtr->skip));
5021 }
5022 contextPtr->skip = skip;
5023 contextPtr->index = newDepth;
5024 if (contextPtr->callPtr->chain[newDepth].isFilter
5025 || contextPtr->callPtr->flags & FILTER_HANDLING) {
5026 oPtr->flags |= FILTER_HANDLING;
5027 } else {
5028 oPtr->flags &= ~FILTER_HANDLING;
5029 }
5030
5031 {
5032 Method *const mPtr =
5033 contextPtr->callPtr->chain[newDepth].mPtr;
5034
5035 return mPtr->typePtr->callProc(mPtr->clientData, interp,
5036 (Tcl_ObjectContext) contextPtr, opnd, objv);
5037 }
5038
5039 case INST_TCLOO_IS_OBJECT:
5040 oPtr = (Object *) Tcl_GetObjectFromObj(interp, OBJ_AT_TOS);
5041 objResultPtr = TCONST(oPtr != NULL ? 1 : 0);
5042 TRACE_WITH_OBJ(("%.30s => ", O2S(OBJ_AT_TOS)), objResultPtr);
5043 NEXT_INST_F(1, 1, 1);
5044 case INST_TCLOO_CLASS:
5045 oPtr = (Object *) Tcl_GetObjectFromObj(interp, OBJ_AT_TOS);
5046 if (oPtr == NULL) {
5047 TRACE(("%.30s => ERROR: not object\n", O2S(OBJ_AT_TOS)));
5048 goto gotError;
5049 }
5050 objResultPtr = TclOOObjectName(interp, oPtr->selfCls->thisPtr);
5051 TRACE_WITH_OBJ(("%.30s => ", O2S(OBJ_AT_TOS)), objResultPtr);
5052 NEXT_INST_F(1, 1, 1);
5053 case INST_TCLOO_NS:
5054 oPtr = (Object *) Tcl_GetObjectFromObj(interp, OBJ_AT_TOS);
5055 if (oPtr == NULL) {
5056 TRACE(("%.30s => ERROR: not object\n", O2S(OBJ_AT_TOS)));
5057 goto gotError;
5058 }
5059
5060 /*
5061 * TclOO objects *never* have the global namespace as their NS.
5062 */
5063
5064 TclNewStringObj(objResultPtr, oPtr->namespacePtr->fullName,
5065 strlen(oPtr->namespacePtr->fullName));
5066 TRACE_WITH_OBJ(("%.30s => ", O2S(OBJ_AT_TOS)), objResultPtr);
5067 NEXT_INST_F(1, 1, 1);
5068 }
5069
5070 /*
5071 * End of TclOO support instructions.
5072 * -----------------------------------------------------------------
5073 * Start of INST_LIST and related instructions.
5074 */
5075
5076 {
5077 int index, numIndices, fromIdx, toIdx;
5078 int nocase, match, length2, cflags, s1len, s2len;
5079 const char *s1, *s2;
5080
5081 case INST_LIST:
5082 /*
5083 * Pop the opnd (objc) top stack elements into a new list obj and then
5084 * decrement their ref counts.
5085 */
5086
5087 opnd = TclGetUInt4AtPtr(pc+1);
5088 objResultPtr = Tcl_NewListObj(opnd, &OBJ_AT_DEPTH(opnd-1));
5089 TRACE_WITH_OBJ(("%u => ", opnd), objResultPtr);
5090 NEXT_INST_V(5, opnd, 1);
5091
5092 case INST_LIST_LENGTH:
5093 TRACE(("\"%.30s\" => ", O2S(OBJ_AT_TOS)));
5094 if (TclListObjLength(interp, OBJ_AT_TOS, &length) != TCL_OK) {
5095 TRACE_ERROR(interp);
5096 goto gotError;
5097 }
5098 TclNewIntObj(objResultPtr, length);
5099 TRACE_APPEND(("%d\n", length));
5100 NEXT_INST_F(1, 1, 1);
5101
5102 case INST_LIST_INDEX: /* lindex with objc == 3 */
5103 value2Ptr = OBJ_AT_TOS;
5104 valuePtr = OBJ_UNDER_TOS;
5105 TRACE(("\"%.30s\" \"%.30s\" => ", O2S(valuePtr), O2S(value2Ptr)));
5106
5107 /*
5108 * Extract the desired list element.
5109 */
5110
5111 if ((TclListObjGetElements(interp, valuePtr, &objc, &objv) == TCL_OK)
5112 && (value2Ptr->typePtr != &tclListType)
5113 && (TclGetIntForIndexM(NULL , value2Ptr, objc-1,
5114 &index) == TCL_OK)) {
5115 TclDecrRefCount(value2Ptr);
5116 tosPtr--;
5117 pcAdjustment = 1;
5118 goto lindexFastPath;
5119 }
5120
5121 objResultPtr = TclLindexList(interp, valuePtr, value2Ptr);
5122 if (!objResultPtr) {
5123 TRACE_ERROR(interp);
5124 goto gotError;
5125 }
5126
5127 /*
5128 * Stash the list element on the stack.
5129 */
5130
5131 TRACE_APPEND(("\"%.30s\"\n", O2S(objResultPtr)));
5132 NEXT_INST_F(1, 2, -1); /* Already has the correct refCount */
5133
5134 case INST_LIST_INDEX_IMM: /* lindex with objc==3 and index in bytecode
5135 * stream */
5136
5137 /*
5138 * Pop the list and get the index.
5139 */
5140
5141 valuePtr = OBJ_AT_TOS;
5142 opnd = TclGetInt4AtPtr(pc+1);
5143 TRACE(("\"%.30s\" %d => ", O2S(valuePtr), opnd));
5144
5145 /*
5146 * Get the contents of the list, making sure that it really is a list
5147 * in the process.
5148 */
5149
5150 if (TclListObjGetElements(interp, valuePtr, &objc, &objv) != TCL_OK) {
5151 TRACE_ERROR(interp);
5152 goto gotError;
5153 }
5154
5155 /* Decode end-offset index values. */
5156
5157 index = TclIndexDecode(opnd, objc - 1);
5158 pcAdjustment = 5;
5159
5160 lindexFastPath:
5161 if (index >= 0 && index < objc) {
5162 objResultPtr = objv[index];
5163 } else {
5164 TclNewObj(objResultPtr);
5165 }
5166
5167 TRACE_APPEND(("\"%.30s\"\n", O2S(objResultPtr)));
5168 NEXT_INST_F(pcAdjustment, 1, 1);
5169
5170 case INST_LIST_INDEX_MULTI: /* 'lindex' with multiple index args */
5171 /*
5172 * Determine the count of index args.
5173 */
5174
5175 opnd = TclGetUInt4AtPtr(pc+1);
5176 numIndices = opnd-1;
5177
5178 /*
5179 * Do the 'lindex' operation.
5180 */
5181
5182 TRACE(("%d => ", opnd));
5183 objResultPtr = TclLindexFlat(interp, OBJ_AT_DEPTH(numIndices),
5184 numIndices, &OBJ_AT_DEPTH(numIndices - 1));
5185 if (!objResultPtr) {
5186 TRACE_ERROR(interp);
5187 goto gotError;
5188 }
5189
5190 /*
5191 * Set result.
5192 */
5193
5194 TRACE_APPEND(("\"%.30s\"\n", O2S(objResultPtr)));
5195 NEXT_INST_V(5, opnd, -1);
5196
5197 case INST_LSET_FLAT:
5198 /*
5199 * Lset with 3, 5, or more args. Get the number of index args.
5200 */
5201
5202 opnd = TclGetUInt4AtPtr(pc + 1);
5203 numIndices = opnd - 2;
5204 TRACE(("%d => ", opnd));
5205
5206 /*
5207 * Get the old value of variable, and remove the stack ref. This is
5208 * safe because the variable still references the object; the ref
5209 * count will never go zero here - we can use the smaller macro
5210 * Tcl_DecrRefCount.
5211 */
5212
5213 valuePtr = POP_OBJECT();
5214 Tcl_DecrRefCount(valuePtr); /* This one should be done here */
5215
5216 /*
5217 * Compute the new variable value.
5218 */
5219
5220 objResultPtr = TclLsetFlat(interp, valuePtr, numIndices,
5221 &OBJ_AT_DEPTH(numIndices), OBJ_AT_TOS);
5222 if (!objResultPtr) {
5223 TRACE_ERROR(interp);
5224 goto gotError;
5225 }
5226
5227 /*
5228 * Set result.
5229 */
5230
5231 TRACE_APPEND(("\"%.30s\"\n", O2S(objResultPtr)));
5232 NEXT_INST_V(5, numIndices+1, -1);
5233
5234 case INST_LSET_LIST: /* 'lset' with 4 args */
5235 /*
5236 * Get the old value of variable, and remove the stack ref. This is
5237 * safe because the variable still references the object; the ref
5238 * count will never go zero here - we can use the smaller macro
5239 * Tcl_DecrRefCount.
5240 */
5241
5242 objPtr = POP_OBJECT();
5243 Tcl_DecrRefCount(objPtr); /* This one should be done here. */
5244
5245 /*
5246 * Get the new element value, and the index list.
5247 */
5248
5249 valuePtr = OBJ_AT_TOS;
5250 value2Ptr = OBJ_UNDER_TOS;
5251 TRACE(("\"%.30s\" \"%.30s\" \"%.30s\" => ",
5252 O2S(value2Ptr), O2S(valuePtr), O2S(objPtr)));
5253
5254 /*
5255 * Compute the new variable value.
5256 */
5257
5258 objResultPtr = TclLsetList(interp, objPtr, value2Ptr, valuePtr);
5259 if (!objResultPtr) {
5260 TRACE_ERROR(interp);
5261 goto gotError;
5262 }
5263
5264 /*
5265 * Set result.
5266 */
5267
5268 TRACE_APPEND(("\"%.30s\"\n", O2S(objResultPtr)));
5269 NEXT_INST_F(1, 2, -1);
5270
5271 case INST_LIST_RANGE_IMM: /* lrange with objc==4 and both indices in
5272 * bytecode stream */
5273
5274 /*
5275 * Pop the list and get the indices.
5276 */
5277
5278 valuePtr = OBJ_AT_TOS;
5279 fromIdx = TclGetInt4AtPtr(pc+1);
5280 toIdx = TclGetInt4AtPtr(pc+5);
5281 TRACE(("\"%.30s\" %d %d => ", O2S(valuePtr), TclGetInt4AtPtr(pc+1),
5282 TclGetInt4AtPtr(pc+5)));
5283
5284 /*
5285 * Get the contents of the list, making sure that it really is a list
5286 * in the process.
5287 */
5288
5289 if (TclListObjGetElements(interp, valuePtr, &objc, &objv) != TCL_OK) {
5290 TRACE_ERROR(interp);
5291 goto gotError;
5292 }
5293
5294 /*
5295 * Skip a lot of work if we're about to throw the result away (common
5296 * with uses of [lassign]).
5297 */
5298
5299 #ifndef TCL_COMPILE_DEBUG
5300 if (*(pc+9) == INST_POP) {
5301 NEXT_INST_F(10, 1, 0);
5302 }
5303 #endif
5304
5305 /* Every range of an empty list is an empty list */
5306 if (objc == 0) {
5307 /* avoid return of not canonical list (e. g. spaces in string repr.) */
5308 if (!valuePtr->bytes || !valuePtr->length) {
5309 TRACE_APPEND(("\n"));
5310 NEXT_INST_F(9, 0, 0);
5311 }
5312 goto emptyList;
5313 }
5314
5315 /* Decode index value operands. */
5316
5317 /*
5318 assert ( toIdx != TCL_INDEX_AFTER);
5319 *
5320 * Extra safety for legacy bytecodes:
5321 */
5322 if (toIdx == TCL_INDEX_AFTER) {
5323 toIdx = TCL_INDEX_END;
5324 }
5325
5326 if ((toIdx == TCL_INDEX_BEFORE) || (fromIdx == TCL_INDEX_AFTER)) {
5327 goto emptyList;
5328 }
5329 toIdx = TclIndexDecode(toIdx, objc - 1);
5330 if (toIdx < 0) {
5331 goto emptyList;
5332 } else if (toIdx >= objc) {
5333 toIdx = objc - 1;
5334 }
5335
5336 assert ( toIdx >= 0 && toIdx < objc);
5337 /*
5338 assert ( fromIdx != TCL_INDEX_BEFORE );
5339 *
5340 * Extra safety for legacy bytecodes:
5341 */
5342 if (fromIdx == TCL_INDEX_BEFORE) {
5343 fromIdx = TCL_INDEX_START;
5344 }
5345
5346 fromIdx = TclIndexDecode(fromIdx, objc - 1);
5347 if (fromIdx < 0) {
5348 fromIdx = 0;
5349 }
5350
5351 if (fromIdx <= toIdx) {
5352 /* Construct the subsequence list */
5353 /* unshared optimization */
5354 if (Tcl_IsShared(valuePtr)) {
5355 objResultPtr = Tcl_NewListObj(toIdx-fromIdx+1, objv+fromIdx);
5356 } else {
5357 if (toIdx != objc - 1) {
5358 Tcl_ListObjReplace(NULL, valuePtr, toIdx + 1, LIST_MAX,
5359 0, NULL);
5360 }
5361 Tcl_ListObjReplace(NULL, valuePtr, 0, fromIdx, 0, NULL);
5362 TRACE_APPEND(("%.30s\n", O2S(valuePtr)));
5363 NEXT_INST_F(9, 0, 0);
5364 }
5365 } else {
5366 emptyList:
5367 TclNewObj(objResultPtr);
5368 }
5369
5370 TRACE_APPEND(("\"%.30s\"", O2S(objResultPtr)));
5371 NEXT_INST_F(9, 1, 1);
5372
5373 case INST_LIST_IN:
5374 case INST_LIST_NOT_IN: /* Basic list containment operators. */
5375 value2Ptr = OBJ_AT_TOS;
5376 valuePtr = OBJ_UNDER_TOS;
5377
5378 s1 = TclGetStringFromObj(valuePtr, &s1len);
5379 TRACE(("\"%.30s\" \"%.30s\" => ", O2S(valuePtr), O2S(value2Ptr)));
5380 if (TclListObjLength(interp, value2Ptr, &length) != TCL_OK) {
5381 TRACE_ERROR(interp);
5382 goto gotError;
5383 }
5384 match = 0;
5385 if (length > 0) {
5386 int i = 0;
5387 Tcl_Obj *o;
5388
5389 /*
5390 * An empty list doesn't match anything.
5391 */
5392
5393 do {
5394 Tcl_ListObjIndex(NULL, value2Ptr, i, &o);
5395 if (o != NULL) {
5396 s2 = TclGetStringFromObj(o, &s2len);
5397 } else {
5398 s2 = "";
5399 s2len = 0;
5400 }
5401 if (s1len == s2len) {
5402 match = (memcmp(s1, s2, s1len) == 0);
5403 }
5404 i++;
5405 } while (i < length && match == 0);
5406 }
5407
5408 if (*pc == INST_LIST_NOT_IN) {
5409 match = !match;
5410 }
5411
5412 TRACE_APPEND(("%d\n", match));
5413
5414 /*
5415 * Peep-hole optimisation: if you're about to jump, do jump from here.
5416 * We're saving the effort of pushing a boolean value only to pop it
5417 * for branching.
5418 */
5419
5420 JUMP_PEEPHOLE_F(match, 1, 2);
5421
5422 case INST_LIST_CONCAT:
5423 value2Ptr = OBJ_AT_TOS;
5424 valuePtr = OBJ_UNDER_TOS;
5425 TRACE(("\"%.30s\" \"%.30s\" => ", O2S(valuePtr), O2S(value2Ptr)));
5426 if (Tcl_IsShared(valuePtr)) {
5427 objResultPtr = Tcl_DuplicateObj(valuePtr);
5428 if (Tcl_ListObjAppendList(interp, objResultPtr,
5429 value2Ptr) != TCL_OK) {
5430 TRACE_ERROR(interp);
5431 TclDecrRefCount(objResultPtr);
5432 goto gotError;
5433 }
5434 TRACE_APPEND(("\"%.30s\"\n", O2S(objResultPtr)));
5435 NEXT_INST_F(1, 2, 1);
5436 } else {
5437 if (Tcl_ListObjAppendList(interp, valuePtr, value2Ptr) != TCL_OK){
5438 TRACE_ERROR(interp);
5439 goto gotError;
5440 }
5441 TRACE_APPEND(("\"%.30s\"\n", O2S(valuePtr)));
5442 NEXT_INST_F(1, 1, 0);
5443 }
5444
5445 /*
5446 * End of INST_LIST and related instructions.
5447 * -----------------------------------------------------------------
5448 * Start of string-related instructions.
5449 */
5450
5451 case INST_STR_EQ:
5452 case INST_STR_NEQ: /* String (in)equality check */
5453 case INST_STR_CMP: /* String compare. */
5454 stringCompare:
5455 value2Ptr = OBJ_AT_TOS;
5456 valuePtr = OBJ_UNDER_TOS;
5457
5458 {
5459 int checkEq = ((*pc == INST_EQ) || (*pc == INST_NEQ)
5460 || (*pc == INST_STR_EQ) || (*pc == INST_STR_NEQ));
5461 match = TclStringCmp(valuePtr, value2Ptr, checkEq, 0, -1);
5462 }
5463
5464 /*
5465 * Make sure only -1,0,1 is returned
5466 * TODO: consider peephole opt.
5467 */
5468
5469 if (*pc != INST_STR_CMP) {
5470 /*
5471 * Take care of the opcodes that goto'ed into here.
5472 */
5473
5474 switch (*pc) {
5475 case INST_STR_EQ:
5476 case INST_EQ:
5477 match = (match == 0);
5478 break;
5479 case INST_STR_NEQ:
5480 case INST_NEQ:
5481 match = (match != 0);
5482 break;
5483 case INST_LT:
5484 match = (match < 0);
5485 break;
5486 case INST_GT:
5487 match = (match > 0);
5488 break;
5489 case INST_LE:
5490 match = (match <= 0);
5491 break;
5492 case INST_GE:
5493 match = (match >= 0);
5494 break;
5495 }
5496 }
5497
5498 TRACE(("\"%.20s\" \"%.20s\" => %d\n", O2S(valuePtr), O2S(value2Ptr),
5499 (match < 0 ? -1 : match > 0 ? 1 : 0)));
5500 JUMP_PEEPHOLE_F(match, 1, 2);
5501
5502 case INST_STR_LEN:
5503 valuePtr = OBJ_AT_TOS;
5504 length = Tcl_GetCharLength(valuePtr);
5505 TclNewIntObj(objResultPtr, length);
5506 TRACE(("\"%.20s\" => %d\n", O2S(valuePtr), length));
5507 NEXT_INST_F(1, 1, 1);
5508
5509 case INST_STR_UPPER:
5510 valuePtr = OBJ_AT_TOS;
5511 TRACE(("\"%.20s\" => ", O2S(valuePtr)));
5512 if (Tcl_IsShared(valuePtr)) {
5513 s1 = TclGetStringFromObj(valuePtr, &length);
5514 TclNewStringObj(objResultPtr, s1, length);
5515 length = Tcl_UtfToUpper(TclGetString(objResultPtr));
5516 Tcl_SetObjLength(objResultPtr, length);
5517 TRACE_APPEND(("\"%.20s\"\n", O2S(objResultPtr)));
5518 NEXT_INST_F(1, 1, 1);
5519 } else {
5520 length = Tcl_UtfToUpper(TclGetString(valuePtr));
5521 Tcl_SetObjLength(valuePtr, length);
5522 TclFreeIntRep(valuePtr);
5523 TRACE_APPEND(("\"%.20s\"\n", O2S(valuePtr)));
5524 NEXT_INST_F(1, 0, 0);
5525 }
5526 case INST_STR_LOWER:
5527 valuePtr = OBJ_AT_TOS;
5528 TRACE(("\"%.20s\" => ", O2S(valuePtr)));
5529 if (Tcl_IsShared(valuePtr)) {
5530 s1 = TclGetStringFromObj(valuePtr, &length);
5531 TclNewStringObj(objResultPtr, s1, length);
5532 length = Tcl_UtfToLower(TclGetString(objResultPtr));
5533 Tcl_SetObjLength(objResultPtr, length);
5534 TRACE_APPEND(("\"%.20s\"\n", O2S(objResultPtr)));
5535 NEXT_INST_F(1, 1, 1);
5536 } else {
5537 length = Tcl_UtfToLower(TclGetString(valuePtr));
5538 Tcl_SetObjLength(valuePtr, length);
5539 TclFreeIntRep(valuePtr);
5540 TRACE_APPEND(("\"%.20s\"\n", O2S(valuePtr)));
5541 NEXT_INST_F(1, 0, 0);
5542 }
5543 case INST_STR_TITLE:
5544 valuePtr = OBJ_AT_TOS;
5545 TRACE(("\"%.20s\" => ", O2S(valuePtr)));
5546 if (Tcl_IsShared(valuePtr)) {
5547 s1 = TclGetStringFromObj(valuePtr, &length);
5548 TclNewStringObj(objResultPtr, s1, length);
5549 length = Tcl_UtfToTitle(TclGetString(objResultPtr));
5550 Tcl_SetObjLength(objResultPtr, length);
5551 TRACE_APPEND(("\"%.20s\"\n", O2S(objResultPtr)));
5552 NEXT_INST_F(1, 1, 1);
5553 } else {
5554 length = Tcl_UtfToTitle(TclGetString(valuePtr));
5555 Tcl_SetObjLength(valuePtr, length);
5556 TclFreeIntRep(valuePtr);
5557 TRACE_APPEND(("\"%.20s\"\n", O2S(valuePtr)));
5558 NEXT_INST_F(1, 0, 0);
5559 }
5560
5561 case INST_STR_INDEX:
5562 value2Ptr = OBJ_AT_TOS;
5563 valuePtr = OBJ_UNDER_TOS;
5564 TRACE(("\"%.20s\" %.20s => ", O2S(valuePtr), O2S(value2Ptr)));
5565
5566 /*
5567 * Get char length to calculate what 'end' means.
5568 */
5569
5570 length = Tcl_GetCharLength(valuePtr);
5571 if (TclGetIntForIndexM(interp, value2Ptr, length-1, &index)!=TCL_OK) {
5572 TRACE_ERROR(interp);
5573 goto gotError;
5574 }
5575
5576 if ((index < 0) || (index >= length)) {
5577 TclNewObj(objResultPtr);
5578 } else if (TclIsPureByteArray(valuePtr)) {
5579 objResultPtr = Tcl_NewByteArrayObj(
5580 Tcl_GetByteArrayFromObj(valuePtr, NULL)+index, 1);
5581 } else if (valuePtr->bytes && length == valuePtr->length) {
5582 objResultPtr = Tcl_NewStringObj((const char *)
5583 valuePtr->bytes+index, 1);
5584 } else {
5585 char buf[8] = "";
5586 int ch = TclGetUCS4(valuePtr, index);
5587
5588 length = TclUCS4ToUtf(ch, buf);
5589 objResultPtr = Tcl_NewStringObj(buf, length);
5590 }
5591
5592 TRACE_APPEND(("\"%s\"\n", O2S(objResultPtr)));
5593 NEXT_INST_F(1, 2, 1);
5594
5595 case INST_STR_RANGE:
5596 TRACE(("\"%.20s\" %.20s %.20s =>",
5597 O2S(OBJ_AT_DEPTH(2)), O2S(OBJ_UNDER_TOS), O2S(OBJ_AT_TOS)));
5598 length = Tcl_GetCharLength(OBJ_AT_DEPTH(2)) - 1;
5599 if (TclGetIntForIndexM(interp, OBJ_UNDER_TOS, length,
5600 &fromIdx) != TCL_OK
5601 || TclGetIntForIndexM(interp, OBJ_AT_TOS, length,
5602 &toIdx) != TCL_OK) {
5603 TRACE_ERROR(interp);
5604 goto gotError;
5605 }
5606
5607 if (fromIdx < 0) {
5608 fromIdx = 0;
5609 }
5610 if (toIdx >= length) {
5611 toIdx = length;
5612 }
5613 if (toIdx >= fromIdx) {
5614 objResultPtr = Tcl_GetRange(OBJ_AT_DEPTH(2), fromIdx, toIdx);
5615 } else {
5616 TclNewObj(objResultPtr);
5617 }
5618 TRACE_APPEND(("\"%.30s\"\n", O2S(objResultPtr)));
5619 NEXT_INST_V(1, 3, 1);
5620
5621 case INST_STR_RANGE_IMM:
5622 valuePtr = OBJ_AT_TOS;
5623 fromIdx = TclGetInt4AtPtr(pc+1);
5624 toIdx = TclGetInt4AtPtr(pc+5);
5625 length = Tcl_GetCharLength(valuePtr);
5626 TRACE(("\"%.20s\" %d %d => ", O2S(valuePtr), fromIdx, toIdx));
5627
5628 /* Every range of an empty value is an empty value */
5629 if (length == 0) {
5630 TRACE_APPEND(("\n"));
5631 NEXT_INST_F(9, 0, 0);
5632 }
5633
5634 /* Decode index operands. */
5635
5636 /*
5637 assert ( toIdx != TCL_INDEX_BEFORE );
5638 assert ( toIdx != TCL_INDEX_AFTER);
5639 *
5640 * Extra safety for legacy bytecodes:
5641 */
5642 if (toIdx == TCL_INDEX_BEFORE) {
5643 goto emptyRange;
5644 }
5645 if (toIdx == TCL_INDEX_AFTER) {
5646 toIdx = TCL_INDEX_END;
5647 }
5648
5649 toIdx = TclIndexDecode(toIdx, length - 1);
5650 if (toIdx < 0) {
5651 goto emptyRange;
5652 } else if (toIdx >= length) {
5653 toIdx = length - 1;
5654 }
5655
5656 assert ( toIdx >= 0 && toIdx < length );
5657
5658 /*
5659 assert ( fromIdx != TCL_INDEX_BEFORE );
5660 assert ( fromIdx != TCL_INDEX_AFTER);
5661 *
5662 * Extra safety for legacy bytecodes:
5663 */
5664 if (fromIdx == TCL_INDEX_BEFORE) {
5665 fromIdx = TCL_INDEX_START;
5666 }
5667 if (fromIdx == TCL_INDEX_AFTER) {
5668 goto emptyRange;
5669 }
5670
5671 fromIdx = TclIndexDecode(fromIdx, length - 1);
5672 if (fromIdx < 0) {
5673 fromIdx = 0;
5674 }
5675
5676 if (fromIdx <= toIdx) {
5677 objResultPtr = Tcl_GetRange(valuePtr, fromIdx, toIdx);
5678 } else {
5679 emptyRange:
5680 TclNewObj(objResultPtr);
5681 }
5682 TRACE_APPEND(("%.30s\n", O2S(objResultPtr)));
5683 NEXT_INST_F(9, 1, 1);
5684
5685 {
5686 Tcl_UniChar *ustring1, *ustring2, *ustring3, *end, *p;
5687 int length3, endIdx;
5688 Tcl_Obj *value3Ptr;
5689
5690 case INST_STR_REPLACE:
5691 value3Ptr = POP_OBJECT();
5692 valuePtr = OBJ_AT_DEPTH(2);
5693 endIdx = Tcl_GetCharLength(valuePtr) - 1;
5694 TRACE(("\"%.20s\" %s %s \"%.20s\" => ", O2S(valuePtr),
5695 O2S(OBJ_UNDER_TOS), O2S(OBJ_AT_TOS), O2S(value3Ptr)));
5696 if (TclGetIntForIndexM(interp, OBJ_UNDER_TOS, endIdx,
5697 &fromIdx) != TCL_OK
5698 || TclGetIntForIndexM(interp, OBJ_AT_TOS, endIdx,
5699 &toIdx) != TCL_OK) {
5700 TclDecrRefCount(value3Ptr);
5701 TRACE_ERROR(interp);
5702 goto gotError;
5703 }
5704 TclDecrRefCount(OBJ_AT_TOS);
5705 (void) POP_OBJECT();
5706 TclDecrRefCount(OBJ_AT_TOS);
5707 (void) POP_OBJECT();
5708
5709 if ((toIdx < 0) ||
5710 (fromIdx > endIdx) ||
5711 (toIdx < fromIdx)) {
5712 TRACE_APPEND(("\"%.30s\"\n", O2S(valuePtr)));
5713 TclDecrRefCount(value3Ptr);
5714 NEXT_INST_F(1, 0, 0);
5715 }
5716
5717 if (fromIdx < 0) {
5718 fromIdx = 0;
5719 }
5720
5721 if (toIdx > endIdx) {
5722 toIdx = endIdx;
5723 }
5724
5725 if (fromIdx == 0 && toIdx == endIdx) {
5726 TclDecrRefCount(OBJ_AT_TOS);
5727 OBJ_AT_TOS = value3Ptr;
5728 TRACE_APPEND(("\"%.30s\"\n", O2S(value3Ptr)));
5729 NEXT_INST_F(1, 0, 0);
5730 }
5731
5732 length3 = Tcl_GetCharLength(value3Ptr);
5733
5734 /*
5735 * See if we can splice in place. This happens when the number of
5736 * characters being replaced is the same as the number of characters
5737 * in the string to be inserted.
5738 */
5739
5740 if (length3 - 1 == toIdx - fromIdx) {
5741 unsigned char *bytes1, *bytes2;
5742
5743 if (Tcl_IsShared(valuePtr)) {
5744 objResultPtr = Tcl_DuplicateObj(valuePtr);
5745 } else {
5746 objResultPtr = valuePtr;
5747 }
5748 if (TclIsPureByteArray(objResultPtr)
5749 && TclIsPureByteArray(value3Ptr)) {
5750 bytes1 = Tcl_GetByteArrayFromObj(objResultPtr, NULL);
5751 bytes2 = Tcl_GetByteArrayFromObj(value3Ptr, NULL);
5752 memcpy(bytes1 + fromIdx, bytes2, length3);
5753 } else {
5754 ustring1 = Tcl_GetUnicodeFromObj(objResultPtr, NULL);
5755 ustring2 = Tcl_GetUnicodeFromObj(value3Ptr, NULL);
5756 memcpy(ustring1 + fromIdx, ustring2,
5757 length3 * sizeof(Tcl_UniChar));
5758 }
5759 Tcl_InvalidateStringRep(objResultPtr);
5760 TclDecrRefCount(value3Ptr);
5761 TRACE_APPEND(("\"%.30s\"\n", O2S(objResultPtr)));
5762 if (objResultPtr == valuePtr) {
5763 NEXT_INST_F(1, 0, 0);
5764 } else {
5765 NEXT_INST_F(1, 1, 1);
5766 }
5767 }
5768
5769 /*
5770 * Get the Unicode representation; this is where we guarantee to lose
5771 * bytearrays.
5772 */
5773
5774 ustring1 = Tcl_GetUnicodeFromObj(valuePtr, &length);
5775 length--;
5776
5777 /*
5778 * Remove substring using copying.
5779 */
5780
5781 objResultPtr = NULL;
5782 if (fromIdx > 0) {
5783 objResultPtr = Tcl_NewUnicodeObj(ustring1, fromIdx);
5784 }
5785 if (length3 > 0) {
5786 if (objResultPtr) {
5787 Tcl_AppendObjToObj(objResultPtr, value3Ptr);
5788 } else if (Tcl_IsShared(value3Ptr)) {
5789 objResultPtr = Tcl_DuplicateObj(value3Ptr);
5790 } else {
5791 objResultPtr = value3Ptr;
5792 }
5793 }
5794 if (toIdx < length) {
5795 if (objResultPtr) {
5796 Tcl_AppendUnicodeToObj(objResultPtr, ustring1 + toIdx + 1,
5797 length - toIdx);
5798 } else {
5799 objResultPtr = Tcl_NewUnicodeObj(ustring1 + toIdx + 1,
5800 length - toIdx);
5801 }
5802 }
5803 if (objResultPtr == NULL) {
5804 /* This has to be the case [string replace $s 0 end {}] */
5805 /* which has result {} which is same as value3Ptr. */
5806 objResultPtr = value3Ptr;
5807 }
5808 if (objResultPtr == value3Ptr) {
5809 /* See [Bug 82e7f67325] */
5810 TclDecrRefCount(OBJ_AT_TOS);
5811 OBJ_AT_TOS = value3Ptr;
5812 TRACE_APPEND(("\"%.30s\"\n", O2S(value3Ptr)));
5813 NEXT_INST_F(1, 0, 0);
5814 }
5815 TclDecrRefCount(value3Ptr);
5816 TRACE_APPEND(("\"%.30s\"\n", O2S(objResultPtr)));
5817 NEXT_INST_F(1, 1, 1);
5818
5819 case INST_STR_MAP:
5820 valuePtr = OBJ_AT_TOS; /* "Main" string. */
5821 value3Ptr = OBJ_UNDER_TOS; /* "Target" string. */
5822 value2Ptr = OBJ_AT_DEPTH(2); /* "Source" string. */
5823 if (value3Ptr == value2Ptr) {
5824 objResultPtr = valuePtr;
5825 goto doneStringMap;
5826 } else if (valuePtr == value2Ptr) {
5827 objResultPtr = value3Ptr;
5828 goto doneStringMap;
5829 }
5830 ustring1 = Tcl_GetUnicodeFromObj(valuePtr, &length);
5831 if (length == 0) {
5832 objResultPtr = valuePtr;
5833 goto doneStringMap;
5834 }
5835 ustring2 = Tcl_GetUnicodeFromObj(value2Ptr, &length2);
5836 if (length2 > length || length2 == 0) {
5837 objResultPtr = valuePtr;
5838 goto doneStringMap;
5839 } else if (length2 == length) {
5840 if (memcmp(ustring1, ustring2, sizeof(Tcl_UniChar) * length)) {
5841 objResultPtr = valuePtr;
5842 } else {
5843 objResultPtr = value3Ptr;
5844 }
5845 goto doneStringMap;
5846 }
5847 ustring3 = Tcl_GetUnicodeFromObj(value3Ptr, &length3);
5848
5849 objResultPtr = Tcl_NewUnicodeObj(ustring1, 0);
5850 p = ustring1;
5851 end = ustring1 + length;
5852 for (; ustring1 < end; ustring1++) {
5853 if ((*ustring1 == *ustring2) &&
5854 /* Fix bug [69218ab7b]: restrict max compare length. */
5855 (end-ustring1 >= length2) && (length2==1 ||
5856 memcmp(ustring1, ustring2, sizeof(Tcl_UniChar) * length2)
5857 == 0)) {
5858 if (p != ustring1) {
5859 Tcl_AppendUnicodeToObj(objResultPtr, p, ustring1-p);
5860 p = ustring1 + length2;
5861 } else {
5862 p += length2;
5863 }
5864 ustring1 = p - 1;
5865
5866 Tcl_AppendUnicodeToObj(objResultPtr, ustring3, length3);
5867 }
5868 }
5869 if (p != ustring1) {
5870 /*
5871 * Put the rest of the unmapped chars onto result.
5872 */
5873
5874 Tcl_AppendUnicodeToObj(objResultPtr, p, ustring1 - p);
5875 }
5876 doneStringMap:
5877 TRACE_WITH_OBJ(("%.20s %.20s %.20s => ",
5878 O2S(value2Ptr), O2S(value3Ptr), O2S(valuePtr)), objResultPtr);
5879 NEXT_INST_V(1, 3, 1);
5880
5881 case INST_STR_FIND:
5882 ustring1 = Tcl_GetUnicodeFromObj(OBJ_AT_TOS, &length); /* Haystack */
5883 ustring2 = Tcl_GetUnicodeFromObj(OBJ_UNDER_TOS, &length2);/* Needle */
5884
5885 match = -1;
5886 if (length2 > 0 && length2 <= length) {
5887 end = ustring1 + length - length2 + 1;
5888 for (p=ustring1 ; p<end ; p++) {
5889 if ((*p == *ustring2) &&
5890 memcmp(ustring2,p,sizeof(Tcl_UniChar)*length2) == 0) {
5891 match = p - ustring1;
5892 break;
5893 }
5894 }
5895 }
5896
5897 TRACE(("%.20s %.20s => %d\n",
5898 O2S(OBJ_UNDER_TOS), O2S(OBJ_AT_TOS), match));
5899 TclNewIntObj(objResultPtr, match);
5900 NEXT_INST_F(1, 2, 1);
5901
5902 case INST_STR_FIND_LAST:
5903 ustring1 = Tcl_GetUnicodeFromObj(OBJ_AT_TOS, &length); /* Haystack */
5904 ustring2 = Tcl_GetUnicodeFromObj(OBJ_UNDER_TOS, &length2);/* Needle */
5905
5906 match = -1;
5907 if (length2 > 0 && length2 <= length) {
5908 for (p=ustring1+length-length2 ; p>=ustring1 ; p--) {
5909 if ((*p == *ustring2) &&
5910 memcmp(ustring2,p,sizeof(Tcl_UniChar)*length2) == 0) {
5911 match = p - ustring1;
5912 break;
5913 }
5914 }
5915 }
5916
5917 TRACE(("%.20s %.20s => %d\n",
5918 O2S(OBJ_UNDER_TOS), O2S(OBJ_AT_TOS), match));
5919
5920 TclNewIntObj(objResultPtr, match);
5921 NEXT_INST_F(1, 2, 1);
5922
5923 case INST_STR_CLASS:
5924 opnd = TclGetInt1AtPtr(pc+1);
5925 valuePtr = OBJ_AT_TOS;
5926 TRACE(("%s \"%.30s\" => ", tclStringClassTable[opnd].name,
5927 O2S(valuePtr)));
5928 ustring1 = Tcl_GetUnicodeFromObj(valuePtr, &length);
5929 match = 1;
5930 if (length > 0) {
5931 int ch;
5932 end = ustring1 + length;
5933 for (p=ustring1 ; p<end ; ) {
5934 p += TclUniCharToUCS4(p, &ch);
5935 if (!tclStringClassTable[opnd].comparator(ch)) {
5936 match = 0;
5937 break;
5938 }
5939 }
5940 }
5941 TRACE_APPEND(("%d\n", match));
5942 JUMP_PEEPHOLE_F(match, 2, 1);
5943 }
5944
5945 case INST_STR_MATCH:
5946 nocase = TclGetInt1AtPtr(pc+1);
5947 valuePtr = OBJ_AT_TOS; /* String */
5948 value2Ptr = OBJ_UNDER_TOS; /* Pattern */
5949
5950 /*
5951 * Check that at least one of the objects is Unicode before promoting
5952 * both.
5953 */
5954
5955 if ((valuePtr->typePtr == &tclStringType)
5956 || (value2Ptr->typePtr == &tclStringType)) {
5957 Tcl_UniChar *ustring1, *ustring2;
5958
5959 ustring1 = Tcl_GetUnicodeFromObj(valuePtr, &length);
5960 ustring2 = Tcl_GetUnicodeFromObj(value2Ptr, &length2);
5961 match = TclUniCharMatch(ustring1, length, ustring2, length2,
5962 nocase);
5963 } else if (TclIsPureByteArray(valuePtr) && !nocase) {
5964 unsigned char *bytes1, *bytes2;
5965
5966 bytes1 = Tcl_GetByteArrayFromObj(valuePtr, &length);
5967 bytes2 = Tcl_GetByteArrayFromObj(value2Ptr, &length2);
5968 match = TclByteArrayMatch(bytes1, length, bytes2, length2, 0);
5969 } else {
5970 match = Tcl_StringCaseMatch(TclGetString(valuePtr),
5971 TclGetString(value2Ptr), nocase);
5972 }
5973
5974 /*
5975 * Reuse value2Ptr object already on stack if possible. Adjustment is
5976 * 2 due to the nocase byte
5977 */
5978
5979 TRACE(("%.20s %.20s => %d\n", O2S(valuePtr), O2S(value2Ptr), match));
5980
5981 /*
5982 * Peep-hole optimisation: if you're about to jump, do jump from here.
5983 */
5984
5985 JUMP_PEEPHOLE_F(match, 2, 2);
5986
5987 {
5988 const char *string1, *string2;
5989 int trim1, trim2;
5990
5991 case INST_STR_TRIM_LEFT:
5992 valuePtr = OBJ_UNDER_TOS; /* String */
5993 value2Ptr = OBJ_AT_TOS; /* TrimSet */
5994 string2 = TclGetStringFromObj(value2Ptr, &length2);
5995 string1 = TclGetStringFromObj(valuePtr, &length);
5996 trim1 = TclTrimLeft(string1, length, string2, length2);
5997 trim2 = 0;
5998 goto createTrimmedString;
5999 case INST_STR_TRIM_RIGHT:
6000 valuePtr = OBJ_UNDER_TOS; /* String */
6001 value2Ptr = OBJ_AT_TOS; /* TrimSet */
6002 string2 = TclGetStringFromObj(value2Ptr, &length2);
6003 string1 = TclGetStringFromObj(valuePtr, &length);
6004 trim2 = TclTrimRight(string1, length, string2, length2);
6005 trim1 = 0;
6006 goto createTrimmedString;
6007 case INST_STR_TRIM:
6008 valuePtr = OBJ_UNDER_TOS; /* String */
6009 value2Ptr = OBJ_AT_TOS; /* TrimSet */
6010 string2 = TclGetStringFromObj(value2Ptr, &length2);
6011 string1 = TclGetStringFromObj(valuePtr, &length);
6012 trim1 = TclTrim(string1, length, string2, length2, &trim2);
6013 createTrimmedString:
6014 /*
6015 * Careful here; trim set often contains non-ASCII characters so we
6016 * take care when printing. [Bug 971cb4f1db]
6017 */
6018
6019 #ifdef TCL_COMPILE_DEBUG
6020 if (traceInstructions) {
6021 TRACE(("\"%.30s\" ", O2S(valuePtr)));
6022 TclPrintObject(stdout, value2Ptr, 30);
6023 printf(" => ");
6024 }
6025 #endif
6026 if (trim1 == 0 && trim2 == 0) {
6027 #ifdef TCL_COMPILE_DEBUG
6028 if (traceInstructions) {
6029 TclPrintObject(stdout, valuePtr, 30);
6030 printf("\n");
6031 }
6032 #endif
6033 NEXT_INST_F(1, 1, 0);
6034 } else {
6035 objResultPtr = Tcl_NewStringObj(string1+trim1, length-trim1-trim2);
6036 #ifdef TCL_COMPILE_DEBUG
6037 if (traceInstructions) {
6038 TclPrintObject(stdout, objResultPtr, 30);
6039 printf("\n");
6040 }
6041 #endif
6042 NEXT_INST_F(1, 2, 1);
6043 }
6044 }
6045
6046 case INST_REGEXP:
6047 cflags = TclGetInt1AtPtr(pc+1); /* RE compile flages like NOCASE */
6048 valuePtr = OBJ_AT_TOS; /* String */
6049 value2Ptr = OBJ_UNDER_TOS; /* Pattern */
6050 TRACE(("\"%.30s\" \"%.30s\" => ", O2S(valuePtr), O2S(value2Ptr)));
6051
6052 /*
6053 * Compile and match the regular expression.
6054 */
6055
6056 {
6057 Tcl_RegExp regExpr =
6058 Tcl_GetRegExpFromObj(interp, value2Ptr, cflags);
6059
6060 if (regExpr == NULL) {
6061 TRACE_ERROR(interp);
6062 goto gotError;
6063 }
6064 match = Tcl_RegExpExecObj(interp, regExpr, valuePtr, 0, 0, 0);
6065 if (match < 0) {
6066 TRACE_ERROR(interp);
6067 goto gotError;
6068 }
6069 }
6070
6071 TRACE_APPEND(("%d\n", match));
6072
6073 /*
6074 * Peep-hole optimisation: if you're about to jump, do jump from here.
6075 * Adjustment is 2 due to the nocase byte.
6076 */
6077
6078 JUMP_PEEPHOLE_F(match, 2, 2);
6079 }
6080
6081 /*
6082 * End of string-related instructions.
6083 * -----------------------------------------------------------------
6084 * Start of numeric operator instructions.
6085 */
6086
6087 {
6088 ClientData ptr1, ptr2;
6089 int type1, type2;
6090 long l1 = 0, l2, lResult;
6091
6092 case INST_NUM_TYPE:
6093 if (GetNumberFromObj(NULL, OBJ_AT_TOS, &ptr1, &type1) != TCL_OK) {
6094 type1 = 0;
6095 } else if (type1 == TCL_NUMBER_LONG) {
6096 /* value is between LONG_MIN and LONG_MAX */
6097 /* [string is integer] is -UINT_MAX to UINT_MAX range */
6098 int i;
6099
6100 if (TclGetIntFromObj(NULL, OBJ_AT_TOS, &i) != TCL_OK) {
6101 type1 = TCL_NUMBER_WIDE;
6102 }
6103 #ifndef TCL_WIDE_INT_IS_LONG
6104 } else if (type1 == TCL_NUMBER_WIDE) {
6105 /* value is between WIDE_MIN and WIDE_MAX */
6106 /* [string is wideinteger] is -UWIDE_MAX to UWIDE_MAX range */
6107 int i;
6108 if (TclGetIntFromObj(NULL, OBJ_AT_TOS, &i) == TCL_OK) {
6109 type1 = TCL_NUMBER_LONG;
6110 }
6111 #endif
6112 } else if (type1 == TCL_NUMBER_BIG) {
6113 /* value is an integer outside the WIDE_MIN to WIDE_MAX range */
6114 /* [string is wideinteger] is -UWIDE_MAX to UWIDE_MAX range */
6115 Tcl_WideInt w;
6116
6117 if (TclGetWideIntFromObj(NULL, OBJ_AT_TOS, &w) == TCL_OK) {
6118 type1 = TCL_NUMBER_WIDE;
6119 }
6120 }
6121 TclNewIntObj(objResultPtr, type1);
6122 TRACE(("\"%.20s\" => %d\n", O2S(OBJ_AT_TOS), type1));
6123 NEXT_INST_F(1, 1, 1);
6124
6125 case INST_EQ:
6126 case INST_NEQ:
6127 case INST_LT:
6128 case INST_GT:
6129 case INST_LE:
6130 case INST_GE: {
6131 int iResult = 0, compare = 0;
6132
6133 value2Ptr = OBJ_AT_TOS;
6134 valuePtr = OBJ_UNDER_TOS;
6135
6136 /*
6137 Try to determine, without triggering generation of a string
6138 representation, whether one value is not a number.
6139 */
6140 if (TclCheckEmptyString(valuePtr) > 0 || TclCheckEmptyString(value2Ptr) > 0) {
6141 goto stringCompare;
6142 }
6143
6144 if (GetNumberFromObj(NULL, valuePtr, &ptr1, &type1) != TCL_OK
6145 || GetNumberFromObj(NULL, value2Ptr, &ptr2, &type2) != TCL_OK) {
6146 /*
6147 * At least one non-numeric argument - compare as strings.
6148 */
6149
6150 goto stringCompare;
6151 }
6152 if (type1 == TCL_NUMBER_NAN || type2 == TCL_NUMBER_NAN) {
6153 /*
6154 * NaN arg: NaN != to everything, other compares are false.
6155 */
6156
6157 iResult = (*pc == INST_NEQ);
6158 goto foundResult;
6159 }
6160 if (valuePtr == value2Ptr) {
6161 compare = MP_EQ;
6162 goto convertComparison;
6163 }
6164 if ((type1 == TCL_NUMBER_LONG) && (type2 == TCL_NUMBER_LONG)) {
6165 l1 = *((const long *)ptr1);
6166 l2 = *((const long *)ptr2);
6167 compare = (l1 < l2) ? MP_LT : ((l1 > l2) ? MP_GT : MP_EQ);
6168 } else {
6169 compare = CompareTwoNumbers(valuePtr, value2Ptr);
6170 }
6171
6172 /*
6173 * Turn comparison outcome into appropriate result for opcode.
6174 */
6175
6176 convertComparison:
6177 switch (*pc) {
6178 case INST_EQ:
6179 iResult = (compare == MP_EQ);
6180 break;
6181 case INST_NEQ:
6182 iResult = (compare != MP_EQ);
6183 break;
6184 case INST_LT:
6185 iResult = (compare == MP_LT);
6186 break;
6187 case INST_GT:
6188 iResult = (compare == MP_GT);
6189 break;
6190 case INST_LE:
6191 iResult = (compare != MP_GT);
6192 break;
6193 case INST_GE:
6194 iResult = (compare != MP_LT);
6195 break;
6196 }
6197
6198 /*
6199 * Peep-hole optimisation: if you're about to jump, do jump from here.
6200 */
6201
6202 foundResult:
6203 TRACE(("\"%.20s\" \"%.20s\" => %d\n", O2S(valuePtr), O2S(value2Ptr),
6204 iResult));
6205 JUMP_PEEPHOLE_F(iResult, 1, 2);
6206 }
6207
6208 case INST_MOD:
6209 case INST_LSHIFT:
6210 case INST_RSHIFT:
6211 case INST_BITOR:
6212 case INST_BITXOR:
6213 case INST_BITAND:
6214 value2Ptr = OBJ_AT_TOS;
6215 valuePtr = OBJ_UNDER_TOS;
6216
6217 if ((GetNumberFromObj(NULL, valuePtr, &ptr1, &type1) != TCL_OK)
6218 || (type1==TCL_NUMBER_DOUBLE) || (type1==TCL_NUMBER_NAN)) {
6219 TRACE(("%.20s %.20s => ILLEGAL 1st TYPE %s\n", O2S(valuePtr),
6220 O2S(value2Ptr), (valuePtr->typePtr?
6221 valuePtr->typePtr->name : "null")));
6222 DECACHE_STACK_INFO();
6223 IllegalExprOperandType(interp, pc, valuePtr);
6224 CACHE_STACK_INFO();
6225 goto gotError;
6226 }
6227
6228 if ((GetNumberFromObj(NULL, value2Ptr, &ptr2, &type2) != TCL_OK)
6229 || (type2==TCL_NUMBER_DOUBLE) || (type2==TCL_NUMBER_NAN)) {
6230 TRACE(("%.20s %.20s => ILLEGAL 2nd TYPE %s\n", O2S(valuePtr),
6231 O2S(value2Ptr), (value2Ptr->typePtr?
6232 value2Ptr->typePtr->name : "null")));
6233 DECACHE_STACK_INFO();
6234 IllegalExprOperandType(interp, pc, value2Ptr);
6235 CACHE_STACK_INFO();
6236 goto gotError;
6237 }
6238
6239 /*
6240 * Check for common, simple case.
6241 */
6242
6243 if ((type1 == TCL_NUMBER_LONG) && (type2 == TCL_NUMBER_LONG)) {
6244 l1 = *((const long *)ptr1);
6245 l2 = *((const long *)ptr2);
6246
6247 switch (*pc) {
6248 case INST_MOD:
6249 if (l2 == 0) {
6250 TRACE(("%s %s => DIVIDE BY ZERO\n", O2S(valuePtr),
6251 O2S(value2Ptr)));
6252 goto divideByZero;
6253 } else if ((l2 == 1) || (l2 == -1)) {
6254 /*
6255 * Div. by |1| always yields remainder of 0.
6256 */
6257
6258 TRACE(("%s %s => ", O2S(valuePtr), O2S(value2Ptr)));
6259 objResultPtr = TCONST(0);
6260 TRACE(("%s\n", O2S(objResultPtr)));
6261 NEXT_INST_F(1, 2, 1);
6262 } else if (l1 == 0) {
6263 /*
6264 * 0 % (non-zero) always yields remainder of 0.
6265 */
6266
6267 TRACE(("%s %s => ", O2S(valuePtr), O2S(value2Ptr)));
6268 objResultPtr = TCONST(0);
6269 TRACE(("%s\n", O2S(objResultPtr)));
6270 NEXT_INST_F(1, 2, 1);
6271 } else {
6272 lResult = l1 / l2;
6273
6274 /*
6275 * Force Tcl's integer division rules.
6276 * TODO: examine for logic simplification
6277 */
6278
6279 if ((lResult < 0 || (lResult == 0 &&
6280 ((l1 < 0 && l2 > 0) || (l1 > 0 && l2 < 0)))) &&
6281 (lResult * l2 != l1)) {
6282 lResult -= 1;
6283 }
6284 lResult = (long)((unsigned long)l1 -
6285 (unsigned long)l2*(unsigned long)lResult);
6286 goto longResultOfArithmetic;
6287 }
6288 break;
6289
6290 case INST_RSHIFT:
6291 if (l2 < 0) {
6292 Tcl_SetObjResult(interp, Tcl_NewStringObj(
6293 "negative shift argument", -1));
6294 #ifdef ERROR_CODE_FOR_EARLY_DETECTED_ARITH_ERROR
6295 DECACHE_STACK_INFO();
6296 Tcl_SetErrorCode(interp, "ARITH", "DOMAIN",
6297 "domain error: argument not in valid range",
6298 (char *)NULL);
6299 CACHE_STACK_INFO();
6300 #endif /* ERROR_CODE_FOR_EARLY_DETECTED_ARITH_ERROR */
6301 goto gotError;
6302 } else if (l1 == 0) {
6303 TRACE(("%s %s => ", O2S(valuePtr), O2S(value2Ptr)));
6304 objResultPtr = TCONST(0);
6305 TRACE(("%s\n", O2S(objResultPtr)));
6306 NEXT_INST_F(1, 2, 1);
6307 } else {
6308 /*
6309 * Quickly force large right shifts to 0 or -1.
6310 */
6311
6312 if (l2 >= (long)(CHAR_BIT*sizeof(l1))) {
6313 /*
6314 * We assume that INT_MAX is much larger than the
6315 * number of bits in a long. This is a pretty safe
6316 * assumption, given that the former is usually around
6317 * 4e9 and the latter 32 or 64...
6318 */
6319
6320 TRACE(("%s %s => ", O2S(valuePtr), O2S(value2Ptr)));
6321 if (l1 > 0L) {
6322 objResultPtr = TCONST(0);
6323 } else {
6324 TclNewIntObj(objResultPtr, -1);
6325 }
6326 TRACE(("%s\n", O2S(objResultPtr)));
6327 NEXT_INST_F(1, 2, 1);
6328 }
6329
6330 /*
6331 * Handle shifts within the native long range.
6332 */
6333
6334 lResult = l1 >> ((int) l2);
6335 goto longResultOfArithmetic;
6336 }
6337 break;
6338
6339 case INST_LSHIFT:
6340 if (l2 < 0) {
6341 Tcl_SetObjResult(interp, Tcl_NewStringObj(
6342 "negative shift argument", -1));
6343 #ifdef ERROR_CODE_FOR_EARLY_DETECTED_ARITH_ERROR
6344 DECACHE_STACK_INFO();
6345 Tcl_SetErrorCode(interp, "ARITH", "DOMAIN",
6346 "domain error: argument not in valid range",
6347 (char *)NULL);
6348 CACHE_STACK_INFO();
6349 #endif /* ERROR_CODE_FOR_EARLY_DETECTED_ARITH_ERROR */
6350 goto gotError;
6351 } else if (l1 == 0) {
6352 TRACE(("%s %s => ", O2S(valuePtr), O2S(value2Ptr)));
6353 objResultPtr = TCONST(0);
6354 TRACE(("%s\n", O2S(objResultPtr)));
6355 NEXT_INST_F(1, 2, 1);
6356 } else if (l2 > (long) INT_MAX) {
6357 /*
6358 * Technically, we could hold the value (1 << (INT_MAX+1))
6359 * in an mp_int, but since we're using mp_mul_2d() to do
6360 * the work, and it takes only an int argument, that's a
6361 * good place to draw the line.
6362 */
6363
6364 Tcl_SetObjResult(interp, Tcl_NewStringObj(
6365 "integer value too large to represent", -1));
6366 #ifdef ERROR_CODE_FOR_EARLY_DETECTED_ARITH_ERROR
6367 DECACHE_STACK_INFO();
6368 Tcl_SetErrorCode(interp, "ARITH", "IOVERFLOW",
6369 "integer value too large to represent", (char *)NULL);
6370 CACHE_STACK_INFO();
6371 #endif /* ERROR_CODE_FOR_EARLY_DETECTED_ARITH_ERROR */
6372 goto gotError;
6373 } else {
6374 int shift = (int) l2;
6375
6376 /*
6377 * Handle shifts within the native long range.
6378 */
6379
6380 if (((size_t) shift < CHAR_BIT*sizeof(l1))
6381 && !((l1>0 ? l1 : ~l1) &
6382 -(1UL<<(CHAR_BIT*sizeof(l1) - 1 - shift)))) {
6383 lResult = (unsigned long)l1 << shift;
6384 goto longResultOfArithmetic;
6385 }
6386 }
6387
6388 /*
6389 * Too large; need to use the broken-out function.
6390 */
6391
6392 TRACE(("%s %s => ", O2S(valuePtr), O2S(value2Ptr)));
6393 break;
6394
6395 case INST_BITAND:
6396 lResult = l1 & l2;
6397 goto longResultOfArithmetic;
6398 case INST_BITOR:
6399 lResult = l1 | l2;
6400 goto longResultOfArithmetic;
6401 case INST_BITXOR:
6402 lResult = l1 ^ l2;
6403 longResultOfArithmetic:
6404 TRACE(("%s %s => ", O2S(valuePtr), O2S(value2Ptr)));
6405 if (Tcl_IsShared(valuePtr)) {
6406 TclNewLongObj(objResultPtr, lResult);
6407 TRACE(("%s\n", O2S(objResultPtr)));
6408 NEXT_INST_F(1, 2, 1);
6409 }
6410 TclSetLongObj(valuePtr, lResult);
6411 TRACE(("%s\n", O2S(valuePtr)));
6412 NEXT_INST_F(1, 1, 0);
6413 }
6414 }
6415
6416 /*
6417 * DO NOT MERGE THIS WITH THE EQUIVALENT SECTION LATER! That would
6418 * encourage the compiler to inline ExecuteExtendedBinaryMathOp, which
6419 * is highly undesirable due to the overall impact on size.
6420 */
6421
6422 TRACE(("%s %s => ", O2S(valuePtr), O2S(value2Ptr)));
6423 objResultPtr = ExecuteExtendedBinaryMathOp(interp, *pc, &TCONST(0),
6424 valuePtr, value2Ptr);
6425 if (objResultPtr == DIVIDED_BY_ZERO) {
6426 TRACE_APPEND(("DIVIDE BY ZERO\n"));
6427 goto divideByZero;
6428 } else if (objResultPtr == GENERAL_ARITHMETIC_ERROR) {
6429 TRACE_ERROR(interp);
6430 goto gotError;
6431 } else if (objResultPtr == NULL) {
6432 TRACE_APPEND(("%s\n", O2S(valuePtr)));
6433 NEXT_INST_F(1, 1, 0);
6434 } else {
6435 TRACE_APPEND(("%s\n", O2S(objResultPtr)));
6436 NEXT_INST_F(1, 2, 1);
6437 }
6438
6439 case INST_EXPON:
6440 case INST_ADD:
6441 case INST_SUB:
6442 case INST_DIV:
6443 case INST_MULT:
6444 value2Ptr = OBJ_AT_TOS;
6445 valuePtr = OBJ_UNDER_TOS;
6446
6447 if ((GetNumberFromObj(NULL, valuePtr, &ptr1, &type1) != TCL_OK)
6448 || IsErroringNaNType(type1)) {
6449 TRACE(("%.20s %.20s => ILLEGAL 1st TYPE %s\n",
6450 O2S(value2Ptr), O2S(valuePtr),
6451 (valuePtr->typePtr? valuePtr->typePtr->name: "null")));
6452 DECACHE_STACK_INFO();
6453 IllegalExprOperandType(interp, pc, valuePtr);
6454 CACHE_STACK_INFO();
6455 goto gotError;
6456 }
6457
6458 #ifdef ACCEPT_NAN
6459 if (type1 == TCL_NUMBER_NAN) {
6460 /*
6461 * NaN first argument -> result is also NaN.
6462 */
6463
6464 NEXT_INST_F(1, 1, 0);
6465 }
6466 #endif
6467
6468 if ((GetNumberFromObj(NULL, value2Ptr, &ptr2, &type2) != TCL_OK)
6469 || IsErroringNaNType(type2)) {
6470 TRACE(("%.20s %.20s => ILLEGAL 2nd TYPE %s\n",
6471 O2S(value2Ptr), O2S(valuePtr),
6472 (value2Ptr->typePtr? value2Ptr->typePtr->name: "null")));
6473 DECACHE_STACK_INFO();
6474 IllegalExprOperandType(interp, pc, value2Ptr);
6475 CACHE_STACK_INFO();
6476 goto gotError;
6477 }
6478
6479 #ifdef ACCEPT_NAN
6480 if (type2 == TCL_NUMBER_NAN) {
6481 /*
6482 * NaN second argument -> result is also NaN.
6483 */
6484
6485 objResultPtr = value2Ptr;
6486 NEXT_INST_F(1, 2, 1);
6487 }
6488 #endif
6489
6490 /*
6491 * Handle (long,long) arithmetic as best we can without going out to
6492 * an external function.
6493 */
6494
6495 if ((type1 == TCL_NUMBER_LONG) && (type2 == TCL_NUMBER_LONG)) {
6496 Tcl_WideInt w1, w2, wResult;
6497
6498 l1 = *((const long *)ptr1);
6499 l2 = *((const long *)ptr2);
6500
6501 switch (*pc) {
6502 case INST_ADD:
6503 w1 = (Tcl_WideInt)l1;
6504 w2 = (Tcl_WideInt)l2;
6505 wResult = (Tcl_WideInt)((Tcl_WideUInt)w1 + (Tcl_WideUInt)w2);
6506 #ifdef TCL_WIDE_INT_IS_LONG
6507 /*
6508 * Check for overflow.
6509 */
6510
6511 if (Overflowing(w1, w2, wResult)) {
6512 goto overflow;
6513 }
6514 #endif
6515 goto wideResultOfArithmetic;
6516
6517 case INST_SUB:
6518 w1 = (Tcl_WideInt)l1;
6519 w2 = (Tcl_WideInt)l2;
6520 wResult = (Tcl_WideInt)((Tcl_WideUInt)w1 - (Tcl_WideUInt)w2);
6521 #ifdef TCL_WIDE_INT_IS_LONG
6522 /*
6523 * Must check for overflow. The macro tests for overflows in
6524 * sums by looking at the sign bits. As we have a subtraction
6525 * here, we are adding -w2. As -w2 could in turn overflow, we
6526 * test with ~w2 instead: it has the opposite sign bit to w2
6527 * so it does the job. Note that the only "bad" case (w2==0)
6528 * is irrelevant for this macro, as in that case w1 and
6529 * wResult have the same sign and there is no overflow anyway.
6530 */
6531
6532 if (Overflowing(w1, ~w2, wResult)) {
6533 goto overflow;
6534 }
6535 #endif
6536 wideResultOfArithmetic:
6537 TRACE(("%s %s => ", O2S(valuePtr), O2S(value2Ptr)));
6538 if (Tcl_IsShared(valuePtr)) {
6539 objResultPtr = Tcl_NewWideIntObj(wResult);
6540 TRACE(("%s\n", O2S(objResultPtr)));
6541 NEXT_INST_F(1, 2, 1);
6542 }
6543 Tcl_SetWideIntObj(valuePtr, wResult);
6544 TRACE(("%s\n", O2S(valuePtr)));
6545 NEXT_INST_F(1, 1, 0);
6546 break;
6547
6548 case INST_DIV:
6549 if (l2 == 0) {
6550 TRACE(("%s %s => DIVIDE BY ZERO\n",
6551 O2S(valuePtr), O2S(value2Ptr)));
6552 goto divideByZero;
6553 } else if ((l1 == LONG_MIN) && (l2 == -1)) {
6554 /*
6555 * Can't represent (-LONG_MIN) as a long.
6556 */
6557
6558 goto overflow;
6559 }
6560 lResult = l1 / l2;
6561
6562 /*
6563 * Force Tcl's integer division rules.
6564 * TODO: examine for logic simplification
6565 */
6566
6567 if (((lResult < 0) || ((lResult == 0) &&
6568 ((l1 < 0 && l2 > 0) || (l1 > 0 && l2 < 0)))) &&
6569 ((lResult * l2) != l1)) {
6570 lResult -= 1;
6571 }
6572 goto longResultOfArithmetic;
6573
6574 case INST_MULT:
6575 if (((sizeof(long) >= 2*sizeof(int))
6576 && (l1 <= INT_MAX) && (l1 >= INT_MIN)
6577 && (l2 <= INT_MAX) && (l2 >= INT_MIN))
6578 || ((sizeof(long) >= 2*sizeof(short))
6579 && (l1 <= SHRT_MAX) && (l1 >= SHRT_MIN)
6580 && (l2 <= SHRT_MAX) && (l2 >= SHRT_MIN))) {
6581 lResult = l1 * l2;
6582 goto longResultOfArithmetic;
6583 }
6584 }
6585
6586 /*
6587 * Fall through with INST_EXPON, INST_DIV and large multiplies.
6588 */
6589 }
6590
6591 overflow:
6592 TRACE(("%s %s => ", O2S(valuePtr), O2S(value2Ptr)));
6593 objResultPtr = ExecuteExtendedBinaryMathOp(interp, *pc, &TCONST(0),
6594 valuePtr, value2Ptr);
6595 if (objResultPtr == DIVIDED_BY_ZERO) {
6596 TRACE_APPEND(("DIVIDE BY ZERO\n"));
6597 goto divideByZero;
6598 } else if (objResultPtr == EXPONENT_OF_ZERO) {
6599 TRACE_APPEND(("EXPONENT OF ZERO\n"));
6600 goto exponOfZero;
6601 } else if (objResultPtr == GENERAL_ARITHMETIC_ERROR) {
6602 TRACE_ERROR(interp);
6603 goto gotError;
6604 } else if (objResultPtr == NULL) {
6605 TRACE_APPEND(("%s\n", O2S(valuePtr)));
6606 NEXT_INST_F(1, 1, 0);
6607 } else {
6608 TRACE_APPEND(("%s\n", O2S(objResultPtr)));
6609 NEXT_INST_F(1, 2, 1);
6610 }
6611
6612 case INST_LNOT: {
6613 int b;
6614
6615 valuePtr = OBJ_AT_TOS;
6616
6617 /* TODO - check claim that taking address of b harms performance */
6618 /* TODO - consider optimization search for constants */
6619 if (TclGetBooleanFromObj(NULL, valuePtr, &b) != TCL_OK) {
6620 TRACE(("\"%.20s\" => ERROR: illegal type %s\n", O2S(valuePtr),
6621 (valuePtr->typePtr? valuePtr->typePtr->name : "null")));
6622 DECACHE_STACK_INFO();
6623 IllegalExprOperandType(interp, pc, valuePtr);
6624 CACHE_STACK_INFO();
6625 goto gotError;
6626 }
6627 /* TODO: Consider peephole opt. */
6628 objResultPtr = TCONST(!b);
6629 TRACE_WITH_OBJ(("%s => ", O2S(valuePtr)), objResultPtr);
6630 NEXT_INST_F(1, 1, 1);
6631 }
6632
6633 case INST_BITNOT:
6634 valuePtr = OBJ_AT_TOS;
6635 TRACE(("\"%.20s\" => ", O2S(valuePtr)));
6636 if ((GetNumberFromObj(NULL, valuePtr, &ptr1, &type1) != TCL_OK)
6637 || (type1==TCL_NUMBER_NAN) || (type1==TCL_NUMBER_DOUBLE)) {
6638 /*
6639 * ... ~$NonInteger => raise an error.
6640 */
6641
6642 TRACE_APPEND(("ERROR: illegal type %s\n",
6643 (valuePtr->typePtr? valuePtr->typePtr->name : "null")));
6644 DECACHE_STACK_INFO();
6645 IllegalExprOperandType(interp, pc, valuePtr);
6646 CACHE_STACK_INFO();
6647 goto gotError;
6648 }
6649 if (type1 == TCL_NUMBER_LONG) {
6650 l1 = *((const long *) ptr1);
6651 if (Tcl_IsShared(valuePtr)) {
6652 TclNewLongObj(objResultPtr, ~l1);
6653 TRACE_APPEND(("%s\n", O2S(objResultPtr)));
6654 NEXT_INST_F(1, 1, 1);
6655 }
6656 TclSetLongObj(valuePtr, ~l1);
6657 TRACE_APPEND(("%s\n", O2S(valuePtr)));
6658 NEXT_INST_F(1, 0, 0);
6659 }
6660 objResultPtr = ExecuteExtendedUnaryMathOp(*pc, valuePtr);
6661 if (objResultPtr != NULL) {
6662 TRACE_APPEND(("%s\n", O2S(objResultPtr)));
6663 NEXT_INST_F(1, 1, 1);
6664 } else {
6665 TRACE_APPEND(("%s\n", O2S(valuePtr)));
6666 NEXT_INST_F(1, 0, 0);
6667 }
6668
6669 case INST_UMINUS:
6670 valuePtr = OBJ_AT_TOS;
6671 TRACE(("\"%.20s\" => ", O2S(valuePtr)));
6672 if ((GetNumberFromObj(NULL, valuePtr, &ptr1, &type1) != TCL_OK)
6673 || IsErroringNaNType(type1)) {
6674 TRACE_APPEND(("ERROR: illegal type %s \n",
6675 (valuePtr->typePtr? valuePtr->typePtr->name : "null")));
6676 DECACHE_STACK_INFO();
6677 IllegalExprOperandType(interp, pc, valuePtr);
6678 CACHE_STACK_INFO();
6679 goto gotError;
6680 }
6681 switch (type1) {
6682 case TCL_NUMBER_NAN:
6683 /* -NaN => NaN */
6684 TRACE_APPEND(("%s\n", O2S(valuePtr)));
6685 NEXT_INST_F(1, 0, 0);
6686 break;
6687 case TCL_NUMBER_LONG:
6688 l1 = *((const long *) ptr1);
6689 if (l1 != LONG_MIN) {
6690 if (Tcl_IsShared(valuePtr)) {
6691 TclNewLongObj(objResultPtr, -l1);
6692 TRACE_APPEND(("%s\n", O2S(objResultPtr)));
6693 NEXT_INST_F(1, 1, 1);
6694 }
6695 TclSetLongObj(valuePtr, -l1);
6696 TRACE_APPEND(("%s\n", O2S(valuePtr)));
6697 NEXT_INST_F(1, 0, 0);
6698 }
6699 /* FALLTHROUGH */
6700 }
6701 objResultPtr = ExecuteExtendedUnaryMathOp(*pc, valuePtr);
6702 if (objResultPtr != NULL) {
6703 TRACE_APPEND(("%s\n", O2S(objResultPtr)));
6704 NEXT_INST_F(1, 1, 1);
6705 } else {
6706 TRACE_APPEND(("%s\n", O2S(valuePtr)));
6707 NEXT_INST_F(1, 0, 0);
6708 }
6709
6710 case INST_UPLUS:
6711 case INST_TRY_CVT_TO_NUMERIC:
6712 /*
6713 * Try to convert the topmost stack object to numeric object. This is
6714 * done in order to support [expr]'s policy of interpreting operands
6715 * if at all possible as numbers first, then strings.
6716 */
6717
6718 valuePtr = OBJ_AT_TOS;
6719 TRACE(("\"%.20s\" => ", O2S(valuePtr)));
6720
6721 if (GetNumberFromObj(NULL, valuePtr, &ptr1, &type1) != TCL_OK) {
6722 if (*pc == INST_UPLUS) {
6723 /*
6724 * ... +$NonNumeric => raise an error.
6725 */
6726
6727 TRACE_APPEND(("ERROR: illegal type %s\n",
6728 (valuePtr->typePtr? valuePtr->typePtr->name:"null")));
6729 DECACHE_STACK_INFO();
6730 IllegalExprOperandType(interp, pc, valuePtr);
6731 CACHE_STACK_INFO();
6732 goto gotError;
6733 }
6734
6735 /* ... TryConvertToNumeric($NonNumeric) is acceptable */
6736 TRACE_APPEND(("not numeric\n"));
6737 NEXT_INST_F(1, 0, 0);
6738 }
6739 if (IsErroringNaNType(type1)) {
6740 if (*pc == INST_UPLUS) {
6741 /*
6742 * ... +$NonNumeric => raise an error.
6743 */
6744
6745 TRACE_APPEND(("ERROR: illegal type %s\n",
6746 (valuePtr->typePtr? valuePtr->typePtr->name:"null")));
6747 DECACHE_STACK_INFO();
6748 IllegalExprOperandType(interp, pc, valuePtr);
6749 CACHE_STACK_INFO();
6750 } else {
6751 /*
6752 * Numeric conversion of NaN -> error.
6753 */
6754
6755 TRACE_APPEND(("ERROR: IEEE floating pt error\n"));
6756 DECACHE_STACK_INFO();
6757 TclExprFloatError(interp, *((const double *) ptr1));
6758 CACHE_STACK_INFO();
6759 }
6760 goto gotError;
6761 }
6762
6763 /*
6764 * Ensure that the numeric value has a string rep the same as the
6765 * formatted version of its internal rep. This is used, e.g., to make
6766 * sure that "expr {0001}" yields "1", not "0001". We implement this
6767 * by _discarding_ the string rep since we know it will be
6768 * regenerated, if needed later, by formatting the internal rep's
6769 * value.
6770 */
6771
6772 if (valuePtr->bytes == NULL) {
6773 TRACE_APPEND(("numeric, same Tcl_Obj\n"));
6774 NEXT_INST_F(1, 0, 0);
6775 }
6776 if (Tcl_IsShared(valuePtr)) {
6777 /*
6778 * Here we do some surgery within the Tcl_Obj internals. We want
6779 * to copy the internalrep, but not the string, so we temporarily hide
6780 * the string so we do not copy it.
6781 */
6782
6783 char *savedString = valuePtr->bytes;
6784
6785 valuePtr->bytes = NULL;
6786 objResultPtr = Tcl_DuplicateObj(valuePtr);
6787 valuePtr->bytes = savedString;
6788 TRACE_APPEND(("numeric, new Tcl_Obj\n"));
6789 NEXT_INST_F(1, 1, 1);
6790 }
6791 TclInvalidateStringRep(valuePtr);
6792 TRACE_APPEND(("numeric, same Tcl_Obj\n"));
6793 NEXT_INST_F(1, 0, 0);
6794 }
6795 break;
6796
6797 /*
6798 * End of numeric operator instructions.
6799 * -----------------------------------------------------------------
6800 */
6801
6802 case INST_TRY_CVT_TO_BOOLEAN:
6803 valuePtr = OBJ_AT_TOS;
6804 if (valuePtr->typePtr == &tclBooleanType) {
6805 objResultPtr = TCONST(1);
6806 } else {
6807 int res = (TclSetBooleanFromAny(NULL, valuePtr) == TCL_OK);
6808 objResultPtr = TCONST(res);
6809 }
6810 TRACE_WITH_OBJ(("\"%.30s\" => ", O2S(valuePtr)), objResultPtr);
6811 NEXT_INST_F(1, 0, 1);
6812 break;
6813
6814 case INST_BREAK:
6815 /*
6816 DECACHE_STACK_INFO();
6817 Tcl_ResetResult(interp);
6818 CACHE_STACK_INFO();
6819 */
6820 result = TCL_BREAK;
6821 cleanup = 0;
6822 TRACE(("=> BREAK!\n"));
6823 goto processExceptionReturn;
6824
6825 case INST_CONTINUE:
6826 /*
6827 DECACHE_STACK_INFO();
6828 Tcl_ResetResult(interp);
6829 CACHE_STACK_INFO();
6830 */
6831 result = TCL_CONTINUE;
6832 cleanup = 0;
6833 TRACE(("=> CONTINUE!\n"));
6834 goto processExceptionReturn;
6835
6836 {
6837 ForeachInfo *infoPtr;
6838 Var *iterVarPtr, *listVarPtr;
6839 Tcl_Obj *oldValuePtr, *listPtr, **elements;
6840 ForeachVarList *varListPtr;
6841 int numLists, iterNum, listTmpIndex, listLen, numVars;
6842 int varIndex, valIndex, continueLoop, j, iterTmpIndex;
6843 long i;
6844
6845 case INST_FOREACH_START4: /* DEPRECATED */
6846 /*
6847 * Initialize the temporary local var that holds the count of the
6848 * number of iterations of the loop body to -1.
6849 */
6850
6851 opnd = TclGetUInt4AtPtr(pc+1);
6852 infoPtr = codePtr->auxDataArrayPtr[opnd].clientData;
6853 iterTmpIndex = infoPtr->loopCtTemp;
6854 iterVarPtr = LOCAL(iterTmpIndex);
6855 oldValuePtr = iterVarPtr->value.objPtr;
6856
6857 if (oldValuePtr == NULL) {
6858 TclNewLongObj(iterVarPtr->value.objPtr, -1);
6859 Tcl_IncrRefCount(iterVarPtr->value.objPtr);
6860 } else {
6861 TclSetLongObj(oldValuePtr, -1);
6862 }
6863 TRACE(("%u => loop iter count temp %d\n", opnd, iterTmpIndex));
6864
6865 #ifndef TCL_COMPILE_DEBUG
6866 /*
6867 * Remark that the compiler ALWAYS sets INST_FOREACH_STEP4 immediately
6868 * after INST_FOREACH_START4 - let us just fall through instead of
6869 * jumping back to the top.
6870 */
6871
6872 pc += 5;
6873 TCL_DTRACE_INST_NEXT();
6874 #else
6875 NEXT_INST_F(5, 0, 0);
6876 #endif
6877
6878 case INST_FOREACH_STEP4: /* DEPRECATED */
6879 /*
6880 * "Step" a foreach loop (i.e., begin its next iteration) by assigning
6881 * the next value list element to each loop var.
6882 */
6883
6884 opnd = TclGetUInt4AtPtr(pc+1);
6885 TRACE(("%u => ", opnd));
6886 infoPtr = codePtr->auxDataArrayPtr[opnd].clientData;
6887 numLists = infoPtr->numLists;
6888
6889 /*
6890 * Increment the temp holding the loop iteration number.
6891 */
6892
6893 iterVarPtr = LOCAL(infoPtr->loopCtTemp);
6894 valuePtr = iterVarPtr->value.objPtr;
6895 iterNum = valuePtr->internalRep.longValue + 1;
6896 TclSetLongObj(valuePtr, iterNum);
6897
6898 /*
6899 * Check whether all value lists are exhausted and we should stop the
6900 * loop.
6901 */
6902
6903 continueLoop = 0;
6904 listTmpIndex = infoPtr->firstValueTemp;
6905 for (i = 0; i < numLists; i++) {
6906 varListPtr = infoPtr->varLists[i];
6907 numVars = varListPtr->numVars;
6908
6909 listVarPtr = LOCAL(listTmpIndex);
6910 listPtr = listVarPtr->value.objPtr;
6911 if (TclListObjLength(interp, listPtr, &listLen) != TCL_OK) {
6912 TRACE_APPEND(("ERROR converting list %ld, \"%.30s\": %s\n",
6913 i, O2S(listPtr), O2S(Tcl_GetObjResult(interp))));
6914 goto gotError;
6915 }
6916 if (listLen > iterNum * numVars) {
6917 continueLoop = 1;
6918 }
6919 listTmpIndex++;
6920 }
6921
6922 /*
6923 * If some var in some var list still has a remaining list element
6924 * iterate one more time. Assign to var the next element from its
6925 * value list. We already checked above that each list temp holds a
6926 * valid list object (by calling Tcl_ListObjLength), but cannot rely
6927 * on that check remaining valid: one list could have been shimmered
6928 * as a side effect of setting a traced variable.
6929 */
6930
6931 if (continueLoop) {
6932 listTmpIndex = infoPtr->firstValueTemp;
6933 for (i = 0; i < numLists; i++) {
6934 varListPtr = infoPtr->varLists[i];
6935 numVars = varListPtr->numVars;
6936
6937 listVarPtr = LOCAL(listTmpIndex);
6938 listPtr = TclListObjCopy(NULL, listVarPtr->value.objPtr);
6939 TclListObjGetElements(interp, listPtr, &listLen, &elements);
6940
6941 valIndex = (iterNum * numVars);
6942 for (j = 0; j < numVars; j++) {
6943 if (valIndex >= listLen) {
6944 TclNewObj(valuePtr);
6945 } else {
6946 valuePtr = elements[valIndex];
6947 }
6948
6949 varIndex = varListPtr->varIndexes[j];
6950 varPtr = LOCAL(varIndex);
6951 while (TclIsVarLink(varPtr)) {
6952 varPtr = varPtr->value.linkPtr;
6953 }
6954 if (TclIsVarDirectWritable(varPtr)) {
6955 value2Ptr = varPtr->value.objPtr;
6956 if (valuePtr != value2Ptr) {
6957 if (value2Ptr != NULL) {
6958 TclDecrRefCount(value2Ptr);
6959 }
6960 varPtr->value.objPtr = valuePtr;
6961 Tcl_IncrRefCount(valuePtr);
6962 }
6963 } else {
6964 DECACHE_STACK_INFO();
6965 if (TclPtrSetVarIdx(interp, varPtr, NULL, NULL, NULL,
6966 valuePtr, TCL_LEAVE_ERR_MSG, varIndex)==NULL){
6967 CACHE_STACK_INFO();
6968 TRACE_APPEND((
6969 "ERROR init. index temp %d: %s\n",
6970 varIndex, O2S(Tcl_GetObjResult(interp))));
6971 TclDecrRefCount(listPtr);
6972 goto gotError;
6973 }
6974 CACHE_STACK_INFO();
6975 }
6976 valIndex++;
6977 }
6978 TclDecrRefCount(listPtr);
6979 listTmpIndex++;
6980 }
6981 }
6982 TRACE_APPEND(("%d lists, iter %d, %s loop\n",
6983 numLists, iterNum, (continueLoop? "continue" : "exit")));
6984
6985 /*
6986 * Run-time peep-hole optimisation: the compiler ALWAYS follows
6987 * INST_FOREACH_STEP4 with an INST_JUMP_FALSE. We just skip that
6988 * instruction and jump direct from here.
6989 */
6990
6991 pc += 5;
6992 if (*pc == INST_JUMP_FALSE1) {
6993 NEXT_INST_F((continueLoop? 2 : TclGetInt1AtPtr(pc+1)), 0, 0);
6994 } else {
6995 NEXT_INST_F((continueLoop? 5 : TclGetInt4AtPtr(pc+1)), 0, 0);
6996 }
6997
6998 }
6999 {
7000 ForeachInfo *infoPtr;
7001 Tcl_Obj *listPtr, **elements;
7002 ForeachVarList *varListPtr;
7003 int numLists, iterMax, listLen, numVars;
7004 int iterTmp, iterNum, listTmpDepth;
7005 int varIndex, valIndex, j;
7006 long i;
7007
7008 case INST_FOREACH_START:
7009 /*
7010 * Initialize the data for the looping construct, pushing the
7011 * corresponding Tcl_Objs to the stack.
7012 */
7013
7014 opnd = TclGetUInt4AtPtr(pc+1);
7015 infoPtr = codePtr->auxDataArrayPtr[opnd].clientData;
7016 numLists = infoPtr->numLists;
7017 TRACE(("%u => ", opnd));
7018
7019 /*
7020 * Compute the number of iterations that will be run: iterMax
7021 */
7022
7023 iterMax = 0;
7024 listTmpDepth = numLists-1;
7025 for (i = 0; i < numLists; i++) {
7026 varListPtr = infoPtr->varLists[i];
7027 numVars = varListPtr->numVars;
7028 listPtr = OBJ_AT_DEPTH(listTmpDepth);
7029 if (TclListObjLength(interp, listPtr, &listLen) != TCL_OK) {
7030 TRACE_APPEND(("ERROR converting list %ld, \"%s\": %s",
7031 i, O2S(listPtr), O2S(Tcl_GetObjResult(interp))));
7032 goto gotError;
7033 }
7034 if (Tcl_IsShared(listPtr)) {
7035 objPtr = TclListObjCopy(NULL, listPtr);
7036 Tcl_IncrRefCount(objPtr);
7037 Tcl_DecrRefCount(listPtr);
7038 OBJ_AT_DEPTH(listTmpDepth) = objPtr;
7039 }
7040 iterTmp = (listLen + (numVars - 1))/numVars;
7041 if (iterTmp > iterMax) {
7042 iterMax = iterTmp;
7043 }
7044 listTmpDepth--;
7045 }
7046
7047 /*
7048 * Store the iterNum and iterMax in a single Tcl_Obj; we keep a
7049 * nul-string obj with the pointer stored in the ptrValue so that the
7050 * thing is properly garbage collected. THIS OBJ MAKES NO SENSE, but
7051 * it will never leave this scope and is read-only.
7052 */
7053
7054 TclNewObj(tmpPtr);
7055 tmpPtr->internalRep.twoPtrValue.ptr1 = INT2PTR(0);
7056 tmpPtr->internalRep.twoPtrValue.ptr2 = INT2PTR(iterMax);
7057 PUSH_OBJECT(tmpPtr); /* iterCounts object */
7058
7059 /*
7060 * Store a pointer to the ForeachInfo struct; same dirty trick
7061 * as above
7062 */
7063
7064 TclNewObj(tmpPtr);
7065 tmpPtr->internalRep.twoPtrValue.ptr1 = infoPtr;
7066 PUSH_OBJECT(tmpPtr); /* infoPtr object */
7067 TRACE_APPEND(("jump to loop step\n"));
7068
7069 /*
7070 * Jump directly to the INST_FOREACH_STEP instruction; the C code just
7071 * falls through.
7072 */
7073
7074 pc += 5 - infoPtr->loopCtTemp;
7075
7076 case INST_FOREACH_STEP:
7077 /*
7078 * "Step" a foreach loop (i.e., begin its next iteration) by assigning
7079 * the next value list element to each loop var.
7080 */
7081
7082 tmpPtr = OBJ_AT_TOS;
7083 infoPtr = tmpPtr->internalRep.twoPtrValue.ptr1;
7084 numLists = infoPtr->numLists;
7085 TRACE(("=> "));
7086
7087 tmpPtr = OBJ_AT_DEPTH(1);
7088 iterNum = PTR2INT(tmpPtr->internalRep.twoPtrValue.ptr1);
7089 iterMax = PTR2INT(tmpPtr->internalRep.twoPtrValue.ptr2);
7090
7091 /*
7092 * If some list still has a remaining list element iterate one more
7093 * time. Assign to var the next element from its value list.
7094 */
7095
7096 if (iterNum < iterMax) {
7097 /*
7098 * Set the variables and jump back to run the body
7099 */
7100
7101 tmpPtr->internalRep.twoPtrValue.ptr1 = INT2PTR(iterNum + 1);
7102
7103 listTmpDepth = numLists + 1;
7104
7105 for (i = 0; i < numLists; i++) {
7106 varListPtr = infoPtr->varLists[i];
7107 numVars = varListPtr->numVars;
7108
7109 listPtr = OBJ_AT_DEPTH(listTmpDepth);
7110 TclListObjGetElements(interp, listPtr, &listLen, &elements);
7111
7112 valIndex = (iterNum * numVars);
7113 for (j = 0; j < numVars; j++) {
7114 if (valIndex >= listLen) {
7115 TclNewObj(valuePtr);
7116 } else {
7117 valuePtr = elements[valIndex];
7118 }
7119
7120 varIndex = varListPtr->varIndexes[j];
7121 varPtr = LOCAL(varIndex);
7122 while (TclIsVarLink(varPtr)) {
7123 varPtr = varPtr->value.linkPtr;
7124 }
7125 if (TclIsVarDirectWritable(varPtr)) {
7126 value2Ptr = varPtr->value.objPtr;
7127 if (valuePtr != value2Ptr) {
7128 if (value2Ptr != NULL) {
7129 TclDecrRefCount(value2Ptr);
7130 }
7131 varPtr->value.objPtr = valuePtr;
7132 Tcl_IncrRefCount(valuePtr);
7133 }
7134 } else {
7135 DECACHE_STACK_INFO();
7136 if (TclPtrSetVarIdx(interp, varPtr, NULL, NULL, NULL,
7137 valuePtr, TCL_LEAVE_ERR_MSG, varIndex)==NULL){
7138 CACHE_STACK_INFO();
7139 TRACE_APPEND(("ERROR init. index temp %d: %.30s",
7140 varIndex, O2S(Tcl_GetObjResult(interp))));
7141 goto gotError;
7142 }
7143 CACHE_STACK_INFO();
7144 }
7145 valIndex++;
7146 }
7147 listTmpDepth--;
7148 }
7149 TRACE_APPEND(("jump to loop start\n"));
7150 /* loopCtTemp being 'misused' for storing the jump size */
7151 NEXT_INST_F(infoPtr->loopCtTemp, 0, 0);
7152 }
7153
7154 TRACE_APPEND(("loop has no more iterations\n"));
7155 #ifdef TCL_COMPILE_DEBUG
7156 NEXT_INST_F(1, 0, 0);
7157 #else
7158 /*
7159 * FALL THROUGH
7160 */
7161 pc++;
7162 #endif
7163
7164 case INST_FOREACH_END:
7165 /* THIS INSTRUCTION IS ONLY CALLED AS A BREAK TARGET */
7166 tmpPtr = OBJ_AT_TOS;
7167 infoPtr = tmpPtr->internalRep.twoPtrValue.ptr1;
7168 numLists = infoPtr->numLists;
7169 TRACE(("=> loop terminated\n"));
7170 NEXT_INST_V(1, numLists+2, 0);
7171
7172 case INST_LMAP_COLLECT:
7173 /*
7174 * This instruction is only issued by lmap. The stack is:
7175 * - result
7176 * - infoPtr
7177 * - loop counters
7178 * - valLists
7179 * - collecting obj (unshared)
7180 * The instruction lappends the result to the collecting obj.
7181 */
7182
7183 tmpPtr = OBJ_AT_DEPTH(1);
7184 infoPtr = tmpPtr->internalRep.twoPtrValue.ptr1;
7185 numLists = infoPtr->numLists;
7186 TRACE_APPEND(("=> appending to list at depth %d\n", 3 + numLists));
7187
7188 objPtr = OBJ_AT_DEPTH(3 + numLists);
7189 Tcl_ListObjAppendElement(NULL, objPtr, OBJ_AT_TOS);
7190 NEXT_INST_F(1, 1, 0);
7191 }
7192 break;
7193
7194 case INST_BEGIN_CATCH4:
7195 /*
7196 * Record start of the catch command with exception range index equal
7197 * to the operand. Push the current stack depth onto the special catch
7198 * stack.
7199 */
7200
7201 *(++catchTop) = CURR_DEPTH;
7202 TRACE(("%u => catchTop=%d, stackTop=%d\n",
7203 TclGetUInt4AtPtr(pc+1), (int) (catchTop - initCatchTop - 1),
7204 (int) CURR_DEPTH));
7205 NEXT_INST_F(5, 0, 0);
7206 break;
7207
7208 case INST_END_CATCH:
7209 catchTop--;
7210 DECACHE_STACK_INFO();
7211 Tcl_ResetResult(interp);
7212 CACHE_STACK_INFO();
7213 result = TCL_OK;
7214 TRACE(("=> catchTop=%d\n", (int) (catchTop - initCatchTop - 1)));
7215 NEXT_INST_F(1, 0, 0);
7216 break;
7217
7218 case INST_PUSH_RESULT:
7219 objResultPtr = Tcl_GetObjResult(interp);
7220 TRACE_WITH_OBJ(("=> "), objResultPtr);
7221
7222 /*
7223 * See the comments at INST_INVOKE_STK
7224 */
7225
7226 TclNewObj(objPtr);
7227 Tcl_IncrRefCount(objPtr);
7228 iPtr->objResultPtr = objPtr;
7229 NEXT_INST_F(1, 0, -1);
7230 break;
7231
7232 case INST_PUSH_RETURN_CODE:
7233 TclNewIntObj(objResultPtr, result);
7234 TRACE(("=> %u\n", result));
7235 NEXT_INST_F(1, 0, 1);
7236 break;
7237
7238 case INST_PUSH_RETURN_OPTIONS:
7239 DECACHE_STACK_INFO();
7240 objResultPtr = Tcl_GetReturnOptions(interp, result);
7241 CACHE_STACK_INFO();
7242 TRACE_WITH_OBJ(("=> "), objResultPtr);
7243 NEXT_INST_F(1, 0, 1);
7244 break;
7245
7246 case INST_RETURN_CODE_BRANCH: {
7247 int code;
7248
7249 if (TclGetIntFromObj(NULL, OBJ_AT_TOS, &code) != TCL_OK) {
7250 Tcl_Panic("INST_RETURN_CODE_BRANCH: TOS not a return code!");
7251 }
7252 if (code == TCL_OK) {
7253 Tcl_Panic("INST_RETURN_CODE_BRANCH: TOS is TCL_OK!");
7254 }
7255 if (code < TCL_ERROR || code > TCL_CONTINUE) {
7256 code = TCL_CONTINUE + 1;
7257 }
7258 TRACE(("\"%s\" => jump offset %d\n", O2S(OBJ_AT_TOS), 2*code-1));
7259 NEXT_INST_F(2*code-1, 1, 0);
7260 }
7261
7262 /*
7263 * -----------------------------------------------------------------
7264 * Start of dictionary-related instructions.
7265 */
7266
7267 {
7268 int opnd2, allocateDict, done, i, allocdict;
7269 Tcl_Obj *dictPtr, *statePtr, *keyPtr, *listPtr, *varNamePtr, *keysPtr;
7270 Tcl_Obj *emptyPtr, **keyPtrPtr;
7271 Tcl_DictSearch *searchPtr;
7272 DictUpdateInfo *duiPtr;
7273
7274 case INST_DICT_VERIFY:
7275 dictPtr = OBJ_AT_TOS;
7276 TRACE(("\"%.30s\" => ", O2S(dictPtr)));
7277 if (Tcl_DictObjSize(interp, dictPtr, &done) != TCL_OK) {
7278 TRACE_APPEND(("ERROR verifying dictionary nature of \"%.30s\": %s\n",
7279 O2S(dictPtr), O2S(Tcl_GetObjResult(interp))));
7280 goto gotError;
7281 }
7282 TRACE_APPEND(("OK\n"));
7283 NEXT_INST_F(1, 1, 0);
7284
7285 case INST_DICT_GET:
7286 case INST_DICT_EXISTS: {
7287 Tcl_Interp *interp2 = interp;
7288 int found;
7289
7290 opnd = TclGetUInt4AtPtr(pc+1);
7291 TRACE(("%u => ", opnd));
7292 dictPtr = OBJ_AT_DEPTH(opnd);
7293 if (*pc == INST_DICT_EXISTS) {
7294 interp2 = NULL;
7295 }
7296 if (opnd > 1) {
7297 dictPtr = TclTraceDictPath(interp2, dictPtr, opnd-1,
7298 &OBJ_AT_DEPTH(opnd-1), DICT_PATH_READ);
7299 if (dictPtr == NULL) {
7300 if (*pc == INST_DICT_EXISTS) {
7301 found = 0;
7302 goto afterDictExists;
7303 }
7304 TRACE_WITH_OBJ((
7305 "ERROR tracing dictionary path into \"%.30s\": ",
7306 O2S(OBJ_AT_DEPTH(opnd))),
7307 Tcl_GetObjResult(interp));
7308 goto gotError;
7309 }
7310 }
7311 if (Tcl_DictObjGet(interp2, dictPtr, OBJ_AT_TOS,
7312 &objResultPtr) == TCL_OK) {
7313 if (*pc == INST_DICT_EXISTS) {
7314 found = (objResultPtr ? 1 : 0);
7315 goto afterDictExists;
7316 }
7317 if (!objResultPtr) {
7318 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
7319 "key \"%s\" not known in dictionary",
7320 TclGetString(OBJ_AT_TOS)));
7321 DECACHE_STACK_INFO();
7322 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "DICT",
7323 TclGetString(OBJ_AT_TOS), (char *)NULL);
7324 CACHE_STACK_INFO();
7325 TRACE_ERROR(interp);
7326 goto gotError;
7327 }
7328 TRACE_APPEND(("%.30s\n", O2S(objResultPtr)));
7329 NEXT_INST_V(5, opnd+1, 1);
7330 } else if (*pc != INST_DICT_EXISTS) {
7331 TRACE_APPEND(("ERROR reading leaf dictionary key \"%.30s\": %s",
7332 O2S(dictPtr), O2S(Tcl_GetObjResult(interp))));
7333 goto gotError;
7334 } else {
7335 found = 0;
7336 }
7337 afterDictExists:
7338 TRACE_APPEND(("%d\n", found));
7339
7340 /*
7341 * The INST_DICT_EXISTS instruction is usually followed by a
7342 * conditional jump, so we can take advantage of this to do some
7343 * peephole optimization (note that we're careful to not close out
7344 * someone doing something else).
7345 */
7346
7347 JUMP_PEEPHOLE_V(found, 5, opnd+1);
7348 }
7349
7350 case INST_DICT_SET:
7351 case INST_DICT_UNSET:
7352 case INST_DICT_INCR_IMM:
7353 opnd = TclGetUInt4AtPtr(pc+1);
7354 opnd2 = TclGetUInt4AtPtr(pc+5);
7355
7356 varPtr = LOCAL(opnd2);
7357 while (TclIsVarLink(varPtr)) {
7358 varPtr = varPtr->value.linkPtr;
7359 }
7360 TRACE(("%u %u => ", opnd, opnd2));
7361 if (TclIsVarDirectReadable(varPtr)) {
7362 dictPtr = varPtr->value.objPtr;
7363 } else {
7364 DECACHE_STACK_INFO();
7365 dictPtr = TclPtrGetVarIdx(interp, varPtr, NULL, NULL, NULL, 0,
7366 opnd2);
7367 CACHE_STACK_INFO();
7368 }
7369 if (dictPtr == NULL) {
7370 TclNewObj(dictPtr);
7371 allocateDict = 1;
7372 } else {
7373 allocateDict = Tcl_IsShared(dictPtr);
7374 if (allocateDict) {
7375 dictPtr = Tcl_DuplicateObj(dictPtr);
7376 }
7377 }
7378
7379 switch (*pc) {
7380 case INST_DICT_SET:
7381 cleanup = opnd + 1;
7382 result = Tcl_DictObjPutKeyList(interp, dictPtr, opnd,
7383 &OBJ_AT_DEPTH(opnd), OBJ_AT_TOS);
7384 break;
7385 case INST_DICT_INCR_IMM:
7386 cleanup = 1;
7387 opnd = TclGetInt4AtPtr(pc+1);
7388 result = Tcl_DictObjGet(interp, dictPtr, OBJ_AT_TOS, &valuePtr);
7389 if (result != TCL_OK) {
7390 break;
7391 }
7392 if (valuePtr == NULL) {
7393 Tcl_DictObjPut(NULL, dictPtr, OBJ_AT_TOS,Tcl_NewIntObj(opnd));
7394 } else {
7395 TclNewIntObj(value2Ptr, opnd);
7396 Tcl_IncrRefCount(value2Ptr);
7397 if (Tcl_IsShared(valuePtr)) {
7398 valuePtr = Tcl_DuplicateObj(valuePtr);
7399 Tcl_DictObjPut(NULL, dictPtr, OBJ_AT_TOS, valuePtr);
7400 }
7401 result = TclIncrObj(interp, valuePtr, value2Ptr);
7402 if (result == TCL_OK) {
7403 TclInvalidateStringRep(dictPtr);
7404 }
7405 TclDecrRefCount(value2Ptr);
7406 }
7407 break;
7408 case INST_DICT_UNSET:
7409 cleanup = opnd;
7410 result = Tcl_DictObjRemoveKeyList(interp, dictPtr, opnd,
7411 &OBJ_AT_DEPTH(opnd-1));
7412 break;
7413 default:
7414 cleanup = 0; /* stop compiler warning */
7415 Tcl_Panic("Should not happen!");
7416 }
7417
7418 if (result != TCL_OK) {
7419 if (allocateDict) {
7420 TclDecrRefCount(dictPtr);
7421 }
7422 TRACE_APPEND(("ERROR updating dictionary: %s\n",
7423 O2S(Tcl_GetObjResult(interp))));
7424 goto checkForCatch;
7425 }
7426
7427 if (TclIsVarDirectWritable(varPtr)) {
7428 if (allocateDict) {
7429 value2Ptr = varPtr->value.objPtr;
7430 Tcl_IncrRefCount(dictPtr);
7431 if (value2Ptr != NULL) {
7432 TclDecrRefCount(value2Ptr);
7433 }
7434 varPtr->value.objPtr = dictPtr;
7435 }
7436 objResultPtr = dictPtr;
7437 } else {
7438 Tcl_IncrRefCount(dictPtr);
7439 DECACHE_STACK_INFO();
7440 objResultPtr = TclPtrSetVarIdx(interp, varPtr, NULL, NULL, NULL,
7441 dictPtr, TCL_LEAVE_ERR_MSG, opnd2);
7442 CACHE_STACK_INFO();
7443 TclDecrRefCount(dictPtr);
7444 if (objResultPtr == NULL) {
7445 TRACE_ERROR(interp);
7446 goto gotError;
7447 }
7448 }
7449 #ifndef TCL_COMPILE_DEBUG
7450 if (*(pc+9) == INST_POP) {
7451 NEXT_INST_V(10, cleanup, 0);
7452 }
7453 #endif
7454 TRACE_APPEND(("\"%.30s\"\n", O2S(objResultPtr)));
7455 NEXT_INST_V(9, cleanup, 1);
7456
7457 case INST_DICT_APPEND:
7458 case INST_DICT_LAPPEND:
7459 opnd = TclGetUInt4AtPtr(pc+1);
7460 varPtr = LOCAL(opnd);
7461 while (TclIsVarLink(varPtr)) {
7462 varPtr = varPtr->value.linkPtr;
7463 }
7464 TRACE(("%u => ", opnd));
7465 if (TclIsVarDirectReadable(varPtr)) {
7466 dictPtr = varPtr->value.objPtr;
7467 } else {
7468 DECACHE_STACK_INFO();
7469 dictPtr = TclPtrGetVarIdx(interp, varPtr, NULL, NULL, NULL, 0,
7470 opnd);
7471 CACHE_STACK_INFO();
7472 }
7473 if (dictPtr == NULL) {
7474 TclNewObj(dictPtr);
7475 allocateDict = 1;
7476 } else {
7477 allocateDict = Tcl_IsShared(dictPtr);
7478 if (allocateDict) {
7479 dictPtr = Tcl_DuplicateObj(dictPtr);
7480 }
7481 }
7482
7483 if (Tcl_DictObjGet(interp, dictPtr, OBJ_UNDER_TOS,
7484 &valuePtr) != TCL_OK) {
7485 if (allocateDict) {
7486 TclDecrRefCount(dictPtr);
7487 }
7488 TRACE_ERROR(interp);
7489 goto gotError;
7490 }
7491
7492 /*
7493 * Note that a non-existent key results in a NULL valuePtr, which is a
7494 * case handled separately below. What we *can* say at this point is
7495 * that the write-back will always succeed.
7496 */
7497
7498 switch (*pc) {
7499 case INST_DICT_APPEND:
7500 if (valuePtr == NULL) {
7501 Tcl_DictObjPut(NULL, dictPtr, OBJ_UNDER_TOS, OBJ_AT_TOS);
7502 } else if (Tcl_IsShared(valuePtr)) {
7503 valuePtr = Tcl_DuplicateObj(valuePtr);
7504 Tcl_AppendObjToObj(valuePtr, OBJ_AT_TOS);
7505 Tcl_DictObjPut(NULL, dictPtr, OBJ_UNDER_TOS, valuePtr);
7506 } else {
7507 Tcl_AppendObjToObj(valuePtr, OBJ_AT_TOS);
7508
7509 /*
7510 * Must invalidate the string representation of dictionary
7511 * here because we have directly updated the internal
7512 * representation; if we don't, callers could see the wrong
7513 * string rep despite the internal version of the dictionary
7514 * having the correct value. [Bug 3079830]
7515 */
7516
7517 TclInvalidateStringRep(dictPtr);
7518 }
7519 break;
7520 case INST_DICT_LAPPEND:
7521 /*
7522 * More complex because list-append can fail.
7523 */
7524
7525 if (valuePtr == NULL) {
7526 Tcl_DictObjPut(NULL, dictPtr, OBJ_UNDER_TOS,
7527 Tcl_NewListObj(1, &OBJ_AT_TOS));
7528 break;
7529 } else if (Tcl_IsShared(valuePtr)) {
7530 valuePtr = Tcl_DuplicateObj(valuePtr);
7531 if (Tcl_ListObjAppendElement(interp, valuePtr,
7532 OBJ_AT_TOS) != TCL_OK) {
7533 TclDecrRefCount(valuePtr);
7534 if (allocateDict) {
7535 TclDecrRefCount(dictPtr);
7536 }
7537 TRACE_ERROR(interp);
7538 goto gotError;
7539 }
7540 Tcl_DictObjPut(NULL, dictPtr, OBJ_UNDER_TOS, valuePtr);
7541 } else {
7542 if (Tcl_ListObjAppendElement(interp, valuePtr,
7543 OBJ_AT_TOS) != TCL_OK) {
7544 if (allocateDict) {
7545 TclDecrRefCount(dictPtr);
7546 }
7547 TRACE_ERROR(interp);
7548 goto gotError;
7549 }
7550
7551 /*
7552 * Must invalidate the string representation of dictionary
7553 * here because we have directly updated the internal
7554 * representation; if we don't, callers could see the wrong
7555 * string rep despite the internal version of the dictionary
7556 * having the correct value. [Bug 3079830]
7557 */
7558
7559 TclInvalidateStringRep(dictPtr);
7560 }
7561 break;
7562 default:
7563 Tcl_Panic("Should not happen!");
7564 }
7565
7566 if (TclIsVarDirectWritable(varPtr)) {
7567 if (allocateDict) {
7568 value2Ptr = varPtr->value.objPtr;
7569 Tcl_IncrRefCount(dictPtr);
7570 if (value2Ptr != NULL) {
7571 TclDecrRefCount(value2Ptr);
7572 }
7573 varPtr->value.objPtr = dictPtr;
7574 }
7575 objResultPtr = dictPtr;
7576 } else {
7577 Tcl_IncrRefCount(dictPtr);
7578 DECACHE_STACK_INFO();
7579 objResultPtr = TclPtrSetVarIdx(interp, varPtr, NULL, NULL, NULL,
7580 dictPtr, TCL_LEAVE_ERR_MSG, opnd);
7581 CACHE_STACK_INFO();
7582 TclDecrRefCount(dictPtr);
7583 if (objResultPtr == NULL) {
7584 TRACE_ERROR(interp);
7585 goto gotError;
7586 }
7587 }
7588 #ifndef TCL_COMPILE_DEBUG
7589 if (*(pc+5) == INST_POP) {
7590 NEXT_INST_F(6, 2, 0);
7591 }
7592 #endif
7593 TRACE_APPEND(("%.30s\n", O2S(objResultPtr)));
7594 NEXT_INST_F(5, 2, 1);
7595
7596 case INST_DICT_FIRST:
7597 opnd = TclGetUInt4AtPtr(pc+1);
7598 TRACE(("%u => ", opnd));
7599 dictPtr = POP_OBJECT();
7600 searchPtr = ckalloc(sizeof(Tcl_DictSearch));
7601 if (Tcl_DictObjFirst(interp, dictPtr, searchPtr, &keyPtr,
7602 &valuePtr, &done) != TCL_OK) {
7603
7604 /*
7605 * dictPtr is no longer on the stack, and we're not
7606 * moving it into the internalrep of an iterator. We need
7607 * to drop the refcount [Tcl Bug 9b352768e6].
7608 */
7609
7610 Tcl_DecrRefCount(dictPtr);
7611 ckfree(searchPtr);
7612 TRACE_ERROR(interp);
7613 goto gotError;
7614 }
7615 TclNewObj(statePtr);
7616 statePtr->typePtr = &dictIteratorType;
7617 statePtr->internalRep.twoPtrValue.ptr1 = searchPtr;
7618 statePtr->internalRep.twoPtrValue.ptr2 = dictPtr;
7619 varPtr = LOCAL(opnd);
7620 if (varPtr->value.objPtr) {
7621 if (varPtr->value.objPtr->typePtr == &dictIteratorType) {
7622 Tcl_Panic("mis-issued dictFirst!");
7623 }
7624 TclDecrRefCount(varPtr->value.objPtr);
7625 }
7626 varPtr->value.objPtr = statePtr;
7627 Tcl_IncrRefCount(statePtr);
7628 goto pushDictIteratorResult;
7629
7630 case INST_DICT_NEXT:
7631 opnd = TclGetUInt4AtPtr(pc+1);
7632 TRACE(("%u => ", opnd));
7633 statePtr = (*LOCAL(opnd)).value.objPtr;
7634 if (statePtr == NULL || statePtr->typePtr != &dictIteratorType) {
7635 Tcl_Panic("mis-issued dictNext!");
7636 }
7637 searchPtr = statePtr->internalRep.twoPtrValue.ptr1;
7638 Tcl_DictObjNext(searchPtr, &keyPtr, &valuePtr, &done);
7639 pushDictIteratorResult:
7640 if (done) {
7641 TclNewObj(emptyPtr);
7642 PUSH_OBJECT(emptyPtr);
7643 PUSH_OBJECT(emptyPtr);
7644 } else {
7645 PUSH_OBJECT(valuePtr);
7646 PUSH_OBJECT(keyPtr);
7647 }
7648 TRACE_APPEND(("\"%.30s\" \"%.30s\" %d\n",
7649 O2S(OBJ_UNDER_TOS), O2S(OBJ_AT_TOS), done));
7650
7651 /*
7652 * The INST_DICT_FIRST and INST_DICT_NEXT instructions are always
7653 * followed by a conditional jump, so we can take advantage of this to
7654 * do some peephole optimization (note that we're careful to not close
7655 * out someone doing something else).
7656 */
7657
7658 JUMP_PEEPHOLE_F(done, 5, 0);
7659
7660 case INST_DICT_UPDATE_START:
7661 opnd = TclGetUInt4AtPtr(pc+1);
7662 opnd2 = TclGetUInt4AtPtr(pc+5);
7663 TRACE(("%u => ", opnd));
7664 varPtr = LOCAL(opnd);
7665 duiPtr = codePtr->auxDataArrayPtr[opnd2].clientData;
7666 while (TclIsVarLink(varPtr)) {
7667 varPtr = varPtr->value.linkPtr;
7668 }
7669 if (TclIsVarDirectReadable(varPtr)) {
7670 dictPtr = varPtr->value.objPtr;
7671 } else {
7672 DECACHE_STACK_INFO();
7673 dictPtr = TclPtrGetVarIdx(interp, varPtr, NULL, NULL, NULL,
7674 TCL_LEAVE_ERR_MSG, opnd);
7675 CACHE_STACK_INFO();
7676 if (dictPtr == NULL) {
7677 TRACE_ERROR(interp);
7678 goto gotError;
7679 }
7680 }
7681 Tcl_IncrRefCount(dictPtr);
7682 if (TclListObjGetElements(interp, OBJ_AT_TOS, &length,
7683 &keyPtrPtr) != TCL_OK) {
7684 TRACE_ERROR(interp);
7685 goto gotError;
7686 }
7687 if (length != duiPtr->length) {
7688 Tcl_Panic("dictUpdateStart argument length mismatch");
7689 }
7690 for (i=0 ; i<length ; i++) {
7691 if (Tcl_DictObjGet(interp, dictPtr, keyPtrPtr[i],
7692 &valuePtr) != TCL_OK) {
7693 TRACE_ERROR(interp);
7694 Tcl_DecrRefCount(dictPtr);
7695 goto gotError;
7696 }
7697 varPtr = LOCAL(duiPtr->varIndices[i]);
7698 while (TclIsVarLink(varPtr)) {
7699 varPtr = varPtr->value.linkPtr;
7700 }
7701 DECACHE_STACK_INFO();
7702 if (valuePtr == NULL) {
7703 TclObjUnsetVar2(interp,
7704 localName(iPtr->varFramePtr, duiPtr->varIndices[i]),
7705 NULL, 0);
7706 } else if (TclPtrSetVarIdx(interp, varPtr, NULL, NULL, NULL,
7707 valuePtr, TCL_LEAVE_ERR_MSG,
7708 duiPtr->varIndices[i]) == NULL) {
7709 CACHE_STACK_INFO();
7710 TRACE_ERROR(interp);
7711 Tcl_DecrRefCount(dictPtr);
7712 goto gotError;
7713 }
7714 CACHE_STACK_INFO();
7715 }
7716 TclDecrRefCount(dictPtr);
7717 TRACE_APPEND(("OK\n"));
7718 NEXT_INST_F(9, 0, 0);
7719
7720 case INST_DICT_UPDATE_END:
7721 opnd = TclGetUInt4AtPtr(pc+1);
7722 opnd2 = TclGetUInt4AtPtr(pc+5);
7723 TRACE(("%u => ", opnd));
7724 varPtr = LOCAL(opnd);
7725 duiPtr = codePtr->auxDataArrayPtr[opnd2].clientData;
7726 while (TclIsVarLink(varPtr)) {
7727 varPtr = varPtr->value.linkPtr;
7728 }
7729 if (TclIsVarDirectReadable(varPtr)) {
7730 dictPtr = varPtr->value.objPtr;
7731 } else {
7732 DECACHE_STACK_INFO();
7733 dictPtr = TclPtrGetVarIdx(interp, varPtr, NULL, NULL, NULL, 0,
7734 opnd);
7735 CACHE_STACK_INFO();
7736 }
7737 if (dictPtr == NULL) {
7738 TRACE_APPEND(("storage was unset\n"));
7739 NEXT_INST_F(9, 1, 0);
7740 }
7741 if (Tcl_DictObjSize(interp, dictPtr, &length) != TCL_OK
7742 || TclListObjGetElements(interp, OBJ_AT_TOS, &length,
7743 &keyPtrPtr) != TCL_OK) {
7744 TRACE_ERROR(interp);
7745 goto gotError;
7746 }
7747 allocdict = Tcl_IsShared(dictPtr);
7748 if (allocdict) {
7749 dictPtr = Tcl_DuplicateObj(dictPtr);
7750 }
7751 if (length > 0) {
7752 TclInvalidateStringRep(dictPtr);
7753 }
7754 for (i=0 ; i<length ; i++) {
7755 Var *var2Ptr = LOCAL(duiPtr->varIndices[i]);
7756
7757 while (TclIsVarLink(var2Ptr)) {
7758 var2Ptr = var2Ptr->value.linkPtr;
7759 }
7760 if (TclIsVarDirectReadable(var2Ptr)) {
7761 valuePtr = var2Ptr->value.objPtr;
7762 } else {
7763 DECACHE_STACK_INFO();
7764 valuePtr = TclPtrGetVarIdx(interp, var2Ptr, NULL, NULL, NULL,
7765 0, duiPtr->varIndices[i]);
7766 CACHE_STACK_INFO();
7767 }
7768 if (valuePtr == NULL) {
7769 Tcl_DictObjRemove(interp, dictPtr, keyPtrPtr[i]);
7770 } else if (dictPtr == valuePtr) {
7771 Tcl_DictObjPut(interp, dictPtr, keyPtrPtr[i],
7772 Tcl_DuplicateObj(valuePtr));
7773 } else {
7774 Tcl_DictObjPut(interp, dictPtr, keyPtrPtr[i], valuePtr);
7775 }
7776 }
7777 if (TclIsVarDirectWritable(varPtr)) {
7778 Tcl_IncrRefCount(dictPtr);
7779 TclDecrRefCount(varPtr->value.objPtr);
7780 varPtr->value.objPtr = dictPtr;
7781 } else {
7782 DECACHE_STACK_INFO();
7783 objResultPtr = TclPtrSetVarIdx(interp, varPtr, NULL, NULL, NULL,
7784 dictPtr, TCL_LEAVE_ERR_MSG, opnd);
7785 CACHE_STACK_INFO();
7786 if (objResultPtr == NULL) {
7787 if (allocdict) {
7788 TclDecrRefCount(dictPtr);
7789 }
7790 TRACE_ERROR(interp);
7791 goto gotError;
7792 }
7793 }
7794 TRACE_APPEND(("written back\n"));
7795 NEXT_INST_F(9, 1, 0);
7796
7797 case INST_DICT_EXPAND:
7798 dictPtr = OBJ_UNDER_TOS;
7799 listPtr = OBJ_AT_TOS;
7800 TRACE(("\"%.30s\" \"%.30s\" =>", O2S(dictPtr), O2S(listPtr)));
7801 if (TclListObjGetElements(interp, listPtr, &objc, &objv) != TCL_OK) {
7802 TRACE_ERROR(interp);
7803 goto gotError;
7804 }
7805 objResultPtr = TclDictWithInit(interp, dictPtr, objc, objv);
7806 if (objResultPtr == NULL) {
7807 TRACE_ERROR(interp);
7808 goto gotError;
7809 }
7810 TRACE_APPEND(("\"%.30s\"\n", O2S(objResultPtr)));
7811 NEXT_INST_F(1, 2, 1);
7812
7813 case INST_DICT_RECOMBINE_STK:
7814 keysPtr = POP_OBJECT();
7815 varNamePtr = OBJ_UNDER_TOS;
7816 listPtr = OBJ_AT_TOS;
7817 TRACE(("\"%.30s\" \"%.30s\" \"%.30s\" => ",
7818 O2S(varNamePtr), O2S(valuePtr), O2S(keysPtr)));
7819 if (TclListObjGetElements(interp, listPtr, &objc, &objv) != TCL_OK) {
7820 TRACE_ERROR(interp);
7821 TclDecrRefCount(keysPtr);
7822 goto gotError;
7823 }
7824 varPtr = TclObjLookupVarEx(interp, varNamePtr, NULL,
7825 TCL_LEAVE_ERR_MSG, "set", 1, 1, &arrayPtr);
7826 if (varPtr == NULL) {
7827 TRACE_ERROR(interp);
7828 TclDecrRefCount(keysPtr);
7829 goto gotError;
7830 }
7831 DECACHE_STACK_INFO();
7832 result = TclDictWithFinish(interp, varPtr,arrayPtr,varNamePtr,NULL,-1,
7833 objc, objv, keysPtr);
7834 CACHE_STACK_INFO();
7835 TclDecrRefCount(keysPtr);
7836 if (result != TCL_OK) {
7837 TRACE_ERROR(interp);
7838 goto gotError;
7839 }
7840 TRACE_APPEND(("OK\n"));
7841 NEXT_INST_F(1, 2, 0);
7842
7843 case INST_DICT_RECOMBINE_IMM:
7844 opnd = TclGetUInt4AtPtr(pc+1);
7845 listPtr = OBJ_UNDER_TOS;
7846 keysPtr = OBJ_AT_TOS;
7847 varPtr = LOCAL(opnd);
7848 TRACE(("%u <- \"%.30s\" \"%.30s\" => ", opnd, O2S(valuePtr),
7849 O2S(keysPtr)));
7850 if (TclListObjGetElements(interp, listPtr, &objc, &objv) != TCL_OK) {
7851 TRACE_ERROR(interp);
7852 goto gotError;
7853 }
7854 while (TclIsVarLink(varPtr)) {
7855 varPtr = varPtr->value.linkPtr;
7856 }
7857 DECACHE_STACK_INFO();
7858 result = TclDictWithFinish(interp, varPtr, NULL, NULL, NULL, opnd,
7859 objc, objv, keysPtr);
7860 CACHE_STACK_INFO();
7861 if (result != TCL_OK) {
7862 TRACE_ERROR(interp);
7863 goto gotError;
7864 }
7865 TRACE_APPEND(("OK\n"));
7866 NEXT_INST_F(5, 2, 0);
7867 }
7868 break;
7869
7870 /*
7871 * End of dictionary-related instructions.
7872 * -----------------------------------------------------------------
7873 */
7874
7875 case INST_CLOCK_READ:
7876 { /* Read the wall clock */
7877 Tcl_WideInt wval;
7878 Tcl_Time now;
7879 switch(TclGetUInt1AtPtr(pc+1)) {
7880 case 0: /* clicks */
7881 #ifdef TCL_WIDE_CLICKS
7882 wval = TclpGetWideClicks();
7883 #else
7884 wval = TclpGetClicks();
7885 #endif
7886 break;
7887 case 1: /* microseconds */
7888 Tcl_GetTime(&now);
7889 wval = (Tcl_WideInt)now.sec * 1000000 + now.usec;
7890 break;
7891 case 2: /* milliseconds */
7892 Tcl_GetTime(&now);
7893 wval = (Tcl_WideInt)now.sec * 1000 + now.usec / 1000;
7894 break;
7895 case 3: /* seconds */
7896 Tcl_GetTime(&now);
7897 wval = now.sec;
7898 break;
7899 default:
7900 Tcl_Panic("clockRead instruction with unknown clock#");
7901 }
7902 objResultPtr = Tcl_NewWideIntObj(wval);
7903 TRACE_WITH_OBJ(("=> "), objResultPtr);
7904 NEXT_INST_F(2, 0, 1);
7905 }
7906 break;
7907
7908 default:
7909 Tcl_Panic("TclNRExecuteByteCode: unrecognized opCode %u", *pc);
7910 } /* end of switch on opCode */
7911
7912 /*
7913 * Block for variables needed to process exception returns.
7914 */
7915
7916 {
7917 ExceptionRange *rangePtr;
7918 /* Points to closest loop or catch exception
7919 * range enclosing the pc. Used by various
7920 * instructions and processCatch to process
7921 * break, continue, and errors. */
7922 const char *bytes;
7923
7924 /*
7925 * An external evaluation (INST_INVOKE or INST_EVAL) returned
7926 * something different from TCL_OK, or else INST_BREAK or
7927 * INST_CONTINUE were called.
7928 */
7929
7930 processExceptionReturn:
7931 #ifdef TCL_COMPILE_DEBUG
7932 switch (*pc) {
7933 case INST_INVOKE_STK1:
7934 opnd = TclGetUInt1AtPtr(pc+1);
7935 TRACE(("%u => ... after \"%.20s\": ", opnd, cmdNameBuf));
7936 break;
7937 case INST_INVOKE_STK4:
7938 opnd = TclGetUInt4AtPtr(pc+1);
7939 TRACE(("%u => ... after \"%.20s\": ", opnd, cmdNameBuf));
7940 break;
7941 case INST_EVAL_STK:
7942 /*
7943 * Note that the object at stacktop has to be used before doing
7944 * the cleanup.
7945 */
7946
7947 TRACE(("\"%.30s\" => ", O2S(OBJ_AT_TOS)));
7948 break;
7949 default:
7950 TRACE(("=> "));
7951 }
7952 #endif
7953 if ((result == TCL_CONTINUE) || (result == TCL_BREAK)) {
7954 rangePtr = GetExceptRangeForPc(pc, result, codePtr);
7955 if (rangePtr == NULL) {
7956 TRACE_APPEND(("no encl. loop or catch, returning %s\n",
7957 StringForResultCode(result)));
7958 goto abnormalReturn;
7959 }
7960 if (rangePtr->type == CATCH_EXCEPTION_RANGE) {
7961 TRACE_APPEND(("%s ...\n", StringForResultCode(result)));
7962 goto processCatch;
7963 }
7964 while (cleanup--) {
7965 valuePtr = POP_OBJECT();
7966 TclDecrRefCount(valuePtr);
7967 }
7968 if (result == TCL_BREAK) {
7969 result = TCL_OK;
7970 pc = (codePtr->codeStart + rangePtr->breakOffset);
7971 TRACE_APPEND(("%s, range at %d, new pc %d\n",
7972 StringForResultCode(result),
7973 rangePtr->codeOffset, rangePtr->breakOffset));
7974 NEXT_INST_F(0, 0, 0);
7975 }
7976 if (rangePtr->continueOffset == -1) {
7977 TRACE_APPEND(("%s, loop w/o continue, checking for catch\n",
7978 StringForResultCode(result)));
7979 goto checkForCatch;
7980 }
7981 result = TCL_OK;
7982 pc = (codePtr->codeStart + rangePtr->continueOffset);
7983 TRACE_APPEND(("%s, range at %d, new pc %d\n",
7984 StringForResultCode(result),
7985 rangePtr->codeOffset, rangePtr->continueOffset));
7986 NEXT_INST_F(0, 0, 0);
7987 }
7988 #ifdef TCL_COMPILE_DEBUG
7989 if (traceInstructions) {
7990 objPtr = Tcl_GetObjResult(interp);
7991 if ((result != TCL_ERROR) && (result != TCL_RETURN)) {
7992 TRACE_APPEND(("OTHER RETURN CODE %d, result=\"%.30s\"\n ",
7993 result, O2S(objPtr)));
7994 } else {
7995 TRACE_APPEND(("%s, result=\"%.30s\"\n",
7996 StringForResultCode(result), O2S(objPtr)));
7997 }
7998 }
7999 #endif
8000 goto checkForCatch;
8001
8002 /*
8003 * Division by zero in an expression. Control only reaches this point
8004 * by "goto divideByZero".
8005 */
8006
8007 divideByZero:
8008 Tcl_SetObjResult(interp, Tcl_NewStringObj("divide by zero", -1));
8009 DECACHE_STACK_INFO();
8010 Tcl_SetErrorCode(interp, "ARITH", "DIVZERO", "divide by zero", (char *)NULL);
8011 CACHE_STACK_INFO();
8012 goto gotError;
8013
8014 /*
8015 * Exponentiation of zero by negative number in an expression. Control
8016 * only reaches this point by "goto exponOfZero".
8017 */
8018
8019 exponOfZero:
8020 Tcl_SetObjResult(interp, Tcl_NewStringObj(
8021 "exponentiation of zero by negative power", -1));
8022 DECACHE_STACK_INFO();
8023 Tcl_SetErrorCode(interp, "ARITH", "DOMAIN",
8024 "exponentiation of zero by negative power", (char *)NULL);
8025 CACHE_STACK_INFO();
8026
8027 /*
8028 * Almost all error paths feed through here rather than assigning to
8029 * result themselves (for a small but consistent saving).
8030 */
8031
8032 gotError:
8033 result = TCL_ERROR;
8034
8035 /*
8036 * Execution has generated an "exception" such as TCL_ERROR. If the
8037 * exception is an error, record information about what was being
8038 * executed when the error occurred. Find the closest enclosing catch
8039 * range, if any. If no enclosing catch range is found, stop execution
8040 * and return the "exception" code.
8041 */
8042
8043 checkForCatch:
8044 if (iPtr->execEnvPtr->rewind) {
8045 goto abnormalReturn;
8046 }
8047 if ((result == TCL_ERROR) && !(iPtr->flags & ERR_ALREADY_LOGGED)) {
8048 const unsigned char *pcBeg;
8049
8050 bytes = GetSrcInfoForPc(pc, codePtr, &length, &pcBeg, NULL);
8051 DECACHE_STACK_INFO();
8052 TclLogCommandInfo(interp, codePtr->source, bytes,
8053 bytes ? length : 0, pcBeg, tosPtr);
8054 CACHE_STACK_INFO();
8055 }
8056 iPtr->flags &= ~ERR_ALREADY_LOGGED;
8057
8058 /*
8059 * Clear all expansions that may have started after the last
8060 * INST_BEGIN_CATCH.
8061 */
8062
8063 while (auxObjList) {
8064 if ((catchTop != initCatchTop)
8065 && (*catchTop > (ptrdiff_t)
8066 auxObjList->internalRep.twoPtrValue.ptr2)) {
8067 break;
8068 }
8069 POP_TAUX_OBJ();
8070 }
8071
8072 /*
8073 * We must not catch if the script in progress has been canceled with
8074 * the TCL_CANCEL_UNWIND flag. Instead, it blows outwards until we
8075 * either hit another interpreter (presumably where the script in
8076 * progress has not been canceled) or we get to the top-level. We do
8077 * NOT modify the interpreter result here because we know it will
8078 * already be set prior to vectoring down to this point in the code.
8079 */
8080
8081 if (TclCanceled(iPtr) && (Tcl_Canceled(interp, 0) == TCL_ERROR)) {
8082 #ifdef TCL_COMPILE_DEBUG
8083 if (traceInstructions) {
8084 fprintf(stdout, " ... cancel with unwind, returning %s\n",
8085 StringForResultCode(result));
8086 }
8087 #endif
8088 goto abnormalReturn;
8089 }
8090
8091 /*
8092 * We must not catch an exceeded limit. Instead, it blows outwards
8093 * until we either hit another interpreter (presumably where the limit
8094 * is not exceeded) or we get to the top-level.
8095 */
8096
8097 if (TclLimitExceeded(iPtr->limit)) {
8098 #ifdef TCL_COMPILE_DEBUG
8099 if (traceInstructions) {
8100 fprintf(stdout, " ... limit exceeded, returning %s\n",
8101 StringForResultCode(result));
8102 }
8103 #endif
8104 goto abnormalReturn;
8105 }
8106 if (catchTop == initCatchTop) {
8107 #ifdef TCL_COMPILE_DEBUG
8108 if (traceInstructions) {
8109 fprintf(stdout, " ... no enclosing catch, returning %s\n",
8110 StringForResultCode(result));
8111 }
8112 #endif
8113 goto abnormalReturn;
8114 }
8115 rangePtr = GetExceptRangeForPc(pc, TCL_ERROR, codePtr);
8116 if (rangePtr == NULL) {
8117 /*
8118 * This is only possible when compiling a [catch] that sends its
8119 * script to INST_EVAL. Cannot correct the compiler without
8120 * breaking compat with previous .tbc compiled scripts.
8121 */
8122
8123 #ifdef TCL_COMPILE_DEBUG
8124 if (traceInstructions) {
8125 fprintf(stdout, " ... no enclosing catch, returning %s\n",
8126 StringForResultCode(result));
8127 }
8128 #endif
8129 goto abnormalReturn;
8130 }
8131
8132 /*
8133 * A catch exception range (rangePtr) was found to handle an
8134 * "exception". It was found either by checkForCatch just above or by
8135 * an instruction during break, continue, or error processing. Jump to
8136 * its catchOffset after unwinding the operand stack to the depth it
8137 * had when starting to execute the range's catch command.
8138 */
8139
8140 processCatch:
8141 while (CURR_DEPTH > *catchTop) {
8142 valuePtr = POP_OBJECT();
8143 TclDecrRefCount(valuePtr);
8144 }
8145 #ifdef TCL_COMPILE_DEBUG
8146 if (traceInstructions) {
8147 fprintf(stdout, " ... found catch at %d, catchTop=%d, "
8148 "unwound to %ld, new pc %u\n",
8149 rangePtr->codeOffset, (int) (catchTop - initCatchTop - 1),
8150 (long) *catchTop, (unsigned) rangePtr->catchOffset);
8151 }
8152 #endif
8153 pc = (codePtr->codeStart + rangePtr->catchOffset);
8154 NEXT_INST_F(0, 0, 0); /* Restart the execution loop at pc. */
8155
8156 /*
8157 * end of infinite loop dispatching on instructions.
8158 */
8159
8160 /*
8161 * Done or abnormal return code. Restore the stack to state it had when
8162 * starting to execute the ByteCode. Panic if the stack is below the
8163 * initial level.
8164 */
8165
8166 abnormalReturn:
8167 TCL_DTRACE_INST_LAST();
8168
8169 /*
8170 * Clear all expansions and same-level NR calls.
8171 *
8172 * Note that expansion markers have a NULL type; avoid removing other
8173 * markers.
8174 */
8175
8176 while (auxObjList) {
8177 POP_TAUX_OBJ();
8178 }
8179 while (tosPtr > initTosPtr) {
8180 objPtr = POP_OBJECT();
8181 Tcl_DecrRefCount(objPtr);
8182 }
8183
8184 if (tosPtr < initTosPtr) {
8185 fprintf(stderr,
8186 "\nTclNRExecuteByteCode: abnormal return at pc %u: "
8187 "stack top %d < entry stack top %d\n",
8188 (unsigned)(pc - codePtr->codeStart),
8189 (unsigned) CURR_DEPTH, (unsigned) 0);
8190 Tcl_Panic("TclNRExecuteByteCode execution failure: end stack top < start stack top");
8191 }
8192 CLANG_ASSERT(bcFramePtr);
8193 }
8194
8195 iPtr->cmdFramePtr = bcFramePtr->nextPtr;
8196 if (codePtr->refCount-- <= 1) {
8197 TclCleanupByteCode(codePtr);
8198 }
8199 TclStackFree(interp, TD); /* free my stack */
8200
8201 return result;
8202
8203 /*
8204 * INST_START_CMD failure case removed where it doesn't bother that much
8205 *
8206 * Remark that if the interpreter is marked for deletion its
8207 * compileEpoch is modified, so that the epoch check also verifies
8208 * that the interp is not deleted. If no outside call has been made
8209 * since the last check, it is safe to omit the check.
8210
8211 * case INST_START_CMD:
8212 */
8213
8214 instStartCmdFailed:
8215 {
8216 const char *bytes;
8217
8218 length = 0;
8219
8220 if (TclInterpReady(interp) == TCL_ERROR) {
8221 goto gotError;
8222 }
8223
8224 /*
8225 * We used to switch to direct eval; for NRE-awareness we now
8226 * compile and eval the command so that this evaluation does not
8227 * add a new TEBC instance. Bug [2910748], bug [fa6bf38d07]
8228 *
8229 * TODO: recompile, search this command and eval a code starting from,
8230 * so that this evaluation does not add a new TEBC instance without
8231 * NRE-trampoline.
8232 */
8233
8234 codePtr->flags |= TCL_BYTECODE_RECOMPILE;
8235 bytes = GetSrcInfoForPc(pc, codePtr, &length, NULL, NULL);
8236 opnd = TclGetUInt4AtPtr(pc+1);
8237 pc += (opnd-1);
8238 assert(bytes);
8239 PUSH_OBJECT(Tcl_NewStringObj(bytes, length));
8240 goto instEvalStk;
8241 }
8242 }
8243
8244 #undef codePtr
8245 #undef iPtr
8246 #undef bcFramePtr
8247 #undef initCatchTop
8248 #undef initTosPtr
8249 #undef auxObjList
8250 #undef catchTop
8251 #undef TCONST
8252 #undef esPtr
8253
8254 static int
8255 FinalizeOONext(
8256 ClientData data[],
8257 Tcl_Interp *interp,
8258 int result)
8259 {
8260 Interp *iPtr = (Interp *) interp;
8261 CallContext *contextPtr = data[1];
8262
8263 /*
8264 * Reset the variable lookup frame.
8265 */
8266
8267 iPtr->varFramePtr = data[0];
8268
8269 /*
8270 * Restore the call chain context index as we've finished the inner invoke
8271 * and want to operate in the outer context again.
8272 */
8273
8274 contextPtr->index = PTR2INT(data[2]);
8275 contextPtr->skip = PTR2INT(data[3]);
8276 contextPtr->oPtr->flags &= ~FILTER_HANDLING;
8277 return result;
8278 }
8279
8280 static int
8281 FinalizeOONextFilter(
8282 ClientData data[],
8283 Tcl_Interp *interp,
8284 int result)
8285 {
8286 Interp *iPtr = (Interp *) interp;
8287 CallContext *contextPtr = data[1];
8288
8289 /*
8290 * Reset the variable lookup frame.
8291 */
8292
8293 iPtr->varFramePtr = data[0];
8294
8295 /*
8296 * Restore the call chain context index as we've finished the inner invoke
8297 * and want to operate in the outer context again.
8298 */
8299
8300 contextPtr->index = PTR2INT(data[2]);
8301 contextPtr->skip = PTR2INT(data[3]);
8302 contextPtr->oPtr->flags |= FILTER_HANDLING;
8303 return result;
8304 }
8305
8306 /*
8307 * LongPwrSmallExpon -- , WidePwrSmallExpon --
8308 *
8309 * Helpers to calculate small powers of integers whose result is long or wide.
8310 */
8311 #if (LONG_MAX == 0x7FFFFFFF)
8312 static inline long
8313 LongPwrSmallExpon(long l1, long exponent) {
8314
8315 long lResult;
8316
8317 lResult = l1 * l1; /* b**2 */
8318 switch (exponent) {
8319 case 2:
8320 break;
8321 case 3:
8322 lResult *= l1; /* b**3 */
8323 break;
8324 case 4:
8325 lResult *= lResult; /* b**4 */
8326 break;
8327 case 5:
8328 lResult *= lResult; /* b**4 */
8329 lResult *= l1; /* b**5 */
8330 break;
8331 case 6:
8332 lResult *= l1; /* b**3 */
8333 lResult *= lResult; /* b**6 */
8334 break;
8335 case 7:
8336 lResult *= l1; /* b**3 */
8337 lResult *= lResult; /* b**6 */
8338 lResult *= l1; /* b**7 */
8339 break;
8340 case 8:
8341 lResult *= lResult; /* b**4 */
8342 lResult *= lResult; /* b**8 */
8343 break;
8344 }
8345 return lResult;
8346 }
8347 #endif
8348 static inline Tcl_WideInt
8349 WidePwrSmallExpon(Tcl_WideInt w1, long exponent) {
8350
8351 Tcl_WideInt wResult;
8352
8353 wResult = w1 * w1; /* b**2 */
8354 switch (exponent) {
8355 case 2:
8356 break;
8357 case 3:
8358 wResult *= w1; /* b**3 */
8359 break;
8360 case 4:
8361 wResult *= wResult; /* b**4 */
8362 break;
8363 case 5:
8364 wResult *= wResult; /* b**4 */
8365 wResult *= w1; /* b**5 */
8366 break;
8367 case 6:
8368 wResult *= w1; /* b**3 */
8369 wResult *= wResult; /* b**6 */
8370 break;
8371 case 7:
8372 wResult *= w1; /* b**3 */
8373 wResult *= wResult; /* b**6 */
8374 wResult *= w1; /* b**7 */
8375 break;
8376 case 8:
8377 wResult *= wResult; /* b**4 */
8378 wResult *= wResult; /* b**8 */
8379 break;
8380 case 9:
8381 wResult *= wResult; /* b**4 */
8382 wResult *= wResult; /* b**8 */
8383 wResult *= w1; /* b**9 */
8384 break;
8385 case 10:
8386 wResult *= wResult; /* b**4 */
8387 wResult *= w1; /* b**5 */
8388 wResult *= wResult; /* b**10 */
8389 break;
8390 case 11:
8391 wResult *= wResult; /* b**4 */
8392 wResult *= w1; /* b**5 */
8393 wResult *= wResult; /* b**10 */
8394 wResult *= w1; /* b**11 */
8395 break;
8396 case 12:
8397 wResult *= w1; /* b**3 */
8398 wResult *= wResult; /* b**6 */
8399 wResult *= wResult; /* b**12 */
8400 break;
8401 case 13:
8402 wResult *= w1; /* b**3 */
8403 wResult *= wResult; /* b**6 */
8404 wResult *= wResult; /* b**12 */
8405 wResult *= w1; /* b**13 */
8406 break;
8407 case 14:
8408 wResult *= w1; /* b**3 */
8409 wResult *= wResult; /* b**6 */
8410 wResult *= w1; /* b**7 */
8411 wResult *= wResult; /* b**14 */
8412 break;
8413 case 15:
8414 wResult *= w1; /* b**3 */
8415 wResult *= wResult; /* b**6 */
8416 wResult *= w1; /* b**7 */
8417 wResult *= wResult; /* b**14 */
8418 wResult *= w1; /* b**15 */
8419 break;
8420 case 16:
8421 wResult *= wResult; /* b**4 */
8422 wResult *= wResult; /* b**8 */
8423 wResult *= wResult; /* b**16 */
8424 break;
8425 }
8426 return wResult;
8427 }
8428 /*
8429 *----------------------------------------------------------------------
8430 *
8431 * ExecuteExtendedBinaryMathOp, ExecuteExtendedUnaryMathOp --
8432 *
8433 * These functions do advanced math for binary and unary operators
8434 * respectively, so that the main TEBC code does not bear the cost of
8435 * them.
8436 *
8437 * Results:
8438 * A Tcl_Obj* result, or a NULL (in which case valuePtr is updated to
8439 * hold the result value), or one of the special flag values
8440 * GENERAL_ARITHMETIC_ERROR, EXPONENT_OF_ZERO or DIVIDED_BY_ZERO. The
8441 * latter two signify a zero value raised to a negative power or a value
8442 * divided by zero, respectively. With GENERAL_ARITHMETIC_ERROR, all
8443 * error information will have already been reported in the interpreter
8444 * result.
8445 *
8446 * Side effects:
8447 * May update the Tcl_Obj indicated valuePtr if it is unshared. Will
8448 * return a NULL when that happens.
8449 *
8450 *----------------------------------------------------------------------
8451 */
8452
8453 static Tcl_Obj *
8454 ExecuteExtendedBinaryMathOp(
8455 Tcl_Interp *interp, /* Where to report errors. */
8456 int opcode, /* What operation to perform. */
8457 Tcl_Obj **constants, /* The execution environment's constants. */
8458 Tcl_Obj *valuePtr, /* The first operand on the stack. */
8459 Tcl_Obj *value2Ptr) /* The second operand on the stack. */
8460 {
8461 #define LONG_RESULT(l) \
8462 if (Tcl_IsShared(valuePtr)) { \
8463 TclNewLongObj(objResultPtr, (l)); \
8464 return objResultPtr; \
8465 } else { \
8466 Tcl_SetLongObj(valuePtr, (l)); \
8467 return NULL; \
8468 }
8469 #define WIDE_RESULT(w) \
8470 if (Tcl_IsShared(valuePtr)) { \
8471 return Tcl_NewWideIntObj(w); \
8472 } else { \
8473 Tcl_SetWideIntObj(valuePtr, (w)); \
8474 return NULL; \
8475 }
8476 #define BIG_RESULT(b) \
8477 if (Tcl_IsShared(valuePtr)) { \
8478 return Tcl_NewBignumObj(b); \
8479 } else { \
8480 Tcl_SetBignumObj(valuePtr, (b)); \
8481 return NULL; \
8482 }
8483 #define DOUBLE_RESULT(d) \
8484 if (Tcl_IsShared(valuePtr)) { \
8485 TclNewDoubleObj(objResultPtr, (d)); \
8486 return objResultPtr; \
8487 } else { \
8488 Tcl_SetDoubleObj(valuePtr, (d)); \
8489 return NULL; \
8490 }
8491
8492 int type1, type2;
8493 ClientData ptr1, ptr2;
8494 double d1, d2, dResult;
8495 long l1, l2, lResult;
8496 Tcl_WideInt w1, w2, wResult;
8497 mp_int big1, big2, bigResult, bigRemainder;
8498 Tcl_Obj *objResultPtr;
8499 int invalid, zero;
8500 int shift;
8501
8502 (void) GetNumberFromObj(NULL, valuePtr, &ptr1, &type1);
8503 (void) GetNumberFromObj(NULL, value2Ptr, &ptr2, &type2);
8504
8505 switch (opcode) {
8506 case INST_MOD:
8507 /* TODO: Attempts to re-use unshared operands on stack */
8508
8509 l2 = 0; /* silence gcc warning */
8510 if (type2 == TCL_NUMBER_LONG) {
8511 l2 = *((const long *)ptr2);
8512 if (l2 == 0) {
8513 return DIVIDED_BY_ZERO;
8514 }
8515 if ((l2 == 1) || (l2 == -1)) {
8516 /*
8517 * Div. by |1| always yields remainder of 0.
8518 */
8519
8520 return constants[0];
8521 }
8522 }
8523 #ifndef TCL_WIDE_INT_IS_LONG
8524 if (type1 == TCL_NUMBER_WIDE) {
8525 w1 = *((const Tcl_WideInt *)ptr1);
8526 if (type2 != TCL_NUMBER_BIG) {
8527 Tcl_WideInt wQuotient, wRemainder;
8528 TclGetWideIntFromObj(NULL, value2Ptr, &w2);
8529 wQuotient = w1 / w2;
8530
8531 /*
8532 * Force Tcl's integer division rules.
8533 * TODO: examine for logic simplification
8534 */
8535
8536 if (((wQuotient < 0)
8537 || ((wQuotient == 0)
8538 && ((w1 < 0 && w2 > 0)
8539 || (w1 > 0 && w2 < 0))))
8540 && (wQuotient * w2 != w1)) {
8541 wQuotient--;
8542 }
8543 wRemainder = (Tcl_WideInt)((Tcl_WideUInt)w1 -
8544 (Tcl_WideUInt)w2*(Tcl_WideUInt)wQuotient);
8545 WIDE_RESULT(wRemainder);
8546 }
8547
8548 Tcl_TakeBignumFromObj(NULL, value2Ptr, &big2);
8549
8550 if ((w1 > 0) ^ !mp_isneg(&big2)) {
8551 /*
8552 * Arguments are opposite sign; remainder is sum.
8553 */
8554
8555 TclBNInitBignumFromWideInt(&big1, w1);
8556 mp_add(&big2, &big1, &big2);
8557 mp_clear(&big1);
8558 BIG_RESULT(&big2);
8559 }
8560
8561 /*
8562 * Arguments are same sign; remainder is first operand.
8563 */
8564
8565 mp_clear(&big2);
8566 return NULL;
8567 }
8568 #endif
8569 Tcl_GetBignumFromObj(NULL, valuePtr, &big1);
8570 Tcl_GetBignumFromObj(NULL, value2Ptr, &big2);
8571 mp_init(&bigResult);
8572 mp_init(&bigRemainder);
8573 mp_div(&big1, &big2, &bigResult, &bigRemainder);
8574 if (!mp_iszero(&bigRemainder) && (mp_isneg(&bigRemainder) != mp_isneg(&big2))) {
8575 /*
8576 * Convert to Tcl's integer division rules.
8577 */
8578
8579 mp_sub_d(&bigResult, 1, &bigResult);
8580 mp_add(&bigRemainder, &big2, &bigRemainder);
8581 }
8582 mp_copy(&bigRemainder, &bigResult);
8583 mp_clear(&bigRemainder);
8584 mp_clear(&big1);
8585 mp_clear(&big2);
8586 BIG_RESULT(&bigResult);
8587
8588 case INST_LSHIFT:
8589 case INST_RSHIFT: {
8590 /*
8591 * Reject negative shift argument.
8592 */
8593
8594 switch (type2) {
8595 case TCL_NUMBER_LONG:
8596 invalid = (*((const long *)ptr2) < 0L);
8597 break;
8598 #ifndef TCL_WIDE_INT_IS_LONG
8599 case TCL_NUMBER_WIDE:
8600 invalid = (*((const Tcl_WideInt *)ptr2) < 0);
8601 break;
8602 #endif
8603 case TCL_NUMBER_BIG:
8604 Tcl_TakeBignumFromObj(NULL, value2Ptr, &big2);
8605 invalid = mp_isneg(&big2);
8606 mp_clear(&big2);
8607 break;
8608 default:
8609 /* Unused, here to silence compiler warning */
8610 invalid = 0;
8611 }
8612 if (invalid) {
8613 Tcl_SetObjResult(interp, Tcl_NewStringObj(
8614 "negative shift argument", -1));
8615 return GENERAL_ARITHMETIC_ERROR;
8616 }
8617
8618 /*
8619 * Zero shifted any number of bits is still zero.
8620 */
8621
8622 if ((type1==TCL_NUMBER_LONG) && (*((const long *)ptr1) == (long)0)) {
8623 return constants[0];
8624 }
8625
8626 if (opcode == INST_LSHIFT) {
8627 /*
8628 * Large left shifts create integer overflow.
8629 *
8630 * BEWARE! Can't use Tcl_GetIntFromObj() here because that
8631 * converts values in the (unsigned) range to their signed int
8632 * counterparts, leading to incorrect results.
8633 */
8634
8635 if ((type2 != TCL_NUMBER_LONG)
8636 || (*((const long *)ptr2) > (long) INT_MAX)) {
8637 /*
8638 * Technically, we could hold the value (1 << (INT_MAX+1)) in
8639 * an mp_int, but since we're using mp_mul_2d() to do the
8640 * work, and it takes only an int argument, that's a good
8641 * place to draw the line.
8642 */
8643
8644 Tcl_SetObjResult(interp, Tcl_NewStringObj(
8645 "integer value too large to represent", -1));
8646 return GENERAL_ARITHMETIC_ERROR;
8647 }
8648 shift = (int)(*((const long *)ptr2));
8649
8650 /*
8651 * Handle shifts within the native wide range.
8652 */
8653
8654 if ((type1 != TCL_NUMBER_BIG)
8655 && ((size_t)shift < CHAR_BIT*sizeof(Tcl_WideInt))) {
8656 TclGetWideIntFromObj(NULL, valuePtr, &w1);
8657 if (!((w1>0 ? w1 : ~w1)
8658 & -(((Tcl_WideUInt)1)
8659 << (CHAR_BIT*sizeof(Tcl_WideInt) - 1 - shift)))) {
8660 WIDE_RESULT((Tcl_WideUInt)w1 << shift);
8661 }
8662 }
8663 } else {
8664 /*
8665 * Quickly force large right shifts to 0 or -1.
8666 */
8667
8668 if ((type2 != TCL_NUMBER_LONG)
8669 || (*(const long *)ptr2 > INT_MAX)) {
8670 /*
8671 * Again, technically, the value to be shifted could be an
8672 * mp_int so huge that a right shift by (INT_MAX+1) bits could
8673 * not take us to the result of 0 or -1, but since we're using
8674 * mp_div_2d to do the work, and it takes only an int
8675 * argument, we draw the line there.
8676 */
8677
8678 switch (type1) {
8679 case TCL_NUMBER_LONG:
8680 zero = (*(const long *)ptr1 > 0L);
8681 break;
8682 #ifndef TCL_WIDE_INT_IS_LONG
8683 case TCL_NUMBER_WIDE:
8684 zero = (*(const Tcl_WideInt *)ptr1 > 0);
8685 break;
8686 #endif
8687 case TCL_NUMBER_BIG:
8688 Tcl_TakeBignumFromObj(NULL, valuePtr, &big1);
8689 zero = (mp_cmp_d(&big1, 0) == MP_GT);
8690 mp_clear(&big1);
8691 break;
8692 default:
8693 /* Unused, here to silence compiler warning. */
8694 zero = 0;
8695 }
8696 if (zero) {
8697 return constants[0];
8698 }
8699 LONG_RESULT(-1);
8700 }
8701 shift = (int)(*(const long *)ptr2);
8702
8703 #ifndef TCL_WIDE_INT_IS_LONG
8704 /*
8705 * Handle shifts within the native wide range.
8706 */
8707
8708 if (type1 == TCL_NUMBER_WIDE) {
8709 w1 = *(const Tcl_WideInt *)ptr1;
8710 if ((size_t)shift >= CHAR_BIT*sizeof(Tcl_WideInt)) {
8711 if (w1 >= 0) {
8712 return constants[0];
8713 }
8714 LONG_RESULT(-1);
8715 }
8716 WIDE_RESULT(w1 >> shift);
8717 }
8718 #endif
8719 }
8720
8721 Tcl_TakeBignumFromObj(NULL, valuePtr, &big1);
8722
8723 mp_init(&bigResult);
8724 if (opcode == INST_LSHIFT) {
8725 mp_mul_2d(&big1, shift, &bigResult);
8726 } else {
8727 mp_signed_rsh(&big1, shift, &bigResult);
8728 }
8729 mp_clear(&big1);
8730 BIG_RESULT(&bigResult);
8731 }
8732
8733 case INST_BITOR:
8734 case INST_BITXOR:
8735 case INST_BITAND:
8736 if ((type1 == TCL_NUMBER_BIG) || (type2 == TCL_NUMBER_BIG)) {
8737 Tcl_TakeBignumFromObj(NULL, valuePtr, &big1);
8738 Tcl_TakeBignumFromObj(NULL, value2Ptr, &big2);
8739
8740 mp_init(&bigResult);
8741
8742 switch (opcode) {
8743 case INST_BITAND:
8744 mp_and(&big1, &big2, &bigResult);
8745 break;
8746
8747 case INST_BITOR:
8748 mp_or(&big1, &big2, &bigResult);
8749 break;
8750
8751 case INST_BITXOR:
8752 mp_xor(&big1, &big2, &bigResult);
8753 break;
8754 }
8755
8756 mp_clear(&big1);
8757 mp_clear(&big2);
8758 BIG_RESULT(&bigResult);
8759 }
8760
8761 #ifndef TCL_WIDE_INT_IS_LONG
8762 if ((type1 == TCL_NUMBER_WIDE) || (type2 == TCL_NUMBER_WIDE)) {
8763 TclGetWideIntFromObj(NULL, valuePtr, &w1);
8764 TclGetWideIntFromObj(NULL, value2Ptr, &w2);
8765
8766 switch (opcode) {
8767 case INST_BITAND:
8768 wResult = w1 & w2;
8769 break;
8770 case INST_BITOR:
8771 wResult = w1 | w2;
8772 break;
8773 case INST_BITXOR:
8774 wResult = w1 ^ w2;
8775 break;
8776 default:
8777 /* Unused, here to silence compiler warning. */
8778 wResult = 0;
8779 }
8780 WIDE_RESULT(wResult);
8781 }
8782 #endif
8783 l1 = *((const long *)ptr1);
8784 l2 = *((const long *)ptr2);
8785
8786 switch (opcode) {
8787 case INST_BITAND:
8788 lResult = l1 & l2;
8789 break;
8790 case INST_BITOR:
8791 lResult = l1 | l2;
8792 break;
8793 case INST_BITXOR:
8794 lResult = l1 ^ l2;
8795 break;
8796 default:
8797 /* Unused, here to silence compiler warning. */
8798 lResult = 0;
8799 }
8800 LONG_RESULT(lResult);
8801
8802 case INST_EXPON: {
8803 int oddExponent = 0, negativeExponent = 0;
8804 unsigned short base;
8805
8806 if ((type1 == TCL_NUMBER_DOUBLE) || (type2 == TCL_NUMBER_DOUBLE)) {
8807 Tcl_GetDoubleFromObj(NULL, valuePtr, &d1);
8808 Tcl_GetDoubleFromObj(NULL, value2Ptr, &d2);
8809
8810 if (d1==0.0 && d2<0.0) {
8811 return EXPONENT_OF_ZERO;
8812 }
8813 dResult = pow(d1, d2);
8814 goto doubleResult;
8815 }
8816 l1 = l2 = 0;
8817 w1 = w2 = 0; /* to silence compiler warning (maybe-uninitialized) */
8818 switch (type2) {
8819 case TCL_NUMBER_LONG:
8820 l2 = *((const long *) ptr2);
8821 #ifndef TCL_WIDE_INT_IS_LONG
8822 pwrLongExpon:
8823 #endif
8824 if (l2 == 0) {
8825 /*
8826 * Anything to the zero power is 1.
8827 */
8828
8829 return constants[1];
8830 } else if (l2 == 1) {
8831 /*
8832 * Anything to the first power is itself
8833 */
8834
8835 return NULL;
8836 }
8837 negativeExponent = (l2 < 0);
8838 oddExponent = (int) (l2 & 1);
8839 break;
8840 #ifndef TCL_WIDE_INT_IS_LONG
8841 case TCL_NUMBER_WIDE:
8842 w2 = *((const Tcl_WideInt *)ptr2);
8843 /* check it fits in long */
8844 l2 = (long)w2;
8845 if (w2 == l2) {
8846 type2 = TCL_NUMBER_LONG;
8847 goto pwrLongExpon;
8848 }
8849 negativeExponent = (w2 < 0);
8850 oddExponent = (int) (w2 & (Tcl_WideInt)1);
8851 break;
8852 #endif
8853 case TCL_NUMBER_BIG:
8854 Tcl_TakeBignumFromObj(NULL, value2Ptr, &big2);
8855 negativeExponent = mp_isneg(&big2);
8856 mp_mod_2d(&big2, 1, &big2);
8857 oddExponent = !mp_iszero(&big2);
8858 mp_clear(&big2);
8859 break;
8860 }
8861
8862 switch (type1) {
8863 case TCL_NUMBER_LONG:
8864 l1 = *((const long *)ptr1);
8865 #ifndef TCL_WIDE_INT_IS_LONG
8866 pwrLongBase:
8867 #endif
8868 switch (l1) {
8869 case 0:
8870 /*
8871 * Zero to a positive power is zero.
8872 * Zero to a negative power is div by zero error.
8873 */
8874
8875 return (!negativeExponent) ? constants[0] : EXPONENT_OF_ZERO;
8876 case 1:
8877 /*
8878 * 1 to any power is 1.
8879 */
8880
8881 return constants[1];
8882 case -1:
8883 if (!negativeExponent) {
8884 if (!oddExponent) {
8885 return constants[1];
8886 }
8887 LONG_RESULT(-1);
8888 }
8889 /* negativeExponent */
8890 if (oddExponent) {
8891 LONG_RESULT(-1);
8892 }
8893 return constants[1];
8894 }
8895 break;
8896 #ifndef TCL_WIDE_INT_IS_LONG
8897 case TCL_NUMBER_WIDE:
8898 w1 = *((const Tcl_WideInt *) ptr1);
8899 /* check it fits in long */
8900 l1 = (long)w1;
8901 if (w1 == l1) {
8902 type1 = TCL_NUMBER_LONG;
8903 goto pwrLongBase;
8904 }
8905 #endif
8906 }
8907 if (negativeExponent) {
8908
8909 /*
8910 * Integers with magnitude greater than 1 raise to a negative
8911 * power yield the answer zero (see TIP 123).
8912 */
8913 return constants[0];
8914 }
8915
8916
8917 if (type1 == TCL_NUMBER_BIG) {
8918 goto overflowExpon;
8919 }
8920
8921 /*
8922 * We refuse to accept exponent arguments that exceed one mp_digit
8923 * which means the max exponent value is 2**28-1 = 0x0FFFFFFF =
8924 * 268435455, which fits into a signed 32 bit int which is within the
8925 * range of the long type. This means any numeric Tcl_Obj value
8926 * not using TCL_NUMBER_LONG type must hold a value larger than we
8927 * accept.
8928 */
8929
8930 if (type2 != TCL_NUMBER_LONG) {
8931 Tcl_SetObjResult(interp, Tcl_NewStringObj(
8932 "exponent too large", -1));
8933 return GENERAL_ARITHMETIC_ERROR;
8934 }
8935
8936 /* From here (up to overflowExpon) exponent is long (l2). */
8937
8938 if (type1 == TCL_NUMBER_LONG) {
8939 if (l1 == 2) {
8940 /*
8941 * Reduce small powers of 2 to shifts.
8942 */
8943
8944 if ((unsigned long) l2 < CHAR_BIT * sizeof(long) - 1) {
8945 LONG_RESULT(1L << l2);
8946 }
8947 #if !defined(TCL_WIDE_INT_IS_LONG)
8948 if ((unsigned long)l2 < CHAR_BIT*sizeof(Tcl_WideInt) - 1) {
8949 WIDE_RESULT(((Tcl_WideInt)1) << l2);
8950 }
8951 #endif
8952 goto overflowExpon;
8953 }
8954 if (l1 == -2) {
8955 int signum = oddExponent ? -1 : 1;
8956
8957 /*
8958 * Reduce small powers of 2 to shifts.
8959 */
8960
8961 if ((unsigned long) l2 < CHAR_BIT * sizeof(long) - 1) {
8962 LONG_RESULT(signum * (1L << l2));
8963 }
8964 #if !defined(TCL_WIDE_INT_IS_LONG)
8965 if ((unsigned long)l2 < CHAR_BIT*sizeof(Tcl_WideInt) - 1){
8966 WIDE_RESULT(signum * (((Tcl_WideInt)1) << l2));
8967 }
8968 #endif
8969 goto overflowExpon;
8970 }
8971 #if (LONG_MAX == 0x7FFFFFFF)
8972 if (l2 - 2 < (long)MaxBase32Size
8973 && l1 <= MaxBase32[l2 - 2]
8974 && l1 >= -MaxBase32[l2 - 2]) {
8975 /*
8976 * Small powers of 32-bit integers.
8977 */
8978 lResult = LongPwrSmallExpon(l1, l2);
8979
8980 LONG_RESULT(lResult);
8981 }
8982
8983 if (l1 - 3 >= 0 && l1 -2 < (long)Exp32IndexSize
8984 && l2 - 2 < (long)(Exp32ValueSize + MaxBase32Size)) {
8985 base = Exp32Index[l1 - 3]
8986 + (unsigned short) (l2 - 2 - MaxBase32Size);
8987 if (base < Exp32Index[l1 - 2]) {
8988 /*
8989 * 32-bit number raised to intermediate power, done by
8990 * table lookup.
8991 */
8992
8993 LONG_RESULT(Exp32Value[base]);
8994 }
8995 }
8996 if (-l1 - 3 >= 0 && -l1 - 2 < (long)Exp32IndexSize
8997 && l2 - 2 < (long)(Exp32ValueSize + MaxBase32Size)) {
8998 base = Exp32Index[-l1 - 3]
8999 + (unsigned short) (l2 - 2 - MaxBase32Size);
9000 if (base < Exp32Index[-l1 - 2]) {
9001 /*
9002 * 32-bit number raised to intermediate power, done by
9003 * table lookup.
9004 */
9005
9006 lResult = (oddExponent) ?
9007 -Exp32Value[base] : Exp32Value[base];
9008 LONG_RESULT(lResult);
9009 }
9010 }
9011 #endif
9012 #if (LONG_MAX > 0x7FFFFFFF) || !defined(TCL_WIDE_INT_IS_LONG)
9013 /* Code below (up to overflowExpon) works with wide-int base */
9014 w1 = l1;
9015 #endif
9016 }
9017
9018 #if (LONG_MAX > 0x7FFFFFFF) || !defined(TCL_WIDE_INT_IS_LONG)
9019
9020 /* From here (up to overflowExpon) base is wide-int (w1). */
9021
9022 if (l2 - 2 < (long)MaxBase64Size
9023 && w1 <= MaxBase64[l2 - 2]
9024 && w1 >= -MaxBase64[l2 - 2]) {
9025 /*
9026 * Small powers of integers whose result is wide.
9027 */
9028 wResult = WidePwrSmallExpon(w1, l2);
9029
9030 WIDE_RESULT(wResult);
9031 }
9032
9033 /*
9034 * Handle cases of powers > 16 that still fit in a 64-bit word by
9035 * doing table lookup.
9036 */
9037
9038 if (w1 - 3 >= 0 && w1 - 2 < (long)Exp64IndexSize
9039 && l2 - 2 < (long)(Exp64ValueSize + MaxBase64Size)) {
9040 base = Exp64Index[w1 - 3]
9041 + (unsigned short) (l2 - 2 - MaxBase64Size);
9042 if (base < Exp64Index[w1 - 2]) {
9043 /*
9044 * 64-bit number raised to intermediate power, done by
9045 * table lookup.
9046 */
9047
9048 WIDE_RESULT(Exp64Value[base]);
9049 }
9050 }
9051
9052 if (-w1 - 3 >= 0 && -w1 - 2 < (long)Exp64IndexSize
9053 && l2 - 2 < (long)(Exp64ValueSize + MaxBase64Size)) {
9054 base = Exp64Index[-w1 - 3]
9055 + (unsigned short) (l2 - 2 - MaxBase64Size);
9056 if (base < Exp64Index[-w1 - 2]) {
9057 /*
9058 * 64-bit number raised to intermediate power, done by
9059 * table lookup.
9060 */
9061
9062 wResult = oddExponent ? -Exp64Value[base] : Exp64Value[base];
9063 WIDE_RESULT(wResult);
9064 }
9065 }
9066 #endif
9067
9068 overflowExpon:
9069
9070 if ((TclGetWideIntFromObj(NULL, value2Ptr, &w2) != TCL_OK)
9071 || (value2Ptr->typePtr != &tclIntType)
9072 || (Tcl_WideUInt)w2 >= (1<<28)) {
9073 Tcl_SetObjResult(interp, Tcl_NewStringObj(
9074 "exponent too large", -1));
9075 return GENERAL_ARITHMETIC_ERROR;
9076 }
9077 Tcl_TakeBignumFromObj(NULL, valuePtr, &big1);
9078 mp_init(&bigResult);
9079 TclBN_mp_expt_d(&big1, (unsigned int)w2, &bigResult);
9080 mp_clear(&big1);
9081 BIG_RESULT(&bigResult);
9082 }
9083
9084 case INST_ADD:
9085 case INST_SUB:
9086 case INST_MULT:
9087 case INST_DIV:
9088 if ((type1 == TCL_NUMBER_DOUBLE) || (type2 == TCL_NUMBER_DOUBLE)) {
9089 /*
9090 * At least one of the values is floating-point, so perform
9091 * floating point calculations.
9092 */
9093
9094 Tcl_GetDoubleFromObj(NULL, valuePtr, &d1);
9095 Tcl_GetDoubleFromObj(NULL, value2Ptr, &d2);
9096
9097 switch (opcode) {
9098 case INST_ADD:
9099 dResult = d1 + d2;
9100 break;
9101 case INST_SUB:
9102 dResult = d1 - d2;
9103 break;
9104 case INST_MULT:
9105 dResult = d1 * d2;
9106 break;
9107 case INST_DIV:
9108 #ifndef IEEE_FLOATING_POINT
9109 if (d2 == 0.0) {
9110 return DIVIDED_BY_ZERO;
9111 }
9112 #endif
9113 /*
9114 * We presume that we are running with zero-divide unmasked if
9115 * we're on an IEEE box. Otherwise, this statement might cause
9116 * demons to fly out our noses.
9117 */
9118
9119 dResult = d1 / d2;
9120 break;
9121 default:
9122 /* Unused, here to silence compiler warning. */
9123 dResult = 0;
9124 }
9125
9126 doubleResult:
9127 #ifndef ACCEPT_NAN
9128 /*
9129 * Check now for IEEE floating-point error.
9130 */
9131
9132 if (TclIsNaN(dResult)) {
9133 TclExprFloatError(interp, dResult);
9134 return GENERAL_ARITHMETIC_ERROR;
9135 }
9136 #endif
9137 DOUBLE_RESULT(dResult);
9138 }
9139 if ((type1 != TCL_NUMBER_BIG) && (type2 != TCL_NUMBER_BIG)) {
9140 TclGetWideIntFromObj(NULL, valuePtr, &w1);
9141 TclGetWideIntFromObj(NULL, value2Ptr, &w2);
9142
9143 switch (opcode) {
9144 case INST_ADD:
9145 wResult = (Tcl_WideInt)((Tcl_WideUInt)w1 + (Tcl_WideUInt)w2);
9146 #ifndef TCL_WIDE_INT_IS_LONG
9147 if ((type1 == TCL_NUMBER_WIDE) || (type2 == TCL_NUMBER_WIDE))
9148 #endif
9149 {
9150 /*
9151 * Check for overflow.
9152 */
9153
9154 if (Overflowing(w1, w2, wResult)) {
9155 goto overflowBasic;
9156 }
9157 }
9158 break;
9159
9160 case INST_SUB:
9161 wResult = (Tcl_WideInt)((Tcl_WideUInt)w1 - (Tcl_WideUInt)w2);
9162 #ifndef TCL_WIDE_INT_IS_LONG
9163 if ((type1 == TCL_NUMBER_WIDE) || (type2 == TCL_NUMBER_WIDE))
9164 #endif
9165 {
9166 /*
9167 * Must check for overflow. The macro tests for overflows
9168 * in sums by looking at the sign bits. As we have a
9169 * subtraction here, we are adding -w2. As -w2 could in
9170 * turn overflow, we test with ~w2 instead: it has the
9171 * opposite sign bit to w2 so it does the job. Note that
9172 * the only "bad" case (w2==0) is irrelevant for this
9173 * macro, as in that case w1 and wResult have the same
9174 * sign and there is no overflow anyway.
9175 */
9176
9177 if (Overflowing(w1, ~w2, wResult)) {
9178 goto overflowBasic;
9179 }
9180 }
9181 break;
9182
9183 case INST_MULT:
9184 if ((sizeof(Tcl_WideInt) < 2*sizeof(long))
9185 || (type1 != TCL_NUMBER_LONG)
9186 || (type2 != TCL_NUMBER_LONG)) {
9187 goto overflowBasic;
9188 }
9189 wResult = w1 * w2;
9190 break;
9191
9192 case INST_DIV:
9193 if (w2 == 0) {
9194 return DIVIDED_BY_ZERO;
9195 }
9196
9197 /*
9198 * Need a bignum to represent (LLONG_MIN / -1)
9199 */
9200
9201 if ((w1 == LLONG_MIN) && (w2 == -1)) {
9202 goto overflowBasic;
9203 }
9204 wResult = w1 / w2;
9205
9206 /*
9207 * Force Tcl's integer division rules.
9208 * TODO: examine for logic simplification
9209 */
9210
9211 if (((wResult < 0) || ((wResult == 0) &&
9212 ((w1 < 0 && w2 > 0) || (w1 > 0 && w2 < 0)))) &&
9213 (wResult*w2 != w1)) {
9214 wResult -= 1;
9215 }
9216 break;
9217
9218 default:
9219 /*
9220 * Unused, here to silence compiler warning.
9221 */
9222
9223 wResult = 0;
9224 }
9225
9226 WIDE_RESULT(wResult);
9227 }
9228
9229 overflowBasic:
9230 Tcl_TakeBignumFromObj(NULL, valuePtr, &big1);
9231 Tcl_TakeBignumFromObj(NULL, value2Ptr, &big2);
9232 mp_init(&bigResult);
9233 switch (opcode) {
9234 case INST_ADD:
9235 mp_add(&big1, &big2, &bigResult);
9236 break;
9237 case INST_SUB:
9238 mp_sub(&big1, &big2, &bigResult);
9239 break;
9240 case INST_MULT:
9241 mp_mul(&big1, &big2, &bigResult);
9242 break;
9243 case INST_DIV:
9244 if (mp_iszero(&big2)) {
9245 mp_clear(&big1);
9246 mp_clear(&big2);
9247 mp_clear(&bigResult);
9248 return DIVIDED_BY_ZERO;
9249 }
9250 mp_init(&bigRemainder);
9251 mp_div(&big1, &big2, &bigResult, &bigRemainder);
9252 if (!mp_iszero(&bigRemainder)
9253 && (mp_isneg(&bigRemainder) != mp_isneg(&big2))) {
9254 /*
9255 * Convert to Tcl's integer division rules.
9256 */
9257
9258 mp_sub_d(&bigResult, 1, &bigResult);
9259 mp_add(&bigRemainder, &big2, &bigRemainder);
9260 }
9261 mp_clear(&bigRemainder);
9262 break;
9263 }
9264 mp_clear(&big1);
9265 mp_clear(&big2);
9266 BIG_RESULT(&bigResult);
9267 }
9268
9269 Tcl_Panic("unexpected opcode");
9270 return NULL;
9271 }
9272
9273 static Tcl_Obj *
9274 ExecuteExtendedUnaryMathOp(
9275 int opcode, /* What operation to perform. */
9276 Tcl_Obj *valuePtr) /* The operand on the stack. */
9277 {
9278 ClientData ptr = NULL;
9279 int type;
9280 Tcl_WideInt w;
9281 mp_int big;
9282 Tcl_Obj *objResultPtr;
9283
9284 (void) GetNumberFromObj(NULL, valuePtr, &ptr, &type);
9285
9286 switch (opcode) {
9287 case INST_BITNOT:
9288 #ifndef TCL_WIDE_INT_IS_LONG
9289 if (type == TCL_NUMBER_WIDE) {
9290 w = *((const Tcl_WideInt *) ptr);
9291 WIDE_RESULT(~w);
9292 }
9293 #endif
9294 Tcl_TakeBignumFromObj(NULL, valuePtr, &big);
9295 /* ~a = - a - 1 */
9296 (void)mp_neg(&big, &big);
9297 mp_sub_d(&big, 1, &big);
9298 BIG_RESULT(&big);
9299 case INST_UMINUS:
9300 switch (type) {
9301 case TCL_NUMBER_DOUBLE:
9302 DOUBLE_RESULT(-(*((const double *) ptr)));
9303 case TCL_NUMBER_LONG:
9304 w = (Tcl_WideInt)(*((const long *) ptr));
9305 if (w != LLONG_MIN) {
9306 WIDE_RESULT(-w);
9307 }
9308 TclBNInitBignumFromLong(&big, *(const long *) ptr);
9309 break;
9310 #ifndef TCL_WIDE_INT_IS_LONG
9311 case TCL_NUMBER_WIDE:
9312 w = *((const Tcl_WideInt *) ptr);
9313 if (w != LLONG_MIN) {
9314 WIDE_RESULT(-w);
9315 }
9316 TclBNInitBignumFromWideInt(&big, w);
9317 break;
9318 #endif
9319 default:
9320 Tcl_TakeBignumFromObj(NULL, valuePtr, &big);
9321 }
9322 (void)mp_neg(&big, &big);
9323 BIG_RESULT(&big);
9324 }
9325
9326 Tcl_Panic("unexpected opcode");
9327 return NULL;
9328 }
9329 #undef LONG_RESULT
9330 #undef WIDE_RESULT
9331 #undef BIG_RESULT
9332 #undef DOUBLE_RESULT
9333
9334 /*
9335 *----------------------------------------------------------------------
9336 *
9337 * CompareTwoNumbers --
9338 *
9339 * This function compares a pair of numbers in Tcl_Objs. Each argument
9340 * must already be known to be numeric and not NaN. Also, valuePtr
9341 * and value2Ptr are destructive: they might lose their internal
9342 * representation.
9343 *
9344 * Results:
9345 * One of MP_LT, MP_EQ or MP_GT, depending on whether valuePtr is less
9346 * than, equal to, or greater than value2Ptr (respectively).
9347 *
9348 * Side effects:
9349 * None, provided both values are numeric.
9350 *
9351 *----------------------------------------------------------------------
9352 */
9353
9354 int
9355 CompareTwoNumbers(
9356 Tcl_Obj *valuePtr,
9357 Tcl_Obj *value2Ptr)
9358 {
9359 int type1 = TCL_NUMBER_NAN, type2 = TCL_NUMBER_NAN, compare;
9360 ClientData ptr1, ptr2;
9361 mp_int big1, big2;
9362 double d1, d2, tmp;
9363 long l1, l2;
9364 #ifndef TCL_WIDE_INT_IS_LONG
9365 Tcl_WideInt w1, w2;
9366 #endif
9367
9368 (void) GetNumberFromObj(NULL, valuePtr, &ptr1, &type1);
9369 (void) GetNumberFromObj(NULL, value2Ptr, &ptr2, &type2);
9370
9371 switch (type1) {
9372 case TCL_NUMBER_LONG:
9373 l1 = *((const long *)ptr1);
9374 switch (type2) {
9375 case TCL_NUMBER_LONG:
9376 l2 = *((const long *)ptr2);
9377 longCompare:
9378 return (l1 < l2) ? MP_LT : ((l1 > l2) ? MP_GT : MP_EQ);
9379 #ifndef TCL_WIDE_INT_IS_LONG
9380 case TCL_NUMBER_WIDE:
9381 w2 = *((const Tcl_WideInt *)ptr2);
9382 w1 = (Tcl_WideInt)l1;
9383 goto wideCompare;
9384 #endif
9385 case TCL_NUMBER_DOUBLE:
9386 d2 = *((const double *)ptr2);
9387 d1 = (double) l1;
9388
9389 /*
9390 * If the double has a fractional part, or if the long can be
9391 * converted to double without loss of precision, then compare as
9392 * doubles.
9393 */
9394
9395 if (DBL_MANT_DIG > CHAR_BIT*sizeof(long) || l1 == (long) d1
9396 || modf(d2, &tmp) != 0.0) {
9397 goto doubleCompare;
9398 }
9399
9400 /*
9401 * Otherwise, to make comparision based on full precision, need to
9402 * convert the double to a suitably sized integer.
9403 *
9404 * Need this to get comparsions like
9405 * expr 20000000000000003 < 20000000000000004.0
9406 * right. Converting the first argument to double will yield two
9407 * double values that are equivalent within double precision.
9408 * Converting the double to an integer gets done exactly, then
9409 * integer comparison can tell the difference.
9410 */
9411
9412 if (d2 < (double)LONG_MIN) {
9413 return MP_GT;
9414 }
9415 if (d2 > (double)LONG_MAX) {
9416 return MP_LT;
9417 }
9418 l2 = (long) d2;
9419 goto longCompare;
9420 case TCL_NUMBER_BIG:
9421 Tcl_TakeBignumFromObj(NULL, value2Ptr, &big2);
9422 if (mp_isneg(&big2)) {
9423 compare = MP_GT;
9424 } else {
9425 compare = MP_LT;
9426 }
9427 mp_clear(&big2);
9428 return compare;
9429 }
9430 break;
9431
9432 #ifndef TCL_WIDE_INT_IS_LONG
9433 case TCL_NUMBER_WIDE:
9434 w1 = *((const Tcl_WideInt *)ptr1);
9435 switch (type2) {
9436 case TCL_NUMBER_WIDE:
9437 w2 = *((const Tcl_WideInt *)ptr2);
9438 wideCompare:
9439 return (w1 < w2) ? MP_LT : ((w1 > w2) ? MP_GT : MP_EQ);
9440 case TCL_NUMBER_LONG:
9441 l2 = *((const long *)ptr2);
9442 w2 = (Tcl_WideInt)l2;
9443 goto wideCompare;
9444 case TCL_NUMBER_DOUBLE:
9445 d2 = *((const double *)ptr2);
9446 d1 = (double) w1;
9447 if (DBL_MANT_DIG > CHAR_BIT*sizeof(Tcl_WideInt)
9448 || w1 == (Tcl_WideInt)d1 || modf(d2, &tmp) != 0.0) {
9449 goto doubleCompare;
9450 }
9451 if (d2 < (double)LLONG_MIN) {
9452 return MP_GT;
9453 }
9454 if (d2 > (double)LLONG_MAX) {
9455 return MP_LT;
9456 }
9457 w2 = (Tcl_WideInt)d2;
9458 goto wideCompare;
9459 case TCL_NUMBER_BIG:
9460 Tcl_TakeBignumFromObj(NULL, value2Ptr, &big2);
9461 if (mp_isneg(&big2)) {
9462 compare = MP_GT;
9463 } else {
9464 compare = MP_LT;
9465 }
9466 mp_clear(&big2);
9467 return compare;
9468 }
9469 break;
9470 #endif
9471
9472 case TCL_NUMBER_DOUBLE:
9473 d1 = *((const double *)ptr1);
9474 switch (type2) {
9475 case TCL_NUMBER_DOUBLE:
9476 d2 = *((const double *)ptr2);
9477 doubleCompare:
9478 return (d1 < d2) ? MP_LT : ((d1 > d2) ? MP_GT : MP_EQ);
9479 case TCL_NUMBER_LONG:
9480 l2 = *((const long *)ptr2);
9481 d2 = (double) l2;
9482 if (DBL_MANT_DIG > CHAR_BIT*sizeof(long) || l2 == (long) d2
9483 || modf(d1, &tmp) != 0.0) {
9484 goto doubleCompare;
9485 }
9486 if (d1 < (double)LONG_MIN) {
9487 return MP_LT;
9488 }
9489 if (d1 > (double)LONG_MAX) {
9490 return MP_GT;
9491 }
9492 l1 = (long) d1;
9493 goto longCompare;
9494 #ifndef TCL_WIDE_INT_IS_LONG
9495 case TCL_NUMBER_WIDE:
9496 w2 = *((const Tcl_WideInt *)ptr2);
9497 d2 = (double) w2;
9498 if (DBL_MANT_DIG > CHAR_BIT*sizeof(Tcl_WideInt)
9499 || w2 == (Tcl_WideInt)d2 || modf(d1, &tmp) != 0.0) {
9500 goto doubleCompare;
9501 }
9502 if (d1 < (double)LLONG_MIN) {
9503 return MP_LT;
9504 }
9505 if (d1 > (double)LLONG_MAX) {
9506 return MP_GT;
9507 }
9508 w1 = (Tcl_WideInt)d1;
9509 goto wideCompare;
9510 #endif
9511 case TCL_NUMBER_BIG:
9512 if (TclIsInfinite(d1)) {
9513 return (d1 > 0.0) ? MP_GT : MP_LT;
9514 }
9515 Tcl_TakeBignumFromObj(NULL, value2Ptr, &big2);
9516 if ((d1 < (double)LONG_MAX) && (d1 > (double)LONG_MIN)) {
9517 if (mp_isneg(&big2)) {
9518 compare = MP_GT;
9519 } else {
9520 compare = MP_LT;
9521 }
9522 mp_clear(&big2);
9523 return compare;
9524 }
9525 if (DBL_MANT_DIG > CHAR_BIT*sizeof(long)
9526 && modf(d1, &tmp) != 0.0) {
9527 d2 = TclBignumToDouble(&big2);
9528 mp_clear(&big2);
9529 goto doubleCompare;
9530 }
9531 Tcl_InitBignumFromDouble(NULL, d1, &big1);
9532 goto bigCompare;
9533 }
9534 break;
9535
9536 case TCL_NUMBER_BIG:
9537 Tcl_TakeBignumFromObj(NULL, valuePtr, &big1);
9538 switch (type2) {
9539 #ifndef TCL_WIDE_INT_IS_LONG
9540 case TCL_NUMBER_WIDE:
9541 #endif
9542 case TCL_NUMBER_LONG:
9543 compare = mp_cmp_d(&big1, 0);
9544 mp_clear(&big1);
9545 return compare;
9546 case TCL_NUMBER_DOUBLE:
9547 d2 = *((const double *)ptr2);
9548 if (TclIsInfinite(d2)) {
9549 compare = (d2 > 0.0) ? MP_LT : MP_GT;
9550 mp_clear(&big1);
9551 return compare;
9552 }
9553 if ((d2 < (double)LONG_MAX) && (d2 > (double)LONG_MIN)) {
9554 compare = mp_cmp_d(&big1, 0);
9555 mp_clear(&big1);
9556 return compare;
9557 }
9558 if (DBL_MANT_DIG > CHAR_BIT*sizeof(long)
9559 && modf(d2, &tmp) != 0.0) {
9560 d1 = TclBignumToDouble(&big1);
9561 mp_clear(&big1);
9562 goto doubleCompare;
9563 }
9564 Tcl_InitBignumFromDouble(NULL, d2, &big2);
9565 goto bigCompare;
9566 case TCL_NUMBER_BIG:
9567 Tcl_TakeBignumFromObj(NULL, value2Ptr, &big2);
9568 bigCompare:
9569 compare = mp_cmp(&big1, &big2);
9570 mp_clear(&big1);
9571 mp_clear(&big2);
9572 return compare;
9573 }
9574 break;
9575 default:
9576 Tcl_Panic("unexpected number type");
9577 }
9578 return TCL_ERROR;
9579 }
9580
9581 #ifdef TCL_COMPILE_DEBUG
9582 /*
9583 *----------------------------------------------------------------------
9584 *
9585 * PrintByteCodeInfo --
9586 *
9587 * This procedure prints a summary about a bytecode object to stdout. It
9588 * is called by TclNRExecuteByteCode when starting to execute the bytecode
9589 * object if tclTraceExec has the value 2 or more.
9590 *
9591 * Results:
9592 * None.
9593 *
9594 * Side effects:
9595 * None.
9596 *
9597 *----------------------------------------------------------------------
9598 */
9599
9600 static void
9601 PrintByteCodeInfo(
9602 ByteCode *codePtr) /* The bytecode whose summary is printed to
9603 * stdout. */
9604 {
9605 Proc *procPtr = codePtr->procPtr;
9606 Interp *iPtr = (Interp *) *codePtr->interpHandle;
9607
9608 fprintf(stdout, "\nExecuting ByteCode 0x%p, refCt %u, epoch %u, interp 0x%p (epoch %u)\n",
9609 codePtr, codePtr->refCount, codePtr->compileEpoch, iPtr,
9610 iPtr->compileEpoch);
9611
9612 fprintf(stdout, " Source: ");
9613 TclPrintSource(stdout, codePtr->source, 60);
9614
9615 fprintf(stdout, "\n Cmds %d, src %d, inst %u, litObjs %u, aux %d, stkDepth %u, code/src %.2f\n",
9616 codePtr->numCommands, codePtr->numSrcBytes,
9617 codePtr->numCodeBytes, codePtr->numLitObjects,
9618 codePtr->numAuxDataItems, codePtr->maxStackDepth,
9619 #ifdef TCL_COMPILE_STATS
9620 codePtr->numSrcBytes?
9621 ((float)codePtr->structureSize)/codePtr->numSrcBytes :
9622 #endif
9623 0.0);
9624
9625 #ifdef TCL_COMPILE_STATS
9626 fprintf(stdout, " Code %lu = header %lu+inst %d+litObj %lu+exc %lu+aux %lu+cmdMap %d\n",
9627 (unsigned long) codePtr->structureSize,
9628 (unsigned long) (TclOffset(ByteCode, localCachePtr)),
9629 codePtr->numCodeBytes,
9630 (unsigned long) (codePtr->numLitObjects * sizeof(Tcl_Obj *)),
9631 (unsigned long) (codePtr->numExceptRanges*sizeof(ExceptionRange)),
9632 (unsigned long) (codePtr->numAuxDataItems * sizeof(AuxData)),
9633 codePtr->numCmdLocBytes);
9634 #endif /* TCL_COMPILE_STATS */
9635 if (procPtr != NULL) {
9636 fprintf(stdout,
9637 " Proc 0x%p, refCt %d, args %d, compiled locals %d\n",
9638 procPtr, procPtr->refCount, procPtr->numArgs,
9639 procPtr->numCompiledLocals);
9640 }
9641 }
9642 #endif /* TCL_COMPILE_DEBUG */
9643
9644 /*
9645 *----------------------------------------------------------------------
9646 *
9647 * ValidatePcAndStackTop --
9648 *
9649 * This procedure is called by TclNRExecuteByteCode when debugging to
9650 * verify that the program counter and stack top are valid during
9651 * execution.
9652 *
9653 * Results:
9654 * None.
9655 *
9656 * Side effects:
9657 * Prints a message to stderr and panics if either the pc or stack top
9658 * are invalid.
9659 *
9660 *----------------------------------------------------------------------
9661 */
9662
9663 #ifdef TCL_COMPILE_DEBUG
9664 static void
9665 ValidatePcAndStackTop(
9666 ByteCode *codePtr, /* The bytecode whose summary is printed to
9667 * stdout. */
9668 const unsigned char *pc, /* Points to first byte of a bytecode
9669 * instruction. The program counter. */
9670 int stackTop, /* Current stack top. Must be between
9671 * stackLowerBound and stackUpperBound
9672 * (inclusive). */
9673 int checkStack) /* 0 if the stack depth check should be
9674 * skipped. */
9675 {
9676 int stackUpperBound = codePtr->maxStackDepth;
9677 /* Greatest legal value for stackTop. */
9678 size_t relativePc = (size_t) (pc - codePtr->codeStart);
9679 size_t codeStart = (size_t) codePtr->codeStart;
9680 size_t codeEnd = (size_t)
9681 (codePtr->codeStart + codePtr->numCodeBytes);
9682 unsigned char opCode = *pc;
9683
9684 if (((size_t) pc < codeStart) || ((size_t) pc > codeEnd)) {
9685 fprintf(stderr, "\nBad instruction pc 0x%p in TclNRExecuteByteCode\n",
9686 pc);
9687 Tcl_Panic("TclNRExecuteByteCode execution failure: bad pc");
9688 }
9689 if ((unsigned) opCode > LAST_INST_OPCODE) {
9690 fprintf(stderr, "\nBad opcode %d at pc %lu in TclNRExecuteByteCode\n",
9691 (unsigned) opCode, (unsigned long)relativePc);
9692 Tcl_Panic("TclNRExecuteByteCode execution failure: bad opcode");
9693 }
9694 if (checkStack &&
9695 ((stackTop < 0) || (stackTop > stackUpperBound))) {
9696 int numChars;
9697 const char *cmd = GetSrcInfoForPc(pc, codePtr, &numChars, NULL, NULL);
9698
9699 fprintf(stderr, "\nBad stack top %d at pc %lu in TclNRExecuteByteCode (min 0, max %i)",
9700 stackTop, (unsigned long)relativePc, stackUpperBound);
9701 if (cmd != NULL) {
9702 Tcl_Obj *message;
9703
9704 TclNewLiteralStringObj(message, "\n executing ");
9705 Tcl_IncrRefCount(message);
9706 Tcl_AppendLimitedToObj(message, cmd, numChars, 100, NULL);
9707 fprintf(stderr,"%s\n", TclGetString(message));
9708 Tcl_DecrRefCount(message);
9709 } else {
9710 fprintf(stderr, "\n");
9711 }
9712 Tcl_Panic("TclNRExecuteByteCode execution failure: bad stack top");
9713 }
9714 }
9715 #endif /* TCL_COMPILE_DEBUG */
9716
9717 /*
9718 *----------------------------------------------------------------------
9719 *
9720 * IllegalExprOperandType --
9721 *
9722 * Used by TclNRExecuteByteCode to append an error message to the interp
9723 * result when an illegal operand type is detected by an expression
9724 * instruction. The argument opndPtr holds the operand object in error.
9725 *
9726 * Results:
9727 * None.
9728 *
9729 * Side effects:
9730 * An error message is appended to the interp result.
9731 *
9732 *----------------------------------------------------------------------
9733 */
9734
9735 static void
9736 IllegalExprOperandType(
9737 Tcl_Interp *interp, /* Interpreter to which error information
9738 * pertains. */
9739 const unsigned char *pc, /* Points to the instruction being executed
9740 * when the illegal type was found. */
9741 Tcl_Obj *opndPtr) /* Points to the operand holding the value
9742 * with the illegal type. */
9743 {
9744 ClientData ptr;
9745 int type;
9746 const unsigned char opcode = *pc;
9747 const char *description, *op = "unknown";
9748
9749 if (opcode == INST_EXPON) {
9750 op = "**";
9751 } else if (opcode <= INST_LNOT) {
9752 op = operatorStrings[opcode - INST_LOR];
9753 }
9754
9755 if (GetNumberFromObj(NULL, opndPtr, &ptr, &type) != TCL_OK) {
9756 int numBytes;
9757 const char *bytes = TclGetStringFromObj(opndPtr, &numBytes);
9758
9759 if (numBytes == 0) {
9760 description = "empty string";
9761 } else if (TclCheckBadOctal(NULL, bytes)) {
9762 description = "invalid octal number";
9763 } else {
9764 description = "non-numeric string";
9765 }
9766 } else if (type == TCL_NUMBER_NAN) {
9767 description = "non-numeric floating-point value";
9768 } else if (type == TCL_NUMBER_DOUBLE) {
9769 description = "floating-point value";
9770 } else {
9771 /* TODO: No caller needs this. Eliminate? */
9772 description = "(big) integer";
9773 }
9774
9775 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
9776 "can't use %s as operand of \"%s\"", description, op));
9777 Tcl_SetErrorCode(interp, "ARITH", "DOMAIN", description, (char *)NULL);
9778 }
9779
9780 /*
9781 *----------------------------------------------------------------------
9782 *
9783 * TclGetSrcInfoForPc, GetSrcInfoForPc, TclGetSourceFromFrame --
9784 *
9785 * Given a program counter value, finds the closest command in the
9786 * bytecode code unit's CmdLocation array and returns information about
9787 * that command's source: a pointer to its first byte and the number of
9788 * characters.
9789 *
9790 * Results:
9791 * If a command is found that encloses the program counter value, a
9792 * pointer to the command's source is returned and the length of the
9793 * source is stored at *lengthPtr. If multiple commands resulted in code
9794 * at pc, information about the closest enclosing command is returned. If
9795 * no matching command is found, NULL is returned and *lengthPtr is
9796 * unchanged.
9797 *
9798 * Side effects:
9799 * The CmdFrame at *cfPtr is updated.
9800 *
9801 *----------------------------------------------------------------------
9802 */
9803
9804 Tcl_Obj *
9805 TclGetSourceFromFrame(
9806 CmdFrame *cfPtr,
9807 int objc,
9808 Tcl_Obj *const objv[])
9809 {
9810 if (cfPtr == NULL) {
9811 return Tcl_NewListObj(objc, objv);
9812 }
9813 if (cfPtr->cmdObj == NULL) {
9814 if (cfPtr->cmd == NULL) {
9815 ByteCode *codePtr = (ByteCode *) cfPtr->data.tebc.codePtr;
9816
9817 cfPtr->cmd = GetSrcInfoForPc((unsigned char *)
9818 cfPtr->data.tebc.pc, codePtr, &cfPtr->len, NULL, NULL);
9819 }
9820 if (cfPtr->cmd) {
9821 cfPtr->cmdObj = Tcl_NewStringObj(cfPtr->cmd, cfPtr->len);
9822 } else {
9823 cfPtr->cmdObj = Tcl_NewListObj(objc, objv);
9824 }
9825 Tcl_IncrRefCount(cfPtr->cmdObj);
9826 }
9827 return cfPtr->cmdObj;
9828 }
9829
9830 void
9831 TclGetSrcInfoForPc(
9832 CmdFrame *cfPtr)
9833 {
9834 ByteCode *codePtr = (ByteCode *) cfPtr->data.tebc.codePtr;
9835
9836 assert(cfPtr->type == TCL_LOCATION_BC);
9837
9838 if (cfPtr->cmd == NULL) {
9839
9840 cfPtr->cmd = GetSrcInfoForPc(
9841 (unsigned char *) cfPtr->data.tebc.pc, codePtr,
9842 &cfPtr->len, NULL, NULL);
9843 }
9844
9845 if (cfPtr->cmd != NULL) {
9846 /*
9847 * We now have the command. We can get the srcOffset back and from
9848 * there find the list of word locations for this command.
9849 */
9850
9851 ExtCmdLoc *eclPtr;
9852 ECL *locPtr = NULL;
9853 int srcOffset, i;
9854 Interp *iPtr = (Interp *) *codePtr->interpHandle;
9855 Tcl_HashEntry *hePtr =
9856 Tcl_FindHashEntry(iPtr->lineBCPtr, codePtr);
9857
9858 if (!hePtr) {
9859 return;
9860 }
9861
9862 srcOffset = cfPtr->cmd - codePtr->source;
9863 eclPtr = Tcl_GetHashValue(hePtr);
9864
9865 for (i=0; i < eclPtr->nuloc; i++) {
9866 if (eclPtr->loc[i].srcOffset == srcOffset) {
9867 locPtr = eclPtr->loc+i;
9868 break;
9869 }
9870 }
9871 if (locPtr == NULL) {
9872 Tcl_Panic("LocSearch failure");
9873 }
9874
9875 cfPtr->line = locPtr->line;
9876 cfPtr->nline = locPtr->nline;
9877 cfPtr->type = eclPtr->type;
9878
9879 if (eclPtr->type == TCL_LOCATION_SOURCE) {
9880 cfPtr->data.eval.path = eclPtr->path;
9881 Tcl_IncrRefCount(cfPtr->data.eval.path);
9882 }
9883
9884 /*
9885 * Do not set cfPtr->data.eval.path NULL for non-SOURCE. Needed for
9886 * cfPtr->data.tebc.codePtr.
9887 */
9888 }
9889 }
9890
9891 static const char *
9892 GetSrcInfoForPc(
9893 const unsigned char *pc, /* The program counter value for which to
9894 * return the closest command's source info.
9895 * This points within a bytecode instruction
9896 * in codePtr's code. */
9897 ByteCode *codePtr, /* The bytecode sequence in which to look up
9898 * the command source for the pc. */
9899 int *lengthPtr, /* If non-NULL, the location where the length
9900 * of the command's source should be stored.
9901 * If NULL, no length is stored. */
9902 const unsigned char **pcBeg,/* If non-NULL, the bytecode location
9903 * where the current instruction starts.
9904 * If NULL; no pointer is stored. */
9905 int *cmdIdxPtr) /* If non-NULL, the location where the index
9906 * of the command containing the pc should
9907 * be stored. */
9908 {
9909 int pcOffset = (pc - codePtr->codeStart);
9910 int numCmds = codePtr->numCommands;
9911 unsigned char *codeDeltaNext, *codeLengthNext;
9912 unsigned char *srcDeltaNext, *srcLengthNext;
9913 int codeOffset, codeLen, codeEnd, srcOffset, srcLen, delta, i;
9914 int bestDist = INT_MAX; /* Distance of pc to best cmd's start pc. */
9915 int bestSrcOffset = -1; /* Initialized to avoid compiler warning. */
9916 int bestSrcLength = -1; /* Initialized to avoid compiler warning. */
9917 int bestCmdIdx = -1;
9918
9919 /* The pc must point within the bytecode */
9920 assert ((pcOffset >= 0) && (pcOffset < codePtr->numCodeBytes));
9921
9922 /*
9923 * Decode the code and source offset and length for each command. The
9924 * closest enclosing command is the last one whose code started before
9925 * pcOffset.
9926 */
9927
9928 codeDeltaNext = codePtr->codeDeltaStart;
9929 codeLengthNext = codePtr->codeLengthStart;
9930 srcDeltaNext = codePtr->srcDeltaStart;
9931 srcLengthNext = codePtr->srcLengthStart;
9932 codeOffset = srcOffset = 0;
9933 for (i = 0; i < numCmds; i++) {
9934 if ((unsigned) *codeDeltaNext == (unsigned) 0xFF) {
9935 codeDeltaNext++;
9936 delta = TclGetInt4AtPtr(codeDeltaNext);
9937 codeDeltaNext += 4;
9938 } else {
9939 delta = TclGetInt1AtPtr(codeDeltaNext);
9940 codeDeltaNext++;
9941 }
9942 codeOffset += delta;
9943
9944 if ((unsigned) *codeLengthNext == (unsigned) 0xFF) {
9945 codeLengthNext++;
9946 codeLen = TclGetInt4AtPtr(codeLengthNext);
9947 codeLengthNext += 4;
9948 } else {
9949 codeLen = TclGetInt1AtPtr(codeLengthNext);
9950 codeLengthNext++;
9951 }
9952 codeEnd = (codeOffset + codeLen - 1);
9953
9954 if ((unsigned) *srcDeltaNext == (unsigned) 0xFF) {
9955 srcDeltaNext++;
9956 delta = TclGetInt4AtPtr(srcDeltaNext);
9957 srcDeltaNext += 4;
9958 } else {
9959 delta = TclGetInt1AtPtr(srcDeltaNext);
9960 srcDeltaNext++;
9961 }
9962 srcOffset += delta;
9963
9964 if ((unsigned) *srcLengthNext == (unsigned) 0xFF) {
9965 srcLengthNext++;
9966 srcLen = TclGetInt4AtPtr(srcLengthNext);
9967 srcLengthNext += 4;
9968 } else {
9969 srcLen = TclGetInt1AtPtr(srcLengthNext);
9970 srcLengthNext++;
9971 }
9972
9973 if (codeOffset > pcOffset) { /* Best cmd already found */
9974 break;
9975 }
9976 if (pcOffset <= codeEnd) { /* This cmd's code encloses pc */
9977 int dist = (pcOffset - codeOffset);
9978
9979 if (dist <= bestDist) {
9980 bestDist = dist;
9981 bestSrcOffset = srcOffset;
9982 bestSrcLength = srcLen;
9983 bestCmdIdx = i;
9984 }
9985 }
9986 }
9987
9988 if (pcBeg != NULL) {
9989 const unsigned char *curr, *prev;
9990
9991 /*
9992 * Walk from beginning of command or BC to pc, by complete
9993 * instructions. Stop when crossing pc; keep previous.
9994 */
9995
9996 curr = ((bestDist == INT_MAX) ? codePtr->codeStart : pc - bestDist);
9997 prev = curr;
9998 while (curr <= pc) {
9999 prev = curr;
10000 curr += tclInstructionTable[*curr].numBytes;
10001 }
10002 *pcBeg = prev;
10003 }
10004
10005 if (bestDist == INT_MAX) {
10006 return NULL;
10007 }
10008
10009 if (lengthPtr != NULL) {
10010 *lengthPtr = bestSrcLength;
10011 }
10012
10013 if (cmdIdxPtr != NULL) {
10014 *cmdIdxPtr = bestCmdIdx;
10015 }
10016
10017 return (codePtr->source + bestSrcOffset);
10018 }
10019
10020 /*
10021 *----------------------------------------------------------------------
10022 *
10023 * GetExceptRangeForPc --
10024 *
10025 * Given a program counter value, return the closest enclosing
10026 * ExceptionRange.
10027 *
10028 * Results:
10029 * If the searchMode is TCL_ERROR, this procedure ignores loop exception
10030 * ranges and returns a pointer to the closest catch range. If the
10031 * searchMode is TCL_BREAK, this procedure returns a pointer to the most
10032 * closely enclosing ExceptionRange regardless of whether it is a loop or
10033 * catch exception range. If the searchMode is TCL_CONTINUE, this
10034 * procedure returns a pointer to the most closely enclosing
10035 * ExceptionRange (of any type) skipping only loop exception ranges if
10036 * they don't have a sensible continueOffset defined. If no matching
10037 * ExceptionRange is found that encloses pc, a NULL is returned.
10038 *
10039 * Side effects:
10040 * None.
10041 *
10042 *----------------------------------------------------------------------
10043 */
10044
10045 static ExceptionRange *
10046 GetExceptRangeForPc(
10047 const unsigned char *pc, /* The program counter value for which to
10048 * search for a closest enclosing exception
10049 * range. This points to a bytecode
10050 * instruction in codePtr's code. */
10051 int searchMode, /* If TCL_BREAK, consider either loop or catch
10052 * ExceptionRanges in search. If TCL_ERROR
10053 * consider only catch ranges (and ignore any
10054 * closer loop ranges). If TCL_CONTINUE, look
10055 * for loop ranges that define a continue
10056 * point or a catch range. */
10057 ByteCode *codePtr) /* Points to the ByteCode in which to search
10058 * for the enclosing ExceptionRange. */
10059 {
10060 ExceptionRange *rangeArrayPtr;
10061 int numRanges = codePtr->numExceptRanges;
10062 ExceptionRange *rangePtr;
10063 int pcOffset = pc - codePtr->codeStart;
10064 int start;
10065
10066 if (numRanges == 0) {
10067 return NULL;
10068 }
10069
10070 /*
10071 * This exploits peculiarities of our compiler: nested ranges are always
10072 * *after* their containing ranges, so that by scanning backwards we are
10073 * sure that the first matching range is indeed the deepest.
10074 */
10075
10076 rangeArrayPtr = codePtr->exceptArrayPtr;
10077 rangePtr = rangeArrayPtr + numRanges;
10078 while (--rangePtr >= rangeArrayPtr) {
10079 start = rangePtr->codeOffset;
10080 if ((start <= pcOffset) &&
10081 (pcOffset < (start + rangePtr->numCodeBytes))) {
10082 if (rangePtr->type == CATCH_EXCEPTION_RANGE) {
10083 return rangePtr;
10084 }
10085 if (searchMode == TCL_BREAK) {
10086 return rangePtr;
10087 }
10088 if (searchMode == TCL_CONTINUE && rangePtr->continueOffset != -1){
10089 return rangePtr;
10090 }
10091 }
10092 }
10093 return NULL;
10094 }
10095
10096 /*
10097 *----------------------------------------------------------------------
10098 *
10099 * GetOpcodeName --
10100 *
10101 * This procedure is called by the TRACE and TRACE_WITH_OBJ macros used
10102 * in TclNRExecuteByteCode when debugging. It returns the name of the
10103 * bytecode instruction at a specified instruction pc.
10104 *
10105 * Results:
10106 * A character string for the instruction.
10107 *
10108 * Side effects:
10109 * None.
10110 *
10111 *----------------------------------------------------------------------
10112 */
10113
10114 #ifdef TCL_COMPILE_DEBUG
10115 static const char *
10116 GetOpcodeName(
10117 const unsigned char *pc) /* Points to the instruction whose name should
10118 * be returned. */
10119 {
10120 unsigned char opCode = *pc;
10121
10122 return tclInstructionTable[opCode].name;
10123 }
10124 #endif /* TCL_COMPILE_DEBUG */
10125
10126 /*
10127 *----------------------------------------------------------------------
10128 *
10129 * TclExprFloatError --
10130 *
10131 * This procedure is called when an error occurs during a floating-point
10132 * operation. It reads errno and sets interp->objResultPtr accordingly.
10133 *
10134 * Results:
10135 * interp->objResultPtr is set to hold an error message.
10136 *
10137 * Side effects:
10138 * None.
10139 *
10140 *----------------------------------------------------------------------
10141 */
10142
10143 void
10144 TclExprFloatError(
10145 Tcl_Interp *interp, /* Where to store error message. */
10146 double value) /* Value returned after error; used to
10147 * distinguish underflows from overflows. */
10148 {
10149 const char *s;
10150
10151 if ((errno == EDOM) || TclIsNaN(value)) {
10152 s = "domain error: argument not in valid range";
10153 Tcl_SetObjResult(interp, Tcl_NewStringObj(s, -1));
10154 Tcl_SetErrorCode(interp, "ARITH", "DOMAIN", s, (char *)NULL);
10155 } else if ((errno == ERANGE) || TclIsInfinite(value)) {
10156 if (value == 0.0) {
10157 s = "floating-point value too small to represent";
10158 Tcl_SetObjResult(interp, Tcl_NewStringObj(s, -1));
10159 Tcl_SetErrorCode(interp, "ARITH", "UNDERFLOW", s, (char *)NULL);
10160 } else {
10161 s = "floating-point value too large to represent";
10162 Tcl_SetObjResult(interp, Tcl_NewStringObj(s, -1));
10163 Tcl_SetErrorCode(interp, "ARITH", "OVERFLOW", s, (char *)NULL);
10164 }
10165 } else {
10166 Tcl_Obj *objPtr = Tcl_ObjPrintf(
10167 "unknown floating-point error, errno = %d", errno);
10168
10169 Tcl_SetErrorCode(interp, "ARITH", "UNKNOWN",
10170 TclGetString(objPtr), (char *)NULL);
10171 Tcl_SetObjResult(interp, objPtr);
10172 }
10173 }
10174
10175 #ifdef TCL_COMPILE_STATS
10176 /*
10177 *----------------------------------------------------------------------
10178 *
10179 * TclLog2 --
10180 *
10181 * Procedure used while collecting compilation statistics to determine
10182 * the log base 2 of an integer.
10183 *
10184 * Results:
10185 * Returns the log base 2 of the operand. If the argument is less than or
10186 * equal to zero, a zero is returned.
10187 *
10188 * Side effects:
10189 * None.
10190 *
10191 *----------------------------------------------------------------------
10192 */
10193
10194 int
10195 TclLog2(
10196 int value) /* The integer for which to compute the log
10197 * base 2. */
10198 {
10199 int n = value;
10200 int result = 0;
10201
10202 while (n > 1) {
10203 n = n >> 1;
10204 result++;
10205 }
10206 return result;
10207 }
10208
10209 /*
10210 *----------------------------------------------------------------------
10211 *
10212 * EvalStatsCmd --
10213 *
10214 * Implements the "evalstats" command that prints instruction execution
10215 * counts to stdout.
10216 *
10217 * Results:
10218 * Standard Tcl results.
10219 *
10220 * Side effects:
10221 * None.
10222 *
10223 *----------------------------------------------------------------------
10224 */
10225
10226 static int
10227 EvalStatsCmd(
10228 ClientData unused, /* Unused. */
10229 Tcl_Interp *interp, /* The current interpreter. */
10230 int objc, /* The number of arguments. */
10231 Tcl_Obj *const objv[]) /* The argument strings. */
10232 {
10233 Interp *iPtr = (Interp *) interp;
10234 LiteralTable *globalTablePtr = &iPtr->literalTable;
10235 ByteCodeStats *statsPtr = &iPtr->stats;
10236 double totalCodeBytes, currentCodeBytes;
10237 double totalLiteralBytes, currentLiteralBytes;
10238 double objBytesIfUnshared, strBytesIfUnshared, sharingBytesSaved;
10239 double strBytesSharedMultX, strBytesSharedOnce;
10240 double numInstructions, currentHeaderBytes;
10241 long numCurrentByteCodes, numByteCodeLits;
10242 long refCountSum, literalMgmtBytes, sum;
10243 int numSharedMultX, numSharedOnce;
10244 int decadeHigh, minSizeDecade, maxSizeDecade, length, i;
10245 char *litTableStats;
10246 LiteralEntry *entryPtr;
10247 Tcl_Obj *objPtr;
10248
10249 #define Percent(a,b) ((a) * 100.0 / (b))
10250
10251 TclNewObj(objPtr);
10252 Tcl_IncrRefCount(objPtr);
10253
10254 numInstructions = 0.0;
10255 for (i = 0; i < 256; i++) {
10256 if (statsPtr->instructionCount[i] != 0) {
10257 numInstructions += statsPtr->instructionCount[i];
10258 }
10259 }
10260
10261 totalLiteralBytes = sizeof(LiteralTable)
10262 + iPtr->literalTable.numBuckets * sizeof(LiteralEntry *)
10263 + (statsPtr->numLiteralsCreated * sizeof(LiteralEntry))
10264 + (statsPtr->numLiteralsCreated * sizeof(Tcl_Obj))
10265 + statsPtr->totalLitStringBytes;
10266 totalCodeBytes = statsPtr->totalByteCodeBytes + totalLiteralBytes;
10267
10268 numCurrentByteCodes =
10269 statsPtr->numCompilations - statsPtr->numByteCodesFreed;
10270 currentHeaderBytes = numCurrentByteCodes
10271 * (TclOffset(ByteCode, localCachePtr));
10272 literalMgmtBytes = sizeof(LiteralTable)
10273 + (iPtr->literalTable.numBuckets * sizeof(LiteralEntry *))
10274 + (iPtr->literalTable.numEntries * sizeof(LiteralEntry));
10275 currentLiteralBytes = literalMgmtBytes
10276 + iPtr->literalTable.numEntries * sizeof(Tcl_Obj)
10277 + statsPtr->currentLitStringBytes;
10278 currentCodeBytes = statsPtr->currentByteCodeBytes + currentLiteralBytes;
10279
10280 /*
10281 * Summary statistics, total and current source and ByteCode sizes.
10282 */
10283
10284 Tcl_AppendPrintfToObj(objPtr, "\n----------------------------------------------------------------\n");
10285 Tcl_AppendPrintfToObj(objPtr,
10286 "Compilation and execution statistics for interpreter %#lx\n",
10287 (unsigned long)(size_t)iPtr);
10288
10289 Tcl_AppendPrintfToObj(objPtr, "\nNumber ByteCodes executed\t%ld\n",
10290 statsPtr->numExecutions);
10291 Tcl_AppendPrintfToObj(objPtr, "Number ByteCodes compiled\t%ld\n",
10292 statsPtr->numCompilations);
10293 Tcl_AppendPrintfToObj(objPtr, " Mean executions/compile\t%.1f\n",
10294 statsPtr->numExecutions / (float)statsPtr->numCompilations);
10295
10296 Tcl_AppendPrintfToObj(objPtr, "\nInstructions executed\t\t%.0f\n",
10297 numInstructions);
10298 Tcl_AppendPrintfToObj(objPtr, " Mean inst/compile\t\t%.0f\n",
10299 numInstructions / statsPtr->numCompilations);
10300 Tcl_AppendPrintfToObj(objPtr, " Mean inst/execution\t\t%.0f\n",
10301 numInstructions / statsPtr->numExecutions);
10302
10303 Tcl_AppendPrintfToObj(objPtr, "\nTotal ByteCodes\t\t\t%ld\n",
10304 statsPtr->numCompilations);
10305 Tcl_AppendPrintfToObj(objPtr, " Source bytes\t\t\t%.6g\n",
10306 statsPtr->totalSrcBytes);
10307 Tcl_AppendPrintfToObj(objPtr, " Code bytes\t\t\t%.6g\n",
10308 totalCodeBytes);
10309 Tcl_AppendPrintfToObj(objPtr, " ByteCode bytes\t\t%.6g\n",
10310 statsPtr->totalByteCodeBytes);
10311 Tcl_AppendPrintfToObj(objPtr, " Literal bytes\t\t%.6g\n",
10312 totalLiteralBytes);
10313 Tcl_AppendPrintfToObj(objPtr, " table %lu + bkts %lu + entries %lu + objects %lu + strings %.6g\n",
10314 (unsigned long) sizeof(LiteralTable),
10315 (unsigned long) (iPtr->literalTable.numBuckets * sizeof(LiteralEntry *)),
10316 (unsigned long) (statsPtr->numLiteralsCreated * sizeof(LiteralEntry)),
10317 (unsigned long) (statsPtr->numLiteralsCreated * sizeof(Tcl_Obj)),
10318 statsPtr->totalLitStringBytes);
10319 Tcl_AppendPrintfToObj(objPtr, " Mean code/compile\t\t%.1f\n",
10320 totalCodeBytes / statsPtr->numCompilations);
10321 Tcl_AppendPrintfToObj(objPtr, " Mean code/source\t\t%.1f\n",
10322 totalCodeBytes / statsPtr->totalSrcBytes);
10323
10324 Tcl_AppendPrintfToObj(objPtr, "\nCurrent (active) ByteCodes\t%ld\n",
10325 numCurrentByteCodes);
10326 Tcl_AppendPrintfToObj(objPtr, " Source bytes\t\t\t%.6g\n",
10327 statsPtr->currentSrcBytes);
10328 Tcl_AppendPrintfToObj(objPtr, " Code bytes\t\t\t%.6g\n",
10329 currentCodeBytes);
10330 Tcl_AppendPrintfToObj(objPtr, " ByteCode bytes\t\t%.6g\n",
10331 statsPtr->currentByteCodeBytes);
10332 Tcl_AppendPrintfToObj(objPtr, " Literal bytes\t\t%.6g\n",
10333 currentLiteralBytes);
10334 Tcl_AppendPrintfToObj(objPtr, " table %lu + bkts %lu + entries %lu + objects %lu + strings %.6g\n",
10335 (unsigned long) sizeof(LiteralTable),
10336 (unsigned long) (iPtr->literalTable.numBuckets * sizeof(LiteralEntry *)),
10337 (unsigned long) (iPtr->literalTable.numEntries * sizeof(LiteralEntry)),
10338 (unsigned long) (iPtr->literalTable.numEntries * sizeof(Tcl_Obj)),
10339 statsPtr->currentLitStringBytes);
10340 Tcl_AppendPrintfToObj(objPtr, " Mean code/source\t\t%.1f\n",
10341 currentCodeBytes / statsPtr->currentSrcBytes);
10342 Tcl_AppendPrintfToObj(objPtr, " Code + source bytes\t\t%.6g (%0.1f mean code/src)\n",
10343 (currentCodeBytes + statsPtr->currentSrcBytes),
10344 (currentCodeBytes / statsPtr->currentSrcBytes) + 1.0);
10345
10346 /*
10347 * Tcl_IsShared statistics check
10348 *
10349 * This gives the refcount of each obj as Tcl_IsShared was called for it.
10350 * Shared objects must be duplicated before they can be modified.
10351 */
10352
10353 numSharedMultX = 0;
10354 Tcl_AppendPrintfToObj(objPtr, "\nTcl_IsShared object check (all objects):\n");
10355 Tcl_AppendPrintfToObj(objPtr, " Object had refcount <=1 (not shared)\t%ld\n",
10356 tclObjsShared[1]);
10357 for (i = 2; i < TCL_MAX_SHARED_OBJ_STATS; i++) {
10358 Tcl_AppendPrintfToObj(objPtr, " refcount ==%d\t\t%ld\n",
10359 i, tclObjsShared[i]);
10360 numSharedMultX += tclObjsShared[i];
10361 }
10362 Tcl_AppendPrintfToObj(objPtr, " refcount >=%d\t\t%ld\n",
10363 i, tclObjsShared[0]);
10364 numSharedMultX += tclObjsShared[0];
10365 Tcl_AppendPrintfToObj(objPtr, " Total shared objects\t\t\t%d\n",
10366 numSharedMultX);
10367
10368 /*
10369 * Literal table statistics.
10370 */
10371
10372 numByteCodeLits = 0;
10373 refCountSum = 0;
10374 numSharedMultX = 0;
10375 numSharedOnce = 0;
10376 objBytesIfUnshared = 0.0;
10377 strBytesIfUnshared = 0.0;
10378 strBytesSharedMultX = 0.0;
10379 strBytesSharedOnce = 0.0;
10380 for (i = 0; i < globalTablePtr->numBuckets; i++) {
10381 for (entryPtr = globalTablePtr->buckets[i]; entryPtr != NULL;
10382 entryPtr = entryPtr->nextPtr) {
10383 if (entryPtr->objPtr->typePtr == &tclByteCodeType) {
10384 numByteCodeLits++;
10385 }
10386 (void)TclGetStringFromObj(entryPtr->objPtr, &length);
10387 refCountSum += entryPtr->refCount;
10388 objBytesIfUnshared += (entryPtr->refCount * sizeof(Tcl_Obj));
10389 strBytesIfUnshared += (entryPtr->refCount * (length+1));
10390 if (entryPtr->refCount > 1) {
10391 numSharedMultX++;
10392 strBytesSharedMultX += (length+1);
10393 } else {
10394 numSharedOnce++;
10395 strBytesSharedOnce += (length+1);
10396 }
10397 }
10398 }
10399 sharingBytesSaved = (objBytesIfUnshared + strBytesIfUnshared)
10400 - currentLiteralBytes;
10401
10402 Tcl_AppendPrintfToObj(objPtr, "\nTotal objects (all interps)\t%ld\n",
10403 tclObjsAlloced);
10404 Tcl_AppendPrintfToObj(objPtr, "Current objects\t\t\t%ld\n",
10405 (tclObjsAlloced - tclObjsFreed));
10406 Tcl_AppendPrintfToObj(objPtr, "Total literal objects\t\t%ld\n",
10407 statsPtr->numLiteralsCreated);
10408
10409 Tcl_AppendPrintfToObj(objPtr, "\nCurrent literal objects\t\t%d (%0.1f%% of current objects)\n",
10410 globalTablePtr->numEntries,
10411 Percent(globalTablePtr->numEntries, tclObjsAlloced-tclObjsFreed));
10412 Tcl_AppendPrintfToObj(objPtr, " ByteCode literals\t\t%ld (%0.1f%% of current literals)\n",
10413 numByteCodeLits,
10414 Percent(numByteCodeLits, globalTablePtr->numEntries));
10415 Tcl_AppendPrintfToObj(objPtr, " Literals reused > 1x\t\t%d\n",
10416 numSharedMultX);
10417 Tcl_AppendPrintfToObj(objPtr, " Mean reference count\t\t%.2f\n",
10418 ((double) refCountSum) / globalTablePtr->numEntries);
10419 Tcl_AppendPrintfToObj(objPtr, " Mean len, str reused >1x \t%.2f\n",
10420 (numSharedMultX ? strBytesSharedMultX/numSharedMultX : 0.0));
10421 Tcl_AppendPrintfToObj(objPtr, " Mean len, str used 1x\t\t%.2f\n",
10422 (numSharedOnce ? strBytesSharedOnce/numSharedOnce : 0.0));
10423 Tcl_AppendPrintfToObj(objPtr, " Total sharing savings\t\t%.6g (%0.1f%% of bytes if no sharing)\n",
10424 sharingBytesSaved,
10425 Percent(sharingBytesSaved, objBytesIfUnshared+strBytesIfUnshared));
10426 Tcl_AppendPrintfToObj(objPtr, " Bytes with sharing\t\t%.6g\n",
10427 currentLiteralBytes);
10428 Tcl_AppendPrintfToObj(objPtr, " table %lu + bkts %lu + entries %lu + objects %lu + strings %.6g\n",
10429 (unsigned long) sizeof(LiteralTable),
10430 (unsigned long) (iPtr->literalTable.numBuckets * sizeof(LiteralEntry *)),
10431 (unsigned long) (iPtr->literalTable.numEntries * sizeof(LiteralEntry)),
10432 (unsigned long) (iPtr->literalTable.numEntries * sizeof(Tcl_Obj)),
10433 statsPtr->currentLitStringBytes);
10434 Tcl_AppendPrintfToObj(objPtr, " Bytes if no sharing\t\t%.6g = objects %.6g + strings %.6g\n",
10435 (objBytesIfUnshared + strBytesIfUnshared),
10436 objBytesIfUnshared, strBytesIfUnshared);
10437 Tcl_AppendPrintfToObj(objPtr, " String sharing savings \t%.6g = unshared %.6g - shared %.6g\n",
10438 (strBytesIfUnshared - statsPtr->currentLitStringBytes),
10439 strBytesIfUnshared, statsPtr->currentLitStringBytes);
10440 Tcl_AppendPrintfToObj(objPtr, " Literal mgmt overhead\t\t%ld (%0.1f%% of bytes with sharing)\n",
10441 literalMgmtBytes,
10442 Percent(literalMgmtBytes, currentLiteralBytes));
10443 Tcl_AppendPrintfToObj(objPtr, " table %lu + buckets %lu + entries %lu\n",
10444 (unsigned long) sizeof(LiteralTable),
10445 (unsigned long) (iPtr->literalTable.numBuckets * sizeof(LiteralEntry *)),
10446 (unsigned long) (iPtr->literalTable.numEntries * sizeof(LiteralEntry)));
10447
10448 /*
10449 * Breakdown of current ByteCode space requirements.
10450 */
10451
10452 Tcl_AppendPrintfToObj(objPtr, "\nBreakdown of current ByteCode requirements:\n");
10453 Tcl_AppendPrintfToObj(objPtr, " Bytes Pct of Avg per\n");
10454 Tcl_AppendPrintfToObj(objPtr, " total ByteCode\n");
10455 Tcl_AppendPrintfToObj(objPtr, "Total %12.6g 100.00%% %8.1f\n",
10456 statsPtr->currentByteCodeBytes,
10457 statsPtr->currentByteCodeBytes / numCurrentByteCodes);
10458 Tcl_AppendPrintfToObj(objPtr, "Header %12.6g %8.1f%% %8.1f\n",
10459 currentHeaderBytes,
10460 Percent(currentHeaderBytes, statsPtr->currentByteCodeBytes),
10461 currentHeaderBytes / numCurrentByteCodes);
10462 Tcl_AppendPrintfToObj(objPtr, "Instructions %12.6g %8.1f%% %8.1f\n",
10463 statsPtr->currentInstBytes,
10464 Percent(statsPtr->currentInstBytes,statsPtr->currentByteCodeBytes),
10465 statsPtr->currentInstBytes / numCurrentByteCodes);
10466 Tcl_AppendPrintfToObj(objPtr, "Literal ptr array %12.6g %8.1f%% %8.1f\n",
10467 statsPtr->currentLitBytes,
10468 Percent(statsPtr->currentLitBytes,statsPtr->currentByteCodeBytes),
10469 statsPtr->currentLitBytes / numCurrentByteCodes);
10470 Tcl_AppendPrintfToObj(objPtr, "Exception table %12.6g %8.1f%% %8.1f\n",
10471 statsPtr->currentExceptBytes,
10472 Percent(statsPtr->currentExceptBytes,statsPtr->currentByteCodeBytes),
10473 statsPtr->currentExceptBytes / numCurrentByteCodes);
10474 Tcl_AppendPrintfToObj(objPtr, "Auxiliary data %12.6g %8.1f%% %8.1f\n",
10475 statsPtr->currentAuxBytes,
10476 Percent(statsPtr->currentAuxBytes,statsPtr->currentByteCodeBytes),
10477 statsPtr->currentAuxBytes / numCurrentByteCodes);
10478 Tcl_AppendPrintfToObj(objPtr, "Command map %12.6g %8.1f%% %8.1f\n",
10479 statsPtr->currentCmdMapBytes,
10480 Percent(statsPtr->currentCmdMapBytes,statsPtr->currentByteCodeBytes),
10481 statsPtr->currentCmdMapBytes / numCurrentByteCodes);
10482
10483 /*
10484 * Detailed literal statistics.
10485 */
10486
10487 Tcl_AppendPrintfToObj(objPtr, "\nLiteral string sizes:\n");
10488 Tcl_AppendPrintfToObj(objPtr, "\t Up to length\t\tPercentage\n");
10489 maxSizeDecade = 0;
10490 for (i = 31; i >= 0; i--) {
10491 if (statsPtr->literalCount[i] > 0) {
10492 maxSizeDecade = i;
10493 break;
10494 }
10495 }
10496 sum = 0;
10497 for (i = 0; i <= maxSizeDecade; i++) {
10498 decadeHigh = (1 << (i+1)) - 1;
10499 sum += statsPtr->literalCount[i];
10500 Tcl_AppendPrintfToObj(objPtr, "\t%10d\t\t%8.0f%%\n",
10501 decadeHigh, Percent(sum, statsPtr->numLiteralsCreated));
10502 }
10503
10504 litTableStats = TclLiteralStats(globalTablePtr);
10505 Tcl_AppendPrintfToObj(objPtr, "\nCurrent literal table statistics:\n%s\n",
10506 litTableStats);
10507 ckfree(litTableStats);
10508
10509 /*
10510 * Source and ByteCode size distributions.
10511 */
10512
10513 Tcl_AppendPrintfToObj(objPtr, "\nSource sizes:\n");
10514 Tcl_AppendPrintfToObj(objPtr, "\t Up to size\t\tPercentage\n");
10515 minSizeDecade = maxSizeDecade = 0;
10516 for (i = 0; i < 31; i++) {
10517 if (statsPtr->srcCount[i] > 0) {
10518 minSizeDecade = i;
10519 break;
10520 }
10521 }
10522 for (i = 31; i >= 0; i--) {
10523 if (statsPtr->srcCount[i] > 0) {
10524 maxSizeDecade = i;
10525 break;
10526 }
10527 }
10528 sum = 0;
10529 for (i = minSizeDecade; i <= maxSizeDecade; i++) {
10530 decadeHigh = (1 << (i+1)) - 1;
10531 sum += statsPtr->srcCount[i];
10532 Tcl_AppendPrintfToObj(objPtr, "\t%10d\t\t%8.0f%%\n",
10533 decadeHigh, Percent(sum, statsPtr->numCompilations));
10534 }
10535
10536 Tcl_AppendPrintfToObj(objPtr, "\nByteCode sizes:\n");
10537 Tcl_AppendPrintfToObj(objPtr, "\t Up to size\t\tPercentage\n");
10538 minSizeDecade = maxSizeDecade = 0;
10539 for (i = 0; i < 31; i++) {
10540 if (statsPtr->byteCodeCount[i] > 0) {
10541 minSizeDecade = i;
10542 break;
10543 }
10544 }
10545 for (i = 31; i >= 0; i--) {
10546 if (statsPtr->byteCodeCount[i] > 0) {
10547 maxSizeDecade = i;
10548 break;
10549 }
10550 }
10551 sum = 0;
10552 for (i = minSizeDecade; i <= maxSizeDecade; i++) {
10553 decadeHigh = (1 << (i+1)) - 1;
10554 sum += statsPtr->byteCodeCount[i];
10555 Tcl_AppendPrintfToObj(objPtr, "\t%10d\t\t%8.0f%%\n",
10556 decadeHigh, Percent(sum, statsPtr->numCompilations));
10557 }
10558
10559 Tcl_AppendPrintfToObj(objPtr, "\nByteCode longevity (excludes Current ByteCodes):\n");
10560 Tcl_AppendPrintfToObj(objPtr, "\t Up to ms\t\tPercentage\n");
10561 minSizeDecade = maxSizeDecade = 0;
10562 for (i = 0; i < 31; i++) {
10563 if (statsPtr->lifetimeCount[i] > 0) {
10564 minSizeDecade = i;
10565 break;
10566 }
10567 }
10568 for (i = 31; i >= 0; i--) {
10569 if (statsPtr->lifetimeCount[i] > 0) {
10570 maxSizeDecade = i;
10571 break;
10572 }
10573 }
10574 sum = 0;
10575 for (i = minSizeDecade; i <= maxSizeDecade; i++) {
10576 decadeHigh = (1 << (i+1)) - 1;
10577 sum += statsPtr->lifetimeCount[i];
10578 Tcl_AppendPrintfToObj(objPtr, "\t%12.3f\t\t%8.0f%%\n",
10579 decadeHigh/1000.0, Percent(sum, statsPtr->numByteCodesFreed));
10580 }
10581
10582 /*
10583 * Instruction counts.
10584 */
10585
10586 Tcl_AppendPrintfToObj(objPtr, "\nInstruction counts:\n");
10587 for (i = 0; i <= LAST_INST_OPCODE; i++) {
10588 Tcl_AppendPrintfToObj(objPtr, "%20s %8ld ",
10589 tclInstructionTable[i].name, statsPtr->instructionCount[i]);
10590 if (statsPtr->instructionCount[i]) {
10591 Tcl_AppendPrintfToObj(objPtr, "%6.1f%%\n",
10592 Percent(statsPtr->instructionCount[i], numInstructions));
10593 } else {
10594 Tcl_AppendPrintfToObj(objPtr, "0\n");
10595 }
10596 }
10597
10598 #ifdef TCL_MEM_DEBUG
10599 Tcl_AppendPrintfToObj(objPtr, "\nHeap Statistics:\n");
10600 TclDumpMemoryInfo((ClientData) objPtr, 1);
10601 #endif
10602 Tcl_AppendPrintfToObj(objPtr, "\n----------------------------------------------------------------\n");
10603
10604 if (objc == 1) {
10605 Tcl_SetObjResult(interp, objPtr);
10606 } else {
10607 Tcl_Channel outChan;
10608 char *str = TclGetStringFromObj(objv[1], &length);
10609
10610 if (length) {
10611 if (strcmp(str, "stdout") == 0) {
10612 outChan = Tcl_GetStdChannel(TCL_STDOUT);
10613 } else if (strcmp(str, "stderr") == 0) {
10614 outChan = Tcl_GetStdChannel(TCL_STDERR);
10615 } else {
10616 outChan = Tcl_OpenFileChannel(NULL, str, "w", 0664);
10617 }
10618 } else {
10619 outChan = Tcl_GetStdChannel(TCL_STDOUT);
10620 }
10621 if (outChan != NULL) {
10622 Tcl_WriteObj(outChan, objPtr);
10623 }
10624 }
10625 Tcl_DecrRefCount(objPtr);
10626 return TCL_OK;
10627 }
10628 #endif /* TCL_COMPILE_STATS */
10629
10630 #ifdef TCL_COMPILE_DEBUG
10631 /*
10632 *----------------------------------------------------------------------
10633 *
10634 * StringForResultCode --
10635 *
10636 * Procedure that returns a human-readable string representing a Tcl
10637 * result code such as TCL_ERROR.
10638 *
10639 * Results:
10640 * If the result code is one of the standard Tcl return codes, the result
10641 * is a string representing that code such as "TCL_ERROR". Otherwise, the
10642 * result string is that code formatted as a sequence of decimal digit
10643 * characters. Note that the resulting string must not be modified by the
10644 * caller.
10645 *
10646 * Side effects:
10647 * None.
10648 *
10649 *----------------------------------------------------------------------
10650 */
10651
10652 static const char *
10653 StringForResultCode(
10654 int result) /* The Tcl result code for which to generate a
10655 * string. */
10656 {
10657 static char buf[TCL_INTEGER_SPACE];
10658
10659 if ((result >= TCL_OK) && (result <= TCL_CONTINUE)) {
10660 return resultStrings[result];
10661 }
10662 TclFormatInt(buf, result);
10663 return buf;
10664 }
10665 #endif /* TCL_COMPILE_DEBUG */
10666
10667 /*
10668 * Local Variables:
10669 * mode: c
10670 * c-basic-offset: 4
10671 * fill-column: 78
10672 * End:
10673 */