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