Blob Blame History Raw
Fix a memory leak with Scalar::Util::weaken(). (Closes: #506324)

Upstream change 34209:

DBI memory leak in 5.10.0 due to change 26530

A weakref to a HV would leak, because the xhv_backreferences
array is created with a refcount of 2 (to avoid premature freeing
during global destruction), but the RC was only decremented once
when the parent HV was freed.
Also, when thread cloned, the new array was being created with a
RC of 1, rather than 2, which coincidentally worked due to the
first bug.

p4raw-id: //depot/perl@34209
diff --git a/hv.c b/hv.c
index c8279d8..80adc1f 100644
--- a/hv.c
+++ b/hv.c
@@ -1961,6 +1961,7 @@ Perl_hv_kill_backrefs(pTHX_ HV *hv) {
     if (av) {
 	HvAUX(hv)->xhv_backreferences = 0;
 	Perl_sv_kill_backrefs(aTHX_ (SV*) hv, av);
+	SvREFCNT_dec(av);
     }
 }
 
diff --git a/sv.c b/sv.c
index fe36438..7eb088b 100644
--- a/sv.c
+++ b/sv.c
@@ -10265,10 +10265,11 @@ Perl_sv_dup(pTHX_ const SV *sstr, CLONE_PARAMS* param)
 			daux->xhv_eiter = saux->xhv_eiter
 			    ? he_dup(saux->xhv_eiter,
 					(bool)!!HvSHAREKEYS(sstr), param) : 0;
+			/* backref array needs refcnt=2; see sv_add_backref */
 			daux->xhv_backreferences =
 			    saux->xhv_backreferences
 				? (AV*) SvREFCNT_inc(
-					sv_dup((SV*)saux->xhv_backreferences, param))
+					sv_dup_inc((SV*)saux->xhv_backreferences, param))
 				: 0;
 
                         daux->xhv_mro_meta = saux->xhv_mro_meta