1use Config;
2
3use strict;
4use warnings;
5
6sub to_string {
7    my ($value) = @_;
8    $value =~ s/\\/\\\\/g;
9    $value =~ s/'/\\'/g;
10    return "'$value'";
11}
12
13#
14# subroutine expand_os_specific expands $^O-specific preprocessing information
15# so that it will not be re-calculated at runtime in Dynaloader.pm
16#
17# Syntax of preprocessor should be kept extremely simple:
18#  - directives are in double angle brackets <<...>>
19#  - <<=string>> will be just evaluated
20#  - for $^O-specific there are two forms:
21#   <<$^O-eq-osname>>
22#   <<$^O-ne-osname>>
23#  this directive should be closed with respectively
24#   <</$^O-eq-osname>>
25#   <</$^O-ne-osname>>
26#  construct <<|$^O-ne-osname>> means #else
27#  nested <<$^O...>>-constructs are allowed but nested values must be for
28#   different OS-names!
29#
30#  -- added by VKON, 03-10-2004 to separate $^O-specific between OSes
31#     (so that Win32 never checks for $^O eq 'VMS' for example)
32#
33# The $^O tests test both for $^O and for $Config{osname}.
34# The latter is better for some for cross-compilation setups.
35#
36sub expand_os_specific {
37    my $s = shift;
38    for ($s) {
39	s/<<=(.*?)>>/$1/gee;
40	s/<<\$\^O-(eq|ne)-(\w+)>>(.*?)<<\/\$\^O-\1-\2>>/
41	  my ($op, $os, $expr) = ($1,$2,$3);
42	  if ($op ne 'eq' and $op ne 'ne') {die "wrong eq-ne arg in $&"};
43	  if ($expr =~ m[^(.*?)<<\|\$\^O-$op-$os>>(.*?)$]s) {
44	      # #if;#else;#endif
45	      my ($if,$el) = ($1,$2);
46	      if (($op eq 'eq' and ($^O eq $os || $Config{osname} eq $os)) || ($op eq 'ne' and ($^O ne $os || $Config{osname} ne $os))) {
47		  $if
48	      }
49	      else {
50		  $el
51	      }
52	  }
53	  else {
54	      # #if;#endif
55	      if (($op eq 'eq' and ($^O eq $os || $Config{osname} eq $os)) || ($op eq 'ne' and ($^O ne $os || $Config{osname} ne $os))) {
56		  $expr
57	      }
58	      else {
59	      	  ""
60	      }
61	  }
62	/ges;
63	if (/<<(=|\$\^O-)/) {die "bad <<\$^O-eq/ne-osname>> expression.".
64	    " Unclosed brackets?";
65	}
66    }
67    $s;
68}
69
70unlink "DynaLoader.pm" if -f "DynaLoader.pm";
71open OUT, '>', "DynaLoader.pm" or die $!;
72print OUT <<'EOT';
73
74# Generated from DynaLoader_pm.PL, this file is unique for every OS
75
76use strict;
77
78package DynaLoader;
79
80#   And Gandalf said: 'Many folk like to know beforehand what is to
81#   be set on the table; but those who have laboured to prepare the
82#   feast like to keep their secret; for wonder makes the words of
83#   praise louder.'
84
85#   (Quote from Tolkien suggested by Anno Siegel.)
86#
87# See pod text at end of file for documentation.
88# See also ext/DynaLoader/README in source tree for other information.
89#
90# Tim.Bunce@ig.co.uk, August 1994
91
92BEGIN {
93    our $VERSION = '1.54';
94}
95
96# Note: in almost any other piece of code "our" would have been a better
97# option than "use vars", but DynaLoader's bootstrap files need the
98# side effect of the variable being declared in any scope whose current
99# package is DynaLoader, not just the current lexical one.
100use vars qw(@dl_library_path @dl_resolve_using @dl_require_symbols
101            $dl_debug @dl_librefs @dl_modules @dl_shared_objects
102            $dl_dlext $dl_so $dlsrc @args $module @dirs $file $bscode);
103
104EOT
105
106if (!$ENV{PERL_BUILD_EXPAND_CONFIG_VARS}) {
107    print OUT "use Config;\n";
108}
109
110print OUT <<'EOT';
111
112# enable debug/trace messages from DynaLoader perl code
113$dl_debug = $ENV{PERL_DL_DEBUG} || 0 unless defined $dl_debug;
114
115#
116# Flags to alter dl_load_file behaviour.  Assigned bits:
117#   0x01  make symbols available for linking later dl_load_file's.
118#         (only known to work on Solaris 2 using dlopen(RTLD_GLOBAL))
119#         (ignored under VMS; effect is built-in to image linking)
120#         (ignored under Android; the linker always uses RTLD_LOCAL)
121#
122# This is called as a class method $module->dl_load_flags.  The
123# definition here will be inherited and result on "default" loading
124# behaviour unless a sub-class of DynaLoader defines its own version.
125#
126
127sub dl_load_flags { 0x00 }
128
129EOT
130
131if ($ENV{PERL_BUILD_EXPAND_CONFIG_VARS}) {
132    print OUT "(\$dl_dlext, \$dl_so, \$dlsrc) = (",
133              to_string($Config{'dlext'}), ",",
134              to_string($Config{'so'}), ",",
135              to_string($Config{'dlsrc'}), ")\n;" ;
136}
137else {
138    print OUT <<'EOT';
139($dl_dlext, $dl_so, $dlsrc) = @Config::Config{qw(dlext so dlsrc)};
140EOT
141}
142
143my @dl_library_path;
144
145print OUT expand_os_specific(<<'EOT');
146
147# Some systems need special handling to expand file specifications
148# (VMS support by Charles Bailey <bailey@HMIVAX.HUMGEN.UPENN.EDU>)
149# See dl_expandspec() for more details. Should be harmless but
150# inefficient to define on systems that don't need it.
151my $do_expand = <<$^O-eq-VMS>>1<<|$^O-eq-VMS>>0<</$^O-eq-VMS>>;
152
153@dl_require_symbols = ();       # names of symbols we need<<$^O-eq-freemint>>
154@dl_resolve_using   = ();       # names of files to link with<</$^O-eq-freemint>><<$^O-eq-hpux>>
155@dl_resolve_using   = ();       # names of files to link with<</$^O-eq-hpux>>
156@dl_library_path    = ();       # path to look for files
157
158#XSLoader.pm may have added elements before we were required
159#@dl_shared_objects  = ();       # shared objects for symbols we have
160#@dl_librefs         = ();       # things we have loaded
161#@dl_modules         = ();       # Modules we have loaded
162
163EOT
164
165my $cfg_dl_library_path = <<'EOT';
166push(@dl_library_path, split(' ', $Config::Config{libpth}));
167EOT
168
169sub dquoted_comma_list {
170    join(", ", map {'"'.quotemeta($_).'"'} @_);
171}
172
173if ($ENV{PERL_BUILD_EXPAND_CONFIG_VARS}) {
174    eval $cfg_dl_library_path;
175    if (!$ENV{PERL_BUILD_EXPAND_ENV_VARS}) {
176        my $dl_library_path = dquoted_comma_list(@dl_library_path);
177        print OUT <<EOT;
178# The below \@dl_library_path has been expanded (%Config) in Perl build time.
179
180\@dl_library_path = ($dl_library_path);
181
182EOT
183    }
184}
185else {
186    print OUT <<EOT;
187# Initialise \@dl_library_path with the 'standard' library path
188# for this platform as determined by Configure.
189
190$cfg_dl_library_path
191
192EOT
193}
194
195my $ldlibpthname;
196my $ldlibpthname_defined;
197my $pthsep;
198
199if ($ENV{PERL_BUILD_EXPAND_CONFIG_VARS}) {
200    $ldlibpthname         = to_string($Config::Config{ldlibpthname});
201    $ldlibpthname_defined = to_string(defined $Config::Config{ldlibpthname} ? 1 : 0);
202    $pthsep               = to_string($Config::Config{path_sep});
203}
204else {
205    $ldlibpthname         = q($Config::Config{ldlibpthname});
206    $ldlibpthname_defined = q(defined $Config::Config{ldlibpthname});
207    $pthsep               = q($Config::Config{path_sep});
208}
209print OUT <<EOT;
210my \$ldlibpthname         = $ldlibpthname;
211my \$ldlibpthname_defined = $ldlibpthname_defined;
212my \$pthsep               = $pthsep;
213
214EOT
215
216my $env_dl_library_path = <<'EOT';
217if ($ldlibpthname_defined &&
218    exists $ENV{$ldlibpthname}) {
219    push(@dl_library_path, split(/$pthsep/, $ENV{$ldlibpthname}));
220}
221
222# E.g. HP-UX supports both its native SHLIB_PATH *and* LD_LIBRARY_PATH.
223
224if ($ldlibpthname_defined &&
225    $ldlibpthname ne 'LD_LIBRARY_PATH' &&
226    exists $ENV{LD_LIBRARY_PATH}) {
227    push(@dl_library_path, split(/$pthsep/, $ENV{LD_LIBRARY_PATH}));
228}
229EOT
230
231if ($ENV{PERL_BUILD_EXPAND_CONFIG_VARS} && $ENV{PERL_BUILD_EXPAND_ENV_VARS}) {
232    eval $env_dl_library_path;
233}
234else {
235    print OUT <<EOT;
236# Add to \@dl_library_path any extra directories we can gather from environment
237# during runtime.
238
239$env_dl_library_path
240
241EOT
242}
243
244if ($ENV{PERL_BUILD_EXPAND_CONFIG_VARS} && $ENV{PERL_BUILD_EXPAND_ENV_VARS}) {
245    my $dl_library_path = dquoted_comma_list(@dl_library_path);
246    print OUT <<EOT;
247# The below \@dl_library_path has been expanded (%Config, %ENV)
248# in Perl build time.
249
250\@dl_library_path = ($dl_library_path);
251
252EOT
253}
254
255if ( $Config::Config{d_libname_unique} ) {
256    printf OUT <<'EOT', length($Config::Config{dlext}) + 1;
257sub mod2fname {
258    my $parts = shift;
259    my $so_len = %d;
260    my $name_max = 255; # No easy way to get this here
261
262    my $libname = "PL_" .  join("__", @$parts);
263
264    return $libname if (length($libname)+$so_len) <= $name_max;
265
266    # It's too darned big, so we need to go strip. We use the same
267    # algorithm as xsubpp does. First, strip out doubled __
268    $libname =~ s/__/_/g;
269    return $libname if (length($libname)+$so_len) <= $name_max;
270
271    # Strip duplicate letters
272    1 while $libname =~ s/(.)\1/\U$1/i;
273    return $libname if (length($libname)+$so_len) <= $name_max;
274
275    # Still too long. Truncate.
276    $libname = substr($libname, 0, $name_max - $so_len);
277    return $libname;
278}
279EOT
280}
281
282# following long string contains $^O-specific stuff, which is factored out
283print OUT expand_os_specific(<<'EOT');
284# No prizes for guessing why we don't say 'bootstrap DynaLoader;' here.
285# NOTE: All dl_*.xs (including dl_none.xs) define a dl_error() XSUB
286boot_DynaLoader('DynaLoader') if defined(&boot_DynaLoader) &&
287                                !defined(&dl_error);
288
289if ($dl_debug) {
290    print STDERR "DynaLoader.pm loaded (@INC, @dl_library_path)\n";
291    print STDERR "DynaLoader not linked into this perl\n"
292	    unless defined(&boot_DynaLoader);
293}
294
2951; # End of main code
296
297
298sub croak   { require Carp; Carp::croak(@_)   }
299
300sub bootstrap_inherit {
301    my $module = $_[0];
302
303    no strict qw/refs vars/;
304    local *isa = *{"$module\::ISA"};
305    local @isa = (@isa, 'DynaLoader');
306    # Cannot goto due to delocalization.  Will report errors on a wrong line?
307    bootstrap(@_);
308}
309
310sub bootstrap {
311    # use local vars to enable $module.bs script to edit values
312    local(@args) = @_;
313    local($module) = $args[0];
314    local(@dirs, $file);
315
316    unless ($module) {
317	require Carp;
318	Carp::confess("Usage: DynaLoader::bootstrap(module)");
319    }
320
321    # A common error on platforms which don't support dynamic loading.
322    # Since it's fatal and potentially confusing we give a detailed message.
323    croak("Can't load module $module, dynamic loading not available in this perl.\n".
324	"  (You may need to build a new perl executable which either supports\n".
325	"  dynamic loading or has the $module module statically linked into it.)\n")
326	unless defined(&dl_load_file);
327
328
329    <<$^O-eq-os2>>
330    # Can dynaload, but cannot dynaload Perl modules...
331    die 'Dynaloaded Perl modules are not available in this build of Perl' if $OS2::is_static;
332
333    <</$^O-eq-os2>>
334    my @modparts = split(/::/,$module);
335    my $modfname = $modparts[-1];
336    my $modfname_orig = $modfname; # For .bs file search
337
338    # Some systems have restrictions on files names for DLL's etc.
339    # mod2fname returns appropriate file base name (typically truncated)
340    # It may also edit @modparts if required.
341    $modfname = &mod2fname(\@modparts) if defined &mod2fname;
342
343    my $modpname = join('/',@modparts);
344
345    print STDERR "DynaLoader::bootstrap for $module ",
346		       "(auto/$modpname/$modfname.$dl_dlext)\n"
347	if $dl_debug;
348
349    my $dir;
350    foreach (@INC) {
351	<<$^O-eq-VMS>>chop($_ = VMS::Filespec::unixpath($_));<</$^O-eq-VMS>>
352	    $dir = "$_/auto/$modpname";
353
354	next unless -d $dir; # skip over uninteresting directories
355
356	# check for common cases to avoid autoload of dl_findfile
357        my $try = "$dir/$modfname.$dl_dlext";
358	last if $file = ($do_expand) ? dl_expandspec($try) : ((-f $try) && $try);
359
360	# no luck here, save dir for possible later dl_findfile search
361	push @dirs, $dir;
362    }
363    # last resort, let dl_findfile have a go in all known locations
364    $file = dl_findfile(map("-L$_",@dirs,@INC), $modfname) unless $file;
365
366    croak("Can't locate loadable object for module $module in \@INC (\@INC contains: @INC)")
367	unless $file;	# wording similar to error from 'require'
368
369    <<$^O-eq-VMS>>$file = uc($file) if $Config::Config{d_vms_case_sensitive_symbols};<</$^O-eq-VMS>>
370    my $bootname = "boot_$module";
371    $bootname =~ s/\W/_/g;
372    @dl_require_symbols = ($bootname);
373
374    # Execute optional '.bootstrap' perl script for this module.
375    # The .bs file can be used to configure @dl_resolve_using etc to
376    # match the needs of the individual module on this architecture.
377    # N.B. The .bs file does not following the naming convention used
378    # by mod2fname.
379    my $bs = "$dir/$modfname_orig";
380    $bs =~ s/(\.\w+)?(;\d*)?$/\.bs/; # look for .bs 'beside' the library
381    if (-s $bs) { # only read file if it's not empty
382        print STDERR "BS: $bs ($^O, $dlsrc)\n" if $dl_debug;
383        eval { local @INC = ('.'); do $bs; };
384        warn "$bs: $@\n" if $@;
385    }
386
387    my $boot_symbol_ref;
388
389    <<$^O-eq-darwin>>
390    if ($boot_symbol_ref = dl_find_symbol(0, $bootname, 1)) {
391        goto boot; #extension library has already been loaded, e.g. darwin
392    }
393    <</$^O-eq-darwin>>
394
395    # Many dynamic extension loading problems will appear to come from
396    # this section of code: XYZ failed at line 123 of DynaLoader.pm.
397    # Often these errors are actually occurring in the initialisation
398    # C code of the extension XS file. Perl reports the error as being
399    # in this perl code simply because this was the last perl code
400    # it executed.
401
402    my $flags = $module->dl_load_flags;
403    <<$^O-eq-android>>
404    # See the note above regarding the linker.
405    $flags = 0x00;
406    <</$^O-eq-android>>
407    my $libref = dl_load_file($file, $flags) or
408	croak("Can't load '$file' for module $module: ".dl_error());
409
410    push(@dl_librefs,$libref);  # record loaded object
411<<$^O-eq-freemint>>
412    my @unresolved = dl_undef_symbols();
413    if (@unresolved) {
414	require Carp;
415	Carp::carp("Undefined symbols present after loading $file: @unresolved\n");
416    }
417<</$^O-eq-freemint>>
418    $boot_symbol_ref = dl_find_symbol($libref, $bootname) or
419         croak("Can't find '$bootname' symbol in $file\n");
420
421    push(@dl_modules, $module); # record loaded module
422
423  boot:
424    my $xs = dl_install_xsub("${module}::bootstrap", $boot_symbol_ref, $file);
425
426    # See comment block above
427
428	push(@dl_shared_objects, $file); # record files loaded
429
430    &$xs(@args);
431}
432
433sub dl_findfile {
434    # This function does not automatically consider the architecture
435    # or the perl library auto directories.
436    my (@args) = @_;
437    my (@dirs,  $dir);   # which directories to search
438    my (@found);         # full paths to real files we have found
439    #my $dl_ext= <<=to_string($Config::Config{'dlext'})>>; # $Config::Config{'dlext'} suffix for perl extensions
440    #my $dl_so = <<=to_string($Config::Config{'so'})>>; # $Config::Config{'so'} suffix for shared libraries
441
442    print STDERR "dl_findfile(@args)\n" if $dl_debug;
443
444    # accumulate directories but process files as they appear
445    arg: foreach(@args) {
446        #  Special fast case: full filepath requires no search
447	<<$^O-eq-VMS>>
448        if (m%[:>/\]]% && -f $_) {
449	    push(@found,dl_expandspec(VMS::Filespec::vmsify($_)));
450	    last arg unless wantarray;
451	    next;
452        }
453	<</$^O-eq-VMS>>
454	<<$^O-ne-VMS>>
455        if (m:/: && -f $_) {
456	    push(@found,$_);
457	    last arg unless wantarray;
458	    next;
459	}
460	<</$^O-ne-VMS>>
461
462        # Deal with directories first:
463        #  Using a -L prefix is the preferred option (faster and more robust)
464        if ( s{^-L}{} ) { push(@dirs, $_); next; }
465
466        #  Otherwise we try to try to spot directories by a heuristic
467        #  (this is a more complicated issue than it first appears)
468        if (m:/: && -d $_) {   push(@dirs, $_); next; }
469
470	<<$^O-eq-VMS>>
471        # VMS: we may be using native VMS directory syntax instead of
472        # Unix emulation, so check this as well
473        if (/[:>\]]/ && -d $_) {   push(@dirs, $_); next; }
474	<</$^O-eq-VMS>>
475
476        #  Only files should get this far...
477        my(@names, $name);    # what filenames to look for
478        if ( s{^-l}{} ) {          # convert -lname to appropriate library name
479            push(@names, "lib$_.$dl_so", "lib$_.a");
480        } else {                # Umm, a bare name. Try various alternatives:
481            # these should be ordered with the most likely first
482            push(@names,"$_.$dl_dlext")    unless m/\.$dl_dlext$/o;
483            push(@names,"$_.$dl_so")     unless m/\.$dl_so$/o;
484	    <<$^O-eq-cygwin>>
485            push(@names,"cyg$_.$dl_so")  unless m:/:;
486	    <</$^O-eq-cygwin>>
487            push(@names,"lib$_.$dl_so")  unless m:/:;
488            push(@names, $_);
489        }
490	my $dirsep = '/';
491        foreach $dir (@dirs, @dl_library_path) {
492            next unless -d $dir;
493	    <<$^O-eq-VMS>>
494            chop($dir = VMS::Filespec::unixpath($dir));
495	    <</$^O-eq-VMS>>
496            foreach $name (@names) {
497		my($file) = "$dir$dirsep$name";
498                print STDERR " checking in $dir for $name\n" if $dl_debug;
499		if ($do_expand && ($file = dl_expandspec($file))) {
500                    push @found, $file;
501                    next arg; # no need to look any further
502		}
503		elsif (-f $file) {
504                    push(@found, $file);
505                    next arg; # no need to look any further
506                }
507		<<$^O-eq-darwin>>
508		elsif (dl_load_file($file, 0)) {
509                    push @found, $file;
510                    next arg; # no need to look any further
511		}
512		<</$^O-eq-darwin>>
513            }
514        }
515    }
516    if ($dl_debug) {
517        foreach(@dirs) {
518            print STDERR " dl_findfile ignored non-existent directory: $_\n" unless -d $_;
519        }
520        print STDERR "dl_findfile found: @found\n";
521    }
522    return $found[0] unless wantarray;
523    @found;
524}
525
526
527<<$^O-eq-VMS>>
528# dl_expandspec should be defined in dl_vms.xs
529<<|$^O-eq-VMS>>
530sub dl_expandspec {
531    my($spec) = @_;
532    # Optional function invoked if DynaLoader.pm sets $do_expand.
533    # Most systems do not require or use this function.
534    # Some systems may implement it in the dl_*.xs file in which case
535    # this Perl version should be excluded at build time.
536
537    # This function is designed to deal with systems which treat some
538    # 'filenames' in a special way. For example VMS 'Logical Names'
539    # (something like unix environment variables - but different).
540    # This function should recognise such names and expand them into
541    # full file paths.
542    # Must return undef if $spec is invalid or file does not exist.
543
544    my $file = $spec; # default output to input
545
546	return undef unless -f $file;
547    print STDERR "dl_expandspec($spec) => $file\n" if $dl_debug;
548    $file;
549}
550<</$^O-eq-VMS>>
551
552sub dl_find_symbol_anywhere
553{
554    my $sym = shift;
555    my $libref;
556    foreach $libref (@dl_librefs) {
557	my $symref = dl_find_symbol($libref,$sym,1);
558	return $symref if $symref;
559    }
560    return undef;
561}
562
563__END__
564
565=head1 NAME
566
567DynaLoader - Dynamically load C libraries into Perl code
568
569=head1 SYNOPSIS
570
571    package YourPackage;
572    require DynaLoader;
573    @ISA = qw(... DynaLoader ...);
574    __PACKAGE__->bootstrap;
575
576    # optional method for 'global' loading
577    sub dl_load_flags { 0x01 }
578
579
580=head1 DESCRIPTION
581
582This document defines a standard generic interface to the dynamic
583linking mechanisms available on many platforms.  Its primary purpose is
584to implement automatic dynamic loading of Perl modules.
585
586This document serves as both a specification for anyone wishing to
587implement the DynaLoader for a new platform and as a guide for
588anyone wishing to use the DynaLoader directly in an application.
589
590The DynaLoader is designed to be a very simple high-level
591interface that is sufficiently general to cover the requirements
592of SunOS, HP-UX, Linux, VMS and other platforms.
593
594It is also hoped that the interface will cover the needs of OS/2, NT
595etc and also allow pseudo-dynamic linking (using C<ld -A> at runtime).
596
597It must be stressed that the DynaLoader, by itself, is practically
598useless for accessing non-Perl libraries because it provides almost no
599Perl-to-C 'glue'.  There is, for example, no mechanism for calling a C
600library function or supplying arguments.  A C::DynaLib module
601is available from CPAN sites which performs that function for some
602common system types.  And since the year 2000, there's also Inline::C,
603a module that allows you to write Perl subroutines in C.  Also available
604from your local CPAN site.
605
606DynaLoader Interface Summary
607
608  @dl_library_path
609  @dl_resolve_using
610  @dl_require_symbols
611  $dl_debug
612  $dl_dlext
613  @dl_librefs
614  @dl_modules
615  @dl_shared_objects
616                                                  Implemented in:
617  bootstrap($modulename)                               Perl
618  @filepaths = dl_findfile(@names)                     Perl
619  $flags = $modulename->dl_load_flags                  Perl
620  $symref  = dl_find_symbol_anywhere($symbol)          Perl
621
622  $libref  = dl_load_file($filename, $flags)           C
623  $status  = dl_unload_file($libref)                   C
624  $symref  = dl_find_symbol($libref, $symbol)          C
625  @symbols = dl_undef_symbols()                        C
626  dl_install_xsub($name, $symref [, $filename])        C
627  $message = dl_error                                  C
628
629=over 4
630
631=item @dl_library_path
632
633The standard/default list of directories in which dl_findfile() will
634search for libraries etc.  Directories are searched in order:
635$dl_library_path[0], [1], ... etc
636
637@dl_library_path is initialised to hold the list of 'normal' directories
638(F</usr/lib>, etc) determined by B<Configure> (C<$Config{'libpth'}>).  This should
639ensure portability across a wide range of platforms.
640
641@dl_library_path should also be initialised with any other directories
642that can be determined from the environment at runtime (such as
643LD_LIBRARY_PATH for SunOS).
644
645After initialisation @dl_library_path can be manipulated by an
646application using push and unshift before calling dl_findfile().
647Unshift can be used to add directories to the front of the search order
648either to save search time or to override libraries with the same name
649in the 'normal' directories.
650
651The load function that dl_load_file() calls may require an absolute
652pathname.  The dl_findfile() function and @dl_library_path can be
653used to search for and return the absolute pathname for the
654library/object that you wish to load.
655
656=item @dl_resolve_using
657
658A list of additional libraries or other shared objects which can be
659used to resolve any undefined symbols that might be generated by a
660later call to load_file().
661
662This is only required on some platforms which do not handle dependent
663libraries automatically.  For example the Socket Perl extension
664library (F<auto/Socket/Socket.so>) contains references to many socket
665functions which need to be resolved when it's loaded.  Most platforms
666will automatically know where to find the 'dependent' library (e.g.,
667F</usr/lib/libsocket.so>).  A few platforms need to be told the
668location of the dependent library explicitly.  Use @dl_resolve_using
669for this.
670
671Example usage:
672
673    @dl_resolve_using = dl_findfile('-lsocket');
674
675=item @dl_require_symbols
676
677A list of one or more symbol names that are in the library/object file
678to be dynamically loaded.  This is only required on some platforms.
679
680=item @dl_librefs
681
682An array of the handles returned by successful calls to dl_load_file(),
683made by bootstrap, in the order in which they were loaded.
684Can be used with dl_find_symbol() to look for a symbol in any of
685the loaded files.
686
687=item @dl_modules
688
689An array of module (package) names that have been bootstrap'ed.
690
691=item @dl_shared_objects
692
693An array of file names for the shared objects that were loaded.
694
695=item dl_error()
696
697Syntax:
698
699    $message = dl_error();
700
701Error message text from the last failed DynaLoader function.  Note
702that, similar to errno in unix, a successful function call does not
703reset this message.
704
705Implementations should detect the error as soon as it occurs in any of
706the other functions and save the corresponding message for later
707retrieval.  This will avoid problems on some platforms (such as SunOS)
708where the error message is very temporary (e.g., dlerror()).
709
710=item $dl_debug
711
712Internal debugging messages are enabled when $dl_debug is set true.
713Currently setting $dl_debug only affects the Perl side of the
714DynaLoader.  These messages should help an application developer to
715resolve any DynaLoader usage problems.
716
717$dl_debug is set to C<$ENV{'PERL_DL_DEBUG'}> if defined.
718
719For the DynaLoader developer/porter there is a similar debugging
720variable added to the C code (see dlutils.c) and enabled if Perl was
721built with the B<-DDEBUGGING> flag.  This can also be set via the
722PERL_DL_DEBUG environment variable.  Set to 1 for minimal information or
723higher for more.
724
725=item $dl_dlext
726
727When specified (localised) in a module's F<.pm> file, indicates the extension
728which the module's loadable object will have. For example:
729
730    local $DynaLoader::dl_dlext = 'unusual_ext';
731
732would indicate that the module's loadable object has an extension of
733C<unusual_ext> instead of the more usual C<$Config{dlext}>.  NOTE: This also
734requires that the module's F<Makefile.PL> specify (in C<WriteMakefile()>):
735
736    DLEXT => 'unusual_ext',
737
738=item dl_findfile()
739
740Syntax:
741
742    @filepaths = dl_findfile(@names)
743
744Determine the full paths (including file suffix) of one or more
745loadable files given their generic names and optionally one or more
746directories.  Searches directories in @dl_library_path by default and
747returns an empty list if no files were found.
748
749Names can be specified in a variety of platform independent forms.  Any
750names in the form B<-lname> are converted into F<libname.*>, where F<.*> is
751an appropriate suffix for the platform.
752
753If a name does not already have a suitable prefix and/or suffix then
754the corresponding file will be searched for by trying combinations of
755prefix and suffix appropriate to the platform: "$name.o", "lib$name.*"
756and "$name".
757
758If any directories are included in @names they are searched before
759@dl_library_path.  Directories may be specified as B<-Ldir>.  Any other
760names are treated as filenames to be searched for.
761
762Using arguments of the form C<-Ldir> and C<-lname> is recommended.
763
764Example:
765
766    @dl_resolve_using = dl_findfile(qw(-L/usr/5lib -lposix));
767
768
769=item dl_expandspec()
770
771Syntax:
772
773    $filepath = dl_expandspec($spec)
774
775Some unusual systems, such as VMS, require special filename handling in
776order to deal with symbolic names for files (i.e., VMS's Logical Names).
777
778To support these systems a dl_expandspec() function can be implemented
779either in the F<dl_*.xs> file or code can be added to the dl_expandspec()
780function in F<DynaLoader.pm>.  See F<DynaLoader_pm.PL> for more information.
781
782=item dl_load_file()
783
784Syntax:
785
786    $libref = dl_load_file($filename, $flags)
787
788Dynamically load $filename, which must be the path to a shared object
789or library.  An opaque 'library reference' is returned as a handle for
790the loaded object.  Returns undef on error.
791
792The $flags argument to alters dl_load_file behaviour.
793Assigned bits:
794
795 0x01  make symbols available for linking later dl_load_file's.
796       (only known to work on Solaris 2 using dlopen(RTLD_GLOBAL))
797       (ignored under VMS; this is a normal part of image linking)
798
799(On systems that provide a handle for the loaded object such as SunOS
800and HPUX, $libref will be that handle.  On other systems $libref will
801typically be $filename or a pointer to a buffer containing $filename.
802The application should not examine or alter $libref in any way.)
803
804This is the function that does the real work.  It should use the
805current values of @dl_require_symbols and @dl_resolve_using if required.
806
807    SunOS: dlopen($filename)
808    HP-UX: shl_load($filename)
809    Linux: dld_create_reference(@dl_require_symbols); dld_link($filename)
810    VMS:   lib$find_image_symbol($filename,$dl_require_symbols[0])
811
812(The dlopen() function is also used by Solaris and some versions of
813Linux, and is a common choice when providing a "wrapper" on other
814mechanisms as is done in the OS/2 port.)
815
816=item dl_unload_file()
817
818Syntax:
819
820    $status = dl_unload_file($libref)
821
822Dynamically unload $libref, which must be an opaque 'library reference' as
823returned from dl_load_file.  Returns one on success and zero on failure.
824This function is optional and may not necessarily be provided on all platforms.
825
826If it is defined and perl is compiled with the C macro C<DL_UNLOAD_ALL_AT_EXIT>
827defined, then it is called automatically when the interpreter exits for
828every shared object or library loaded by DynaLoader::bootstrap.  All such
829library references are stored in @dl_librefs by DynaLoader::Bootstrap as it
830loads the libraries.  The files are unloaded in last-in, first-out order.
831
832This unloading is usually necessary when embedding a shared-object perl (e.g.
833one configured with -Duseshrplib) within a larger application, and the perl
834interpreter is created and destroyed several times within the lifetime of the
835application.  In this case it is possible that the system dynamic linker will
836unload and then subsequently reload the shared libperl without relocating any
837references to it from any files DynaLoaded by the previous incarnation of the
838interpreter.  As a result, any shared objects opened by DynaLoader may point to
839a now invalid 'ghost' of the libperl shared object, causing apparently random
840memory corruption and crashes.  This behaviour is most commonly seen when using
841Apache and mod_perl built with the APXS mechanism.
842
843    SunOS: dlclose($libref)
844    HP-UX: ???
845    Linux: ???
846    VMS:   ???
847
848(The dlclose() function is also used by Solaris and some versions of
849Linux, and is a common choice when providing a "wrapper" on other
850mechanisms as is done in the OS/2 port.)
851
852=item dl_load_flags()
853
854Syntax:
855
856    $flags = dl_load_flags $modulename;
857
858Designed to be a method call, and to be overridden by a derived class
859(i.e. a class which has DynaLoader in its @ISA).  The definition in
860DynaLoader itself returns 0, which produces standard behavior from
861dl_load_file().
862
863=item dl_find_symbol()
864
865Syntax:
866
867    $symref = dl_find_symbol($libref, $symbol)
868
869Return the address of the symbol $symbol or C<undef> if not found.  If the
870target system has separate functions to search for symbols of different
871types then dl_find_symbol() should search for function symbols first and
872then other types.
873
874The exact manner in which the address is returned in $symref is not
875currently defined.  The only initial requirement is that $symref can
876be passed to, and understood by, dl_install_xsub().
877
878    SunOS: dlsym($libref, $symbol)
879    HP-UX: shl_findsym($libref, $symbol)
880    Linux: dld_get_func($symbol) and/or dld_get_symbol($symbol)
881    VMS:   lib$find_image_symbol($libref,$symbol)
882
883
884=item dl_find_symbol_anywhere()
885
886Syntax:
887
888    $symref = dl_find_symbol_anywhere($symbol)
889
890Applies dl_find_symbol() to the members of @dl_librefs and returns
891the first match found.
892
893=item dl_undef_symbols()
894
895Example
896
897    @symbols = dl_undef_symbols()
898
899Return a list of symbol names which remain undefined after load_file().
900Returns C<()> if not known.  Don't worry if your platform does not provide
901a mechanism for this.  Most do not need it and hence do not provide it,
902they just return an empty list.
903
904
905=item dl_install_xsub()
906
907Syntax:
908
909    dl_install_xsub($perl_name, $symref [, $filename])
910
911Create a new Perl external subroutine named $perl_name using $symref as
912a pointer to the function which implements the routine.  This is simply
913a direct call to newXS()/newXS_flags().  Returns a reference to the installed
914function.
915
916The $filename parameter is used by Perl to identify the source file for
917the function if required by die(), caller() or the debugger.  If
918$filename is not defined then "DynaLoader" will be used.
919
920
921=item bootstrap()
922
923Syntax:
924
925bootstrap($module [...])
926
927This is the normal entry point for automatic dynamic loading in Perl.
928
929It performs the following actions:
930
931=over 8
932
933=item *
934
935locates an auto/$module directory by searching @INC
936
937=item *
938
939uses dl_findfile() to determine the filename to load
940
941=item *
942
943sets @dl_require_symbols to C<("boot_$module")>
944
945=item *
946
947executes an F<auto/$module/$module.bs> file if it exists
948(typically used to add to @dl_resolve_using any files which
949are required to load the module on the current platform)
950
951=item *
952
953calls dl_load_flags() to determine how to load the file.
954
955=item *
956
957calls dl_load_file() to load the file
958
959=item *
960
961calls dl_undef_symbols() and warns if any symbols are undefined
962
963=item *
964
965calls dl_find_symbol() for "boot_$module"
966
967=item *
968
969calls dl_install_xsub() to install it as "${module}::bootstrap"
970
971=item *
972
973calls &{"${module}::bootstrap"} to bootstrap the module (actually
974it uses the function reference returned by dl_install_xsub for speed)
975
976=back
977
978All arguments to bootstrap() are passed to the module's bootstrap function.
979The default code generated by F<xsubpp> expects $module [, $version]
980If the optional $version argument is not given, it defaults to
981C<$XS_VERSION // $VERSION> in the module's symbol table. The default code
982compares the Perl-space version with the version of the compiled XS code,
983and croaks with an error if they do not match.
984
985=back
986
987
988=head1 AUTHOR
989
990Tim Bunce, 11 August 1994.
991
992This interface is based on the work and comments of (in no particular
993order): Larry Wall, Robert Sanders, Dean Roehrich, Jeff Okamoto, Anno
994Siegel, Thomas Neumann, Paul Marquess, Charles Bailey, myself and others.
995
996Larry Wall designed the elegant inherited bootstrap mechanism and
997implemented the first Perl 5 dynamic loader using it.
998
999Solaris global loading added by Nick Ing-Simmons with design/coding
1000assistance from Tim Bunce, January 1996.
1001
1002=cut
1003EOT
1004
1005close OUT or die $!;
1006
1007