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