C-DynaLib

 view release on metacpan or  search on metacpan

lib/C/DynaLib.pm  view on Meta::CPAN

    if ($node->isa('GCC::Node::record_type')) {
      declare_struct process_struct($node);
    }
  }
}

sub my_carp {
  # inspired by Exporter
  my $text = shift;
  local $Carp::CarpLevel = 0;
  if ((caller 2)[3] =~ /^\QC::DynaLib::__ANON__/) {
    $Carp::CarpLevel = 2;
    $text =~ s/(?: in pack)? at \(eval \d+\) line \d+.*\n//;
  }
  carp($text);
};

sub my_croak {
  my $text = shift;
  local $Carp::CarpLevel = 0;
  if ((caller 2)[3] =~ /^\QC::DynaLib::__ANON__/) {
    $Carp::CarpLevel = 2;
    $text =~ s/(?: in pack)? at \(eval \d+\) line \d+.*\n//;
  }
  croak($text);
};


package C::DynaLib::Callback;

use strict;
use Carp;
use vars qw($Config $GoodRet $GoodFirst $GoodArg $empty);
use subs qw(new Ptr DESTROY);

sub CONFIG_TEMPLATE () { C::DynaLib::PTR_TYPE ."pp". C::DynaLib::PTR_TYPE }
$empty = "";

if (C::DynaLib::PTR_TYPE eq 'q') {
  $GoodRet = '[iIq]?';
  $GoodFirst = '(?:[ilscILSCpqQ]?|P\d+)';
  $GoodArg = '(?:[ilscILSCfdpqQ]?|P\d+)';
} else {
  $GoodRet = '[iI]?';
  $GoodFirst = '(?:[ilscILSCp]?|P\d+)';
  $GoodArg = '(?:[ilscILSCfdp]?|P\d+)';
}

