Skip to content

Commit

Permalink
classes: don't allocate object fields if there are none
Browse files Browse the repository at this point in the history
This was crashing on dump, since the dump code assumed
xhv_class_fields was non-NULL when ObjectFIELDS() was non-NULL.

Also add tests for dumping objects, one for this case and another
for an object with fields, since there were no such tests.

Fixes #22959
  • Loading branch information
tonycoz committed Feb 9, 2025
1 parent 225c128 commit 0befb25
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 3 deletions.
10 changes: 7 additions & 3 deletions class.c
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,15 @@ Perl_newSVobject(pTHX_ Size_t fieldcount)
{
SV *sv = newSV_type(SVt_PVOBJ);

Newx(ObjectFIELDS(sv), fieldcount, SV *);
if (fieldcount) {
Newx(ObjectFIELDS(sv), fieldcount, SV *);
Zero(ObjectFIELDS(sv), fieldcount, SV *);
}
else {
ObjectFIELDS(sv) = NULL;
}
ObjectMAXFIELD(sv) = fieldcount - 1;

Zero(ObjectFIELDS(sv), fieldcount, SV *);

return sv;
}

Expand Down
41 changes: 41 additions & 0 deletions ext/Devel-Peek/t/Peek.t
Original file line number Diff line number Diff line change
Expand Up @@ -1675,4 +1675,45 @@ EODUMP
$head . 'NV = 0\.99999999\d+' . $tail);
}

{
use experimental "class";
# this could crash [github #22959]
class Foo {
};
do_test('class object with no fields', Foo->new, <<~'EOS');
SV = IV\($ADDR\) at $ADDR
REFCNT = \d+
FLAGS = \(ROK\)
RV = $ADDR
SV = PVOBJ\($ADDR\) at $ADDR
REFCNT = 1
FLAGS = \(OBJECT\)
STASH = $ADDR\s+"Foo"
MAXFIELD = -1
FIELDS = 0x0
EOS

# test object with fields too
class Foo2 {
field $x = 0;
};
do_test('class object with a field', Foo2->new, <<~'EOS');
SV = IV\($ADDR\) at $ADDR
REFCNT = \d+
FLAGS = \(ROK\)
RV = $ADDR
SV = PVOBJ\($ADDR\) at $ADDR
REFCNT = 1
FLAGS = \(OBJECT\)
STASH = $ADDR\s+"Foo2"
MAXFIELD = 0
FIELDS = $ADDR
Field No\. 0 \(\$x\)
SV = IV\($ADDR\) at $ADDR
REFCNT = 1
FLAGS = \(IOK,pIOK\)
IV = 0
EOS
}

done_testing();

0 comments on commit 0befb25

Please sign in to comment.