develooper Front page | perl.perl5.porters | Postings from February 2003

a problem with converting undef => char * in XS and possible solutions

Thread Next
Stas Bekman
February 19, 2003 20:41
a problem with converting undef => char * in XS and possible solutions
Message ID:
one of the modperl1 functions is calling an apache function which
manipulates the passed string and makes sure that it ends with
\0 after the manipulation is done.

If the mod_perl function receives an undef, the typemap entry
for 'char *' was returning "" rather than an allocated string "".'\0'
which causes a segfault when later the apache function
assigns '\0' to an non-allocated memory storage.

The following xs function demonstrates the problem:


void trunc(str)
     char *str
     str[0] = '\0';

when calling from perl:


we segfault with:

#0  0x4017bbfa in XS_Bug_truncate (my_perl=0x804b288, cv=0x8102bb0)
     at Bug.xs:10
10          str[0] = '\0';

The problem is in how the conversion is performed:

	char *	str = (char *)SvPV_nolen(ST(0));
where SvPV_nolen is a disguised Perl_sv_2pv_flags, which does:

       return "";

when undef is passed (and it doesn't generate a warning under 'use warnings'!)

Shouldn't coercing of undef into a string actually allocate 1 char and
assign '\0' to it? returning "" looks like a bad cheating.

At least won't it be better to use the following entry in the typemap,
so it warns when undef is passed and correctly returns an allocated
empty string from the coerced into SvPV undef.

--- lib/ExtUtils/typemap.orig   2003-02-20 15:32:27.000000000 +1100
+++ lib/ExtUtils/typemap        2003-02-20 15:33:30.000000000 +1100
@@ -110,7 +110,7 @@
         $var = (double)SvNV($arg)
-       $var = ($type)SvPV_nolen($arg)
+       $var = ($type)SvPV_force($arg, PL_na);
         $var = INT2PTR($type,SvIV($arg))

now when the same function is called, we get:

   Use of uninitialized value in subroutine entry at line 7.

and no segfault!

Stas Bekman            JAm_pH ------> Just Another mod_perl Hacker     mod_perl Guide --->

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