This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
regcomp.c: Stop regexp-to-pv assignemnt from leaking
[perl5.git] / hv.c
1 /*    hv.c
2  *
3  *    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4  *    2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
5  *
6  *    You may distribute under the terms of either the GNU General Public
7  *    License or the Artistic License, as specified in the README file.
8  *
9  */
10
11 /*
12  *      I sit beside the fire and think
13  *          of all that I have seen.
14  *                         --Bilbo
15  *
16  *     [p.278 of _The Lord of the Rings_, II/iii: "The Ring Goes South"]
17  */
18
19 /* 
20 =head1 Hash Manipulation Functions
21
22 A HV structure represents a Perl hash.  It consists mainly of an array
23 of pointers, each of which points to a linked list of HE structures.  The
24 array is indexed by the hash function of the key, so each linked list
25 represents all the hash entries with the same hash value.  Each HE contains
26 a pointer to the actual value, plus a pointer to a HEK structure which
27 holds the key and hash value.
28
29 =cut
30
31 */
32
33 #include "EXTERN.h"
34 #define PERL_IN_HV_C
35 #define PERL_HASH_INTERNAL_ACCESS
36 #include "perl.h"
37
38 #define HV_MAX_LENGTH_BEFORE_SPLIT 14
39
40 static const char S_strtab_error[]
41     = "Cannot modify shared string table in hv_%s";
42
43 #ifdef PURIFY
44
45 #define new_HE() (HE*)safemalloc(sizeof(HE))
46 #define del_HE(p) safefree((char*)p)
47
48 #else
49
50 STATIC HE*
51 S_new_he(pTHX)
52 {
53     dVAR;
54     HE* he;
55     void ** const root = &PL_body_roots[HE_SVSLOT];
56
57     if (!*root)
58         Perl_more_bodies(aTHX_ HE_SVSLOT, sizeof(HE), PERL_ARENA_SIZE);
59     he = (HE*) *root;
60     assert(he);
61     *root = HeNEXT(he);
62     return he;
63 }
64
65 #define new_HE() new_he()
66 #define del_HE(p) \
67     STMT_START { \
68         HeNEXT(p) = (HE*)(PL_body_roots[HE_SVSLOT]);    \
69         PL_body_roots[HE_SVSLOT] = p; \
70     } STMT_END
71
72
73
74 #endif
75
76 STATIC HEK *
77 S_save_hek_flags(const char *str, I32 len, U32 hash, int flags)
78 {
79     const int flags_masked = flags & HVhek_MASK;
80     char *k;
81     HEK *hek;
82
83     PERL_ARGS_ASSERT_SAVE_HEK_FLAGS;
84
85     Newx(k, HEK_BASESIZE + len + 2, char);
86     hek = (HEK*)k;
87     Copy(str, HEK_KEY(hek), len, char);
88     HEK_KEY(hek)[len] = 0;
89     HEK_LEN(hek) = len;
90     HEK_HASH(hek) = hash;
91     HEK_FLAGS(hek) = (unsigned char)flags_masked | HVhek_UNSHARED;
92
93     if (flags & HVhek_FREEKEY)
94         Safefree(str);
95     return hek;
96 }
97
98 /* free the pool of temporary HE/HEK pairs returned by hv_fetch_ent
99  * for tied hashes */
100
101 void
102 Perl_free_tied_hv_pool(pTHX)
103 {
104     dVAR;
105     HE *he = PL_hv_fetch_ent_mh;
106     while (he) {
107         HE * const ohe = he;
108         Safefree(HeKEY_hek(he));
109         he = HeNEXT(he);
110         del_HE(ohe);
111     }
112     PL_hv_fetch_ent_mh = NULL;
113 }
114
115 #if defined(USE_ITHREADS)
116 HEK *
117 Perl_hek_dup(pTHX_ HEK *source, CLONE_PARAMS* param)
118 {
119     HEK *shared;
120
121     PERL_ARGS_ASSERT_HEK_DUP;
122     PERL_UNUSED_ARG(param);
123
124     if (!source)
125         return NULL;
126
127     shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
128     if (shared) {
129         /* We already shared this hash key.  */
130         (void)share_hek_hek(shared);
131     }
132     else {
133         shared
134             = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
135                               HEK_HASH(source), HEK_FLAGS(source));
136         ptr_table_store(PL_ptr_table, source, shared);
137     }
138     return shared;
139 }
140
141 HE *
142 Perl_he_dup(pTHX_ const HE *e, bool shared, CLONE_PARAMS* param)
143 {
144     HE *ret;
145
146     PERL_ARGS_ASSERT_HE_DUP;
147
148     if (!e)
149         return NULL;
150     /* look for it in the table first */
151     ret = (HE*)ptr_table_fetch(PL_ptr_table, e);
152     if (ret)
153         return ret;
154
155     /* create anew and remember what it is */
156     ret = new_HE();
157     ptr_table_store(PL_ptr_table, e, ret);
158
159     HeNEXT(ret) = he_dup(HeNEXT(e),shared, param);
160     if (HeKLEN(e) == HEf_SVKEY) {
161         char *k;
162         Newx(k, HEK_BASESIZE + sizeof(const SV *), char);
163         HeKEY_hek(ret) = (HEK*)k;
164         HeKEY_sv(ret) = sv_dup_inc(HeKEY_sv(e), param);
165     }
166     else if (shared) {
167         /* This is hek_dup inlined, which seems to be important for speed
168            reasons.  */
169         HEK * const source = HeKEY_hek(e);
170         HEK *shared = (HEK*)ptr_table_fetch(PL_ptr_table, source);
171
172         if (shared) {
173             /* We already shared this hash key.  */
174             (void)share_hek_hek(shared);
175         }
176         else {
177             shared
178                 = share_hek_flags(HEK_KEY(source), HEK_LEN(source),
179                                   HEK_HASH(source), HEK_FLAGS(source));
180             ptr_table_store(PL_ptr_table, source, shared);
181         }
182         HeKEY_hek(ret) = shared;
183     }
184     else
185         HeKEY_hek(ret) = save_hek_flags(HeKEY(e), HeKLEN(e), HeHASH(e),
186                                         HeKFLAGS(e));
187     HeVAL(ret) = sv_dup_inc(HeVAL(e), param);
188     return ret;
189 }
190 #endif  /* USE_ITHREADS */
191
192 static void
193 S_hv_notallowed(pTHX_ int flags, const char *key, I32 klen,
194                 const char *msg)
195 {
196     SV * const sv = sv_newmortal();
197
198     PERL_ARGS_ASSERT_HV_NOTALLOWED;
199
200     if (!(flags & HVhek_FREEKEY)) {
201         sv_setpvn(sv, key, klen);
202     }
203     else {
204         /* Need to free saved eventually assign to mortal SV */
205         /* XXX is this line an error ???:  SV *sv = sv_newmortal(); */
206         sv_usepvn(sv, (char *) key, klen);
207     }
208     if (flags & HVhek_UTF8) {
209         SvUTF8_on(sv);
210     }
211     Perl_croak(aTHX_ msg, SVfARG(sv));
212 }
213
214 /* (klen == HEf_SVKEY) is special for MAGICAL hv entries, meaning key slot
215  * contains an SV* */
216
217 /*
218 =for apidoc hv_store
219
220 Stores an SV in a hash.  The hash key is specified as C<key> and the
221 absolute value of C<klen> is the length of the key.  If C<klen> is
222 negative the key is assumed to be in UTF-8-encoded Unicode.  The
223 C<hash> parameter is the precomputed hash value; if it is zero then
224 Perl will compute it.
225
226 The return value will be
227 NULL if the operation failed or if the value did not need to be actually
228 stored within the hash (as in the case of tied hashes).  Otherwise it can
229 be dereferenced to get the original C<SV*>.  Note that the caller is
230 responsible for suitably incrementing the reference count of C<val> before
231 the call, and decrementing it if the function returned NULL.  Effectively
232 a successful hv_store takes ownership of one reference to C<val>.  This is
233 usually what you want; a newly created SV has a reference count of one, so
234 if all your code does is create SVs then store them in a hash, hv_store
235 will own the only reference to the new SV, and your code doesn't need to do
236 anything further to tidy up.  hv_store is not implemented as a call to
237 hv_store_ent, and does not create a temporary SV for the key, so if your
238 key data is not already in SV form then use hv_store in preference to
239 hv_store_ent.
240
241 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
242 information on how to use this function on tied hashes.
243
244 =for apidoc hv_store_ent
245
246 Stores C<val> in a hash.  The hash key is specified as C<key>.  The C<hash>
247 parameter is the precomputed hash value; if it is zero then Perl will
248 compute it.  The return value is the new hash entry so created.  It will be
249 NULL if the operation failed or if the value did not need to be actually
250 stored within the hash (as in the case of tied hashes).  Otherwise the
251 contents of the return value can be accessed using the C<He?> macros
252 described here.  Note that the caller is responsible for suitably
253 incrementing the reference count of C<val> before the call, and
254 decrementing it if the function returned NULL.  Effectively a successful
255 hv_store_ent takes ownership of one reference to C<val>.  This is
256 usually what you want; a newly created SV has a reference count of one, so
257 if all your code does is create SVs then store them in a hash, hv_store
258 will own the only reference to the new SV, and your code doesn't need to do
259 anything further to tidy up.  Note that hv_store_ent only reads the C<key>;
260 unlike C<val> it does not take ownership of it, so maintaining the correct
261 reference count on C<key> is entirely the caller's responsibility.  hv_store
262 is not implemented as a call to hv_store_ent, and does not create a temporary
263 SV for the key, so if your key data is not already in SV form then use
264 hv_store in preference to hv_store_ent.
265
266 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
267 information on how to use this function on tied hashes.
268
269 =for apidoc hv_exists
270
271 Returns a boolean indicating whether the specified hash key exists.  The
272 absolute value of C<klen> is the length of the key.  If C<klen> is
273 negative the key is assumed to be in UTF-8-encoded Unicode.
274
275 =for apidoc hv_fetch
276
277 Returns the SV which corresponds to the specified key in the hash.
278 The absolute value of C<klen> is the length of the key.  If C<klen> is
279 negative the key is assumed to be in UTF-8-encoded Unicode.  If
280 C<lval> is set then the fetch will be part of a store.  This means that if
281 there is no value in the hash associated with the given key, then one is
282 created and a pointer to it is returned.  The C<SV*> it points to can be
283 assigned to.  But always check that the
284 return value is non-null before dereferencing it to an C<SV*>.
285
286 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
287 information on how to use this function on tied hashes.
288
289 =for apidoc hv_exists_ent
290
291 Returns a boolean indicating whether
292 the specified hash key exists.  C<hash>
293 can be a valid precomputed hash value, or 0 to ask for it to be
294 computed.
295
296 =cut
297 */
298
299 /* returns an HE * structure with the all fields set */
300 /* note that hent_val will be a mortal sv for MAGICAL hashes */
301 /*
302 =for apidoc hv_fetch_ent
303
304 Returns the hash entry which corresponds to the specified key in the hash.
305 C<hash> must be a valid precomputed hash number for the given C<key>, or 0
306 if you want the function to compute it.  IF C<lval> is set then the fetch
307 will be part of a store.  Make sure the return value is non-null before
308 accessing it.  The return value when C<hv> is a tied hash is a pointer to a
309 static location, so be sure to make a copy of the structure if you need to
310 store it somewhere.
311
312 See L<perlguts/"Understanding the Magic of Tied Hashes and Arrays"> for more
313 information on how to use this function on tied hashes.
314
315 =cut
316 */
317
318 /* Common code for hv_delete()/hv_exists()/hv_fetch()/hv_store()  */
319 void *
320 Perl_hv_common_key_len(pTHX_ HV *hv, const char *key, I32 klen_i32,
321                        const int action, SV *val, const U32 hash)
322 {
323     STRLEN klen;
324     int flags;
325
326     PERL_ARGS_ASSERT_HV_COMMON_KEY_LEN;
327
328     if (klen_i32 < 0) {
329         klen = -klen_i32;
330         flags = HVhek_UTF8;
331     } else {
332         klen = klen_i32;
333         flags = 0;
334     }
335     return hv_common(hv, NULL, key, klen, flags, action, val, hash);
336 }
337
338 void *
339 Perl_hv_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
340                int flags, int action, SV *val, register U32 hash)
341 {
342     dVAR;
343     XPVHV* xhv;
344     HE *entry;
345     HE **oentry;
346     SV *sv;
347     bool is_utf8;
348     int masked_flags;
349     const int return_svp = action & HV_FETCH_JUST_SV;
350
351     if (!hv)
352         return NULL;
353     if (SvTYPE(hv) == (svtype)SVTYPEMASK)
354         return NULL;
355
356     assert(SvTYPE(hv) == SVt_PVHV);
357
358     if (SvSMAGICAL(hv) && SvGMAGICAL(hv) && !(action & HV_DISABLE_UVAR_XKEY)) {
359         MAGIC* mg;
360         if ((mg = mg_find((const SV *)hv, PERL_MAGIC_uvar))) {
361             struct ufuncs * const uf = (struct ufuncs *)mg->mg_ptr;
362             if (uf->uf_set == NULL) {
363                 SV* obj = mg->mg_obj;
364
365                 if (!keysv) {
366                     keysv = newSVpvn_flags(key, klen, SVs_TEMP |
367                                            ((flags & HVhek_UTF8)
368                                             ? SVf_UTF8 : 0));
369                 }
370                 
371                 mg->mg_obj = keysv;         /* pass key */
372                 uf->uf_index = action;      /* pass action */
373                 magic_getuvar(MUTABLE_SV(hv), mg);
374                 keysv = mg->mg_obj;         /* may have changed */
375                 mg->mg_obj = obj;
376
377                 /* If the key may have changed, then we need to invalidate
378                    any passed-in computed hash value.  */
379                 hash = 0;
380             }
381         }
382     }
383     if (keysv) {
384         if (flags & HVhek_FREEKEY)
385             Safefree(key);
386         key = SvPV_const(keysv, klen);
387         is_utf8 = (SvUTF8(keysv) != 0);
388         if (SvIsCOW_shared_hash(keysv)) {
389             flags = HVhek_KEYCANONICAL | (is_utf8 ? HVhek_UTF8 : 0);
390         } else {
391             flags = is_utf8 ? HVhek_UTF8 : 0;
392         }
393     } else {
394         is_utf8 = ((flags & HVhek_UTF8) ? TRUE : FALSE);
395     }
396
397     if (action & HV_DELETE) {
398         return (void *) hv_delete_common(hv, keysv, key, klen,
399                                          flags, action, hash);
400     }
401
402     xhv = (XPVHV*)SvANY(hv);
403     if (SvMAGICAL(hv)) {
404         if (SvRMAGICAL(hv) && !(action & (HV_FETCH_ISSTORE|HV_FETCH_ISEXISTS))) {
405             if (mg_find((const SV *)hv, PERL_MAGIC_tied)
406                 || SvGMAGICAL((const SV *)hv))
407             {
408                 /* FIXME should be able to skimp on the HE/HEK here when
409                    HV_FETCH_JUST_SV is true.  */
410                 if (!keysv) {
411                     keysv = newSVpvn_utf8(key, klen, is_utf8);
412                 } else {
413                     keysv = newSVsv(keysv);
414                 }
415                 sv = sv_newmortal();
416                 mg_copy(MUTABLE_SV(hv), sv, (char *)keysv, HEf_SVKEY);
417
418                 /* grab a fake HE/HEK pair from the pool or make a new one */
419                 entry = PL_hv_fetch_ent_mh;
420                 if (entry)
421                     PL_hv_fetch_ent_mh = HeNEXT(entry);
422                 else {
423                     char *k;
424                     entry = new_HE();
425                     Newx(k, HEK_BASESIZE + sizeof(const SV *), char);
426                     HeKEY_hek(entry) = (HEK*)k;
427                 }
428                 HeNEXT(entry) = NULL;
429                 HeSVKEY_set(entry, keysv);
430                 HeVAL(entry) = sv;
431                 sv_upgrade(sv, SVt_PVLV);
432                 LvTYPE(sv) = 'T';
433                  /* so we can free entry when freeing sv */
434                 LvTARG(sv) = MUTABLE_SV(entry);
435
436                 /* XXX remove at some point? */
437                 if (flags & HVhek_FREEKEY)
438                     Safefree(key);
439
440                 if (return_svp) {
441                     return entry ? (void *) &HeVAL(entry) : NULL;
442                 }
443                 return (void *) entry;
444             }
445 #ifdef ENV_IS_CASELESS
446             else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
447                 U32 i;
448                 for (i = 0; i < klen; ++i)
449                     if (isLOWER(key[i])) {
450                         /* Would be nice if we had a routine to do the
451                            copy and upercase in a single pass through.  */
452                         const char * const nkey = strupr(savepvn(key,klen));
453                         /* Note that this fetch is for nkey (the uppercased
454                            key) whereas the store is for key (the original)  */
455                         void *result = hv_common(hv, NULL, nkey, klen,
456                                                  HVhek_FREEKEY, /* free nkey */
457                                                  0 /* non-LVAL fetch */
458                                                  | HV_DISABLE_UVAR_XKEY
459                                                  | return_svp,
460                                                  NULL /* no value */,
461                                                  0 /* compute hash */);
462                         if (!result && (action & HV_FETCH_LVALUE)) {
463                             /* This call will free key if necessary.
464                                Do it this way to encourage compiler to tail
465                                call optimise.  */
466                             result = hv_common(hv, keysv, key, klen, flags,
467                                                HV_FETCH_ISSTORE
468                                                | HV_DISABLE_UVAR_XKEY
469                                                | return_svp,
470                                                newSV(0), hash);
471                         } else {
472                             if (flags & HVhek_FREEKEY)
473                                 Safefree(key);
474                         }
475                         return result;
476                     }
477             }
478 #endif
479         } /* ISFETCH */
480         else if (SvRMAGICAL(hv) && (action & HV_FETCH_ISEXISTS)) {
481             if (mg_find((const SV *)hv, PERL_MAGIC_tied)
482                 || SvGMAGICAL((const SV *)hv)) {
483                 /* I don't understand why hv_exists_ent has svret and sv,
484                    whereas hv_exists only had one.  */
485                 SV * const svret = sv_newmortal();
486                 sv = sv_newmortal();
487
488                 if (keysv || is_utf8) {
489                     if (!keysv) {
490                         keysv = newSVpvn_utf8(key, klen, TRUE);
491                     } else {
492                         keysv = newSVsv(keysv);
493                     }
494                     mg_copy(MUTABLE_SV(hv), sv, (char *)sv_2mortal(keysv), HEf_SVKEY);
495                 } else {
496                     mg_copy(MUTABLE_SV(hv), sv, key, klen);
497                 }
498                 if (flags & HVhek_FREEKEY)
499                     Safefree(key);
500                 magic_existspack(svret, mg_find(sv, PERL_MAGIC_tiedelem));
501                 /* This cast somewhat evil, but I'm merely using NULL/
502                    not NULL to return the boolean exists.
503                    And I know hv is not NULL.  */
504                 return SvTRUE(svret) ? (void *)hv : NULL;
505                 }
506 #ifdef ENV_IS_CASELESS
507             else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
508                 /* XXX This code isn't UTF8 clean.  */
509                 char * const keysave = (char * const)key;
510                 /* Will need to free this, so set FREEKEY flag.  */
511                 key = savepvn(key,klen);
512                 key = (const char*)strupr((char*)key);
513                 is_utf8 = FALSE;
514                 hash = 0;
515                 keysv = 0;
516
517                 if (flags & HVhek_FREEKEY) {
518                     Safefree(keysave);
519                 }
520                 flags |= HVhek_FREEKEY;
521             }
522 #endif
523         } /* ISEXISTS */
524         else if (action & HV_FETCH_ISSTORE) {
525             bool needs_copy;
526             bool needs_store;
527             hv_magic_check (hv, &needs_copy, &needs_store);
528             if (needs_copy) {
529                 const bool save_taint = PL_tainted;
530                 if (keysv || is_utf8) {
531                     if (!keysv) {
532                         keysv = newSVpvn_utf8(key, klen, TRUE);
533                     }
534                     if (PL_tainting)
535                         PL_tainted = SvTAINTED(keysv);
536                     keysv = sv_2mortal(newSVsv(keysv));
537                     mg_copy(MUTABLE_SV(hv), val, (char*)keysv, HEf_SVKEY);
538                 } else {
539                     mg_copy(MUTABLE_SV(hv), val, key, klen);
540                 }
541
542                 TAINT_IF(save_taint);
543                 if (!needs_store) {
544                     if (flags & HVhek_FREEKEY)
545                         Safefree(key);
546                     return NULL;
547                 }
548 #ifdef ENV_IS_CASELESS
549                 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
550                     /* XXX This code isn't UTF8 clean.  */
551                     const char *keysave = key;
552                     /* Will need to free this, so set FREEKEY flag.  */
553                     key = savepvn(key,klen);
554                     key = (const char*)strupr((char*)key);
555                     is_utf8 = FALSE;
556                     hash = 0;
557                     keysv = 0;
558
559                     if (flags & HVhek_FREEKEY) {
560                         Safefree(keysave);
561                     }
562                     flags |= HVhek_FREEKEY;
563                 }
564 #endif
565             }
566         } /* ISSTORE */
567     } /* SvMAGICAL */
568
569     if (!HvARRAY(hv)) {
570         if ((action & (HV_FETCH_LVALUE | HV_FETCH_ISSTORE))
571 #ifdef DYNAMIC_ENV_FETCH  /* if it's an %ENV lookup, we may get it on the fly */
572                  || (SvRMAGICAL((const SV *)hv)
573                      && mg_find((const SV *)hv, PERL_MAGIC_env))
574 #endif
575                                                                   ) {
576             char *array;
577             Newxz(array,
578                  PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
579                  char);
580             HvARRAY(hv) = (HE**)array;
581         }
582 #ifdef DYNAMIC_ENV_FETCH
583         else if (action & HV_FETCH_ISEXISTS) {
584             /* for an %ENV exists, if we do an insert it's by a recursive
585                store call, so avoid creating HvARRAY(hv) right now.  */
586         }
587 #endif
588         else {
589             /* XXX remove at some point? */
590             if (flags & HVhek_FREEKEY)
591                 Safefree(key);
592
593             return NULL;
594         }
595     }
596
597     if (is_utf8 && !(flags & HVhek_KEYCANONICAL)) {
598         char * const keysave = (char *)key;
599         key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
600         if (is_utf8)
601             flags |= HVhek_UTF8;
602         else
603             flags &= ~HVhek_UTF8;
604         if (key != keysave) {
605             if (flags & HVhek_FREEKEY)
606                 Safefree(keysave);
607             flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
608             /* If the caller calculated a hash, it was on the sequence of
609                octets that are the UTF-8 form. We've now changed the sequence
610                of octets stored to that of the equivalent byte representation,
611                so the hash we need is different.  */
612             hash = 0;
613         }
614     }
615
616     if (HvREHASH(hv) || (!hash && !(keysv && (SvIsCOW_shared_hash(keysv)))))
617         PERL_HASH_INTERNAL_(hash, key, klen, HvREHASH(hv));
618     else if (!hash)
619         hash = SvSHARED_HASH(keysv);
620
621     /* We don't have a pointer to the hv, so we have to replicate the
622        flag into every HEK, so that hv_iterkeysv can see it.
623        And yes, you do need this even though you are not "storing" because
624        you can flip the flags below if doing an lval lookup.  (And that
625        was put in to give the semantics Andreas was expecting.)  */
626     if (HvREHASH(hv))
627         flags |= HVhek_REHASH;
628
629     masked_flags = (flags & HVhek_MASK);
630
631 #ifdef DYNAMIC_ENV_FETCH
632     if (!HvARRAY(hv)) entry = NULL;
633     else
634 #endif
635     {
636         entry = (HvARRAY(hv))[hash & (I32) HvMAX(hv)];
637     }
638     for (; entry; entry = HeNEXT(entry)) {
639         if (HeHASH(entry) != hash)              /* strings can't be equal */
640             continue;
641         if (HeKLEN(entry) != (I32)klen)
642             continue;
643         if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen))        /* is this it? */
644             continue;
645         if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
646             continue;
647
648         if (action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE)) {
649             if (HeKFLAGS(entry) != masked_flags) {
650                 /* We match if HVhek_UTF8 bit in our flags and hash key's
651                    match.  But if entry was set previously with HVhek_WASUTF8
652                    and key now doesn't (or vice versa) then we should change
653                    the key's flag, as this is assignment.  */
654                 if (HvSHAREKEYS(hv)) {
655                     /* Need to swap the key we have for a key with the flags we
656                        need. As keys are shared we can't just write to the
657                        flag, so we share the new one, unshare the old one.  */
658                     HEK * const new_hek = share_hek_flags(key, klen, hash,
659                                                    masked_flags);
660                     unshare_hek (HeKEY_hek(entry));
661                     HeKEY_hek(entry) = new_hek;
662                 }
663                 else if (hv == PL_strtab) {
664                     /* PL_strtab is usually the only hash without HvSHAREKEYS,
665                        so putting this test here is cheap  */
666                     if (flags & HVhek_FREEKEY)
667                         Safefree(key);
668                     Perl_croak(aTHX_ S_strtab_error,
669                                action & HV_FETCH_LVALUE ? "fetch" : "store");
670                 }
671                 else
672                     HeKFLAGS(entry) = masked_flags;
673                 if (masked_flags & HVhek_ENABLEHVKFLAGS)
674                     HvHASKFLAGS_on(hv);
675             }
676             if (HeVAL(entry) == &PL_sv_placeholder) {
677                 /* yes, can store into placeholder slot */
678                 if (action & HV_FETCH_LVALUE) {
679                     if (SvMAGICAL(hv)) {
680                         /* This preserves behaviour with the old hv_fetch
681                            implementation which at this point would bail out
682                            with a break; (at "if we find a placeholder, we
683                            pretend we haven't found anything")
684
685                            That break mean that if a placeholder were found, it
686                            caused a call into hv_store, which in turn would
687                            check magic, and if there is no magic end up pretty
688                            much back at this point (in hv_store's code).  */
689                         break;
690                     }
691                     /* LVAL fetch which actually needs a store.  */
692                     val = newSV(0);
693                     HvPLACEHOLDERS(hv)--;
694                 } else {
695                     /* store */
696                     if (val != &PL_sv_placeholder)
697                         HvPLACEHOLDERS(hv)--;
698                 }
699                 HeVAL(entry) = val;
700             } else if (action & HV_FETCH_ISSTORE) {
701                 SvREFCNT_dec(HeVAL(entry));
702                 HeVAL(entry) = val;
703             }
704         } else if (HeVAL(entry) == &PL_sv_placeholder) {
705             /* if we find a placeholder, we pretend we haven't found
706                anything */
707             break;
708         }
709         if (flags & HVhek_FREEKEY)
710             Safefree(key);
711         if (return_svp) {
712             return entry ? (void *) &HeVAL(entry) : NULL;
713         }
714         return entry;
715     }
716 #ifdef DYNAMIC_ENV_FETCH  /* %ENV lookup?  If so, try to fetch the value now */
717     if (!(action & HV_FETCH_ISSTORE) 
718         && SvRMAGICAL((const SV *)hv)
719         && mg_find((const SV *)hv, PERL_MAGIC_env)) {
720         unsigned long len;
721         const char * const env = PerlEnv_ENVgetenv_len(key,&len);
722         if (env) {
723             sv = newSVpvn(env,len);
724             SvTAINTED_on(sv);
725             return hv_common(hv, keysv, key, klen, flags,
726                              HV_FETCH_ISSTORE|HV_DISABLE_UVAR_XKEY|return_svp,
727                              sv, hash);
728         }
729     }
730 #endif
731
732     if (!entry && SvREADONLY(hv) && !(action & HV_FETCH_ISEXISTS)) {
733         hv_notallowed(flags, key, klen,
734                         "Attempt to access disallowed key '%"SVf"' in"
735                         " a restricted hash");
736     }
737     if (!(action & (HV_FETCH_LVALUE|HV_FETCH_ISSTORE))) {
738         /* Not doing some form of store, so return failure.  */
739         if (flags & HVhek_FREEKEY)
740             Safefree(key);
741         return NULL;
742     }
743     if (action & HV_FETCH_LVALUE) {
744         val = action & HV_FETCH_EMPTY_HE ? NULL : newSV(0);
745         if (SvMAGICAL(hv)) {
746             /* At this point the old hv_fetch code would call to hv_store,
747                which in turn might do some tied magic. So we need to make that
748                magic check happen.  */
749             /* gonna assign to this, so it better be there */
750             /* If a fetch-as-store fails on the fetch, then the action is to
751                recurse once into "hv_store". If we didn't do this, then that
752                recursive call would call the key conversion routine again.
753                However, as we replace the original key with the converted
754                key, this would result in a double conversion, which would show
755                up as a bug if the conversion routine is not idempotent.  */
756             return hv_common(hv, keysv, key, klen, flags,
757                              HV_FETCH_ISSTORE|HV_DISABLE_UVAR_XKEY|return_svp,
758                              val, hash);
759             /* XXX Surely that could leak if the fetch-was-store fails?
760                Just like the hv_fetch.  */
761         }
762     }
763
764     /* Welcome to hv_store...  */
765
766     if (!HvARRAY(hv)) {
767         /* Not sure if we can get here.  I think the only case of oentry being
768            NULL is for %ENV with dynamic env fetch.  But that should disappear
769            with magic in the previous code.  */
770         char *array;
771         Newxz(array,
772              PERL_HV_ARRAY_ALLOC_BYTES(xhv->xhv_max+1 /* HvMAX(hv)+1 */),
773              char);
774         HvARRAY(hv) = (HE**)array;
775     }
776
777     oentry = &(HvARRAY(hv))[hash & (I32) xhv->xhv_max];
778
779     entry = new_HE();
780     /* share_hek_flags will do the free for us.  This might be considered
781        bad API design.  */
782     if (HvSHAREKEYS(hv))
783         HeKEY_hek(entry) = share_hek_flags(key, klen, hash, flags);
784     else if (hv == PL_strtab) {
785         /* PL_strtab is usually the only hash without HvSHAREKEYS, so putting
786            this test here is cheap  */
787         if (flags & HVhek_FREEKEY)
788             Safefree(key);
789         Perl_croak(aTHX_ S_strtab_error,
790                    action & HV_FETCH_LVALUE ? "fetch" : "store");
791     }
792     else                                       /* gotta do the real thing */
793         HeKEY_hek(entry) = save_hek_flags(key, klen, hash, flags);
794     HeVAL(entry) = val;
795     HeNEXT(entry) = *oentry;
796     *oentry = entry;
797
798     if (val == &PL_sv_placeholder)
799         HvPLACEHOLDERS(hv)++;
800     if (masked_flags & HVhek_ENABLEHVKFLAGS)
801         HvHASKFLAGS_on(hv);
802
803     {
804         const HE *counter = HeNEXT(entry);
805
806         xhv->xhv_keys++; /* HvTOTALKEYS(hv)++ */
807         if (!counter) {                         /* initial entry? */
808         } else if (xhv->xhv_keys > xhv->xhv_max) {
809                 /* Use only the old HvUSEDKEYS(hv) > HvMAX(hv) condition to limit
810                    bucket splits on a rehashed hash, as we're not going to
811                    split it again, and if someone is lucky (evil) enough to
812                    get all the keys in one list they could exhaust our memory
813                    as we repeatedly double the number of buckets on every
814                    entry. Linear search feels a less worse thing to do.  */
815             hsplit(hv);
816         } else if(!HvREHASH(hv)) {
817             U32 n_links = 1;
818
819             while ((counter = HeNEXT(counter)))
820                 n_links++;
821
822             if (n_links > HV_MAX_LENGTH_BEFORE_SPLIT) {
823                 hsplit(hv);
824             }
825         }
826     }
827
828     if (return_svp) {
829         return entry ? (void *) &HeVAL(entry) : NULL;
830     }
831     return (void *) entry;
832 }
833
834 STATIC void
835 S_hv_magic_check(HV *hv, bool *needs_copy, bool *needs_store)
836 {
837     const MAGIC *mg = SvMAGIC(hv);
838
839     PERL_ARGS_ASSERT_HV_MAGIC_CHECK;
840
841     *needs_copy = FALSE;
842     *needs_store = TRUE;
843     while (mg) {
844         if (isUPPER(mg->mg_type)) {
845             *needs_copy = TRUE;
846             if (mg->mg_type == PERL_MAGIC_tied) {
847                 *needs_store = FALSE;
848                 return; /* We've set all there is to set. */
849             }
850         }
851         mg = mg->mg_moremagic;
852     }
853 }
854
855 /*
856 =for apidoc hv_scalar
857
858 Evaluates the hash in scalar context and returns the result. Handles magic when the hash is tied.
859
860 =cut
861 */
862
863 SV *
864 Perl_hv_scalar(pTHX_ HV *hv)
865 {
866     SV *sv;
867
868     PERL_ARGS_ASSERT_HV_SCALAR;
869
870     if (SvRMAGICAL(hv)) {
871         MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_tied);
872         if (mg)
873             return magic_scalarpack(hv, mg);
874     }
875
876     sv = sv_newmortal();
877     if (HvTOTALKEYS((const HV *)hv)) 
878         Perl_sv_setpvf(aTHX_ sv, "%ld/%ld",
879                 (long)HvFILL(hv), (long)HvMAX(hv) + 1);
880     else
881         sv_setiv(sv, 0);
882     
883     return sv;
884 }
885
886 /*
887 =for apidoc hv_delete
888
889 Deletes a key/value pair in the hash.  The value's SV is removed from
890 the hash, made mortal, and returned to the caller.  The absolute
891 value of C<klen> is the length of the key.  If C<klen> is negative the
892 key is assumed to be in UTF-8-encoded Unicode.  The C<flags> value
893 will normally be zero; if set to G_DISCARD then NULL will be returned.
894 NULL will also be returned if the key is not found.
895
896 =for apidoc hv_delete_ent
897
898 Deletes a key/value pair in the hash.  The value SV is removed from the hash,
899 made mortal, and returned to the caller.  The C<flags> value will normally be
900 zero; if set to G_DISCARD then NULL will be returned.  NULL will also be
901 returned if the key is not found.  C<hash> can be a valid precomputed hash
902 value, or 0 to ask for it to be computed.
903
904 =cut
905 */
906
907 STATIC SV *
908 S_hv_delete_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
909                    int k_flags, I32 d_flags, U32 hash)
910 {
911     dVAR;
912     XPVHV* xhv;
913     HE *entry;
914     HE **oentry;
915     bool is_utf8 = (k_flags & HVhek_UTF8) ? TRUE : FALSE;
916     int masked_flags;
917
918     if (SvRMAGICAL(hv)) {
919         bool needs_copy;
920         bool needs_store;
921         hv_magic_check (hv, &needs_copy, &needs_store);
922
923         if (needs_copy) {
924             SV *sv;
925             entry = (HE *) hv_common(hv, keysv, key, klen,
926                                      k_flags & ~HVhek_FREEKEY,
927                                      HV_FETCH_LVALUE|HV_DISABLE_UVAR_XKEY,
928                                      NULL, hash);
929             sv = entry ? HeVAL(entry) : NULL;
930             if (sv) {
931                 if (SvMAGICAL(sv)) {
932                     mg_clear(sv);
933                 }
934                 if (!needs_store) {
935                     if (mg_find(sv, PERL_MAGIC_tiedelem)) {
936                         /* No longer an element */
937                         sv_unmagic(sv, PERL_MAGIC_tiedelem);
938                         return sv;
939                     }           
940                     return NULL;                /* element cannot be deleted */
941                 }
942 #ifdef ENV_IS_CASELESS
943                 else if (mg_find((const SV *)hv, PERL_MAGIC_env)) {
944                     /* XXX This code isn't UTF8 clean.  */
945                     keysv = newSVpvn_flags(key, klen, SVs_TEMP);
946                     if (k_flags & HVhek_FREEKEY) {
947                         Safefree(key);
948                     }
949                     key = strupr(SvPVX(keysv));
950                     is_utf8 = 0;
951                     k_flags = 0;
952                     hash = 0;
953                 }
954 #endif
955             }
956         }
957     }
958     xhv = (XPVHV*)SvANY(hv);
959     if (!HvARRAY(hv))
960         return NULL;
961
962     if (is_utf8 && !(k_flags & HVhek_KEYCANONICAL)) {
963         const char * const keysave = key;
964         key = (char*)bytes_from_utf8((U8*)key, &klen, &is_utf8);
965
966         if (is_utf8)
967             k_flags |= HVhek_UTF8;
968         else
969             k_flags &= ~HVhek_UTF8;
970         if (key != keysave) {
971             if (k_flags & HVhek_FREEKEY) {
972                 /* This shouldn't happen if our caller does what we expect,
973                    but strictly the API allows it.  */
974                 Safefree(keysave);
975             }
976             k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
977         }
978         HvHASKFLAGS_on(MUTABLE_SV(hv));
979     }
980
981     if (HvREHASH(hv) || (!hash && !(keysv && (SvIsCOW_shared_hash(keysv)))))
982         PERL_HASH_INTERNAL_(hash, key, klen, HvREHASH(hv));
983     else if (!hash)
984         hash = SvSHARED_HASH(keysv);
985
986     masked_flags = (k_flags & HVhek_MASK);
987
988     oentry = &(HvARRAY(hv))[hash & (I32) HvMAX(hv)];
989     entry = *oentry;
990     for (; entry; oentry = &HeNEXT(entry), entry = *oentry) {
991         SV *sv;
992         U8 mro_changes = 0; /* 1 = isa; 2 = package moved */
993         GV *gv = NULL;
994         HV *stash = NULL;
995
996         if (HeHASH(entry) != hash)              /* strings can't be equal */
997             continue;
998         if (HeKLEN(entry) != (I32)klen)
999             continue;
1000         if (HeKEY(entry) != key && memNE(HeKEY(entry),key,klen))        /* is this it? */
1001             continue;
1002         if ((HeKFLAGS(entry) ^ masked_flags) & HVhek_UTF8)
1003             continue;
1004
1005         if (hv == PL_strtab) {
1006             if (k_flags & HVhek_FREEKEY)
1007                 Safefree(key);
1008             Perl_croak(aTHX_ S_strtab_error, "delete");
1009         }
1010
1011         /* if placeholder is here, it's already been deleted.... */
1012         if (HeVAL(entry) == &PL_sv_placeholder) {
1013             if (k_flags & HVhek_FREEKEY)
1014                 Safefree(key);
1015             return NULL;
1016         }
1017         if (SvREADONLY(hv) && HeVAL(entry) && SvREADONLY(HeVAL(entry))
1018          && !SvIsCOW(HeVAL(entry))) {
1019             hv_notallowed(k_flags, key, klen,
1020                             "Attempt to delete readonly key '%"SVf"' from"
1021                             " a restricted hash");
1022         }
1023         if (k_flags & HVhek_FREEKEY)
1024             Safefree(key);
1025
1026         /* If this is a stash and the key ends with ::, then someone is 
1027          * deleting a package.
1028          */
1029         if (HeVAL(entry) && HvENAME_get(hv)) {
1030                 gv = (GV *)HeVAL(entry);
1031                 if (keysv) key = SvPV(keysv, klen);
1032                 if ((
1033                      (klen > 1 && key[klen-2] == ':' && key[klen-1] == ':')
1034                       ||
1035                      (klen == 1 && key[0] == ':')
1036                     )
1037                  && (klen != 6 || hv!=PL_defstash || memNE(key,"main::",6))
1038                  && SvTYPE(gv) == SVt_PVGV && (stash = GvHV((GV *)gv))
1039                  && HvENAME_get(stash)) {
1040                         /* A previous version of this code checked that the
1041                          * GV was still in the symbol table by fetching the
1042                          * GV with its name. That is not necessary (and
1043                          * sometimes incorrect), as HvENAME cannot be set
1044                          * on hv if it is not in the symtab. */
1045                         mro_changes = 2;
1046                         /* Hang on to it for a bit. */
1047                         SvREFCNT_inc_simple_void_NN(
1048                          sv_2mortal((SV *)gv)
1049                         );
1050                 }
1051                 else if (klen == 3 && strnEQ(key, "ISA", 3))
1052                     mro_changes = 1;
1053         }
1054
1055         sv = d_flags & G_DISCARD ? HeVAL(entry) : sv_2mortal(HeVAL(entry));
1056         HeVAL(entry) = &PL_sv_placeholder;
1057         if (sv) {
1058             /* deletion of method from stash */
1059             if (isGV(sv) && isGV_with_GP(sv) && GvCVu(sv)
1060              && HvENAME_get(hv))
1061                 mro_method_changed_in(hv);
1062         }
1063
1064         /*
1065          * If a restricted hash, rather than really deleting the entry, put
1066          * a placeholder there. This marks the key as being "approved", so
1067          * we can still access via not-really-existing key without raising
1068          * an error.
1069          */
1070         if (SvREADONLY(hv))
1071             /* We'll be saving this slot, so the number of allocated keys
1072              * doesn't go down, but the number placeholders goes up */
1073             HvPLACEHOLDERS(hv)++;
1074         else {
1075             *oentry = HeNEXT(entry);
1076             if (SvOOK(hv) && entry == HvAUX(hv)->xhv_eiter /* HvEITER(hv) */)
1077                 HvLAZYDEL_on(hv);
1078             else {
1079                 if (SvOOK(hv) && HvLAZYDEL(hv) &&
1080                     entry == HeNEXT(HvAUX(hv)->xhv_eiter))
1081                     HeNEXT(HvAUX(hv)->xhv_eiter) = HeNEXT(entry);
1082                 hv_free_ent(hv, entry);
1083             }
1084             xhv->xhv_keys--; /* HvTOTALKEYS(hv)-- */
1085             if (xhv->xhv_keys == 0)
1086                 HvHASKFLAGS_off(hv);
1087         }
1088
1089         if (d_flags & G_DISCARD) {
1090             SvREFCNT_dec(sv);
1091             sv = NULL;
1092         }
1093
1094         if (mro_changes == 1) mro_isa_changed_in(hv);
1095         else if (mro_changes == 2)
1096             mro_package_moved(NULL, stash, gv, 1);
1097
1098         return sv;
1099     }
1100     if (SvREADONLY(hv)) {
1101         hv_notallowed(k_flags, key, klen,
1102                         "Attempt to delete disallowed key '%"SVf"' from"
1103                         " a restricted hash");
1104     }
1105
1106     if (k_flags & HVhek_FREEKEY)
1107         Safefree(key);
1108     return NULL;
1109 }
1110
1111 STATIC void
1112 S_hsplit(pTHX_ HV *hv)
1113 {
1114     dVAR;
1115     XPVHV* const xhv = (XPVHV*)SvANY(hv);
1116     const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1117     I32 newsize = oldsize * 2;
1118     I32 i;
1119     char *a = (char*) HvARRAY(hv);
1120     HE **aep;
1121     int longest_chain = 0;
1122     int was_shared;
1123
1124     PERL_ARGS_ASSERT_HSPLIT;
1125
1126     /*PerlIO_printf(PerlIO_stderr(), "hsplit called for %p which had %d\n",
1127       (void*)hv, (int) oldsize);*/
1128
1129     if (HvPLACEHOLDERS_get(hv) && !SvREADONLY(hv)) {
1130       /* Can make this clear any placeholders first for non-restricted hashes,
1131          even though Storable rebuilds restricted hashes by putting in all the
1132          placeholders (first) before turning on the readonly flag, because
1133          Storable always pre-splits the hash.  */
1134       hv_clear_placeholders(hv);
1135     }
1136                
1137     PL_nomemok = TRUE;
1138 #if defined(STRANGE_MALLOC) || defined(MYMALLOC)
1139     Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1140           + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1141     if (!a) {
1142       PL_nomemok = FALSE;
1143       return;
1144     }
1145     if (SvOOK(hv)) {
1146         Move(&a[oldsize * sizeof(HE*)], &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1147     }
1148 #else
1149     Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1150         + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1151     if (!a) {
1152       PL_nomemok = FALSE;
1153       return;
1154     }
1155     Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
1156     if (SvOOK(hv)) {
1157         Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1158     }
1159     Safefree(HvARRAY(hv));
1160 #endif
1161
1162     PL_nomemok = FALSE;
1163     Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char);     /* zero 2nd half*/
1164     xhv->xhv_max = --newsize;   /* HvMAX(hv) = --newsize */
1165     HvARRAY(hv) = (HE**) a;
1166     aep = (HE**)a;
1167
1168     for (i=0; i<oldsize; i++,aep++) {
1169         int left_length = 0;
1170         int right_length = 0;
1171         HE **oentry = aep;
1172         HE *entry = *aep;
1173         HE **bep;
1174
1175         if (!entry)                             /* non-existent */
1176             continue;
1177         bep = aep+oldsize;
1178         do {
1179             if ((HeHASH(entry) & newsize) != (U32)i) {
1180                 *oentry = HeNEXT(entry);
1181                 HeNEXT(entry) = *bep;
1182                 *bep = entry;
1183                 right_length++;
1184             }
1185             else {
1186                 oentry = &HeNEXT(entry);
1187                 left_length++;
1188             }
1189             entry = *oentry;
1190         } while (entry);
1191         /* I think we don't actually need to keep track of the longest length,
1192            merely flag if anything is too long. But for the moment while
1193            developing this code I'll track it.  */
1194         if (left_length > longest_chain)
1195             longest_chain = left_length;
1196         if (right_length > longest_chain)
1197             longest_chain = right_length;
1198     }
1199
1200
1201     /* Pick your policy for "hashing isn't working" here:  */
1202     if (longest_chain <= HV_MAX_LENGTH_BEFORE_SPLIT /* split worked?  */
1203         || HvREHASH(hv)) {
1204         return;
1205     }
1206
1207     if (hv == PL_strtab) {
1208         /* Urg. Someone is doing something nasty to the string table.
1209            Can't win.  */
1210         return;
1211     }
1212
1213     /* Awooga. Awooga. Pathological data.  */
1214     /*PerlIO_printf(PerlIO_stderr(), "%p %d of %d with %d/%d buckets\n", (void*)hv,
1215       longest_chain, HvTOTALKEYS(hv), HvFILL(hv),  1+HvMAX(hv));*/
1216
1217     ++newsize;
1218     Newxz(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1219          + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1220     if (SvOOK(hv)) {
1221         Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1222     }
1223
1224     was_shared = HvSHAREKEYS(hv);
1225
1226     HvSHAREKEYS_off(hv);
1227     HvREHASH_on(hv);
1228
1229     aep = HvARRAY(hv);
1230
1231     for (i=0; i<newsize; i++,aep++) {
1232         HE *entry = *aep;
1233         while (entry) {
1234             /* We're going to trash this HE's next pointer when we chain it
1235                into the new hash below, so store where we go next.  */
1236             HE * const next = HeNEXT(entry);
1237             UV hash;
1238             HE **bep;
1239
1240             /* Rehash it */
1241             PERL_HASH_INTERNAL(hash, HeKEY(entry), HeKLEN(entry));
1242
1243             if (was_shared) {
1244                 /* Unshare it.  */
1245                 HEK * const new_hek
1246                     = save_hek_flags(HeKEY(entry), HeKLEN(entry),
1247                                      hash, HeKFLAGS(entry));
1248                 unshare_hek (HeKEY_hek(entry));
1249                 HeKEY_hek(entry) = new_hek;
1250             } else {
1251                 /* Not shared, so simply write the new hash in. */
1252                 HeHASH(entry) = hash;
1253             }
1254             /*PerlIO_printf(PerlIO_stderr(), "%d ", HeKFLAGS(entry));*/
1255             HEK_REHASH_on(HeKEY_hek(entry));
1256             /*PerlIO_printf(PerlIO_stderr(), "%d\n", HeKFLAGS(entry));*/
1257
1258             /* Copy oentry to the correct new chain.  */
1259             bep = ((HE**)a) + (hash & (I32) xhv->xhv_max);
1260             HeNEXT(entry) = *bep;
1261             *bep = entry;
1262
1263             entry = next;
1264         }
1265     }
1266     Safefree (HvARRAY(hv));
1267     HvARRAY(hv) = (HE **)a;
1268 }
1269
1270 void
1271 Perl_hv_ksplit(pTHX_ HV *hv, IV newmax)
1272 {
1273     dVAR;
1274     XPVHV* xhv = (XPVHV*)SvANY(hv);
1275     const I32 oldsize = (I32) xhv->xhv_max+1; /* HvMAX(hv)+1 (sick) */
1276     I32 newsize;
1277     I32 i;
1278     char *a;
1279     HE **aep;
1280
1281     PERL_ARGS_ASSERT_HV_KSPLIT;
1282
1283     newsize = (I32) newmax;                     /* possible truncation here */
1284     if (newsize != newmax || newmax <= oldsize)
1285         return;
1286     while ((newsize & (1 + ~newsize)) != newsize) {
1287         newsize &= ~(newsize & (1 + ~newsize)); /* get proper power of 2 */
1288     }
1289     if (newsize < newmax)
1290         newsize *= 2;
1291     if (newsize < newmax)
1292         return;                                 /* overflow detection */
1293
1294     a = (char *) HvARRAY(hv);
1295     if (a) {
1296         PL_nomemok = TRUE;
1297 #if defined(STRANGE_MALLOC) || defined(MYMALLOC)
1298         Renew(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1299               + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1300         if (!a) {
1301           PL_nomemok = FALSE;
1302           return;
1303         }
1304         if (SvOOK(hv)) {
1305             Copy(&a[oldsize * sizeof(HE*)], &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1306         }
1307 #else
1308         Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize)
1309             + (SvOOK(hv) ? sizeof(struct xpvhv_aux) : 0), char);
1310         if (!a) {
1311           PL_nomemok = FALSE;
1312           return;
1313         }
1314         Copy(HvARRAY(hv), a, oldsize * sizeof(HE*), char);
1315         if (SvOOK(hv)) {
1316             Copy(HvAUX(hv), &a[newsize * sizeof(HE*)], 1, struct xpvhv_aux);
1317         }
1318         Safefree(HvARRAY(hv));
1319 #endif
1320         PL_nomemok = FALSE;
1321         Zero(&a[oldsize * sizeof(HE*)], (newsize-oldsize) * sizeof(HE*), char); /* zero 2nd half*/
1322     }
1323     else {
1324         Newxz(a, PERL_HV_ARRAY_ALLOC_BYTES(newsize), char);
1325     }
1326     xhv->xhv_max = --newsize;   /* HvMAX(hv) = --newsize */
1327     HvARRAY(hv) = (HE **) a;
1328     if (!xhv->xhv_keys /* !HvTOTALKEYS(hv) */)  /* skip rest if no entries */
1329         return;
1330
1331     aep = (HE**)a;
1332     for (i=0; i<oldsize; i++,aep++) {
1333         HE **oentry = aep;
1334         HE *entry = *aep;
1335
1336         if (!entry)                             /* non-existent */
1337             continue;
1338         do {
1339             I32 j = (HeHASH(entry) & newsize);
1340
1341             if (j != i) {
1342                 j -= i;
1343                 *oentry = HeNEXT(entry);
1344                 HeNEXT(entry) = aep[j];
1345                 aep[j] = entry;
1346             }
1347             else
1348                 oentry = &HeNEXT(entry);
1349             entry = *oentry;
1350         } while (entry);
1351     }
1352 }
1353
1354 HV *
1355 Perl_newHVhv(pTHX_ HV *ohv)
1356 {
1357     dVAR;
1358     HV * const hv = newHV();
1359     STRLEN hv_max;
1360
1361     if (!ohv || (!HvTOTALKEYS(ohv) && !SvMAGICAL((const SV *)ohv)))
1362         return hv;
1363     hv_max = HvMAX(ohv);
1364
1365     if (!SvMAGICAL((const SV *)ohv)) {
1366         /* It's an ordinary hash, so copy it fast. AMS 20010804 */
1367         STRLEN i;
1368         const bool shared = !!HvSHAREKEYS(ohv);
1369         HE **ents, ** const oents = (HE **)HvARRAY(ohv);
1370         char *a;
1371         Newx(a, PERL_HV_ARRAY_ALLOC_BYTES(hv_max+1), char);
1372         ents = (HE**)a;
1373
1374         /* In each bucket... */
1375         for (i = 0; i <= hv_max; i++) {
1376             HE *prev = NULL;
1377             HE *oent = oents[i];
1378
1379             if (!oent) {
1380                 ents[i] = NULL;
1381                 continue;
1382             }
1383
1384             /* Copy the linked list of entries. */
1385             for (; oent; oent = HeNEXT(oent)) {
1386                 const U32 hash   = HeHASH(oent);
1387                 const char * const key = HeKEY(oent);
1388                 const STRLEN len = HeKLEN(oent);
1389                 const int flags  = HeKFLAGS(oent);
1390                 HE * const ent   = new_HE();
1391                 SV *const val    = HeVAL(oent);
1392
1393                 HeVAL(ent) = SvIMMORTAL(val) ? val : newSVsv(val);
1394                 HeKEY_hek(ent)
1395                     = shared ? share_hek_flags(key, len, hash, flags)
1396                              :  save_hek_flags(key, len, hash, flags);
1397                 if (prev)
1398                     HeNEXT(prev) = ent;
1399                 else
1400                     ents[i] = ent;
1401                 prev = ent;
1402                 HeNEXT(ent) = NULL;
1403             }
1404         }
1405
1406         HvMAX(hv)   = hv_max;
1407         HvTOTALKEYS(hv)  = HvTOTALKEYS(ohv);
1408         HvARRAY(hv) = ents;
1409     } /* not magical */
1410     else {
1411         /* Iterate over ohv, copying keys and values one at a time. */
1412         HE *entry;
1413         const I32 riter = HvRITER_get(ohv);
1414         HE * const eiter = HvEITER_get(ohv);
1415         STRLEN hv_fill = HvFILL(ohv);
1416
1417         /* Can we use fewer buckets? (hv_max is always 2^n-1) */
1418         while (hv_max && hv_max + 1 >= hv_fill * 2)
1419             hv_max = hv_max / 2;
1420         HvMAX(hv) = hv_max;
1421
1422         hv_iterinit(ohv);
1423         while ((entry = hv_iternext_flags(ohv, 0))) {
1424             SV *val = hv_iterval(ohv,entry);
1425             SV * const keysv = HeSVKEY(entry);
1426             val = SvIMMORTAL(val) ? val : newSVsv(val);
1427             if (keysv)
1428                 (void)hv_store_ent(hv, keysv, val, 0);
1429             else
1430                 (void)hv_store_flags(hv, HeKEY(entry), HeKLEN(entry), val,
1431                                  HeHASH(entry), HeKFLAGS(entry));
1432         }
1433         HvRITER_set(ohv, riter);
1434         HvEITER_set(ohv, eiter);
1435     }
1436
1437     return hv;
1438 }
1439
1440 /*
1441 =for apidoc Am|HV *|hv_copy_hints_hv|HV *ohv
1442
1443 A specialised version of L</newHVhv> for copying C<%^H>.  I<ohv> must be
1444 a pointer to a hash (which may have C<%^H> magic, but should be generally
1445 non-magical), or C<NULL> (interpreted as an empty hash).  The content
1446 of I<ohv> is copied to a new hash, which has the C<%^H>-specific magic
1447 added to it.  A pointer to the new hash is returned.
1448
1449 =cut
1450 */
1451
1452 HV *
1453 Perl_hv_copy_hints_hv(pTHX_ HV *const ohv)
1454 {
1455     HV * const hv = newHV();
1456
1457     if (ohv) {
1458         STRLEN hv_max = HvMAX(ohv);
1459         STRLEN hv_fill = HvFILL(ohv);
1460         HE *entry;
1461         const I32 riter = HvRITER_get(ohv);
1462         HE * const eiter = HvEITER_get(ohv);
1463
1464         ENTER;
1465         SAVEFREESV(hv);
1466
1467         while (hv_max && hv_max + 1 >= hv_fill * 2)
1468             hv_max = hv_max / 2;
1469         HvMAX(hv) = hv_max;
1470
1471         hv_iterinit(ohv);
1472         while ((entry = hv_iternext_flags(ohv, 0))) {
1473             SV *const sv = newSVsv(hv_iterval(ohv,entry));
1474             SV *heksv = HeSVKEY(entry);
1475             if (!heksv && sv) heksv = newSVhek(HeKEY_hek(entry));
1476             if (sv) sv_magic(sv, NULL, PERL_MAGIC_hintselem,
1477                      (char *)heksv, HEf_SVKEY);
1478             if (heksv == HeSVKEY(entry))
1479                 (void)hv_store_ent(hv, heksv, sv, 0);
1480             else {
1481                 (void)hv_common(hv, heksv, HeKEY(entry), HeKLEN(entry),
1482                                  HeKFLAGS(entry), HV_FETCH_ISSTORE|HV_FETCH_JUST_SV, sv, HeHASH(entry));
1483                 SvREFCNT_dec(heksv);
1484             }
1485         }
1486         HvRITER_set(ohv, riter);
1487         HvEITER_set(ohv, eiter);
1488
1489         SvREFCNT_inc_simple_void_NN(hv);
1490         LEAVE;
1491     }
1492     hv_magic(hv, NULL, PERL_MAGIC_hints);
1493     return hv;
1494 }
1495
1496 /* like hv_free_ent, but returns the SV rather than freeing it */
1497 STATIC SV*
1498 S_hv_free_ent_ret(pTHX_ HV *hv, register HE *entry)
1499 {
1500     dVAR;
1501     SV *val;
1502
1503     PERL_ARGS_ASSERT_HV_FREE_ENT_RET;
1504
1505     if (!entry)
1506         return NULL;
1507     val = HeVAL(entry);
1508     if (HeKLEN(entry) == HEf_SVKEY) {
1509         SvREFCNT_dec(HeKEY_sv(entry));
1510         Safefree(HeKEY_hek(entry));
1511     }
1512     else if (HvSHAREKEYS(hv))
1513         unshare_hek(HeKEY_hek(entry));
1514     else
1515         Safefree(HeKEY_hek(entry));
1516     del_HE(entry);
1517     return val;
1518 }
1519
1520
1521 void
1522 Perl_hv_free_ent(pTHX_ HV *hv, register HE *entry)
1523 {
1524     dVAR;
1525     SV *val;
1526
1527     PERL_ARGS_ASSERT_HV_FREE_ENT;
1528
1529     if (!entry)
1530         return;
1531     val = hv_free_ent_ret(hv, entry);
1532     SvREFCNT_dec(val);
1533 }
1534
1535
1536 void
1537 Perl_hv_delayfree_ent(pTHX_ HV *hv, register HE *entry)
1538 {
1539     dVAR;
1540
1541     PERL_ARGS_ASSERT_HV_DELAYFREE_ENT;
1542
1543     if (!entry)
1544         return;
1545     /* SvREFCNT_inc to counter the SvREFCNT_dec in hv_free_ent  */
1546     sv_2mortal(SvREFCNT_inc(HeVAL(entry)));     /* free between statements */
1547     if (HeKLEN(entry) == HEf_SVKEY) {
1548         sv_2mortal(SvREFCNT_inc(HeKEY_sv(entry)));
1549     }
1550     hv_free_ent(hv, entry);
1551 }
1552
1553 /*
1554 =for apidoc hv_clear
1555
1556 Frees the all the elements of a hash, leaving it empty.
1557 The XS equivalent of C<%hash = ()>.  See also L</hv_undef>.
1558
1559 If any destructors are triggered as a result, the hv itself may
1560 be freed.
1561
1562 =cut
1563 */
1564
1565 void
1566 Perl_hv_clear(pTHX_ HV *hv)
1567 {
1568     dVAR;
1569     XPVHV* xhv;
1570     if (!hv)
1571         return;
1572
1573     DEBUG_A(Perl_hv_assert(aTHX_ hv));
1574
1575     xhv = (XPVHV*)SvANY(hv);
1576
1577     ENTER;
1578     SAVEFREESV(SvREFCNT_inc_simple_NN(hv));
1579     if (SvREADONLY(hv) && HvARRAY(hv) != NULL) {
1580         /* restricted hash: convert all keys to placeholders */
1581         STRLEN i;
1582         for (i = 0; i <= xhv->xhv_max; i++) {
1583             HE *entry = (HvARRAY(hv))[i];
1584             for (; entry; entry = HeNEXT(entry)) {
1585                 /* not already placeholder */
1586                 if (HeVAL(entry) != &PL_sv_placeholder) {
1587                     if (HeVAL(entry) && SvREADONLY(HeVAL(entry))
1588                      && !SvIsCOW(HeVAL(entry))) {
1589                         SV* const keysv = hv_iterkeysv(entry);
1590                         Perl_croak(aTHX_
1591                                    "Attempt to delete readonly key '%"SVf"' from a restricted hash",
1592                                    (void*)keysv);
1593                     }
1594                     SvREFCNT_dec(HeVAL(entry));
1595                     HeVAL(entry) = &PL_sv_placeholder;
1596                     HvPLACEHOLDERS(hv)++;
1597                 }
1598             }
1599         }
1600     }
1601     else {
1602         hfreeentries(hv);
1603         HvPLACEHOLDERS_set(hv, 0);
1604
1605         if (SvRMAGICAL(hv))
1606             mg_clear(MUTABLE_SV(hv));
1607
1608         HvHASKFLAGS_off(hv);
1609         HvREHASH_off(hv);
1610     }
1611     if (SvOOK(hv)) {
1612         if(HvENAME_get(hv))
1613             mro_isa_changed_in(hv);
1614         HvEITER_set(hv, NULL);
1615     }
1616     LEAVE;
1617 }
1618
1619 /*
1620 =for apidoc hv_clear_placeholders
1621
1622 Clears any placeholders from a hash.  If a restricted hash has any of its keys
1623 marked as readonly and the key is subsequently deleted, the key is not actually
1624 deleted but is marked by assigning it a value of &PL_sv_placeholder.  This tags
1625 it so it will be ignored by future operations such as iterating over the hash,
1626 but will still allow the hash to have a value reassigned to the key at some
1627 future point.  This function clears any such placeholder keys from the hash.
1628 See Hash::Util::lock_keys() for an example of its use.
1629
1630 =cut
1631 */
1632
1633 void
1634 Perl_hv_clear_placeholders(pTHX_ HV *hv)
1635 {
1636     dVAR;
1637     const U32 items = (U32)HvPLACEHOLDERS_get(hv);
1638
1639     PERL_ARGS_ASSERT_HV_CLEAR_PLACEHOLDERS;
1640
1641     if (items)
1642         clear_placeholders(hv, items);
1643 }
1644
1645 static void
1646 S_clear_placeholders(pTHX_ HV *hv, U32 items)
1647 {
1648     dVAR;
1649     I32 i;
1650
1651     PERL_ARGS_ASSERT_CLEAR_PLACEHOLDERS;
1652
1653     if (items == 0)
1654         return;
1655
1656     i = HvMAX(hv);
1657     do {
1658         /* Loop down the linked list heads  */
1659         HE **oentry = &(HvARRAY(hv))[i];
1660         HE *entry;
1661
1662         while ((entry = *oentry)) {
1663             if (HeVAL(entry) == &PL_sv_placeholder) {
1664                 *oentry = HeNEXT(entry);
1665                 if (entry == HvEITER_get(hv))
1666                     HvLAZYDEL_on(hv);
1667                 else {
1668                     if (SvOOK(hv) && HvLAZYDEL(hv) &&
1669                         entry == HeNEXT(HvAUX(hv)->xhv_eiter))
1670                         HeNEXT(HvAUX(hv)->xhv_eiter) = HeNEXT(entry);
1671                     hv_free_ent(hv, entry);
1672                 }
1673
1674                 if (--items == 0) {
1675                     /* Finished.  */
1676                     HvTOTALKEYS(hv) -= (IV)HvPLACEHOLDERS_get(hv);
1677                     if (HvUSEDKEYS(hv) == 0)
1678                         HvHASKFLAGS_off(hv);
1679                     HvPLACEHOLDERS_set(hv, 0);
1680                     return;
1681                 }
1682             } else {
1683                 oentry = &HeNEXT(entry);
1684             }
1685         }
1686     } while (--i >= 0);
1687     /* You can't get here, hence assertion should always fail.  */
1688     assert (items == 0);
1689     assert (0);
1690 }
1691
1692 STATIC void
1693 S_hfreeentries(pTHX_ HV *hv)
1694 {
1695     STRLEN index = 0;
1696     XPVHV * const xhv = (XPVHV*)SvANY(hv);
1697     SV *sv;
1698
1699     PERL_ARGS_ASSERT_HFREEENTRIES;
1700
1701     while ((sv = Perl_hfree_next_entry(aTHX_ hv, &index))||xhv->xhv_keys) {
1702         SvREFCNT_dec(sv);
1703     }
1704 }
1705
1706
1707 /* hfree_next_entry()
1708  * For use only by S_hfreeentries() and sv_clear().
1709  * Delete the next available HE from hv and return the associated SV.
1710  * Returns null on empty hash. Nevertheless null is not a reliable
1711  * indicator that the hash is empty, as the deleted entry may have a
1712  * null value.
1713  * indexp is a pointer to the current index into HvARRAY. The index should
1714  * initially be set to 0. hfree_next_entry() may update it.  */
1715
1716 SV*
1717 Perl_hfree_next_entry(pTHX_ HV *hv, STRLEN *indexp)
1718 {
1719     struct xpvhv_aux *iter;
1720     HE *entry;
1721     HE ** array;
1722 #ifdef DEBUGGING
1723     STRLEN orig_index = *indexp;
1724 #endif
1725
1726     PERL_ARGS_ASSERT_HFREE_NEXT_ENTRY;
1727
1728     if (SvOOK(hv) && ((iter = HvAUX(hv)))
1729         && ((entry = iter->xhv_eiter)) )
1730     {
1731         /* the iterator may get resurrected after each
1732          * destructor call, so check each time */
1733         if (entry && HvLAZYDEL(hv)) {   /* was deleted earlier? */
1734             HvLAZYDEL_off(hv);
1735             hv_free_ent(hv, entry);
1736             /* warning: at this point HvARRAY may have been
1737              * re-allocated, HvMAX changed etc */
1738         }
1739         iter->xhv_riter = -1;   /* HvRITER(hv) = -1 */
1740         iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
1741     }
1742
1743     if (!((XPVHV*)SvANY(hv))->xhv_keys)
1744         return NULL;
1745
1746     array = HvARRAY(hv);
1747     assert(array);
1748     while ( ! ((entry = array[*indexp])) ) {
1749         if ((*indexp)++ >= HvMAX(hv))
1750             *indexp = 0;
1751         assert(*indexp != orig_index);
1752     }
1753     array[*indexp] = HeNEXT(entry);
1754     ((XPVHV*) SvANY(hv))->xhv_keys--;
1755
1756     if (   PL_phase != PERL_PHASE_DESTRUCT && HvENAME(hv)
1757         && HeVAL(entry) && isGV(HeVAL(entry))
1758         && GvHV(HeVAL(entry)) && HvENAME(GvHV(HeVAL(entry)))
1759     ) {
1760         STRLEN klen;
1761         const char * const key = HePV(entry,klen);
1762         if ((klen > 1 && key[klen-1]==':' && key[klen-2]==':')
1763          || (klen == 1 && key[0] == ':')) {
1764             mro_package_moved(
1765              NULL, GvHV(HeVAL(entry)),
1766              (GV *)HeVAL(entry), 0
1767             );
1768         }
1769     }
1770     return hv_free_ent_ret(hv, entry);
1771 }
1772
1773
1774 /*
1775 =for apidoc hv_undef
1776
1777 Undefines the hash.  The XS equivalent of C<undef(%hash)>.
1778
1779 As well as freeing all the elements of the hash (like hv_clear()), this
1780 also frees any auxiliary data and storage associated with the hash.
1781
1782 If any destructors are triggered as a result, the hv itself may
1783 be freed.
1784
1785 See also L</hv_clear>.
1786
1787 =cut
1788 */
1789
1790 void
1791 Perl_hv_undef_flags(pTHX_ HV *hv, U32 flags)
1792 {
1793     dVAR;
1794     XPVHV* xhv;
1795     const char *name;
1796     const bool save = !!SvREFCNT(hv);
1797
1798     if (!hv)
1799         return;
1800     DEBUG_A(Perl_hv_assert(aTHX_ hv));
1801     xhv = (XPVHV*)SvANY(hv);
1802
1803     /* The name must be deleted before the call to hfreeeeentries so that
1804        CVs are anonymised properly. But the effective name must be pre-
1805        served until after that call (and only deleted afterwards if the
1806        call originated from sv_clear). For stashes with one name that is
1807        both the canonical name and the effective name, hv_name_set has to
1808        allocate an array for storing the effective name. We can skip that
1809        during global destruction, as it does not matter where the CVs point
1810        if they will be freed anyway. */
1811     /* note that the code following prior to hfreeentries is duplicated
1812      * in sv_clear(), and changes here should be done there too */
1813     if (PL_phase != PERL_PHASE_DESTRUCT && (name = HvNAME(hv))) {
1814         if (PL_stashcache) {
1815             DEBUG_o(Perl_deb(aTHX_ "hv_undef_flags clearing PL_stashcache for '%"
1816                              HEKf"'\n", HvNAME_HEK(hv)));
1817             (void)hv_delete(PL_stashcache, name,
1818                             HEK_UTF8(HvNAME_HEK(hv)) ? -HvNAMELEN_get(hv) : HvNAMELEN_get(hv),
1819                             G_DISCARD
1820                            );
1821         }
1822         hv_name_set(hv, NULL, 0, 0);
1823     }
1824     if (save) {
1825         ENTER;
1826         SAVEFREESV(SvREFCNT_inc_simple_NN(hv));
1827     }
1828     hfreeentries(hv);
1829     if (SvOOK(hv)) {
1830       struct xpvhv_aux * const aux = HvAUX(hv);
1831       struct mro_meta *meta;
1832
1833       if ((name = HvENAME_get(hv))) {
1834         if (PL_phase != PERL_PHASE_DESTRUCT)
1835             mro_isa_changed_in(hv);
1836         if (PL_stashcache) {
1837             DEBUG_o(Perl_deb(aTHX_ "hv_undef_flags clearing PL_stashcache for effective name '%"
1838                              HEKf"'\n", HvENAME_HEK(hv)));
1839             (void)hv_delete(
1840                     PL_stashcache, name,
1841                     HEK_UTF8(HvENAME_HEK(hv)) ? -HvENAMELEN_get(hv) : HvENAMELEN_get(hv),
1842                     G_DISCARD
1843                   );
1844         }
1845       }
1846
1847       /* If this call originated from sv_clear, then we must check for
1848        * effective names that need freeing, as well as the usual name. */
1849       name = HvNAME(hv);
1850       if (flags & HV_NAME_SETALL ? !!aux->xhv_name_u.xhvnameu_name : !!name) {
1851         if (name && PL_stashcache) {
1852             DEBUG_o(Perl_deb(aTHX_ "hv_undef_flags clearing PL_stashcache for name '%"
1853                              HEKf"'\n", HvNAME_HEK(hv)));
1854             (void)hv_delete(PL_stashcache, name, (HEK_UTF8(HvNAME_HEK(hv)) ? -HvNAMELEN_get(hv) : HvNAMELEN_get(hv)), G_DISCARD);
1855         }
1856         hv_name_set(hv, NULL, 0, flags);
1857       }
1858       if((meta = aux->xhv_mro_meta)) {
1859         if (meta->mro_linear_all) {
1860             SvREFCNT_dec(MUTABLE_SV(meta->mro_linear_all));
1861             meta->mro_linear_all = NULL;
1862             /* This is just acting as a shortcut pointer.  */
1863             meta->mro_linear_current = NULL;
1864         } else if (meta->mro_linear_current) {
1865             /* Only the current MRO is stored, so this owns the data.
1866              */
1867             SvREFCNT_dec(meta->mro_linear_current);
1868             meta->mro_linear_current = NULL;
1869         }
1870         SvREFCNT_dec(meta->mro_nextmethod);
1871         SvREFCNT_dec(meta->isa);
1872         Safefree(meta);
1873         aux->xhv_mro_meta = NULL;
1874       }
1875       SvREFCNT_dec(aux->xhv_super);
1876       if (!aux->xhv_name_u.xhvnameu_name && ! aux->xhv_backreferences)
1877         SvFLAGS(hv) &= ~SVf_OOK;
1878     }
1879     if (!SvOOK(hv)) {
1880         Safefree(HvARRAY(hv));
1881         xhv->xhv_max   = 7;     /* HvMAX(hv) = 7 (it's a normal hash) */
1882         HvARRAY(hv) = 0;
1883     }
1884     /* if we're freeing the HV, the SvMAGIC field has been reused for
1885      * other purposes, and so there can't be any placeholder magic */
1886     if (SvREFCNT(hv))
1887         HvPLACEHOLDERS_set(hv, 0);
1888
1889     if (SvRMAGICAL(hv))
1890         mg_clear(MUTABLE_SV(hv));
1891     if (save) LEAVE;
1892 }
1893
1894 /*
1895 =for apidoc hv_fill
1896
1897 Returns the number of hash buckets that happen to be in use. This function is
1898 wrapped by the macro C<HvFILL>.
1899
1900 Previously this value was stored in the HV structure, rather than being
1901 calculated on demand.
1902
1903 =cut
1904 */
1905
1906 STRLEN
1907 Perl_hv_fill(pTHX_ HV const *const hv)
1908 {
1909     STRLEN count = 0;
1910     HE **ents = HvARRAY(hv);
1911
1912     PERL_ARGS_ASSERT_HV_FILL;
1913
1914     if (ents) {
1915         HE *const *const last = ents + HvMAX(hv);
1916         count = last + 1 - ents;
1917
1918         do {
1919             if (!*ents)
1920                 --count;
1921         } while (++ents <= last);
1922     }
1923     return count;
1924 }
1925
1926 static struct xpvhv_aux*
1927 S_hv_auxinit(HV *hv) {
1928     struct xpvhv_aux *iter;
1929     char *array;
1930
1931     PERL_ARGS_ASSERT_HV_AUXINIT;
1932
1933     if (!HvARRAY(hv)) {
1934         Newxz(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1935             + sizeof(struct xpvhv_aux), char);
1936     } else {
1937         array = (char *) HvARRAY(hv);
1938         Renew(array, PERL_HV_ARRAY_ALLOC_BYTES(HvMAX(hv) + 1)
1939               + sizeof(struct xpvhv_aux), char);
1940     }
1941     HvARRAY(hv) = (HE**) array;
1942     SvOOK_on(hv);
1943     iter = HvAUX(hv);
1944
1945     iter->xhv_riter = -1;       /* HvRITER(hv) = -1 */
1946     iter->xhv_eiter = NULL;     /* HvEITER(hv) = NULL */
1947     iter->xhv_name_u.xhvnameu_name = 0;
1948     iter->xhv_name_count = 0;
1949     iter->xhv_backreferences = 0;
1950     iter->xhv_mro_meta = NULL;
1951     iter->xhv_super = NULL;
1952     return iter;
1953 }
1954
1955 /*
1956 =for apidoc hv_iterinit
1957
1958 Prepares a starting point to traverse a hash table.  Returns the number of
1959 keys in the hash (i.e. the same as C<HvUSEDKEYS(hv)>).  The return value is
1960 currently only meaningful for hashes without tie magic.
1961
1962 NOTE: Before version 5.004_65, C<hv_iterinit> used to return the number of
1963 hash buckets that happen to be in use.  If you still need that esoteric
1964 value, you can get it through the macro C<HvFILL(hv)>.
1965
1966
1967 =cut
1968 */
1969
1970 I32
1971 Perl_hv_iterinit(pTHX_ HV *hv)
1972 {
1973     PERL_ARGS_ASSERT_HV_ITERINIT;
1974
1975     /* FIXME: Are we not NULL, or do we croak? Place bets now! */
1976
1977     if (!hv)
1978         Perl_croak(aTHX_ "Bad hash");
1979
1980     if (SvOOK(hv)) {
1981         struct xpvhv_aux * const iter = HvAUX(hv);
1982         HE * const entry = iter->xhv_eiter; /* HvEITER(hv) */
1983         if (entry && HvLAZYDEL(hv)) {   /* was deleted earlier? */
1984             HvLAZYDEL_off(hv);
1985             hv_free_ent(hv, entry);
1986         }
1987         iter->xhv_riter = -1;   /* HvRITER(hv) = -1 */
1988         iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
1989     } else {
1990         hv_auxinit(hv);
1991     }
1992
1993     /* used to be xhv->xhv_fill before 5.004_65 */
1994     return HvTOTALKEYS(hv);
1995 }
1996
1997 I32 *
1998 Perl_hv_riter_p(pTHX_ HV *hv) {
1999     struct xpvhv_aux *iter;
2000
2001     PERL_ARGS_ASSERT_HV_RITER_P;
2002
2003     if (!hv)
2004         Perl_croak(aTHX_ "Bad hash");
2005
2006     iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2007     return &(iter->xhv_riter);
2008 }
2009
2010 HE **
2011 Perl_hv_eiter_p(pTHX_ HV *hv) {
2012     struct xpvhv_aux *iter;
2013
2014     PERL_ARGS_ASSERT_HV_EITER_P;
2015
2016     if (!hv)
2017         Perl_croak(aTHX_ "Bad hash");
2018
2019     iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2020     return &(iter->xhv_eiter);
2021 }
2022
2023 void
2024 Perl_hv_riter_set(pTHX_ HV *hv, I32 riter) {
2025     struct xpvhv_aux *iter;
2026
2027     PERL_ARGS_ASSERT_HV_RITER_SET;
2028
2029     if (!hv)
2030         Perl_croak(aTHX_ "Bad hash");
2031
2032     if (SvOOK(hv)) {
2033         iter = HvAUX(hv);
2034     } else {
2035         if (riter == -1)
2036             return;
2037
2038         iter = hv_auxinit(hv);
2039     }
2040     iter->xhv_riter = riter;
2041 }
2042
2043 void
2044 Perl_hv_eiter_set(pTHX_ HV *hv, HE *eiter) {
2045     struct xpvhv_aux *iter;
2046
2047     PERL_ARGS_ASSERT_HV_EITER_SET;
2048
2049     if (!hv)
2050         Perl_croak(aTHX_ "Bad hash");
2051
2052     if (SvOOK(hv)) {
2053         iter = HvAUX(hv);
2054     } else {
2055         /* 0 is the default so don't go malloc()ing a new structure just to
2056            hold 0.  */
2057         if (!eiter)
2058             return;
2059
2060         iter = hv_auxinit(hv);
2061     }
2062     iter->xhv_eiter = eiter;
2063 }
2064
2065 void
2066 Perl_hv_name_set(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
2067 {
2068     dVAR;
2069     struct xpvhv_aux *iter;
2070     U32 hash;
2071     HEK **spot;
2072
2073     PERL_ARGS_ASSERT_HV_NAME_SET;
2074
2075     if (len > I32_MAX)
2076         Perl_croak(aTHX_ "panic: hv name too long (%"UVuf")", (UV) len);
2077
2078     if (SvOOK(hv)) {
2079         iter = HvAUX(hv);
2080         if (iter->xhv_name_u.xhvnameu_name) {
2081             if(iter->xhv_name_count) {
2082               if(flags & HV_NAME_SETALL) {
2083                 HEK ** const name = HvAUX(hv)->xhv_name_u.xhvnameu_names;
2084                 HEK **hekp = name + (
2085                     iter->xhv_name_count < 0
2086                      ? -iter->xhv_name_count
2087                      :  iter->xhv_name_count
2088                    );
2089                 while(hekp-- > name+1) 
2090                     unshare_hek_or_pvn(*hekp, 0, 0, 0);
2091                 /* The first elem may be null. */
2092                 if(*name) unshare_hek_or_pvn(*name, 0, 0, 0);
2093                 Safefree(name);
2094                 spot = &iter->xhv_name_u.xhvnameu_name;
2095                 iter->xhv_name_count = 0;
2096               }
2097               else {
2098                 if(iter->xhv_name_count > 0) {
2099                     /* shift some things over */
2100                     Renew(
2101                      iter->xhv_name_u.xhvnameu_names, iter->xhv_name_count + 1, HEK *
2102                     );
2103                     spot = iter->xhv_name_u.xhvnameu_names;
2104                     spot[iter->xhv_name_count] = spot[1];
2105                     spot[1] = spot[0];
2106                     iter->xhv_name_count = -(iter->xhv_name_count + 1);
2107                 }
2108                 else if(*(spot = iter->xhv_name_u.xhvnameu_names)) {
2109                     unshare_hek_or_pvn(*spot, 0, 0, 0);
2110                 }
2111               }
2112             }
2113             else if (flags & HV_NAME_SETALL) {
2114                 unshare_hek_or_pvn(iter->xhv_name_u.xhvnameu_name, 0, 0, 0);
2115                 spot = &iter->xhv_name_u.xhvnameu_name;
2116             }
2117             else {
2118                 HEK * const existing_name = iter->xhv_name_u.xhvnameu_name;
2119                 Newx(iter->xhv_name_u.xhvnameu_names, 2, HEK *);
2120                 iter->xhv_name_count = -2;
2121                 spot = iter->xhv_name_u.xhvnameu_names;
2122                 spot[1] = existing_name;
2123             }
2124         }
2125         else { spot = &iter->xhv_name_u.xhvnameu_name; iter->xhv_name_count = 0; }
2126     } else {
2127         if (name == 0)
2128             return;
2129
2130         iter = hv_auxinit(hv);
2131         spot = &iter->xhv_name_u.xhvnameu_name;
2132     }
2133     PERL_HASH(hash, name, len);
2134     *spot = name ? share_hek(name, flags & SVf_UTF8 ? -(I32)len : (I32)len, hash) : NULL;
2135 }
2136
2137 /*
2138 This is basically sv_eq_flags() in sv.c, but we avoid the magic
2139 and bytes checking.
2140 */
2141
2142 STATIC I32
2143 hek_eq_pvn_flags(pTHX_ const HEK *hek, const char* pv, const I32 pvlen, const U32 flags) {
2144     if ( (HEK_UTF8(hek) ? 1 : 0) != (flags & SVf_UTF8 ? 1 : 0) ) {
2145         if (flags & SVf_UTF8)
2146             return (bytes_cmp_utf8(
2147                         (const U8*)HEK_KEY(hek), HEK_LEN(hek),
2148                         (const U8*)pv, pvlen) == 0);
2149         else
2150             return (bytes_cmp_utf8(
2151                         (const U8*)pv, pvlen,
2152                         (const U8*)HEK_KEY(hek), HEK_LEN(hek)) == 0);
2153     }
2154     else
2155         return HEK_LEN(hek) == pvlen && ((HEK_KEY(hek) == pv)
2156                     || memEQ(HEK_KEY(hek), pv, pvlen));
2157 }
2158
2159 /*
2160 =for apidoc hv_ename_add
2161
2162 Adds a name to a stash's internal list of effective names.  See
2163 C<hv_ename_delete>.
2164
2165 This is called when a stash is assigned to a new location in the symbol
2166 table.
2167
2168 =cut
2169 */
2170
2171 void
2172 Perl_hv_ename_add(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
2173 {
2174     dVAR;
2175     struct xpvhv_aux *aux = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2176     U32 hash;
2177
2178     PERL_ARGS_ASSERT_HV_ENAME_ADD;
2179
2180     if (len > I32_MAX)
2181         Perl_croak(aTHX_ "panic: hv name too long (%"UVuf")", (UV) len);
2182
2183     PERL_HASH(hash, name, len);
2184
2185     if (aux->xhv_name_count) {
2186         HEK ** const xhv_name = aux->xhv_name_u.xhvnameu_names;
2187         I32 count = aux->xhv_name_count;
2188         HEK **hekp = xhv_name + (count < 0 ? -count : count);
2189         while (hekp-- > xhv_name)
2190             if (
2191                  (HEK_UTF8(*hekp) || (flags & SVf_UTF8)) 
2192                     ? hek_eq_pvn_flags(aTHX_ *hekp, name, (I32)len, flags)
2193                     : (HEK_LEN(*hekp) == (I32)len && memEQ(HEK_KEY(*hekp), name, len))
2194                ) {
2195                 if (hekp == xhv_name && count < 0)
2196                     aux->xhv_name_count = -count;
2197                 return;
2198             }
2199         if (count < 0) aux->xhv_name_count--, count = -count;
2200         else aux->xhv_name_count++;
2201         Renew(aux->xhv_name_u.xhvnameu_names, count + 1, HEK *);
2202         (aux->xhv_name_u.xhvnameu_names)[count] = share_hek(name, (flags & SVf_UTF8 ? -(I32)len : (I32)len), hash);
2203     }
2204     else {
2205         HEK *existing_name = aux->xhv_name_u.xhvnameu_name;
2206         if (
2207             existing_name && (
2208              (HEK_UTF8(existing_name) || (flags & SVf_UTF8))
2209                 ? hek_eq_pvn_flags(aTHX_ existing_name, name, (I32)len, flags)
2210                 : (HEK_LEN(existing_name) == (I32)len && memEQ(HEK_KEY(existing_name), name, len))
2211             )
2212         ) return;
2213         Newx(aux->xhv_name_u.xhvnameu_names, 2, HEK *);
2214         aux->xhv_name_count = existing_name ? 2 : -2;
2215         *aux->xhv_name_u.xhvnameu_names = existing_name;
2216         (aux->xhv_name_u.xhvnameu_names)[1] = share_hek(name, (flags & SVf_UTF8 ? -(I32)len : (I32)len), hash);
2217     }
2218 }
2219
2220 /*
2221 =for apidoc hv_ename_delete
2222
2223 Removes a name from a stash's internal list of effective names.  If this is
2224 the name returned by C<HvENAME>, then another name in the list will take
2225 its place (C<HvENAME> will use it).
2226
2227 This is called when a stash is deleted from the symbol table.
2228
2229 =cut
2230 */
2231
2232 void
2233 Perl_hv_ename_delete(pTHX_ HV *hv, const char *name, U32 len, U32 flags)
2234 {
2235     dVAR;
2236     struct xpvhv_aux *aux;
2237
2238     PERL_ARGS_ASSERT_HV_ENAME_DELETE;
2239
2240     if (len > I32_MAX)
2241         Perl_croak(aTHX_ "panic: hv name too long (%"UVuf")", (UV) len);
2242
2243     if (!SvOOK(hv)) return;
2244
2245     aux = HvAUX(hv);
2246     if (!aux->xhv_name_u.xhvnameu_name) return;
2247
2248     if (aux->xhv_name_count) {
2249         HEK ** const namep = aux->xhv_name_u.xhvnameu_names;
2250         I32 const count = aux->xhv_name_count;
2251         HEK **victim = namep + (count < 0 ? -count : count);
2252         while (victim-- > namep + 1)
2253             if (
2254              (HEK_UTF8(*victim) || (flags & SVf_UTF8)) 
2255                 ? hek_eq_pvn_flags(aTHX_ *victim, name, (I32)len, flags)
2256                 : (HEK_LEN(*victim) == (I32)len && memEQ(HEK_KEY(*victim), name, len))
2257             ) {
2258                 unshare_hek_or_pvn(*victim, 0, 0, 0);
2259                 if (count < 0) ++aux->xhv_name_count;
2260                 else --aux->xhv_name_count;
2261                 if (
2262                     (aux->xhv_name_count == 1 || aux->xhv_name_count == -1)
2263                  && !*namep
2264                 ) {  /* if there are none left */
2265                     Safefree(namep);
2266                     aux->xhv_name_u.xhvnameu_names = NULL;
2267                     aux->xhv_name_count = 0;
2268                 }
2269                 else {
2270                     /* Move the last one back to fill the empty slot. It
2271                        does not matter what order they are in. */
2272                     *victim = *(namep + (count < 0 ? -count : count) - 1);
2273                 }
2274                 return;
2275             }
2276         if (
2277             count > 0 && (HEK_UTF8(*namep) || (flags & SVf_UTF8)) 
2278                 ? hek_eq_pvn_flags(aTHX_ *namep, name, (I32)len, flags)
2279                 : (HEK_LEN(*namep) == (I32)len && memEQ(HEK_KEY(*namep), name, len))
2280         ) {
2281             aux->xhv_name_count = -count;
2282         }
2283     }
2284     else if(
2285         (HEK_UTF8(aux->xhv_name_u.xhvnameu_name) || (flags & SVf_UTF8)) 
2286                 ? hek_eq_pvn_flags(aTHX_ aux->xhv_name_u.xhvnameu_name, name, (I32)len, flags)
2287                 : (HEK_LEN(aux->xhv_name_u.xhvnameu_name) == (I32)len &&
2288                             memEQ(HEK_KEY(aux->xhv_name_u.xhvnameu_name), name, len))
2289     ) {
2290         HEK * const namehek = aux->xhv_name_u.xhvnameu_name;
2291         Newx(aux->xhv_name_u.xhvnameu_names, 1, HEK *);
2292         *aux->xhv_name_u.xhvnameu_names = namehek;
2293         aux->xhv_name_count = -1;
2294     }
2295 }
2296
2297 AV **
2298 Perl_hv_backreferences_p(pTHX_ HV *hv) {
2299     struct xpvhv_aux * const iter = SvOOK(hv) ? HvAUX(hv) : hv_auxinit(hv);
2300
2301     PERL_ARGS_ASSERT_HV_BACKREFERENCES_P;
2302     PERL_UNUSED_CONTEXT;
2303
2304     return &(iter->xhv_backreferences);
2305 }
2306
2307 void
2308 Perl_hv_kill_backrefs(pTHX_ HV *hv) {
2309     AV *av;
2310
2311     PERL_ARGS_ASSERT_HV_KILL_BACKREFS;
2312
2313     if (!SvOOK(hv))
2314         return;
2315
2316     av = HvAUX(hv)->xhv_backreferences;
2317
2318     if (av) {
2319         HvAUX(hv)->xhv_backreferences = 0;
2320         Perl_sv_kill_backrefs(aTHX_ MUTABLE_SV(hv), av);
2321         if (SvTYPE(av) == SVt_PVAV)
2322             SvREFCNT_dec(av);
2323     }
2324 }
2325
2326 /*
2327 hv_iternext is implemented as a macro in hv.h
2328
2329 =for apidoc hv_iternext
2330
2331 Returns entries from a hash iterator.  See C<hv_iterinit>.
2332
2333 You may call C<hv_delete> or C<hv_delete_ent> on the hash entry that the
2334 iterator currently points to, without losing your place or invalidating your
2335 iterator.  Note that in this case the current entry is deleted from the hash
2336 with your iterator holding the last reference to it.  Your iterator is flagged
2337 to free the entry on the next call to C<hv_iternext>, so you must not discard
2338 your iterator immediately else the entry will leak - call C<hv_iternext> to
2339 trigger the resource deallocation.
2340
2341 =for apidoc hv_iternext_flags
2342
2343 Returns entries from a hash iterator.  See C<hv_iterinit> and C<hv_iternext>.
2344 The C<flags> value will normally be zero; if HV_ITERNEXT_WANTPLACEHOLDERS is
2345 set the placeholders keys (for restricted hashes) will be returned in addition
2346 to normal keys. By default placeholders are automatically skipped over.
2347 Currently a placeholder is implemented with a value that is
2348 C<&PL_sv_placeholder>.  Note that the implementation of placeholders and
2349 restricted hashes may change, and the implementation currently is
2350 insufficiently abstracted for any change to be tidy.
2351
2352 =cut
2353 */
2354
2355 HE *
2356 Perl_hv_iternext_flags(pTHX_ HV *hv, I32 flags)
2357 {
2358     dVAR;
2359     XPVHV* xhv;
2360     HE *entry;
2361     HE *oldentry;
2362     MAGIC* mg;
2363     struct xpvhv_aux *iter;
2364
2365     PERL_ARGS_ASSERT_HV_ITERNEXT_FLAGS;
2366
2367     if (!hv)
2368         Perl_croak(aTHX_ "Bad hash");
2369
2370     xhv = (XPVHV*)SvANY(hv);
2371
2372     if (!SvOOK(hv)) {
2373         /* Too many things (well, pp_each at least) merrily assume that you can
2374            call hv_iternext without calling hv_iterinit, so we'll have to deal
2375            with it.  */
2376         hv_iterinit(hv);
2377     }
2378     iter = HvAUX(hv);
2379
2380     oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
2381     if (SvMAGICAL(hv) && SvRMAGICAL(hv)) {
2382         if ( ( mg = mg_find((const SV *)hv, PERL_MAGIC_tied) ) ) {
2383             SV * const key = sv_newmortal();
2384             if (entry) {
2385                 sv_setsv(key, HeSVKEY_force(entry));
2386                 SvREFCNT_dec(HeSVKEY(entry));       /* get rid of previous key */
2387                 HeSVKEY_set(entry, NULL);
2388             }
2389             else {
2390                 char *k;
2391                 HEK *hek;
2392
2393                 /* one HE per MAGICAL hash */
2394                 iter->xhv_eiter = entry = new_HE(); /* HvEITER(hv) = new_HE() */
2395                 HvLAZYDEL_on(hv); /* make sure entry gets freed */
2396                 Zero(entry, 1, HE);
2397                 Newxz(k, HEK_BASESIZE + sizeof(const SV *), char);
2398                 hek = (HEK*)k;
2399                 HeKEY_hek(entry) = hek;
2400                 HeKLEN(entry) = HEf_SVKEY;
2401             }
2402             magic_nextpack(MUTABLE_SV(hv),mg,key);
2403             if (SvOK(key)) {
2404                 /* force key to stay around until next time */
2405                 HeSVKEY_set(entry, SvREFCNT_inc_simple_NN(key));
2406                 return entry;               /* beware, hent_val is not set */
2407             }
2408             SvREFCNT_dec(HeVAL(entry));
2409             Safefree(HeKEY_hek(entry));
2410             del_HE(entry);
2411             iter->xhv_eiter = NULL; /* HvEITER(hv) = NULL */
2412             HvLAZYDEL_off(hv);
2413             return NULL;
2414         }
2415     }
2416 #if defined(DYNAMIC_ENV_FETCH) && !defined(__riscos__)  /* set up %ENV for iteration */
2417     if (!entry && SvRMAGICAL((const SV *)hv)
2418         && mg_find((const SV *)hv, PERL_MAGIC_env)) {
2419         prime_env_iter();
2420 #ifdef VMS
2421         /* The prime_env_iter() on VMS just loaded up new hash values
2422          * so the iteration count needs to be reset back to the beginning
2423          */
2424         hv_iterinit(hv);
2425         iter = HvAUX(hv);
2426         oldentry = entry = iter->xhv_eiter; /* HvEITER(hv) */
2427 #endif
2428     }
2429 #endif
2430
2431     /* hv_iterinit now ensures this.  */
2432     assert (HvARRAY(hv));
2433
2434     /* At start of hash, entry is NULL.  */
2435     if (entry)
2436     {
2437         entry = HeNEXT(entry);
2438         if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2439             /*
2440              * Skip past any placeholders -- don't want to include them in
2441              * any iteration.
2442              */
2443             while (entry && HeVAL(entry) == &PL_sv_placeholder) {
2444                 entry = HeNEXT(entry);
2445             }
2446         }
2447     }
2448
2449     /* Skip the entire loop if the hash is empty.   */
2450     if ((flags & HV_ITERNEXT_WANTPLACEHOLDERS)
2451         ? HvTOTALKEYS(hv) : HvUSEDKEYS(hv)) {
2452         while (!entry) {
2453             /* OK. Come to the end of the current list.  Grab the next one.  */
2454
2455             iter->xhv_riter++; /* HvRITER(hv)++ */
2456             if (iter->xhv_riter > (I32)xhv->xhv_max /* HvRITER(hv) > HvMAX(hv) */) {
2457                 /* There is no next one.  End of the hash.  */
2458                 iter->xhv_riter = -1; /* HvRITER(hv) = -1 */
2459                 break;
2460             }
2461             entry = (HvARRAY(hv))[iter->xhv_riter];
2462
2463             if (!(flags & HV_ITERNEXT_WANTPLACEHOLDERS)) {
2464                 /* If we have an entry, but it's a placeholder, don't count it.
2465                    Try the next.  */
2466                 while (entry && HeVAL(entry) == &PL_sv_placeholder)
2467                     entry = HeNEXT(entry);
2468             }
2469             /* Will loop again if this linked list starts NULL
2470                (for HV_ITERNEXT_WANTPLACEHOLDERS)
2471                or if we run through it and find only placeholders.  */
2472         }
2473     }
2474     else iter->xhv_riter = -1;
2475
2476     if (oldentry && HvLAZYDEL(hv)) {            /* was deleted earlier? */
2477         HvLAZYDEL_off(hv);
2478         hv_free_ent(hv, oldentry);
2479     }
2480
2481     /*if (HvREHASH(hv) && entry && !HeKREHASH(entry))
2482       PerlIO_printf(PerlIO_stderr(), "Awooga %p %p\n", (void*)hv, (void*)entry);*/
2483
2484     iter->xhv_eiter = entry; /* HvEITER(hv) = entry */
2485     return entry;
2486 }
2487
2488 /*
2489 =for apidoc hv_iterkey
2490
2491 Returns the key from the current position of the hash iterator.  See
2492 C<hv_iterinit>.
2493
2494 =cut
2495 */
2496
2497 char *
2498 Perl_hv_iterkey(pTHX_ register HE *entry, I32 *retlen)
2499 {
2500     PERL_ARGS_ASSERT_HV_ITERKEY;
2501
2502     if (HeKLEN(entry) == HEf_SVKEY) {
2503         STRLEN len;
2504         char * const p = SvPV(HeKEY_sv(entry), len);
2505         *retlen = len;
2506         return p;
2507     }
2508     else {
2509         *retlen = HeKLEN(entry);
2510         return HeKEY(entry);
2511     }
2512 }
2513
2514 /* unlike hv_iterval(), this always returns a mortal copy of the key */
2515 /*
2516 =for apidoc hv_iterkeysv
2517
2518 Returns the key as an C<SV*> from the current position of the hash
2519 iterator.  The return value will always be a mortal copy of the key.  Also
2520 see C<hv_iterinit>.
2521
2522 =cut
2523 */
2524
2525 SV *
2526 Perl_hv_iterkeysv(pTHX_ register HE *entry)
2527 {
2528     PERL_ARGS_ASSERT_HV_ITERKEYSV;
2529
2530     return sv_2mortal(newSVhek(HeKEY_hek(entry)));
2531 }
2532
2533 /*
2534 =for apidoc hv_iterval
2535
2536 Returns the value from the current position of the hash iterator.  See
2537 C<hv_iterkey>.
2538
2539 =cut
2540 */
2541
2542 SV *
2543 Perl_hv_iterval(pTHX_ HV *hv, register HE *entry)
2544 {
2545     PERL_ARGS_ASSERT_HV_ITERVAL;
2546
2547     if (SvRMAGICAL(hv)) {
2548         if (mg_find((const SV *)hv, PERL_MAGIC_tied)) {
2549             SV* const sv = sv_newmortal();
2550             if (HeKLEN(entry) == HEf_SVKEY)
2551                 mg_copy(MUTABLE_SV(hv), sv, (char*)HeKEY_sv(entry), HEf_SVKEY);
2552             else
2553                 mg_copy(MUTABLE_SV(hv), sv, HeKEY(entry), HeKLEN(entry));
2554             return sv;
2555         }
2556     }
2557     return HeVAL(entry);
2558 }
2559
2560 /*
2561 =for apidoc hv_iternextsv
2562
2563 Performs an C<hv_iternext>, C<hv_iterkey>, and C<hv_iterval> in one
2564 operation.
2565
2566 =cut
2567 */
2568
2569 SV *
2570 Perl_hv_iternextsv(pTHX_ HV *hv, char **key, I32 *retlen)
2571 {
2572     HE * const he = hv_iternext_flags(hv, 0);
2573
2574     PERL_ARGS_ASSERT_HV_ITERNEXTSV;
2575
2576     if (!he)
2577         return NULL;
2578     *key = hv_iterkey(he, retlen);
2579     return hv_iterval(hv, he);
2580 }
2581
2582 /*
2583
2584 Now a macro in hv.h
2585
2586 =for apidoc hv_magic
2587
2588 Adds magic to a hash.  See C<sv_magic>.
2589
2590 =cut
2591 */
2592
2593 /* possibly free a shared string if no one has access to it
2594  * len and hash must both be valid for str.
2595  */
2596 void
2597 Perl_unsharepvn(pTHX_ const char *str, I32 len, U32 hash)
2598 {
2599     unshare_hek_or_pvn (NULL, str, len, hash);
2600 }
2601
2602
2603 void
2604 Perl_unshare_hek(pTHX_ HEK *hek)
2605 {
2606     assert(hek);
2607     unshare_hek_or_pvn(hek, NULL, 0, 0);
2608 }
2609
2610 /* possibly free a shared string if no one has access to it
2611    hek if non-NULL takes priority over the other 3, else str, len and hash
2612    are used.  If so, len and hash must both be valid for str.
2613  */
2614 STATIC void
2615 S_unshare_hek_or_pvn(pTHX_ const HEK *hek, const char *str, I32 len, U32 hash)
2616 {
2617     dVAR;
2618     XPVHV* xhv;
2619     HE *entry;
2620     HE **oentry;
2621     bool is_utf8 = FALSE;
2622     int k_flags = 0;
2623     const char * const save = str;
2624     struct shared_he *he = NULL;
2625
2626     if (hek) {
2627         /* Find the shared he which is just before us in memory.  */
2628         he = (struct shared_he *)(((char *)hek)
2629                                   - STRUCT_OFFSET(struct shared_he,
2630                                                   shared_he_hek));
2631
2632         /* Assert that the caller passed us a genuine (or at least consistent)
2633            shared hek  */
2634         assert (he->shared_he_he.hent_hek == hek);
2635
2636         if (he->shared_he_he.he_valu.hent_refcount - 1) {
2637             --he->shared_he_he.he_valu.hent_refcount;
2638             return;
2639         }
2640
2641         hash = HEK_HASH(hek);
2642     } else if (len < 0) {
2643         STRLEN tmplen = -len;
2644         is_utf8 = TRUE;
2645         /* See the note in hv_fetch(). --jhi */
2646         str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2647         len = tmplen;
2648         if (is_utf8)
2649             k_flags = HVhek_UTF8;
2650         if (str != save)
2651             k_flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2652     }
2653
2654     /* what follows was the moral equivalent of:
2655     if ((Svp = hv_fetch(PL_strtab, tmpsv, FALSE, hash))) {
2656         if (--*Svp == NULL)
2657             hv_delete(PL_strtab, str, len, G_DISCARD, hash);
2658     } */
2659     xhv = (XPVHV*)SvANY(PL_strtab);
2660     /* assert(xhv_array != 0) */
2661     oentry = &(HvARRAY(PL_strtab))[hash & (I32) HvMAX(PL_strtab)];
2662     if (he) {
2663         const HE *const he_he = &(he->shared_he_he);
2664         for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2665             if (entry == he_he)
2666                 break;
2667         }
2668     } else {
2669         const int flags_masked = k_flags & HVhek_MASK;
2670         for (entry = *oentry; entry; oentry = &HeNEXT(entry), entry = *oentry) {
2671             if (HeHASH(entry) != hash)          /* strings can't be equal */
2672                 continue;
2673             if (HeKLEN(entry) != len)
2674                 continue;
2675             if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len))     /* is this it? */
2676                 continue;
2677             if (HeKFLAGS(entry) != flags_masked)
2678                 continue;
2679             break;
2680         }
2681     }
2682
2683     if (entry) {
2684         if (--entry->he_valu.hent_refcount == 0) {
2685             *oentry = HeNEXT(entry);
2686             Safefree(entry);
2687             xhv->xhv_keys--; /* HvTOTALKEYS(hv)-- */
2688         }
2689     }
2690
2691     if (!entry)
2692         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
2693                          "Attempt to free nonexistent shared string '%s'%s"
2694                          pTHX__FORMAT,
2695                          hek ? HEK_KEY(hek) : str,
2696                          ((k_flags & HVhek_UTF8) ? " (utf8)" : "") pTHX__VALUE);
2697     if (k_flags & HVhek_FREEKEY)
2698         Safefree(str);
2699 }
2700
2701 /* get a (constant) string ptr from the global string table
2702  * string will get added if it is not already there.
2703  * len and hash must both be valid for str.
2704  */
2705 HEK *
2706 Perl_share_hek(pTHX_ const char *str, I32 len, register U32 hash)
2707 {
2708     bool is_utf8 = FALSE;
2709     int flags = 0;
2710     const char * const save = str;
2711
2712     PERL_ARGS_ASSERT_SHARE_HEK;
2713
2714     if (len < 0) {
2715       STRLEN tmplen = -len;
2716       is_utf8 = TRUE;
2717       /* See the note in hv_fetch(). --jhi */
2718       str = (char*)bytes_from_utf8((U8*)str, &tmplen, &is_utf8);
2719       len = tmplen;
2720       /* If we were able to downgrade here, then than means that we were passed
2721          in a key which only had chars 0-255, but was utf8 encoded.  */
2722       if (is_utf8)
2723           flags = HVhek_UTF8;
2724       /* If we found we were able to downgrade the string to bytes, then
2725          we should flag that it needs upgrading on keys or each.  Also flag
2726          that we need share_hek_flags to free the string.  */
2727       if (str != save) {
2728           PERL_HASH(hash, str, len);
2729           flags |= HVhek_WASUTF8 | HVhek_FREEKEY;
2730       }
2731     }
2732
2733     return share_hek_flags (str, len, hash, flags);
2734 }
2735
2736 STATIC HEK *
2737 S_share_hek_flags(pTHX_ const char *str, I32 len, register U32 hash, int flags)
2738 {
2739     dVAR;
2740     HE *entry;
2741     const int flags_masked = flags & HVhek_MASK;
2742     const U32 hindex = hash & (I32) HvMAX(PL_strtab);
2743     XPVHV * const xhv = (XPVHV*)SvANY(PL_strtab);
2744
2745     PERL_ARGS_ASSERT_SHARE_HEK_FLAGS;
2746
2747     /* what follows is the moral equivalent of:
2748
2749     if (!(Svp = hv_fetch(PL_strtab, str, len, FALSE)))
2750         hv_store(PL_strtab, str, len, NULL, hash);
2751
2752         Can't rehash the shared string table, so not sure if it's worth
2753         counting the number of entries in the linked list
2754     */
2755
2756     /* assert(xhv_array != 0) */
2757     entry = (HvARRAY(PL_strtab))[hindex];
2758     for (;entry; entry = HeNEXT(entry)) {
2759         if (HeHASH(entry) != hash)              /* strings can't be equal */
2760             continue;
2761         if (HeKLEN(entry) != len)
2762             continue;
2763         if (HeKEY(entry) != str && memNE(HeKEY(entry),str,len)) /* is this it? */
2764             continue;
2765         if (HeKFLAGS(entry) != flags_masked)
2766             continue;
2767         break;
2768     }
2769
2770     if (!entry) {
2771         /* What used to be head of the list.
2772            If this is NULL, then we're the first entry for this slot, which
2773            means we need to increate fill.  */
2774         struct shared_he *new_entry;
2775         HEK *hek;
2776         char *k;
2777         HE **const head = &HvARRAY(PL_strtab)[hindex];
2778         HE *const next = *head;
2779
2780         /* We don't actually store a HE from the arena and a regular HEK.
2781            Instead we allocate one chunk of memory big enough for both,
2782            and put the HEK straight after the HE. This way we can find the
2783            HE directly from the HEK.
2784         */
2785
2786         Newx(k, STRUCT_OFFSET(struct shared_he,
2787                                 shared_he_hek.hek_key[0]) + len + 2, char);
2788         new_entry = (struct shared_he *)k;
2789         entry = &(new_entry->shared_he_he);
2790         hek = &(new_entry->shared_he_hek);
2791
2792         Copy(str, HEK_KEY(hek), len, char);
2793         HEK_KEY(hek)[len] = 0;
2794         HEK_LEN(hek) = len;
2795         HEK_HASH(hek) = hash;
2796         HEK_FLAGS(hek) = (unsigned char)flags_masked;
2797
2798         /* Still "point" to the HEK, so that other code need not know what
2799            we're up to.  */
2800         HeKEY_hek(entry) = hek;
2801         entry->he_valu.hent_refcount = 0;
2802         HeNEXT(entry) = next;
2803         *head = entry;
2804
2805         xhv->xhv_keys++; /* HvTOTALKEYS(hv)++ */
2806         if (!next) {                    /* initial entry? */
2807         } else if (xhv->xhv_keys > xhv->xhv_max /* HvUSEDKEYS(hv) > HvMAX(hv) */) {
2808                 hsplit(PL_strtab);
2809         }
2810     }
2811
2812     ++entry->he_valu.hent_refcount;
2813
2814     if (flags & HVhek_FREEKEY)
2815         Safefree(str);
2816
2817     return HeKEY_hek(entry);
2818 }
2819
2820 I32 *
2821 Perl_hv_placeholders_p(pTHX_ HV *hv)
2822 {
2823     dVAR;
2824     MAGIC *mg = mg_find((const SV *)hv, PERL_MAGIC_rhash);
2825
2826     PERL_ARGS_ASSERT_HV_PLACEHOLDERS_P;
2827
2828     if (!mg) {
2829         mg = sv_magicext(MUTABLE_SV(hv), 0, PERL_MAGIC_rhash, 0, 0, 0);
2830
2831         if (!mg) {
2832             Perl_die(aTHX_ "panic: hv_placeholders_p");
2833         }
2834     }
2835     return &(mg->mg_len);
2836 }
2837
2838
2839 I32
2840 Perl_hv_placeholders_get(pTHX_ const HV *hv)
2841 {
2842     dVAR;
2843     MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_rhash);
2844
2845     PERL_ARGS_ASSERT_HV_PLACEHOLDERS_GET;
2846
2847     return mg ? mg->mg_len : 0;
2848 }
2849
2850 void
2851 Perl_hv_placeholders_set(pTHX_ HV *hv, I32 ph)
2852 {
2853     dVAR;
2854     MAGIC * const mg = mg_find((const SV *)hv, PERL_MAGIC_rhash);
2855
2856     PERL_ARGS_ASSERT_HV_PLACEHOLDERS_SET;
2857
2858     if (mg) {
2859         mg->mg_len = ph;
2860     } else if (ph) {
2861         if (!sv_magicext(MUTABLE_SV(hv), 0, PERL_MAGIC_rhash, 0, 0, ph))
2862             Perl_die(aTHX_ "panic: hv_placeholders_set");
2863     }
2864     /* else we don't need to add magic to record 0 placeholders.  */
2865 }
2866
2867 STATIC SV *
2868 S_refcounted_he_value(pTHX_ const struct refcounted_he *he)
2869 {
2870     dVAR;
2871     SV *value;
2872
2873     PERL_ARGS_ASSERT_REFCOUNTED_HE_VALUE;
2874
2875     switch(he->refcounted_he_data[0] & HVrhek_typemask) {
2876     case HVrhek_undef:
2877         value = newSV(0);
2878         break;
2879     case HVrhek_delete:
2880         value = &PL_sv_placeholder;
2881         break;
2882     case HVrhek_IV:
2883         value = newSViv(he->refcounted_he_val.refcounted_he_u_iv);
2884         break;
2885     case HVrhek_UV:
2886         value = newSVuv(he->refcounted_he_val.refcounted_he_u_uv);
2887         break;
2888     case HVrhek_PV:
2889     case HVrhek_PV_UTF8:
2890         /* Create a string SV that directly points to the bytes in our
2891            structure.  */
2892         value = newSV_type(SVt_PV);
2893         SvPV_set(value, (char *) he->refcounted_he_data + 1);
2894         SvCUR_set(value, he->refcounted_he_val.refcounted_he_u_len);
2895         /* This stops anything trying to free it  */
2896         SvLEN_set(value, 0);
2897         SvPOK_on(value);
2898         SvREADONLY_on(value);
2899         if ((he->refcounted_he_data[0] & HVrhek_typemask) == HVrhek_PV_UTF8)
2900             SvUTF8_on(value);
2901         break;
2902     default:
2903         Perl_croak(aTHX_ "panic: refcounted_he_value bad flags %"UVxf,
2904                    (UV)he->refcounted_he_data[0]);
2905     }
2906     return value;
2907 }
2908
2909 /*
2910 =for apidoc m|HV *|refcounted_he_chain_2hv|const struct refcounted_he *c|U32 flags
2911
2912 Generates and returns a C<HV *> representing the content of a
2913 C<refcounted_he> chain.
2914 I<flags> is currently unused and must be zero.
2915
2916 =cut
2917 */
2918 HV *
2919 Perl_refcounted_he_chain_2hv(pTHX_ const struct refcounted_he *chain, U32 flags)
2920 {
2921     dVAR;
2922     HV *hv;
2923     U32 placeholders, max;
2924
2925     if (flags)
2926         Perl_croak(aTHX_ "panic: refcounted_he_chain_2hv bad flags %"UVxf,
2927             (UV)flags);
2928
2929     /* We could chase the chain once to get an idea of the number of keys,
2930        and call ksplit.  But for now we'll make a potentially inefficient
2931        hash with only 8 entries in its array.  */
2932     hv = newHV();
2933     max = HvMAX(hv);
2934     if (!HvARRAY(hv)) {
2935         char *array;
2936         Newxz(array, PERL_HV_ARRAY_ALLOC_BYTES(max + 1), char);
2937         HvARRAY(hv) = (HE**)array;
2938     }
2939
2940     placeholders = 0;
2941     while (chain) {
2942 #ifdef USE_ITHREADS
2943         U32 hash = chain->refcounted_he_hash;
2944 #else
2945         U32 hash = HEK_HASH(chain->refcounted_he_hek);
2946 #endif
2947         HE **oentry = &((HvARRAY(hv))[hash & max]);
2948         HE *entry = *oentry;
2949         SV *value;
2950
2951         for (; entry; entry = HeNEXT(entry)) {
2952             if (HeHASH(entry) == hash) {
2953                 /* We might have a duplicate key here.  If so, entry is older
2954                    than the key we've already put in the hash, so if they are
2955                    the same, skip adding entry.  */
2956 #ifdef USE_ITHREADS
2957                 const STRLEN klen = HeKLEN(entry);
2958                 const char *const key = HeKEY(entry);
2959                 if (klen == chain->refcounted_he_keylen
2960                     && (!!HeKUTF8(entry)
2961                         == !!(chain->refcounted_he_data[0] & HVhek_UTF8))
2962                     && memEQ(key, REF_HE_KEY(chain), klen))
2963                     goto next_please;
2964 #else
2965                 if (HeKEY_hek(entry) == chain->refcounted_he_hek)
2966                     goto next_please;
2967                 if (HeKLEN(entry) == HEK_LEN(chain->refcounted_he_hek)
2968                     && HeKUTF8(entry) == HEK_UTF8(chain->refcounted_he_hek)
2969                     && memEQ(HeKEY(entry), HEK_KEY(chain->refcounted_he_hek),
2970                              HeKLEN(entry)))
2971                     goto next_please;
2972 #endif
2973             }
2974         }
2975         assert (!entry);
2976         entry = new_HE();
2977
2978 #ifdef USE_ITHREADS
2979         HeKEY_hek(entry)
2980             = share_hek_flags(REF_HE_KEY(chain),
2981                               chain->refcounted_he_keylen,
2982                               chain->refcounted_he_hash,
2983                               (chain->refcounted_he_data[0]
2984                                & (HVhek_UTF8|HVhek_WASUTF8)));
2985 #else
2986         HeKEY_hek(entry) = share_hek_hek(chain->refcounted_he_hek);
2987 #endif
2988         value = refcounted_he_value(chain);
2989         if (value == &PL_sv_placeholder)
2990             placeholders++;
2991         HeVAL(entry) = value;
2992
2993         /* Link it into the chain.  */
2994         HeNEXT(entry) = *oentry;
2995         *oentry = entry;
2996
2997         HvTOTALKEYS(hv)++;
2998
2999     next_please:
3000         chain = chain->refcounted_he_next;
3001     }
3002
3003     if (placeholders) {
3004         clear_placeholders(hv, placeholders);
3005         HvTOTALKEYS(hv) -= placeholders;
3006     }
3007
3008     /* We could check in the loop to see if we encounter any keys with key
3009        flags, but it's probably not worth it, as this per-hash flag is only
3010        really meant as an optimisation for things like Storable.  */
3011     HvHASKFLAGS_on(hv);
3012     DEBUG_A(Perl_hv_assert(aTHX_ hv));
3013
3014     return hv;
3015 }
3016
3017 /*
3018 =for apidoc m|SV *|refcounted_he_fetch_pvn|const struct refcounted_he *chain|const char *keypv|STRLEN keylen|U32 hash|U32 flags
3019
3020 Search along a C<refcounted_he> chain for an entry with the key specified
3021 by I<keypv> and I<keylen>.  If I<flags> has the C<REFCOUNTED_HE_KEY_UTF8>
3022 bit set, the key octets are interpreted as UTF-8, otherwise they
3023 are interpreted as Latin-1.  I<hash> is a precomputed hash of the key
3024 string, or zero if it has not been precomputed.  Returns a mortal scalar
3025 representing the value associated with the key, or C<&PL_sv_placeholder>
3026 if there is no value associated with the key.
3027
3028 =cut
3029 */
3030
3031 SV *
3032 Perl_refcounted_he_fetch_pvn(pTHX_ const struct refcounted_he *chain,
3033                          const char *keypv, STRLEN keylen, U32 hash, U32 flags)
3034 {
3035     dVAR;
3036     U8 utf8_flag;
3037     PERL_ARGS_ASSERT_REFCOUNTED_HE_FETCH_PVN;
3038
3039     if (flags & ~(REFCOUNTED_HE_KEY_UTF8|REFCOUNTED_HE_EXISTS))
3040         Perl_croak(aTHX_ "panic: refcounted_he_fetch_pvn bad flags %"UVxf,
3041             (UV)flags);
3042     if (!chain)
3043         return &PL_sv_placeholder;
3044     if (flags & REFCOUNTED_HE_KEY_UTF8) {
3045         /* For searching purposes, canonicalise to Latin-1 where possible. */
3046         const char *keyend = keypv + keylen, *p;
3047         STRLEN nonascii_count = 0;
3048         for (p = keypv; p != keyend; p++) {
3049             U8 c = (U8)*p;
3050             if (c & 0x80) {
3051                 if (!((c & 0xfe) == 0xc2 && ++p != keyend &&
3052                             (((U8)*p) & 0xc0) == 0x80))
3053                     goto canonicalised_key;
3054                 nonascii_count++;
3055             }
3056         }
3057         if (nonascii_count) {
3058             char *q;
3059             const char *p = keypv, *keyend = keypv + keylen;
3060             keylen -= nonascii_count;
3061             Newx(q, keylen, char);
3062             SAVEFREEPV(q);
3063             keypv = q;
3064             for (; p != keyend; p++, q++) {
3065                 U8 c = (U8)*p;
3066                 *q = (char)
3067                     ((c & 0x80) ? ((c & 0x03) << 6) | (((U8)*++p) & 0x3f) : c);
3068             }
3069         }
3070         flags &= ~REFCOUNTED_HE_KEY_UTF8;
3071         canonicalised_key: ;
3072     }
3073     utf8_flag = (flags & REFCOUNTED_HE_KEY_UTF8) ? HVhek_UTF8 : 0;
3074     if (!hash)
3075         PERL_HASH(hash, keypv, keylen);
3076
3077     for (; chain; chain = chain->refcounted_he_next) {
3078         if (
3079 #ifdef USE_ITHREADS
3080             hash == chain->refcounted_he_hash &&
3081             keylen == chain->refcounted_he_keylen &&
3082             memEQ(REF_HE_KEY(chain), keypv, keylen) &&
3083             utf8_flag == (chain->refcounted_he_data[0] & HVhek_UTF8)
3084 #else
3085             hash == HEK_HASH(chain->refcounted_he_hek) &&
3086             keylen == (STRLEN)HEK_LEN(chain->refcounted_he_hek) &&
3087             memEQ(HEK_KEY(chain->refcounted_he_hek), keypv, keylen) &&
3088             utf8_flag == (HEK_FLAGS(chain->refcounted_he_hek) & HVhek_UTF8)
3089 #endif
3090         ) {
3091             if (flags & REFCOUNTED_HE_EXISTS)
3092                 return (chain->refcounted_he_data[0] & HVrhek_typemask)
3093                     == HVrhek_delete
3094                     ? NULL : &PL_sv_yes;
3095             return sv_2mortal(refcounted_he_value(chain));
3096         }
3097     }
3098     return flags & REFCOUNTED_HE_EXISTS ? NULL : &PL_sv_placeholder;
3099 }
3100
3101 /*
3102 =for apidoc m|SV *|refcounted_he_fetch_pv|const struct refcounted_he *chain|const char *key|U32 hash|U32 flags
3103
3104 Like L</refcounted_he_fetch_pvn>, but takes a nul-terminated string
3105 instead of a string/length pair.
3106
3107 =cut
3108 */
3109
3110 SV *
3111 Perl_refcounted_he_fetch_pv(pTHX_ const struct refcounted_he *chain,
3112                          const char *key, U32 hash, U32 flags)
3113 {
3114     PERL_ARGS_ASSERT_REFCOUNTED_HE_FETCH_PV;
3115     return refcounted_he_fetch_pvn(chain, key, strlen(key), hash, flags);
3116 }
3117
3118 /*
3119 =for apidoc m|SV *|refcounted_he_fetch_sv|const struct refcounted_he *chain|SV *key|U32 hash|U32 flags
3120
3121 Like L</refcounted_he_fetch_pvn>, but takes a Perl scalar instead of a
3122 string/length pair.
3123
3124 =cut
3125 */
3126
3127 SV *
3128 Perl_refcounted_he_fetch_sv(pTHX_ const struct refcounted_he *chain,
3129                          SV *key, U32 hash, U32 flags)
3130 {
3131     const char *keypv;
3132     STRLEN keylen;
3133     PERL_ARGS_ASSERT_REFCOUNTED_HE_FETCH_SV;
3134     if (flags & REFCOUNTED_HE_KEY_UTF8)
3135         Perl_croak(aTHX_ "panic: refcounted_he_fetch_sv bad flags %"UVxf,
3136             (UV)flags);
3137     keypv = SvPV_const(key, keylen);
3138     if (SvUTF8(key))
3139         flags |= REFCOUNTED_HE_KEY_UTF8;
3140     if (!hash && SvIsCOW_shared_hash(key))
3141         hash = SvSHARED_HASH(key);
3142     return refcounted_he_fetch_pvn(chain, keypv, keylen, hash, flags);
3143 }
3144
3145 /*
3146 =for apidoc m|struct refcounted_he *|refcounted_he_new_pvn|struct refcounted_he *parent|const char *keypv|STRLEN keylen|U32 hash|SV *value|U32 flags
3147
3148 Creates a new C<refcounted_he>.  This consists of a single key/value
3149 pair and a reference to an existing C<refcounted_he> chain (which may
3150 be empty), and thus forms a longer chain.  When using the longer chain,
3151 the new key/value pair takes precedence over any entry for the same key
3152 further along the chain.
3153
3154 The new key is specified by I<keypv> and I<keylen>.  If I<flags> has
3155 the C<REFCOUNTED_HE_KEY_UTF8> bit set, the key octets are interpreted
3156 as UTF-8, otherwise they are interpreted as Latin-1.  I<hash> is
3157 a precomputed hash of the key string, or zero if it has not been
3158 precomputed.
3159
3160 I<value> is the scalar value to store for this key.  I<value> is copied
3161 by this function, which thus does not take ownership of any reference
3162 to it, and later changes to the scalar will not be reflected in the
3163 value visible in the C<refcounted_he>.  Complex types of scalar will not
3164 be stored with referential integrity, but will be coerced to strings.
3165 I<value> may be either null or C<&PL_sv_placeholder> to indicate that no
3166 value is to be associated with the key; this, as with any non-null value,
3167 takes precedence over the existence of a value for the key further along
3168 the chain.
3169
3170 I<parent> points to the rest of the C<refcounted_he> chain to be
3171 attached to the new C<refcounted_he>.  This function takes ownership
3172 of one reference to I<parent>, and returns one reference to the new
3173 C<refcounted_he>.
3174
3175 =cut
3176 */
3177
3178 struct refcounted_he *
3179 Perl_refcounted_he_new_pvn(pTHX_ struct refcounted_he *parent,
3180         const char *keypv, STRLEN keylen, U32 hash, SV *value, U32 flags)
3181 {
3182     dVAR;
3183     STRLEN value_len = 0;
3184     const char *value_p = NULL;
3185     bool is_pv;
3186     char value_type;
3187     char hekflags;
3188     STRLEN key_offset = 1;
3189     struct refcounted_he *he;
3190     PERL_ARGS_ASSERT_REFCOUNTED_HE_NEW_PVN;
3191
3192     if (!value || value == &PL_sv_placeholder) {
3193         value_type = HVrhek_delete;
3194     } else if (SvPOK(value)) {
3195         value_type = HVrhek_PV;
3196     } else if (SvIOK(value)) {
3197         value_type = SvUOK((const SV *)value) ? HVrhek_UV : HVrhek_IV;
3198     } else if (!SvOK(value)) {
3199         value_type = HVrhek_undef;
3200     } else {
3201         value_type = HVrhek_PV;
3202     }
3203     is_pv = value_type == HVrhek_PV;
3204     if (is_pv) {
3205         /* Do it this way so that the SvUTF8() test is after the SvPV, in case
3206            the value is overloaded, and doesn't yet have the UTF-8flag set.  */
3207         value_p = SvPV_const(value, value_len);
3208         if (SvUTF8(value))
3209             value_type = HVrhek_PV_UTF8;
3210         key_offset = value_len + 2;
3211     }
3212     hekflags = value_type;
3213
3214     if (flags & REFCOUNTED_HE_KEY_UTF8) {
3215         /* Canonicalise to Latin-1 where possible. */
3216         const char *keyend = keypv + keylen, *p;
3217         STRLEN nonascii_count = 0;
3218         for (p = keypv; p != keyend; p++) {
3219             U8 c = (U8)*p;
3220             if (c & 0x80) {
3221                 if (!((c & 0xfe) == 0xc2 && ++p != keyend &&
3222                             (((U8)*p) & 0xc0) == 0x80))
3223                     goto canonicalised_key;
3224                 nonascii_count++;
3225             }
3226         }
3227         if (nonascii_count) {
3228             char *q;
3229             const char *p = keypv, *keyend = keypv + keylen;
3230             keylen -= nonascii_count;
3231             Newx(q, keylen, char);
3232             SAVEFREEPV(q);
3233             keypv = q;
3234             for (; p != keyend; p++, q++) {
3235                 U8 c = (U8)*p;
3236                 *q = (char)
3237                     ((c & 0x80) ? ((c & 0x03) << 6) | (((U8)*++p) & 0x3f) : c);
3238             }
3239         }
3240         flags &= ~REFCOUNTED_HE_KEY_UTF8;
3241         canonicalised_key: ;
3242     }
3243     if (flags & REFCOUNTED_HE_KEY_UTF8)
3244         hekflags |= HVhek_UTF8;
3245     if (!hash)
3246         PERL_HASH(hash, keypv, keylen);
3247
3248 #ifdef USE_ITHREADS
3249     he = (struct refcounted_he*)
3250         PerlMemShared_malloc(sizeof(struct refcounted_he) - 1
3251                              + keylen
3252                              + key_offset);
3253 #else
3254     he = (struct refcounted_he*)
3255         PerlMemShared_malloc(sizeof(struct refcounted_he) - 1
3256                              + key_offset);
3257 #endif
3258
3259     he->refcounted_he_next = parent;
3260
3261     if (is_pv) {
3262         Copy(value_p, he->refcounted_he_data + 1, value_len + 1, char);
3263         he->refcounted_he_val.refcounted_he_u_len = value_len;
3264     } else if (value_type == HVrhek_IV) {
3265         he->refcounted_he_val.refcounted_he_u_iv = SvIVX(value);
3266     } else if (value_type == HVrhek_UV) {
3267         he->refcounted_he_val.refcounted_he_u_uv = SvUVX(value);
3268     }
3269
3270 #ifdef USE_ITHREADS
3271     he->refcounted_he_hash = hash;
3272     he->refcounted_he_keylen = keylen;
3273     Copy(keypv, he->refcounted_he_data + key_offset, keylen, char);
3274 #else
3275     he->refcounted_he_hek = share_hek_flags(keypv, keylen, hash, hekflags);
3276 #endif
3277
3278     he->refcounted_he_data[0] = hekflags;
3279     he->refcounted_he_refcnt = 1;
3280
3281     return he;
3282 }
3283
3284 /*
3285 =for apidoc m|struct refcounted_he *|refcounted_he_new_pv|struct refcounted_he *parent|const char *key|U32 hash|SV *value|U32 flags
3286
3287 Like L</refcounted_he_new_pvn>, but takes a nul-terminated string instead
3288 of a string/length pair.
3289
3290 =cut
3291 */
3292
3293 struct refcounted_he *
3294 Perl_refcounted_he_new_pv(pTHX_ struct refcounted_he *parent,
3295         const char *key, U32 hash, SV *value, U32 flags)
3296 {
3297     PERL_ARGS_ASSERT_REFCOUNTED_HE_NEW_PV;
3298     return refcounted_he_new_pvn(parent, key, strlen(key), hash, value, flags);
3299 }
3300
3301 /*
3302 =for apidoc m|struct refcounted_he *|refcounted_he_new_sv|struct refcounted_he *parent|SV *key|U32 hash|SV *value|U32 flags
3303
3304 Like L</refcounted_he_new_pvn>, but takes a Perl scalar instead of a
3305 string/length pair.
3306
3307 =cut
3308 */
3309
3310 struct refcounted_he *
3311 Perl_refcounted_he_new_sv(pTHX_ struct refcounted_he *parent,
3312         SV *key, U32 hash, SV *value, U32 flags)
3313 {
3314     const char *keypv;
3315     STRLEN keylen;
3316     PERL_ARGS_ASSERT_REFCOUNTED_HE_NEW_SV;
3317     if (flags & REFCOUNTED_HE_KEY_UTF8)
3318         Perl_croak(aTHX_ "panic: refcounted_he_new_sv bad flags %"UVxf,
3319             (UV)flags);
3320     keypv = SvPV_const(key, keylen);
3321     if (SvUTF8(key))
3322         flags |= REFCOUNTED_HE_KEY_UTF8;
3323     if (!hash && SvIsCOW_shared_hash(key))
3324         hash = SvSHARED_HASH(key);
3325     return refcounted_he_new_pvn(parent, keypv, keylen, hash, value, flags);
3326 }
3327
3328 /*
3329 =for apidoc m|void|refcounted_he_free|struct refcounted_he *he
3330
3331 Decrements the reference count of a C<refcounted_he> by one.  If the
3332 reference count reaches zero the structure's memory is freed, which
3333 (recursively) causes a reduction of its parent C<refcounted_he>'s
3334 reference count.  It is safe to pass a null pointer to this function:
3335 no action occurs in this case.
3336
3337 =cut
3338 */
3339
3340 void
3341 Perl_refcounted_he_free(pTHX_ struct refcounted_he *he) {
3342     dVAR;
3343     PERL_UNUSED_CONTEXT;
3344
3345     while (he) {
3346         struct refcounted_he *copy;
3347         U32 new_count;
3348
3349         HINTS_REFCNT_LOCK;
3350         new_count = --he->refcounted_he_refcnt;
3351         HINTS_REFCNT_UNLOCK;
3352         
3353         if (new_count) {
3354             return;
3355         }
3356
3357 #ifndef USE_ITHREADS
3358         unshare_hek_or_pvn (he->refcounted_he_hek, 0, 0, 0);
3359 #endif
3360         copy = he;
3361         he = he->refcounted_he_next;
3362         PerlMemShared_free(copy);
3363     }
3364 }
3365
3366 /*
3367 =for apidoc m|struct refcounted_he *|refcounted_he_inc|struct refcounted_he *he
3368
3369 Increment the reference count of a C<refcounted_he>.  The pointer to the
3370 C<refcounted_he> is also returned.  It is safe to pass a null pointer
3371 to this function: no action occurs and a null pointer is returned.
3372
3373 =cut
3374 */
3375
3376 struct refcounted_he *
3377 Perl_refcounted_he_inc(pTHX_ struct refcounted_he *he)
3378 {
3379     dVAR;
3380     if (he) {
3381         HINTS_REFCNT_LOCK;
3382         he->refcounted_he_refcnt++;
3383         HINTS_REFCNT_UNLOCK;
3384     }
3385     return he;
3386 }
3387
3388 /*
3389 =for apidoc cop_fetch_label
3390
3391 Returns the label attached to a cop.
3392 The flags pointer may be set to C<SVf_UTF8> or 0.
3393
3394 =cut
3395 */
3396
3397 /* pp_entereval is aware that labels are stored with a key ':' at the top of
3398    the linked list.  */
3399 const char *
3400 Perl_cop_fetch_label(pTHX_ COP *const cop, STRLEN *len, U32 *flags) {
3401     struct refcounted_he *const chain = cop->cop_hints_hash;
3402
3403     PERL_ARGS_ASSERT_COP_FETCH_LABEL;
3404
3405     if (!chain)
3406         return NULL;
3407 #ifdef USE_ITHREADS
3408     if (chain->refcounted_he_keylen != 1)
3409         return NULL;
3410     if (*REF_HE_KEY(chain) != ':')
3411         return NULL;
3412 #else
3413     if ((STRLEN)HEK_LEN(chain->refcounted_he_hek) != 1)
3414         return NULL;
3415     if (*HEK_KEY(chain->refcounted_he_hek) != ':')
3416         return NULL;
3417 #endif
3418     /* Stop anyone trying to really mess us up by adding their own value for
3419        ':' into %^H  */
3420     if ((chain->refcounted_he_data[0] & HVrhek_typemask) != HVrhek_PV
3421         && (chain->refcounted_he_data[0] & HVrhek_typemask) != HVrhek_PV_UTF8)
3422         return NULL;
3423
3424     if (len)
3425         *len = chain->refcounted_he_val.refcounted_he_u_len;
3426     if (flags) {
3427         *flags = ((chain->refcounted_he_data[0] & HVrhek_typemask)
3428                   == HVrhek_PV_UTF8) ? SVf_UTF8 : 0;
3429     }
3430     return chain->refcounted_he_data + 1;
3431 }
3432
3433 /*
3434 =for apidoc cop_store_label
3435
3436 Save a label into a C<cop_hints_hash>. You need to set flags to C<SVf_UTF8>
3437 for a utf-8 label.
3438
3439 =cut
3440 */
3441
3442 void
3443 Perl_cop_store_label(pTHX_ COP *const cop, const char *label, STRLEN len,
3444                      U32 flags)
3445 {
3446     SV *labelsv;
3447     PERL_ARGS_ASSERT_COP_STORE_LABEL;
3448
3449     if (flags & ~(SVf_UTF8))
3450         Perl_croak(aTHX_ "panic: cop_store_label illegal flag bits 0x%" UVxf,
3451                    (UV)flags);
3452     labelsv = newSVpvn_flags(label, len, SVs_TEMP);
3453     if (flags & SVf_UTF8)
3454         SvUTF8_on(labelsv);
3455     cop->cop_hints_hash
3456         = refcounted_he_new_pvs(cop->cop_hints_hash, ":", labelsv, 0);
3457 }
3458
3459 /*
3460 =for apidoc hv_assert
3461
3462 Check that a hash is in an internally consistent state.
3463
3464 =cut
3465 */
3466
3467 #ifdef DEBUGGING
3468
3469 void
3470 Perl_hv_assert(pTHX_ HV *hv)
3471 {
3472     dVAR;
3473     HE* entry;
3474     int withflags = 0;
3475     int placeholders = 0;
3476     int real = 0;
3477     int bad = 0;
3478     const I32 riter = HvRITER_get(hv);
3479     HE *eiter = HvEITER_get(hv);
3480
3481     PERL_ARGS_ASSERT_HV_ASSERT;
3482
3483     (void)hv_iterinit(hv);
3484
3485     while ((entry = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS))) {
3486         /* sanity check the values */
3487         if (HeVAL(entry) == &PL_sv_placeholder)
3488             placeholders++;
3489         else
3490             real++;
3491         /* sanity check the keys */
3492         if (HeSVKEY(entry)) {
3493             NOOP;   /* Don't know what to check on SV keys.  */
3494         } else if (HeKUTF8(entry)) {
3495             withflags++;
3496             if (HeKWASUTF8(entry)) {
3497                 PerlIO_printf(Perl_debug_log,
3498                             "hash key has both WASUTF8 and UTF8: '%.*s'\n",
3499                             (int) HeKLEN(entry),  HeKEY(entry));
3500                 bad = 1;
3501             }
3502         } else if (HeKWASUTF8(entry))
3503             withflags++;
3504     }
3505     if (!SvTIED_mg((const SV *)hv, PERL_MAGIC_tied)) {
3506         static const char bad_count[] = "Count %d %s(s), but hash reports %d\n";
3507         const int nhashkeys = HvUSEDKEYS(hv);
3508         const int nhashplaceholders = HvPLACEHOLDERS_get(hv);
3509
3510         if (nhashkeys != real) {
3511             PerlIO_printf(Perl_debug_log, bad_count, real, "keys", nhashkeys );
3512             bad = 1;
3513         }
3514         if (nhashplaceholders != placeholders) {
3515             PerlIO_printf(Perl_debug_log, bad_count, placeholders, "placeholder", nhashplaceholders );
3516             bad = 1;
3517         }
3518     }
3519     if (withflags && ! HvHASKFLAGS(hv)) {
3520         PerlIO_printf(Perl_debug_log,
3521                     "Hash has HASKFLAGS off but I count %d key(s) with flags\n",
3522                     withflags);
3523         bad = 1;
3524     }
3525     if (bad) {
3526         sv_dump(MUTABLE_SV(hv));
3527     }
3528     HvRITER_set(hv, riter);             /* Restore hash iterator state */
3529     HvEITER_set(hv, eiter);
3530 }
3531
3532 #endif
3533
3534 /*
3535  * Local variables:
3536  * c-indentation-style: bsd
3537  * c-basic-offset: 4
3538  * indent-tabs-mode: nil
3539  * End:
3540  *
3541  * ex: set ts=8 sts=4 sw=4 et:
3542  */