develooper Front page | perl.perl5.porters | Postings from August 2023

Calling eval_sv() at compiletime with the right context

Thread Next
From:
Paul "LeoNerd" Evans
Date:
August 21, 2023 20:03
Subject:
Calling eval_sv() at compiletime with the right context
Message ID:
20230821210255.0be5daa7@shy.leonerd.org.uk
I'm running some C code that's somewhere within a big nest of C
function calls, ultimately invoked from Perl's PL_keyword_plugin. I.e.
happening at parse-time. The code is trying to eval_sv() a string
parsed out of the source code. Here's the call currently:

  https://metacpan.org/release/PEVANS/Object-Pad-FieldAttr-Checked-0.02/source/lib/Object/Pad/FieldAttr/Checked.xs#L95

I find that when that happens, the eval'ed code runs in package "main",
has no strict, no warnings, no features from the prevailing `use
VERSION`, etc... So I suspect I am doing something wrong. But I have
no idea what.

Evidentally I'm not the first to encounter this problem. mauke said it
sounded familiar, and offered this workaround:

  https://github.com/mauke/Function-Parameters/blob/main/Parameters.xs#L706

I took that inspiration and adjusted it a bit; now I'm doing this:

    // We have to fool eval_sv() into seeing the right package
    SAVEVPTR(PL_curcop);
    COP *fakecop = (COP *)newSTATEOP(0, NULL, NULL);
    SAVEFREEOP(fakecop);
    CopSTASH_set(fakecop, PL_curstash);
    PL_curcop = fakecop;

    eval_sv_rethrow(value, G_SCALAR);

This now fixes a littlebit. The invoked code now sees the correct
package, e.g. if I inject the code `print STDERR __PACKAGE__, "\n"`

Problem is everything else is still wrong. I still have no strict and
no feature flags. Though, I do get warnings. I seem to have this
bizarre mixture of some state but not the rest.

I suspect I'm somewhat on the right lines here in that I need to create
a fake COP to put into PL_curcop, but apparently it doesn't have the
right settings for hints or feature flags.

Can anyone suggest some further guidance?

-- 
Paul "LeoNerd" Evans

leonerd@leonerd.org.uk      |  https://metacpan.org/author/PEVANS
http://www.leonerd.org.uk/  |  https://www.tindie.com/stores/leonerd/

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About