forked from msteveb/jimtcl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jim.c
15247 lines (13449 loc) · 460 KB
/
jim.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Jim - A small embeddable Tcl interpreter
*
* Copyright 2005 Salvatore Sanfilippo <antirez@invece.org>
* Copyright 2005 Clemens Hintze <c.hintze@gmx.net>
* Copyright 2005 patthoyts - Pat Thoyts <patthoyts@users.sf.net>
* Copyright 2008,2009 oharboe - Øyvind Harboe - oyvind.harboe@zylin.com
* Copyright 2008 Andrew Lunn <andrew@lunn.ch>
* Copyright 2008 Duane Ellis <openocd@duaneellis.com>
* Copyright 2008 Uwe Klein <uklein@klein-messgeraete.de>
* Copyright 2008 Steve Bennett <steveb@workware.net.au>
* Copyright 2009 Nico Coesel <ncoesel@dealogic.nl>
* Copyright 2009 Zachary T Welch zw@superlucidity.net
* Copyright 2009 David Brownell
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE JIM TCL PROJECT ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* JIM TCL PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation
* are those of the authors and should not be interpreted as representing
* official policies, either expressed or implied, of the Jim Tcl Project.
**/
#define JIM_OPTIMIZATION /* comment to avoid optimizations and reduce size */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <ctype.h>
#include <limits.h>
#include <assert.h>
#include <errno.h>
#include <time.h>
#include <setjmp.h>
#include "jim.h"
#include "jimautoconf.h"
#include "utf8.h"
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_BACKTRACE
#include <execinfo.h>
#endif
#ifdef HAVE_CRT_EXTERNS_H
#include <crt_externs.h>
#endif
/* For INFINITY, even if math functions are not enabled */
#include <math.h>
/* We may decide to switch to using $[...] after all, so leave it as an option */
/*#define EXPRSUGAR_BRACKET*/
/* For the no-autoconf case */
#ifndef TCL_LIBRARY
#define TCL_LIBRARY "."
#endif
#ifndef TCL_PLATFORM_OS
#define TCL_PLATFORM_OS "unknown"
#endif
#ifndef TCL_PLATFORM_PLATFORM
#define TCL_PLATFORM_PLATFORM "unknown"
#endif
#ifndef TCL_PLATFORM_PATH_SEPARATOR
#define TCL_PLATFORM_PATH_SEPARATOR ":"
#endif
/*#define DEBUG_SHOW_SCRIPT*/
/*#define DEBUG_SHOW_SCRIPT_TOKENS*/
/*#define DEBUG_SHOW_SUBST*/
/*#define DEBUG_SHOW_EXPR*/
/*#define DEBUG_SHOW_EXPR_TOKENS*/
/*#define JIM_DEBUG_GC*/
#ifdef JIM_MAINTAINER
#define JIM_DEBUG_COMMAND
#define JIM_DEBUG_PANIC
#endif
/* Enable this (in conjunction with valgrind) to help debug
* reference counting issues
*/
/*#define JIM_DISABLE_OBJECT_POOL*/
/* Maximum size of an integer */
#define JIM_INTEGER_SPACE 24
const char *jim_tt_name(int type);
#ifdef JIM_DEBUG_PANIC
static void JimPanicDump(int panic_condition, const char *fmt, ...);
#define JimPanic(X) JimPanicDump X
#else
#define JimPanic(X)
#endif
/* -----------------------------------------------------------------------------
* Global variables
* ---------------------------------------------------------------------------*/
/* A shared empty string for the objects string representation.
* Jim_InvalidateStringRep knows about it and doesn't try to free it. */
static char JimEmptyStringRep[] = "";
/* -----------------------------------------------------------------------------
* Required prototypes of not exported functions
* ---------------------------------------------------------------------------*/
static void JimChangeCallFrameId(Jim_Interp *interp, Jim_CallFrame *cf);
static void JimFreeCallFrame(Jim_Interp *interp, Jim_CallFrame *cf, int flags);
static int ListSetIndex(Jim_Interp *interp, Jim_Obj *listPtr, int listindex, Jim_Obj *newObjPtr,
int flags);
static int JimDeleteLocalProcs(Jim_Interp *interp, Jim_Stack *localCommands);
static Jim_Obj *JimExpandDictSugar(Jim_Interp *interp, Jim_Obj *objPtr);
static void SetDictSubstFromAny(Jim_Interp *interp, Jim_Obj *objPtr);
static Jim_Obj **JimDictPairs(Jim_Obj *dictPtr, int *len);
static void JimSetFailedEnumResult(Jim_Interp *interp, const char *arg, const char *badtype,
const char *prefix, const char *const *tablePtr, const char *name);
static int JimCallProcedure(Jim_Interp *interp, Jim_Cmd *cmd, int argc, Jim_Obj *const *argv);
static int JimGetWideNoErr(Jim_Interp *interp, Jim_Obj *objPtr, jim_wide * widePtr);
static int JimSign(jim_wide w);
static int JimValidName(Jim_Interp *interp, const char *type, Jim_Obj *nameObjPtr);
static void JimPrngSeed(Jim_Interp *interp, unsigned char *seed, int seedLen);
static void JimRandomBytes(Jim_Interp *interp, void *dest, unsigned int len);
/* Fast access to the int (wide) value of an object which is known to be of int type */
#define JimWideValue(objPtr) (objPtr)->internalRep.wideValue
#define JimObjTypeName(O) ((O)->typePtr ? (O)->typePtr->name : "none")
static int utf8_tounicode_case(const char *s, int *uc, int upper)
{
int l = utf8_tounicode(s, uc);
if (upper) {
*uc = utf8_upper(*uc);
}
return l;
}
/* These can be used in addition to JIM_CASESENS/JIM_NOCASE */
#define JIM_CHARSET_SCAN 2
#define JIM_CHARSET_GLOB 0
/**
* pattern points to a string like "[^a-z\ub5]"
*
* The pattern may contain trailing chars, which are ignored.
*
* The pattern is matched against unicode char 'c'.
*
* If (flags & JIM_NOCASE), case is ignored when matching.
* If (flags & JIM_CHARSET_SCAN), the considers ^ and ] special at the start
* of the charset, per scan, rather than glob/string match.
*
* If the unicode char 'c' matches that set, returns a pointer to the ']' character,
* or the null character if the ']' is missing.
*
* Returns NULL on no match.
*/
static const char *JimCharsetMatch(const char *pattern, int c, int flags)
{
int not = 0;
int pchar;
int match = 0;
int nocase = 0;
if (flags & JIM_NOCASE) {
nocase++;
c = utf8_upper(c);
}
if (flags & JIM_CHARSET_SCAN) {
if (*pattern == '^') {
not++;
pattern++;
}
/* Special case. If the first char is ']', it is part of the set */
if (*pattern == ']') {
goto first;
}
}
while (*pattern && *pattern != ']') {
/* Exact match */
if (pattern[0] == '\\') {
first:
pattern += utf8_tounicode_case(pattern, &pchar, nocase);
}
else {
/* Is this a range? a-z */
int start;
int end;
pattern += utf8_tounicode_case(pattern, &start, nocase);
if (pattern[0] == '-' && pattern[1]) {
/* skip '-' */
pattern += utf8_tounicode(pattern, &pchar);
pattern += utf8_tounicode_case(pattern, &end, nocase);
/* Handle reversed range too */
if ((c >= start && c <= end) || (c >= end && c <= start)) {
match = 1;
}
continue;
}
pchar = start;
}
if (pchar == c) {
match = 1;
}
}
if (not) {
match = !match;
}
return match ? pattern : NULL;
}
/* Glob-style pattern matching. */
/* Note: string *must* be valid UTF-8 sequences
*/
static int JimGlobMatch(const char *pattern, const char *string, int nocase)
{
int c;
int pchar;
while (*pattern) {
switch (pattern[0]) {
case '*':
while (pattern[1] == '*') {
pattern++;
}
pattern++;
if (!pattern[0]) {
return 1; /* match */
}
while (*string) {
/* Recursive call - Does the remaining pattern match anywhere? */
if (JimGlobMatch(pattern, string, nocase))
return 1; /* match */
string += utf8_tounicode(string, &c);
}
return 0; /* no match */
case '?':
string += utf8_tounicode(string, &c);
break;
case '[': {
string += utf8_tounicode(string, &c);
pattern = JimCharsetMatch(pattern + 1, c, nocase ? JIM_NOCASE : 0);
if (!pattern) {
return 0;
}
if (!*pattern) {
/* Ran out of pattern (no ']') */
continue;
}
break;
}
case '\\':
if (pattern[1]) {
pattern++;
}
/* fall through */
default:
string += utf8_tounicode_case(string, &c, nocase);
utf8_tounicode_case(pattern, &pchar, nocase);
if (pchar != c) {
return 0;
}
break;
}
pattern += utf8_tounicode_case(pattern, &pchar, nocase);
if (!*string) {
while (*pattern == '*') {
pattern++;
}
break;
}
}
if (!*pattern && !*string) {
return 1;
}
return 0;
}
/**
* string comparison works on binary data.
*
* Note that the lengths are byte lengths, not char lengths.
*/
static int JimStringCompare(const char *s1, int l1, const char *s2, int l2)
{
if (l1 < l2) {
return memcmp(s1, s2, l1) <= 0 ? -1 : 1;
}
else if (l2 < l1) {
return memcmp(s1, s2, l2) >= 0 ? 1 : -1;
}
else {
return JimSign(memcmp(s1, s2, l1));
}
}
/**
* Compare null terminated strings, up to a maximum of 'maxchars' characters,
* (or end of string if 'maxchars' is -1).
*
* Returns -1, 0, 1 for s1 < s2, s1 == s2, s1 > s2 respectively.
*/
static int JimStringCompareLen(const char *s1, const char *s2, int maxchars, int nocase)
{
while (*s1 && *s2 && maxchars) {
int c1, c2;
s1 += utf8_tounicode_case(s1, &c1, nocase);
s2 += utf8_tounicode_case(s2, &c2, nocase);
if (c1 != c2) {
return JimSign(c1 - c2);
}
maxchars--;
}
if (!maxchars) {
return 0;
}
/* One string or both terminated */
if (*s1) {
return 1;
}
if (*s2) {
return -1;
}
return 0;
}
/* Search 's1' inside 's2', starting to search from char 'index' of 's2'.
* The index of the first occurrence of s1 in s2 is returned.
* If s1 is not found inside s2, -1 is returned. */
static int JimStringFirst(const char *s1, int l1, const char *s2, int l2, int idx)
{
int i;
int l1bytelen;
if (!l1 || !l2 || l1 > l2) {
return -1;
}
if (idx < 0)
idx = 0;
s2 += utf8_index(s2, idx);
l1bytelen = utf8_index(s1, l1);
for (i = idx; i <= l2 - l1; i++) {
int c;
if (memcmp(s2, s1, l1bytelen) == 0) {
return i;
}
s2 += utf8_tounicode(s2, &c);
}
return -1;
}
/**
* Note: Lengths and return value are in bytes, not chars.
*/
static int JimStringLast(const char *s1, int l1, const char *s2, int l2)
{
const char *p;
if (!l1 || !l2 || l1 > l2)
return -1;
/* Now search for the needle */
for (p = s2 + l2 - 1; p != s2 - 1; p--) {
if (*p == *s1 && memcmp(s1, p, l1) == 0) {
return p - s2;
}
}
return -1;
}
#ifdef JIM_UTF8
/**
* Note: Lengths and return value are in chars.
*/
static int JimStringLastUtf8(const char *s1, int l1, const char *s2, int l2)
{
int n = JimStringLast(s1, utf8_index(s1, l1), s2, utf8_index(s2, l2));
if (n > 0) {
n = utf8_strlen(s2, n);
}
return n;
}
#endif
static int JimWideToString(char *buf, jim_wide wideValue)
{
int pos = 0;
if (wideValue == 0) {
buf[pos++] = '0';
}
else {
char tmp[JIM_INTEGER_SPACE];
int num = 0;
int i;
if (wideValue < 0) {
buf[pos++] = '-';
/* -106 % 10 may be -6 or 4! */
i = wideValue % 10;
tmp[num++] = (i > 0) ? (10 - i) : -i;
wideValue /= -10;
}
while (wideValue) {
tmp[num++] = wideValue % 10;
wideValue /= 10;
}
for (i = 0; i < num; i++) {
buf[pos++] = '0' + tmp[num - i - 1];
}
}
buf[pos] = 0;
return pos;
}
/**
* After an strtol()/strtod()-like conversion,
* check whether something was converted and that
* the only thing left is white space.
*
* Returns JIM_OK or JIM_ERR.
*/
static int JimCheckConversion(const char *str, const char *endptr)
{
if (str[0] == '\0' || str == endptr) {
return JIM_ERR;
}
if (endptr[0] != '\0') {
while (*endptr) {
if (!isspace(UCHAR(*endptr))) {
return JIM_ERR;
}
endptr++;
}
}
return JIM_OK;
}
/* Parses the front of a number to determine it's sign and base
* Returns the index to start parsing according to the given base
*/
static int JimNumberBase(const char *str, int *base, int *sign)
{
int i = 0;
*base = 10;
while (isspace(UCHAR(str[i]))) {
i++;
}
if (str[i] == '-') {
*sign = -1;
i++;
}
else {
if (str[i] == '+') {
i++;
}
*sign = 1;
}
if (str[i] != '0') {
/* base 10 */
return 0;
}
/* We have 0<x>, so see if we can convert it */
switch (str[i + 1]) {
case 'x': case 'X': *base = 16; break;
case 'o': case 'O': *base = 8; break;
case 'b': case 'B': *base = 2; break;
default: return 0;
}
i += 2;
/* Ensure that (e.g.) 0x-5 fails to parse */
if (str[i] != '-' && str[i] != '+' && !isspace(UCHAR(str[i]))) {
/* Parse according to this base */
return i;
}
/* Parse as base 10 */
*base = 10;
return 0;
}
/* Converts a number as per strtol(..., 0) except leading zeros do *not*
* imply octal. Instead, decimal is assumed unless the number begins with 0x, 0o or 0b
*/
static long jim_strtol(const char *str, char **endptr)
{
int sign;
int base;
int i = JimNumberBase(str, &base, &sign);
if (base != 10) {
long value = strtol(str + i, endptr, base);
if (endptr == NULL || *endptr != str + i) {
return value * sign;
}
}
/* Can just do a regular base-10 conversion */
return strtol(str, endptr, 10);
}
/* Converts a number as per strtoull(..., 0) except leading zeros do *not*
* imply octal. Instead, decimal is assumed unless the number begins with 0x, 0o or 0b
*/
static jim_wide jim_strtoull(const char *str, char **endptr)
{
#ifdef HAVE_LONG_LONG
int sign;
int base;
int i = JimNumberBase(str, &base, &sign);
if (base != 10) {
jim_wide value = strtoull(str + i, endptr, base);
if (endptr == NULL || *endptr != str + i) {
return value * sign;
}
}
/* Can just do a regular base-10 conversion */
return strtoull(str, endptr, 10);
#else
return (unsigned long)jim_strtol(str, endptr);
#endif
}
int Jim_StringToWide(const char *str, jim_wide * widePtr, int base)
{
char *endptr;
if (base) {
*widePtr = strtoull(str, &endptr, base);
}
else {
*widePtr = jim_strtoull(str, &endptr);
}
return JimCheckConversion(str, endptr);
}
int Jim_DoubleToString(char *buf, double doubleValue)
{
int len;
int i;
len = sprintf(buf, "%.12g", doubleValue);
/* Add a final ".0" if necessary */
for (i = 0; i < len; i++) {
if (buf[i] == '.' || buf[i] == 'e') {
#if defined(JIM_SPRINTF_DOUBLE_NEEDS_FIX)
/* If 'buf' ends in e-0nn or e+0nn, remove
* the 0 after the + or - and reduce the length by 1
*/
char *e = strchr(buf, 'e');
if (e && (e[1] == '-' || e[1] == '+') && e[2] == '0') {
/* Move it up */
e += 2;
memmove(e, e + 1, len - (e - buf));
return len - 1;
}
#endif
return len;
}
/* inf or Infinity -> Inf, nan -> NaN */
if (buf[i] == 'i' || buf[i] == 'I' || buf[i] == 'n' || buf[i] == 'N') {
buf[i] = toupper(UCHAR(buf[i]));
if (buf[i] == 'n' || buf[i] == 'N')
buf[i+2] = toupper(UCHAR(buf[i+2]));
buf[i + 3] = 0;
return i + 3;
}
}
buf[i++] = '.';
buf[i++] = '0';
buf[i] = '\0';
return i;
}
int Jim_StringToDouble(const char *str, double *doublePtr)
{
char *endptr;
/* Callers can check for underflow via ERANGE */
errno = 0;
*doublePtr = strtod(str, &endptr);
return JimCheckConversion(str, endptr);
}
static jim_wide JimPowWide(jim_wide b, jim_wide e)
{
jim_wide i, res = 1;
if ((b == 0 && e != 0) || (e < 0))
return 0;
for (i = 0; i < e; i++) {
res *= b;
}
return res;
}
/* -----------------------------------------------------------------------------
* Special functions
* ---------------------------------------------------------------------------*/
#ifdef JIM_DEBUG_PANIC
void JimPanicDump(int condition, const char *fmt, ...)
{
va_list ap;
if (!condition) {
return;
}
va_start(ap, fmt);
fprintf(stderr, JIM_NL "JIM INTERPRETER PANIC: ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, JIM_NL JIM_NL);
va_end(ap);
#ifdef HAVE_BACKTRACE
{
void *array[40];
int size, i;
char **strings;
size = backtrace(array, 40);
strings = backtrace_symbols(array, size);
for (i = 0; i < size; i++)
fprintf(stderr, "[backtrace] %s" JIM_NL, strings[i]);
fprintf(stderr, "[backtrace] Include the above lines and the output" JIM_NL);
fprintf(stderr, "[backtrace] of 'nm <executable>' in the bug report." JIM_NL);
}
#endif
exit(1);
}
#endif
/* -----------------------------------------------------------------------------
* Memory allocation
* ---------------------------------------------------------------------------*/
void *Jim_Alloc(int size)
{
return size ? malloc(size) : NULL;
}
void Jim_Free(void *ptr)
{
free(ptr);
}
void *Jim_Realloc(void *ptr, int size)
{
return realloc(ptr, size);
}
char *Jim_StrDup(const char *s)
{
return strdup(s);
}
char *Jim_StrDupLen(const char *s, int l)
{
char *copy = Jim_Alloc(l + 1);
memcpy(copy, s, l + 1);
copy[l] = 0; /* Just to be sure, original could be substring */
return copy;
}
/* -----------------------------------------------------------------------------
* Time related functions
* ---------------------------------------------------------------------------*/
/* Returns microseconds of CPU used since start. */
static jim_wide JimClock(void)
{
struct timeval tv;
gettimeofday(&tv, NULL);
return (jim_wide) tv.tv_sec * 1000000 + tv.tv_usec;
}
/* -----------------------------------------------------------------------------
* Hash Tables
* ---------------------------------------------------------------------------*/
/* -------------------------- private prototypes ---------------------------- */
static void JimExpandHashTableIfNeeded(Jim_HashTable *ht);
static unsigned int JimHashTableNextPower(unsigned int size);
static Jim_HashEntry *JimInsertHashEntry(Jim_HashTable *ht, const void *key, int replace);
/* -------------------------- hash functions -------------------------------- */
/* Thomas Wang's 32 bit Mix Function */
unsigned int Jim_IntHashFunction(unsigned int key)
{
key += ~(key << 15);
key ^= (key >> 10);
key += (key << 3);
key ^= (key >> 6);
key += ~(key << 11);
key ^= (key >> 16);
return key;
}
/* Generic hash function (we are using to multiply by 9 and add the byte
* as Tcl) */
unsigned int Jim_GenHashFunction(const unsigned char *buf, int len)
{
unsigned int h = 0;
while (len--)
h += (h << 3) + *buf++;
return h;
}
/* ----------------------------- API implementation ------------------------- */
/* reset a hashtable already initialized with ht_init().
* NOTE: This function should only called by ht_destroy(). */
static void JimResetHashTable(Jim_HashTable *ht)
{
ht->table = NULL;
ht->size = 0;
ht->sizemask = 0;
ht->used = 0;
ht->collisions = 0;
}
static void JimInitHashTableIterator(Jim_HashTable *ht, Jim_HashTableIterator *iter)
{
iter->ht = ht;
iter->index = -1;
iter->entry = NULL;
iter->nextEntry = NULL;
}
/* Initialize the hash table */
int Jim_InitHashTable(Jim_HashTable *ht, const Jim_HashTableType *type, void *privDataPtr)
{
JimResetHashTable(ht);
ht->type = type;
ht->privdata = privDataPtr;
return JIM_OK;
}
/* Resize the table to the minimal size that contains all the elements,
* but with the invariant of a USER/BUCKETS ration near to <= 1 */
void Jim_ResizeHashTable(Jim_HashTable *ht)
{
int minimal = ht->used;
if (minimal < JIM_HT_INITIAL_SIZE)
minimal = JIM_HT_INITIAL_SIZE;
Jim_ExpandHashTable(ht, minimal);
}
/* Expand or create the hashtable */
void Jim_ExpandHashTable(Jim_HashTable *ht, unsigned int size)
{
Jim_HashTable n; /* the new hashtable */
unsigned int realsize = JimHashTableNextPower(size), i;
/* the size is invalid if it is smaller than the number of
* elements already inside the hashtable */
if (size <= ht->used)
return;
Jim_InitHashTable(&n, ht->type, ht->privdata);
n.size = realsize;
n.sizemask = realsize - 1;
n.table = Jim_Alloc(realsize * sizeof(Jim_HashEntry *));
/* Initialize all the pointers to NULL */
memset(n.table, 0, realsize * sizeof(Jim_HashEntry *));
/* Copy all the elements from the old to the new table:
* note that if the old hash table is empty ht->used is zero,
* so Jim_ExpandHashTable just creates an empty hash table. */
n.used = ht->used;
for (i = 0; ht->used > 0; i++) {
Jim_HashEntry *he, *nextHe;
if (ht->table[i] == NULL)
continue;
/* For each hash entry on this slot... */
he = ht->table[i];
while (he) {
unsigned int h;
nextHe = he->next;
/* Get the new element index */
h = Jim_HashKey(ht, he->key) & n.sizemask;
he->next = n.table[h];
n.table[h] = he;
ht->used--;
/* Pass to the next element */
he = nextHe;
}
}
assert(ht->used == 0);
Jim_Free(ht->table);
/* Remap the new hashtable in the old */
*ht = n;
}
/* Add an element to the target hash table */
int Jim_AddHashEntry(Jim_HashTable *ht, const void *key, void *val)
{
Jim_HashEntry *entry;
/* Get the index of the new element, or -1 if
* the element already exists. */
entry = JimInsertHashEntry(ht, key, 0);
if (entry == NULL)
return JIM_ERR;
/* Set the hash entry fields. */
Jim_SetHashKey(ht, entry, key);
Jim_SetHashVal(ht, entry, val);
return JIM_OK;
}
/* Add an element, discarding the old if the key already exists */
int Jim_ReplaceHashEntry(Jim_HashTable *ht, const void *key, void *val)
{
int existed;
Jim_HashEntry *entry;
/* Get the index of the new element, or -1 if
* the element already exists. */
entry = JimInsertHashEntry(ht, key, 1);
if (entry->key) {
/* It already exists, so replace the value */
Jim_FreeEntryVal(ht, entry);
existed = 1;
}
else {
/* Doesn't exist, so set the key */
Jim_SetHashKey(ht, entry, key);
existed = 0;
}
Jim_SetHashVal(ht, entry, val);
return existed;
}
/* Search and remove an element */
int Jim_DeleteHashEntry(Jim_HashTable *ht, const void *key)
{
unsigned int h;
Jim_HashEntry *he, *prevHe;
if (ht->used == 0)
return JIM_ERR;
h = Jim_HashKey(ht, key) & ht->sizemask;
he = ht->table[h];
prevHe = NULL;
while (he) {
if (Jim_CompareHashKeys(ht, key, he->key)) {
/* Unlink the element from the list */
if (prevHe)
prevHe->next = he->next;
else
ht->table[h] = he->next;
Jim_FreeEntryKey(ht, he);
Jim_FreeEntryVal(ht, he);
Jim_Free(he);
ht->used--;
return JIM_OK;
}
prevHe = he;
he = he->next;
}
return JIM_ERR; /* not found */
}
/* Destroy an entire hash table */
int Jim_FreeHashTable(Jim_HashTable *ht)
{
unsigned int i;
/* Free all the elements */
for (i = 0; ht->used > 0; i++) {
Jim_HashEntry *he, *nextHe;
if ((he = ht->table[i]) == NULL)
continue;
while (he) {
nextHe = he->next;
Jim_FreeEntryKey(ht, he);
Jim_FreeEntryVal(ht, he);
Jim_Free(he);
ht->used--;
he = nextHe;
}
}
/* Free the table and the allocated cache structure */
Jim_Free(ht->table);
/* Re-initialize the table */
JimResetHashTable(ht);
return JIM_OK; /* never fails */
}
Jim_HashEntry *Jim_FindHashEntry(Jim_HashTable *ht, const void *key)
{
Jim_HashEntry *he;
unsigned int h;
if (ht->used == 0)
return NULL;
h = Jim_HashKey(ht, key) & ht->sizemask;
he = ht->table[h];
while (he) {
if (Jim_CompareHashKeys(ht, key, he->key))
return he;
he = he->next;
}
return NULL;
}
Jim_HashTableIterator *Jim_GetHashTableIterator(Jim_HashTable *ht)
{
Jim_HashTableIterator *iter = Jim_Alloc(sizeof(*iter));
JimInitHashTableIterator(ht, iter);
return iter;
}
Jim_HashEntry *Jim_NextHashEntry(Jim_HashTableIterator *iter)
{
while (1) {
if (iter->entry == NULL) {
iter->index++;
if (iter->index >= (signed)iter->ht->size)
break;
iter->entry = iter->ht->table[iter->index];
}
else {
iter->entry = iter->nextEntry;
}
if (iter->entry) {
/* We need to save the 'next' here, the iterator user
* may delete the entry we are returning. */
iter->nextEntry = iter->entry->next;
return iter->entry;
}
}