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

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

Thread Next
From:
Stas Bekman
Date:
February 19, 2003 20:41
Subject:
a problem with converting undef => char * in XS and possible solutions
Message ID:
3E545C19.60809@stason.org
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:

MODULE = Bug		PACKAGE = Bug		

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

when calling from perl:

   Bug::trunc(undef)

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 @@
  T_DOUBLE
         $var = (double)SvNV($arg)
  T_PV
-       $var = ($type)SvPV_nolen($arg)
+       $var = ($type)SvPV_force($arg, PL_na);
  T_PTR
         $var = INT2PTR($type,SvIV($arg))
  T_PTRREF


now when the same function is called, we get:

   Use of uninitialized value in subroutine entry at test.pl line 7.

and no segfault!

__________________________________________________________________
Stas Bekman            JAm_pH ------> Just Another mod_perl Hacker
http://stason.org/     mod_perl Guide ---> http://perl.apache.org
mailto:stas@stason.org http://use.perl.org http://apacheweek.com
http://modperlbook.org http://apache.org   http://ticketmaster.com


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