home *** CD-ROM | disk | FTP | other *** search
/ OpenStep 4.2 / Openstep-4.2-Intel-User.iso / usr / lib / perl5 / DynaLoader.pm < prev    next >
Text File  |  1997-03-29  |  19KB  |  574 lines

  1. package DynaLoader;
  2.  
  3. =head1 NAME
  4.  
  5. DynaLoader - Dynamically load C libraries into Perl code
  6.  
  7. dl_error(), dl_findfile(), dl_expandspec(), dl_load_file(), dl_find_symbol(), dl_undef_symbols(), dl_install_xsub(), boostrap() - routines used by DynaLoader modules
  8.  
  9. =head1 SYNOPSIS
  10.  
  11.     require DynaLoader;
  12.     @ISA = qw(... DynaLoader ...);
  13.  
  14.  
  15. =head1 DESCRIPTION
  16.  
  17. This document defines a standard generic interface to the dynamic
  18. linking mechanisms available on many platforms.  Its primary purpose is
  19. to implement automatic dynamic loading of Perl modules.
  20.  
  21. This document serves as both a specification for anyone wishing to
  22. implement the DynaLoader for a new platform and as a guide for
  23. anyone wishing to use the DynaLoader directly in an application.
  24.  
  25. The DynaLoader is designed to be a very simple high-level
  26. interface that is sufficiently general to cover the requirements
  27. of SunOS, HP-UX, NeXT, Linux, VMS and other platforms.
  28.  
  29. It is also hoped that the interface will cover the needs of OS/2, NT
  30. etc and also allow pseudo-dynamic linking (using C<ld -A> at runtime).
  31.  
  32. It must be stressed that the DynaLoader, by itself, is practically
  33. useless for accessing non-Perl libraries because it provides almost no
  34. Perl-to-C 'glue'.  There is, for example, no mechanism for calling a C
  35. library function or supplying arguments.  It is anticipated that any
  36. glue that may be developed in the future will be implemented in a
  37. separate dynamically loaded module.
  38.  
  39. DynaLoader Interface Summary
  40.  
  41.   @dl_library_path
  42.   @dl_resolve_using
  43.   @dl_require_symbols
  44.   $dl_debug
  45.                                                   Implemented in:
  46.   bootstrap($modulename)                               Perl
  47.   @filepaths = dl_findfile(@names)                     Perl
  48.  
  49.   $libref  = dl_load_file($filename)                   C
  50.   $symref  = dl_find_symbol($libref, $symbol)          C
  51.   @symbols = dl_undef_symbols()                        C
  52.   dl_install_xsub($name, $symref [, $filename])        C
  53.   $message = dl_error                                  C
  54.  
  55. =over 4
  56.  
  57. =item @dl_library_path
  58.  
  59. The standard/default list of directories in which dl_findfile() will
  60. search for libraries etc.  Directories are searched in order:
  61. $dl_library_path[0], [1], ... etc
  62.  
  63. @dl_library_path is initialised to hold the list of 'normal' directories
  64. (F</usr/lib>, etc) determined by B<Configure> (C<$Config{'libpth'}>).  This should
  65. ensure portability across a wide range of platforms.
  66.  
  67. @dl_library_path should also be initialised with any other directories
  68. that can be determined from the environment at runtime (such as
  69. LD_LIBRARY_PATH for SunOS).
  70.  
  71. After initialisation @dl_library_path can be manipulated by an
  72. application using push and unshift before calling dl_findfile().
  73. Unshift can be used to add directories to the front of the search order
  74. either to save search time or to override libraries with the same name
  75. in the 'normal' directories.
  76.  
  77. The load function that dl_load_file() calls may require an absolute
  78. pathname.  The dl_findfile() function and @dl_library_path can be
  79. used to search for and return the absolute pathname for the
  80. library/object that you wish to load.
  81.  
  82. =item @dl_resolve_using
  83.  
  84. A list of additional libraries or other shared objects which can be
  85. used to resolve any undefined symbols that might be generated by a
  86. later call to load_file().
  87.  
  88. This is only required on some platforms which do not handle dependent
  89. libraries automatically.  For example the Socket Perl extension library
  90. (F<auto/Socket/Socket.so>) contains references to many socket functions
  91. which need to be resolved when it's loaded.  Most platforms will
  92. automatically know where to find the 'dependent' library (e.g.,
  93. F</usr/lib/libsocket.so>).  A few platforms need to to be told the location
  94. of the dependent library explicitly.  Use @dl_resolve_using for this.
  95.  
  96. Example usage:
  97.  
  98.     @dl_resolve_using = dl_findfile('-lsocket');
  99.  
  100. =item @dl_require_symbols
  101.  
  102. A list of one or more symbol names that are in the library/object file
  103. to be dynamically loaded.  This is only required on some platforms.
  104.  
  105. =item dl_error()
  106.  
  107. Syntax:
  108.  
  109.     $message = dl_error();
  110.  
  111. Error message text from the last failed DynaLoader function.  Note
  112. that, similar to errno in unix, a successful function call does not
  113. reset this message.
  114.  
  115. Implementations should detect the error as soon as it occurs in any of
  116. the other functions and save the corresponding message for later
  117. retrieval.  This will avoid problems on some platforms (such as SunOS)
  118. where the error message is very temporary (e.g., dlerror()).
  119.  
  120. =item $dl_debug
  121.  
  122. Internal debugging messages are enabled when $dl_debug is set true.
  123. Currently setting $dl_debug only affects the Perl side of the
  124. DynaLoader.  These messages should help an application developer to
  125. resolve any DynaLoader usage problems.
  126.  
  127. $dl_debug is set to C<$ENV{'PERL_DL_DEBUG'}> if defined.
  128.  
  129. For the DynaLoader developer/porter there is a similar debugging
  130. variable added to the C code (see dlutils.c) and enabled if Perl was
  131. built with the B<-DDEBUGGING> flag.  This can also be set via the
  132. PERL_DL_DEBUG environment variable.  Set to 1 for minimal information or
  133. higher for more.
  134.  
  135. =item dl_findfile()
  136.  
  137. Syntax:
  138.  
  139.     @filepaths = dl_findfile(@names)
  140.  
  141. Determine the full paths (including file suffix) of one or more
  142. loadable files given their generic names and optionally one or more
  143. directories.  Searches directories in @dl_library_path by default and
  144. returns an empty list if no files were found.
  145.  
  146. Names can be specified in a variety of platform independent forms.  Any
  147. names in the form B<-lname> are converted into F<libname.*>, where F<.*> is
  148. an appropriate suffix for the platform.
  149.  
  150. If a name does not already have a suitable prefix and/or suffix then
  151. the corresponding file will be searched for by trying combinations of
  152. prefix and suffix appropriate to the platform: "$name.o", "lib$name.*"
  153. and "$name".
  154.  
  155. If any directories are included in @names they are searched before
  156. @dl_library_path.  Directories may be specified as B<-Ldir>.  Any other
  157. names are treated as filenames to be searched for.
  158.  
  159. Using arguments of the form C<-Ldir> and C<-lname> is recommended.
  160.  
  161. Example: 
  162.  
  163.     @dl_resolve_using = dl_findfile(qw(-L/usr/5lib -lposix));
  164.  
  165.  
  166. =item dl_expandspec()
  167.  
  168. Syntax:
  169.  
  170.     $filepath = dl_expandspec($spec)
  171.  
  172. Some unusual systems, such as VMS, require special filename handling in
  173. order to deal with symbolic names for files (i.e., VMS's Logical Names).
  174.  
  175. To support these systems a dl_expandspec() function can be implemented
  176. either in the F<dl_*.xs> file or code can be added to the autoloadable
  177. dl_expandspec() function in F<DynaLoader.pm>.  See F<DynaLoader.pm> for
  178. more information.
  179.  
  180. =item dl_load_file()
  181.  
  182. Syntax:
  183.  
  184.     $libref = dl_load_file($filename)
  185.  
  186. Dynamically load $filename, which must be the path to a shared object
  187. or library.  An opaque 'library reference' is returned as a handle for
  188. the loaded object.  Returns undef on error.
  189.  
  190. (On systems that provide a handle for the loaded object such as SunOS
  191. and HPUX, $libref will be that handle.  On other systems $libref will
  192. typically be $filename or a pointer to a buffer containing $filename.
  193. The application should not examine or alter $libref in any way.)
  194.  
  195. This is function that does the real work.  It should use the current
  196. values of @dl_require_symbols and @dl_resolve_using if required.
  197.  
  198.     SunOS: dlopen($filename)
  199.     HP-UX: shl_load($filename)
  200.     Linux: dld_create_reference(@dl_require_symbols); dld_link($filename)
  201.     NeXT:  rld_load($filename, @dl_resolve_using)
  202.     VMS:   lib$find_image_symbol($filename,$dl_require_symbols[0])
  203.  
  204.  
  205. =item dl_find_symbol()
  206.  
  207. Syntax:
  208.  
  209.     $symref = dl_find_symbol($libref, $symbol)
  210.  
  211. Return the address of the symbol $symbol or C<undef> if not found.  If the
  212. target system has separate functions to search for symbols of different
  213. types then dl_find_symbol() should search for function symbols first and
  214. then other types.
  215.  
  216. The exact manner in which the address is returned in $symref is not
  217. currently defined.  The only initial requirement is that $symref can
  218. be passed to, and understood by, dl_install_xsub().
  219.  
  220.     SunOS: dlsym($libref, $symbol)
  221.     HP-UX: shl_findsym($libref, $symbol)
  222.     Linux: dld_get_func($symbol) and/or dld_get_symbol($symbol)
  223.     NeXT:  rld_lookup("_$symbol")
  224.     VMS:   lib$find_image_symbol($libref,$symbol)
  225.  
  226.  
  227. =item dl_undef_symbols()
  228.  
  229. Example
  230.  
  231.     @symbols = dl_undef_symbols()
  232.  
  233. Return a list of symbol names which remain undefined after load_file().
  234. Returns C<()> if not known.  Don't worry if your platform does not provide
  235. a mechanism for this.  Most do not need it and hence do not provide it,
  236. they just return an empty list.
  237.  
  238.  
  239. =item dl_install_xsub()
  240.  
  241. Syntax:
  242.  
  243.     dl_install_xsub($perl_name, $symref [, $filename])
  244.  
  245. Create a new Perl external subroutine named $perl_name using $symref as
  246. a pointer to the function which implements the routine.  This is simply
  247. a direct call to newXSUB().  Returns a reference to the installed
  248. function.
  249.  
  250. The $filename parameter is used by Perl to identify the source file for
  251. the function if required by die(), caller() or the debugger.  If
  252. $filename is not defined then "DynaLoader" will be used.
  253.  
  254.  
  255. =item boostrap()
  256.  
  257. Syntax:
  258.  
  259. bootstrap($module)
  260.  
  261. This is the normal entry point for automatic dynamic loading in Perl.
  262.  
  263. It performs the following actions:
  264.  
  265. =over 8
  266.  
  267. =item *
  268.  
  269. locates an auto/$module directory by searching @INC
  270.  
  271. =item *
  272.  
  273. uses dl_findfile() to determine the filename to load
  274.  
  275. =item *
  276.  
  277. sets @dl_require_symbols to C<("boot_$module")>
  278.  
  279. =item *
  280.  
  281. executes an F<auto/$module/$module.bs> file if it exists
  282. (typically used to add to @dl_resolve_using any files which
  283. are required to load the module on the current platform)
  284.  
  285. =item *
  286.  
  287. calls dl_load_file() to load the file
  288.  
  289. =item *
  290.  
  291. calls dl_undef_symbols() and warns if any symbols are undefined
  292.  
  293. =item *
  294.  
  295. calls dl_find_symbol() for "boot_$module"
  296.  
  297. =item *
  298.  
  299. calls dl_install_xsub() to install it as "${module}::bootstrap"
  300.  
  301. =item *
  302.  
  303. calls &{"${module}::bootstrap"} to bootstrap the module
  304.  
  305. =back
  306.  
  307. =back
  308.  
  309.  
  310. =head1 AUTHOR
  311.  
  312. Tim Bunce, 11 August 1994.
  313.  
  314. This interface is based on the work and comments of (in no particular
  315. order): Larry Wall, Robert Sanders, Dean Roehrich, Jeff Okamoto, Anno
  316. Siegel, Thomas Neumann, Paul Marquess, Charles Bailey, myself and others.
  317.  
  318. Larry Wall designed the elegant inherited bootstrap mechanism and
  319. implemented the first Perl 5 dynamic loader using it.
  320.  
  321. =cut
  322.  
  323. #
  324. #   And Gandalf said: 'Many folk like to know beforehand what is to
  325. #   be set on the table; but those who have laboured to prepare the
  326. #   feast like to keep their secret; for wonder makes the words of
  327. #   praise louder.'
  328. #
  329.  
  330. # Quote from Tolkien sugested by Anno Siegel.
  331. #
  332. # Read ext/DynaLoader/README for detailed information.
  333. #
  334. # Tim.Bunce@ig.co.uk, August 1994
  335.  
  336. use Config;
  337. use Carp;
  338. use AutoLoader;
  339.  
  340. @ISA=qw(AutoLoader);
  341.  
  342.  
  343. # enable messages from DynaLoader perl code
  344. $dl_debug = 0 unless $dl_debug;
  345. $dl_debug = $ENV{'PERL_DL_DEBUG'} if $ENV{'PERL_DL_DEBUG'};
  346.  
  347. $dl_so = $dl_dlext = ""; # avoid typo warnings
  348. $dl_so = $Config{'so'}; # suffix for shared libraries
  349. $dl_dlext = $Config{'dlext'}; # suffix for dynamic modules
  350.  
  351. # Some systems need special handling to expand file specifications
  352. # (VMS support by Charles Bailey <bailey@HMIVAX.HUMGEN.UPENN.EDU>)
  353. # See dl_expandspec() for more details. Should be harmless but
  354. # inefficient to define on systems that don't need it.
  355. $do_expand = ($Config{'osname'} eq 'VMS');
  356.  
  357. @dl_require_symbols = ();       # names of symbols we need
  358. @dl_resolve_using   = ();       # names of files to link with
  359. @dl_library_path    = ();       # path to look for files
  360.  
  361. # This is a fix to support DLD's unfortunate desire to relink -lc
  362. @dl_resolve_using = dl_findfile('-lc') if $Config{'dlsrc'} eq "dl_dld.xs";
  363.  
  364. # Initialise @dl_library_path with the 'standard' library path
  365. # for this platform as determined by Configure
  366. push(@dl_library_path, split(' ',$Config{'libpth'}));
  367.  
  368. # Add to @dl_library_path any extra directories we can gather from
  369. # environment variables. So far LD_LIBRARY_PATH is the only known
  370. # variable used for this purpose. Others may be added later.
  371. push(@dl_library_path, split(/:/, $ENV{'LD_LIBRARY_PATH'}))
  372.     if $ENV{'LD_LIBRARY_PATH'};
  373.  
  374.  
  375. # No prizes for guessing why we don't say 'bootstrap DynaLoader;' here.
  376. boot_DynaLoader() if defined(&boot_DynaLoader);
  377.  
  378.  
  379. if ($dl_debug){
  380.     print STDERR "DynaLoader.pm loaded (@dl_library_path)\n";
  381.     print STDERR "DynaLoader not linked into this perl\n"
  382.         unless defined(&boot_DynaLoader);
  383. }
  384.  
  385. 1; # End of main code
  386.  
  387.  
  388. # The bootstrap function cannot be autoloaded (without complications)
  389. # so we define it here:
  390.  
  391. sub bootstrap {
  392.     # use local vars to enable $module.bs script to edit values
  393.     local(@args) = @_;
  394.     local($module) = $args[0];
  395.     local(@dirs, $file);
  396.  
  397.     confess "Usage: DynaLoader::bootstrap(module)" unless $module;
  398.  
  399.     # A common error on platforms which don't support dynamic loading.
  400.     # Since it's fatal and potentially confusing we give a detailed message.
  401.     croak("Can't load module $module, dynamic loading not available in this perl.\n".
  402.     "  (You may need to build a new perl executable which either supports\n".
  403.     "  dynamic loading or has the $module module statically linked into it.)\n")
  404.     unless defined(&dl_load_file);
  405.  
  406.     print STDERR "DynaLoader::bootstrap($module)\n" if $dl_debug;
  407.  
  408.     my(@modparts) = split(/::/,$module);
  409.     my($modfname) = $modparts[-1];
  410.     my($modpname) = join('/',@modparts);
  411.     foreach (@INC) {
  412.     my $dir = "$_/auto/$modpname";
  413.     next unless -d $dir; # skip over uninteresting directories
  414.  
  415.     # check for common cases to avoid autoload of dl_findfile
  416.     last if ($file=_check_file("$dir/$modfname.$dl_dlext"));
  417.  
  418.     # no luck here, save dir for possible later dl_findfile search
  419.     push(@dirs, "-L$dir");
  420.     }
  421.     # last resort, let dl_findfile have a go in all known locations
  422.     $file = dl_findfile(@dirs, map("-L$_",@INC), $modfname) unless $file;
  423.  
  424.     croak "Can't find loadable object for module $module in \@INC"
  425.         unless $file;
  426.  
  427.     my($bootname) = "boot_$module";
  428.     $bootname =~ s/\W/_/g;
  429.     @dl_require_symbols = ($bootname);
  430.  
  431.     # Execute optional '.bootstrap' perl script for this module.
  432.     # The .bs file can be used to configure @dl_resolve_using etc to
  433.     # match the needs of the individual module on this architecture.
  434.     my $bs = $file;
  435.     $bs =~ s/(\.\w+)?$/\.bs/; # look for .bs 'beside' the library
  436.     if (-s $bs) { # only read file if it's not empty
  437.         local($osname, $dlsrc) = @Config{'osname','dlsrc'};
  438.         print STDERR "BS: $bs ($osname, $dlsrc)\n" if $dl_debug;
  439.         eval { do $bs; };
  440.         warn "$bs: $@\n" if $@;
  441.     }
  442.  
  443.     # Many dynamic extension loading problems will appear to come from
  444.     # this section of code: XYZ failed at line 123 of DynaLoader.pm.
  445.     # Often these errors are actually occurring in the initialisation
  446.     # C code of the extension XS file. Perl reports the error as being
  447.     # in this perl code simply because this was the last perl code
  448.     # it executed.
  449.  
  450.     my $libref = dl_load_file($file) or
  451.     croak "Can't load '$file' for module $module: ".dl_error()."\n";
  452.  
  453.     my(@unresolved) = dl_undef_symbols();
  454.     carp "Undefined symbols present after loading $file: @unresolved\n"
  455.         if (@unresolved);
  456.  
  457.     my $boot_symbol_ref = dl_find_symbol($libref, $bootname) or
  458.          croak "Can't find '$bootname' symbol in $file\n";
  459.  
  460.     dl_install_xsub("${module}::bootstrap", $boot_symbol_ref, $file);
  461.  
  462.     # See comment block above
  463.     &{"${module}::bootstrap"}(@args);
  464. }
  465.  
  466.  
  467. sub _check_file{   # private utility to handle dl_expandspec vs -f tests
  468.     my($file) = @_;
  469.     return $file if (!$do_expand && -f $file); # the common case
  470.     return $file if ( $do_expand && ($file=dl_expandspec($file)));
  471.     return undef;
  472. }
  473.  
  474.  
  475. # Let autosplit and the autoloader deal with these functions:
  476. __END__
  477.  
  478.  
  479. sub dl_findfile {
  480.     # Read ext/DynaLoader/DynaLoader.doc for detailed information.
  481.     # This function does not automatically consider the architecture
  482.     # or the perl library auto directories.
  483.     my (@args) = @_;
  484.     my (@dirs,  $dir);   # which directories to search
  485.     my (@found);         # full paths to real files we have found
  486.     my ($vms) = ($Config{'osname'} eq 'VMS');
  487.  
  488.     print STDERR "dl_findfile(@args)\n" if $dl_debug;
  489.  
  490.     # accumulate directories but process files as they appear
  491.     arg: foreach(@args) {
  492.         #  Special fast case: full filepath requires no search
  493.         if (m:/: && -f $_ && !$do_expand){
  494.         push(@found,$_);
  495.         last arg unless wantarray;
  496.         next;
  497.     }
  498.  
  499.         # Deal with directories first:
  500.         #  Using a -L prefix is the preferred option (faster and more robust)
  501.         if (m:^-L:){ s/^-L//; push(@dirs, $_); next; }
  502.  
  503.         #  Otherwise we try to try to spot directories by a heuristic
  504.         #  (this is a more complicated issue than it first appears)
  505.         if (m:/: && -d $_){   push(@dirs, $_); next; }
  506.  
  507.         # VMS: we may be using native VMS directry syntax instead of
  508.         # Unix emulation, so check this as well
  509.         if ($vms && /[:>\]]/ && -d $_){   push(@dirs, $_); next; }
  510.  
  511.         #  Only files should get this far...
  512.         my(@names, $name);    # what filenames to look for
  513.         if (m:-l: ){          # convert -lname to appropriate library name
  514.             s/-l//;
  515.             push(@names,"lib$_.$dl_so");
  516.             push(@names,"lib$_.a");
  517.         }else{                # Umm, a bare name. Try various alternatives:
  518.             # these should be ordered with the most likely first
  519.             push(@names,"$_.$dl_so")     unless m/\.$dl_so$/o;
  520.             push(@names,"lib$_.$dl_so")  unless m:/:;
  521.             push(@names,"$_.o")          unless m/\.(o|$dl_so)$/o;
  522.             push(@names,"$_.a")          unless m/\.a$/;
  523.             push(@names, $_);
  524.         }
  525.         foreach $dir (@dirs, @dl_library_path) {
  526.             next unless -d $dir;
  527.             foreach $name (@names) {
  528.         my($file) = "$dir/$name";
  529.                 print STDERR " checking in $dir for $name\n" if $dl_debug;
  530.         $file = _check_file($file);
  531.         if ($file){
  532.                     push(@found, $file);
  533.                     next arg; # no need to look any further
  534.                 }
  535.             }
  536.         }
  537.     }
  538.     if ($dl_debug) {
  539.         foreach(@dirs) {
  540.             print STDERR " dl_findfile ignored non-existent directory: $_\n" unless -d $_;
  541.         }
  542.         print STDERR "dl_findfile found: @found\n";
  543.     }
  544.     return $found[0] unless wantarray;
  545.     @found;
  546. }
  547.  
  548.  
  549. sub dl_expandspec{
  550.     my($spec) = @_;
  551.     # Optional function invoked if DynaLoader.pm sets $do_expand.
  552.     # Most systems do not require or use this function.
  553.     # Some systems may implement it in the dl_*.xs file in which case
  554.     # this autoload version will not be called but is harmless.
  555.  
  556.     # This function is designed to deal with systems which treat some
  557.     # 'filenames' in a special way. For example VMS 'Logical Names'
  558.     # (something like unix environment variables - but different).
  559.     # This function should recognise such names and expand them into
  560.     # full file paths.
  561.     # Must return undef if $spec is invalid or file does not exist.
  562.  
  563.     my($file)   = $spec; # default output to input
  564.     my($osname) = $Config{'osname'};
  565.  
  566.     if ($osname eq 'VMS'){ # dl_expandspec should be defined in dl_vms.xs
  567.     croak "dl_expandspec: should be defined in XS file!\n";
  568.     }else{
  569.     return undef unless -f $file;
  570.     }
  571.     print STDERR "dl_expandspec($spec) => $file\n" if $dl_debug;
  572.     $file;
  573. }
  574.