-
Notifications
You must be signed in to change notification settings - Fork 123
/
jim.c
16852 lines (14974 loc) · 515 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.
**/
#ifndef JIM_TINY
#define JIM_OPTIMIZATION /* comment to avoid optimizations and reduce size */
#endif
#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 "jim-subcmd.h"
#include "utf8.h"
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_EXECINFO_H
#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
#if defined(DEBUG_SHOW_SCRIPT) || defined(DEBUG_SHOW_SCRIPT_TOKENS) || defined(JIM_DEBUG_COMMAND) || defined(DEBUG_SHOW_SUBST)
static const char *jim_tt_name(int type);
#endif
#ifdef JIM_DEBUG_PANIC
static void JimPanicDump(int fail_condition, const char *fmt, ...);
#define JimPanic(X) JimPanicDump X
#else
#define JimPanic(X)
#endif
#ifdef JIM_OPTIMIZATION
static int JimIsWide(Jim_Obj *objPtr);
#define JIM_IF_OPTIM(X) X
#else
#define JIM_IF_OPTIM(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 JimFreeCallFrame(Jim_Interp *interp, Jim_CallFrame *cf, int action);
static int ListSetIndex(Jim_Interp *interp, Jim_Obj *listPtr, int listindex, Jim_Obj *newObjPtr,
int flags);
static int Jim_ListIndices(Jim_Interp *interp, Jim_Obj *listPtr, Jim_Obj *const *indexv, int indexc,
Jim_Obj **resultObj, 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 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 void JimPrngSeed(Jim_Interp *interp, unsigned char *seed, int seedLen);
static void JimRandomBytes(Jim_Interp *interp, void *dest, unsigned int len);
static int JimSetNewVariable(Jim_HashTable *ht, Jim_Obj *nameObjPtr, Jim_VarVal *vv);
static Jim_VarVal *JimFindVariable(Jim_HashTable *ht, Jim_Obj *nameObjPtr);
static int SetVariableFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
#define JIM_DICT_SUGAR 100 /* Only returned by SetVariableFromAny() */
/* 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;
}
/* A common pattern is to save an object from interp and set a new
* value, and then restore the original. Use this pattern:
*
* Jim_Obj *saveObj = JimPushInterpObj(interp->obj, newobj);
* JimPopInterpObj(interp, interp->obj, saveObj);
*/
static Jim_Obj *JimPushInterpObjImpl(Jim_Obj **iop, Jim_Obj *no)
{
Jim_Obj *io = *iop;
Jim_IncrRefCount(no);
*iop = no;
return io;
}
#define JimPushInterpObj(IO, NO) JimPushInterpObjImpl(&(IO), NO)
#define JimPopInterpObj(I, IO, SO) do { Jim_DecrRefCount(I, IO); IO = SO; } while (0)
/* 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 plen, int c, int flags)
{
int not = 0;
int pchar;
int match = 0;
int nocase = 0;
int n;
if (flags & JIM_NOCASE) {
nocase++;
c = utf8_upper(c);
}
if (flags & JIM_CHARSET_SCAN) {
if (*pattern == '^') {
not++;
pattern++;
plen--;
}
/* Special case. If the first char is ']', it is part of the set */
if (*pattern == ']') {
goto first;
}
}
while (plen && *pattern != ']') {
/* Exact match */
if (pattern[0] == '\\') {
first:
n = utf8_tounicode_case(pattern, &pchar, nocase);
pattern += n;
plen -= n;
}
else {
/* Is this a range? a-z */
int start;
int end;
n = utf8_tounicode_case(pattern, &start, nocase);
pattern += n;
plen -= n;
if (pattern[0] == '-' && plen > 1) {
/* skip '-' */
n = 1 + utf8_tounicode_case(pattern + 1, &end, nocase);
pattern += n;
plen -= n;
/* 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, int plen, const char *string, int slen, int nocase)
{
int c;
int pchar;
int n;
const char *p;
while (plen) {
switch (pattern[0]) {
case '*':
while (pattern[1] == '*' && plen) {
pattern++;
plen--;
}
pattern++;
plen--;
if (!plen) {
return 1; /* match */
}
while (slen) {
/* Recursive call - Does the remaining pattern match anywhere? */
if (JimGlobMatch(pattern, plen, string, slen, nocase))
return 1; /* match */
n = utf8_tounicode(string, &c);
string += n;
slen -= n;
}
return 0; /* no match */
case '?':
n = utf8_tounicode(string, &c);
string += n;
slen -= n;
break;
case '[': {
n = utf8_tounicode(string, &c);
string += n;
slen -= n;
p = JimCharsetMatch(pattern + 1, plen - 1, c, nocase ? JIM_NOCASE : 0);
if (!p) {
return 0;
}
plen -= p - pattern;
pattern = p;
if (!plen) {
/* Ran out of pattern (no ']') */
continue;
}
break;
}
case '\\':
if (pattern[1]) {
pattern++;
plen--;
}
/* fall through */
default:
n = utf8_tounicode_case(string, &c, nocase);
string += n;
slen -= n;
utf8_tounicode_case(pattern, &pchar, nocase);
if (pchar != c) {
return 0;
}
break;
}
n = utf8_tounicode_case(pattern, &pchar, nocase);
pattern += n;
plen -= n;
if (!slen) {
while (*pattern == '*' && plen) {
pattern++;
plen--;
}
break;
}
}
if (!plen && !slen) {
return 1;
}
return 0;
}
/**
* utf-8 string comparison. case-insensitive if nocase is set.
*
* Returns -1, 0 or 1
*
* Note that the lengths are character lengths, not byte lengths.
*/
static int JimStringCompareUtf8(const char *s1, int l1, const char *s2, int l2, int nocase)
{
int minlen = l1;
if (l2 < l1) {
minlen = l2;
}
while (minlen) {
int c1, c2;
s1 += utf8_tounicode_case(s1, &c1, nocase);
s2 += utf8_tounicode_case(s2, &c2, nocase);
if (c1 != c2) {
return JimSign(c1 - c2);
}
minlen--;
}
/* Equal to this point, so the shorter string is less */
if (l1 < l2) {
return -1;
}
if (l1 > l2) {
return 1;
}
return 0;
}
/* Search for '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.
*
* Note: Lengths and return value are in bytes, not chars.
*/
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;
}
/* Search for the last occurrence 's1' inside 's2', starting to search from char 'index' of 's2'.
* The index of the last occurrence of s1 in s2 is returned.
* If s1 is not found inside s2, -1 is returned.
*
* 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
/**
* Per JimStringLast but lengths and return value are in chars, not bytes.
*/
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
/**
* 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 its sign and base.
* Returns the index to start parsing according to the given base.
* Sets *base to zero if *str contains no indicator of its base and
* to the base (2, 8, 10 or 16) otherwise.
*/
static int JimNumberBase(const char *str, int *base, int *sign)
{
int i = 0;
*base = 0;
while (isspace(UCHAR(str[i]))) {
i++;
}
if (str[i] == '-') {
*sign = -1;
i++;
}
else {
if (str[i] == '+') {
i++;
}
*sign = 1;
}
if (str[i] != '0') {
/* no base indicator */
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;
case 'd': case 'D': *base = 10; 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 default */
*base = 0;
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 != 0) {
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 != 0) {
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_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 res = 1;
/* Special cases */
if (b == 1) {
/* 1 ^ any = 1 */
return 1;
}
if (e < 0) {
if (b != -1) {
return 0;
}
/* Only special case is -1 ^ -n
* -1^-1 = -1
* -1^-2 = 1
* i.e. same as +ve n
*/
e = -e;
}
while (e)
{
if (e & 1) {
res *= b;
}
e >>= 1;
b *= b;
}
return res;
}
/* -----------------------------------------------------------------------------
* Special functions
* ---------------------------------------------------------------------------*/
#ifdef JIM_DEBUG_PANIC
static void JimPanicDump(int condition, const char *fmt, ...)
{
va_list ap;
if (!condition) {
return;
}
va_start(ap, fmt);
fprintf(stderr, "\nJIM INTERPRETER PANIC: ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n\n");
va_end(ap);
#if defined(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\n", strings[i]);
fprintf(stderr, "[backtrace] Include the above lines and the output\n");
fprintf(stderr, "[backtrace] of 'nm <executable>' in the bug report.\n");
}
#endif
exit(1);
}
#endif
/* -----------------------------------------------------------------------------
* Memory allocation
* ---------------------------------------------------------------------------*/
void *JimDefaultAllocator(void *ptr, size_t size)
{
if (size == 0) {
free(ptr);
return NULL;
}
else if (ptr) {
return realloc(ptr, size);
}
else {
return malloc(size);
}
}
void *(*Jim_Allocator)(void *ptr, size_t size) = JimDefaultAllocator;
char *Jim_StrDup(const char *s)
{
return Jim_StrDupLen(s, strlen(s));
}
char *Jim_StrDupLen(const char *s, int l)
{
char *copy = Jim_Alloc(l + 1);
memcpy(copy, s, l);
copy[l] = 0; /* NULL terminate */
return copy;
}
/* -----------------------------------------------------------------------------
* Time related functions
* ---------------------------------------------------------------------------*/
/* Returns current time in microseconds
* CLOCK_MONOTONIC (monotonic clock that is affected by time adjustments)
* CLOCK_MONOTONIC_RAW (monotonic clock that is not affected by time adjustments)
* CLOCK_REALTIME (wall time)
*/
jim_wide Jim_GetTimeUsec(unsigned type)
{
long long now;
struct timeval tv;
#if defined(HAVE_CLOCK_GETTIME)
struct timespec ts;
if (clock_gettime(type, &ts) == 0) {
now = ts.tv_sec * 1000000LL + ts.tv_nsec / 1000;
}
else
#endif
{
gettimeofday(&tv, NULL);
now = tv.tv_sec * 1000000LL + tv.tv_usec;
}
return now;
}
/* -----------------------------------------------------------------------------
* 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 string hash function */
unsigned int Jim_GenHashFunction(const unsigned char *string, int length)
{
unsigned result = 0;
string += length;
while (length--) {
result += (result << 3) + (unsigned char)(*--string);
}
return result;
}
/* ----------------------------- API implementation ------------------------- */
/*
* Reset a hashtable already initialized.
* The table data should already have been freed.
*
* Note that type and privdata are not initialised
* to allow the now-empty hashtable to be reused
*/
static void JimResetHashTable(Jim_HashTable *ht)
{
ht->table = NULL;
ht->size = 0;
ht->sizemask = 0;
ht->used = 0;
ht->collisions = 0;
#ifdef JIM_RANDOMISE_HASH
/* This is initialised to a random value to avoid a hash collision attack.
* See: n.runs-SA-2011.004
*/
ht->uniq = (rand() ^ time(NULL) ^ clock());
#else
ht->uniq = 0;
#endif
}
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;
}
/* 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 *));
/* Keep the same 'uniq' as the original */
n.uniq = ht->uniq;
/* 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
* Returns JIM_ERR if the entry already exists
*/
int Jim_AddHashEntry(Jim_HashTable *ht, const void *key, void *val)
{
Jim_HashEntry *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 only replace the value.
* Note if both a destructor and a duplicate function exist,
* need to dup before destroy. perhaps they are the same
* reference counted object
*/
if (ht->type->valDestructor && ht->type->valDup) {
void *newval = ht->type->valDup(ht->privdata, val);
ht->type->valDestructor(ht->privdata, entry->u.val);
entry->u.val = newval;
}
else {
Jim_FreeEntryVal(ht, entry);
Jim_SetHashVal(ht, entry, val);
}
existed = 1;
}
else {
/* Doesn't exist, so set the key */
Jim_SetHashKey(ht, entry, key);
Jim_SetHashVal(ht, entry, val);
existed = 0;
}
return existed;
}
/**
* Search the hash table for the given key.
* If found, removes the hash entry and returns JIM_OK.
* Otherwise returns JIM_ERR.
*/
int Jim_DeleteHashEntry(Jim_HashTable *ht, const void *key)
{
if (ht->used) {
unsigned int h = Jim_HashKey(ht, key) & ht->sizemask;
Jim_HashEntry *prevHe = NULL;
Jim_HashEntry *he = ht->table[h];
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;
ht->used--;
Jim_FreeEntryKey(ht, he);
Jim_FreeEntryVal(ht, he);
Jim_Free(he);
return JIM_OK;
}
prevHe = he;
he = he->next;
}
}
/* not found */
return JIM_ERR;
}
/**
* Clear all hash entries from the table, but don't free
* the table.
*/
void Jim_ClearHashTable(Jim_HashTable *ht)
{
unsigned int i;
/* Free all the elements */
for (i = 0; ht->used > 0; i++) {
Jim_HashEntry *he, *nextHe;
he = ht->table[i];
while (he) {
nextHe = he->next;
Jim_FreeEntryKey(ht, he);
Jim_FreeEntryVal(ht, he);
Jim_Free(he);
ht->used--;
he = nextHe;
}
ht->table[i] = NULL;
}
}
/* Remove all entries from the hash table
* and leave it empty for reuse
*/
int Jim_FreeHashTable(Jim_HashTable *ht)
{
Jim_ClearHashTable(ht);
/* Free the table and the allocated cache structure */
Jim_Free(ht->table);
/* Re-initialize the table */
JimResetHashTable(ht);
return JIM_OK; /* never fails */
}