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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
|
/*
* hashtable.c - hash tables
*
* This file is part of zsh, the Z shell.
*
* Copyright (c) 1992-1997 Paul Falstad
* All rights reserved.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and to distribute modified versions of this software for any
* purpose, provided that the above copyright notice and the following
* two paragraphs appear in all copies of this software.
*
* In no event shall Paul Falstad or the Zsh Development Group be liable
* to any party for direct, indirect, special, incidental, or consequential
* damages arising out of the use of this software and its documentation,
* even if Paul Falstad and the Zsh Development Group have been advised of
* the possibility of such damage.
*
* Paul Falstad and the Zsh Development Group specifically disclaim any
* warranties, including, but not limited to, the implied warranties of
* merchantability and fitness for a particular purpose. The software
* provided hereunder is on an "as is" basis, and Paul Falstad and the
* Zsh Development Group have no obligation to provide maintenance,
* support, updates, enhancements, or modifications.
*
*/
#include "../config.h"
#include "zsh.mdh"
#include "hashtable.pro"
typedef struct scanstatus *ScanStatus;
typedef struct hashtableimpl* HashTableImpl;
struct hashtableimpl {
/* Public part of hash table, accessible from outside of hashtable.c. *
* Must be the first field to allow casting HashTable to HashTableImpl. */
struct hashtable pub;
/* HASHTABLE INTERNAL MEMBERS */
ScanStatus scan; /* status of a scan over this hashtable */
#ifdef ZSH_HASH_DEBUG
/* HASHTABLE DEBUG MEMBERS */
HashTableImpl next, last; /* linked list of all hash tables */
char *tablename; /* string containing name of the hash table */
PrintTableStats printinfo; /* pointer to function to print table stats */
#endif /* !ZSH_HASH_DEBUG */
};
static inline HashTableImpl impl(HashTable ht) { return (HashTableImpl)ht; }
/* Structure for recording status of a hashtable scan in progress. When a *
* scan starts, the .scan member of the hashtable structure points to one *
* of these. That member being non-NULL disables resizing of the *
* hashtable (when adding elements). When elements are deleted, the *
* contents of this structure is used to make sure the scan won't stumble *
* into the deleted element. */
struct scanstatus {
int sorted;
union {
struct {
HashNode *hashtab;
int ct;
} s;
HashNode u;
} u;
};
/********************************/
/* Generic Hash Table functions */
/********************************/
#ifdef ZSH_HASH_DEBUG
static void printhashtabinfo(HashTable ht);
static HashTableImpl firstht, lastht;
#endif /* ZSH_HASH_DEBUG */
/* Generic hash function */
/**/
mod_export unsigned
hasher(const char *str)
{
unsigned hashval = 0, c;
while ((c = *((unsigned char *) str++)))
hashval += (hashval << 5) + c;
return hashval;
}
/* Get a new hash table */
/**/
mod_export HashTable
newhashtable(int size, UNUSED(char const *name), UNUSED(PrintTableStats printinfo))
{
HashTableImpl ht;
ht = (HashTableImpl) zshcalloc(sizeof *ht);
#ifdef ZSH_HASH_DEBUG
ht->next = NULL;
if(!firstht)
firstht = ht;
ht->last = lastht;
if(lastht)
lastht->next = ht;
lastht = ht;
ht->printinfo = printinfo ? printinfo : printhashtabinfo;
ht->tablename = ztrdup(name);
#endif /* ZSH_HASH_DEBUG */
ht->pub.nodes = (HashNode *) zshcalloc(size * sizeof(HashNode));
ht->pub.hsize = size;
ht->pub.ct = 0;
ht->scan = NULL;
ht->pub.scantab = NULL;
return &ht->pub;
}
/* Delete a hash table. After this function has been used, any *
* existing pointers to the hash table are invalid. */
/**/
mod_export void
deletehashtable(HashTable ht)
{
ht->emptytable(ht);
#ifdef ZSH_HASH_DEBUG
if(impl(ht)->next)
impl(ht)->next->last = impl(ht)->last;
else
lastht = impl(ht)->last;
if(impl(ht)->last)
impl(ht)->last->next = impl(ht)->next;
else
firstht = impl(ht)->next;
zsfree(impl(ht)->tablename);
#endif /* ZSH_HASH_DEBUG */
zfree(ht->nodes, ht->hsize * sizeof(HashNode));
zfree(ht, sizeof(struct hashtableimpl));
}
/* Add a node to a hash table. *
* nam is the key to use in hashing. nodeptr points *
* to the node to add. If there is already a node in *
* the table with the same key, it is first freed, and *
* then the new node is added. If the number of nodes *
* is now greater than twice the number of hash values, *
* the table is then expanded. */
/**/
mod_export void
addhashnode(HashTable ht, char *nam, void *nodeptr)
{
HashNode oldnode = addhashnode2(ht, nam, nodeptr);
if (oldnode)
ht->freenode(oldnode);
}
/* Add a node to a hash table, returning the old node on replacement. */
/**/
HashNode
addhashnode2(HashTable ht, char *nam, void *nodeptr)
{
unsigned hashval;
HashNode hn, hp, hq;
hn = (HashNode) nodeptr;
hn->nam = nam;
hashval = ht->hash(hn->nam) % ht->hsize;
hp = ht->nodes[hashval];
/* check if this is the first node for this hash value */
if (!hp) {
hn->next = NULL;
ht->nodes[hashval] = hn;
if (++ht->ct >= ht->hsize * 2 && !impl(ht)->scan)
expandhashtable(ht);
return NULL;
}
/* else check if the first node contains the same key */
if (ht->cmpnodes(hp->nam, hn->nam) == 0) {
ht->nodes[hashval] = hn;
replacing:
hn->next = hp->next;
if(impl(ht)->scan) {
if(impl(ht)->scan->sorted) {
HashNode *hashtab = impl(ht)->scan->u.s.hashtab;
int i;
for(i = impl(ht)->scan->u.s.ct; i--; )
if(hashtab[i] == hp)
hashtab[i] = hn;
} else if(impl(ht)->scan->u.u == hp)
impl(ht)->scan->u.u = hn;
}
return hp;
}
/* else run through the list and check all the keys */
hq = hp;
hp = hp->next;
for (; hp; hq = hp, hp = hp->next) {
if (ht->cmpnodes(hp->nam, hn->nam) == 0) {
hq->next = hn;
goto replacing;
}
}
/* else just add it at the front of the list */
hn->next = ht->nodes[hashval];
ht->nodes[hashval] = hn;
if (++ht->ct >= ht->hsize * 2 && !impl(ht)->scan)
expandhashtable(ht);
return NULL;
}
/* Get an enabled entry in a hash table. *
* If successful, it returns a pointer to *
* the hashnode. If the node is DISABLED *
* or isn't found, it returns NULL */
/**/
mod_export HashNode
gethashnode(HashTable ht, const char *nam)
{
unsigned hashval;
HashNode hp;
hashval = ht->hash(nam) % ht->hsize;
for (hp = ht->nodes[hashval]; hp; hp = hp->next) {
if (ht->cmpnodes(hp->nam, nam) == 0) {
if (hp->flags & DISABLED)
return NULL;
else
return hp;
}
}
return NULL;
}
/* Get an entry in a hash table. It will *
* ignore the DISABLED flag and return a *
* pointer to the hashnode if found, else *
* it returns NULL. */
/**/
mod_export HashNode
gethashnode2(HashTable ht, const char *nam)
{
unsigned hashval;
HashNode hp;
hashval = ht->hash(nam) % ht->hsize;
for (hp = ht->nodes[hashval]; hp; hp = hp->next) {
if (ht->cmpnodes(hp->nam, nam) == 0)
return hp;
}
return NULL;
}
/* Remove an entry from a hash table. *
* If successful, it removes the node from the *
* table and returns a pointer to it. If there *
* is no such node, then it returns NULL */
/**/
mod_export HashNode
removehashnode(HashTable ht, const char *nam)
{
unsigned hashval;
HashNode hp, hq;
hashval = ht->hash(nam) % ht->hsize;
hp = ht->nodes[hashval];
/* if no nodes at this hash value, return NULL */
if (!hp)
return NULL;
/* else check if the key in the first one matches */
if (ht->cmpnodes(hp->nam, nam) == 0) {
ht->nodes[hashval] = hp->next;
gotit:
ht->ct--;
if(impl(ht)->scan) {
if(impl(ht)->scan->sorted) {
HashNode *hashtab = impl(ht)->scan->u.s.hashtab;
int i;
for(i = impl(ht)->scan->u.s.ct; i--; )
if(hashtab[i] == hp)
hashtab[i] = NULL;
} else if(impl(ht)->scan->u.u == hp)
impl(ht)->scan->u.u = hp->next;
}
return hp;
}
/* else run through the list and check the rest of the keys */
hq = hp;
hp = hp->next;
for (; hp; hq = hp, hp = hp->next) {
if (ht->cmpnodes(hp->nam, nam) == 0) {
hq->next = hp->next;
goto gotit;
}
}
/* else it is not in the list, so return NULL */
return NULL;
}
/* Disable a node in a hash table */
/**/
void
disablehashnode(HashNode hn, UNUSED(int flags))
{
hn->flags |= DISABLED;
}
/* Enable a node in a hash table */
/**/
void
enablehashnode(HashNode hn, UNUSED(int flags))
{
hn->flags &= ~DISABLED;
}
/* Compare two hash table entries by name */
/**/
static int
hnamcmp(const void *ap, const void *bp)
{
HashNode a = *(HashNode *)ap;
HashNode b = *(HashNode *)bp;
return ztrcmp(a->nam, b->nam);
}
/* Scan the nodes in a hash table and execute scanfunc on nodes based on
* the flags that are set/unset. scanflags is passed unchanged to
* scanfunc (if executed).
*
* If sorted != 0, then sort entries of hash table before scanning.
* If flags1 > 0, then execute scanfunc on a node only if at least one of
* these flags is set.
* If flags2 > 0, then execute scanfunc on a node only if all of
* these flags are NOT set.
* The conditions above for flags1/flags2 must both be true.
*
* It is safe to add, remove or replace hash table elements from within
* the scanfunc. Replaced elements will appear in the scan exactly once,
* the new version if it was not scanned before the replacement was made.
* Added elements might or might not appear in the scan.
*
* pprog, if non-NULL, is a pattern that must match the name
* of the node.
*
* The function returns the number of matches, as reduced by pprog, flags1
* and flags2.
*/
/**/
mod_export int
scanmatchtable(HashTable ht, Patprog pprog, int sorted,
int flags1, int flags2, ScanFunc scanfunc, int scanflags)
{
int match = 0;
struct scanstatus st;
/*
* scantab is currently only used by modules to scan
* tables where the contents are generated on the fly from
* other objects. Note the fact that in this case pprog,
* sorted, flags1 and flags2 are ignore.
*/
if (!pprog && ht->scantab) {
ht->scantab(ht, scanfunc, scanflags);
return ht->ct;
}
if (sorted) {
int i, ct = ht->ct;
VARARR(HashNode, hnsorttab, ct);
HashNode *htp, hn;
/*
* Because the structure might change under our feet,
* we can't apply the flags and the pattern before sorting,
* tempting though that is.
*/
for (htp = hnsorttab, i = 0; i < ht->hsize; i++)
for (hn = ht->nodes[i]; hn; hn = hn->next)
*htp++ = hn;
qsort((void *)hnsorttab, ct, sizeof(HashNode), hnamcmp);
st.sorted = 1;
st.u.s.hashtab = hnsorttab;
st.u.s.ct = ct;
impl(ht)->scan = &st;
for (htp = hnsorttab, i = 0; i < ct; i++, htp++) {
if ((!flags1 || ((*htp)->flags & flags1)) &&
!((*htp)->flags & flags2) &&
(!pprog || pattry(pprog, (*htp)->nam))) {
match++;
scanfunc(*htp, scanflags);
}
}
impl(ht)->scan = NULL;
} else {
int i, hsize = ht->hsize;
HashNode *nodes = ht->nodes;
st.sorted = 0;
impl(ht)->scan = &st;
for (i = 0; i < hsize; i++)
for (st.u.u = nodes[i]; st.u.u; ) {
HashNode hn = st.u.u;
st.u.u = st.u.u->next;
if ((!flags1 || (hn->flags & flags1)) && !(hn->flags & flags2)
&& (!pprog || pattry(pprog, hn->nam))) {
match++;
scanfunc(hn, scanflags);
}
}
impl(ht)->scan = NULL;
}
return match;
}
/**/
mod_export int
scanhashtable(HashTable ht, int sorted, int flags1, int flags2,
ScanFunc scanfunc, int scanflags)
{
return scanmatchtable(ht, NULL, sorted, flags1, flags2,
scanfunc, scanflags);
}
/* Expand hash tables when they get too many entries. *
* The new size is 4 times the previous size. */
/**/
static void
expandhashtable(HashTable ht)
{
struct hashnode **onodes, **ha, *hn, *hp;
int i, osize;
osize = ht->hsize;
onodes = ht->nodes;
ht->hsize = osize * 4;
ht->nodes = (HashNode *) zshcalloc(ht->hsize * sizeof(HashNode));
ht->ct = 0;
/* scan through the old list of nodes, and *
* rehash them into the new list of nodes */
for (i = 0, ha = onodes; i < osize; i++, ha++) {
for (hn = *ha; hn;) {
hp = hn->next;
ht->addnode(ht, hn->nam, hn);
hn = hp;
}
}
zfree(onodes, osize * sizeof(HashNode));
}
/* Empty the hash table and resize it if necessary */
/**/
static void
resizehashtable(HashTable ht, int newsize)
{
struct hashnode **ha, *hn, *hp;
int i;
/* free all the hash nodes */
ha = ht->nodes;
for (i = 0; i < ht->hsize; i++, ha++) {
for (hn = *ha; hn;) {
hp = hn->next;
ht->freenode(hn);
hn = hp;
}
}
/* If new size desired is different from current size, *
* we free it and allocate a new nodes array. */
if (ht->hsize != newsize) {
zfree(ht->nodes, ht->hsize * sizeof(HashNode));
ht->nodes = (HashNode *) zshcalloc(newsize * sizeof(HashNode));
ht->hsize = newsize;
} else {
/* else we just re-zero the current nodes array */
memset(ht->nodes, 0, newsize * sizeof(HashNode));
}
ht->ct = 0;
}
/* Generic method to empty a hash table */
/**/
mod_export void
emptyhashtable(HashTable ht)
{
resizehashtable(ht, ht->hsize);
}
/**/
#ifdef ZSH_HASH_DEBUG
/* Print info about hash table */
#define MAXDEPTH 7
/**/
static void
printhashtabinfo(HashTable ht)
{
HashNode hn;
int chainlen[MAXDEPTH + 1];
int i, tmpcount, total;
printf("name of table : %s\n", impl(ht)->tablename);
printf("size of nodes[] : %d\n", ht->hsize);
printf("number of nodes : %d\n\n", ht->ct);
memset(chainlen, 0, sizeof(chainlen));
/* count the number of nodes just to be sure */
total = 0;
for (i = 0; i < ht->hsize; i++) {
tmpcount = 0;
for (hn = ht->nodes[i]; hn; hn = hn->next)
tmpcount++;
if (tmpcount >= MAXDEPTH)
chainlen[MAXDEPTH]++;
else
chainlen[tmpcount]++;
total += tmpcount;
}
for (i = 0; i < MAXDEPTH; i++)
printf("number of hash values with chain of length %d : %4d\n", i, chainlen[i]);
printf("number of hash values with chain of length %d+ : %4d\n", MAXDEPTH, chainlen[MAXDEPTH]);
printf("total number of nodes : %4d\n", total);
}
/**/
int
bin_hashinfo(UNUSED(char *nam), UNUSED(char **args), UNUSED(Options ops), UNUSED(int func))
{
HashTableImpl ht;
printf("----------------------------------------------------\n");
queue_signals();
for(ht = firstht; ht; ht = ht->next) {
ht->printinfo(&ht->pub);
printf("----------------------------------------------------\n");
}
unqueue_signals();
return 0;
}
/**/
#endif /* ZSH_HASH_DEBUG */
/********************************/
/* Command Hash Table Functions */
/********************************/
/* hash table containing external commands */
/**/
mod_export HashTable cmdnamtab;
/* how far we've hashed the PATH so far */
/**/
mod_export char **pathchecked;
/* Create a new command hash table */
/**/
void
createcmdnamtable(void)
{
cmdnamtab = newhashtable(201, "cmdnamtab", NULL);
cmdnamtab->hash = hasher;
cmdnamtab->emptytable = emptycmdnamtable;
cmdnamtab->filltable = fillcmdnamtable;
cmdnamtab->cmpnodes = strcmp;
cmdnamtab->addnode = addhashnode;
cmdnamtab->getnode = gethashnode2;
cmdnamtab->getnode2 = gethashnode2;
cmdnamtab->removenode = removehashnode;
cmdnamtab->disablenode = NULL;
cmdnamtab->enablenode = NULL;
cmdnamtab->freenode = freecmdnamnode;
cmdnamtab->printnode = printcmdnamnode;
pathchecked = path;
}
/**/
static void
emptycmdnamtable(HashTable ht)
{
emptyhashtable(ht);
pathchecked = path;
}
/* Add all commands in a given directory *
* to the command hashtable. */
/**/
void
hashdir(char **dirp)
{
Cmdnam cn;
DIR *dir;
char *fn, *unmetadir, *pathbuf, *pathptr;
int dirlen;
#if defined(_WIN32) || defined(__CYGWIN__)
char *exe;
#endif /* _WIN32 || _CYGWIN__ */
if (isrelative(*dirp))
return;
unmetadir = unmeta(*dirp);
if (!(dir = opendir(unmetadir)))
return;
dirlen = strlen(unmetadir);
pathbuf = (char *)zalloc(dirlen + PATH_MAX + 2);
sprintf(pathbuf, "%s/", unmetadir);
pathptr = pathbuf + dirlen + 1;
while ((fn = zreaddir(dir, 1))) {
if (!cmdnamtab->getnode(cmdnamtab, fn)) {
char *fname = ztrdup(fn);
struct stat statbuf;
int add = 0, dummylen;
unmetafy(fn, &dummylen);
if (strlen(fn) > PATH_MAX) {
/* Too heavy to do all the allocation */
add = 1;
} else {
strcpy(pathptr, fn);
/*
* This is the same test as for the glob qualifier for
* executable plain files.
*/
if (unset(HASHEXECUTABLESONLY) ||
(access(pathbuf, X_OK) == 0 &&
stat(pathbuf, &statbuf) == 0 &&
S_ISREG(statbuf.st_mode) && (statbuf.st_mode & S_IXUGO)))
add = 1;
}
if (add) {
cn = (Cmdnam) zshcalloc(sizeof *cn);
cn->node.flags = 0;
cn->u.name = dirp;
cmdnamtab->addnode(cmdnamtab, fname, cn);
} else
zsfree(fname);
}
#if defined(_WIN32) || defined(__CYGWIN__)
/* Hash foo.exe as foo, since when no real foo exists, foo.exe
will get executed by DOS automatically. This quiets
spurious corrections when CORRECT or CORRECT_ALL is set. */
if ((exe = strrchr(fn, '.')) &&
(exe[1] == 'E' || exe[1] == 'e') &&
(exe[2] == 'X' || exe[2] == 'x') &&
(exe[3] == 'E' || exe[3] == 'e') && exe[4] == 0) {
*exe = 0;
if (!cmdnamtab->getnode(cmdnamtab, fn)) {
cn = (Cmdnam) zshcalloc(sizeof *cn);
cn->node.flags = 0;
cn->u.name = dirp;
cmdnamtab->addnode(cmdnamtab, ztrdup(fn), cn);
}
}
#endif /* _WIN32 || __CYGWIN__ */
}
closedir(dir);
zfree(pathbuf, dirlen + PATH_MAX + 2);
}
/* Go through user's PATH and add everything to *
* the command hashtable. */
/**/
static void
fillcmdnamtable(UNUSED(HashTable ht))
{
char **pq;
for (pq = pathchecked; *pq; pq++)
hashdir(pq);
pathchecked = pq;
}
/**/
static void
freecmdnamnode(HashNode hn)
{
Cmdnam cn = (Cmdnam) hn;
zsfree(cn->node.nam);
if (cn->node.flags & HASHED)
zsfree(cn->u.cmd);
zfree(cn, sizeof(struct cmdnam));
}
/* Print an element of the cmdnamtab hash table (external command) */
/**/
static void
printcmdnamnode(HashNode hn, int printflags)
{
Cmdnam cn = (Cmdnam) hn;
if (printflags & PRINT_WHENCE_WORD) {
printf("%s: %s\n", cn->node.nam, (cn->node.flags & HASHED) ?
"hashed" : "command");
return;
}
if ((printflags & PRINT_WHENCE_CSH) || (printflags & PRINT_WHENCE_SIMPLE)) {
if (cn->node.flags & HASHED) {
zputs(cn->u.cmd, stdout);
putchar('\n');
} else {
zputs(*(cn->u.name), stdout);
putchar('/');
zputs(cn->node.nam, stdout);
putchar('\n');
}
return;
}
if (printflags & PRINT_WHENCE_VERBOSE) {
if (cn->node.flags & HASHED) {
nicezputs(cn->node.nam, stdout);
printf(" is hashed to ");
nicezputs(cn->u.cmd, stdout);
putchar('\n');
} else {
nicezputs(cn->node.nam, stdout);
printf(" is ");
nicezputs(*(cn->u.name), stdout);
putchar('/');
nicezputs(cn->node.nam, stdout);
putchar('\n');
}
return;
}
if (printflags & PRINT_LIST) {
printf("hash ");
if(cn->node.nam[0] == '-')
printf("-- ");
}
if (cn->node.flags & HASHED) {
quotedzputs(cn->node.nam, stdout);
putchar('=');
quotedzputs(cn->u.cmd, stdout);
putchar('\n');
} else {
quotedzputs(cn->node.nam, stdout);
putchar('=');
quotedzputs(*(cn->u.name), stdout);
putchar('/');
quotedzputs(cn->node.nam, stdout);
putchar('\n');
}
}
/***************************************/
/* Shell Function Hash Table Functions */
/***************************************/
/* hash table containing the shell functions */
/**/
mod_export HashTable shfunctab;
/**/
void
createshfunctable(void)
{
shfunctab = newhashtable(7, "shfunctab", NULL);
shfunctab->hash = hasher;
shfunctab->emptytable = NULL;
shfunctab->filltable = NULL;
shfunctab->cmpnodes = strcmp;
shfunctab->addnode = addhashnode;
shfunctab->getnode = gethashnode;
shfunctab->getnode2 = gethashnode2;
shfunctab->removenode = removeshfuncnode;
shfunctab->disablenode = disableshfuncnode;
shfunctab->enablenode = enableshfuncnode;
shfunctab->freenode = freeshfuncnode;
shfunctab->printnode = printshfuncnode;
}
/* Remove an entry from the shell function hash table. *
* It checks if the function is a signal trap and if so, *
* it will disable the trapping of that signal. */
/**/
static HashNode
removeshfuncnode(UNUSED(HashTable ht), const char *nam)
{
HashNode hn;
int sigidx;
if (!strncmp(nam, "TRAP", 4) && (sigidx = getsigidx(nam + 4)) != -1)
hn = removetrap(sigidx);
else
hn = removehashnode(shfunctab, nam);
return hn;
}
/* Disable an entry in the shell function hash table. *
* It checks if the function is a signal trap and if so, *
* it will disable the trapping of that signal. */
/**/
static void
disableshfuncnode(HashNode hn, UNUSED(int flags))
{
hn->flags |= DISABLED;
if (!strncmp(hn->nam, "TRAP", 4)) {
int sigidx = getsigidx(hn->nam + 4);
if (sigidx != -1) {
sigtrapped[sigidx] &= ~ZSIG_FUNC;
unsettrap(sigidx);
}
}
}
/* Re-enable an entry in the shell function hash table. *
* It checks if the function is a signal trap and if so, *
* it will re-enable the trapping of that signal. */
/**/
static void
enableshfuncnode(HashNode hn, UNUSED(int flags))
{
Shfunc shf = (Shfunc) hn;
shf->node.flags &= ~DISABLED;
if (!strncmp(shf->node.nam, "TRAP", 4)) {
int sigidx = getsigidx(shf->node.nam + 4);
if (sigidx != -1) {
settrap(sigidx, NULL, ZSIG_FUNC);
}
}
}
/**/
static void
freeshfuncnode(HashNode hn)
{
Shfunc shf = (Shfunc) hn;
zsfree(shf->node.nam);
if (shf->funcdef)
freeeprog(shf->funcdef);
if (shf->redir)
freeeprog(shf->redir);
dircache_set(&shf->filename, NULL);
if (shf->sticky) {
if (shf->sticky->n_on_opts)
zfree(shf->sticky->on_opts,
shf->sticky->n_on_opts * sizeof(*shf->sticky->on_opts));
if (shf->sticky->n_off_opts)
zfree(shf->sticky->off_opts,
shf->sticky->n_off_opts * sizeof(*shf->sticky->off_opts));
zfree(shf->sticky, sizeof(*shf->sticky));
}
zfree(shf, sizeof(struct shfunc));
}
/* Print a shell function */
/**/
static void
printshfuncnode(HashNode hn, int printflags)
{
Shfunc f = (Shfunc) hn;
char *t = 0;
if ((printflags & PRINT_NAMEONLY) ||
((printflags & PRINT_WHENCE_SIMPLE) &&
!(printflags & PRINT_WHENCE_FUNCDEF))) {
zputs(f->node.nam, stdout);
putchar('\n');
return;
}
if ((printflags & (PRINT_WHENCE_VERBOSE|PRINT_WHENCE_WORD)) &&
!(printflags & PRINT_WHENCE_FUNCDEF)) {
nicezputs(f->node.nam, stdout);
printf((printflags & PRINT_WHENCE_WORD) ? ": function" :
(f->node.flags & PM_UNDEFINED) ?
" is an autoload shell function" :
" is a shell function");
if ((printflags & PRINT_WHENCE_VERBOSE) && f->filename) {
printf(" from ");
quotedzputs(f->filename, stdout);
if (f->node.flags & PM_LOADDIR) {
printf("/");
quotedzputs(f->node.nam, stdout);
}
}
putchar('\n');
return;
}
quotedzputs(f->node.nam, stdout);
if (f->funcdef || f->node.flags & PM_UNDEFINED) {
printf(" () {\n");
zoutputtab(stdout);
if (f->node.flags & PM_UNDEFINED) {
printf("%c undefined\n", hashchar);
zoutputtab(stdout);
} else
t = getpermtext(f->funcdef, NULL, 1);
if (f->node.flags & (PM_TAGGED|PM_TAGGED_LOCAL)) {
printf("%c traced\n", hashchar);
zoutputtab(stdout);
}
if (!t) {
char *fopt = "UtTkzc";
int flgs[] = {
PM_UNALIASED, PM_TAGGED, PM_TAGGED_LOCAL,
PM_KSHSTORED, PM_ZSHSTORED, PM_CUR_FPATH, 0
};
int fl;;
zputs("builtin autoload -X", stdout);
for (fl=0;fopt[fl];fl++)
if (f->node.flags & flgs[fl]) putchar(fopt[fl]);
if (f->filename && (f->node.flags & PM_LOADDIR)) {
putchar(' ');
zputs(f->filename, stdout);
}
} else {
zputs(t, stdout);
zsfree(t);
if (f->funcdef->flags & EF_RUN) {
printf("\n");
zoutputtab(stdout);
quotedzputs(f->node.nam, stdout);
printf(" \"$@\"");
}
}
printf("\n}");
} else {
printf(" () { }");
}
if (f->redir) {
t = getpermtext(f->redir, NULL, 1);
if (t) {
zputs(t, stdout);
zsfree(t);
}
}
putchar('\n');
}
/*
* Wrap scanmatchtable for shell functions with optional
* expansion of leading tabs.
* expand = 0 is standard: use hard tabs.
* expand > 0 uses that many spaces.
* expand < 0 uses no indentation.
*
* Note this function and the following two are called with
* interrupts queued, so saving and restoring text_expand_tabs
* is safe.
*/
/**/
mod_export int
scanmatchshfunc(Patprog pprog, int sorted, int flags1, int flags2,
ScanFunc scanfunc, int scanflags, int expand)
{
int ret, save_expand;
save_expand = text_expand_tabs;
text_expand_tabs = expand;
ret = scanmatchtable(shfunctab, pprog, sorted, flags1, flags2,
scanfunc, scanflags);
text_expand_tabs = save_expand;
return ret;
}
/* Wrap scanhashtable to expand tabs for shell functions */
/**/
mod_export int
scanshfunc(int sorted, int flags1, int flags2,
ScanFunc scanfunc, int scanflags, int expand)
{
return scanmatchshfunc(NULL, sorted, flags1, flags2,
scanfunc, scanflags, expand);
}
/* Wrap shfunctab->printnode to expand tabs */
/**/
mod_export void
printshfuncexpand(HashNode hn, int printflags, int expand)
{
int save_expand;
save_expand = text_expand_tabs;
text_expand_tabs = expand;
shfunctab->printnode(hn, printflags);
text_expand_tabs = save_expand;
}
/*
* Get a heap-duplicated name of the shell function, for
* use in tracing.
*/
/**/
mod_export char *
getshfuncfile(Shfunc shf)
{
if (shf->node.flags & PM_LOADDIR) {
return zhtricat(shf->filename, "/", shf->node.nam);
} else if (shf->filename) {
return dupstring(shf->filename);
} else {
return NULL;
}
}
/**************************************/
/* Reserved Word Hash Table Functions */
/**************************************/
/* Nodes for reserved word hash table */
static struct reswd reswds[] = {
{{NULL, "!", 0}, BANG},
{{NULL, "[[", 0}, DINBRACK},
{{NULL, "{", 0}, INBRACE},
{{NULL, "}", 0}, OUTBRACE},
{{NULL, "case", 0}, CASE},
{{NULL, "coproc", 0}, COPROC},
{{NULL, "declare", 0}, TYPESET},
{{NULL, "do", 0}, DOLOOP},
{{NULL, "done", 0}, DONE},
{{NULL, "elif", 0}, ELIF},
{{NULL, "else", 0}, ELSE},
{{NULL, "end", 0}, ZEND},
{{NULL, "esac", 0}, ESAC},
{{NULL, "export", 0}, TYPESET},
{{NULL, "fi", 0}, FI},
{{NULL, "float", 0}, TYPESET},
{{NULL, "for", 0}, FOR},
{{NULL, "foreach", 0}, FOREACH},
{{NULL, "function", 0}, FUNC},
{{NULL, "if", 0}, IF},
{{NULL, "integer", 0}, TYPESET},
{{NULL, "local", 0}, TYPESET},
{{NULL, "nocorrect", 0}, NOCORRECT},
{{NULL, "readonly", 0}, TYPESET},
{{NULL, "repeat", 0}, REPEAT},
{{NULL, "select", 0}, SELECT},
{{NULL, "then", 0}, THEN},
{{NULL, "time", 0}, TIME},
{{NULL, "typeset", 0}, TYPESET},
{{NULL, "until", 0}, UNTIL},
{{NULL, "while", 0}, WHILE},
{{NULL, NULL, 0}, 0}
};
/* hash table containing the reserved words */
/**/
mod_export HashTable reswdtab;
/* Build the hash table containing zsh's reserved words. */
/**/
void
createreswdtable(void)
{
Reswd rw;
reswdtab = newhashtable(23, "reswdtab", NULL);
reswdtab->hash = hasher;
reswdtab->emptytable = NULL;
reswdtab->filltable = NULL;
reswdtab->cmpnodes = strcmp;
reswdtab->addnode = addhashnode;
reswdtab->getnode = gethashnode;
reswdtab->getnode2 = gethashnode2;
reswdtab->removenode = NULL;
reswdtab->disablenode = disablehashnode;
reswdtab->enablenode = enablehashnode;
reswdtab->freenode = NULL;
reswdtab->printnode = printreswdnode;
for (rw = reswds; rw->node.nam; rw++)
reswdtab->addnode(reswdtab, rw->node.nam, rw);
}
/* Print a reserved word */
/**/
static void
printreswdnode(HashNode hn, int printflags)
{
Reswd rw = (Reswd) hn;
if (printflags & PRINT_WHENCE_WORD) {
printf("%s: reserved\n", rw->node.nam);
return;
}
if (printflags & PRINT_WHENCE_CSH) {
printf("%s: shell reserved word\n", rw->node.nam);
return;
}
if (printflags & PRINT_WHENCE_VERBOSE) {
printf("%s is a reserved word\n", rw->node.nam);
return;
}
/* default is name only */
printf("%s\n", rw->node.nam);
}
/********************************/
/* Aliases Hash Table Functions */
/********************************/
/* hash table containing the aliases */
/**/
mod_export HashTable aliastab;
/* has table containing suffix aliases */
/**/
mod_export HashTable sufaliastab;
/* Create new hash tables for aliases */
/**/
void
createaliastable(HashTable ht)
{
ht->hash = hasher;
ht->emptytable = NULL;
ht->filltable = NULL;
ht->cmpnodes = strcmp;
ht->addnode = addhashnode;
ht->getnode = gethashnode;
ht->getnode2 = gethashnode2;
ht->removenode = removehashnode;
ht->disablenode = disablehashnode;
ht->enablenode = enablehashnode;
ht->freenode = freealiasnode;
ht->printnode = printaliasnode;
}
/**/
void
createaliastables(void)
{
/* Table for regular and global aliases */
aliastab = newhashtable(23, "aliastab", NULL);
createaliastable(aliastab);
/* add the default aliases */
aliastab->addnode(aliastab, ztrdup("run-help"), createaliasnode(ztrdup("man"), 0));
aliastab->addnode(aliastab, ztrdup("which-command"), createaliasnode(ztrdup("whence"), 0));
/* Table for suffix aliases --- make this smaller */
sufaliastab = newhashtable(11, "sufaliastab", NULL);
createaliastable(sufaliastab);
}
/* Create a new alias node */
/**/
mod_export Alias
createaliasnode(char *txt, int flags)
{
Alias al;
al = (Alias) zshcalloc(sizeof *al);
al->node.flags = flags;
al->text = txt;
al->inuse = 0;
return al;
}
/**/
static void
freealiasnode(HashNode hn)
{
Alias al = (Alias) hn;
zsfree(al->node.nam);
zsfree(al->text);
zfree(al, sizeof(struct alias));
}
/* Print an alias */
/**/
static void
printaliasnode(HashNode hn, int printflags)
{
Alias a = (Alias) hn;
if (printflags & PRINT_NAMEONLY) {
zputs(a->node.nam, stdout);
putchar('\n');
return;
}
if (printflags & PRINT_WHENCE_WORD) {
if (a->node.flags & ALIAS_SUFFIX)
printf("%s: suffix alias\n", a->node.nam);
else if (a->node.flags & ALIAS_GLOBAL)
printf("%s: global alias\n", a->node.nam);
else
printf("%s: alias\n", a->node.nam);
return;
}
if (printflags & PRINT_WHENCE_SIMPLE) {
zputs(a->text, stdout);
putchar('\n');
return;
}
if (printflags & PRINT_WHENCE_CSH) {
nicezputs(a->node.nam, stdout);
printf(": ");
if (a->node.flags & ALIAS_SUFFIX)
printf("suffix ");
else if (a->node.flags & ALIAS_GLOBAL)
printf("globally ");
printf ("aliased to ");
nicezputs(a->text, stdout);
putchar('\n');
return;
}
if (printflags & PRINT_WHENCE_VERBOSE) {
nicezputs(a->node.nam, stdout);
printf(" is a");
if (a->node.flags & ALIAS_SUFFIX)
printf(" suffix");
else if (a->node.flags & ALIAS_GLOBAL)
printf(" global");
else
printf("n");
printf(" alias for ");
nicezputs(a->text, stdout);
putchar('\n');
return;
}
if (printflags & PRINT_LIST) {
/* Fast fail on unrepresentable values. */
if (strchr(a->node.nam, '=')) {
zwarn("invalid alias '%s' encountered while printing aliases",
a->node.nam);
/* ### TODO: Return an error status to the C caller */
return;
}
/* Normal path. */
printf("alias ");
if (a->node.flags & ALIAS_SUFFIX)
printf("-s ");
else if (a->node.flags & ALIAS_GLOBAL)
printf("-g ");
/* If an alias begins with `-' or `+', then we must output `-- '
* first, so that it is not interpreted as an option. */
if(a->node.nam[0] == '-' || a->node.nam[0] == '+')
printf("-- ");
}
quotedzputs(a->node.nam, stdout);
putchar('=');
quotedzputs(a->text, stdout);
putchar('\n');
}
/*************************************/
/* History Line Hash Table Functions */
/*************************************/
/**/
void
createhisttable(void)
{
histtab = newhashtable(599, "histtab", NULL);
histtab->hash = histhasher;
histtab->emptytable = emptyhisttable;
histtab->filltable = NULL;
histtab->cmpnodes = histstrcmp;
histtab->addnode = addhistnode;
histtab->getnode = gethashnode2;
histtab->getnode2 = gethashnode2;
histtab->removenode = removehashnode;
histtab->disablenode = NULL;
histtab->enablenode = NULL;
histtab->freenode = freehistnode;
histtab->printnode = NULL;
}
/**/
unsigned
histhasher(const char *str)
{
unsigned hashval = 0;
while (inblank(*str)) str++;
while (*str) {
if (inblank(*str)) {
do str++; while (inblank(*str));
if (*str)
hashval += (hashval << 5) + ' ';
}
else
hashval += (hashval << 5) + *(unsigned char *)str++;
}
return hashval;
}
/**/
void
emptyhisttable(HashTable ht)
{
emptyhashtable(ht);
if (hist_ring)
histremovedups();
}
/* Compare two strings with normalized white-space */
/**/
int
histstrcmp(const char *str1, const char *str2)
{
while (inblank(*str1)) str1++;
while (inblank(*str2)) str2++;
while (*str1 && *str2) {
if (inblank(*str1)) {
if (!inblank(*str2))
break;
do str1++; while (inblank(*str1));
do str2++; while (inblank(*str2));
}
else {
if (*str1 != *str2)
break;
str1++;
str2++;
}
}
return *str1 - *str2;
}
/**/
void
addhistnode(HashTable ht, char *nam, void *nodeptr)
{
HashNode oldnode = addhashnode2(ht, nam, nodeptr);
Histent he = (Histent)nodeptr;
if (oldnode && oldnode != (HashNode)nodeptr) {
if (he->node.flags & HIST_MAKEUNIQUE
|| (he->node.flags & HIST_FOREIGN && (Histent)oldnode == he->up)) {
(void) addhashnode2(ht, oldnode->nam, oldnode); /* restore hash */
he->node.flags |= HIST_DUP;
he->node.flags &= ~HIST_MAKEUNIQUE;
}
else {
oldnode->flags |= HIST_DUP;
if (hist_ignore_all_dups)
freehistnode(oldnode); /* Remove the old dup */
}
}
else
he->node.flags &= ~HIST_MAKEUNIQUE;
}
/**/
void
freehistnode(HashNode nodeptr)
{
freehistdata((Histent)nodeptr, 1);
zfree(nodeptr, sizeof (struct histent));
}
/**/
void
freehistdata(Histent he, int unlink)
{
if (!he)
return;
if (he == &curline)
return;
if (!(he->node.flags & (HIST_DUP | HIST_TMPSTORE)))
removehashnode(histtab, he->node.nam);
zsfree(he->node.nam);
if (he->nwords)
zfree(he->words, he->nwords*2*sizeof(short));
if (unlink) {
if (!--histlinect)
hist_ring = NULL;
else {
if (he == hist_ring)
hist_ring = hist_ring->up;
he->up->down = he->down;
he->down->up = he->up;
}
}
}
/***********************************************************************
* Directory name cache mechanism
*
* The idea of this is that there are various shell structures,
* notably functions, that record the directories with which they
* are associated. Rather than store the full string each time,
* we store a pointer to the same location and count the references.
* This is optimised so that retrieval is quick at the expense of
* searching the list when setting up the structure, which is a much
* rarer operation.
*
* There is nothing special about the fact that the strings are
* directories, except for the assumptions for efficiency that many
* structures will point to the same one, and that there are not too
* many different directories associated with the shell.
**********************************************************************/
struct dircache_entry
{
/* Name of directory in cache */
char *name;
/* Number of references to it */
int refs;
};
/*
* dircache is the cache, of length dircache_size.
* dircache_lastentry is the last entry used, an optimisation
* for multiple references to the same directory, e.g
* "autoload /blah/blah/\*".
*/
static struct dircache_entry *dircache, *dircache_lastentry;
static int dircache_size;
/*
* Set *name to point to a cached version of value.
* value is copied so may come from any source.
*
* If value is NULL, look for the existing value of *name (safe if this
* too is NULL) and remove a reference to it from the cache. If it's
* not found in the cache, it's assumed to be an allocated string and
* freed --- this currently occurs for a shell function that's been
* loaded as the filename is now a full path, not just a directory,
* though we may one day optimise this to a cached directory plus a
* name, too. Note --- the function does *not* otherwise check
* if *name points to something already cached, so this is
* necessary any time *name may already be in the cache.
*/
/**/
mod_export void
dircache_set(char **name, char *value)
{
struct dircache_entry *dcptr, *dcnew;
if (!value) {
if (!*name)
return;
if (!dircache_size) {
zsfree(*name);
*name = NULL;
return;
}
for (dcptr = dircache; dcptr < dircache + dircache_size; dcptr++)
{
/* Must be a pointer much, not a string match */
if (*name == dcptr->name)
{
--dcptr->refs;
if (!dcptr->refs) {
ptrdiff_t ind = dcptr - dircache;
zsfree(dcptr->name);
--dircache_size;
if (!dircache_size) {
zfree(dircache, sizeof(*dircache));
dircache = NULL;
dircache_lastentry = NULL;
*name = NULL;
return;
}
dcnew = (struct dircache_entry *)
zalloc(dircache_size * sizeof(*dcnew));
if (ind)
memcpy(dcnew, dircache, ind * sizeof(*dcnew));
if (ind < dircache_size)
memcpy(dcnew + ind, dcptr + 1,
(dircache_size - ind) * sizeof(*dcnew));
zfree(dircache, (dircache_size+1)*sizeof(*dcnew));
dircache = dcnew;
dircache_lastentry = NULL;
}
*name = NULL;
return;
}
}
zsfree(*name);
*name = NULL;
} else {
/*
* As the function path has been resolved to a particular
* location, we'll store it as an absolute path.
*/
if (*value != '/') {
value = zhtricat(metafy(zgetcwd(), -1, META_HEAPDUP),
"/", value);
value = xsymlink(value, 1);
}
/*
* We'll maintain the cache at exactly the right size rather
* than overallocating. The rationale here is that typically
* we'll get a lot of functions in a small number of directories
* so the complexity overhead of maintaining a separate count
* isn't really matched by the efficiency gain.
*/
if (dircache_lastentry &&
!strcmp(value, dircache_lastentry->name)) {
*name = dircache_lastentry->name;
++dircache_lastentry->refs;
return;
} else if (!dircache_size) {
dircache_size = 1;
dcptr = dircache =
(struct dircache_entry *)zalloc(sizeof(*dircache));
} else {
for (dcptr = dircache; dcptr < dircache + dircache_size; dcptr++)
{
if (!strcmp(value, dcptr->name)) {
*name = dcptr->name;
++dcptr->refs;
return;
}
}
++dircache_size;
dircache = (struct dircache_entry *)
zrealloc(dircache, sizeof(*dircache) * dircache_size);
dcptr = dircache + dircache_size - 1;
}
dcptr->name = ztrdup(value);
*name = dcptr->name;
dcptr->refs = 1;
dircache_lastentry = dcptr;
}
}
|