Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Bizarre copy of ARRAY etc - solved

by etj (Deacon)
on May 13, 2024 at 21:07 UTC ( [id://11159421]=perlmeditation: print w/replies, xml ) Need Help??

A simple XS function in PDL, firstvals_nophys, was giving "panic: attempt to copy freed scalar", but only if called on a complex-valued ndarray. The aim of this post is to appear when a despairing XS programmer googles that message, and give them another thing to check. When constructing a test to capture this, another message that appeared was "Bizarre copy of ARRAY". This is the old text of the function:
void firstvals_nophys(x) pdl *x PPCODE: if (!(x->state & PDL_ALLOCATED)) barf("firstvals_nophys called on +non-ALLOCATED %p", x); PDL_Indx i, maxvals = PDLMIN(10, x->nvals); EXTEND(SP, maxvals); for(i=0; i<maxvals; i++) { PDL_Anyval anyval = pdl_get_offs(x, i); if (anyval.type < 0) barf("Error getting value, type=%d", anyval +.type); SV *sv = sv_newmortal(); ANYVAL_TO_SV(sv, anyval); PUSHs(sv); }
The problem was that the ANYVAL_TO_SV macro was, only for complex-valued data, calling a Perl function to create a Math::Complex object (well, a subclass thereof because the overloads were wrong). That obviously uses the top of the stack, including writing values into it, and reading values out of it, including mortal ones that then got freed because they were done with. Therefore, the function was returning with some garbage on the stack, but the last value was correct.

The solution was simply to do a PUTBACK after the PUSH, which moves the top of the stack above data we care about. The new text of the function with that:

void firstvals_nophys(x) pdl *x PPCODE: if (!(x->state & PDL_ALLOCATED)) barf("firstvals_nophys called on +non-ALLOCATED %p", x); PDL_Indx i, maxvals = PDLMIN(10, x->nvals); EXTEND(SP, maxvals); for(i=0; i<maxvals; i++) { PDL_Anyval anyval = pdl_get_offs(x, i); if (anyval.type < 0) barf("Error getting value, type=%d", anyval +.type); SV *sv = sv_newmortal(); ANYVAL_TO_SV(sv, anyval); PUSHs(sv); PUTBACK; }
The commit that fixed this is at https://github.com/PDLPorters/pdl/commit/68389413537c6ea7ed85f121a580b3b008ba82a6. The docs on how to call a Perl function from C are at https://perldoc.perl.org/perlcall, with a full explanation of PUSHMARK, PUSH*, PUTBACK, and (after the call) SPAGAIN, and maybe POP* and maybe then PUTBACK.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlmeditation [id://11159421]
Approved by marto
Front-paged by marto
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (3)
As of 2024-05-26 21:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found