sub new {
  my $class = shift;
  my $self = [];
  my ($index, $coderef);
  my ($codeptr, $ret_type, $arg_type, @arg_type, $func);
  my $i;
  for ($index = 0; $index <= $#{$Config}; $index++) {
    ($codeptr, $ret_type, $arg_type, $func)
      = unpack(CONFIG_TEMPLATE, $Config->[$index]);
    last unless $codeptr;
  }
  if ($index > $#{$Config}) {
    carp "Limit of ", scalar(@$Config), " callbacks exceeded";
    return undef;
  }
  ($coderef, $ret_type, @arg_type) = @_;

  $ret_type =~ /^$GoodRet$/o
    or croak "Invalid callback return type: '$ret_type'";
  ! @arg_type || $arg_type[0] =~ /^$GoodFirst$/o
    or croak "Invalid callback first argument type: '$arg_type[0]'";
  for $i (@arg_type[1..$#arg_type]) {
    $i =~ /^$GoodArg$/o
      or croak "Invalid callback argument type: '$i'";
  }

  unshift @$self, $coderef;
  $codeptr = \$self->[0] + 0;
  $arg_type = join ('', @arg_type);

  unshift @$self, $codeptr, $ret_type, $arg_type, $func, $index;
  $Config->[$index] = pack (CONFIG_TEMPLATE, @$self);

  bless $self, $class;
}

sub Ptr {
  $_[0]->[3];
}

sub DESTROY {
  $Config->[$_[0]->[4]] = pack(CONFIG_TEMPLATE, 0, $empty, $empty,
			       $_[0]->[3]);
}

package C::DynaLib;
1;
__END__

=head1 NAME

C::DynaLib - Dynamic Perl interface to C compiled code.

=head1 SYNOPSIS

  use C::DynaLib;
  use sigtrap;	# recommended

  $lib = new C::DynaLib( $library [, $decl, [$dlopen_flags]] );

  $func = $lib->DeclareSub( $symbol_name
			    [, $return_type [, @arg_types] ] );
  $result = &$func(@args);
  # or
  $func = $lib->DeclareSub( { "name" => $symbol_name,
                              "decl" => 'stdcall',
			      [param => $value,] ... } );
  $func = $lib->DeclareSub( $symbol_name, $ret, $params...);
  # or
  use C::DynaLib qw(DeclareSub);
  $func = DeclareSub( $function_pointer,
		      [, $return_type [, @arg_types] ] );
  # or

lib/C/DynaLib.pm  view on Meta::CPAN

Passing structs by value is not generally supported, but you might
find a way to do it with a given compiler by experimenting or
using L<C::DynaLib::Struct>.

=item C<decl>

Allows you to specify a function's calling convention.  This is
possible only with a named-parameter form of C<DeclareSub>. See below
for information about the supported calling conventions.
This overrides LibDecl().

The global $C::DynaLib::decl holds the string for the current
global declaration convention.

=back

=head2 ->LibRef()

A library reference obtained from either C<DynaLoader::dl_load_file>
or the C<C::DynaLib::LibRef> method. 

=head2 ->LibDecl()

Read the name of the calling convention in which this libary was 
declared. The 2nd arg to new, or the default calling convention.
All functions in this library are called with this calling convention 
by default,

=head2 PTR_TYPE()

Type declaration for an opaque pointer, which is either "i", "q",
"l" or "s".

If you want to use strings use "p" instead.

=head2 $DefConv

Name of the currently used default calling convention. See below.

=head2 Parse( '<<EOS' ) - Parse macro, function and struct declarations c-style

The argument may be c-string (best done via '<<EOS' ... EOS)
or a Convert::Binary::C object.

NYI for funcs. Only C::DynaLib::Struct->Parse is implemented yet.
TODO with L<GCC::TranslationUnit>. See F<script/hparse.pl>

=head2 Calling a declared function

The returned value of C<DeclareSub> is a code reference.  Calling
through it results in a call to the C function.  See L<perlref(1)> on
how to use code references.

=head2 C::DynaLib::Callback( \&some_sub, $ret_type, @arg_types )

Using callback routines

Some C functions expect a pointer to another C function as an
argument.  The library code that receives the pointer may use it to
call an application function at a later time.  Such functions are
called I<callbacks>.

This module allows you to use a Perl sub as a C callback, subject to
certain restrictions.  There is a hard-coded maximum number of
callbacks that can be active at any given time.  The default (4) may
be changed by specifying C<CALLBACKS=number> on the F<Makefile.PL>
command line.

A callback's argument and return types are specified using C<pack>
codes, as described above for library functions.  Currently, the
return value must be interpretable as type C<int> or C<void>, so the
only valid codes are C<"i">, C<"I">, and C<"">.  There are also
restrictions on the permissible argument types, especially for the
first argument position.  These limitations are considered bugs to be
fixed someday.

To enable a Perl sub to be used as a callback, you must construct an
object of class C<C::DynaLib::Callback>.  The syntax is

  $cb_ref = new C::DynaLib::Callback( \&some_sub,
                    $ret_type, @arg_types );

where C<$ret_type> and C<@arg_types> are the C<pack>-style types of
the function return value and arguments, respectively.  C<\&some_sub>
must be a code reference or sub name (see L<perlref>).

C<$cb_ref-E<gt>Ptr()> then returns a function pointer.  C code that
calls it will end up calling C<&some_sub>.

=head1 EXAMPLES

This code loads and calls the math library function I<sinh()>.  It
assumes that you have a dynamic version of the math library which will
be found by C<DynaLoader::dl_findfile("-lm")>.  If this doesn't work,
replace C<"-lm"> with the name of your dynamic math library.

  use C::DynaLib;
  $libm = new C::DynaLib("-lm");
  $sinh = $libm->DeclareSub("sinh", "d", "d");
  print "The hyperbolic sine of 3 is ", &{$sinh}(3), "\n";
  # The hyperbolic sine of 3 is 10.0178749274099

The following example uses the C library's I<strncmp()> to compare the
first I<n> characters of two strings:

  use C::DynaLib;
  $libc = new C::DynaLib("-lc");
  $strncmp = $libc->DeclareSub("strncmp", "i", "p", "p", "I");
  $string1 = "foobar";
  $string2 = "foolish";
  $result = &{$strncmp}($string1, $string2, 3);  # $result is 0
  $result = &{$strncmp}($string1, $string2, 4);  # $result is -1

The files F<test.pl> and F<README.win32> contain examples using
callbacks.

=head1 CALLING CONVENTIONS

This section is intended for anyone who is interested in debugging or
extending this module.  You probably don't need to read it just to
I<use> the module.

=head2 The problem

The hardest thing about writing this module is to accommodate the
different calling conventions used by different compilers, operating
systems, and CPU types.

"What's a calling convention?" you may be wondering.  It is how
compiler-generated functions receive their arguments from and make
their return values known to the code that calls them, at the level of
machine instructions and registers.  Each machine has a set of rules
for this.  Compilers and operating systems may use variations even on
the same machine type.  In some cases, it is necessary to support more
than one calling convention on the same system.

"But that's all handled by the compiler!" you might object.  True
enough, if the calling code knows the signature of the called function
at compile time.  For example, consider this C code:

  int foo(double bar, const char *baz);
  ...
  int res;
  res = foo(sqrt(2.0), "hi");

A compiler will generate specific instruction sequences to load the
return value from I<sqrt()> and a pointer to the string C<"hi"> into
whatever registers or memory locations I<foo()> expects to receive
them in, based on its calling convention and the types C<double> and
C<S<char *>>.  Another specific instruction sequence stores the return
value in the variable C<res>.

But when you compile the C code in this module, it must be general
enough to handle all sorts of function argument and return types.

"Why not use varargs/stdarg?"  Most C compilers support a special set
of macros that allow a function to receive a variable number of
arguments of variable type.  When the function receiving the arguments
is compiled, it does not know with what argument types it will be
called.

But the code that I<calls> such a function I<does> know at compile
time how many and what type of arguments it is passing to the varargs
function.  There is no "reverse stdarg" standard for passing types to
be determined at run time.  You can't simply pass a C<va_list> to a
function unless that function is defined to receive a C<va_list>.
This module uses varargs/stdarg where appropriate, but the only
appropriate place is in the callback support.

=head2 The solution (well, half-solution)

Having failed to find a magic bullet to spare us from the whims of
system designers and compiler writers, we are forced to examine the
calling conventions in common use and try to put together some "glue"
code that stands a chance of being portable.

lib/C/DynaLib.pm  view on Meta::CPAN

C<double>, for example, may not work on systems that use
floating-point registers for this purpose.  Specialized code may be
required to support such systems.

=head2 Robustness

Usually, Perl programs run under the control of the Perl interpreter.
Perl is extremely stable and can almost guarantee an environment free
of the problems of C, such as bad pointers causing memory access
violations.  Some modules use a Perl feature called "XSubs" to call C
code directly from a Perl program.  In such cases, a crash may occur
if the C or XS code is faulty.  However, once the XS module has been
sufficiently debugged, one can be reasonably sure that it will work
right.

Code called through this module lacks such protection.  Since the
association between Perl and C is made at run time, errors due to
incompatible library interfaces or incorrect assumptions have a much
greater chance of causing a crash than with either straight Perl or XS
code.

=head2 Security

This module does not require special privileges to run.  I have no
reason to think it contains any security bugs (except to the extent
that the known bugs impact security).  However, when this module is
installed, Perl programs gain great power to exploit C code which
could potentially have such bugs.  I'm not really sure whether this is
a major issue or not.

I haven't gotten around to understanding Perl's internal tainting
interface, so taint-checking may not accomplish what you expect.  (See
L<perlsec>)

=head2 Deallocation of Resources

To maximize portability, this module uses the F<DynaLoader> interface
to dynamic library linking.  F<DynaLoader>'s main purpose is to
support XS modules, which are loaded once by a program and not (to my
knowledge) unloaded.

L<DynaLoader::dl_unload_file> was added March 2000 for solaris, aix,
linux, hpux, OS/390, symbian, cygwin and win32. For darwin e.g. not.

=head2 Literal and temporary strings

Before Perl 5.00402, it was impossible to pass a string literal as a
pointer-to-nul-terminated-string argument of a C function.  For
example, the following statement (incorrectly) produced the error
C<Modification of a read-only value attempted>:

  &$strncmp("foo", "bar", 3);

To work around this problem, one must assign the value to a variable
and pass the variable in its place, as in

  &$strncmp($dummy1 = "foo", $dummy2 = "bar", 3);

=head2 Callbacks

Only a certain number of callbacks can exist at a time.  Callbacks can
mess up the message produced by C<die> in the presence of nested
C<eval>s.  The Callback code uses global data, and is consequently not
thread-safe.

=head2 Miscellaneous Bugs

There are restrictions on what C data types may be used.  Using
argument types of unusual size may have nasty results.  The techniques
used to pass values to and from C functions are generally hackish and
nonstandard.  Assembly code would be more complete.  Makefile.PL does
too much.  I haven't yet checked for memory leaks.

=head1 TODO

  Support fastcall (regs only) and ia64 (first four in regs, rest on stack)
  calling conventions. Very similar to alpha. See cdecl3 with stack_reserve=4

  Fiddle with autoloading so we don't have to call DeclareSub
  all the time.

  Mangle C++ symbol names.

  Parse C header files (macros, structs and function declarations) via
  Convert::Binary::C and/or GCC::TranslationUnit to make them useful here.
  Convert::Binary::C should be extended to return function types.
  The struct parser using Convert::Binary::C  needs more robustness.
  See hparse.pl for using GCC::TranslationUnit. gccxml might also be
  worthwhile.

  Multiple calling-conventions:
  Add stdcall dynamically on cdecl/cdecl3/hack30 for the W32 API.
  Include and link the useful ones per platform, and define a
  DeclareSub or LibRef syntax.

=head1 LICENSE

Copyright (c) 1997, 2000 by John Tobey.
Copyright (c) 2005, 2007, 2008, 2010 by Reini Urban.
This package is distributed under the same license as Perl itself.
There is no expressed or implied warranty, since it is free software.
See the file README in the top level Perl source directory for details.
The Perl source may be found at:

  http://www.perl.com/CPAN/src/

=head1 AUTHOR

John Tobey C<lt>jtobey@john-edwin-tobey.orgC<gt>

Maintainer: Reini Urban C<lt>rurban@cpan.orgC<gt>

=head1 SEE ALSO

L<perl(1)>, L<perlfunc/pack>, L<perlref>,
L<sigtrap(3)>, L<DynaLoader>, L<perlxs>, L<perlcall>

L<C::DynaLib::Struct> to conveniently declare and access structs.

The other perl FFIs:
L<Win32::API>, L<FFI>, L<P5NCI>, L<CTypes> I<(not yet)>



( run in 0.610 second using v1.01-cache-2.11-cpan-99c4e6809bf )