forked from ldmud/ldmud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmapping.c
4672 lines (3921 loc) · 133 KB
/
mapping.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
/*---------------------------------------------------------------------------
* Mapping handling functions.
*
*---------------------------------------------------------------------------
* TODO: Rewrite the low-level functions (like allocate_mapping()) to return
* TODO:: failure codes (errno like) instead of throwing errors. In addition,
* TODO:: provide wrapper functions which do throw errorf()s, so that every
* TODO:: caller can handle the errors himself (like the swapper).
*
* TODO: A better mapping implementation would utilise the to-be-written
* TODO:: small block pools. The mapping entries would be unified to
* TODO:: (hash header:key:values) tuples and stored in a pool.
* TODO:: The 'compacted' part of the mapping would obviously go away,
* TODO:: and all indexing would be done through hash table.
* TODO:: The pool is not absolutely required, but would reduce overhead if
* TODO:: MALLOC_TRACE is in effect.
*
* TODO: Check if the use of mp_int is reasonable for values for num_values
* TODO::and num_entries (which are in the struct p_int). And check as
* TODO::the wild mixture of mp_int, p_int, size_t (and maybe still int?)
* TODO::used for iterating over mapping structures.
*
* Mappings, or 'associative arrays', are similar to normal arrays, with
* the principal difference that they can use every value to index their
* stored data, whereas arrays only index with integer values. On the
* other hand this means that in mappings the data is not stored in any
* particular order, whereas arrays imply an order through their indexing.
*
* LPMud mappings in extension allow to store several values for each
* index value. This behaviour is functionally equivalent to a 'normal'
* mapping holding arrays as data, but its direct implementation allows
* certain optimisations.
*
* NB: Where strings are used as index value, they are made shared strings.
*
*
* A mapping consists of several structures (defined in mapping.h):
*
* - the mapping_t is the base of all mappings.
* - mapping_cond_t holds the condensed entries
* - mapping_hash_t holds the hashed entries added since the
* creation of the mapping_cond_t block.
*
* Using this approach, mappings manage to combine a low memory overhead
* with fast operation. Both the hashed and the condensed part may
* be absent.
*
* The key values are sorted according to svalue_cmp(), that is in principle
* by (.type, .u.number >> 1, .x.generic), with the exception of closures and
* strings which have their own sorting order within their .type.
*
* Since the x.generic information is also used to generate the hash value for
* hashing, for values which don't have a secondary information, x.generic is
* set to .u.number << 1.
*
* The mapping_cond_t block holds mapping entries in sorted order.
* Deleted entries are signified by a T_INVALID key value and can appear
* out of order. The data values for a deleted entry are set to svalue-0.
*
* The mapping_hash_t block is used to record all the new additions to
* the mapping since the last compaction. The new entries' data is kept
* directly in the hash entries. The hash table grows with the
* number of hashed entries, so that the average chain length is
* no more than 2. For easier computations,the number of buckets
* is always a power of 2.
*
* All mappings with a mapping_hash_t structure are considered 'dirty'
* (and vice versa, only 'dirty' mappings have a mapping_hash_t).
* During the regular object cleanup, the backend will find and 'clean'
* the dirty mappings by sorting the hashed entries into the condensed part,
* removing the hashed part by this.
*
* To be compacted, a mapping has to conform to a number of conditions:
* - it has been at least TIME_TO_COMPACT seconds (typical 10 minutes)
* since the last addition or deletion of an entry
* and
* - it was to be at least 2*TIME_TO_COMPACT seconds (typical 20 minutes)
* since the last addition or deletion of an entry
* or - the number of condensed-deleted entries is at least half the capacity
* of the condensed part
* or - the number of hashed entries exceeds the number non-deleted condensed
* entries.
*
* The idea is to minimize reallocations of the (potentially large) condensed
* block, as it easily runs into fragmentation of the large block heap.
*
* A garbage collection however compacts all mappings unconditionally.
*
*
* Mappings maintain two refcounts: the main refcount for all references,
* and in the hash structure a protector refcount for references as
* PROTECTED_MAPPING. The latter references are used for 'dirty' mappings
* (ie. mappings with a hash part) which are passed fully or in part as a
* reference to a function. As long as the protector refcount is not 0, all
* entry deletions are not executed immediately. Instead, the 'deleted'
* entries are kept in a separate list until all protective references
* are removed. PROTECTED_MAPPINGs don't need to protect the condensed
* part of a mapping as that changes only during compact_mapping()s
* in the backend.
*
*
* -- mapping_t --
*
* mapping_t {
* p_int ref;
* wiz_list_t * user;
* int num_values;
* p_int num_entries;
*
* mapping_cond_t * cond;
* mapping_hash_t * hash;
*
* mapping_t * next;
* }
*
* .ref is the number of references, as usual.
*
* .user is, as usual, the wizlist entry of the owner object.
*
* .num_values and .num_entries give the width (excluding the key!)
* and number of valid entries in the mapping.
*
* .cond and .hash are the condensed resp. hashed data blocks.
* .hash also serves as indicator if the mapping is 'dirty',
* and therefore contains all the information about the dirtyness.
*
* The .next pointer is not used by the mapping module itself,
* but is provided as courtesy for the cleanup code and the GC, to
* avoid additional memory allocations during a low memory situation.
* The cleanup code uses it to keep its list of dirty mappings; the
* GC uses it to keep its list of stale mappings (ie. mappings with
* keys referencing destructed objects).
*
* -- mapping_cond_t --
*
* mapping_cond_t {
* size_t size;
* svalue_t *data[(mapping->num_values+1) * .size];
* }
*
* This structure holds the .size compacted entries for a mapping (.size
* includes the deleted entries as well, if any).
*
* The first .size svalues in .data[] are the keys. Follwing are the
* actual data values, the values for one entry each in one row.
*
* If a key is .data[ix], its data values are in
* .data[.size + ix * mapping->num_values] through
* .data[.size + (ix+1) * mapping->num_values - 1].
*
* If an entry is deleted, the key's .type is set to T_INVALID and
* the data values are zeroed out (and mapping->hash->cond_deleted is
* incremented), but the entry is otherwise left in place.
*
* -- mapping_hash_t --
*
* hash_mapping_t {
* p_int mask;
* p_int used;
* p_int cond_deleted;
* p_int ref;
* mp_int last_used;
* map_chain_t *deleted;
* map_chain_t *chains[ 1 +.mask ];
* }
*
* This structure keeps track of the changes to a mapping. Every mapping
* with a hash part is considered 'dirty'.
*
* New entries to the mapping are kept in the hashtable made up by
* .chains[]. There are .mask+1 different chains, with .mask+1 always
* being a power of two. This way, .mask can be used in a binary-&
* operation to convert a hash value into a chain index. The number
* of entries in the hashtable is listed in .used.
*
* The driver imposes an upper limit onto the average length of the
* chains: if the average length exceeds two elements, the size of
* the hashtable is doubled (by reallocating the hash_mapping structure).
* This is the reason why you can allocate a mapping with a given 'size':
* it reduces the number of reallocations in the long run.
*
* .condensed_deleted gives the number of deleted entries in
* the mappings condensed_part.
*
* .ref and .deleted come into use when the mapping is used as
* protector mapping. Protector mappings are necessary whenever
* single values of the mapping are used as lvalues, in order to
* protect them against premature deletion ( map[0] = ({ map=0 })
* being the classic case). .ref counts the number of such
* protective references, and is always <= mapping.ref. .deleted
* is the list of entries deleted from the mapping while the
* protection is in effect. If the .ref falls back to 0, all
* the pending deletions of the .deleted entries are performed.
*
* .last_used holds the time (seconds since the epoch) of the last addition
* or removal of an entry. It is used by the compaction algorithm to
* determine whether the mapping should be compacted or not.
*
* -- map_chain_t --
*
* This structure is used to keep single entries in the hash chains
* of hash_mapping, and occasionally, in the .deleted list of
* protector mappings.
*
* map_chain_t {
* map_chain_t *next;
* svalue_t data[ mapping->num_values+1 ];
* }
*
* .next is the next struct map_chain in the hash chain (or .deleted list).
* .data holds the key and it's data values.
*
*---------------------------------------------------------------------------
*/
#include "driver.h"
#include "typedefs.h"
#include "my-alloca.h"
#include <stdio.h>
#include "mapping.h"
#include "array.h"
#include "backend.h"
#include "closure.h"
#include "gcollect.h"
#include "interpret.h"
#include "main.h"
#include "mstrings.h"
#include "object.h"
#include "simulate.h"
#include "structs.h"
#include "svalue.h"
#include "wiz_list.h"
#include "xalloc.h"
#include "i-current_object.h"
#include "i-svalue_cmp.h"
#define TIME_TO_COMPACT (600) /* 10 Minutes */
/* TODO: Make this configurable.
* TODO:: When doing so, also implement the shrinking of the hashtable
*/
/*-------------------------------------------------------------------------*/
/* Types */
/* The local typedefs */
typedef struct map_chain_s map_chain_t;
typedef struct walk_mapping_s walk_mapping_t;
/* --- struct map_chain_s: one entry in a hash chain ---
*
* The hashed mapping entries.
*/
struct map_chain_s {
map_chain_t * next; /* next entry */
svalue_t data[1 /* +mapping->num_values */];
/* [0]: the key, [1..]: the data */
};
#define SIZEOF_MCH(mch, nv) ( \
sizeof(*mch) + (nv) * sizeof(svalue_t) \
)
/* Allocation size of a map_chain_t for <nv> values per key.
*/
/* --- struct walk_mapping_s: contains all walk_mapping pointers */
struct walk_mapping_s {
error_handler_t head; /* The error handler: f_walk_mapping_cleanup */
p_int entries; /* Number of mapping entries. */
mapping_t * map; /* The mapping. */
Bool has_hash; /* The mapping has a hash part (refcount +1) */
callback_t * callback; /* The callback structure */
svalue_t pointers[1 /* + .entries-1*/];
};
/*-------------------------------------------------------------------------*/
mp_int num_mappings = 0;
/* Number of allocated mappings.
*/
mp_int num_hash_mappings = 0;
/* Number of allocated mappings with only a hash part.
*/
mp_int num_dirty_mappings = 0;
/* Number of allocated mappings with a hash and a condensed part.
*/
mapping_t *stale_mappings;
/* During a garbage collection, this is a list of mappings with
* keys referencing destructed objects/lambdas, linked through
* the .next pointers. Since th GC performs a global cleanup first,
* this list is normally empty, but having it increases the robustness
* of the GC.
*/
/*-------------------------------------------------------------------------*/
/* Forward declarations */
#if 0
/* TODO: Remove these defines when the statistics prove to be correct */
#define LOG_ALLOC(where,add,alloc) \
printf("DEBUG: %s: m %p user %p total %ld + %ld (alloc %ld) = %ld\n", where, m, m->user, m->user->mapping_total, add, alloc, m->user->mapping_total + (add))
#define LOG_ADD(where,add) \
printf("DEBUG: %s: m %p user %p total %ld + %ld = %ld\n", where, m, m->user, m->user->mapping_total, add, m->user->mapping_total + (add))
#define LOG_SUB(where,sub) \
printf("DEBUG: %s: m %p user %p total %ld - %ld = %ld\n", where, m, m->user, m->user->mapping_total, sub, m->user->mapping_total - (sub))
#define LOG_SUB_M(where,m,sub) \
printf("DEBUG: %s: m %p user %p total %ld - %ld = %ld\n", where, (m), (m)->user, (m)->user->mapping_total, sub, (m)->user->mapping_total - (sub))
#else
#define LOG_ALLOC(where,add,alloc)
#define LOG_ADD(where,add)
#define LOG_SUB(where,add)
#define LOG_SUB_M(where,m,add)
#endif
/*-------------------------------------------------------------------------*/
static INLINE map_chain_t *
new_map_chain (mapping_t * m)
/* Return a fresh map_chain_t for mapping <m>.
* The .data[] values are not initialised.
*
* Return NULL if out of memory.
*/
{
map_chain_t *rc;
rc = xalloc(SIZEOF_MCH(rc, m->num_values));
if (rc)
{
LOG_ALLOC("new_map_chain", SIZEOF_MCH(rc, m->num_values), SIZEOF_MCH(rc, m->num_values));
m->user->mapping_total += SIZEOF_MCH(rc, m->num_values);
}
return rc;
} /* new_map_chain() */
/*-------------------------------------------------------------------------*/
static INLINE void
free_map_chain (mapping_t * m, map_chain_t *mch, Bool no_data)
/* Free the map_chain <mch> of mapping <m>.
* If <no_data> is TRUE, the svalues themselves are supposed to be empty.
*/
{
p_int ix;
if (!no_data)
{
for (ix = m->num_values; ix >= 0; ix--)
{
free_svalue(mch->data+ix);
}
}
LOG_SUB("free_map_chain", SIZEOF_MCH(mch, m->num_values));
m->user->mapping_total -= SIZEOF_MCH(mch, m->num_values);
xfree(mch);
} /* free_map_chain() */
/*-------------------------------------------------------------------------*/
static INLINE mapping_hash_t *
get_new_hash ( mapping_t *m, mp_int hash_size)
/* Allocate a new hash structure for mapping <m>, prepared to take
* <hash_size> entries. The hash structure is NOT linked into <m>.
*
* Return the new structure, or NULL when out of memory.
*/
/* TODO: hash_size of mp_int seems unnecessarily large to me, because
* TODO::mappings can only have p_int values? */
{
mapping_hash_t *hm;
map_chain_t **mcp;
/* Compute the number of hash buckets to 2**k, where
* k is such that 2**(k+1) > size >= 2**k.
*
* To do this, compute 'size' to (2**k)-1 by first setting
* all bits after the leading '1' and then shifting the
* number right once. The result is then also the mask
* required for indexing.
*/
hash_size |= hash_size >> 1;
hash_size |= hash_size >> 2;
hash_size |= hash_size >> 4;
if (hash_size & ~0xff)
{
hash_size |= hash_size >> 8;
hash_size |= hash_size >> 16;
}
hash_size >>= 1;
/* Allocate the hash_mapping big enough to hold (size+1) hash
* buckets.
* size must not exceed the accessible indexing range. This is
* a possibility because size as a mp_int may have a different
* range than array indices which are size_t.
* TODO: The 0x100000 seems to be a safety offset, but is it?
*/
if (hash_size > (mp_int)((SIZE_MAX - sizeof *hm - 0x100000) / sizeof *mcp)
|| !(hm = xalloc(sizeof *hm + sizeof *mcp * hash_size) ) )
{
return NULL;
}
hm->mask = hash_size;
hm->used = hm->cond_deleted = hm->ref = 0;
hm->last_used = current_time;
/* These members don't really need a default initialisation
* but it's here to catch bogies.
*/
hm->deleted = NULL;
/* Initialise the hashbuckets (there is at least one) */
mcp = hm->chains;
do *mcp++ = NULL; while (--hash_size >= 0);
LOG_ALLOC("get_new_hash", SIZEOF_MH(hm), sizeof *hm + sizeof *mcp * hm->mask);
m->user->mapping_total += SIZEOF_MH(hm);
return hm;
} /* get_new_hash() */
/*-------------------------------------------------------------------------*/
static mapping_t *
get_new_mapping ( wiz_list_t * user, mp_int num_values
, mp_int hash_size, mp_int cond_size)
/* Allocate a basic mapping with <num_values> values per key, and set it
* up to have an initial datablock of <data_size> entries, a hash
* suitable for <hash_size> entries, and a condensed block for <cond_size>
* entries.
*
* The .user is of the mapping is set to <user>.
*
* Return the new mapping, or NULL when out of memory.
*/
/* TODO: hash_size of mp_int seems unnecessarily large to me, because
* TODO::mappings can only have p_int values? */
{
mapping_cond_t *cm;
mapping_hash_t *hm;
mapping_t *m;
/* DEBUG: */ size_t cm_size;
/* Check if the new size is too big */
if (num_values > 0)
{
if (num_values > SSIZE_MAX /* TODO: SIZET_MAX, see port.h */
|| ( num_values != 0
&& (SSIZE_MAX - sizeof(map_chain_t)) / num_values < sizeof(svalue_t))
)
return NULL;
}
/* Allocate the structures */
m = xalloc(sizeof *m);
if (!m)
return NULL;
m->user = user; /* Already needed for statistics */
/* Set up the key block for <cond_size> entries */
cm = NULL;
if (cond_size > 0)
{
/* !DEBUG: size_t */ cm_size = (size_t)cond_size;
cm = xalloc(sizeof(*cm) + sizeof(svalue_t) * cm_size * (num_values+1) - 1);
if (!cm)
{
xfree(m);
return NULL;
}
cm->size = cm_size;
}
/* Set up the hash block for <hash_size> entries.
* Do this last because get_new_hash() modifies the statistics.
*/
hm = NULL;
if (hash_size > 0)
{
hm = get_new_hash(m, hash_size);
if (!hm)
{
if (cm) xfree(cm);
xfree(m);
return NULL;
}
}
/* Initialise the mapping */
m->cond = cm;
m->hash = hm;
m->next = NULL;
m->num_values = num_values;
m->num_entries = 0;
// there can't be a destructed object in the mapping now, record the
// current counter.
m->last_destr_check = destructed_ob_counter;
m->ref = 1;
/* Statistics */
LOG_ADD("get_new_mapping - base", sizeof *m);
m->user->mapping_total += sizeof *m;
if (cm)
{
LOG_ALLOC("get_new_mapping - cond", SIZEOF_MC(cm, num_values), sizeof(*cm) + sizeof(svalue_t) * cm_size * (num_values+1) - 1);
m->user->mapping_total += SIZEOF_MC(cm, num_values);
}
/* hm has already been counted */
num_mappings++;
if (m->cond && m->hash)
num_dirty_mappings++;
else if (m->hash)
num_hash_mappings++;
check_total_mapping_size();
return m;
} /* get_new_mapping() */
/*-------------------------------------------------------------------------*/
mapping_t *
allocate_mapping (mp_int size, mp_int num_values)
/* Allocate a mapping with <num_values> values per key, and setup the
* hash part for (initially) <size> entries. The condensed part will
* not be allocated.
*
* Return the new mapping, or NULL when out of memory.
*/
{
return get_new_mapping(get_current_user(), num_values, size, 0);
} /* allocate_mapping() */
/*-------------------------------------------------------------------------*/
mapping_t *
allocate_cond_mapping (wiz_list_t * user, mp_int size, mp_int num_values)
/* Allocate for <user> a mapping with <num_values> values per key, and
* setup the condensed part for <size> entries. The hash part will not be
* allocated.
*
* The swapper uses this function.
*
* Return the new mapping, or NULL when out of memory.
*/
{
return get_new_mapping(user, num_values, 0, size);
} /* allocate_cond_mapping() */
/*-------------------------------------------------------------------------*/
Bool
_free_mapping (mapping_t *m, Bool no_data)
/* Aliases: free_mapping(m) -> _free_mapping(m, FALSE)
* free_empty_mapping(m) -> _free_mapping(m, TRUE)
*
* The mapping and all associated memory is deallocated resp. dereferenced.
* Always return TRUE (for use within the free_mapping() macro).
*
* If <no_data> is TRUE, all the svalues are assumed to be freed already
* (the swapper uses this after swapping out a mapping). The function still
* will deallocate any map_chain entries, if existing.
*
* If the mapping is 'dirty' (ie. contains a hash_mapping part), it
* is not deallocated immediately, but instead counts 1 to the empty_mapping-
* _load (with regard to the threshold).
*/
{
mapping_hash_t *hm; /* Hashed part of <m> */
#ifdef DEBUG
if (!m)
fatal("NULL pointer passed to free_mapping().\n");
if (!m->user)
fatal("No wizlist pointer for mapping");
if (!no_data && m->ref > 0)
fatal("Mapping with %"PRIdPINT" refs passed to _free_mapping().\n",
m->ref);
#endif
num_mappings--;
if (m->cond && m->hash)
num_dirty_mappings--;
else if (m->hash)
num_hash_mappings--;
m->ref = 0;
/* In case of free_empty_mapping(), this is neither guaranteed nor a
* precondition, but in case this mapping needs to be entered into the
* dirty list the refcount needs to be correct.
*/
/* Free the condensed data */
if (m->cond != NULL)
{
p_int left = m->cond->size * (m->num_values + 1);
svalue_t *data = &(m->cond->data[0]);
for (; !no_data && left > 0; left--, data++)
free_svalue(data);
LOG_SUB("free_mapping cond", SIZEOF_MC(m->cond, m->num_values));
m->user->mapping_total -= SIZEOF_MC(m->cond, m->num_values);
check_total_mapping_size();
xfree(m->cond);
m->cond = NULL;
}
/* Free the hashed data */
if ( NULL != (hm = m->hash) )
{
map_chain_t **mcp, *mc, *next;
p_int i;
#ifdef DEBUG
if (hm->ref)
fatal("Ref count in freed hash mapping: %"PRIdPINT"\n", hm->ref);
#endif
LOG_SUB("free_mapping hash", SIZEOF_MH(hm));
m->user->mapping_total -= SIZEOF_MH(hm);
check_total_mapping_size();
mcp = hm->chains;
/* Loop through all chains */
i = hm->mask + 1;
do {
/* Free this chain */
for (next = *mcp++; NULL != (mc = next); )
{
next = mc->next;
free_map_chain(m, mc, no_data);
}
} while (--i);
xfree(hm);
}
/* Free the base structure.
*/
LOG_SUB("free_mapping base", sizeof(*m));
m->user->mapping_total -= sizeof(*m);
check_total_mapping_size();
xfree(m);
return MY_TRUE;
} /* _free_mapping() */
/*-------------------------------------------------------------------------*/
static INLINE mp_int
mhash (svalue_t * svp)
/* Compute and return the hash value for svalue *<svp>.
* The function requires that x.generic is valid even for types without
* a secondary type information.
*/
{
mp_int i;
switch (svp->type)
{
case T_STRING:
case T_BYTES:
i = mstr_get_hash(svp->u.str);
break;
case T_CLOSURE:
if (CLOSURE_REFERENCES_CODE(svp->x.closure_type))
{
i = (p_int)(svp->u.lambda) ^ *SVALUE_FULLTYPE(svp);
}
else if (CLOSURE_MALLOCED(svp->x.closure_type))
{
i = (svp->u.lambda->ob.type == T_OBJECT
? (p_int)svp->u.lambda->ob.u.ob
: (p_int)svp->u.lambda->ob.u.lwob) ^ *SVALUE_FULLTYPE(svp);
}
else /* Efun, Simul-Efun, Operator closure */
{
i = *SVALUE_FULLTYPE(svp);
}
break;
#ifdef FLOAT_FORMAT_2
case T_FLOAT:
/* We have no additional type information. */
i = svp->u.number;
break;
#endif
default:
i = svp->u.number ^ *SVALUE_FULLTYPE(svp);
break;
}
i = i ^ i >> 16;
i = i ^ i >> 8;
return i;
} /* mhash() */
/*-------------------------------------------------------------------------*/
static svalue_t *
find_map_entry ( mapping_t *m, svalue_t *map_index
, p_int * pKeys, map_chain_t ** ppChain
, Bool bMakeTabled
)
/* Index mapping <m> with key value <map_index> and if found, return a pointer
* to the entry block for this key (ie. the result pointer will point to
* the stored key value).
* If the key was found in the condensed data, *<pKeys> will be set
* to key index; otherwise *<ppChain> will point to the hash map chain entry.
* The 'not found' values for the two variables are -1 and NULL resp.
*
* If <bMakeTabled> is TRUE and <map_index> is a string, it is made tabled.
*
* If the key is not found, NULL is returned.
*
* Sideeffect: <map_index>.x.generic information is generated for types
* which usually have none (required for hashing) and keys referencing
* destructed objects are replaced by const0.
*/
{
*pKeys = -1;
*ppChain = NULL;
/* If the key is a string, make it tabled */
if ((map_index->type == T_STRING || map_index->type == T_BYTES)
&& !mstr_tabled(map_index->u.str)
&& bMakeTabled)
{
map_index->u.str = make_tabled(map_index->u.str);
}
/* Check if it's a destructed object.
*/
if (destructed_object_ref(map_index))
assign_svalue(map_index, &const0);
/* Generate secondary information for types which usually
* have none (required for hashing).
*/
if (map_index->type != T_CLOSURE
&& map_index->type != T_FLOAT
&& map_index->type != T_SYMBOL
&& map_index->type != T_QUOTED_ARRAY
&& map_index->type != T_LVALUE
)
map_index->x.generic = (short)(map_index->u.number << 1);
/* Search in the condensed part first.
*/
if (m->cond && m->cond->size != 0)
{
mapping_cond_t *cm = m->cond;
mp_int size = cm->size;
svalue_t *key, * keystart, * keyend;
keystart = &cm->data[0];
keyend = keystart + size;
/* Skip eventual deleted entries at start or end */
while (size > 0 && keystart->type == T_INVALID)
{
keystart++;
size--;
}
while (size > 0 && keyend[-1].type == T_INVALID)
{
keyend--;
size--;
}
while (keyend > keystart)
{
int cmp;
key = (keyend - keystart) / 2 + keystart;
while (key > keystart && key->type == T_INVALID)
key--;
cmp = svalue_cmp(map_index, key);
if (cmp == 0)
{
/* Found it */
*pKeys = (p_int)(key - &(cm->data[0]));
return key;
}
if (cmp > 0)
{
/* The map_index value is after key */
for ( keystart = key+1
; keystart < keyend && keystart->type == T_INVALID
; keystart++)
NOOP;
}
else
{
/* The map_index value is before key */
for ( keyend = key
; keystart < keyend && keyend[-1].type == T_INVALID
; keyend--)
NOOP;
}
}
}
/* At this point, the key was not found in the condensed index
* of the mapping. Try the hashed index next.
*/
if (m->hash && m->hash->used)
{
mapping_hash_t *hm = m->hash;
map_chain_t *mc;
mp_int idx = mhash(map_index) & hm->mask;
/* Look for the value in the chain determined by index */
for (mc = hm->chains[idx]; mc != NULL; mc = mc->next)
{
if (!svalue_eq(&(mc->data[0]), map_index))
{
/* Found it */
*ppChain = mc;
return &(mc->data[0]);
}
}
}
/* Not found at all */
return NULL;
} /* find_map_entry() */
/*-------------------------------------------------------------------------*/
svalue_t *
_get_map_lvalue (mapping_t *m, svalue_t *map_index
, Bool need_lvalue, Bool check_size)
/* Index mapping <m> with key value <map_index> and return a pointer to the
* array of values stored for this key. If the mapping has no values for a
* key, a pointer to const1 is returned.
*
* If the mapping does not contains the given index, and <need_lvalue> is
* false, &const0 is returned. If <need_lvalue> is true, a new key/value
* entry is created and returned (map_index is assigned for this). If the
* mapping doesn't have values for a key, a pointer to a local static
* instance of svalue-0 is returned.
*
* If check_size is true and the extension of the mapping would increase
* its size over max_mapping_size, a runtime error is raised.
*
* Return NULL when out of memory.
*
* Sideeffect: if <map_index> is an unshared string, it is made shared.
* Also, <map_index>.x.generic information is generated for types
* which usually have none (required for hashing).
*
* For easier use, mapping.h defines the following macros:
* get_map_value(m,x) -> _get_map_lvalue(m,x,false,true)
* get_map_lvalue(m,x) -> _get_map_lvalue(m,x,true,true)
* get_map_lvalue_unchecked(m,x) -> _get_map_lvalue(m,x,true,false)
*/
{
map_chain_t * mc;
mapping_hash_t * hm;
svalue_t * entry;
mp_int idx;
svalue_t real_index;
static svalue_t local_const0;
/* Local svalue-0 instance to be returned if a lvalue
* for a 0-width was requested.
*/
assign_rvalue_no_free(&real_index, map_index);
entry = find_map_entry(m, &real_index, (p_int *)&idx, &mc, need_lvalue);
/* If we found the entry, return the values */
if (entry != NULL)
{
free_svalue(&real_index);
if (!m->num_values)
return &const1;
if (mc != NULL)
return entry+1;
return COND_DATA(m->cond, idx, m->num_values);
}
if (!need_lvalue)
{
free_svalue(&real_index);
return &const0;
}
/* We didn't find key and the caller wants the data.
* So create a new entry and enter it into the hash index (also
* created if necessary).
*/
/* Size limit exceeded? */
if (check_size && (max_mapping_size || max_mapping_keys))
{
mp_int msize;
msize = (mp_int)MAP_TOTAL_SIZE(m) + m->num_values + 1;
if ( (max_mapping_size && msize > (mp_int)max_mapping_size)
|| (max_mapping_keys && MAP_SIZE(m)+1 > max_mapping_keys)
)
{
check_map_for_destr_keys(m);
msize = (mp_int)MAP_TOTAL_SIZE(m) + m->num_values + 1;
}
if (max_mapping_size && msize > (mp_int)max_mapping_size)
{
free_svalue(&real_index);
errorf("Illegal mapping size: %"PRIdMPINT" elements (%"
PRIdPINT" x %"PRIdPINT")\n"
, msize, MAP_SIZE(m)+1, m->num_values);
return NULL;
}
if (max_mapping_keys && MAP_SIZE(m) > (mp_int)max_mapping_keys)
{
free_svalue(&real_index);
errorf("Illegal mapping size: %"PRIdMPINT" entries\n", msize+1);
return NULL;
}
}
/* Get the new entry svalues, but don't assign the key value
* yet - further steps might still fail.
*/
mc = new_map_chain(m);
if (NULL == mc)
{
free_svalue(&real_index);
return NULL;
}
/* If the mapping has no hashed index, create one with just one
* chain and put the new entry in there.
*/
if ( !(hm = m->hash) )
{
/* Create the hash part of the mapping and put