-
Notifications
You must be signed in to change notification settings - Fork 561
/
Copy pathhv.c
4190 lines (3573 loc) · 135 KB
/
hv.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
/* hv.c
*
* Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
* 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
*
* You may distribute under the terms of either the GNU General Public
* License or the Artistic License, as specified in the README file.
*
*/
/*
* I sit beside the fire and think
* of all that I have seen.
* --Bilbo
*
* [p.278 of _The Lord of the Rings_, II/iii: "The Ring Goes South"]
*/
/*
=head1 HV Handling
A HV structure represents a Perl hash. It consists mainly of an array
of pointers, each of which points to a linked list of HE structures. The
array is indexed by the hash function of the key, so each linked list
represents all the hash entries with the same hash value. Each HE contains
a pointer to the actual value, plus a pointer to a HEK structure which
holds the key and hash value.
=cut
*/
#include "EXTERN.h"
#define PERL_IN_HV_C
#define PERL_HASH_INTERNAL_ACCESS
#include "perl.h"
/* we split when we collide and we have a load factor over 0.667.
* NOTE if you change this formula so we split earlier than previously
* you MUST change the logic in hv_ksplit()
*/
/* MAX_BUCKET_MAX is the maximum max bucket index, at which point we stop growing the
* number of buckets,
*/
#define MAX_BUCKET_MAX ((1<<26)-1)
#define DO_HSPLIT(xhv) ( ( ((xhv)->xhv_keys + ((xhv)->xhv_keys >> 1)) > (xhv)->xhv_max ) && \
((xhv)->xhv_max < MAX_BUCKET_MAX) )
static const char S_strtab_error[]
= "Cannot modify shared string table in hv_%s";
#define DEBUG_HASH_RAND_BITS (DEBUG_h_TEST)
/* Algorithm "xor" from p. 4 of Marsaglia, "Xorshift RNGs"
* See also https://en.wikipedia.org/wiki/Xorshift
*/
#if IVSIZE == 8
/* 64 bit version */
#define XORSHIFT_RAND_BITS(x) PERL_XORSHIFT64_A(x)
#else
/* 32 bit version */
#define XORSHIFT_RAND_BITS(x) PERL_XORSHIFT32_A(x)
#endif
#define UPDATE_HASH_RAND_BITS_KEY(key,klen) \
STMT_START { \
XORSHIFT_RAND_BITS(PL_hash_rand_bits); \
if (DEBUG_HASH_RAND_BITS) { \
PerlIO_printf( Perl_debug_log, \
"PL_hash_rand_bits=%016" UVxf" @ %s:%-4d", \
(UV)PL_hash_rand_bits, __FILE__, __LINE__ \
); \
if (DEBUG_v_TEST && key) { \
PerlIO_printf( Perl_debug_log, " key:'%.*s' %" UVuf"\n", \
(int)klen, \
key ? key : "", /* silence warning */ \
(UV)klen \
); \
} else { \
PerlIO_printf( Perl_debug_log, "\n"); \
} \
} \
} STMT_END
#define MAYBE_UPDATE_HASH_RAND_BITS_KEY(key,klen) \
STMT_START { \
if (PL_HASH_RAND_BITS_ENABLED) \
UPDATE_HASH_RAND_BITS_KEY(key,klen); \
} STMT_END
#define UPDATE_HASH_RAND_BITS() \
UPDATE_HASH_RAND_BITS_KEY(NULL,0)
#define MAYBE_UPDATE_HASH_RAND_BITS() \
MAYBE_UPDATE_HASH_RAND_BITS_KEY(NULL,0)
/* HeKFLAGS(entry) is a single U8, so only provides 8 flags bits.
We currently use 3. All 3 we have behave differently, so if we find a use for
more flags it's hard to predict which they group with.
Hash keys are stored as flat octet sequences, not SVs. Hence we need a flag
bit to say whether those octet sequences represent ISO-8859-1 or UTF-8 -
HVhek_UTF8. The value of this flag bit matters for (regular) hash key
lookups.
To speed up comparisons, keys are normalised to octets. But we (also)
preserve whether the key was supplied, so we need another flag bit to say
whether to reverse the normalisation when iterating the keys (converting them
back to SVs) - HVhek_WASUTF8. The value of this flag bit must be ignored for
(regular) hash key lookups.
But for the shared string table (the private "hash" that manages shared hash
keys and their reference counts), we need to be able to store both variants
(HVhek_WASUTF8 set and clear), so the code performing lookups in this hash
must be different and consider both keys.
However, regular hashes (now) can have a mix of shared and unshared keys.
(This avoids the need to reallocate all the keys into unshared storage at
the point where hash passes the "large" hash threshold, and no longer uses
the shared string table - existing keys remain shared, to avoid makework.)
Meaning that HVhek_NOTSHARED *may* be set in regular hashes (but should be
ignored for hash lookups) but must always be clear in the keys in the shared
string table (because the pointers to these keys are directly copied into
regular hashes - this is how shared keys work.)
Hence all 3 are different, and it's hard to predict the best way to future
proof what is needed next.
We also have HVhek_ENABLEHVKFLAGS, which is used as a mask within the code
below to determine whether to set HvHASKFLAGS() true on the hash as a whole.
This is a public "optimisation" flag provided to serealisers, to indicate
(up front) that a hash contains non-8-bit keys, if they want to use different
storage formats for hashes where all keys are simple octet sequences
(avoiding needing to store an extra byte per hash key), and they need to know
that this holds *before* iterating the hash keys. Only Storable seems to use
this. (For this use case, HVhek_NOTSHARED doesn't matter)
For now, we assume that any future flag bits will need to be distinguished
in the shared string table, hence we create this mask for the shared string
table code. It happens to be the same as HVhek_ENABLEHVKFLAGS, but that might
change if we add a flag bit that matters to the shared string table but not
to Storable (or similar). */
#define HVhek_STORAGE_MASK (0xFF & ~HVhek_NOTSHARED)
#ifdef PURIFY
#define new_HE() (HE*)safemalloc(sizeof(HE))
#define del_HE(p) safefree((char*)p)
#else
STATIC HE*
S_new_he(pTHX)
{
HE* he;
void ** const root = &PL_body_roots[HE_ARENA_ROOT_IX];
if (!*root)
Perl_more_bodies(aTHX_ HE_ARENA_ROOT_IX, sizeof(HE), PERL_ARENA_SIZE);
he = (HE*) *root;
assert(he);
*root = HeNEXT(he);
return he;
}
#define new_HE() new_he()
#define del_HE(p) \
STMT_START { \
HeNEXT(p) = (HE*)(PL_body_roots[HE_ARENA_ROOT_IX]); \
PL_body_roots[HE_ARENA_ROOT_IX] = p; \
} STMT_END
#endif
STATIC HEK *
S_save_hek_flags(const char *str, I32 len, U32 hash, int flags)
{
char *k;
HEK *hek;
PERL_ARGS_ASSERT_SAVE_HEK_FLAGS;
Newx(k, HEK_BASESIZE + len + 2, char);
hek = (HEK*)k;
Copy(str, HEK_KEY(hek), len, char);
HEK_KEY(hek)[len] = 0;
HEK_LEN(hek) = len;
HEK_HASH(hek) = hash;
HEK_FLAGS(hek) = HVhek_NOTSHARED | (flags & HVhek_STORAGE_MASK);
if (flags & HVhek_FREEKEY)
Safefree(str);
return hek;
}
/* free the pool of temporary HE/HEK pairs returned by hv_fetch_ent
* for tied hashes */
void
Perl_free_tied_hv_pool(pTHX)
{
HE *he = PL_hv_fetch_ent_mh;
while (he) {
HE * const ohe = he;
Safefree(HeKEY_hek(he));
he = HeNEXT(he);
del_HE(ohe);
}
PL_hv_fetch_ent_mh = NULL;
}
#if defined(USE_ITHREADS)
HEK *
Perl_hek_dup(pTHX_ HEK *source, CLONE_PARAMS* param)
{
HEK *shared;
PERL_ARGS_ASSERT_HEK_DUP;
PERL_UNUSED_ARG(param);
if (!source)
return NULL;
shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
if (shared) {
/* We already shared this hash key. */
(void)share_hek_hek(shared);
}
else {
shared
= share_hek_flags(HEK_KEY(source), HEK_LEN(source),
HEK_HASH(source), HEK_FLAGS(source));
ptr_table_store(PL_ptr_table, source, shared);
}
return shared;
}
HE *
Perl_he_dup(pTHX_ const HE *e, bool shared, CLONE_PARAMS* param)
{
HE *ret;
PERL_ARGS_ASSERT_HE_DUP;
/* All the *_dup functions are deemed to be API, despite most being deeply
tied to the internals. Hence we can't simply remove the parameter
"shared" from this function. */
/* sv_dup and sv_dup_inc seem to be the only two that are used by XS code.
Probably the others should be dropped from the API. See #19409 */
PERL_UNUSED_ARG(shared);
if (!e)
return NULL;
/* look for it in the table first */
ret = (HE*)ptr_table_fetch(PL_ptr_table, e);
if (ret)
return ret;
/* create anew and remember what it is */
ret = new_HE();
ptr_table_store(PL_ptr_table, e, ret);
if (HeKLEN(e) == HEf_SVKEY) {
char *k;
Newx(k, HEK_BASESIZE + sizeof(const SV *), char);
HeKEY_hek(ret) = (HEK*)k;
HeKEY_sv(ret) = sv_dup_inc(HeKEY_sv(e), param);
}
else if (!(HeKFLAGS(e) & HVhek_NOTSHARED)) {
/* This is hek_dup inlined, which seems to be important for speed
reasons. */
HEK * const source = HeKEY_hek(e);
HEK *shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
if (shared) {
/* We already shared this hash key. */
(void)share_hek_hek(shared);
}
else {
shared
= share_hek_flags(HEK_KEY(source), HEK_LEN(source),
HEK_HASH(source), HEK_FLAGS(source));
ptr_table_store(PL_ptr_table, source, shared);
}
HeKEY_hek(ret) = shared;
}
else
HeKEY_hek(ret) = save_hek_flags(HeKEY(e), HeKLEN(e), HeHASH(e),
HeKFLAGS(e));
HeVAL(ret) = sv_dup_inc(HeVAL(e), param);
HeNEXT(ret) = he_dup(HeNEXT(e), FALSE, param);
return ret;
}
#endif /* USE_ITHREADS */
static void
S_hv_notallowed(pTHX_ int flags, const char *key, I32 klen,
const char *msg)
{
/* Straight to SVt_PVN here, as needed by sv_setpvn_fresh and
* sv_usepvn would otherwise call it */
SV * const sv = newSV_type_mortal(SVt_PV);
PERL_ARGS_ASSERT_HV_NOTALLOWED;
if (!(flags & HVhek_FREEKEY)) {
sv_setpvn_fresh(sv, key, klen);
}
else {
/* Need to free saved eventually assign to mortal SV */
/* XXX is this line an error ???: SV *sv = sv_newmortal(); */
sv_usepvn(sv, (char *) key, klen);
}
if (flags & HVhek_UTF8) {
SvUTF8_on(sv);
}
Perl_croak(aTHX_ msg, SVfARG(sv));
}
/* (klen == HEf_SVKEY) is special for MAGICAL hv entries, meaning key slot
* contains an SV* */
/*
=for apidoc hv_store
=for apidoc_item hv_stores
These each store SV C<val> with the specified key in hash C<hv>, returning NULL
if the operation failed or if the value did not need to be actually stored
within the hash (as in the case of tied hashes). Otherwise it can be
dereferenced to get the original C<SV*>.
They differ only in how the hash key is specified.
In C<hv_stores>, the key must be a C language string literal, enclosed in
double quotes. It is never treated as being in UTF-8. There is no
length_parameter.
In C<hv_store>, C<key> is either NULL or points to the first byte of the string
specifying the key, and its length in bytes is given by the absolute value of
an additional parameter, C<klen>. A NULL key indicates the key is to be
treated as C<undef>, and C<klen> is ignored; otherwise the key string may
contain embedded-NUL bytes. If C<klen> is negative, the string is treated as
being encoded in UTF-8; otherwise not.
C<hv_store> has another extra parameter, C<hash>, a precomputed hash of the key
string, or zero if it has not been precomputed. This parameter is omitted from
C<hv_stores>, as it is computed automatically at compile time.
If C<hv> is NULL, NULL is returned and no action is taken.
If C<val> is NULL, it is treated as being C<undef>; otherwise the caller is
responsible for suitably incrementing the reference count of C<val> before
the call, and decrementing it if the function returned C<NULL>. Effectively
a successful C<hv_store> takes ownership of one reference to C<val>. This is
usually what you want; a newly created SV has a reference count of one, so
if all your code does is create SVs and store them in a hash, C<hv_store>
will own the only reference to the new SV, and your code doesn't need to do
anything further to tidy up.
C<hv_store> is not implemented as a call to L</C<hv_store_ent>>, and does not
create a temporary SV for the key, so if your key data is not already in SV
form, then use C<hv_store> in preference to C<hv_store_ent>.
See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
information on how to use this function on tied hashes.
=for apidoc hv_store_ent
Stores C<val> in a hash. The hash key is specified as C<key>. The C<hash>
parameter is the precomputed hash value; if it is zero, then Perl will
compute it. The return value is the new hash entry so created. It will be
C<NULL> if the operation failed or if the value did not need to be actually
stored within the hash (as in the case of tied hashes). Otherwise the
contents of the return value can be accessed using the C<He?> macros
described here. Note that the caller is responsible for suitably
incrementing the reference count of C<val> before the call, and
decrementing it if the function returned NULL. Effectively a successful
C<hv_store_ent> takes ownership of one reference to C<val>. This is
usually what you want; a newly created SV has a reference count of one, so
if all your code does is create SVs and store them in a hash, C<hv_store>
will own the only reference to the new SV, and your code doesn't need to do
anything further to tidy up. Note that C<hv_store_ent> only reads the C<key>;
unlike C<val> it does not take ownership of it, so maintaining the correct
reference count on C<key> is entirely the caller's responsibility. The reason
it does not take ownership is that C<key> is not used after this function
returns, and so can be freed immediately. C<hv_store>
is not implemented as a call to C<hv_store_ent>, and does not create a temporary
SV for the key, so if your key data is not already in SV form, then use
C<hv_store> in preference to C<hv_store_ent>.
See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
information on how to use this function on tied hashes.
=for apidoc hv_exists
=for apidoc_item hv_existss
=for apidoc_item hv_exists_ent
These each return a boolean indicating whether the specified hash key exists.
They differ only in how the key is specified.
In C<hv_existss>, the key must be a C language string literal, enclosed in
double quotes. It is never treated as being in UTF-8. There is no
length_parameter.
In C<hv_exists>, the absolute value of C<klen> is the length of the key. If
C<klen> is negative the key is assumed to be in UTF-8-encoded Unicode.
C<key> may contain embedded NUL characters.
In C<hv_exists_ent>, the key is specified by the SV C<keysv>; its UTF8ness is
the same as that SV. There is an additional parameter, C<hash>, which can be a
valid precomputed hash value, or 0 to ask for it to be computed.
=for apidoc hv_fetch
=for apidoc_item hv_fetchs
These each return the SV which corresponds to the specified key in the hash.
They differ only in how the key is specified.
In C<hv_fetchs>, the key must be a C language string literal, enclosed in
double quotes. It is never treated as being in UTF-8. There is no
length_parameter.
In C<hv_fetch>, the absolute value of C<klen> is the length of the key. If
C<klen> is negative the key is assumed to be in UTF-8-encoded Unicode.
C<key> may contain embedded NUL characters.
In both, if C<lval> is set, then the fetch will be part of a store. This means
that if there is no value in the hash associated with the given key, then one
is created and a pointer to it is returned. The C<SV*> it points to can be
assigned to. But always check that the return value is non-null before
dereferencing it to an C<SV*>.
See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
information on how to use this function on tied hashes.
=cut
*/
/* returns an HE * structure with the all fields set */
/* note that hent_val will be a mortal sv for MAGICAL hashes */
/*
=for apidoc hv_fetch_ent
Returns the hash entry which corresponds to the specified key in the hash.
C<hash> must be a valid precomputed hash number for the given C<key>, or 0
if you want the function to compute it. IF C<lval> is set then the fetch
will be part of a store. Make sure the return value is non-null before
accessing it. The return value when C<hv> is a tied hash is a pointer to a
static location, so be sure to make a copy of the structure if you need to
store it somewhere.
See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
information on how to use this function on tied hashes.
=cut
*/
/* Common code for hv_delete()/hv_exists()/hv_fetch()/hv_store() */
void *
Perl_hv_common_key_len(pTHX_ HV *hv, const char *key, I32 klen_i32,
const int action, SV *val, const U32 hash)
{
STRLEN klen;
int flags;
PERL_ARGS_ASSERT_HV_COMMON_KEY_LEN;
if (klen_i32 < 0) {
klen = -klen_i32;
flags = HVhek_UTF8;
} else {
klen = klen_i32;
flags = 0;
}
return hv_common(hv, NULL, key, klen, flags, action, val, hash);
}
void *
Perl_hv_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
int flags, int action, SV *val, U32 hash)
{
XPVHV* xhv;
HE *entry;
HE **oentry;
SV *sv;
bool is_utf8;
bool in_collision;
const int return_svp = action & HV_FETCH_JUST_SV;
HEK *keysv_hek = NULL;
if (!hv)
return NULL;
if (SvIS_FREED(hv))
return NULL;
assert(SvTYPE(hv) == SVt_PVHV);
if (SvSMAGICAL(hv) && SvGMAGICAL(hv) && !(action & HV_DISABLE_UVAR_XKEY)) {
MAGIC* mg;
if ((mg = mg_find((const SV *)hv, PERL_MAGIC_uvar))) {
struct ufuncs * const uf = (struct ufuncs *)mg->mg_ptr;
if (uf->uf_set == NULL) {
SV* obj = mg->mg_obj;
if (!keysv) {
keysv = newSVpvn_flags(key, klen, SVs_TEMP |
((flags & HVhek_UTF8)
? SVf_UTF8 : 0));
}
mg->mg_obj = keysv; /* pass key */
uf->uf_index = action; /* pass action */
magic_getuvar(MUTABLE_SV(hv), mg);
keysv = mg->mg_obj; /* may have changed */
mg->mg_obj = obj;
/* If the key may have changed, then we need to invalidate
any passed-in computed hash value. */
hash = 0;
}
}
}
/* flags might have HVhek_NOTSHARED set. If so, we need to ignore that.
Some callers to hv_common() pass the flags value from an existing HEK,
and if that HEK is not shared, then it has the relevant flag bit set,
which must not be passed into share_hek_flags().
It would be "purer" to insist that all callers clear it, but we'll end up
with subtle bugs if we leave it to them, or runtime assertion failures if
we try to enforce our documentation with landmines.
If keysv is true, all code paths assign a new value to flags with that
bit clear, so we're always "good". Hence we only need to explicitly clear
this bit in the else block. */
if (keysv) {
if (flags & HVhek_FREEKEY)
Safefree(key);
key = SvPV_const(keysv, klen);
is_utf8 = (SvUTF8(keysv) != 0);
if (SvIsCOW_shared_hash(keysv)) {
flags = HVhek_KEYCANONICAL | (is_utf8 ? HVhek_UTF8 : 0);
} else {
flags = 0;
}
} else {
is_utf8 = cBOOL(flags & HVhek_UTF8);
flags &= ~HVhek_NOTSHARED;
}
if (action & HV_DELETE) {
return (void *) hv_delete_common(hv, keysv, key, klen,
flags | (is_utf8 ? HVhek_UTF8 : 0),
action, hash);
}
xhv = (XPVHV*)SvANY(hv);
if (SvMAGICAL(hv)) {
if (SvRMAGICAL(hv) && !(action & (HV_FETCH_ISSTORE|HV_FETCH_ISEXISTS))) {
if (mg_find((const SV *)hv, PERL_MAGIC_tied)
|| SvGMAGICAL((const SV *)hv))
{
/* FIXME should be able to skimp on the HE/HEK here when
HV_FETCH_JUST_SV is true. */
if (!keysv) {
keysv = newSVpvn_utf8(key, klen, is_utf8);
} else {
keysv = newSVsv(keysv);
}
sv = sv_newmortal();
mg_copy(MUTABLE_SV(hv), sv, (char *)keysv, HEf_SVKEY);
/* grab a fake HE/HEK pair from the pool or make a new one */
entry = PL_hv_fetch_ent_mh;
if (entry)
PL_hv_fetch_ent_mh = HeNEXT(entry);
else {
char *k;
entry = new_HE();
Newx(k, HEK_BASESIZE + sizeof(const SV *), char);
HeKEY_hek(entry) = (HEK*)k;
}
HeNEXT(entry) = NULL;
HeSVKEY_set(entry, keysv);
HeVAL(entry) = sv;
sv_upgrade(sv, SVt_PVLV);
LvTYPE(sv) = 'T';
/* so we can free entry when freeing sv */
LvTARG(sv) = MUTABLE_SV(entry);
/* XXX remove at some point? */
if (flags & HVhek_FREEKEY)
Safefree(key);
if (return_svp) {
return entry ? (void *) &HeVAL(entry) : NULL;
}
return (void *) entry;
}
#ifdef ENV_IS_CASELESS
else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
U32 i;
for (i = 0; i < klen; ++i)
if (isLOWER(key[i])) {
/* Would be nice if we had a routine to do the
copy and uppercase in a single pass through. */
const char * const nkey = strupr(savepvn(key,klen));
/* Note that this fetch is for nkey (the uppercased
key) whereas the store is for key (the original) */
void *result = hv_common(hv, NULL, nkey, klen,
HVhek_FREEKEY, /* free nkey */
0 /* non-LVAL fetch */
| HV_DISABLE_UVAR_XKEY
| return_svp,
NULL /* no value */,
0 /* compute hash */);
if (!result && (action & HV_FETCH_LVALUE)) {
/* This call will free key if necessary.
Do it this way to encourage compiler to tail
call optimise. */
result = hv_common(hv, keysv, key, klen, flags,
HV_FETCH_ISSTORE
| HV_DISABLE_UVAR_XKEY
| return_svp,
newSV_type(SVt_NULL), hash);
} else {
if (flags & HVhek_FREEKEY)
Safefree(key);
}
return result;
}
}
#endif
} /* ISFETCH */
else if (SvRMAGICAL(hv) && (action & HV_FETCH_ISEXISTS)) {
if (mg_find((const SV *)hv, PERL_MAGIC_tied)
|| SvGMAGICAL((const SV *)hv)) {
/* I don't understand why hv_exists_ent has svret and sv,
whereas hv_exists only had one. */
SV * const svret = sv_newmortal();
sv = sv_newmortal();
if (keysv || is_utf8) {
if (!keysv) {
keysv = newSVpvn_utf8(key, klen, TRUE);
} else {
keysv = newSVsv(keysv);
}
mg_copy(MUTABLE_SV(hv), sv, (char *)sv_2mortal(keysv), HEf_SVKEY);
} else {
mg_copy(MUTABLE_SV(hv), sv, key, klen);
}
if (flags & HVhek_FREEKEY)
Safefree(key);
{
MAGIC * const mg = mg_find(sv, PERL_MAGIC_tiedelem);
if (mg)
magic_existspack(svret, mg);
}
/* This cast somewhat evil, but I'm merely using NULL/
not NULL to return the boolean exists.
And I know hv is not NULL. */
return SvTRUE_NN(svret) ? (void *)hv : NULL;
}
#ifdef ENV_IS_CASELESS
else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
/* XXX This code isn't UTF8 clean. */
char * const keysave = (char * const)key;
/* Will need to free this, so set FREEKEY flag. */
key = savepvn(key,klen);
key = (const char*)strupr((char*)key);
is_utf8 = FALSE;
hash = 0;
keysv = 0;
if (flags & HVhek_FREEKEY) {
Safefree(keysave);
}
flags |= HVhek_FREEKEY;
}
#endif
} /* ISEXISTS */
else if (action & HV_FETCH_ISSTORE) {
bool needs_copy;
bool needs_store;
hv_magic_check (hv, &needs_copy, &needs_store);
if (needs_copy) {
const bool save_taint = TAINT_get;
if (keysv || is_utf8) {
if (!keysv) {
keysv = newSVpvn_utf8(key, klen, TRUE);
}
if (TAINTING_get)
TAINT_set(SvTAINTED(keysv));
keysv = sv_mortalcopy_flags(keysv, SV_GMAGIC|SV_NOSTEAL);
mg_copy(MUTABLE_SV(hv), val, (char*)keysv, HEf_SVKEY);
} else {
mg_copy(MUTABLE_SV(hv), val, key, klen);
}
TAINT_IF(save_taint);
#ifdef NO_TAINT_SUPPORT
PERL_UNUSED_VAR(save_taint);
#endif
if (!needs_store) {
if (flags & HVhek_FREEKEY)
Safefree(key);
return NULL;
}
#ifdef ENV_IS_CASELESS
else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
/* XXX This code isn't UTF8 clean. */
const char *keysave = key;
/* Will need to free this, so set FREEKEY flag. */
key = savepvn(key,klen);
key = (const char*)strupr((char*)key);
is_utf8 = FALSE;
hash = 0;
keysv = 0;
if (flags & HVhek_FREEKEY) {
Safefree(keysave);
}
flags |= HVhek_FREEKEY;
}
#endif
}
} /* ISSTORE */
} /* SvMAGICAL */
if (!HvARRAY(hv)) {
if ((action & (HV_FETCH_LVALUE | HV_FETCH_ISSTORE))
#ifdef DYNAMIC_ENV_FETCH /* if it's an %ENV lookup, we may get it on the fly */
|| (SvRMAGICAL((const SV *)hv)
&& mg_find((const SV *)hv, PERL_MAGIC_env))
#endif
) {
char *array;
Newxz(array,
PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
char);
HvARRAY(hv) = (HE**)array;
}
#ifdef DYNAMIC_ENV_FETCH
else if (action & HV_FETCH_ISEXISTS) {
/* for an %ENV exists, if we do an insert it's by a recursive
store call, so avoid creating HvARRAY(hv) right now. */
}
#endif
else {
/* XXX remove at some point? */
if (flags & HVhek_FREEKEY)
Safefree(key);
return NULL;
}
}
if (is_utf8 && !(flags & HVhek_KEYCANONICAL)) {
/* If the caller wants us to free the key when done, instead use it as
* scratch to store the converted value, and let later code free it. */
if (flags & HVhek_FREEKEY) {
if (! utf8_to_bytes_overwrite((U8 **) &key, &klen)) {
flags |= HVhek_UTF8; /* Couldn't convert */
}
else {
/* Here, key is now in native bytes, and klen is its length */
# define NOW_NATIVE \
is_utf8 = false; \
flags &= ~HVhek_UTF8; \
flags |= HVhek_WASUTF8;
NOW_NATIVE;
}
}
else {
/* Here, the caller wants to retain the key. Use newly allocated
* memory to store any converted value */
void * free_me = NULL;
if (! utf8_to_bytes_new_pv((const U8 **) &key, &klen, &free_me)) {
flags |= HVhek_UTF8; /* Couldn't convert */
}
else {
/* Here, key is now in native bytes, and klen is its length */
NOW_NATIVE;
/* 'free_me' is NULL if the key was already in native bytes, so
* nothing changed, hence no need for anything more. Otherwise
* we have to compensate. */
if (free_me) {
/* Make sure the newly allocated memory gets freed */
flags |= HVhek_FREEKEY;
/* If the caller calculated a hash, it was on the sequence
* of octets that are the UTF-8 form. We've now changed the
* sequence of octets stored to that of the equivalent byte
* representation, so the hash we need is different. */
hash = 0;
}
}
}
}
if (keysv && (SvIsCOW_shared_hash(keysv))) {
if (HvSHAREKEYS(hv))
keysv_hek = SvSHARED_HEK_FROM_PV(SvPVX_const(keysv));
hash = SvSHARED_HASH(keysv);
}
else if (!hash)
PERL_HASH(hash, key, klen);
#ifdef DYNAMIC_ENV_FETCH
if (!HvARRAY(hv)) entry = NULL;
else
#endif
{
entry = (HvARRAY(hv))[hash & (I32) HvMAX(hv)];
}
if (!entry)
goto not_found;
if (keysv_hek) {
/* keysv is actually a HEK in disguise, so we can match just by
* comparing the HEK pointers in the HE chain. There is a slight
* caveat: on something like "\x80", which has both plain and utf8
* representations, perl's hashes do encoding-insensitive lookups,
* but preserve the encoding of the stored key. Thus a particular
* key could map to two different HEKs in PL_strtab. We only
* conclude 'not found' if all the flags are the same; otherwise
* we fall back to a full search (this should only happen in rare
* cases).
*/
int keysv_flags = HEK_FLAGS(keysv_hek);
HE *orig_entry = entry;
for (; entry; entry = HeNEXT(entry)) {
HEK *hek = HeKEY_hek(entry);
if (hek == keysv_hek)
goto found;
if (HEK_FLAGS(hek) != keysv_flags)
break; /* need to do full match */
}
if (!entry)
goto not_found;
/* failed on shortcut - do full search loop */
entry = orig_entry;
}
for (; entry; entry = HeNEXT(entry)) {
if (HeHASH(entry) != hash) /* strings can't be equal */
continue;
if (HeKLEN(entry) != (I32)klen)
continue;
if (memNE(HeKEY(entry),key,klen)) /* is this it? */
continue;
if ((HeKFLAGS(entry) ^ flags) & HVhek_UTF8)
continue;
found:
if (action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE)) {
if ((HeKFLAGS(entry) ^ flags) & HVhek_WASUTF8) {
/* We match if HVhek_UTF8 bit in our flags and hash key's
match. But if entry was set previously with HVhek_WASUTF8
and key now doesn't (or vice versa) then we should change
the key's flag, as this is assignment. */
if ((HeKFLAGS(entry) & HVhek_NOTSHARED) == 0) {
/* Need to swap the key we have for a key with the flags we
need. As keys are shared we can't just write to the
flag, so we share the new one, unshare the old one. */
HEK * const new_hek
= share_hek_flags(key, klen, hash, flags & ~HVhek_FREEKEY);
unshare_hek (HeKEY_hek(entry));
HeKEY_hek(entry) = new_hek;
}
else if (hv == PL_strtab) {
/* PL_strtab is usually the only hash without HvSHAREKEYS,
so putting this test here is cheap */
if (flags & HVhek_FREEKEY)
Safefree(key);
Perl_croak(aTHX_ S_strtab_error,
action & HV_FETCH_LVALUE ? "fetch" : "store");
}
else {
/* Effectively this is save_hek_flags() for a new version
of the HEK and Safefree() of the old rolled together. */
HeKFLAGS(entry) ^= HVhek_WASUTF8;
}
if (flags & HVhek_ENABLEHVKFLAGS)
HvHASKFLAGS_on(hv);
}
if (HeVAL(entry) == &PL_sv_placeholder) {
/* yes, can store into placeholder slot */
if (action & HV_FETCH_LVALUE) {
if (SvMAGICAL(hv)) {
/* This preserves behaviour with the old hv_fetch
implementation which at this point would bail out
with a break; (at "if we find a placeholder, we
pretend we haven't found anything")
That break mean that if a placeholder were found, it
caused a call into hv_store, which in turn would
check magic, and if there is no magic end up pretty
much back at this point (in hv_store's code). */
break;
}
/* LVAL fetch which actually needs a store. */
val = newSV_type(SVt_NULL);
HvPLACEHOLDERS(hv)--;
} else {
/* store */
if (val != &PL_sv_placeholder)
HvPLACEHOLDERS(hv)--;
}
HeVAL(entry) = val;
} else if (action & HV_FETCH_ISSTORE) {
SvREFCNT_dec(HeVAL(entry));
HeVAL(entry) = val;
}
} else if (HeVAL(entry) == &PL_sv_placeholder) {
/* if we find a placeholder, we pretend we haven't found
anything */
break;
}
if (flags & HVhek_FREEKEY)
Safefree(key);
if (return_svp) {
return (void *) &HeVAL(entry);
}
return entry;
}
not_found:
#ifdef DYNAMIC_ENV_FETCH /* %ENV lookup? If so, try to fetch the value now */
if (!(action & HV_FETCH_ISSTORE)
&& SvRMAGICAL((const SV *)hv)
&& mg_find((const SV *)hv, PERL_MAGIC_env)) {
unsigned long len;
const char * const env = PerlEnv_ENVgetenv_len(key,&len);
if (env) {
sv = newSVpvn(env,len);
SvTAINTED_on(sv);
return hv_common(hv, keysv, key, klen, flags,
HV_FETCH_ISSTORE|HV_DISABLE_UVAR_XKEY|return_svp,
sv, hash);
}
}
#endif
if (!entry && SvREADONLY(hv) && !(action & HV_FETCH_ISEXISTS)) {
hv_notallowed(flags, key, klen,
"Attempt to access disallowed key '%" SVf "' in"
" a restricted hash");
}
if (!(action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE))) {
/* Not doing some form of store, so return failure. */
if (flags & HVhek_FREEKEY)
Safefree(key);
return NULL;
}
if (action & HV_FETCH_LVALUE) {
val = action & HV_FETCH_EMPTY_HE ? NULL : newSV_type(SVt_NULL);
if (SvMAGICAL(hv)) {
/* At this point the old hv_fetch code would call to hv_store,
which in turn might do some tied magic. So we need to make that
magic check happen. */
/* gonna assign to this, so it better be there */
/* If a fetch-as-store fails on the fetch, then the action is to
recurse once into "hv_store". If we didn't do this, then that
recursive call would call the key conversion routine again.
However, as we replace the original key with the converted
key, this would result in a double conversion, which would show
up as a bug if the conversion routine is not idempotent.
Hence the use of HV_DISABLE_UVAR_XKEY. */
return hv_common(hv, keysv, key, klen, flags,
HV_FETCH_ISSTORE|HV_DISABLE_UVAR_XKEY|return_svp,
val, hash);
/* XXX Surely that could leak if the fetch-was-store fails?
Just like the hv_fetch. */
}
}
/* Welcome to hv_store... */
if (!HvARRAY(hv)) {
/* Not sure if we can get here. I think the only case of oentry being
NULL is for %ENV with dynamic env fetch. But that should disappear
with magic in the previous code. */