develooper Front page | perl.perl5.porters | Postings from December 2011

[perl #97988] readline can cause PL_last_in_gv to point to freed scalar

Thread Previous | Thread Next
Father Chrysostomos via RT
December 17, 2011 07:18
[perl #97988] readline can cause PL_last_in_gv to point to freed scalar
Message ID:
[Slightly off-topic for the beginners’ list.  But, in short, you should
*always* close your file handles explicitly.]

On Mon Aug 29 09:20:37 2011, sprout wrote:
> $ perl -le 'open my $fh, "t/"; <$fh> for 1,2; $f{g} = *foo;
> readline $f{g}; $f{g}=3; undef %f; *{"foom"} = $fh; print tell'
> 72
> In that example the *foom glob re-uses the SV of the now-freed $f{g}. So
> it just happens by chance that the other file handle is used.
> I would suggest two things:
> • Switch readline over to rv2gv (which makes sure its returned glob is
> not FAKE). That will prevent $f{g} = 3 from making PL_last_in_gv point
> to an SV that is not a glob.
> • Make PL_last_in_gv refcounted, because rv2gv, when given a FAKE glob,
> returns a mortal copy. Without that, the GV assigned to PL_last_in_gv
> could be freed at the end of the statement containing the readline.
> Alternatively, we could add a gv==PL_last_in_gv check to sv_force_normal
> (like the check in sv_clear), to make sure glob copy coercion does not
> leave PL_last_in_gv pointed to a non-glob.

It looks as though the latter will be the only recourse.  Due to the
unfortunate practice, sometimes encouraged on the beginners’ list, of
not explicitly closing file handles, my first suggestion, which would
make for a cleaner implementation, would prevent the last-read file
handle from going out of scope and result in breakage (of already-broken
code; Perl already makes no guarantee as to when things will be freed)
and bug reports.


Father Chrysostomos

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About