in reply to Re^2: XS: Manipulating refcounts
in thread XS: Manipulating refcounts

Ofcourse there are (CORE) modules doing it... But it's not that because they do it you should do it too... And in my opinion the tied hash from DB_File and your scalar are two completly differnt things...

The way to make DB_File segfault is to get the tied object and then change it.

The way to make your code segfault is to either change the thing it references to or pass the wrong thing to one of your other routines.

For example:

my $artist2; my $cd = new_cd($artist2);
This code will segfault. Sure in this example it is (or atleast should be) obvious why it segfaults... But if you are passing $artist to several subroutines and maybe forgetting it/passing the wrong thing once then it is not that obvious...

To prevent $$artist from being changed you could use: SvREADONLY_on(SvRV(perlref));.

But this still leaves the other issue... As in, passing the wrong variable/undef to new_cd(); (for example)...

I guess it comes down to:

Update: removed accidental link.

Replies are listed 'Best First'.
Re^4: XS: Manipulating refcounts
by creamygoodness (Curate) on Sep 20, 2006 at 19:11 UTC
    The standard way of throwing a meaningful error rather than segfaulting when supplied with bad input of the type you describe is to vet arguments using sv_derived_from, which is the perlapi function which implements isa. Manually inserted, such argument checking would look something like this...
    /* Constructor for CD. */ SV* new_cd(SV *artist_sv) { if (!sv_derived_from(artist_sv, "Artist") { Croak("Not an Artist"); } Artist *artist = INT2PTR( Artist*, SvIV(SvRV(artist_sv)) ); /* ... */ }

    That stops anything but Artist and its subclasses from getting through. If somebody does something like bless a hash into the "Artist" package and submit that we'll still get a segfault, but that's less likely to happen inadvertently.

    Typically, the argument-checking code is not typed in manually, but is inserted by xsubpp via a typemap which spares the programmer from the error-prone drudgery of repeating that code over and over.

    Rest assured that my production code always implements such checks. I agree that the example code is dangerous. I left out the safety code because the sample was already too long -- long enough to dissuade demerphq from looking at it, for example.

    --
    Marvin Humphrey
    Rectangular Research ― http://www.rectangular.com