6518bcc9218f709f408b310f53312be5c80bcfb2
[p5sagit/p5-mst-13.2.git] / lib / ExtUtils / MakeMaker.pm
1 package ExtUtils::MakeMaker;
2
3 $Version = 4.06; # Last edited 10th Feb 1995 by Andreas Koenig
4
5 use Config;
6 check_hints();
7 use Carp;
8 use Cwd;
9
10 require Exporter;
11 @ISA = qw(Exporter);
12 @EXPORT = qw(&WriteMakefile &mkbootstrap &mksymlists $Verbose);
13 @EXPORT_OK = qw($Version %att %skip %Recognized_Att_Keys
14         @MM_Sections %MM_Sections
15         &help &lsdir &neatvalue);
16
17 $Is_VMS = $Config{'osname'} eq 'VMS';
18 require ExtUtils::MM_VMS if $Is_VMS;
19
20 use strict qw(refs);
21
22 $Version = $Version;# avoid typo warning
23 $Verbose = 0;
24 $^W=1;
25
26
27 =head1 NAME
28
29 ExtUtils::MakeMaker - create an extension Makefile
30
31 =head1 SYNOPSIS
32
33 C<use ExtUtils::MakeMaker;>
34
35 C<WriteMakefile( ATTRIBUTE =E<gt> VALUE [, ...] );>
36
37 =head1 DESCRIPTION
38
39 This utility is designed to write a Makefile for an extension module
40 from a Makefile.PL. It is based on the Makefile.SH model provided by
41 Andy Dougherty and the perl5-porters.
42
43 It splits the task of generating the Makefile into several subroutines
44 that can be individually overridden.  Each subroutine returns the text
45 it wishes to have written to the Makefile.
46
47 MakeMaker.pm uses the architecture specific information from
48 Config.pm. In addition the extension may contribute to the C<%Config>
49 hash table of Config.pm by supplying hints files in a C<hints/>
50 directory. The hints files are expected to be named like their
51 counterparts in C<PERL_SRC/hints>, but with an C<.pl> file name
52 extension (eg. C<next_3_2.sh>). They are simply C<eval>ed by MakeMaker
53 and can be used to execute commands as well as to include special
54 variables. If there is no hintsfile for the actual system, but for
55 some previous releases of the same operating system, the latest one of
56 those is used.
57
58 =head2 Default Makefile Behaviour
59
60 The automatically generated Makefile enables the user of the extension
61 to invoke
62
63   perl Makefile.PL
64   make
65   make test
66   make install # May need to invoke as root to write into INST_LIB
67
68 The Makefile to be produced may be altered by adding arguments of the
69 form C<KEY=VALUE>. If the user wants to have the extension installed
70 into a directory different from C<$Config{"installprivlib"}> it can be
71 done by specifying
72
73   perl Makefile.PL INST_LIB=~/myperllib
74
75 Note, that in this example MakeMaker does the tilde expansion for you
76 and INST_ARCHLIB is set to either C<INST_LIB/$Config{"osname"}> if
77 that directory exists and otherwise to INST_LIB.
78
79 Other interesting targets in the generated Makefile are
80
81   make config     # to check if the Makefile is up-to-date
82   make clean      # delete local temporary files (Makefile gets renamed)
83   make realclean  # delete all derived files (including installed files)
84   make distclean  # produce a gzipped file ready for shipping
85
86 The macros in the produced Makefile may be overridden on the command
87 line to the make call as in the following example:
88
89   make INST_LIB=/some/where INST_ARCHLIB=/some/where
90
91 Note, that this is a solution provided by C<make> in general, so tilde
92 expansion will probably not be available and INST_ARCHLIB will not be
93 set automatically when INST_LIB is given as argument.
94
95 The generated Makefile does not set any permissions. The installer has
96 to decide, which umask should be in effect.
97
98 =head2 Support to Link a New Perl Binary
99
100 An extension that is built with the above steps is ready to use on
101 systems supporting dynamic loading. On systems that do not support
102 dynamic loading, any newly created extension has to be linked together
103 with the available ressources. MakeMaker supports the linking process
104 by creating appropriate targets in the Makefile whenever an extension
105 is built. You can invoke the corresponding section of the makefile with
106
107     make perl
108
109 That produces a new perl binary in the current directory with all
110 extensions that are present on the system (either in the current build
111 environment or in the perl library) linked in.
112
113 The binary can be installed into the directory where perl normally
114 resides on your machine with
115
116     make inst_perl
117
118 Note, that there is a C<makeaperl> scipt available, that supports the
119 linking of a new perl binary in a similar fashion, but with more
120 options for those, that want to build perl binaries of the
121 not-quite-everyday type. 
122
123 Warning: The perl: and inst_perl: targets are new in MakeMaker v4.06,
124 and should be watched with care. Watch out for what it does and what
125 you want!
126
127 =head2 Determination of Perl Library and Installation Locations
128
129 MakeMaker needs to know, or to guess, where certain things are
130 located.  Especially INST_LIB and INST_ARCHLIB (where to install files
131 into), PERL_LIB and PERL_ARCHLIB (where to read existing modules
132 from), and PERL_INC (header files and C<libperl*.*>).
133
134 Extensions may be built either using the contents of the perl source
135 directory tree or from an installed copy of the perl library.
136
137 If an extension is being built below the C<ext/> directory of the perl
138 source then MakeMaker will set PERL_SRC automatically (e.g., C<../..>).
139 If PERL_SRC is defined then other variables default to the following:
140
141   PERL_INC     = PERL_SRC
142   PERL_LIB     = PERL_SRC/lib
143   PERL_ARCHLIB = PERL_SRC/lib
144   INST_LIB     = PERL_LIB
145   INST_ARCHLIB = PERL_ARCHLIB
146
147 If an extension is being built away from the perl source then MakeMaker
148 will leave PERL_SRC undefined and default to using the installed copy
149 of the perl library. The other variables default to the following:
150
151   PERL_INC     = $archlib/CORE
152   PERL_LIB     = $privlib
153   PERL_ARCHLIB = $archlib
154   INST_LIB     = ./blib
155   INST_ARCHLIB = ./blib
156
157 If perl has not yet been installed then PERL_SRC can be defined on the
158 command line as shown in the previous section.
159
160 =head2 Useful Default Makefile Macros
161
162 FULLEXT = Pathname for extension directory (eg DBD/Oracle).
163
164 BASEEXT = Basename part of FULLEXT. May be just equal FULLEXT.
165
166 ROOTEXT = Directory part of FULLEXT with leading slash (eg /DBD)
167
168 PERL_LIB = Directory where we read the perl library files
169
170 PERL_ARCHLIB = Same as above for architecture dependent files
171
172 INST_LIB = Directory where we put library files of this extension
173 while building it. If we are building below PERL_SRC/ext
174 we default to PERL_SRC/lib, else we default to ./blib.
175
176 INST_ARCHLIB = Same as above for architecture dependent files
177
178 INST_LIBDIR = C<$(INST_LIB)$(ROOTEXT)>
179
180 INST_AUTODIR = C<$(INST_LIB)/auto/$(FULLEXT)>
181
182 INST_ARCHAUTODIR = C<$(INST_ARCHLIB)/auto/$(FULLEXT)>
183
184 =head2 Customizing The Generated Makefile
185
186 If the Makefile generated does not fit your purpose you can change it
187 using the mechanisms described below.
188
189 =head2 Using Attributes (and Parameters)
190
191 The following attributes can be specified as arguments to WriteMakefile()
192 or as NAME=VALUE pairs on the command line:
193
194 This description is not yet documented; you can get at the description
195 with the command
196
197 C<perl Makefile.PL help>    (if you already have a basic Makefile.PL)
198
199 or
200
201 C<perl -e 'use ExtUtils::MakeMaker qw(&help); &help;'>
202
203 =head2 Overriding MakeMaker Methods
204
205 If you cannot achieve the desired Makefile behaviour by specifying
206 attributes you may define private subroutines in the Makefile.PL.
207 Each subroutines returns the text it wishes to have written to
208 the Makefile. To override a section of the Makefile you can
209 either say:
210
211         sub MY::c_o { "new literal text" }
212
213 or you can edit the default by saying something like:
214
215         sub MY::c_o { $_=MM->c_o; s/old text/new text/; $_ }
216
217 If you still need a different solution, try to develop another
218 subroutine, that fits your needs and submit the diffs to
219 F<perl5-porters@nicoh.com> or F<comp.lang.perl> as appropriate.
220
221 =cut
222
223 sub check_hints {
224     # We allow extension-specific hints files. If we find one we act as if Config.pm
225     # had read the contents
226
227     # First we look for the best hintsfile we have
228     my(@goodhints);
229     my($hint)="$Config{'osname'}_$Config{'osvers'}";
230     $hint =~ s/\./_/g;
231     $hint =~ s/_$//;
232     opendir DIR, "hints";
233     while (defined ($_ = readdir DIR)) {
234         next if /^\./;
235         next unless s/\.pl$//;
236         next unless /^$Config{'osname'}/;
237         # Don't trust a hintfile for a later OS version:
238         next if $_ gt $hint;
239         push @goodhints, $_;
240         if ($_ eq $hint){
241             @goodhints=$_;
242             last;
243         }
244     }
245     closedir DIR;
246     return unless @goodhints; # There was no hintsfile
247     # the last one in lexical ordering is our choice:
248     $hint=(reverse sort @goodhints)[0];
249
250     # execute the hintsfile:
251     eval `cat hints/$hint.pl`;
252 }
253
254 # Setup dummy package:
255 # MY exists for overriding methods to be defined within
256 unshift(@MY::ISA, qw(MM));
257
258 # Dummy package MM inherits actual methods from OS-specific
259 # default packages.  We use this intermediate package so
260 # MY->func() can call MM->func() and get the proper
261 # default routine without having to know under what OS
262 # it's running.
263 unshift(@MM::ISA, $Is_VMS ? qw(ExtUtils::MM_VMS MM_Unix) : qw(MM_Unix));
264
265 $Attrib_Help = <<'END';
266  NAME:          Perl module name for this extension (DBD::Oracle)
267                 This will default to the directory name but should
268                 be explicitly defined in the Makefile.PL.
269
270  DISTNAME:      Your name for distributing the package (by tar file)
271                 This defaults to NAME above.
272
273  VERSION:       Your version number for distributing the package.
274                 This defaults to 0.1.
275
276  INST_LIB:      Perl library directory to install the module into.
277  INST_ARCHLIB:  Perl architecture-dependent library to install into
278                 (defaults to INST_LIB)
279
280  PERL_LIB:      Directory containing the Perl library to use.
281  PERL_SRC:      Directory containing the Perl source code
282                 (use of this should be avoided, it may be undefined)
283
284  INC:           Include file dirs eg: '-I/usr/5include -I/path/to/inc'
285  DEFINE:        something like "-DHAVE_UNISTD_H"
286  OBJECT:        List of object files, defaults to '$(BASEEXT).o',
287                 but can be a long string containing all object files,
288                     e.g. "tkpBind.o tkpButton.o tkpCanvas.o"
289  MYEXTLIB:      If the extension links to a library that it builds
290                 set this to the name of the library (see SDBM_File)
291
292  LIBS:          An anonymous array of alternative library specifications
293                 to be searched for (in order) until at least one library
294                 is found.
295                   'LIBS' => [ "-lgdbm", "-ldbm -lfoo", "-L/path -ldbm.nfs" ]
296                 Mind, that any element of the array contains a complete
297                 set of arguments for the ld command. So do not specify
298                   'LIBS' => ["-ltcl", "-ltk", "-lX11" ], #wrong
299                 See ODBM_File/Makefile.PL for an example, where an
300                 array is needed. If you specify a scalar as in
301                   'LIBS' => "-ltcl -ltk -lX11"
302                 MakeMaker will turn it into an array with one element.
303
304  LDFROM:        defaults to "$(OBJECT)" and is used in the ld command
305                 to specify what files to link/load from
306                 (also see dynamic_lib below for how to specify ld flags)
307
308  DIR:           Ref to array of subdirectories containing Makefile.PLs
309                 e.g. [ 'sdbm' ] in ext/SDBM_File
310
311  PMLIBDIRS:     Ref to array of subdirectories containing library files.
312                 Defaults to [ 'lib', $(BASEEXT) ]. The directories will
313                 be scanned and any *.pm and *.pl files they contain will
314                 be installed in the corresponding location in the library.
315                 A MY::libscan() function can be used to alter the behaviour.
316                 Defining PM in the Makefile.PL will override PMLIBDIRS.
317
318  PM:            Hashref of .pm files and *.pl files to be installed.
319                 e.g. { 'name_of_file.pm' => '$(INST_LIBDIR)/install_as.pm' }
320                 By default this will include *.pm and *.pl. If a lib directory
321                 exists and is not listed in DIR (above) then any *.pm and
322                 *.pl files it contains will also be included by default.
323                 Defining PM in the Makefile.PL will override PMLIBDIRS.
324
325  XS:            Hashref of .xs files. MakeMaker will default this.
326                 e.g. { 'name_of_file.xs' => 'name_of_file.c' }
327                 The .c files will automatically be included in the list
328                 of files deleted by a make clean.
329
330  C:             Ref to array of *.c file names. Initialised from a directory scan
331                 and the values portion of the XS attribute hash. This is not
332                 currently used by MakeMaker but may be handy in Makefile.PLs.
333
334  H:             Ref to array of *.h file names. Similar to C: above.
335
336  LINKTYPE:      =>'static' or 'dynamic' (default unless usedl=undef in config.sh)
337                 Should only be used to force static linking (also see linkext below).
338
339  DL_FUNCS:      Hashref of symbol names for routines to be made available as
340                 universal symbols.  Each key/value pair consists of the package
341                 name and an array of routine names in that package.  Used only
342                 under AIX (export lists) and VMS (linker options) at present.
343                 The routine names supplied will be expanded in the same way
344                 as XSUB names are expanded by the XS() macro.
345                 Defaults to { "$(NAME)" => [ "boot_$(NAME)" ] }.
346                 (e.g. { "RPC" => [qw( boot_rpcb rpcb_gettime getnetconfigent )],
347                         "NetconfigPtr" => [ 'DESTROY'] } )
348
349  DL_VARS:       Array of symbol names for variables to be made available as
350                 universal symbols.  Used only under AIX (export lists) and VMS
351                 (linker options) at present.  Defaults to [].
352                 (e.g. [ qw( Foo_version Foo_numstreams Foo_tree ) ])
353
354  CONFIG:        =>[qw(archname manext)] defines ARCHNAME & MANEXT from config.sh
355  SKIP:          =>[qw(name1 name2)] skip (do not write) sections of the Makefile
356
357  PERL:
358  FULLPERL:
359
360 Additional lowercase attributes can be used to pass parameters to the
361 methods which implement that part of the Makefile. These are not
362 normally required:
363
364  installpm:     {SPLITLIB => '$(INST_LIB)' (default) or '$(INST_ARCHLIB)'}
365  linkext:       {LINKTYPE => 'static', 'dynamic' or ''}
366  dynamic_lib:   {ARMAYBE => 'ar', OTHERLDFLAGS => '...'}
367  clean:         {FILES => "*.xyz foo"}
368  realclean:     {FILES => '$(INST_ARCHAUTODIR)/*.xyz'}
369  distclean:     {TARNAME=>'MyTarFile', TARFLAGS=>'cvfF', COMPRESS=>'gzip'}
370  tool_autosplit:        {MAXLEN => 8}
371 END
372
373 sub help {print $Attrib_Help;}
374
375 @MM_Sections_spec = (
376     'post_initialize'   => {},
377     'const_config'      => {},
378     'constants'         => {},
379     'const_loadlibs'    => {},
380     'const_cccmd'       => {},
381     'tool_autosplit'    => {},
382     'tool_xsubpp'       => {},
383     'tools_other'       => {},
384     'post_constants'    => {},
385     'c_o'               => {},
386     'xs_c'              => {},
387     'xs_o'              => {},
388     'top_targets'       => {},
389     'linkext'           => {},
390     'dlsyms'            => {},
391     'dynamic'           => {},
392     'dynamic_bs'        => {},
393     'dynamic_lib'       => {},
394     'static'            => {},
395     'static_lib'        => {},
396     'installpm'         => {},
397     'subdirs'           => {},
398     'clean'             => {},
399     'realclean'         => {},
400     'distclean'         => {},
401     'test'              => {},
402     'install'           => {},
403     'force'             => {},
404     'perldepend'        => {},
405     'makefile'          => {},
406     'postamble'         => {},
407     'staticmake'        => {},
408 );
409 %MM_Sections = @MM_Sections_spec; # looses section ordering
410 @MM_Sections = grep(!ref, @MM_Sections_spec); # keeps order
411
412 %Recognized_Att_Keys = %MM_Sections; # All sections are valid keys.
413 foreach(split(/\n/,$Attrib_Help)){
414     chomp;
415     next unless m/^\s*(\w+):\s*(.*)/;
416     $Recognized_Att_Keys{$1} = $2;
417     print "Attribute '$1' => '$2'\n" if ($Verbose >= 2);
418 }
419
420 %att  = ();
421 %skip = ();
422
423 sub skipcheck{
424     my($section) = @_;
425     if ($section eq 'dynamic') {
426         print STDOUT "Warning (non-fatal): Target 'dynamic' depends on targets "
427           . "in skipped section 'dynamic_bs'\n"
428             if $skip{'dynamic_bs'} && $Verbose;
429         print STDOUT "Warning (non-fatal): Target 'dynamic' depends on targets "
430           . "in skipped section 'dynamic_lib'\n"
431             if $skip{'dynamic_lib'} && $Verbose;
432     }
433     if ($section eq 'dynamic_lib') {
434         print STDOUT "Warning (non-fatal): Target '\$(INST_DYNAMIC)' depends on "
435           . "targets in skipped section 'dynamic_bs'\n"
436             if $skip{'dynamic_bs'} && $Verbose;
437     }
438     if ($section eq 'static') {
439         print STDOUT "Warning (non-fatal): Target 'static' depends on targets "
440           . "in skipped section 'static_lib'\n"
441             if $skip{'static_lib'} && $Verbose;
442     }
443     return 'skipped' if $skip{$section};
444     return '';
445 }
446
447
448 sub WriteMakefile {
449     %att = @_;
450     local($\)="\n";
451
452     print STDOUT "MakeMaker" if $Verbose;
453
454     parse_args(\%att, @ARGV);
455     my(%initial_att) = %att; # record initial attributes
456
457     MY->init_main();
458
459     print STDOUT "Writing Makefile for $att{NAME}";
460
461     MY->init_dirscan();
462     MY->init_others();
463
464     unlink("Makefile", "MakeMaker.tmp", $Is_VMS ? 'Descrip.MMS' : '');
465     open MAKE, ">MakeMaker.tmp" or die "Unable to open MakeMaker.tmp: $!";
466     select MAKE; $|=1; select STDOUT;
467
468     print MAKE "# This Makefile is for the $att{NAME} extension to perl.\n#";
469     print MAKE "# It was generated automatically by MakeMaker version $Version from the contents";
470     print MAKE "# of Makefile.PL. Don't edit this file, edit Makefile.PL instead.";
471     print MAKE "#\n#    ANY CHANGES MADE HERE WILL BE LOST! \n#";
472     print MAKE "#   MakeMaker Parameters: ";
473     foreach $key (sort keys %initial_att){
474         my($v) = neatvalue($initial_att{$key});
475         $v =~ tr/\n/ /s;
476         print MAKE "#   $key => $v";
477     }
478
479     # build hash for SKIP to make testing easy
480     %skip = map( ($_,1), @{$att{'SKIP'} || []});
481
482     foreach $section ( @MM_Sections ){
483         print "Processing Makefile '$section' section" if ($Verbose >= 2);
484         my($skipit) = skipcheck($section);
485         if ($skipit){
486             print MAKE "\n# --- MakeMaker $section section $skipit.";
487         } else {
488             my(%a) = %{$att{$section} || {}};
489             print MAKE "\n# --- MakeMaker $section section:";
490             print MAKE "# ",%a if $Verbose;
491             print(MAKE MY->nicetext(MY->$section( %a )));
492         }
493     }
494
495     if ($Verbose){
496         print MAKE "\n# Full list of MakeMaker attribute values:";
497         foreach $key (sort keys %att){
498             my($v) = neatvalue($att{$key});
499             $v =~ tr/\n/ /s;
500             print MAKE "#       $key => $v";
501         }
502     }
503
504     print MAKE "\n# End.";
505     close MAKE;
506     my($finalname) = $Is_VMS ? "Descrip.MMS" : "Makefile";
507     rename("MakeMaker.tmp", $finalname);
508
509     chmod 0644, $finalname;
510     system("$Config{'eunicefix'} $finalname") unless $Config{'eunicefix'} eq ":";
511
512     1;
513 }
514
515
516 sub mkbootstrap{
517     parse_args(\%att, @ARGV);
518     MY->mkbootstrap(@_);
519 }
520
521 sub mksymlists{
522     %att = @_;
523     parse_args(\%att, @ARGV);
524     MY->mksymlists(@_);
525 }
526
527 sub parse_args{
528     my($attr, @args) = @_;
529     foreach (@args){
530         unless (m/(.*?)=(.*)/){
531             help(),exit 1 if m/^help$/;
532             ++$Verbose if m/^verb/;
533             next;
534         }
535         my($name, $value) = ($1, $2);
536         if ($value =~ m/^~(\w+)?/){ # tilde with optional username
537             my($home) = ($1) ? (getpwnam($1))[7] : (getpwuid($>))[7];
538             $value =~ s/^~(\w+)?/$home/;
539         }
540         $$attr{$name} = $value;
541     }
542     # catch old-style 'potential_libs' and inform user how to 'upgrade'
543     if (defined $$attr{'potential_libs'}){
544         my($msg)="'potential_libs' => '$$attr{potential_libs}' should be";
545         if ($$attr{'potential_libs'}){
546             print STDOUT "$msg changed to:\n\t'LIBS' => ['$$attr{potential_libs}']\n";
547         } else {
548             print STDOUT "$msg deleted.\n";
549         }
550         $$attr{LIBS} = [$$attr{'potential_libs'}];
551         delete $$attr{'potential_libs'};
552     }
553     # catch old-style 'ARMAYBE' and inform user how to 'upgrade'
554     if (defined $$attr{'ARMAYBE'}){
555         my($armaybe) = $$attr{'ARMAYBE'};
556         print STDOUT "ARMAYBE => '$armaybe' should be changed to:\n",
557                         "\t'dynamic_lib' => {ARMAYBE => '$armaybe'}\n";
558         my(%dl) = %{$$attr{'dynamic_lib'} || {}};
559         $$attr{'dynamic_lib'} = { %dl, ARMAYBE => $armaybe};
560         delete $$attr{'ARMAYBE'};
561     }
562     if (defined $$attr{'LDTARGET'}){
563         print STDOUT "LDTARGET should be changed to LDFROM\n";
564         $$attr{'LDFROM'} = $$attr{'LDTARGET'};
565         delete $$attr{'LDTARGET'};
566     }
567     foreach(sort keys %{$attr}){
568         print STDOUT "  $_ => ".neatvalue($$attr{$_}) if ($Verbose);
569         print STDOUT "'$_' is not a known MakeMaker parameter name.\n"
570             unless exists $Recognized_Att_Keys{$_};
571     }
572 }
573
574
575 sub neatvalue{
576     my($v) = @_;
577     return "undef" unless defined $v;
578     my($t) = ref $v;
579     return "'$v'" unless $t;
580     return "[ ".join(', ',map("'$_'",@$v))." ]" if ($t eq 'ARRAY');
581     return "$v" unless $t eq 'HASH';
582     my(@m, $key, $val);
583     push(@m,"$key=>".neatvalue($val)) while (($key,$val) = each %$v);
584     return "{ ".join(', ',@m)." }";
585 }
586
587
588 # ------ Define the MakeMaker default methods in package MM_Unix ------
589
590 package MM_Unix;
591
592 use Config;
593 use Cwd;
594 use File::Basename;
595 require Exporter;
596
597 Exporter::import('ExtUtils::MakeMaker',
598         qw(%att %skip %Recognized_Att_Keys $Verbose));
599
600 # These attributes cannot be overridden externally
601 @Other_Att_Keys{qw(EXTRALIBS BSLOADLIBS LDLOADLIBS)} = (1) x 3;
602
603 if ($Is_VMS = $Config{'osname'} eq 'VMS') {
604     require File::VMSspec;
605     import File::VMSspec 'vmsify';
606 }
607
608
609 sub init_main {
610     # Find out directory name.  This may contain the extension name.
611     my($pwd) = fastcwd(); # from Cwd.pm
612
613     # --- Initialize PERL_LIB, INST_LIB, PERL_SRC
614
615     # *Real* information: where did we get these two from? ...
616     $inc_config_dir = dirname($INC{'Config.pm'});
617     $inc_carp_dir   = dirname($INC{'Carp.pm'});
618
619     # Typically PERL_* and INST_* will be identical but that need
620     # not be the case (e.g., installing into project libraries etc).
621
622     # Perl Macro:    With source    No source
623     # PERL_LIB       ../../lib      /usr/local/lib/perl5
624     # PERL_ARCHLIB   ../../lib      /usr/local/lib/perl5/sun4-sunos
625     # PERL_SRC       ../..          (undefined)
626
627     # INST Macro:    Locally        Publically
628     # INST_LIB       ../../lib      ./blib
629     # INST_ARCHLIB   ../../lib      ./blib
630
631     unless ($att{PERL_SRC}){
632         foreach(qw(../.. ../../.. ../../../..)){
633             ($att{PERL_SRC}=$_, last) if -f "$_/config.sh";
634         }
635     }
636     unless ($att{PERL_SRC}){
637         # we should also consider $ENV{PERL5LIB} here
638         $att{PERL_LIB}     = $Config{'privlib'} unless $att{PERL_LIB};
639         $att{PERL_ARCHLIB} = $Config{'archlib'} unless $att{PERL_ARCHLIB};
640         $att{PERL_INC}     = "$att{PERL_ARCHLIB}/CORE"; # wild guess for now
641         die "Unable to locate Perl source. Try setting PERL_SRC in Makefile.PL or on command line.\n"
642                 unless (-f "$att{PERL_INC}/perl.h");
643         print STDOUT "Using header files found in $att{PERL_INC}" if $Verbose;
644     } else {
645         $att{PERL_LIB}     = "$att{PERL_SRC}/lib" unless $att{PERL_LIB};
646         $att{PERL_ARCHLIB} = $att{PERL_LIB};
647         $att{PERL_INC}     = $att{PERL_SRC};
648     }
649
650     # INST_LIB typically pre-set if building an extension after
651     # perl has been built and installed. Setting INST_LIB allows
652     # you to build directly into privlib and avoid installperl.
653     unless ($att{INST_LIB}){
654         if (defined $att{PERL_SRC}) {
655             $att{INST_LIB} = $att{PERL_LIB};
656         } else {
657             $att{INST_LIB} = "$pwd/blib";
658         }
659     }
660     # Try to work out what INST_ARCHLIB should be if not set:
661     unless ($att{INST_ARCHLIB}){
662         my(%archmap) = (
663             "$pwd/blib"         => "$pwd/blib", # our private build lib
664             $att{PERL_LIB}      => $att{PERL_ARCHLIB},
665             $Config{'privlib'}  => $Config{'archlib'},
666             $Config{'installprivlib'}   => $Config{'installarchlib'},
667             $inc_carp_dir       => $inc_config_dir,
668         );
669         $att{INST_ARCHLIB} = $archmap{$att{INST_LIB}};
670         unless($att{INST_ARCHLIB}){
671             # Oh dear, we'll have to default it and warn the user
672             my($archname) = $Config{'archname'};
673             if (-d "$att{INST_LIB}/$archname"){
674                 $att{INST_ARCHLIB} = "$att{INST_LIB}/$archname";
675                 print STDOUT "Defaulting INST_ARCHLIB to INST_LIB/$archname\n";
676             } else {
677                 $att{INST_ARCHLIB} = $att{INST_LIB};
678                 print STDOUT "Warning: Defaulting INST_ARCHLIB to INST_LIB ",
679                         "(not architecture independent).\n";
680             }
681         }
682     }
683
684     # make a few simple checks
685     die "PERL_LIB ($att{PERL_LIB}) is not a perl library directory"
686         unless (-f "$att{PERL_LIB}/Exporter.pm");
687
688     # --- Initialize Module Name and Paths
689
690     # NAME    = The perl module name for this extension (eg DBD::Oracle).
691     # FULLEXT = Pathname for extension directory (eg DBD/Oracle).
692     # BASEEXT = Basename part of FULLEXT. May be just equal FULLEXT.
693     # ROOTEXT = Directory part of FULLEXT with leading /.
694     unless($att{NAME}){ # we have to guess our name
695         my($name) = $pwd;
696         if ($Is_VMS) {
697           $name =~ s:.*?([^.\]]+)\]:$1: unless ($name =~ s:.*[.\[]ext\.(.*)\]:$1:i);
698           ($att{NAME}=$name) =~ s#[.\]]#::#g;
699         } else {
700           $name =~ s:.*/:: unless ($name =~ s:^.*/ext/::);
701           ($att{NAME} =$name) =~ s#/#::#g;
702         }
703     }
704     ($att{FULLEXT} =$att{NAME}) =~ s#::#/#g ;           #eg. BSD/Foo/Socket
705     ($att{BASEEXT} =$att{NAME}) =~ s#.*::##;            #eg. Socket
706     ($att{ROOTEXT} =$att{FULLEXT}) =~ s#/?\Q$att{BASEEXT}\E$## ; # eg. /BSD/Foo
707     $att{ROOTEXT} = ($Is_VMS ? '' : '/') . $att{ROOTEXT} if $att{ROOTEXT};
708
709     ($att{DISTNAME}=$att{NAME}) =~ s#(::)#-#g unless $att{DISTNAME};
710     $att{VERSION} = "0.1" unless $att{VERSION};
711
712
713     # --- Initialize Perl Binary Locations
714
715     # Find Perl 5. The only contract here is that both 'PERL' and 'FULLPERL'
716     # will be working versions of perl 5. miniperl has priority over perl
717     # for PERL to ensure that $(PERL) is usable while building ./ext/*
718     $att{'PERL'} = MY->find_perl(5.0, [ qw(miniperl perl) ],
719             [ grep defined $_, $att{PERL_SRC}, split(":", $ENV{PATH}), $Config{'bin'} ], $Verbose )
720         unless ($att{'PERL'} && -x $att{'PERL'});
721
722     # Define 'FULLPERL' to be a non-miniperl (used in test: target)
723     ($att{'FULLPERL'} = $att{'PERL'}) =~ s/miniperl/perl/
724         unless ($att{'FULLPERL'} && -x $att{'FULLPERL'});
725
726     if ($Is_VMS) {
727         $att{'PERL'} = 'MCR ' . vmsify($att{'PERL'});
728         $att{'FULLPERL'} = 'MCR ' . vmsify($att{'FULLPERL'});
729     }
730 }
731
732
733 sub init_dirscan {      # --- File and Directory Lists (.xs .pm etc)
734
735     my($name, %dir, %xs, %c, %h, %ignore);
736     local(%pm); #the sub in find() has to see this hash
737     $ignore{'test.pl'} = 1;
738     $ignore{'makefile.pl'} = 1 if $Is_VMS;
739     foreach $name (lsdir(".")){
740         next if ($name =~ /^\./ or $ignore{$name});
741         if (-d $name){
742             $dir{$name} = $name if (-f "$name/Makefile.PL");
743         } elsif ($name =~ /\.xs$/){
744             my($c); ($c = $name) =~ s/\.xs$/.c/;
745             $xs{$name} = $c;
746             $c{$c} = 1;
747         } elsif ($name =~ /\.c$/){
748             $c{$name} = 1;
749         } elsif ($name =~ /\.h$/){
750             $h{$name} = 1;
751         } elsif ($name =~ /\.p[ml]$/){
752             $pm{$name} = "\$(INST_LIBDIR)/$name";
753         }
754     }
755
756     # Some larger extensions often wish to install a number of *.pm/pl
757     # files into the library in various locations.
758
759     # The attribute PMLIBDIRS holds an array reference which lists
760     # subdirectories which we should search for library files to
761     # install. PMLIBDIRS defaults to [ 'lib', $att{BASEEXT} ].
762     # We recursively search through the named directories (skipping
763     # any which don't exist or contain Makefile.PL files).
764
765     # For each *.pm or *.pl file found MY->libscan() is called with
766     # the default installation path in $_. The return value of libscan
767     # defines the actual installation location.
768     # The default libscan function simply returns $_.
769     # The file is skipped if libscan returns false.
770
771     # The default installation location passed to libscan in $_ is:
772     #
773     #  ./*.pm           => $(INST_LIBDIR)/*.pm
774     #  ./xyz/...        => $(INST_LIBDIR)/xyz/...
775     #  ./lib/...        => $(INST_LIB)/...
776     #
777     # In this way the 'lib' directory is seen as the root of the actual
778     # perl library whereas the others are relative to INST_LIBDIR
779     # (which includes ROOTEXT). This is a subtle distinction but one
780     # that's important for nested modules.
781
782     $att{PMLIBDIRS} = [ 'lib', $att{BASEEXT} ] unless $att{PMLIBDIRS};
783
784     #only existing directories that aren't in $dir are allowed
785     @{$att{PMLIBDIRS}} = grep -d && !$dir{$_}, @{$att{PMLIBDIRS}};
786
787     if (@{$att{PMLIBDIRS}}){
788         print "Searching PMLIBDIRS: @{$att{PMLIBDIRS}}"
789             if ($Verbose >= 2);
790         use File::Find;         # try changing to require !
791         File::Find::find(sub {
792 # We now allow any file in PMLIBDIRS to be installed. nTk needs that, and
793 # we should allow it.
794 #               return unless m/\.p[ml]$/;
795                 return if -d $_; # anything else that Can't be copied?
796                 my($path, $prefix) = ($File::Find::name, '$(INST_LIBDIR)');
797                 $prefix =  '$(INST_LIB)' if ($path =~ s:^lib/::);
798                 local($_) = "$prefix/$path";
799                 my($inst) = MY->libscan();
800                 print "libscan($path) => '$inst'" if ($Verbose >= 2);
801                 return unless $inst;
802                 $pm{$path} = $inst;
803              }, @{$att{PMLIBDIRS}});
804     }
805
806     $att{DIR} = [sort keys %dir] unless $att{DIRS};
807     $att{XS}  = \%xs             unless $att{XS};
808     $att{PM}  = \%pm             unless $att{PM};
809     $att{C}   = [sort keys %c]   unless $att{C};
810     my(@o_files) = @{$att{C}};
811     my($sufx) = $Is_VMS ? '.obj' : '.o';
812     $att{O_FILES} = [grep s/\.c$/$sufx/, @o_files] ;
813     $att{H}   = [sort keys %h]   unless $att{H};
814 }
815
816
817 sub libscan {
818     $_;
819 }
820
821 sub init_others {       # --- Initialize Other Attributes
822
823     for $key (keys(%Recognized_Att_Keys), keys(%Other_Att_Keys)){
824         # avoid warnings for uninitialized vars
825         next if exists $att{$key};
826         $att{$key} = "";
827     }
828
829     # Compute EXTRALIBS, BSLOADLIBS and LDLOADLIBS from $att{'LIBS'}
830     # Lets look at $att{LIBS} carefully: It may be an anon array, a string or
831     # undefined. In any case we turn it into an anon array:
832     $att{LIBS}=[] unless $att{LIBS};
833     $att{LIBS}=[$att{LIBS}] if ref \$att{LIBS} eq SCALAR;
834     foreach ( @{$att{'LIBS'}} ){
835         s/^\s*(.*\S)\s*$/$1/; # remove leading and trailing whitespace
836         my(@libs) = MY->extliblist($_);
837         if ($libs[0] or $libs[1] or $libs[2]){
838             @att{EXTRALIBS, BSLOADLIBS, LDLOADLIBS} = @libs;
839             last;
840         }
841     }
842
843     print STDOUT "CONFIG must be an array ref\n"
844         if ($att{CONFIG} and ref $att{CONFIG} ne 'ARRAY');
845     $att{CONFIG} = [] unless (ref $att{CONFIG});
846     push(@{$att{CONFIG}},
847         qw( cc libc ldflags lddlflags ccdlflags cccdlflags
848             ranlib so dlext dlsrc installprivlib installarchlib
849         ));
850     push(@{$att{CONFIG}}, 'shellflags') if $Config{'shellflags'};
851
852     if ($Is_VMS) {
853       $att{OBJECT} = '$(BASEEXT).obj' unless $att{OBJECT};
854       $att{OBJECT} =~ s/[^,\s]\s+/, /g;
855       $att{OBJECT} =~ s/\n+/, /g;
856       $att{OBJECT} =~ s#\.o,#\.obj,#;
857     } else {
858       $att{OBJECT} = '$(BASEEXT).o' unless $att{OBJECT};
859       $att{OBJECT} =~ s/\n+/ \\\n\t/g;
860     }
861     $att{BOOTDEP}  = (-f "$att{BASEEXT}_BS") ? "$att{BASEEXT}_BS" : "";
862     $att{LD}       = ($Config{'ld'} || 'ld') unless $att{LD};
863     $att{LDFROM} = '$(OBJECT)' unless $att{LDFROM};
864     # Sanity check: don't define LINKTYPE = dynamic if we're skipping
865     # the 'dynamic' section of MM.  We don't have this problem with
866     # 'static', since we either must use it (%Config says we can't
867     # use dynamic loading) or the caller asked for it explicitly.
868     if (!$att{LINKTYPE}) {
869        $att{LINKTYPE} = grep(/dynamic/,@{$att{SKIP} || []})
870                         ? 'static'
871                         : ($Config{'usedl'} ? 'dynamic' : 'static');
872     };
873
874     # These get overridden for VMS and maybe some other systems
875     $att{NOOP}  = "";
876     $att{MAKEFILE} = "Makefile";
877     $att{RM_F}  = "rm -f";
878     $att{RM_RF} = "rm -rf";
879     $att{TOUCH} = "touch";
880     $att{CP} = "cp";
881     $att{MV} = "mv";
882 }
883
884
885 sub lsdir{
886     my($dir, $regex) = @_;
887     local(*DIR, @ls);
888     opendir(DIR, $_[0] || ".") or die "opendir: $!";
889     @ls = readdir(DIR);
890     closedir(DIR);
891     @ls = grep(/$regex/, @ls) if $regex;
892     @ls;
893 }
894
895
896 sub find_perl{
897     my($self, $ver, $names, $dirs, $trace) = @_;
898     my($name, $dir);
899     if ($trace){
900         print "Looking for perl $ver by these names: ";
901         print "@$names, ";
902         print "in these dirs:";
903         print "@$dirs";
904     }
905     foreach $dir (@$dirs){
906         next unless defined $dir; # $att{PERL_SRC} may be undefined
907         foreach $name (@$names){
908             print "checking $dir/$name" if ($trace >= 2);
909             if ($Is_VMS) {
910               $name .= ".exe" unless -x "$dir/$name";
911             }
912             next unless -x "$dir/$name";
913             print "Executing $dir/$name" if ($trace);
914             my($out);
915             if ($Is_VMS) {
916               my($vmscmd) = 'MCR ' . vmsify("$dir/$name");
917               $out = `$vmscmd -e "require $ver; print ""VER_OK\n"""`;
918             } else {
919               $out = `$dir/$name -e 'require $ver; print "VER_OK\n" ' 2>&1`;
920             }
921             return "$dir/$name" if $out =~ /VER_OK/;
922         }
923     }
924     print STDOUT "Unable to find a perl $ver (by these names: @$names, in these dirs: @$dirs)\n";
925     0; # false and not empty
926 }
927
928
929 sub post_initialize{
930     "";
931 }
932
933
934 sub constants {
935     my(@m);
936
937     push @m, "
938 NAME = $att{NAME}
939 DISTNAME = $att{DISTNAME}
940 VERSION = $att{VERSION}
941
942 # In which library should we install this extension?
943 # This is typically the same as PERL_LIB.
944 # (also see INST_LIBDIR and relationship to ROOTEXT)
945 INST_LIB = $att{INST_LIB}
946 INST_ARCHLIB = $att{INST_ARCHLIB}
947
948 # Perl library to use when building the extension
949 PERL_LIB = $att{PERL_LIB}
950 PERL_ARCHLIB = $att{PERL_ARCHLIB}
951 ";
952
953     # Define I_PERL_LIBS to include the required -Ipaths
954     # To be cute we only include PERL_ARCHLIB if different
955     # To be portable we add quotes for VMS
956     my(@i_perl_libs) = qw{-I$(PERL_ARCHLIB) -I$(PERL_LIB)};
957     shift(@i_perl_libs) if ($att{PERL_ARCHLIB} eq $att{PERL_LIB});
958     if ($Is_VMS){
959         push @m, "I_PERL_LIBS = \"".join('" "',@i_perl_libs)."\"\n";
960     } else {
961         push @m, "I_PERL_LIBS = ".join(' ',@i_perl_libs)."\n";
962     }
963
964     push @m, "
965 # Where is the perl source code located?
966 PERL_SRC = $att{PERL_SRC}\n" if $att{PERL_SRC};
967
968     push @m, "
969 # Perl header files (will eventually be under PERL_LIB)
970 PERL_INC = $att{PERL_INC}
971 # Perl binaries
972 PERL = $att{'PERL'}
973 FULLPERL = $att{'FULLPERL'}
974 ";
975     push @m, "
976 # FULLEXT = Pathname for extension directory (eg DBD/Oracle).
977 # BASEEXT = Basename part of FULLEXT. May be just equal FULLEXT.
978 # ROOTEXT = Directory part of FULLEXT with leading slash (eg /DBD)
979 FULLEXT = $att{FULLEXT}
980 BASEEXT = $att{BASEEXT}
981 ROOTEXT = $att{ROOTEXT}
982 ";
983     push @m, "
984 INC = $att{INC}
985 DEFINE = $att{DEFINE}
986 OBJECT = $att{OBJECT}
987 LDFROM = $att{LDFROM}
988 LINKTYPE = $att{LINKTYPE}
989
990 # Handy lists of source code files:
991 XS_FILES= ".join(" \\\n\t", sort keys %{$att{XS}})."
992 C_FILES = ".join(" \\\n\t", @{$att{C}})."
993 O_FILES = ".join(" \\\n\t", @{$att{O_FILES}})."
994 H_FILES = ".join(" \\\n\t", @{$att{H}})."
995
996 .SUFFIXES: .xs
997
998 .PRECIOUS: Makefile
999
1000 .PHONY: all config static dynamic test linkext
1001
1002 # This extension may link to it's own library (see SDBM_File)
1003 MYEXTLIB = $att{MYEXTLIB}
1004
1005 # Where is the Config information that we are using/depend on
1006 CONFIGDEP = \$(PERL_ARCHLIB)/Config.pm \$(PERL_INC)/config.h
1007 ";
1008
1009     push @m, '
1010 # Where to put things:
1011 INST_LIBDIR     = $(INST_LIB)$(ROOTEXT)
1012 INST_ARCHLIBDIR = $(INST_ARCHLIB)$(ROOTEXT)
1013
1014 INST_AUTODIR      = $(INST_LIB)/auto/$(FULLEXT)
1015 INST_ARCHAUTODIR  = $(INST_ARCHLIB)/auto/$(FULLEXT)
1016 ';
1017
1018     push @m, '
1019 INST_STATIC  = $(INST_ARCHAUTODIR)/$(BASEEXT).a
1020 INST_DYNAMIC = $(INST_ARCHAUTODIR)/$(BASEEXT).$(DLEXT)
1021 INST_BOOT    = $(INST_ARCHAUTODIR)/$(BASEEXT).bs
1022 INST_PM = '.join(" \\\n\t", sort values %{$att{PM}}).'
1023 ';
1024
1025     join('',@m);
1026 }
1027
1028
1029 sub const_cccmd{
1030     # This is implemented in the same manner as extliblist,
1031     # e.g., do both and compare results during the transition period.
1032     my($cc,$ccflags,$optimize,$large,$split, $shflags)
1033         = @Config{qw(cc ccflags optimize large split shellflags)};
1034     $shflags = '' unless $shflags;
1035     my($prog, $old);
1036
1037     chop($old = `cd $att{PERL_SRC}; sh $shflags ./cflags $att{BASEEXT}.c 2>/dev/null`)
1038         if $att{PERL_SRC};
1039
1040     my($name);
1041     ( $name = $att{NAME} . "_cflags" ) =~ s/:/_/g ;
1042     if ($prog = $Config{$name}) {
1043         # Expand hints for this extension via the shell
1044         print STDOUT "Processing $name hint:\n" if $Verbose;
1045         my(@o)=`cc=\"$cc\"
1046           ccflags=\"$ccflags\"
1047           optimize=\"$optimize\"
1048           large=\"$large\"
1049           split=\"$split\"
1050           eval '$prog'
1051           echo cc=\$cc
1052           echo ccflags=\$ccflags
1053           echo optimize=\$optimize
1054           echo large=\$large
1055           echo split=\$split
1056           `;
1057         my(%cflags);
1058         foreach $line (@o){
1059             chomp $line;
1060             if ($line =~ /(.*?)=\s*(.*)\s*$/){
1061                 $cflags{$1} = $2;
1062                 print STDOUT "  $1 = $2" if $Verbose;
1063             } else {
1064                 print STDOUT "Unrecognised result from hint: '$line'\n";
1065             }
1066         }
1067         ($cc,$ccflags,$optimize,$large,$split)=@cflags{qw(cc ccflags optimize large split)};
1068     }
1069
1070     my($new) = "$cc -c $ccflags $optimize  $large $split";
1071     if (defined($old) and $new ne $old) {
1072         print STDOUT "Warning (non-fatal): cflags evaluation in MakeMaker differs from shell output\n"
1073         ."   package: $att{NAME}\n"
1074         ."   old: $old\n"
1075         ."   new: $new\n"
1076         ."   Using 'old' set.\n"
1077         ."Please notify perl5-porters\@nicoh.com\n";
1078     }
1079     my($cccmd)=($old) ? $old : $new;
1080     "CCCMD = $cccmd\n";
1081 }
1082
1083
1084 # --- Constants Sections ---
1085
1086 sub const_config{
1087     my(@m,$m);
1088     push(@m,"\n# These definitions are from config.sh (via $INC{'Config.pm'})\n");
1089     my(%once_only);
1090     foreach $m (@{$att{'CONFIG'}}){
1091         next if $once_only{$m};
1092         print STDOUT "CONFIG key '$m' does not exist in Config.pm\n"
1093                 unless exists $Config{$m};
1094         push @m, "\U$m\E = $Config{$m}\n";
1095         $once_only{$m} = 1;
1096     }
1097     join('', @m);
1098 }
1099
1100
1101 sub const_loadlibs{
1102     "
1103 # $att{NAME} might depend on some other libraries:
1104 # (These comments may need revising:)
1105 #
1106 # Dependent libraries can be linked in one of three ways:
1107 #
1108 #  1.  (For static extensions) by the ld command when the perl binary
1109 #      is linked with the extension library. See EXTRALIBS below.
1110 #
1111 #  2.  (For dynamic extensions) by the ld command when the shared
1112 #      object is built/linked. See LDLOADLIBS below.
1113 #
1114 #  3.  (For dynamic extensions) by the DynaLoader when the shared
1115 #      object is loaded. See BSLOADLIBS below.
1116 #
1117 # EXTRALIBS =   List of libraries that need to be linked with when
1118 #               linking a perl binary which includes this extension
1119 #               Only those libraries that actually exist are included.
1120 #               These are written to a file and used when linking perl.
1121 #
1122 # LDLOADLIBS =  List of those libraries which can or must be linked into
1123 #               the shared library when created using ld. These may be
1124 #               static or dynamic libraries.
1125 #
1126 # BSLOADLIBS =  List of those libraries that are needed but can be
1127 #               linked in dynamically at run time on this platform.
1128 #               SunOS/Solaris does not need this because ld records
1129 #               the information (from LDLOADLIBS) into the object file.
1130 #               This list is used to create a .bs (bootstrap) file.
1131 #
1132 EXTRALIBS  = $att{'EXTRALIBS'}
1133 LDLOADLIBS = $att{'LDLOADLIBS'}
1134 BSLOADLIBS = $att{'BSLOADLIBS'}
1135 ";
1136 }
1137
1138
1139 # --- Tool Sections ---
1140
1141 sub tool_autosplit{
1142     my($self, %attribs) = @_;
1143     my($asl) = "";
1144     $asl = "\$AutoSplit::Maxlen=$attribs{MAXLEN};" if $attribs{MAXLEN};
1145     q{
1146 # Usage: $(AUTOSPLITFILE) FileToSplit AutoDirToSplitInto
1147 AUTOSPLITFILE = $(PERL) $(I_PERL_LIBS) -e 'use AutoSplit;}.$asl.q{autosplit($$ARGV[0], $$ARGV[1], 0, 1, 1) ;'
1148 };
1149 }
1150
1151
1152 sub tool_xsubpp{
1153     my($xsdir)  = '$(PERL_LIB)/ExtUtils';
1154     # drop back to old location if xsubpp is not in new location yet
1155     $xsdir = '$(PERL_SRC)/ext' unless (-f "$att{PERL_LIB}/ExtUtils/xsubpp");
1156     my(@tmdeps) = ('$(XSUBPPDIR)/typemap');
1157     push(@tmdeps, "typemap") if -f "typemap";
1158     my(@tmargs) = map("-typemap $_", @tmdeps);
1159     "
1160 XSUBPPDIR = $xsdir
1161 XSUBPP = \$(XSUBPPDIR)/xsubpp
1162 XSUBPPDEPS = @tmdeps
1163 XSUBPPARGS = @tmargs
1164 ";
1165 };
1166
1167
1168 sub tools_other{
1169     "
1170 SHELL = /bin/sh
1171 LD = $att{LD}
1172 TOUCH = $att{TOUCH}
1173 CP = $att{CP}
1174 MV = $att{MV}
1175 RM_F  = $att{RM_F}
1176 RM_RF = $att{RM_RF}
1177 ".q{
1178 # The following is a portable way to say mkdir -p
1179 MKPATH = $(PERL) -wle '$$"="/"; foreach $$p (@ARGV){ next if -d $$p; my(@p); foreach(split(/\//,$$p)){ push(@p,$$_); next if -d "@p/"; print "mkdir @p"; mkdir("@p",0777)||die $$! }} exit 0;'
1180 };
1181 }
1182
1183
1184 sub post_constants{
1185     "";
1186 }
1187
1188
1189 # --- Translation Sections ---
1190
1191 sub c_o {
1192     push @m, '
1193 .c.o:
1194         $(CCCMD) $(CCCDLFLAGS) -I$(PERL_INC) $(DEFINE) $(INC) $*.c
1195 ';
1196     join "", @m;
1197 }
1198
1199 sub xs_c {
1200     '
1201 .xs.c:
1202         $(PERL) $(XSUBPP) $(XSUBPPARGS) $*.xs >$*.tc && mv $*.tc $@
1203 ';
1204 }
1205
1206 sub xs_o {      # many makes are too dumb to use xs_c then c_o
1207     '
1208 .xs.o:
1209         $(PERL) $(XSUBPP) $(XSUBPPARGS) $*.xs >xstmp.c && mv xstmp.c $*.c
1210         $(CCCMD) $(CCCDLFLAGS) -I$(PERL_INC) $(DEFINE) $(INC) $*.c
1211 ';
1212 }
1213
1214
1215 # --- Target Sections ---
1216
1217 sub top_targets{
1218     push @m, '
1219 all ::  config linkext $(INST_PM)
1220 '.$att{NOOP}.'
1221
1222 config :: '.$att{MAKEFILE}.'
1223         @ $(MKPATH) $(INST_LIBDIR) $(INST_ARCHAUTODIR)
1224 ';
1225
1226     push @m, '
1227 $(O_FILES): $(H_FILES)
1228 ' if @{$att{O_FILES} || []} && @{$att{H} || []};
1229     join('',@m);
1230 }
1231
1232 sub linkext {
1233     my($self, %attribs) = @_;
1234     # LINKTYPE => static or dynamic
1235     my($linktype) = $attribs{LINKTYPE} || '$(LINKTYPE)';
1236     "
1237 linkext :: $linktype
1238 $att{NOOP}
1239 ";
1240 }
1241
1242 sub dlsyms {
1243     my($self,%attribs) = @_;
1244
1245     return '' if ($Config{'osname'} ne 'AIX');
1246
1247     my($funcs) = $attribs{DL_FUNCS} || $att{DL_FUNCS} || {};
1248     my($vars)  = $attribs{DL_VARS} || $att{DL_VARS} || [];
1249     my(@m);
1250
1251     push(@m,"
1252 dynamic :: $att{BASEEXT}.exp
1253
1254 ") unless $skip{'dynamic'};
1255
1256     push(@m,"
1257 static :: $att{BASEEXT}.exp
1258
1259 ") unless $skip{'static'};
1260
1261     push(@m,"
1262 $att{BASEEXT}.exp: Makefile.PL
1263 ",'     $(PERL) $(I_PERL_LIBS) -e \'use ExtUtils::MakeMaker; \\
1264         mksymlists(DL_FUNCS => ',
1265         %$funcs ? neatvalue($funcs) : "''",', DL_VARS => ',
1266         @$vars  ? neatvalue($vars)  : "''",")'
1267 ");
1268
1269     join('',@m);
1270 }
1271
1272 # --- Dynamic Loading Sections ---
1273
1274 sub dynamic {
1275     '
1276 # $(INST_PM) has been moved to the all: target.
1277 # It remains here for awhile to allow for old usage: "make dynamic"
1278 dynamic :: '.$att{MAKEFILE}.' $(INST_DYNAMIC) $(INST_BOOT) $(INST_PM)
1279 '.$att{NOOP}.'
1280 ';
1281 }
1282
1283 sub dynamic_bs {
1284     my($self, %attribs) = @_;
1285     '
1286 BOOTSTRAP = '."$att{BASEEXT}.bs".'
1287
1288 # As MakeMaker mkbootstrap might not write a file (if none is required)
1289 # we use touch to prevent make continually trying to remake it.
1290 # The DynaLoader only reads a non-empty file.
1291 $(BOOTSTRAP): '."$att{MAKEFILE} $att{BOOTDEP}".'
1292         $(PERL) $(I_PERL_LIBS) \
1293                 -e \'use ExtUtils::MakeMaker; &mkbootstrap("$(BSLOADLIBS)");\' \
1294                 INST_LIB=$(INST_LIB) INST_ARCHLIB=$(INST_ARCHLIB) PERL_SRC=$(PERL_SRC) NAME=$(NAME)
1295         @ $(TOUCH) $(BOOTSTRAP)
1296
1297 $(INST_BOOT): $(BOOTSTRAP)
1298         @ '.$att{RM_RF}.' $(INST_BOOT)
1299         - '.$att{CP}.' $(BOOTSTRAP) $(INST_BOOT)
1300 ';
1301 }
1302
1303
1304 sub dynamic_lib {
1305     my($self, %attribs) = @_;
1306     my($otherldflags) = $attribs{OTHERLDFLAGS} || "";
1307     my($armaybe) = $attribs{ARMAYBE} || $att{ARMAYBE} || ":";
1308     my($ldfrom) = '$(LDFROM)';
1309     my($osname) = $Config{'osname'};
1310     $armaybe = 'ar' if ($osname eq 'dec_osf' and $armaybe eq ':');
1311     my(@m);
1312     push(@m,'
1313 # This section creates the dynamically loadable $(INST_DYNAMIC)
1314 # from $(OBJECT) and possibly $(MYEXTLIB).
1315 ARMAYBE = '.$armaybe.'
1316 OTHERLDFLAGS = '.$otherldflags.'
1317
1318 $(INST_DYNAMIC): $(OBJECT) $(MYEXTLIB) $(BOOTSTRAP)
1319         @ $(MKPATH) $(INST_ARCHAUTODIR)
1320 ');
1321     if ($armaybe ne ':'){
1322         $ldfrom = "tmp.a";
1323         push(@m,'       $(ARMAYBE) cr '.$ldfrom.' $(OBJECT)'."\n");
1324         push(@m,'       $(RANLIB) '."$ldfrom\n");
1325     }
1326     $ldfrom = "-all $ldfrom -none" if ($osname eq 'dec_osf');
1327     push(@m,'   $(LD) -o $@ $(LDDLFLAGS) '.$ldfrom.
1328                         ' $(OTHERLDFLAGS) $(MYEXTLIB) $(LDLOADLIBS)'."\n");
1329     join('',@m);
1330 }
1331
1332
1333 # --- Static Loading Sections ---
1334
1335 sub static {
1336     '
1337 # $(INST_PM) has been moved to the all: target.
1338 # It remains here for awhile to allow for old usage: "make static"
1339 static :: '.$att{MAKEFILE}.' $(INST_STATIC) $(INST_PM)
1340 '.$att{NOOP}.'
1341 ';
1342 }
1343
1344 sub static_lib{
1345     my(@m);
1346     push(@m, <<'END');
1347 $(INST_STATIC): $(OBJECT) $(MYEXTLIB)
1348         @ $(MKPATH) $(INST_ARCHAUTODIR)
1349 END
1350     # If this extension has it's own library (eg SDBM_File)
1351     # then copy that to $(INST_STATIC) and add $(OBJECT) into it.
1352     push(@m, "  $att{CP} \$(MYEXTLIB) \$\@\n") if $att{MYEXTLIB};
1353
1354     push(@m, <<'END');
1355         @ $(MKPATH) $(INST_ARCHAUTODIR)
1356         ar cr $@ $(OBJECT) && $(RANLIB) $@
1357         @echo "$(EXTRALIBS)" > $(INST_ARCHAUTODIR)/extralibs.ld
1358 END
1359
1360 # Old mechanism - still available:
1361
1362     push(@m, <<'END') if $att{PERL_SRC};
1363         @ echo "$(EXTRALIBS)" >> $(PERL_SRC)/ext.libs
1364 END
1365     join('', "\n",@m);
1366 }
1367
1368
1369 sub installpm {
1370     my($self, %attribs) = @_;
1371     # By default .pm files are split into the architecture independent
1372     # library. This is a good thing. If a specific module requires that
1373     # it's .pm files are split into the architecture specific library
1374     # then it should use: installpm => {SPLITLIB=>'$(INST_ARCHLIB)'}
1375     # Note that installperl currently interferes with this (Config.pm)
1376     # User can disable split by saying: installpm => {SPLITLIB=>''}
1377     my($splitlib) = '$(INST_LIB)'; # NOT arch specific by default
1378     $splitlib = $attribs{SPLITLIB} if exists $attribs{SPLITLIB};
1379     my(@m, $dist);
1380     foreach $dist (sort keys %{$att{PM}}){
1381         my($inst) = $att{PM}->{$dist};
1382         push(@m, "\n# installpm: $dist => $inst, splitlib=$splitlib\n");
1383         push(@m, MY->installpm_x($dist, $inst, $splitlib));
1384         push(@m, "\n");
1385     }
1386     join('', @m);
1387 }
1388
1389 sub installpm_x { # called by installpm per file
1390     my($self, $dist, $inst, $splitlib) = @_;
1391     my($instdir) = $inst =~ m|(.*)/|;
1392     my(@m);
1393     push(@m,"
1394 $inst: $dist Makefile
1395 ".'     @ '.$att{RM_F}.' $@
1396         @ $(MKPATH) '.$instdir.'
1397         '."$att{CP} $dist".' $@
1398 ');
1399     push(@m, "\t\$(AUTOSPLITFILE) \$@ $splitlib/auto\n")
1400         if ($splitlib and $inst =~ m/\.pm$/);
1401     join('', @m);
1402 }
1403
1404
1405 # --- Sub-directory Sections ---
1406
1407 sub subdirs {
1408     my(@m);
1409     # This method provides a mechanism to automatically deal with
1410     # subdirectories containing further Makefile.PL scripts.
1411     # It calls the subdir_x() method for each subdirectory.
1412     foreach(<*/Makefile.PL>){
1413         s:/Makefile\.PL$:: ;
1414         print "Including $_ subdirectory" if ($Verbose);
1415         push(@m, MY->subdir_x($_));
1416     }
1417     if (@m){
1418         unshift(@m, "
1419 # The default clean, realclean and test targets in this Makefile
1420 # have automatically been given entries for each subdir.
1421
1422 all :: subdirs
1423 ");
1424     } else {
1425         push(@m, "\n# none")
1426     }
1427     join('',@m);
1428 }
1429
1430 sub runsubdirpl{        # Experimental! See subdir_x section
1431     my($self,$subdir) = @_;
1432     chdir($subdir) or die "chdir($subdir): $!";
1433     ExtUtils::MakeMaker::check_hints();
1434     require "Makefile.PL";
1435 }
1436
1437 sub subdir_x {
1438     my($self, $subdir) = @_;
1439     my(@m);
1440     # The intention is that the calling Makefile.PL should define the
1441     # $(SUBDIR_MAKEFILE_PL_ARGS) make macro to contain whatever
1442     # information needs to be passed down to the other Makefile.PL scripts.
1443     # If this does not suit your needs you'll need to write your own
1444     # MY::subdir_x() method to override this one.
1445     qq{
1446 config :: $subdir/$att{MAKEFILE}
1447         cd $subdir ; \$(MAKE) config INST_LIB=\$(INST_LIB) INST_ARCHLIB=\$(INST_ARCHLIB)  LINKTYPE=\$(LINKTYPE)
1448
1449 $subdir/$att{MAKEFILE}: $subdir/Makefile.PL \$(CONFIGDEP)
1450 }.'     @echo "Rebuilding $@ ..."
1451         $(PERL) $(I_PERL_LIBS) \\
1452                 -e "use ExtUtils::MakeMaker; MM->runsubdirpl(qw('.$subdir.'))" \\
1453                 INST_LIB=$(INST_LIB) INST_ARCHLIB=$(INST_ARCHLIB) $(SUBDIR_MAKEFILE_PL_ARGS)
1454         @echo "Rebuild of $@ complete."
1455 '.qq{
1456
1457 subdirs ::
1458         cd $subdir ; \$(MAKE) all LINKTYPE=\$(LINKTYPE)
1459
1460 };
1461 }
1462
1463
1464 # --- Cleanup and Distribution Sections ---
1465
1466 sub clean {
1467     my($self, %attribs) = @_;
1468     my(@m);
1469     push(@m, '
1470 # Delete temporary files but do not touch installed files. We don\'t delete
1471 # the Makefile here so a later make realclean still has a makefile to use.
1472
1473 clean ::
1474 ');
1475     # clean subdirectories first
1476     push(@m, map("\t-cd $_ && test -f $att{MAKEFILE} && \$(MAKE) clean\n",@{$att{DIR}}));
1477     my(@otherfiles) = values %{$att{XS}}; # .c files from *.xs files
1478     push(@otherfiles, $attribs{FILES}) if $attribs{FILES};
1479     push(@otherfiles, "./blib");
1480     push(@m, "  -$att{RM_RF} *~ t/*~ *.o *.a mon.out core so_locations "
1481                         ."\$(BOOTSTRAP) \$(BASEEXT).bso @otherfiles\n");
1482     # See realclean and ext/utils/make_ext for usage of Makefile.old
1483     push(@m, "  -$att{MV} $att{MAKEFILE} $att{MAKEFILE}.old 2>/dev/null\n");
1484     push(@m, "  $attribs{POSTOP}\n")   if $attribs{POSTOP};
1485     join("", @m);
1486 }
1487
1488 sub realclean {
1489     my($self, %attribs) = @_;
1490     my(@m);
1491     push(@m,'
1492 # Delete temporary files (via clean) and also delete installed files
1493 realclean purge ::  clean
1494 ');
1495     # realclean subdirectories first (already cleaned)
1496     $sub = "\t-cd %s && test -f %s && \$(MAKE) %s realclean\n";
1497     foreach(@{$att{DIR}}){
1498         push(@m, sprintf($sub,$_,"$att{MAKEFILE}.old","-f $att{MAKEFILE}.old"));
1499         push(@m, sprintf($sub,$_,"$att{MAKEFILE}",''));
1500     }
1501     push(@m, "  $att{RM_RF} \$(INST_AUTODIR) \$(INST_ARCHAUTODIR)\n");
1502     push(@m, "  $att{RM_F} \$(INST_DYNAMIC) \$(INST_BOOT)\n");
1503     push(@m, "  $att{RM_F} \$(INST_STATIC) \$(INST_PM)\n");
1504     my(@otherfiles) = ($att{MAKEFILE}, 
1505                        "Perl.make", "$att{MAKEFILE}.old"); # Makefiles last
1506     push(@otherfiles, $attribs{FILES}) if $attribs{FILES};
1507     push(@m, "  $att{RM_RF} @otherfiles\n") if @otherfiles;
1508     push(@m, "  $attribs{POSTOP}\n")       if $attribs{POSTOP};
1509     join("", @m);
1510 }
1511
1512
1513 sub distclean {
1514     my($self, %attribs) = @_;
1515     # VERSION should be sanitised before use as a file name
1516     my($tarname)  = $attribs{TARNAME}  || '$(DISTNAME)-$(VERSION)';
1517     my($tarflags) = $attribs{TARFLAGS} || 'cvf';
1518     my($compress) = $attribs{COMPRESS} || 'compress'; # eg gzip
1519     my($preop)    = $attribs{PREOP}  || '@:'; # e.g., update MANIFEST
1520     my($postop)   = $attribs{POSTOP} || '@:';
1521     my($mkfiles)  = join(' ', map("$_/$att{MAKEFILE} $_/$att{MAKEFILE}.old", ".", @{$att{DIR}}));
1522     "
1523 distclean:     clean
1524         $preop
1525         $att{RM_F} $mkfiles
1526         cd ..; tar $tarflags $tarname.tar \$(BASEEXT)
1527         cd ..; $compress $tarname.tar
1528         $postop
1529 ";
1530 }
1531
1532
1533 # --- Test and Installation Sections ---
1534
1535 sub test {
1536     my($self, %attribs) = @_;
1537     my($tests) = $attribs{TESTS} || (-d "t" ? "t/*.t" : "");
1538     my(@m);
1539     push(@m,"
1540 test :: all
1541 ");
1542     push(@m, <<"END") if $tests;
1543         \$(FULLPERL) -I\$(INST_ARCHLIB) -I\$(INST_LIB) -I\$(PERL_ARCHLIB) -I\$(PERL_LIB) -e 'use Test::Harness; runtests \@ARGV;' $tests
1544 END
1545     push(@m, <<'END') if -f "test.pl";
1546         $(FULLPERL) -I$(INST_ARCHLIB) -I$(INST_LIB) -I$(PERL_ARCHLIB) -I$(PERL_LIB) test.pl
1547 END
1548     push(@m, map("\tcd $_ && test -f $att{MAKEFILE} && \$(MAKE) test LINKTYPE=\$(LINKTYPE)\n",@{$att{DIR}}));
1549     push(@m, "\t\@echo 'No tests defined for \$(NAME) extension.'\n") unless @m > 1;
1550     join("", @m);
1551 }
1552
1553
1554 sub install {
1555     my($self, %attribs) = @_;
1556     my(@m);
1557     push(@m, "
1558 install :: all
1559 ");
1560     # install subdirectories first
1561     push(@m, map("\tcd $_ && test -f $att{MAKEFILE} && \$(MAKE) install\n",@{$att{DIR}}));
1562
1563     push(@m, "\t: perl5.000 and MM pre 3.8 autosplit into INST_ARCHLIB, we delete these old files here
1564         $att{RM_F} $Config{'installarchlib'}/auto/\$(FULLEXT)/*.al $Config{'installarchlib'}/auto/\$(FULLEXT)/*.ix
1565         \$(MAKE) INST_LIB=$Config{'installprivlib'} INST_ARCHLIB=$Config{'installarchlib'}
1566 ");
1567
1568     join("",@m);
1569 }
1570
1571 sub force {
1572     '# Phony target to force checking subdirectories.
1573 FORCE:
1574 ';
1575 }
1576
1577
1578 sub perldepend {
1579         my(@m);
1580     push(@m,'
1581 PERL_HDRS = $(PERL_INC)/EXTERN.h $(PERL_INC)/INTERN.h \
1582     $(PERL_INC)/XSUB.h  $(PERL_INC)/av.h        $(PERL_INC)/cop.h \
1583     $(PERL_INC)/cv.h    $(PERL_INC)/dosish.h    $(PERL_INC)/embed.h \
1584     $(PERL_INC)/form.h  $(PERL_INC)/gv.h        $(PERL_INC)/handy.h \
1585     $(PERL_INC)/hv.h    $(PERL_INC)/keywords.h  $(PERL_INC)/mg.h \
1586     $(PERL_INC)/op.h    $(PERL_INC)/opcode.h    $(PERL_INC)/patchlevel.h \
1587     $(PERL_INC)/perl.h  $(PERL_INC)/perly.h     $(PERL_INC)/pp.h \
1588     $(PERL_INC)/proto.h $(PERL_INC)/regcomp.h   $(PERL_INC)/regexp.h \
1589     $(PERL_INC)/scope.h $(PERL_INC)/sv.h        $(PERL_INC)/unixish.h \
1590     $(PERL_INC)/util.h  $(PERL_INC)/config.h
1591
1592 $(OBJECT) : $(PERL_HDRS)
1593 ');
1594
1595     push(@m,'
1596 # Check for unpropogated config.sh changes. Should never happen.
1597 # We do NOT just update config.h because that is not sufficient.
1598 # An out of date config.h is not fatal but complains loudly!
1599 $(PERL_INC)/config.h: $(PERL_SRC)/config.sh
1600         -@echo "Warning: $(PERL_INC)/config.h out of date with $(PERL_SRC)/config.sh"; false
1601
1602 $(PERL_ARCHLIB)/Config.pm: $(PERL_SRC)/config.sh
1603         @echo "Warning: $(PERL_ARCHLIB)/Config.pm may be out of date with $(PERL_SRC)/config.sh"
1604         cd $(PERL_SRC); $(MAKE) lib/Config.pm
1605 ') if $att{PERL_SRC};
1606
1607     push(@m, join(" ", values %{$att{XS}})." : \$(XSUBPPDEPS)\n")
1608         if %{$att{XS}};
1609     join("\n",@m);
1610 }
1611
1612
1613 sub makefile {
1614     # We do not know what target was originally specified so we
1615     # must force a manual rerun to be sure. But as it should only
1616     # happen very rarely it is not a significant problem.
1617     '
1618 $(OBJECT) : '.$att{MAKEFILE}.'
1619
1620 # We take a very conservative approach here, but it\'s worth it.
1621 # We move Makefile to Makefile.old here to avoid gnu make looping.
1622 '.$att{MAKEFILE}.':     Makefile.PL $(CONFIGDEP)
1623         @echo "Makefile out-of-date with respect to $?"
1624         @echo "Cleaning current config before rebuilding Makefile..."
1625         -@mv '."$att{MAKEFILE} $att{MAKEFILE}.old".'
1626         -$(MAKE) -f '.$att{MAKEFILE}.'.old clean >/dev/null 2>&1 || true
1627         $(PERL) $(I_PERL_LIBS) Makefile.PL
1628         @echo "Now you must rerun make."; false
1629 ';
1630 }
1631
1632
1633 sub postamble{
1634     "";
1635 }
1636
1637 # --- Make-A-Perl section ---
1638
1639 sub staticmake {
1640     my($self, %attribs) = @_;
1641
1642     my(%searchdirs)=($att{PERL_ARCHLIB} => 1,  $att{INST_ARCHLIB} => 1);
1643     my(@searchdirs)=keys %searchdirs;
1644     # And as it's not yet built, we add the current extension
1645     my(@static)="$att{INST_ARCHLIB}/auto/$att{FULLEXT}/$att{BASEEXT}.a";
1646     my(@extra);
1647     push(@extra, split(' ', $att{EXTRALIBS})) if defined $att{EXTRALIBS};
1648     my(@perlinc) = ($att{INST_ARCHLIB}, $att{INST_LIB}, $att{PERL_ARCHLIB}, $att{PERL_LIB});
1649     MY->makeaperl('MAKE' => $att{MAKEFILE}, 
1650                              'DIRS' => \@searchdirs, 
1651                              'STAT' => \@static, 
1652                              'EXTRA' => \@extra, 
1653                              'INCL' => \@perlinc,
1654                              'TARGET' => "perl",
1655                              'TMP' => "",
1656                              'LIBPERL' => "$att{PERL_INC}/libperl.a"
1657                              );
1658 }
1659
1660 sub makeaperl {
1661     my($self, %attribs) = @_;
1662     my($makefilename, $searchdirs, $static, $extra, $perlinc, $target, $tmp, $libperl) = 
1663       @attribs{qw(MAKE DIRS STAT EXTRA INCL TARGET TMP LIBPERL)};
1664     my(@m);
1665     my($cccmd, $linkcmd, %map);
1666
1667     # This emulates cflags to get the compiler invocation...
1668     $cccmd = MY->const_cccmd();
1669     $cccmd =~ s/^CCCMD\s*=\s*//;
1670     chomp $cccmd;
1671     $cccmd =~ s/\s/ -I$att{PERL_INC} /;
1672     $cccmd .= " $Config{'cccdlflags'}" if ($Config{'d_shrplib'});
1673
1674     # The front matter of the linkcommand...
1675     $linkcmd = join ' ', $Config{'cc'},
1676             grep($_, @Config{qw(large split ldflags ccdlflags)});
1677     $linkcmd =~ s/\s+/ /g;
1678
1679     # Which *.a files could we make use of...
1680     local(%static,%libperl);
1681     File::Find::find(sub {
1682         return unless m/\.a$/;
1683         if (m/^libperl/) {
1684             $libperl{$File::Find::name}++;
1685             return;
1686         }
1687         $static{$File::Find::name}++;
1688     }, grep( -d $_, @{$searchdirs || []}) );
1689
1690     $extra = [] unless $extra && ref $extra eq 'ARRAY';
1691     for (sort keys %static) {
1692         next unless /\.a$/;
1693         s#^#./# unless m#/#;        # Prepend "./" if it is in the current dir
1694         s#(.*/).*#$1extralibs.ld#;
1695         if (-f $_){
1696             push @$extra, split(' ',`cat $_`);
1697         } else {
1698             print STDOUT "$0: warning $_ not found";
1699         }
1700     }
1701
1702     # These have been handed in explicitly, so we do not read extralibs.ld for them,
1703     # they might not even exist, and extralibs.ld might be outdated.
1704     @static{@{$static || []}} = (1) x @{$static || []};
1705     grep(s/^/-I/, @$perlinc);
1706
1707     $target = "perl" unless $target;
1708     $tmp = "." unless $tmp;
1709
1710     push @m, "
1711 # Fill in the target you want to produce if it's not perl
1712 MAP_TARGET    = $target
1713 FULLPERL      = $att{'FULLPERL'}
1714 MAP_LINKCMD   = $linkcmd
1715 MAP_PERLINC   = @{$perlinc}
1716 MAP_STATIC    = ",
1717 join(" ", sort keys %static), "
1718 MAP_EXTRA     = @{$extra}
1719 MAP_PRELIBS   = $Config{'libs'} $Config{'cryptlib'}
1720 ";
1721
1722     my(@libperl);
1723     if ($libperl) {
1724         @libperl = $libperl;
1725     } else {
1726         @libperl = sort keys %libperl;
1727         if (@libperl==0 && defined $att{PERL_SRC}) {
1728             push @libperl, "$att{PERL_SRC}/libperl.a";
1729         }
1730         if (@libperl==0 && -f "$INC[0]/CORE/libperl.a") {
1731             push @libperl, "$INC[0]/CORE/libperl.a";
1732         }
1733         if (@libperl==0){
1734             push @m, "\nMAP_LIBPERL = ---NOT FOUND---\n\n";
1735         }
1736     }
1737
1738     # if we have to work with other libraries than libperl.a...
1739     %map = (
1740                 D =>   '-DDEBUGGING',
1741                 E =>   '-DEMBED',
1742                 DE =>  '-DDEBUGGING -DEMBED',
1743                 M =>   '-DEMBED -DMULTIPLICITY',
1744                 DM =>  '-DDEBUGGING -DEMBED -DMULTIPLICITY',
1745                 );
1746     for (@libperl) {
1747         my($uc, $thiscccmd);
1748         ( $uc = $_ ) =~ s!.*/libperl(\w*)\.a!uc($1)!e;
1749
1750         # We have to tamper with the cccmd...
1751         $thiscccmd = $cccmd;
1752         # All perls of flavor D need a compilation with -g instead of 
1753         # whatever optimize was before
1754         if ($uc =~ /^D/) {
1755             $thiscccmd =~ s/\B$Config{'optimize'}\b/-g/;
1756         }
1757         $thiscccmd .= $map{$uc} if $uc;
1758         $thiscccmd =~ s/\s+/ /g;
1759
1760         # If we have to write the Makefile for only one
1761         # target, we do not need the variable $uc
1762         $uc = "" if @libperl == 1;
1763
1764         push @m, "MAP_LIBPERL$uc = $_
1765 $target$uc: $tmp/perlmain$uc.o \$(MAP_LIBPERL$uc) \$(MAP_STATIC)
1766         \$(MAP_LINKCMD) -o \$\@ $tmp/perlmain$uc.o \$(MAP_LIBPERL$uc) \$(MAP_STATIC) \$(MAP_EXTRA) \$(MAP_PRELIBS)
1767
1768 $tmp/perlmain$uc.o: $tmp/perlmain$uc.c
1769 ";
1770         push @m, "\tcd $tmp && $thiscccmd perlmain$uc.c\n";
1771
1772         if ($uc) {
1773             push @m, "$tmp/perlmain$uc.c: $tmp/perlmain.c
1774         cp \$< \$\@\n\n";
1775         }
1776     }
1777
1778     push @m, qq{
1779 $tmp/perlmain.c: $makefilename}, q{
1780         $(FULLPERL) $(MAP_PERLINC) -e 'use ExtUtils::Miniperl; \\
1781                 writemain(grep s#.*/auto/##, qw|$(MAP_STATIC)|)' > $@
1782
1783 };
1784
1785     push @m, qq{
1786 inst_perl: \$(MAP_TARGET)
1787         $att{CP} \$(MAP_TARGET) $Config{'installbin'}/\$(MAP_TARGET)
1788
1789 };
1790
1791     join '', @m;
1792 }
1793
1794 # --- Determine libraries to use and how to use them ---
1795
1796 sub extliblist{
1797     my($self, $libs) = @_;
1798     return ("", "", "") unless $libs;
1799     print STDOUT "Potential libraries are '$libs':" if $Verbose;
1800     my(@new) = MY->new_extliblist($libs);
1801
1802     if ($att{PERL_SRC}){
1803         my(@old) = MY->old_extliblist($libs);
1804         my($oldlibs) = join(" : ",@old);
1805         my($newlibs) = join(" : ",@new);
1806         print STDOUT "Warning (non-fatal): $att{NAME} extliblist consistency check failed:\n".
1807             "  old: $oldlibs\n".
1808             "  new: $newlibs\n".
1809             "Using 'new' set. Please notify perl5-porters\@nicoh.com.\n"
1810                 if ("$newlibs" ne "$oldlibs");
1811     }
1812     @new;
1813 }
1814
1815
1816 sub old_extliblist {
1817     my($self, $potential_libs)=@_;
1818     return ("", "", "") unless $potential_libs;
1819     die "old_extliblist requires PERL_SRC" unless $att{PERL_SRC};
1820
1821     my(%attrib, @w);
1822     # Now run ext/util/extliblist to discover what *libs definitions
1823     # are required for the needs of $potential_libs
1824     $ENV{'potential_libs'} = $potential_libs;
1825     my(@o)=`. $att{PERL_SRC}/config.sh
1826             . $att{PERL_SRC}/ext/util/extliblist;
1827             echo EXTRALIBS=\$extralibs
1828             echo BSLOADLIBS=\$dynaloadlibs
1829             echo LDLOADLIBS=\$statloadlibs
1830             `;
1831     foreach $line (@o){
1832         chomp $line;
1833         if ($line =~ /(.*)\s*=\s*(.*)\s*$/){
1834             $attrib{$1} = $2;
1835             print STDOUT "      $1 = $2" if $Verbose;
1836         }else{
1837             push(@w, $line);
1838         }
1839     }
1840     print STDOUT "Messages from extliblist:\n", join("\n",@w,'')
1841        if @w ;
1842     @attrib{qw(EXTRALIBS BSLOADLIBS LDLOADLIBS)};
1843 }
1844
1845
1846 sub new_extliblist {
1847     my($self, $potential_libs)=@_;
1848     return ("", "", "") unless $potential_libs;
1849
1850     my($so)   = $Config{'so'};
1851     my($libs) = $Config{'libs'};
1852
1853     # compute $extralibs, $bsloadlibs and $ldloadlibs from
1854     # $potential_libs
1855     # this is a rewrite of Andy Dougherty's extliblist in perl
1856     # its home is in <distribution>/ext/util
1857
1858     my(@searchpath); # from "-L/path" entries in $potential_libs
1859     my(@libpath) = split " ", $Config{'libpth'};
1860     my(@ldloadlibs);
1861     my(@bsloadlibs);
1862     my(@extralibs);
1863     my($fullname);
1864     my($pwd) = fastcwd(); # from Cwd.pm
1865
1866     foreach $thislib (split ' ', $potential_libs){
1867
1868         # Handle possible linker path arguments.
1869         if ($thislib =~ s/^(-[LR])//){  # save path flag type
1870             my($ptype) = $1;
1871             unless (-d $thislib){
1872                 print STDOUT "$ptype$thislib ignored, directory does not exist\n"
1873                         if $Verbose;
1874                 next;
1875             }
1876             if ($thislib !~ m|^/|) {
1877               print STDOUT "Warning: $ptype$thislib changed to $ptype$pwd/$thislib\n";
1878               $thislib = "$pwd/$thislib";
1879             }
1880             push(@searchpath, $thislib);
1881             push(@extralibs,  "$ptype$thislib");
1882             push(@ldloadlibs, "$ptype$thislib");
1883             next;
1884         }
1885
1886         # Handle possible library arguments.
1887         unless ($thislib =~ s/^-l//){
1888           print STDOUT "Unrecognized argument in LIBS ignored: '$thislib'\n";
1889           next;
1890         }
1891
1892         my($found_lib)=0;
1893         foreach $thispth (@searchpath, @libpath){
1894
1895             if (@fullname=<${thispth}/lib${thislib}.${so}.[0-9]*>){
1896                 $fullname=$fullname[-1]; #ATTN: 10 looses against 9!
1897             } elsif (-f ($fullname="$thispth/lib$thislib.$so")){
1898             } elsif (-f ($fullname="$thispth/lib${thislib}_s.a")
1899                      && ($thislib .= "_s") ){ # we must explicitly ask for _s version
1900             } elsif (-f ($fullname="$thispth/lib$thislib.a")){
1901             } elsif (-f ($fullname="$thispth/Slib$thislib.a")){
1902             } else {
1903                 print STDOUT "$thislib not found in $thispth\n" if $Verbose;
1904                 next;
1905             }
1906             print STDOUT "'-l$thislib' found at $fullname" if $Verbose;
1907             $found_lib++;
1908
1909             # Now update library lists
1910
1911             # what do we know about this library...
1912             my $is_dyna = ($fullname !~ /\.a$/);
1913             my $in_perl = ($libs =~ /\B-l${thislib}\b/s);
1914
1915             # Do not add it into the list if it is already linked in
1916             # with the main perl executable.
1917             # We have to special-case the NeXT, because all the math is also in libsys_s
1918             unless ( $in_perl || ($Config{'osname'} eq 'next' && $thislib eq 'm') ){
1919                 push(@extralibs, "-l$thislib");
1920             }
1921
1922
1923             # We might be able to load this archive file dynamically
1924             if ( $Config{'dlsrc'} =~ /dl_next|dl_dld/){
1925                 # We push -l$thislib instead of $fullname because
1926                 # it avoids hardwiring a fixed path into the .bs file.
1927                 # mkbootstrap will automatically add dl_findfile() to
1928                 # the .bs file if it sees a name in the -l format.
1929                 # USE THIS LATER: push(@bsloadlibs, "-l$thislib"); # " $fullname";
1930                 # USE THIS while checking results against old_extliblist
1931                 push(@bsloadlibs, "$fullname");
1932             } else {
1933                 if ($is_dyna){
1934                     # For SunOS4, do not add in this shared library if
1935                     # it is already linked in the main perl executable
1936                     push(@ldloadlibs, "-l$thislib")
1937                         unless ($in_perl and $Config{'osname'} eq 'sunos');
1938                 } else {
1939                     push(@ldloadlibs, "-l$thislib");
1940                 }
1941             }
1942             last;       # found one here so don't bother looking further
1943         }
1944         print STDOUT "Warning (non-fatal): No library found for -l$thislib\n" unless $found_lib>0;
1945     }
1946     ("@extralibs", "@bsloadlibs", "@ldloadlibs");
1947 }
1948
1949
1950 # --- Write a DynaLoader bootstrap file if required
1951
1952 sub mkbootstrap {
1953
1954 =head1 USEFUL SUBROUTINES
1955
1956 =head2 mkbootstrap()
1957
1958 Make a bootstrap file for use by this system's DynaLoader.  It
1959 typically gets called from an extension Makefile.
1960
1961 There is no C<*.bs> file supplied with the extension. Instead a
1962 C<*_BS> file which has code for the special cases, like posix for
1963 berkeley db on the NeXT.
1964
1965 This file will get parsed, and produce a maybe empty
1966 C<@DynaLoader::dl_resolve_using> array for the current architecture.
1967 That will be extended by $BSLOADLIBS, which was computed by Andy's
1968 extliblist script. If this array still is empty, we do nothing, else
1969 we write a .bs file with an C<@DynaLoader::dl_resolve_using> array, but
1970 without any C<if>s, because there is no longer a need to deal with
1971 special cases.
1972
1973 The C<*_BS> file can put some code into the generated C<*.bs> file by placing
1974 it in C<$bscode>. This is a handy 'escape' mechanism that may prove
1975 useful in complex situations.
1976
1977 If @DynaLoader::dl_resolve_using contains C<-L*> or C<-l*> entries then
1978 mkbootstrap will automatically add a dl_findfile() call to the
1979 generated C<*.bs> file.
1980
1981 =cut
1982
1983     my($self, @bsloadlibs)=@_;
1984
1985     @bsloadlibs = grep($_, @bsloadlibs); # strip empty libs
1986
1987     print STDOUT "      bsloadlibs=@bsloadlibs\n" if $Verbose;
1988
1989     # We need DynaLoader here because we and/or the *_BS file may
1990     # call dl_findfile(). We don't say `use' here because when
1991     # first building perl extensions the DynaLoader will not have
1992     # been built when MakeMaker gets first used.
1993     require DynaLoader;
1994     import DynaLoader;
1995
1996     init_main() unless defined $att{'BASEEXT'};
1997
1998     rename "$att{BASEEXT}.bs", "$att{BASEEXT}.bso";
1999
2000     if (-f "$att{BASEEXT}_BS"){
2001         $_ = "$att{BASEEXT}_BS";
2002         package DynaLoader; # execute code as if in DynaLoader
2003         local($osname, $dlsrc) = (); # avoid warnings
2004         ($osname, $dlsrc) = @Config::Config{qw(osname dlsrc)};
2005         $bscode = "";
2006         unshift @INC, ".";
2007         require $_;
2008         shift @INC;
2009     }
2010
2011     if ($Config{'dlsrc'} =~ /^dl_dld/){
2012         package DynaLoader;
2013         push(@dl_resolve_using, dl_findfile('-lc'));
2014     }
2015
2016     my(@all) = (@bsloadlibs, @DynaLoader::dl_resolve_using);
2017     my($method) = '';
2018     if (@all){
2019         open BS, ">$att{BASEEXT}.bs"
2020                 or die "Unable to open $att{BASEEXT}.bs: $!";
2021         print STDOUT "Writing $att{BASEEXT}.bs\n";
2022         print STDOUT "  containing: @all" if $Verbose;
2023         print BS "# $att{BASEEXT} DynaLoader bootstrap file for $Config{'osname'} architecture.\n";
2024         print BS "# Do not edit this file, changes will be lost.\n";
2025         print BS "# This file was automatically generated by the\n";
2026         print BS "# mkbootstrap routine in ExtUtils/MakeMaker.pm.\n";
2027         print BS "\@DynaLoader::dl_resolve_using = ";
2028         # If @all contains names in the form -lxxx or -Lxxx then it's asking for
2029         # runtime library location so we automatically add a call to dl_findfile()
2030         if (" @all" =~ m/ -[lLR]/){
2031             print BS "  dl_findfile(qw(\n  @all\n  ));\n";
2032         }else{
2033             print BS "  qw(@all);\n";
2034         }
2035         # write extra code if *_BS says so
2036         print BS $DynaLoader::bscode if $DynaLoader::bscode;
2037         print BS "\n1;\n";
2038         close BS;
2039     }
2040 }
2041
2042 sub mksymlists {
2043     my($self) = shift;
2044
2045     # only AIX requires a symbol list at this point
2046     # (so does VMS, but that's handled by the MM_VMS package)
2047     return '' unless $Config{'osname'} eq 'AIX';
2048
2049     init_main(@ARGV) unless defined $att{'BASEEXT'};
2050     if (! %{$att{DL_FUNCS}}) {
2051        (my($bootfunc) = $att{NAME}) =~ s/\W/_/g;
2052        $att{DL_FUNCS} = {$att{BASEEXT} => ["boot_$bootfunc"]};
2053     }
2054     rename "$att{BASEEXT}.exp", "$att{BASEEXT}.exp_old";
2055
2056     open(EXP,">$att{BASEEXT}.exp") or die $!;
2057     print EXP join("\n",@{$att{DL_VARS}}) if @{$att{DL_VARS}};
2058     foreach $pkg (keys %{$att{DL_FUNC}}) {
2059         (my($prefix) = $pkg) =~ s/\W/_/g;
2060         foreach $func (@{$att{DL_FUNC}->{$pkg}}) {
2061             $func = "XS_${prefix}_$func" unless $func =~ /^boot_/;
2062             print EXP "$func\n";
2063         }
2064     }
2065     close EXP;
2066 }
2067
2068 # --- Output postprocessing section ---
2069 #nicetext is included to make VMS support easier
2070 sub nicetext { # Just return the input - no action needed
2071     my($self,$text) = @_;
2072     $text;
2073 }
2074
2075 =head1 AUTHORS
2076
2077 Andy Dougherty F<E<lt>doughera@lafcol.lafayette.eduE<gt>>, Andreas
2078 Koenig F<E<lt>k@franz.ww.TU-Berlin.DEE<gt>>, Tim Bunce
2079 F<E<lt>Tim.Bunce@ig.co.ukE<gt>>.  VMS support by Charles Bailey
2080 F<E<lt>bailey@HMIVAX.HUMGEN.UPENN.EDUE<gt>>.
2081
2082 =head1 MODIFICATION HISTORY
2083
2084 v1, August 1994; by Andreas Koenig. Based on Andy Dougherty's Makefile.SH.
2085 v2, September 1994 by Tim Bunce.
2086 v3.0 October  1994 by Tim Bunce.
2087 v3.1 November 11th 1994 by Tim Bunce.
2088 v3.2 November 18th 1994 by Tim Bunce.
2089 v3.3 November 27th 1994 by Andreas Koenig.
2090 v3.4 December  7th 1994 by Andreas Koenig and Tim Bunce.
2091 v3.5 December 15th 1994 by Tim Bunce.
2092 v3.6 December 15th 1994 by Tim Bunce.
2093 v3.7 December 30th 1994 By Tim Bunce
2094 v3.8 January  17th 1995 By Andreas Koenig and Tim Bunce
2095 v3.9 January 19th 1995 By Tim Bunce
2096
2097 v3.10 January 23rd 1995 By Tim Bunce
2098
2099 miniperl now given preference when defining PERL. This improves the
2100 reliability of ext/*/Makefile's recreating themselves if needed.
2101 $(XS), $(C) and $(H) renamed to XS_FILES C_FILES and H_FILES.
2102 INST_STATIC now INST_ARCHLIBDIR/BASEEXT.a (alongside INST_DYNAMIC).
2103 Static lib no longer copied back to local directory.
2104
2105 v3.11 January 24th 1995 By Andreas Koenig
2106
2107 DynaLoader.c was not deleted by clean target, now fixed.
2108 Added PMDIR attribute that allows directories to be named that contain
2109 only *.p[pl] files to be installed into INST_LIB. Added some documentation.
2110
2111 v4.00 January 24th 1995 By Tim Bunce
2112
2113 Revised some of the documentation. Changed version number to 4.00 to
2114 avoid problems caused by my earlier poor choice of 3.10!  Renamed PMDIR
2115 to PMLIBDIRS and restructured find code to use inherited MY->libscan.
2116 Added ability to say: "perl Makefile.PL help"  to get help.
2117 Added ability to say: "perl Makefile.PL verbose"  to get debugging.
2118 Added MakeMaker version number to generated Makefiles.
2119
2120 v4.01 January 25th 1995 By Tim Bunce
2121
2122 Changes in the section that deals with PMLIBDIRS: some pm files were
2123 put into INST_LIB instead of INST_LIBDIR.
2124
2125 v4.02 January 29th 1995 By Andreas Koenig
2126
2127 Enabled the use of the XXX_cflags variable from Config.pm for nested
2128 extensions: to change e.g. the $Config{"ccflags"} variable on the NeXT
2129 for the nTk::pTk extension, say
2130     nTk__pTk_cflags='ccflags="-posix $ccflags"'
2131 in the hints-file.
2132
2133 Hints may now be put in a hints/*.sh file within the the module's
2134 directory tree. Any *.sh file in that directory acts as if it had been
2135 parsed during the perl build process.
2136
2137 Added O_FILES, which is an array like C_FILES. Done so to add a
2138 dependency O_FILES from H_FILES. This has the effect, that the
2139 extension gets rebuilt after some headerfiles have changed.
2140
2141 Made life easier in some "I've just edited config.sh" situations and
2142 reduce the risk of "MakeMaker is being pedantic" complaints by letting
2143 the Makefile proceed with a warning if Config.pm is out of date (Tim's
2144 suggestion).
2145
2146 $Verbose now passed to the findperl routine, to get debugging output
2147 from there, too.
2148
2149 Make clean now also deletes the ./blib directory.
2150
2151 Added lots of ideas of Charles Bailey that enable VMS support.
2152
2153 v4.03 January 30th 1995 By Andreas Koenig
2154
2155 check_hints() now also called within runsubdirpl(). More VMS code
2156 included. Trivial cosmetics.
2157
2158 v4.04 Februeary 5th 1995 By Andreas Koenig
2159
2160 Another VMS patch by Charles Bailey added. Documentation restructured.
2161 ext/util/make_ext minor change. 
2162
2163 All *.pm and *.pl files are now touched when MakeMaker finds
2164 them. This inhibits that make omits their installation in
2165 circumstances, where an older version has recently been built.
2166
2167 installperl: perl.exp now goes into $installarchlib/CORE
2168
2169 New files: lib/File/Path.pm, minimod.PL, perllink, and
2170 vms/ext/MM_VMS.pm while writemain.SH is gone. minimod.PL writes a
2171 trivial module, ExtUtils::Miniperl, which has the writemain function
2172 in it to write perlmain.c files. perllink was not in the 4.01 patch
2173 (which was 0i in fact), but it was introduced in 3.10. It is much
2174 smaller now than it was -- most of its code has gone into minimod.PL
2175 and MakeMaker.
2176
2177 MakeMaker now writes a second Makefile that can be perused to make a
2178 new perl binary from some extensions and some libperl libraries. This
2179 Makefile has most likely to be adjusted to needs by hand, but it's a
2180 quite reasonable starting point. The routines related to the writing
2181 of the Makefile are also exploited by a new makeaperl script, that is
2182 not in the patch, but distributed seperately.
2183
2184 v4.05 February 8th 1995 By Andreas Koenig
2185
2186 When searching for static extensions makeaperl() now ignores
2187 inexistent directories. Updated documentation (check_hints() now uses
2188 eval instead of running a shell script)
2189
2190 v4.06 February 10th 1995 By Andreas Koenig
2191
2192 Cleaning up the new interface. Suggestion to freeze now until 5.001.
2193
2194 =head1 NOTES
2195
2196 MakeMaker development work still to be done:
2197
2198 Needs more complete documentation.
2199
2200 Add a html: target when there has been found a general solution to
2201 installing html files.
2202
2203 Create a perllocal.pod somewhere that documents what has been done 
2204 on this system. (Thanks to Jarkko Hietaniemi for the idea)
2205
2206 =cut
2207
2208 # the following keeps AutoSplit happy
2209 package ExtUtils::MakeMaker;
2210 1;
2211
2212 __END__