Debian Codegraph @

generic/tclLiteral.c

raw
1 /*
2 * tclLiteral.c --
3 *
4 * Implementation of the global and ByteCode-local literal tables used to
5 * manage the Tcl objects created for literal values during compilation
6 * of Tcl scripts. This implementation borrows heavily from the more
7 * general hashtable implementation of Tcl hash tables that appears in
8 * tclHash.c.
9 *
10 * Copyright (c) 1997-1998 Sun Microsystems, Inc.
11 * Copyright (c) 2004 by Kevin B. Kenny. All rights reserved.
12 *
13 * See the file "license.terms" for information on usage and redistribution of
14 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
15 */
16
17 #include "tclInt.h"
18 #include "tclCompile.h"
19
20 /*
21 * When there are this many entries per bucket, on average, rebuild a
22 * literal's hash table to make it larger.
23 */
24
25 #define REBUILD_MULTIPLIER 3
26
27 /*
28 * Function prototypes for static functions in this file:
29 */
30
31 static int AddLocalLiteralEntry(CompileEnv *envPtr,
32 Tcl_Obj *objPtr, int localHash);
33 static void ExpandLocalLiteralArray(CompileEnv *envPtr);
34 static unsigned HashString(const char *string, int length);
35 #ifdef TCL_COMPILE_DEBUG
36 static LiteralEntry * LookupLiteralEntry(Tcl_Interp *interp,
37 Tcl_Obj *objPtr);
38 #endif
39 static void RebuildLiteralTable(LiteralTable *tablePtr);
40
41 /*
42 *----------------------------------------------------------------------
43 *
44 * TclInitLiteralTable --
45 *
46 * This function is called to initialize the fields of a literal table
47 * structure for either an interpreter or a compilation's CompileEnv
48 * structure.
49 *
50 * Results:
51 * None.
52 *
53 * Side effects:
54 * The literal table is made ready for use.
55 *
56 *----------------------------------------------------------------------
57 */
58
59 void
60 TclInitLiteralTable(
61 LiteralTable *tablePtr)
62 /* Pointer to table structure, which is
63 * supplied by the caller. */
64 {
65 #if (TCL_SMALL_HASH_TABLE != 4)
66 Tcl_Panic("%s: TCL_SMALL_HASH_TABLE is %d, not 4", "TclInitLiteralTable",
67 TCL_SMALL_HASH_TABLE);
68 #endif
69
70 tablePtr->buckets = tablePtr->staticBuckets;
71 tablePtr->staticBuckets[0] = tablePtr->staticBuckets[1] = 0;
72 tablePtr->staticBuckets[2] = tablePtr->staticBuckets[3] = 0;
73 tablePtr->numBuckets = TCL_SMALL_HASH_TABLE;
74 tablePtr->numEntries = 0;
75 tablePtr->rebuildSize = TCL_SMALL_HASH_TABLE * REBUILD_MULTIPLIER;
76 tablePtr->mask = 3;
77 }
78
79 /*
80 *----------------------------------------------------------------------
81 *
82 * TclDeleteLiteralTable --
83 *
84 * This function frees up everything associated with a literal table
85 * except for the table's structure itself. It is called when the
86 * interpreter is deleted.
87 *
88 * Results:
89 * None.
90 *
91 * Side effects:
92 * Each literal in the table is released: i.e., its reference count in
93 * the global literal table is decremented and, if it becomes zero, the
94 * literal is freed. In addition, the table's bucket array is freed.
95 *
96 *----------------------------------------------------------------------
97 */
98
99 void
100 TclDeleteLiteralTable(
101 Tcl_Interp *interp, /* Interpreter containing shared literals
102 * referenced by the table to delete. */
103 LiteralTable *tablePtr) /* Points to the literal table to delete. */
104 {
105 LiteralEntry *entryPtr, *nextPtr;
106 Tcl_Obj *objPtr;
107 int i;
108
109 /*
110 * Release remaining literals in the table. Note that releasing a literal
111 * might release other literals, modifying the table, so we restart the
112 * search from the bucket chain we last found an entry.
113 */
114
115 #ifdef TCL_COMPILE_DEBUG
116 TclVerifyGlobalLiteralTable((Interp *) interp);
117 #endif /*TCL_COMPILE_DEBUG*/
118
119 /*
120 * We used to call TclReleaseLiteral for each literal in the table, which
121 * is rather inefficient as it causes one lookup-by-hash for each
122 * reference to the literal. We now rely at interp-deletion on each
123 * bytecode object to release its references to the literal Tcl_Obj
124 * without requiring that it updates the global table itself, and deal
125 * here only with the table.
126 */
127
128 for (i=0 ; i<tablePtr->numBuckets ; i++) {
129 entryPtr = tablePtr->buckets[i];
130 while (entryPtr != NULL) {
131 objPtr = entryPtr->objPtr;
132 TclDecrRefCount(objPtr);
133 nextPtr = entryPtr->nextPtr;
134 ckfree(entryPtr);
135 entryPtr = nextPtr;
136 }
137 }
138
139 /*
140 * Free up the table's bucket array if it was dynamically allocated.
141 */
142
143 if (tablePtr->buckets != tablePtr->staticBuckets) {
144 ckfree(tablePtr->buckets);
145 }
146 }
147
148 /*
149 *----------------------------------------------------------------------
150 *
151 * TclCreateLiteral --
152 *
153 * Find, or if necessary create, an object in the interpreter's literal
154 * table that has a string representation matching the argument
155 * string. If nsPtr!=NULL then only literals stored for the namespace are
156 * considered.
157 *
158 * Results:
159 * The literal object. If it was created in this call *newPtr is set to
160 * 1, else 0. NULL is returned if newPtr==NULL and no literal is found.
161 *
162 * Side effects:
163 * Increments the ref count of the global LiteralEntry since the caller
164 * now holds a reference. If LITERAL_ON_HEAP is set in flags, this
165 * function is given ownership of the string: if an object is created
166 * then its string representation is set directly from string, otherwise
167 * the string is freed. Typically, a caller sets LITERAL_ON_HEAP if
168 * "string" is an already heap-allocated buffer holding the result of
169 * backslash substitutions.
170 *
171 *----------------------------------------------------------------------
172 */
173
174 Tcl_Obj *
175 TclCreateLiteral(
176 Interp *iPtr,
177 char *bytes, /* The start of the string. Note that this is
178 * not a NUL-terminated string. */
179 int length, /* Number of bytes in the string. */
180 unsigned hash, /* The string's hash. If -1, it will be
181 * computed here. */
182 int *newPtr,
183 Namespace *nsPtr,
184 int flags,
185 LiteralEntry **globalPtrPtr)
186 {
187 LiteralTable *globalTablePtr = &iPtr->literalTable;
188 LiteralEntry *globalPtr;
189 int globalHash;
190 Tcl_Obj *objPtr;
191
192 /*
193 * Is it in the interpreter's global literal table?
194 */
195
196 if (hash == (unsigned) -1) {
197 hash = HashString(bytes, length);
198 }
199 globalHash = (hash & globalTablePtr->mask);
200 for (globalPtr=globalTablePtr->buckets[globalHash] ; globalPtr!=NULL;
201 globalPtr = globalPtr->nextPtr) {
202 objPtr = globalPtr->objPtr;
203 if (globalPtr->nsPtr == nsPtr) {
204 /*
205 * Literals should always have UTF-8 representations... but this
206 * is not guaranteed so we need to be careful anyway.
207 *
208 * https://stackoverflow.com/q/54337750/301832
209 */
210
211 int objLength;
212 char *objBytes = TclGetStringFromObj(objPtr, &objLength);
213
214 if ((objLength == length) && ((length == 0)
215 || ((objBytes[0] == bytes[0])
216 && (memcmp(objBytes, bytes, length) == 0)))) {
217 /*
218 * A literal was found: return it
219 */
220
221 if (newPtr) {
222 *newPtr = 0;
223 }
224 if (globalPtrPtr) {
225 *globalPtrPtr = globalPtr;
226 }
227 if (flags & LITERAL_ON_HEAP) {
228 ckfree(bytes);
229 }
230 globalPtr->refCount++;
231 return objPtr;
232 }
233 }
234 }
235 if (!newPtr) {
236 if ((flags & LITERAL_ON_HEAP)) {
237 ckfree(bytes);
238 }
239 return NULL;
240 }
241
242 /*
243 * The literal is new to the interpreter. Add it to the global literal
244 * table.
245 */
246
247 TclNewObj(objPtr);
248 if ((flags & LITERAL_ON_HEAP)) {
249 objPtr->bytes = bytes;
250 objPtr->length = length;
251 } else {
252 TclInitStringRep(objPtr, bytes, length);
253 }
254
255 if ((flags & LITERAL_UNSHARED)) {
256 /*
257 * Make clear, that no global value is returned
258 */
259 if (globalPtrPtr != NULL) {
260 *globalPtrPtr = NULL;
261 }
262 return objPtr;
263 }
264
265 #ifdef TCL_COMPILE_DEBUG
266 if (LookupLiteralEntry((Tcl_Interp *) iPtr, objPtr) != NULL) {
267 Tcl_Panic("%s: literal \"%.*s\" found globally but shouldn't be",
268 "TclRegisterLiteral", (length>60? 60 : length), bytes);
269 }
270 #endif
271
272 globalPtr = (LiteralEntry *)ckalloc(sizeof(LiteralEntry));
273 globalPtr->objPtr = objPtr;
274 Tcl_IncrRefCount(objPtr);
275 globalPtr->refCount = 1;
276 globalPtr->nsPtr = nsPtr;
277 globalPtr->nextPtr = globalTablePtr->buckets[globalHash];
278 globalTablePtr->buckets[globalHash] = globalPtr;
279 globalTablePtr->numEntries++;
280
281 /*
282 * If the global literal table has exceeded a decent size, rebuild it with
283 * more buckets.
284 */
285
286 if (globalTablePtr->numEntries >= globalTablePtr->rebuildSize) {
287 RebuildLiteralTable(globalTablePtr);
288 }
289
290 #ifdef TCL_COMPILE_DEBUG
291 TclVerifyGlobalLiteralTable(iPtr);
292 {
293 LiteralEntry *entryPtr;
294 int found, i;
295
296 found = 0;
297 for (i=0 ; i<globalTablePtr->numBuckets ; i++) {
298 for (entryPtr=globalTablePtr->buckets[i]; entryPtr!=NULL ;
299 entryPtr=entryPtr->nextPtr) {
300 if ((entryPtr == globalPtr) && (entryPtr->objPtr == objPtr)) {
301 found = 1;
302 }
303 }
304 }
305 if (!found) {
306 Tcl_Panic("%s: literal \"%.*s\" wasn't global",
307 "TclRegisterLiteral", (length>60? 60 : length), bytes);
308 }
309 }
310 #endif /*TCL_COMPILE_DEBUG*/
311
312 #ifdef TCL_COMPILE_STATS
313 iPtr->stats.numLiteralsCreated++;
314 iPtr->stats.totalLitStringBytes += (double) (length + 1);
315 iPtr->stats.currentLitStringBytes += (double) (length + 1);
316 iPtr->stats.literalCount[TclLog2(length)]++;
317 #endif /*TCL_COMPILE_STATS*/
318
319 if (globalPtrPtr) {
320 *globalPtrPtr = globalPtr;
321 }
322 *newPtr = 1;
323 return objPtr;
324 }
325
326 /*
327 *----------------------------------------------------------------------
328 *
329 * TclFetchLiteral --
330 *
331 * Fetch from a CompileEnv the literal value identified by an index
332 * value, as returned by a prior call to TclRegisterLiteral().
333 *
334 * Results:
335 * The literal value, or NULL if the index is out of range.
336 *
337 *----------------------------------------------------------------------
338 */
339
340 Tcl_Obj *
341 TclFetchLiteral(
342 CompileEnv *envPtr, /* Points to the CompileEnv from which to
343 * fetch the registered literal value. */
344 unsigned int index) /* Index of the desired literal, as returned
345 * by prior call to TclRegisterLiteral() */
346 {
347 if (index >= (unsigned int) envPtr->literalArrayNext) {
348 return NULL;
349 }
350 return envPtr->literalArrayPtr[index].objPtr;
351 }
352
353 /*
354 *----------------------------------------------------------------------
355 *
356 * TclRegisterLiteral --
357 *
358 * Find, or if necessary create, an object in a CompileEnv literal array
359 * that has a string representation matching the argument string.
360 *
361 * Results:
362 * The index in the CompileEnv's literal array that references a shared
363 * literal matching the string. The object is created if necessary.
364 *
365 * Side effects:
366 * To maximize sharing, we look up the string in the interpreter's global
367 * literal table. If not found, we create a new shared literal in the
368 * global table. We then add a reference to the shared literal in the
369 * CompileEnv's literal array.
370 *
371 * If LITERAL_ON_HEAP is set in flags, this function is given ownership
372 * of the string: if an object is created then its string representation
373 * is set directly from string, otherwise the string is freed. Typically,
374 * a caller sets LITERAL_ON_HEAP if "string" is an already heap-allocated
375 * buffer holding the result of backslash substitutions.
376 *
377 *----------------------------------------------------------------------
378 */
379
380 int
381 TclRegisterLiteral(
382 void *ePtr, /* Points to the CompileEnv in whose object
383 * array an object is found or created. */
384 char *bytes, /* Points to string for which to find or
385 * create an object in CompileEnv's object
386 * array. */
387 int length, /* Number of bytes in the string. If < 0, the
388 * string consists of all bytes up to the
389 * first null character. */
390 int flags) /* If LITERAL_ON_HEAP then the caller already
391 * malloc'd bytes and ownership is passed to
392 * this function. If LITERAL_CMD_NAME then
393 * the literal should not be shared across
394 * namespaces. */
395 {
396 CompileEnv *envPtr = (CompileEnv *)ePtr;
397 Interp *iPtr = envPtr->iPtr;
398 LiteralTable *localTablePtr = &envPtr->localLitTable;
399 LiteralEntry *globalPtr, *localPtr;
400 Tcl_Obj *objPtr;
401 unsigned hash;
402 int localHash, objIndex, isNew;
403 Namespace *nsPtr;
404
405 if (length < 0) {
406 length = (bytes ? strlen(bytes) : 0);
407 }
408 hash = HashString(bytes, length);
409
410 /*
411 * Is the literal already in the CompileEnv's local literal array? If so,
412 * just return its index.
413 */
414
415 localHash = (hash & localTablePtr->mask);
416 for (localPtr=localTablePtr->buckets[localHash] ; localPtr!=NULL;
417 localPtr = localPtr->nextPtr) {
418 objPtr = localPtr->objPtr;
419 if ((objPtr->length == length) && ((length == 0)
420 || ((objPtr->bytes[0] == bytes[0])
421 && (memcmp(objPtr->bytes, bytes, length) == 0)))) {
422 if ((flags & LITERAL_ON_HEAP)) {
423 ckfree(bytes);
424 }
425 objIndex = (localPtr - envPtr->literalArrayPtr);
426 #ifdef TCL_COMPILE_DEBUG
427 TclVerifyLocalLiteralTable(envPtr);
428 #endif /*TCL_COMPILE_DEBUG*/
429
430 return objIndex;
431 }
432 }
433
434 /*
435 * The literal is new to this CompileEnv. If it is a command name, avoid
436 * sharing it across namespaces, and try not to share it with non-cmd
437 * literals. Note that FQ command names can be shared, so that we register
438 * the namespace as the interp's global NS.
439 */
440
441 if ((flags & LITERAL_CMD_NAME)) {
442 if ((length >= 2) && (bytes[0] == ':') && (bytes[1] == ':')) {
443 nsPtr = iPtr->globalNsPtr;
444 } else {
445 nsPtr = iPtr->varFramePtr->nsPtr;
446 }
447 } else {
448 nsPtr = NULL;
449 }
450
451 /*
452 * Is it in the interpreter's global literal table? If not, create it.
453 */
454
455 globalPtr = NULL;
456 objPtr = TclCreateLiteral(iPtr, bytes, length, hash, &isNew, nsPtr, flags,
457 &globalPtr);
458 objIndex = AddLocalLiteralEntry(envPtr, objPtr, localHash);
459
460 #ifdef TCL_COMPILE_DEBUG
461 if (globalPtr != NULL && globalPtr->refCount < 1) {
462 Tcl_Panic("%s: global literal \"%.*s\" had bad refCount %d",
463 "TclRegisterLiteral", (length>60? 60 : length), bytes,
464 globalPtr->refCount);
465 }
466 TclVerifyLocalLiteralTable(envPtr);
467 #endif /*TCL_COMPILE_DEBUG*/
468 return objIndex;
469 }
470
471 #ifdef TCL_COMPILE_DEBUG
472 /*
473 *----------------------------------------------------------------------
474 *
475 * LookupLiteralEntry --
476 *
477 * Finds the LiteralEntry that corresponds to a literal Tcl object
478 * holding a literal.
479 *
480 * Results:
481 * Returns the matching LiteralEntry if found, otherwise NULL.
482 *
483 * Side effects:
484 * None.
485 *
486 *----------------------------------------------------------------------
487 */
488
489 static LiteralEntry *
490 LookupLiteralEntry(
491 Tcl_Interp *interp, /* Interpreter for which objPtr was created to
492 * hold a literal. */
493 Tcl_Obj *objPtr) /* Points to a Tcl object holding a literal
494 * that was previously created by a call to
495 * TclRegisterLiteral. */
496 {
497 Interp *iPtr = (Interp *) interp;
498 LiteralTable *globalTablePtr = &iPtr->literalTable;
499 LiteralEntry *entryPtr;
500 const char *bytes;
501 int length, globalHash;
502
503 bytes = TclGetStringFromObj(objPtr, &length);
504 globalHash = (HashString(bytes, length) & globalTablePtr->mask);
505 for (entryPtr=globalTablePtr->buckets[globalHash] ; entryPtr!=NULL;
506 entryPtr=entryPtr->nextPtr) {
507 if (entryPtr->objPtr == objPtr) {
508 return entryPtr;
509 }
510 }
511 return NULL;
512 }
513
514 #endif
515 /*
516 *----------------------------------------------------------------------
517 *
518 * TclHideLiteral --
519 *
520 * Remove a literal entry from the literal hash tables, leaving it in the
521 * literal array so existing references continue to function. This makes
522 * it possible to turn a shared literal into a private literal that
523 * cannot be shared.
524 *
525 * Results:
526 * None.
527 *
528 * Side effects:
529 * Removes the literal from the local hash table and decrements the
530 * global hash entry's reference count.
531 *
532 *----------------------------------------------------------------------
533 */
534
535 void
536 TclHideLiteral(
537 Tcl_Interp *interp, /* Interpreter for which objPtr was created to
538 * hold a literal. */
539 CompileEnv *envPtr,/* Points to CompileEnv whose literal array
540 * contains the entry being hidden. */
541 int index) /* The index of the entry in the literal
542 * array. */
543 {
544 LiteralEntry **nextPtrPtr, *entryPtr, *lPtr;
545 LiteralTable *localTablePtr = &envPtr->localLitTable;
546 int localHash, length;
547 const char *bytes;
548 Tcl_Obj *newObjPtr;
549
550 lPtr = &envPtr->literalArrayPtr[index];
551
552 /*
553 * To avoid unwanted sharing we need to copy the object and remove it from
554 * the local and global literal tables. It still has a slot in the literal
555 * array so it can be referred to by byte codes, but it will not be
556 * matched by literal searches.
557 */
558
559 newObjPtr = Tcl_DuplicateObj(lPtr->objPtr);
560 Tcl_IncrRefCount(newObjPtr);
561 TclReleaseLiteral(interp, lPtr->objPtr);
562 lPtr->objPtr = newObjPtr;
563
564 bytes = TclGetStringFromObj(newObjPtr, &length);
565 localHash = (HashString(bytes, length) & localTablePtr->mask);
566 nextPtrPtr = &localTablePtr->buckets[localHash];
567
568 for (entryPtr=*nextPtrPtr ; entryPtr!=NULL ; entryPtr=*nextPtrPtr) {
569 if (entryPtr == lPtr) {
570 *nextPtrPtr = lPtr->nextPtr;
571 lPtr->nextPtr = NULL;
572 localTablePtr->numEntries--;
573 break;
574 }
575 nextPtrPtr = &entryPtr->nextPtr;
576 }
577 }
578
579 /*
580 *----------------------------------------------------------------------
581 *
582 * TclAddLiteralObj --
583 *
584 * Add a single literal object to the literal array. This function does
585 * not add the literal to the local or global literal tables. The caller
586 * is expected to add the entry to whatever tables are appropriate.
587 *
588 * Results:
589 * The index in the CompileEnv's literal array that references the
590 * literal. Stores the pointer to the new literal entry in the location
591 * referenced by the localPtrPtr argument.
592 *
593 * Side effects:
594 * Expands the literal array if necessary. Increments the refcount on the
595 * literal object.
596 *
597 *----------------------------------------------------------------------
598 */
599
600 int
601 TclAddLiteralObj(
602 CompileEnv *envPtr,/* Points to CompileEnv in whose literal array
603 * the object is to be inserted. */
604 Tcl_Obj *objPtr, /* The object to insert into the array. */
605 LiteralEntry **litPtrPtr) /* The location where the pointer to the new
606 * literal entry should be stored. May be
607 * NULL. */
608 {
609 LiteralEntry *lPtr;
610 int objIndex;
611
612 if (envPtr->literalArrayNext >= envPtr->literalArrayEnd) {
613 ExpandLocalLiteralArray(envPtr);
614 }
615 objIndex = envPtr->literalArrayNext;
616 envPtr->literalArrayNext++;
617
618 lPtr = &envPtr->literalArrayPtr[objIndex];
619 lPtr->objPtr = objPtr;
620 Tcl_IncrRefCount(objPtr);
621 lPtr->refCount = -1; /* i.e., unused */
622 lPtr->nextPtr = NULL;
623
624 if (litPtrPtr) {
625 *litPtrPtr = lPtr;
626 }
627
628 return objIndex;
629 }
630
631 /*
632 *----------------------------------------------------------------------
633 *
634 * AddLocalLiteralEntry --
635 *
636 * Insert a new literal into a CompileEnv's local literal array.
637 *
638 * Results:
639 * The index in the CompileEnv's literal array that references the
640 * literal.
641 *
642 * Side effects:
643 * Expands the literal array if necessary. May rebuild the hash bucket
644 * array of the CompileEnv's literal array if it becomes too large.
645 *
646 *----------------------------------------------------------------------
647 */
648
649 static int
650 AddLocalLiteralEntry(
651 CompileEnv *envPtr,/* Points to CompileEnv in whose literal array
652 * the object is to be inserted. */
653 Tcl_Obj *objPtr, /* The literal to add to the CompileEnv. */
654 int localHash) /* Hash value for the literal's string. */
655 {
656 LiteralTable *localTablePtr = &envPtr->localLitTable;
657 LiteralEntry *localPtr;
658 int objIndex;
659
660 objIndex = TclAddLiteralObj(envPtr, objPtr, &localPtr);
661
662 /*
663 * Add the literal to the local table.
664 */
665
666 localPtr->nextPtr = localTablePtr->buckets[localHash];
667 localTablePtr->buckets[localHash] = localPtr;
668 localTablePtr->numEntries++;
669
670 /*
671 * If the CompileEnv's local literal table has exceeded a decent size,
672 * rebuild it with more buckets.
673 */
674
675 if (localTablePtr->numEntries >= localTablePtr->rebuildSize) {
676 RebuildLiteralTable(localTablePtr);
677 }
678
679 #ifdef TCL_COMPILE_DEBUG
680 TclVerifyLocalLiteralTable(envPtr);
681 {
682 char *bytes;
683 int length, found, i;
684
685 found = 0;
686 for (i=0 ; i<localTablePtr->numBuckets ; i++) {
687 for (localPtr=localTablePtr->buckets[i] ; localPtr!=NULL ;
688 localPtr=localPtr->nextPtr) {
689 if (localPtr->objPtr == objPtr) {
690 found = 1;
691 }
692 }
693 }
694
695 if (!found) {
696 bytes = TclGetStringFromObj(objPtr, &length);
697 Tcl_Panic("%s: literal \"%.*s\" wasn't found locally",
698 "AddLocalLiteralEntry", (length>60? 60 : length), bytes);
699 }
700 }
701 #endif /*TCL_COMPILE_DEBUG*/
702
703 return objIndex;
704 }
705
706 /*
707 *----------------------------------------------------------------------
708 *
709 * ExpandLocalLiteralArray --
710 *
711 * Function that uses malloc to allocate more storage for a CompileEnv's
712 * local literal array.
713 *
714 * Results:
715 * None.
716 *
717 * Side effects:
718 * The literal array in *envPtr is reallocated to a new array of double
719 * the size, and if envPtr->mallocedLiteralArray is non-zero the old
720 * array is freed. Entries are copied from the old array to the new one.
721 * The local literal table is updated to refer to the new entries.
722 *
723 *----------------------------------------------------------------------
724 */
725
726 static void
727 ExpandLocalLiteralArray(
728 CompileEnv *envPtr)/* Points to the CompileEnv whose object array
729 * must be enlarged. */
730 {
731 /*
732 * The current allocated local literal entries are stored between elements
733 * 0 and (envPtr->literalArrayNext - 1) [inclusive].
734 */
735
736 LiteralTable *localTablePtr = &envPtr->localLitTable;
737 int currElems = envPtr->literalArrayNext;
738 size_t currBytes = (currElems * sizeof(LiteralEntry));
739 LiteralEntry *currArrayPtr = envPtr->literalArrayPtr;
740 LiteralEntry *newArrayPtr;
741 int i;
742 unsigned int newSize = (currBytes <= UINT_MAX / 2) ? 2*currBytes : UINT_MAX;
743
744 if (currBytes == newSize) {
745 Tcl_Panic("max size of Tcl literal array (%d literals) exceeded",
746 currElems);
747 }
748
749 if (envPtr->mallocedLiteralArray) {
750 newArrayPtr = (LiteralEntry *)ckrealloc(currArrayPtr, newSize);
751 } else {
752 /*
753 * envPtr->literalArrayPtr isn't a ckalloc'd pointer, so we must
754 * code a ckrealloc equivalent for ourselves.
755 */
756
757 newArrayPtr = (LiteralEntry *)ckalloc(newSize);
758 memcpy(newArrayPtr, currArrayPtr, currBytes);
759 envPtr->mallocedLiteralArray = 1;
760 }
761
762 /*
763 * Update the local literal table's bucket array.
764 */
765
766 if (currArrayPtr != newArrayPtr) {
767 for (i=0 ; i<currElems ; i++) {
768 if (newArrayPtr[i].nextPtr != NULL) {
769 newArrayPtr[i].nextPtr = newArrayPtr
770 + (newArrayPtr[i].nextPtr - currArrayPtr);
771 }
772 }
773 for (i=0 ; i<localTablePtr->numBuckets ; i++) {
774 if (localTablePtr->buckets[i] != NULL) {
775 localTablePtr->buckets[i] = newArrayPtr
776 + (localTablePtr->buckets[i] - currArrayPtr);
777 }
778 }
779 }
780
781 envPtr->literalArrayPtr = newArrayPtr;
782 envPtr->literalArrayEnd = newSize / sizeof(LiteralEntry);
783 }
784
785 /*
786 *----------------------------------------------------------------------
787 *
788 * TclReleaseLiteral --
789 *
790 * This function releases a reference to one of the shared Tcl objects
791 * that hold literals. It is called to release the literals referenced by
792 * a ByteCode that is being destroyed, and it is also called by
793 * TclDeleteLiteralTable.
794 *
795 * Results:
796 * None.
797 *
798 * Side effects:
799 * The reference count for the global LiteralTable entry that corresponds
800 * to the literal is decremented. If no other reference to a global
801 * literal object remains, it is freed.
802 *
803 *----------------------------------------------------------------------
804 */
805
806 void
807 TclReleaseLiteral(
808 Tcl_Interp *interp, /* Interpreter for which objPtr was created to
809 * hold a literal. */
810 Tcl_Obj *objPtr) /* Points to a literal object that was
811 * previously created by a call to
812 * TclRegisterLiteral. */
813 {
814 Interp *iPtr = (Interp *) interp;
815 LiteralTable *globalTablePtr;
816 LiteralEntry *entryPtr, *prevPtr;
817 const char *bytes;
818 int length, index;
819
820 if (iPtr == NULL) {
821 goto done;
822 }
823
824 globalTablePtr = &iPtr->literalTable;
825 bytes = TclGetStringFromObj(objPtr, &length);
826 index = (HashString(bytes, length) & globalTablePtr->mask);
827
828 /*
829 * Check to see if the object is in the global literal table and remove
830 * this reference. The object may not be in the table if it is a hidden
831 * local literal.
832 */
833
834 for (prevPtr=NULL, entryPtr=globalTablePtr->buckets[index];
835 entryPtr!=NULL ; prevPtr=entryPtr, entryPtr=entryPtr->nextPtr) {
836 if (entryPtr->objPtr == objPtr) {
837 entryPtr->refCount--;
838
839 /*
840 * If the literal is no longer being used by any ByteCode, delete
841 * the entry then remove the reference corresponding to the global
842 * literal table entry (decrement the ref count of the object).
843 */
844
845 if (entryPtr->refCount == 0) {
846 if (prevPtr == NULL) {
847 globalTablePtr->buckets[index] = entryPtr->nextPtr;
848 } else {
849 prevPtr->nextPtr = entryPtr->nextPtr;
850 }
851 ckfree(entryPtr);
852 globalTablePtr->numEntries--;
853
854 TclDecrRefCount(objPtr);
855
856 #ifdef TCL_COMPILE_STATS
857 iPtr->stats.currentLitStringBytes -= (double) (length + 1);
858 #endif /*TCL_COMPILE_STATS*/
859 }
860 break;
861 }
862 }
863
864 /*
865 * Remove the reference corresponding to the local literal table entry.
866 */
867
868 done:
869 Tcl_DecrRefCount(objPtr);
870 }
871
872 /*
873 *----------------------------------------------------------------------
874 *
875 * HashString --
876 *
877 * Compute a one-word summary of a text string, which can be used to
878 * generate a hash index.
879 *
880 * Results:
881 * The return value is a one-word summary of the information in string.
882 *
883 * Side effects:
884 * None.
885 *
886 *----------------------------------------------------------------------
887 */
888
889 static unsigned
890 HashString(
891 const char *string, /* String for which to compute hash value. */
892 int length) /* Number of bytes in the string. */
893 {
894 unsigned int result = 0;
895
896 /*
897 * I tried a zillion different hash functions and asked many other people
898 * for advice. Many people had their own favorite functions, all
899 * different, but no-one had much idea why they were good ones. I chose
900 * the one below (multiply by 9 and add new character) because of the
901 * following reasons:
902 *
903 * 1. Multiplying by 10 is perfect for keys that are decimal strings, and
904 * multiplying by 9 is just about as good.
905 * 2. Times-9 is (shift-left-3) plus (old). This means that each
906 * character's bits hang around in the low-order bits of the hash value
907 * for ever, plus they spread fairly rapidly up to the high-order bits
908 * to fill out the hash value. This seems works well both for decimal
909 * and non-decimal strings.
910 *
911 * Note that this function is very weak against malicious strings; it's
912 * very easy to generate multiple keys that have the same hashcode. On the
913 * other hand, that hardly ever actually occurs and this function *is*
914 * very cheap, even by comparison with industry-standard hashes like FNV.
915 * If real strength of hash is required though, use a custom hash based on
916 * Bob Jenkins's lookup3(), but be aware that it's significantly slower.
917 * Tcl scripts tend to not have a big issue in this area, and literals
918 * mostly aren't looked up by name anyway.
919 *
920 * See also HashStringKey in tclHash.c.
921 * See also TclObjHashKey in tclObj.c.
922 *
923 * See [tcl-Feature Request #2958832]
924 */
925
926 if (length > 0) {
927 result = UCHAR(*string);
928 while (--length) {
929 result += (result << 3) + UCHAR(*++string);
930 }
931 }
932 return result;
933 }
934
935 /*
936 *----------------------------------------------------------------------
937 *
938 * RebuildLiteralTable --
939 *
940 * This function is invoked when the ratio of entries to hash buckets
941 * becomes too large in a local or global literal table. It allocates a
942 * larger bucket array and moves the entries into the new buckets.
943 *
944 * Results:
945 * None.
946 *
947 * Side effects:
948 * Memory gets reallocated and entries get rehashed into new buckets.
949 *
950 *----------------------------------------------------------------------
951 */
952
953 static void
954 RebuildLiteralTable(
955 LiteralTable *tablePtr)
956 /* Local or global table to enlarge. */
957 {
958 LiteralEntry **oldBuckets;
959 LiteralEntry **oldChainPtr, **newChainPtr;
960 LiteralEntry *entryPtr;
961 LiteralEntry **bucketPtr;
962 const char *bytes;
963 unsigned int oldSize;
964 int count, index, length;
965
966 oldSize = tablePtr->numBuckets;
967 oldBuckets = tablePtr->buckets;
968
969 /*
970 * Allocate and initialize the new bucket array, and set up hashing
971 * constants for new array size.
972 */
973
974 if (oldSize > UINT_MAX/(4 * sizeof(LiteralEntry *))) {
975 /*
976 * Memory allocator limitations will not let us create the
977 * next larger table size. Best option is to limp along
978 * with what we have.
979 */
980
981 return;
982 }
983
984 tablePtr->numBuckets *= 4;
985 tablePtr->buckets = (LiteralEntry **)ckalloc(
986 tablePtr->numBuckets * sizeof(LiteralEntry *));
987 for (count=tablePtr->numBuckets, newChainPtr=tablePtr->buckets;
988 count>0 ; count--, newChainPtr++) {
989 *newChainPtr = NULL;
990 }
991 tablePtr->rebuildSize *= 4;
992 tablePtr->mask = (tablePtr->mask << 2) + 3;
993
994 /*
995 * Rehash all of the existing entries into the new bucket array.
996 */
997
998 for (oldChainPtr=oldBuckets ; oldSize>0 ; oldSize--,oldChainPtr++) {
999 for (entryPtr=*oldChainPtr ; entryPtr!=NULL ; entryPtr=*oldChainPtr) {
1000 bytes = TclGetStringFromObj(entryPtr->objPtr, &length);
1001 index = (HashString(bytes, length) & tablePtr->mask);
1002
1003 *oldChainPtr = entryPtr->nextPtr;
1004 bucketPtr = &tablePtr->buckets[index];
1005 entryPtr->nextPtr = *bucketPtr;
1006 *bucketPtr = entryPtr;
1007 }
1008 }
1009
1010 /*
1011 * Free up the old bucket array, if it was dynamically allocated.
1012 */
1013
1014 if (oldBuckets != tablePtr->staticBuckets) {
1015 ckfree(oldBuckets);
1016 }
1017 }
1018
1019 /*
1020 *----------------------------------------------------------------------
1021 *
1022 * TclInvalidateCmdLiteral --
1023 *
1024 * Invalidate a command literal entry, if present in the literal hash
1025 * tables, by resetting its internal representation. This invalidation
1026 * leaves it in the literal tables and in existing literal arrays. As a
1027 * result, existing references continue to work but we force a fresh
1028 * command look-up upon the next use (see, in particular,
1029 * TclSetCmdNameObj()).
1030 *
1031 * Results:
1032 * None.
1033 *
1034 * Side effects:
1035 * Resets the internal representation of the CmdName Tcl_Obj
1036 * using TclFreeIntRep().
1037 *
1038 *----------------------------------------------------------------------
1039 */
1040
1041 void
1042 TclInvalidateCmdLiteral(
1043 Tcl_Interp *interp, /* Interpreter for which to invalidate a
1044 * command literal. */
1045 const char *name, /* Points to the start of the cmd literal
1046 * name. */
1047 Namespace *nsPtr) /* The namespace for which to lookup and
1048 * invalidate a cmd literal. */
1049 {
1050 Interp *iPtr = (Interp *) interp;
1051 Tcl_Obj *literalObjPtr = TclCreateLiteral(iPtr, (char *) name,
1052 strlen(name), -1, NULL, nsPtr, 0, NULL);
1053
1054 if (literalObjPtr != NULL) {
1055 if (literalObjPtr->typePtr == &tclCmdNameType) {
1056 TclFreeIntRep(literalObjPtr);
1057 }
1058 /* Balance the refcount effects of TclCreateLiteral() above */
1059 Tcl_IncrRefCount(literalObjPtr);
1060 TclReleaseLiteral(interp, literalObjPtr);
1061 }
1062 }
1063
1064 #ifdef TCL_COMPILE_STATS
1065 /*
1066 *----------------------------------------------------------------------
1067 *
1068 * TclLiteralStats --
1069 *
1070 * Return statistics describing the layout of the hash table in its hash
1071 * buckets.
1072 *
1073 * Results:
1074 * The return value is a malloc-ed string containing information about
1075 * tablePtr. It is the caller's responsibility to free this string.
1076 *
1077 * Side effects:
1078 * None.
1079 *
1080 *----------------------------------------------------------------------
1081 */
1082
1083 char *
1084 TclLiteralStats(
1085 LiteralTable *tablePtr) /* Table for which to produce stats. */
1086 {
1087 #define NUM_COUNTERS 10
1088 int count[NUM_COUNTERS], overflow, i, j;
1089 double average, tmp;
1090 LiteralEntry *entryPtr;
1091 char *result, *p;
1092
1093 /*
1094 * Compute a histogram of bucket usage. For each bucket chain i, j is the
1095 * number of entries in the chain.
1096 */
1097
1098 for (i=0 ; i<NUM_COUNTERS ; i++) {
1099 count[i] = 0;
1100 }
1101 overflow = 0;
1102 average = 0.0;
1103 for (i=0 ; i<tablePtr->numBuckets ; i++) {
1104 j = 0;
1105 for (entryPtr=tablePtr->buckets[i] ; entryPtr!=NULL;
1106 entryPtr=entryPtr->nextPtr) {
1107 j++;
1108 }
1109 if (j < NUM_COUNTERS) {
1110 count[j]++;
1111 } else {
1112 overflow++;
1113 }
1114 tmp = j;
1115 average += (tmp+1.0)*(tmp/tablePtr->numEntries)/2.0;
1116 }
1117
1118 /*
1119 * Print out the histogram and a few other pieces of information.
1120 */
1121
1122 result = (char *)ckalloc(NUM_COUNTERS*60 + 300);
1123 snprintf(result, 60, "%d entries in table, %d buckets\n",
1124 tablePtr->numEntries, tablePtr->numBuckets);
1125 p = result + strlen(result);
1126 for (i=0 ; i<NUM_COUNTERS ; i++) {
1127 snprintf(p, 60, "number of buckets with %d entries: %d\n",
1128 i, count[i]);
1129 p += strlen(p);
1130 }
1131 snprintf(p, 60, "number of buckets with %d or more entries: %d\n",
1132 NUM_COUNTERS, overflow);
1133 p += strlen(p);
1134 snprintf(p, 60, "average search distance for entry: %.1f", average);
1135 return result;
1136 }
1137 #endif /*TCL_COMPILE_STATS*/
1138
1139 #ifdef TCL_COMPILE_DEBUG
1140 /*
1141 *----------------------------------------------------------------------
1142 *
1143 * TclVerifyLocalLiteralTable --
1144 *
1145 * Check a CompileEnv's local literal table for consistency.
1146 *
1147 * Results:
1148 * None.
1149 *
1150 * Side effects:
1151 * Tcl_Panic if problems are found.
1152 *
1153 *----------------------------------------------------------------------
1154 */
1155
1156 void
1157 TclVerifyLocalLiteralTable(
1158 CompileEnv *envPtr) /* Points to CompileEnv whose literal table is
1159 * to be validated. */
1160 {
1161 LiteralTable *localTablePtr = &envPtr->localLitTable;
1162 LiteralEntry *localPtr;
1163 char *bytes;
1164 int i;
1165 int length, count;
1166
1167 count = 0;
1168 for (i=0 ; i<localTablePtr->numBuckets ; i++) {
1169 for (localPtr=localTablePtr->buckets[i] ; localPtr!=NULL;
1170 localPtr=localPtr->nextPtr) {
1171 count++;
1172 if (localPtr->refCount != -1) {
1173 bytes = TclGetStringFromObj(localPtr->objPtr, &length);
1174 Tcl_Panic("%s: local literal \"%.*s\" had bad refCount %d",
1175 "TclVerifyLocalLiteralTable",
1176 (length>60? 60 : length), bytes, localPtr->refCount);
1177 }
1178 if (localPtr->objPtr->bytes == NULL) {
1179 Tcl_Panic("%s: literal has NULL string rep",
1180 "TclVerifyLocalLiteralTable");
1181 }
1182 }
1183 }
1184 if (count != localTablePtr->numEntries) {
1185 Tcl_Panic("%s: local literal table had %d entries, should be %d",
1186 "TclVerifyLocalLiteralTable", count,
1187 localTablePtr->numEntries);
1188 }
1189 }
1190
1191 /*
1192 *----------------------------------------------------------------------
1193 *
1194 * TclVerifyGlobalLiteralTable --
1195 *
1196 * Check an interpreter's global literal table literal for consistency.
1197 *
1198 * Results:
1199 * None.
1200 *
1201 * Side effects:
1202 * Tcl_Panic if problems are found.
1203 *
1204 *----------------------------------------------------------------------
1205 */
1206
1207 void
1208 TclVerifyGlobalLiteralTable(
1209 Interp *iPtr) /* Points to interpreter whose global literal
1210 * table is to be validated. */
1211 {
1212 LiteralTable *globalTablePtr = &iPtr->literalTable;
1213 LiteralEntry *globalPtr;
1214 char *bytes;
1215 int i;
1216 int length, count;
1217
1218 count = 0;
1219 for (i=0 ; i<globalTablePtr->numBuckets ; i++) {
1220 for (globalPtr=globalTablePtr->buckets[i] ; globalPtr!=NULL;
1221 globalPtr=globalPtr->nextPtr) {
1222 count++;
1223 if (globalPtr->refCount < 1) {
1224 bytes = TclGetStringFromObj(globalPtr->objPtr, &length);
1225 Tcl_Panic("%s: global literal \"%.*s\" had bad refCount %d",
1226 "TclVerifyGlobalLiteralTable",
1227 (length>60? 60 : length), bytes, globalPtr->refCount);
1228 }
1229 if (globalPtr->objPtr->bytes == NULL) {
1230 Tcl_Panic("%s: literal has NULL string rep",
1231 "TclVerifyGlobalLiteralTable");
1232 }
1233 }
1234 }
1235 if (count != globalTablePtr->numEntries) {
1236 Tcl_Panic("%s: global literal table had %d entries, should be %d",
1237 "TclVerifyGlobalLiteralTable", count,
1238 globalTablePtr->numEntries);
1239 }
1240 }
1241 #endif /*TCL_COMPILE_DEBUG*/
1242
1243 /*
1244 * Local Variables:
1245 * mode: c
1246 * c-basic-offset: 4
1247 * fill-column: 78
1248 * End:
1249 */