This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
7172dbdf2a1ba02f0d3df13ae031867a1685674f
[perl5.git] / lib / ExtUtils / MakeMaker.pm
1 package ExtUtils::MakeMaker;
2
3 $Version = 3.7;         # Last edited 19th Dec 1994 by Tim Bunce
4
5 use Config;
6 use Carp;
7 use Cwd;
8
9 require Exporter;
10 @ISA = qw(Exporter);
11 @EXPORT = qw(&WriteMakefile &mkbootstrap $Verbose &writeMakefile);
12 @EXPORT_OK = qw($Version %att %skip %Recognized_Att_Keys @MM_Sections %MM_Sections);
13
14 $Is_VMS = $Config{'osname'} eq 'VMS';
15 require ExtUtils::MM_VMS if $Is_VMS;
16
17 use strict qw(refs);
18
19 $Version = $Version;# avoid typo warning
20 $Verbose = 0;
21 $^W=1;
22
23
24 =head1 NAME
25
26 ExtUtils::MakeMaker - create an extension Makefile
27
28 =head1 SYNOPSIS
29
30 use ExtUtils::MakeMaker;
31 WriteMakefile( ATTRIBUTE => VALUE [, ...] );
32
33 =head1 DESCRIPTION
34
35 This utility is designed to write a Makefile for an extension module
36 from a Makefile.PL. It is based on the Makefile.SH model provided by
37 Andy Dougherty and the perl5-porters.
38
39 It splits the task of generating the Makefile into several subroutines
40 that can be individually overridden.  Each subroutine returns the text
41 it wishes to have written to the Makefile.
42
43 =head2 Default Makefile Behaviour
44
45 This section (not yet written) will describe how a default Makefile will behave.
46
47 =head2 Determination of Perl Library and Installation Locations
48
49 MakeMaker needs to know, or to guess, where certain things are located.
50 Especially INST_LIB, INST_ARCHLIB, PERL_LIB, PERL_ARCHLIB and PERL_SRC.
51
52 Because installperl does not currently install header files (etc) into
53 the library the Perl source code must be available when building
54 extensions.  Currently MakeMaker will default PERL_LIB and PERL_ARCHLIB
55 to PERL_SRC/lib.  Later, once installperl does install header files
56 (etc) into the library, PERL_*LIB will only default to PERL_SRC/lib if
57 the extension is in PERL_SRC/ext/* (e.g., a standard extension).
58 Otherwise PERL_*LIB and PERL_SRC will default to the public library
59 locations.
60
61 INST_LIB and INST_ARCHLIB default to PERL_LIB and PERL_ARCHLIB.
62
63 =head2 Useful Default Makefile Macros
64
65 FULLEXT = Pathname for extension directory (eg DBD/Oracle).
66
67 BASEEXT = Basename part of FULLEXT. May be just equal FULLEXT.
68
69 ROOTEXT = Directory part of FULLEXT with leading slash (eg /DBD)
70
71 PERL_LIB
72
73 PERL_ARCHLIB
74
75 INST_LIB
76
77 INST_ARCHLIB
78
79 INST_LIBDIR = $(INST_LIB)$(ROOTEXT)          (and INST_ARCHLIBDIR)
80
81 INST_AUTODIR = $(INST_LIB)/auto/$(FULLEXT)   (and INST_ARCHAUTODIR)
82
83 =head2 Customizing The Generated Makefile
84
85 If the Makefile generated does not fit your purpose you can change it
86 using the mechanisms described below.
87
88 =head2 Using Attributes (and Parameters)
89
90 The following attributes can be specified as arguments to WriteMakefile()
91 or as NAME=VALUE pairs on the command line:
92
93 (not yet complete)
94
95 =head2 Overriding MakeMaker Methods
96
97 If you cannot achieve the desired Makefile behaviour by specifying
98 attributes you may define private subroutines in the Makefile.PL.
99 Each subroutines returns the text it wishes to have written to
100 the Makefile. To override a section of the Makefile you can
101 either say:
102
103         sub MY::c_o { "new literal text" }
104
105 or you can edit the default by saying something like:
106
107         sub MY::c_o { $_=MM->c_o; s/old text/new text/; $_ }
108
109 If you still need a different solution, try to develop another 
110 subroutine, that fits your needs and submit the diffs to 
111 perl5-porters@isu.edu or comp.lang.perl as appropriate.
112
113
114 =head1 AUTHORS
115
116 Andy Dougherty <doughera@lafcol.lafayette.edu>, Andreas Koenig
117 <k@franz.ww.TU-Berlin.DE>, Tim Bunce <Tim.Bunce@ig.co.uk>
118
119 =head1 MODIFICATION HISTORY
120
121 v1, August 1994; by Andreas Koenig.
122
123 Initial version. Based on Andy Dougherty's Makefile.SH work.
124
125 v2, September 1994; by Tim Bunce.
126
127 Use inheritance to implement overriding.  Methods return text so
128 derived methods can edit it before it's output.  mkbootstrap() now
129 executes the *_BS file in the DynaLoader package and automatically adds
130 dl_findfile() if required. More support for nested modules.
131
132 v3.0, October/November 1994; by Tim Bunce.
133
134 Major reorganisation. Fixed perl binary locating code. Replaced single
135 $(TOP) with $(PERL_SRC), $(PERL_LIB) and $(INST_LIB).  Restructured
136 code.  Consolidated and/or eliminated several attributes and added
137 argument name checking. Added initial pod documentation. Made generated
138 Makefile easier to read. Added generic mechanism for passing parameters
139 to specific sections of the Makefile. Merged in Andreas's perl version
140 of Andy's extliblist.
141
142 v3.1 November 11th 1994 by Tim Bunce
143
144 Fixed AIX dynamic loading problem for nested modules. Fixed perl
145 extliblist to give paths not names for libs so that cross-check works.
146 Converted the .xs to .c translation to a suffix rule. Added a .xs.o
147 rule for dumb makes.  Added very useful PM, XS and DIR attributes. Used
148 new attributes to make other sections smarter (especially clean and
149 realclean). Make clean no longer deletes Makefile so that a later make
150 realclean can still work. Fixed all known problems.  Write temporary
151 Makefile as Makefile.new and rename once complete.
152
153 v3.2 November 18th 1994 By Tim Bunce
154
155 Fixed typos, added makefile section (split out of a flattened
156 perldepend section). Added subdirectories to test section. Added -lm
157 fix for NeXT in extliblist. Added clean of *~ files. Tidied up clean
158 and realclean sections to produce fewer lines. Major revision to the
159 const_loadlibs comments for EXTRALIBS, LDLOADLIBS and BSLOADLIBS.
160 Added LINKTYPE=\$(LINKTYPE) to subdirectory make invocations.
161 Write temporary Makefile as MakeMaker.tmp. Write temporary xsubpp
162 output files as xstmp.c instead of tmp. Now installs multiple PM files.
163 Improved parsing of NAME=VALUE args. $(BOOTSTRAP) is now a dependency
164 of $(INST_DYNAMIC). Improved init of PERL_LIB, INST_LIB and PERL_SRC.
165 Reinstated $(TOP) for transition period.  Removed CONFIG_SH attribute
166 (no longer used). Put INST_PM back and include .pm and .pl files in
167 current and lib directory.  Allow OBJECT to contain newlines. ROOTEXT
168 now has leading slash. Added INST_LIBDIR (containing ROOTEXT) and
169 renamed AUTOEXT to INST_AUTO.  Assorted other cosmetic changes.
170 All known problems fixed.
171
172 v3.3 November 27th 1994 By Andreas Koenig
173
174 Bug fixes submitted by Michael Peppler and Wayne Scott. Changed the
175 order how @libpath is constructed in C<new_extliblist()>. Improved
176 pod-structure. Relative paths in C<-L> switches to LIBS are turned into
177 absolute ones now.  Included VMS support thanks to submissions by
178 Charles Bailey.  Added warnings for switches other than C<-L> or C<-l>
179 in new_extliblist() and if a library is not found at all. Changed
180 dependency distclean:clean to distclean:realclean. Added dependency
181 all->config. ext.libs is now written without duplicates and empty
182 lines.  As old_extliblist() and new_extliblist() do not produce the
183 same anymore, the default becomes new_extliblist(), though the warning
184 remains, whenever they differ. The use of cflags is accompanied by a
185 replacement: there will be a warning when the two routines lead to
186 different results, but still the output of cflags will be used.
187 Cosmetic changes (Capitalize globals, uncapitalize others, insert a
188 C<:> as default for $postop). Added some verbosity.
189
190 v3.4 December 7th 1994 By Andreas Koenig and Tim Bunce
191
192 Introduced ARCH_LIB and required other perl files to be patched.
193
194 v3.5 December 15th 1994 By Tim Bunce
195
196 Based primarily on v3.3. Replaced ARCH_LIB with INST_ARCHLIB, which
197 defaults to INST_LIB, because the rest of perl assumes that ./lib
198 includes architecture dependent files. Ideally an ./archlib should
199 exist, that would be more consistent and simplify installperl.
200 Added linkext and $(INST_PM) dependencies to all: target. The linkext
201 target (and subroutine) exists solely to depend on $(LINKTYPE). Any
202 Makefile.PLs using LINKTYPE => '...' where '...' is not 'static' or
203 'dynamic' should be changed to use 'linkext' => { LINKTYPE => '...' }.
204
205 Automatic determination of PERL_* and INST_* has been revised.  The
206 INST_* macros have INST_ARCH* and INST_*DIR variants. The ARCH variants
207 point to the architecture specific directory and the *DIR variants
208 include the module specific subdirectory path.  So INST_AUTO is now
209 INST_AUTODIR and an INST_ARCHAUTODIR has also been defined.
210
211 An AUTOSPLITFILE tool macro has been defined which will AutoSplit any
212 named file into any named auto directory. This replaces AUTOSPLITLIB.
213 MKPATH now accepts multiple paths. The paths INST_LIBDIR,
214 INST_ARCHLIBDIR, INST_AUTODIR and INST_ARCHAUTODIR are made by the
215 config: target. A new ext.libs mechanism has been added. installpm has
216 been split and now calls installpm_x per file.  A section attribute
217 mechanism has been added and skip cross-checking has been moved into a
218 skipcheck function. MakeMaker now uses Cwd and File::Basename modules.
219
220 v3.6 December 15th 1994 By Tim Bunce
221
222 Added C and H attributes and corresponding macros. These default to the
223 list of *.c and *.h files in the directory. C also includes *.c file
224 names corresponding to any *.xs files in the directory. ARMAYBE should
225 now be specified as an attribute of the dynamic_lib section. The installpm
226 section now accepts a SPLITLIB attribute. This defaults to '$(INST_LIB)'.
227 Improved automatic setting of INST_ARCHLIB. Newlines in OBJECT now translate
228 into <space><backslash><newline><tab> for better formatting. Improved
229 descriptive comments for EXTRALIBS, LDLOADLIBS and BSLOADLIBS. Bootstrap
230 files are now always installed - (after a small patch) the DynaLoader will
231 only read a non-empty bootstrap file. Subdirectory dependencies have
232 been improved. The .c files produced from .xs files now depend on
233 XSUBPPDEPS (the typemaps).
234
235
236 =head1 NOTES
237
238 MakeMaker development work still to be done:
239
240 Needs more complete documentation.
241
242 Replace use of cflags with %Config (taking note of hints etc)
243
244 Move xsubpp and typemap into lib/ExtUtils/...
245
246 The ext.libs file mechanism will need to be revised to allow a
247 make-a-perl [list-of-static-extensions] script to work.
248
249 Eventually eliminate use of $(PERL_SRC). This must wait until
250 MakeMaker is the standard and Larry makes the required changes
251 elsewhere.
252
253 Add method to take a list of files and wrap it in a Makefile
254 compatible way (<space><backslash><newline><tab>).
255
256 =cut
257
258
259 # Setup dummy package:
260 # MY exists for overriding methods to be defined within
261 unshift(@MY::ISA, qw(MM));
262
263 # Dummy package MM inherits actual methods from OS-specific
264 # default packages.  We use this intermediate package so
265 # MY->func() can call MM->func() and get the proper
266 # default routine without having to know under what OS
267 # it's running.
268 unshift(@MM::ISA, $Is_VMS ? qw(ExtUtils::MM_VMS MM_Unix) : qw(MM_Unix));
269
270 $Attrib_Help = <<'END';
271  NAME:          Perl module name for this extension (DBD::Oracle)
272                 This defaults to the directory name.
273
274  DISTNAME:      Your name for distributing the package (by tar file)
275                 This defaults to NAME above.
276
277  VERSION:       Your version number for distributing the package.
278                 This defaults to 0.1.
279
280  INST_LIB:      Perl library directory to install the module into.
281  INST_ARCHLIB:  Perl architecture-dependent library to install into
282                 (defaults to INST_LIB)
283
284  PERL_LIB:      Directory containing the Perl library to use.
285  PERL_SRC:      Directory containing the Perl source code
286                 (use of this should be avoided, it may be undefined)
287
288  INC:           Include file dirs eg: '-I/usr/5include -I/path/to/inc'
289  DEFINE:        something like "-DHAVE_UNISTD_H"
290  OBJECT:        List of object files, defaults to '$(BASEEXT).o',
291                 but can be a long string containing all object files,
292                     e.g. "tkpBind.o tkpButton.o tkpCanvas.o"
293  MYEXTLIB:      If the extension links to a library that it builds
294                 set this to the name of the library (see SDBM_File)
295
296  LIBS:          An anonymous array of alternative library specifications
297                 to be searched for (in order) until at least one library
298                 is found.
299                   'LIBS' => [ "-lgdbm", "-ldbm -lfoo", "-L/path -ldbm.nfs" ]
300                 Mind, that any element of the array contains a complete
301                 set of arguments for the ld command. So do not specify
302                   'LIBS' => ["-ltcl", "-ltk", "-lX11" ], #wrong
303                 See ODBM_File/Makefile.PL for an example, where an
304                 array is needed. If you specify a scalar as in
305                   'LIBS' => "-ltcl -ltk -lX11"
306                 MakeMaker will turn it into an array with one element.
307
308  LDTARGET:      defaults to "$(OBJECT)" and is used in the ld command
309                 (some machines need additional switches for bigger projects)
310
311  DIR:           Ref to array of subdirectories containing Makefile.PLs
312                 e.g. [ 'sdbm' ] in ext/SDBM_File
313
314  PM:            Hashref of .pm files and *.pl files to be installed.
315                 e.g. { 'name_of_file.pm' => '$(INST_LIBDIR)/install_as.pm' }
316                 By default this will include *.pm and *.pl. If a lib directory
317                 exists and is not listed in DIR (above) then any *.pm and
318                 *.pl files it contains will also be included by default.
319
320  XS:            Hashref of .xs files. MakeMaker will default this.
321                 e.g. { 'name_of_file.xs' => 'name_of_file.c' }
322                 The .c files will automatically be included in the list
323                 of files deleted by a make clean.
324
325  C:             Ref to array of *.c file names. Initialised from a directory scan
326                 and the values portion of the XS attribute hash. This is not
327                 currently used by MakeMaker but may be handy in Makefile.PLs.
328
329  H:             Ref to array of *.h file names. Similar to C: above.
330
331  LINKTYPE:      =>'static' or 'dynamic' (default unless usedl=undef in config.sh)
332                 Should only be used to force static linking (also see linkext below).
333
334  CONFIG:        =>[qw(archname manext)] defines ARCHNAME & MANEXT from config.sh
335  SKIP:          =>[qw(name1 name2)] skip (do not write) sections of the Makefile
336
337  PERL:
338  FULLPERL:
339
340 Additional lowercase attributes can be used to pass parameters to the
341 methods which implement that part of the Makefile. These are not
342 normally required:
343
344  installpm:     {SPLITLIB => '$(INST_LIB)' (default) or '$(INST_ARCHLIB)'}
345  linkext:       {LINKTYPE => 'static', 'dynamic' or ''}
346  dynamic_lib    {ARMAYBE => 'ar', OTHERLDFLAGS => '...'}
347  clean:         {FILES => "*.xyz foo"}
348  realclean:     {FILES => '$(INST_AUTODIR)/*.xyz'}
349  distclean:     {TARNAME=>'MyTarFile', TARFLAGS=>'cvfF', COMPRESS=>'gzip'}
350  tool_autosplit:        {MAXLEN => 8}
351 END
352
353 @MM_Sections_spec = (
354     'post_initialize'   => {},
355     'constants'         => {},
356     'const_config'      => {},
357     'const_loadlibs'    => {},
358     'const_cccmd'       => {},
359     'tool_autosplit'    => {},
360     'tool_xsubpp'       => {},
361     'tools_other'       => {},
362     'post_constants'    => {},
363     'c_o'               => {},
364     'xs_c'              => {},
365     'xs_o'              => {},
366     'top_targets'       => {},
367     'linkext'           => {},
368     'dynamic'           => {},
369     'dynamic_bs'        => {},
370     'dynamic_lib'       => {},
371     'static'            => {},
372     'static_lib'        => {},
373     'installpm'         => {},
374     'subdirs'           => {},
375     'clean'             => {},
376     'realclean'         => {},
377     'distclean'         => {},
378     'test'              => {},
379     'install'           => {},
380     'force'             => {},
381     'perldepend'        => {},
382     'makefile'          => {},
383     'postamble'         => {},
384 );
385 %MM_Sections = @MM_Sections_spec; # looses section ordering
386 @MM_Sections = grep(!ref, @MM_Sections_spec); # keeps order
387
388 %Recognized_Att_Keys = %MM_Sections; # All sections are valid keys.
389 foreach(split(/\n/,$Attrib_Help)){
390     chomp;
391     next unless m/^\s*(\w+):\s*(.*)/;
392     $Recognized_Att_Keys{$1} = $2;
393     print "Attribute '$1' => '$2'\n" if ($Verbose >= 2);
394 }
395
396 %att  = ();
397 %skip = ();
398
399 sub skipcheck{
400     my($section) = @_;
401     return 'skipped' if $skip{$section};
402     return '';
403 }
404
405
406 sub WriteMakefile {
407     %att = @_;
408     local($\)="\n";
409
410     print STDOUT "MakeMaker" if $Verbose;
411
412     parse_args(\%att, @ARGV);
413     my(%initial_att) = %att; # record initial attributes
414
415     MY->initialize(@ARGV);
416
417     print STDOUT "Writing Makefile for $att{NAME}";
418
419     unlink("Makefile", "MakeMaker.tmp", $Is_VMS ? 'Descrip.MMS' : '');
420     open MAKE, ">MakeMaker.tmp" or die "Unable to open MakeMaker.tmp: $!";
421     select MAKE; $|=1; select STDOUT;
422
423     print MAKE "# This Makefile is for the $att{NAME} extension to perl.\n#";
424     print MAKE "# It was generated automatically by MakeMaker from the contents";
425     print MAKE "# of Makefile.PL. Don't edit this file, edit Makefile.PL instead.";
426     print MAKE "#\n#    ANY CHANGES MADE HERE WILL BE LOST! \n#";
427     print MAKE "#   MakeMaker Parameters: ";
428     foreach $key (sort keys %initial_att){
429         my($v) = neatvalue($initial_att{$key});
430         $v =~ tr/\n/ /s;
431         print MAKE "#   $key => $v";
432     }
433
434     # build hash for SKIP to make testing easy
435     %skip = map( ($_,1), @{$att{'SKIP'} || []});
436
437     foreach $section ( @MM_Sections ){
438         print "Processing Makefile '$section' section" if ($Verbose >= 2);
439         my($skipit) = skipcheck($section);
440         if ($skipit){
441             print MAKE "\n# --- MakeMaker $section section $skipit.";
442         } else {
443             my(%a) = %{$att{$section} || {}};
444             print MAKE "\n# --- MakeMaker $section section:";
445             print MAKE "# ",%a if ($Verbose >= 2);
446             print(MAKE MY->nicetext(MY->$section( %a )));
447         }
448     }
449
450     if ($Verbose){
451         print MAKE "\n# Full list of MakeMaker attribute values:";
452         foreach $key (sort keys %att){
453             my($v) = neatvalue($att{$key});
454             $v =~ tr/\n/ /s;
455             print MAKE "#       $key => $v";
456         }
457     }
458
459     print MAKE "\n# End.";
460     close MAKE;
461     my($finalname) = $Is_VMS ? "Descrip.MMS" : "Makefile";
462     rename("MakeMaker.tmp", $finalname);
463
464     chmod 0644, $finalname;
465     system("$Config{'eunicefix'} $finalname") unless $Config{'eunicefix'} eq ":";
466
467     1;
468 }
469
470
471 sub mkbootstrap{
472     parse_args(\%att, @ARGV);
473     MY->mkbootstrap(@_);
474 }
475
476
477 sub parse_args{
478     my($attr, @args) = @_;
479     foreach (@args){
480         next unless m/(.*?)=(.*)/;
481         $$attr{$1} = $2;
482     }
483     # catch old-style 'potential_libs' and inform user how to 'upgrade'
484     if (defined $$attr{'potential_libs'}){
485         my($msg)="'potential_libs' => '$$attr{potential_libs}' should be";
486         if ($$attr{'potential_libs'}){
487             print STDERR "$msg changed to:\n\t'LIBS' => ['$$attr{potential_libs}']\n";
488         } else {
489             print STDERR "$msg deleted.\n";
490         }
491         $$attr{LIBS} = [$$attr{'potential_libs'}];
492         delete $$attr{'potential_libs'};
493     }
494     # catch old-style 'ARMAYBE' and inform user how to 'upgrade'
495     if (defined $$attr{'ARMAYBE'}){
496         my($armaybe) = $$attr{'ARMAYBE'};
497         print STDERR "ARMAYBE => '$armaybe' should be changed to:\n",
498                         "\t'dynamic_lib' => {ARMAYBE => '$armaybe'}\n";
499         my(%dl) = %{$$attr{'dynamic_lib'} || {}};
500         $$attr{'dynamic_lib'} = { %dl, ARMAYBE => $armaybe};
501         delete $$attr{'ARMAYBE'};
502     }
503     foreach(sort keys %{$attr}){
504         print STDOUT "  $_ => ".neatvalue($$attr{$_}) if ($Verbose);
505         warn "'$_' is not a known MakeMaker parameter name.\n"
506             unless exists $Recognized_Att_Keys{$_};
507     }
508 }
509
510
511 sub neatvalue{
512     my($v) = @_;
513     my($t) = ref $v;
514     return "'$v'" unless $t;
515     return "[ ".join(', ',map("'$_'",@$v))." ]" if ($t eq 'ARRAY');
516     return "$v" unless $t eq 'HASH';
517     my(@m, $key, $val);
518     push(@m,"$key=>".neatvalue($val)) while (($key,$val) = each %$v);
519     return "{ ".join(', ',@m)." }";
520 }
521
522
523 # ------ Define the MakeMaker default methods in package MM_Unix ------
524
525 package MM_Unix;
526
527 use Config;
528 use Cwd;
529 use File::Basename;
530 require Exporter;
531
532 Exporter::import('ExtUtils::MakeMaker',
533         qw(%att %skip %Recognized_Att_Keys $Verbose));
534
535 # These attributes cannot be overridden externally
536 @Other_Att_Keys{qw(EXTRALIBS BSLOADLIBS LDLOADLIBS)} = (1) x 3;
537
538 if ($Is_VMS = $Config{'osname'} eq 'VMS') {
539     require File::VMSspec;
540     import File::VMSspec 'vmsify';
541 }
542
543
544 sub initialize {
545     # Find out directory name.  This may contain the extension name.
546     my($pwd) = fastcwd(); # from Cwd.pm
547
548     # --- Initialize PERL_LIB, INST_LIB, PERL_SRC
549
550     # *Real* information: where did we get these two from? ...
551     $inc_config_dir = dirname($INC{'Config.pm'});
552     $inc_carp_dir   = dirname($INC{'Carp.pm'});
553
554     # Typically PERL_* and INST_* will be identical but that need
555     # not be the case (e.g., installing into project libraries etc).
556
557     # Perl Macro:    With source    No source
558     # PERL_LIB       ../../lib      /usr/local/lib/perl5
559     # PERL_ARCHLIB   ../../lib      /usr/local/lib/perl5/sun4-sunos
560     # PERL_SRC       ../..          (undefined)
561
562     # INST Macro:    Locally        Publically
563     # INST_LIB       ../../lib      /usr/local/lib/perl5
564     # INST_ARCHLIB   ../../lib      /usr/local/lib/perl5/sun4-sunos
565
566     # This code will need to be reworked to deal with having no perl
567     # source.  PERL_LIB should become the primary focus.
568
569     unless ($att{PERL_SRC}){
570         foreach(qw(../.. ../../.. ../../../..)){
571             ($att{PERL_SRC}=$_, last) if -f "$_/config.sh";
572         }
573     }
574     unless ($att{PERL_SRC}){
575         warn "Unable to locate perl source.\n";
576         # we should also consider $ENV{PERL5LIB} here
577         $att{PERL_LIB}     = $Config{'privlib'} unless $att{PERL_LIB};
578         $att{PERL_ARCHLIB} = $Config{'archlib'} unless $att{PERL_ARCHLIB};
579         $att{PERL_INC}     = "$att{PERL_ARCHLIB}/CORE"; # wild guess for now
580         die "Try setting PERL_SRC in Makefile.PL or on command line.\n"
581                 unless (-f "$att{PERL_INC}/perl.h");
582     } else {
583         $att{PERL_LIB}     = "$att{PERL_SRC}/lib" unless $att{PERL_LIB};
584         $att{PERL_ARCHLIB} = $att{PERL_LIB};
585         $att{PERL_INC}     = $att{PERL_SRC};
586     }
587
588     # INST_LIB typically pre-set if building an extension after
589     # perl has been built and installed. Setting INST_LIB allows
590     # You to build directly into privlib and avoid installperl.
591     $att{INST_LIB} = $att{PERL_LIB} unless $att{INST_LIB};
592
593     # Try to work out what INST_ARCHLIB should be if not set:
594     unless ($att{INST_ARCHLIB}){
595         my(%archmap) = (
596             $att{PERL_LIB}      => $att{PERL_ARCHLIB},
597             $Config{'privlib'}  => $Config{'archlib'},
598             $Config{'installprivlib'}   => $Config{'installarchlib'},
599             $inc_carp_dir       => $inc_config_dir,
600         );
601         $att{INST_ARCHLIB} = $archmap{$att{INST_LIB}};
602         die "Unable to determine INST_ARCHLIB. Please define it explicitly.\n"
603             unless $att{INST_ARCHLIB};
604     }
605
606     # make a few simple checks
607     die "PERL_LIB ($att{PERL_LIB}) is not a perl library directory"
608         unless (-f "$att{PERL_LIB}/Exporter.pm");
609
610     # --- Initialize Module Name and Paths
611
612     # NAME    = The perl module name for this extension (eg DBD::Oracle).
613     # FULLEXT = Pathname for extension directory (eg DBD/Oracle).
614     # BASEEXT = Basename part of FULLEXT. May be just equal FULLEXT.
615     # ROOTEXT = Directory part of FULLEXT with leading /.
616     unless($att{NAME}){ # we have to guess our name
617         my($name) = $pwd;
618         if ($Is_VMS) {
619           $name =~ s:.*?([^.\]]+)\]:$1: unless ($name =~ s:.*[.\[]ext\.::);
620           ($att{NAME}=$name) =~ s#[.\]]#::#g;
621         } else {
622           $name =~ s:.*/:: unless ($name =~ s:^.*/ext/::);
623           ($att{NAME} =$name) =~ s#/#::#g;
624         }
625     }
626     ($att{FULLEXT} =$att{NAME}) =~ s#::#/#g ;           #eg. BSD/Foo/Socket
627     ($att{BASEEXT} =$att{NAME}) =~ s#.*::##;            #eg. Socket
628     ($att{ROOTEXT} =$att{FULLEXT}) =~ s#/?\Q$att{BASEEXT}\E$## ; # eg. /BSD/Foo
629     $att{ROOTEXT} = "/$att{ROOTEXT}" if $att{ROOTEXT};
630     $att{ROOTEXT} = "" if $Is_VMS;
631
632     ($att{DISTNAME}=$att{NAME}) =~ s#(::)#-#g;
633     $att{VERSION} = "0.1" unless $att{VERSION};
634
635
636     # --- Initialize Perl Binary Locations
637
638     # Find Perl 5. The only contract here is that both 'PERL' and 'FULLPERL'
639     # will be working versions of perl 5.
640     $att{'PERL'} = MY->find_perl(5.0, [ qw(perl5 perl miniperl) ],
641             [ $att{PERL_SRC}, split(":", $ENV{PATH}), $Config{'bin'} ], 0 )
642         unless ($att{'PERL'} && -x $att{'PERL'});
643
644     # Define 'FULLPERL' to be a non-miniperl (used in test: target)
645     ($att{'FULLPERL'} = $att{'PERL'}) =~ s/miniperl/perl/
646         unless ($att{'FULLPERL'} && -x $att{'FULLPERL'});
647
648     if ($Is_VMS) {
649         ($att{'PERL'} = 'MCR ' . vmsify($att{'PERL'})) =~ s:.*/::;
650         ($att{'FULLPERL'} = 'MCR ' . vmsify($att{'FULLPERL'})) =~ s:.*/::;
651     }
652
653     # --- Initialize File and Directory Lists (.xs .pm etc)
654
655     {
656         my($name, %dir, %xs, %pm, %c, %h, %ignore);
657         $ignore{'test.pl'} = 1;
658         $ignore{'makefile.pl'} = 1 if $Is_VMS;
659         foreach $name (lsdir(".")){
660             next if ($name =~ /^\./ or $ignore{$name});
661             if (-d $name){
662                 $dir{$name} = $name if (-f "$name/Makefile.PL");
663             }elsif ($name =~ /\.xs$/){
664                 my($c); ($c = $name) =~ s/\.xs$/.c/;
665                 $xs{$name} = $c;
666                 $c{$c} = 1;
667             }elsif ($name =~ /\.c$/){
668                 $c{$name} = 1;
669             }elsif ($name =~ /\.h$/){
670                 $h{$name} = 1;
671             }elsif ($name =~ /\.p[ml]$/){
672                 $pm{$name} = "\$(INST_LIBDIR)/$name";
673             }
674         }
675
676         # If we have a ./lib dir that does NOT contain a Makefile.PL
677         # then add in any .pm and .pl files in that directory.
678         # This makes it easy and tidy to ship a number of perl files.
679         if (-d "lib" and !$dir{'lib'}){
680             foreach $name (lsdir("lib")){
681                 next unless ($name =~ /\.p[ml]$/);
682                 $pm{"lib/$name"} = "\$(INST_LIBDIR)/$name";
683             }
684         }
685
686         $att{DIR} = [sort keys %dir] unless $att{DIRS};
687         $att{XS}  = \%xs             unless $att{XS};
688         $att{PM}  = \%pm             unless $att{PM};
689         $att{C}   = [sort keys %c]   unless $att{C};
690         $att{H}   = [sort keys %h]   unless $att{H};
691     }
692
693     # --- Initialize Other Attributes
694
695     for $key (keys(%Recognized_Att_Keys), keys(%Other_Att_Keys)){
696         # avoid warnings for uninitialized vars
697         next if exists $att{$key};
698         $att{$key} = "";
699     }
700
701     # Compute EXTRALIBS, BSLOADLIBS and LDLOADLIBS from $att{'LIBS'}
702     # Lets look at $att{LIBS} carefully: It may be an anon array, a string or
703     # undefined. In any case we turn it into an anon array:
704     $att{LIBS}=[] unless $att{LIBS};
705     $att{LIBS}=[$att{LIBS}] if ref \$att{LIBS} eq SCALAR;
706     foreach ( @{$att{'LIBS'}} ){
707         s/^\s*(.*\S)\s*$/$1/; # remove leading and trailing whitespace
708         my(@libs) = MY->extliblist($_);
709         if ($libs[0] or $libs[1] or $libs[2]){
710             @att{EXTRALIBS, BSLOADLIBS, LDLOADLIBS} = @libs;
711             last;
712         }
713     }
714
715     warn "CONFIG must be an array ref\n"
716         if ($att{CONFIG} and ref $att{CONFIG} ne 'ARRAY');
717     $att{CONFIG} = [] unless (ref $att{CONFIG});
718     push(@{$att{CONFIG}},
719         qw( cc libc ldflags lddlflags ccdlflags cccdlflags
720             ranlib so dlext dlsrc installprivlib installarchlib
721         ));
722     push(@{$att{CONFIG}}, 'shellflags') if $Config{'shellflags'};
723
724     if ($Is_VMS) {
725       # This will not make other Makefile.PLs portable. Any Makefile.PL
726       # which says OBJECT => "foo.o bar.o" will fail on VMS. It might
727       # be better to fix the c_o section to produce .o files.
728       $att{OBJECT} = '$(BASEEXT).obj' unless $att{OBJECT};
729       $att{OBJECT} =~ s/[^,\s]\s+/, /g;
730       $att{OBJECT} =~ s/\n+/, /g;
731     } else {
732       $att{OBJECT} = '$(BASEEXT).o' unless $att{OBJECT};
733       $att{OBJECT} =~ s/\n+/ \\\n\t/g;
734     }
735     $att{BOOTDEP}  = (-f "$att{BASEEXT}_BS") ? "$att{BASEEXT}_BS" : "";
736     $att{LD}       = ($Config{'ld'} || 'ld') unless $att{LD};
737     $att{LDTARGET} = '$(OBJECT)' unless $att{LDTARGET};
738     $att{LINKTYPE} = ($Config{'usedl'}) ? 'dynamic' : 'static'
739         unless $att{LINKTYPE};
740
741 }
742
743
744 sub lsdir{
745     local(*DIR, @ls);
746     opendir(DIR, $_[0] || ".") or die "opendir: $!";
747     @ls = readdir(DIR);
748     closedir(DIR);
749     @ls;
750 }
751
752
753 sub find_perl{
754     my($self, $ver, $names, $dirs, $trace) = @_;
755     my($name, $dir);
756     print "Looking for perl $ver by these names: @$names, in these dirs: @$dirs\n"
757         if ($trace);
758     foreach $dir (@$dirs){
759         foreach $name (@$names){
760             print "checking $dir/$name\n" if ($trace >= 2);
761             if ($Is_VMS) {
762               $name .= ".exe" unless -x "$dir/$name";
763             }
764             next unless -x "$dir/$name";
765             print "executing $dir/$name\n" if ($trace);
766             my($out);
767             if ($Is_VMS) {
768               my($vmscmd) = 'MCR ' . vmsify("$dir/$name");
769               $out = `$vmscmd -e "require $ver; print ""VER_OK\n"""`;
770             } else {
771               $out = `$dir/$name -e 'require $ver; print "VER_OK\n" ' 2>&1`;
772             }
773             return "$dir/$name" if $out =~ /VER_OK/;
774         }
775     }
776     warn "Unable to find a perl $ver (by these names: @$names, in these dirs: @$dirs)\n";
777     0; # false and not empty
778 }
779
780
781 sub post_initialize{
782     "";
783 }
784  
785
786 sub constants {
787     my(@m);
788
789     push @m, "
790 NAME = $att{NAME}
791 DISTNAME = $att{DISTNAME}
792 VERSION = $att{VERSION}
793
794 # In which library should we install this extension?
795 # This is typically the same as PERL_LIB.
796 # (also see INST_LIBDIR and relationship to ROOTEXT)
797 INST_LIB = $att{INST_LIB}
798 INST_ARCHLIB = $att{INST_ARCHLIB}
799
800 # Perl library to use when building the extension
801 PERL_LIB = $att{PERL_LIB}
802 PERL_ARCHLIB = $att{PERL_ARCHLIB}
803
804 # Where is the perl source code located? (Eventually we should
805 # be able to build extensions without requiring the perl source
806 # but that's a way off yet).
807 PERL_SRC = $att{PERL_SRC}
808 # Perl header files (will eventually be under PERL_LIB)
809 PERL_INC = $att{PERL_INC}
810 # Perl binaries
811 PERL = $att{'PERL'}
812 FULLPERL = $att{'FULLPERL'}
813
814 # FULLEXT = Pathname for extension directory (eg DBD/Oracle).
815 # BASEEXT = Basename part of FULLEXT. May be just equal FULLEXT.
816 # ROOTEXT = Directory part of FULLEXT with leading slash (eg /DBD)
817 FULLEXT = $att{FULLEXT}
818 BASEEXT = $att{BASEEXT}
819 ROOTEXT = $att{ROOTEXT}
820
821 # These will be removed later. Use PERL_SRC and BASEEXT instead.
822 TOP = \$(PERL_SRC)
823 EXT = CHANGE_EXT_TO_BASEEXT
824
825 INC = $att{INC}
826 DEFINE = $att{DEFINE}
827 OBJECT = $att{OBJECT}
828 LDTARGET = $att{LDTARGET}
829 LINKTYPE = $att{LINKTYPE}
830
831 # Source code:
832 XS= ".join(" \\\n\t", sort keys %{$att{XS}})."
833 C = ".join(" \\\n\t", @{$att{C}})."
834 H = ".join(" \\\n\t", @{$att{H}})."
835
836 .SUFFIXES: .xs
837
838 .PRECIOUS: Makefile
839
840 .PHONY: all config static dynamic test 
841
842 # This extension may link to it's own library (see SDBM_File)
843 MYEXTLIB = $att{MYEXTLIB}
844
845 # Where is the Config.pm that we are using/depend on
846 CONFIGDEP = \$(PERL_ARCHLIB)/Config.pm
847 ";
848
849     push @m, '
850 # Where to put things:
851 INST_LIBDIR     = $(INST_LIB)$(ROOTEXT)
852 INST_ARCHLIBDIR = $(INST_ARCHLIB)$(ROOTEXT)
853
854 INST_AUTODIR     = $(INST_LIB)/auto/$(FULLEXT)
855 INST_ARCHAUTODIR = $(INST_ARCHLIB)/auto/$(FULLEXT)
856
857 INST_BOOT    = $(INST_ARCHAUTODIR)/$(BASEEXT).bs
858 INST_DYNAMIC = $(INST_ARCHAUTODIR)/$(BASEEXT).$(DLEXT)
859 INST_STATIC  = $(BASEEXT).a
860 INST_PM = '.join(" \\\n\t", sort values %{$att{PM}}).'
861 ';
862
863     join('',@m);
864 }
865
866
867 sub const_cccmd{
868     # This is implemented in the
869     # same manner as extliblist, e.g., do both and compare results during
870     # the transition period.
871   my($cc,$ccflags,$optimize,$large,$split)=@Config{qw(cc ccflags optimize large split)};
872   my($prog, $old);
873
874   chop($old = `cd $att{PERL_SRC}; sh $Config{'shellflags'} ./cflags $att{BASEEXT}.c`)
875         if $att{PERL_SRC};
876
877   # Why is this written this way ?
878   if ($prog = $Config{"$att{BASEEXT}_cflags"}) {
879     my(@o)=`cc=\"$cc\"
880       ccflags=\"$ccflags\"
881       optimize=\"$optimize\"
882       large=\"$large\"
883       split=\"$split\"
884       eval '$prog'
885       echo cc=\$cc
886       echo ccflags=\$ccflags
887       echo optimize=\$optimize
888       echo large=\$large
889       echo split=\$split
890       `;
891     my(%cflags);
892     foreach $line (@o){
893       chomp $line;
894       if ($line =~ /(.*?)\s*=\s*(.*)\s*$/){
895         $cflags{$1} = $2;
896         print STDERR "  $1 = $2" if $Verbose;
897       }
898     }
899     ($cc,$ccflags,$optimize,$large,$split)=@cflags{qw(cc ccflags optimize large split)};
900   }
901
902   my($new) = "$cc -c $ccflags $optimize  $large $split";
903   if (defined($old) and $new ne $old) {
904     warn "Warning (non-fatal): cflags evaluation in MakeMaker differs from shell output\n"
905       ."   package: $att{NAME}\n"
906       ."   old: $old\n"
907       ."   new: $new\n"
908       ."   Using 'old' set.\n"
909       ."Please notify perl5-porters\@isu.edu\n";
910   }
911   my($cccmd)=($old) ? $old : $new;
912   "CCCMD = $cccmd\n";
913 }
914
915
916 # --- Constants Sections ---
917
918 sub const_config{
919     my(@m,$m);
920     push(@m,"\n# These definitions are from config.sh (via $INC{'Config.pm'})\n");
921     my(%once_only);
922     foreach $m (@{$att{'CONFIG'}}){
923         next if $once_only{$m};
924         warn "CONFIG key '$m' does not exist in Config.pm\n"
925                 unless exists $Config{$m};
926         push @m, "\U$m\E = $Config{$m}\n";
927         $once_only{$m} = 1;
928     }
929     join('', @m);
930 }
931
932
933 sub const_loadlibs{
934     "
935 # $att{NAME} might depend on some other libraries:
936 # (These comments may need revising:)
937 #
938 # Dependent libraries can be linked in one of three ways:
939 #
940 #  1.  (For static extensions) by the ld command when the perl binary
941 #      is linked with the extension library. See EXTRALIBS below.
942 #
943 #  2.  (For dynamic extensions) by the ld command when the shared
944 #      object is built/linked. See LDLOADLIBS below.
945 #
946 #  3.  (For dynamic extensions) by the DynaLoader when the shared
947 #      object is loaded. See BSLOADLIBS below.
948 #
949 # EXTRALIBS =   List of libraries that need to be linked with when
950 #               linking a perl binary which includes this extension
951 #               Only those libraries that actually exist are included.
952 #               These are written to a file and used when linking perl.
953 #
954 # LDLOADLIBS =  List of those libraries which can or must be linked into
955 #               the shared library when created using ld. These may be
956 #               static or dynamic libraries.
957 #
958 # BSLOADLIBS =  List of those libraries that are needed but can be
959 #               linked in dynamically at run time on this platform.
960 #               SunOS/Solaris does not need this because ld records
961 #               the information (from LDLOADLIBS) into the object file.
962 #               This list is used to create a .bs (bootstrap) file.
963 #               The bootstrap file is installed only if it's not empty.
964 #
965 EXTRALIBS  = $att{'EXTRALIBS'}
966 LDLOADLIBS = $att{'LDLOADLIBS'}
967 BSLOADLIBS = $att{'BSLOADLIBS'}
968 ";
969 }
970
971
972 # --- Tool Sections ---
973
974 sub tool_autosplit{
975     my($self, %attribs) = @_;
976     my($asl) = "";
977     $asl = "\$AutoSplit::Maxlen=$attribs{MAXLEN};" if $attribs{MAXLEN};
978     q{
979 AUTOSPLITLIB = $(PERL) -I$(PERL_ARCHLIB) -I$(PERL_LIB) -e 'use AutoSplit; chdir("$(INST_LIB)/..") or die $$!; $$AutoSplit::Maxlen=}.$asl.q{; autosplit_lib_modules(@ARGV) ;'
980
981 # Usage: $(AUTOSPLITFILE) FileToSplit AutoDirToSplitInto
982 AUTOSPLITFILE = $(PERL) -I$(PERL_ARCHLIB) -I$(PERL_LIB) -e 'use AutoSplit;}.$asl.q{ AutoSplit::autosplit_file($$ARGV[0], $$ARGV[1], 0, 1, 1) ;'
983 };
984 }
985
986
987 sub tool_xsubpp{
988     my($xsdir)  = '$(PERL_LIB)/ExtUtils';
989     # drop back to old location if xsubpp is not in new location yet
990     $xsdir = '$(PERL_SRC)/ext' unless (-f "$att{PERL_LIB}/ExtUtils/xsubpp");
991     my(@tmdeps) = ('$(XSUBPPDIR)/typemap');
992     push(@tmdeps, "typemap") if -f "typemap";
993     my(@tmargs) = map("-typemap $_", @tmdeps);
994     "
995 XSUBPPDIR = $xsdir
996 XSUBPP = \$(XSUBPPDIR)/xsubpp
997 XSUBPPDEPS = @tmdeps
998 XSUBPPARGS = @tmargs
999 ";
1000 };
1001
1002
1003 sub tools_other{
1004     "
1005 SHELL = /bin/sh
1006 LD = $att{LD}
1007 ".q{
1008 # The following is a portable way to say mkdir -p
1009 MKPATH = $(PERL) -wle '$$"="/"; foreach $$p (@ARGV){ my(@p); foreach(split(/\//,$$p)){ push(@p,$$_); next if -d "@p/"; print "mkdir @p"; mkdir("@p",0777)||die $$! }} exit 0;'
1010 };
1011 }
1012
1013
1014 sub post_constants{
1015     "";
1016 }
1017
1018
1019 # --- Translation Sections ---
1020
1021 sub c_o {
1022     '
1023 .c.o:
1024         $(CCCMD) $(CCCDLFLAGS) -I$(PERL_INC) $(DEFINE) $(INC) $*.c
1025 ';
1026 }
1027
1028 sub xs_c {
1029     '
1030 .xs.c:
1031         $(PERL) $(XSUBPP) $(XSUBPPARGS) $*.xs >xstmp.c && mv xstmp.c $@
1032 ';
1033 }
1034
1035 sub xs_o {      # many makes are too dumb to use xs_c then c_o
1036     '
1037 .xs.o:
1038         $(PERL) $(XSUBPP) $(XSUBPPARGS) $*.xs >xstmp.c && mv xstmp.c $*.c
1039         $(CCCMD) $(CCCDLFLAGS) -I$(PERL_INC) $(DEFINE) $(INC) $*.c
1040 ';
1041 }
1042
1043
1044 # --- Target Sections ---
1045
1046 sub top_targets{
1047     '
1048 all ::  config linkext $(INST_PM)
1049
1050 config :: Makefile
1051         @$(MKPATH) $(INST_LIBDIR)  $(INST_ARCHLIBDIR)
1052         @$(MKPATH) $(INST_AUTODIR) $(INST_ARCHAUTODIR)
1053
1054 install :: all
1055 ';
1056 }
1057
1058 sub linkext {
1059     my($self, %attribs) = @_;
1060     # LINKTYPE => static or dynamic
1061     my($linktype) = $attribs{LINKTYPE} || '$(LINKTYPE)';
1062     "
1063 linkext :: $linktype
1064 ";
1065 }
1066
1067
1068 # --- Dynamic Loading Sections ---
1069
1070 sub dynamic {
1071     '
1072 # $(INST_PM) has been moved to the all: target.
1073 # It remains here for awhile to allow for old usage: "make dynamic"
1074 dynamic :: $(INST_DYNAMIC) $(INST_BOOT) $(INST_PM)
1075 ';
1076 }
1077
1078 sub dynamic_bs {
1079     my($self, %attribs) = @_;
1080     '
1081 BOOTSTRAP = '."$att{BASEEXT}.bs".'
1082
1083 # As MakeMaker mkbootstrap might not write a file (if none is required)
1084 # we use touch to prevent make continually trying to remake it.
1085 # The DynaLoader only reads a non-empty file.
1086 $(BOOTSTRAP): '.$att{BOOTDEP}.' $(CONFIGDEP)
1087         $(PERL) -I$(PERL_LIB) -e \'use ExtUtils::MakeMaker; &mkbootstrap("$(BSLOADLIBS)");\' \
1088                 INST_LIB=$(INST_LIB) INST_ARCHLIB=$(INST_ARCHLIB) PERL_SRC=$(PERL_SRC) NAME=$(NAME)
1089         @touch $(BOOTSTRAP)
1090
1091 $(INST_BOOT): $(BOOTSTRAP)
1092         @rm -f $(INST_BOOT)
1093         cp $(BOOTSTRAP) $(INST_BOOT)
1094 ';
1095 }
1096
1097 sub dynamic_lib {
1098     my($self, %attribs) = @_;
1099     my($otherldflags) = $attribs{OTHERLDFLAGS} || "";
1100     my($armaybe) = $attribs{ARMAYBE} || $att{ARMAYBE} || ":";
1101     '
1102 ARMAYBE = '.$armaybe.'
1103 OTHERLDFLAGS = '.$otherldflags.'
1104
1105 $(INST_DYNAMIC): $(OBJECT) $(MYEXTLIB) $(BOOTSTRAP)
1106         @$(MKPATH) $(INST_AUTODIR)
1107         $(ARMAYBE) cr $(BASEEXT).a $(OBJECT) 
1108         $(LD) $(LDDLFLAGS) -o $@ $(LDTARGET) $(OTHERLDFLAGS) $(MYEXTLIB) $(LDLOADLIBS)
1109 ';
1110 }
1111
1112
1113 # --- Static Loading Sections ---
1114
1115 sub static {
1116     '
1117 # $(INST_PM) has been moved to the all: target.
1118 # It remains here for awhile to allow for old usage: "make static"
1119 static :: $(INST_STATIC) $(INST_PM) 
1120 ';
1121 }
1122
1123 sub static_lib{
1124     my(@m);
1125     push(@m, <<'END');
1126 $(INST_STATIC): $(OBJECT) $(MYEXTLIB)
1127 END
1128     # If this extension has it's own library (eg SDBM_File)
1129     # then copy that to $(INST_STATIC) and add $(OBJECT) into it.
1130     push(@m, '  cp $(MYEXTLIB) $@'."\n") if $att{MYEXTLIB};
1131
1132     push(@m, <<'END');
1133         ar cr $@ $(OBJECT) && $(RANLIB) $@
1134         @: New mechanism - not yet used:
1135         @echo $(EXTRALIBS) > $(INST_ARCHAUTODIR)/extralibs.ld
1136         cp $@ $(INST_ARCHAUTODIR)/
1137 END
1138     push(@m, <<'END') if $att{PERL_SRC};
1139         @: Old mechanism - still needed:
1140         @echo $(EXTRALIBS) >> $(PERL_SRC)/ext.libs
1141 END
1142     join('', "\n",@m);
1143 }
1144
1145
1146 sub installpm {
1147     my($self, %attribs) = @_;
1148     # By default .pm files are split into the architecture independent
1149     # library. This is a good thing. If a specific module requires that
1150     # it's .pm files are split into the architecture specific library
1151     # then it should use: installpm => {SPLITLIB=>'$(INST_ARCHLIB)'}
1152     # Note that installperl currently interferes with this (Config.pm)
1153     # User can disable split by saying: installpm => {SPLITLIB=>''}
1154     my($splitlib) = '$(INST_LIB)'; # NOT arch specific by default
1155     $splitlib = $attribs{SPLITLIB} if exists $attribs{SPLITLIB};
1156     my(@m, $dist);
1157     foreach $dist (sort keys %{$att{PM}}){
1158         my($inst) = $att{PM}->{$dist};
1159         push(@m, "\n# installpm: $dist => $inst, splitlib=$splitlib\n");
1160         push(@m, MY->installpm_x($dist, $inst, $splitlib));
1161         push(@m, "\n");
1162     }
1163     join('', @m);
1164 }
1165
1166 sub installpm_x { # called by installpm per file
1167     my($self, $dist, $inst, $splitlib) = @_;
1168     my($instdir) = $inst =~ m|(.*)/|;
1169     my(@m);
1170     push(@m,"
1171 $inst: $dist
1172 ".'     @rm -f $@
1173         @$(MKPATH) '.$instdir.'
1174         cp $? $@
1175 ');
1176     push(@m, "\t\$(AUTOSPLITFILE) \$@ $splitlib/auto\n")
1177         if ($splitlib and $inst =~ m/\.pm$/);
1178     join('', @m);
1179 }
1180
1181
1182 # --- Sub-directory Sections ---
1183
1184 sub subdirs {
1185     my(@m);
1186     # This method provides a mechanism to automatically deal with
1187     # subdirectories containing further Makefile.PL scripts.
1188     # It calls the subdir_x() method for each subdirectory.
1189     foreach(<*/Makefile.PL>){
1190         s:/Makefile\.PL$:: ;
1191         print "Including $_ subdirectory" if ($Verbose);
1192         push(@m, MY->subdir_x($_));
1193     }
1194     if (@m){
1195         unshift(@m, "
1196 # The default clean, realclean and test targets in this Makefile
1197 # have automatically been given entries for each subdir.
1198
1199 all :: subdirs
1200 ");
1201     } else {
1202         push(@m, "\n# none")
1203     }
1204     join('',@m);
1205 }
1206
1207 sub runsubdirpl{        # Experimental! See subdir_x section
1208     my($self,$subdir) = @_;
1209     chdir($subdir) or die "chdir($subdir): $!";
1210     require "Makefile.PL";
1211 }
1212
1213 sub subdir_x {
1214     my($self, $subdir) = @_;
1215     my(@m);
1216     # The intention is that the calling Makefile.PL should define the
1217     # $(SUBDIR_MAKEFILE_PL_ARGS) make macro to contain whatever
1218     # information needs to be passed down to the other Makefile.PL scripts.
1219     # If this does not suit your needs you'll need to write your own
1220     # MY::subdir_x() method to override this one.
1221     qq{
1222 config :: $subdir/Makefile
1223         cd $subdir ; \$(MAKE) config LINKTYPE=\$(LINKTYPE)
1224
1225 $subdir/Makefile: $subdir/Makefile.PL \$(CONFIGDEP)
1226 }.'     @echo "Rebuilding $@ ..."
1227         $(PERL) -I$(PERL_ARCHLIB) -I$(PERL_LIB) \\
1228                 -e "use ExtUtils::MakeMaker; MM->runsubdirpl(qw('.$subdir.'))" \\
1229                 $(SUBDIR_MAKEFILE_PL_ARGS)
1230         @echo "Rebuild of $@ complete."
1231 '.qq{
1232
1233 subdirs ::
1234         cd $subdir ; \$(MAKE) all LINKTYPE=\$(LINKTYPE)
1235
1236 };
1237 }
1238
1239
1240 # --- Cleanup and Distribution Sections ---
1241
1242 sub clean {
1243     my($self, %attribs) = @_;
1244     my(@m);
1245     push(@m, '
1246 # Delete temporary files but do not touch installed files. We don\'t delete
1247 # the Makefile here so a later make realclean still has a makefile to use.
1248
1249 clean ::
1250 ');
1251     # clean subdirectories first
1252     push(@m, map("\t-cd $_ && test -f Makefile && \$(MAKE) clean\n",@{$att{DIR}}));
1253     push(@m, "  rm -f *~ t/*~ *.o *.a mon.out core so_locations \$(BOOTSTRAP) \$(BASEEXT).bso\n");
1254     my(@otherfiles);
1255     # Automatically delete the .c files generated from *.xs files:
1256     push(@otherfiles, values %{$att{XS}});
1257     push(@otherfiles, $attribs{FILES}) if $attribs{FILES};
1258     push(@m, "  rm -rf @otherfiles\n") if @otherfiles;
1259     push(@m, "  $attribs{POSTOP}\n")   if $attribs{POSTOP};
1260     join("", @m);
1261 }
1262
1263 sub realclean {
1264     my($self, %attribs) = @_;
1265     my(@m);
1266     push(@m,'
1267 # Delete temporary files (via clean) and also delete installed files
1268 realclean purge ::  clean
1269 ');
1270     # clean subdirectories first
1271     push(@m, map("\t-cd $_ && test -f Makefile && \$(MAKE) realclean\n",@{$att{DIR}}));
1272     push(@m, '  rm -f Makefile $(INST_DYNAMIC) $(INST_STATIC) $(INST_BOOT) $(INST_PM)'."\n");
1273     push(@m, '  rm -rf $(INST_AUTODIR) $(INST_ARCHAUTODIR)'."\n");
1274     my(@otherfiles);
1275     push(@otherfiles, $attribs{FILES}) if $attribs{FILES};
1276     push(@m, "  rm -rf @otherfiles\n") if @otherfiles;
1277     push(@m, "  $attribs{POSTOP}\n")       if $attribs{POSTOP};
1278     join("", @m);
1279 }
1280
1281
1282 sub distclean {
1283     my($self, %attribs) = @_;
1284     # VERSION should be sanitised before use as a file name
1285     my($tarname)  = $attribs{TARNAME}  || '$(DISTNAME)-$(VERSION)';
1286     my($tarflags) = $attribs{TARFLAGS} || 'cvf';
1287     my($compress) = $attribs{COMPRESS} || 'compress'; # eg gzip
1288     my($preop)    = $attribs{PREOP}  || '@:'; # e.g., update MANIFEST
1289     my($postop)   = $attribs{POSTOP} || '@:';
1290     my($mkfiles)  = join(' ', map("$_/Makefile", ".", @{$att{DIR}}));
1291     "
1292 distclean:     clean
1293         $preop
1294         rm -f $mkfiles
1295         cd ..; tar $tarflags $tarname.tar \$(BASEEXT)
1296         cd ..; $compress $tarname.tar
1297         $postop
1298 ";
1299 }
1300
1301
1302 # --- Test and Installation Sections ---
1303
1304 sub test {
1305     my($self, %attribs) = @_;
1306     my($tests) = $attribs{TESTS} || (-d "t" ? "t/*.t" : "");
1307     my(@m);
1308     push(@m,"
1309 test :: all
1310 ");
1311     push(@m, <<"END") if $tests;
1312         \$(FULLPERL) -I\$(PERL_ARCHLIB) -I\$(PERL_LIB) -e 'use Test::Harness; runtests \@ARGV;' $tests
1313 END
1314     push(@m, <<'END') if -f "test.pl";
1315         $(FULLPERL) -I$(PERL_ARCHLIB) -I$(PERL_LIB) test.pl
1316 END
1317     push(@m, map("\tcd $_ && test -f Makefile && \$(MAKE) test LINKTYPE=\$(LINKTYPE)\n",@{$att{DIR}}));
1318     push(@m, "\t\@echo 'No tests defined for \$(NAME) extension.'\n") unless @m > 1;
1319     join("", @m);
1320 }
1321
1322
1323 sub install {
1324     '
1325 install :: all
1326         # install is not defined. Makefile, by default, builds the extension
1327         # directly into $(INST_LIB) so "installing" does not make much sense.
1328         # If INST_LIB is in the perl source tree then installperl will install
1329         # the extension when it installs perl.
1330 ';
1331 }
1332
1333
1334 sub force {
1335     '# Phony target to force checking subdirectories.
1336 FORCE:
1337 ';
1338 }
1339
1340
1341 sub perldepend {
1342         my(@m);
1343     push(@m,'
1344 PERL_HDRS = $(PERL_INC)/EXTERN.h $(PERL_INC)/INTERN.h \
1345     $(PERL_INC)/XSUB.h  $(PERL_INC)/av.h        $(PERL_INC)/cop.h \
1346     $(PERL_INC)/cv.h    $(PERL_INC)/dosish.h    $(PERL_INC)/embed.h \
1347     $(PERL_INC)/form.h  $(PERL_INC)/gv.h        $(PERL_INC)/handy.h \
1348     $(PERL_INC)/hv.h    $(PERL_INC)/keywords.h  $(PERL_INC)/mg.h \
1349     $(PERL_INC)/op.h    $(PERL_INC)/opcode.h    $(PERL_INC)/patchlevel.h \
1350     $(PERL_INC)/perl.h  $(PERL_INC)/perly.h     $(PERL_INC)/pp.h \
1351     $(PERL_INC)/proto.h $(PERL_INC)/regcomp.h   $(PERL_INC)/regexp.h \
1352     $(PERL_INC)/scope.h $(PERL_INC)/sv.h        $(PERL_INC)/unixish.h \
1353     $(PERL_INC)/util.h
1354
1355 $(OBJECT) : $(PERL_HDRS)
1356 ');
1357
1358     push(@m,'
1359 $(PERL_INC)/config.h: $(PERL_SRC)/config.sh; cd $(PERL_SRC); /bin/sh config_h.SH
1360 $(PERL_INC)/embed.h:  $(PERL_SRC)/config.sh; cd $(PERL_SRC); /bin/sh embed_h.SH
1361 ') if $att{PERL_SRC};
1362
1363     # This needs a better home:
1364     push(@m, join(" ", values %{$att{XS}})." : \$(XSUBPPDEPS)\n")
1365         if %{$att{XS}};
1366     join("\n",@m);
1367 }
1368
1369
1370 sub makefile {
1371     # We do not know what target was originally specified so we
1372     # must force a manual rerun to be sure. But as it would only
1373     # happen very rarely it is not a significant problem.
1374     '
1375 $(OBJECT) : Makefile
1376
1377 Makefile:       Makefile.PL $(CONFIGDEP)
1378         $(PERL) -I$(PERL_ARCHLIB) -I$(PERL_LIB) Makefile.PL
1379         @echo "Now you must rerun make."; false
1380 ';
1381 }
1382
1383
1384 sub postamble{
1385     "";
1386 }
1387
1388
1389 # --- Determine libraries to use and how to use them ---
1390
1391 sub extliblist{
1392     my($self, $libs) = @_;
1393     return ("", "", "") unless $libs;
1394     print STDERR "Potential libraries are '$libs':" if $Verbose;
1395     my(@new) = MY->new_extliblist($libs);
1396
1397     if ($att{PERL_SRC}){
1398         my(@old) = MY->old_extliblist($libs);
1399         my($oldlibs) = join(" : ",@old);
1400         my($newlibs) = join(" : ",@new);
1401         warn "Warning (non-fatal): $att{NAME} extliblist consistency check failed:\n".
1402             "  old: $oldlibs\n".
1403             "  new: $newlibs\n".
1404             "Using 'new' set. Please notify perl5-porters\@isu.edu.\n"
1405                 if ("$newlibs" ne "$oldlibs");
1406     }
1407     @new;
1408 }
1409
1410
1411 sub old_extliblist {
1412     my($self, $potential_libs)=@_;
1413     return ("", "", "") unless $potential_libs;
1414     die "old_extliblist requires PERL_SRC" unless $att{PERL_SRC};
1415
1416     my(%attrib, @w);
1417     # Now run ext/util/extliblist to discover what *libs definitions
1418     # are required for the needs of $potential_libs
1419     $ENV{'potential_libs'} = $potential_libs;
1420     my(@o)=`. $att{PERL_SRC}/config.sh
1421             . $att{PERL_SRC}/ext/util/extliblist;
1422             echo EXTRALIBS=\$extralibs
1423             echo BSLOADLIBS=\$dynaloadlibs
1424             echo LDLOADLIBS=\$statloadlibs
1425             `;
1426     foreach $line (@o){
1427         chomp $line;
1428         if ($line =~ /(.*)\s*=\s*(.*)\s*$/){
1429             $attrib{$1} = $2;
1430             print STDERR "      $1 = $2" if $Verbose;
1431         }else{
1432             push(@w, $line);
1433         }
1434     }
1435     print STDERR "Messages from extliblist:\n", join("\n",@w,'')
1436        if @w ;
1437     @attrib{qw(EXTRALIBS BSLOADLIBS LDLOADLIBS)};
1438 }
1439
1440
1441 sub new_extliblist {
1442     my($self, $potential_libs)=@_;
1443     return ("", "", "") unless $potential_libs;
1444
1445     my($so)   = $Config{'so'};
1446     my($libs) = $Config{'libs'};
1447
1448     # compute $extralibs, $bsloadlibs and $ldloadlibs from
1449     # $potential_libs
1450     # this is a rewrite of Andy Dougherty's extliblist in perl
1451     # its home is in <distribution>/ext/util
1452
1453     my(@searchpath); # from "-L/path" entries in $potential_libs
1454     my(@libpath) = split " ", $Config{'libpth'};
1455     my(@ldloadlibs);
1456     my(@bsloadlibs);
1457     my(@extralibs);
1458     my($fullname);
1459     my($pwd) = fastcwd(); # from Cwd.pm
1460
1461     foreach $thislib (split ' ', $potential_libs){
1462
1463         # Handle possible linker path arguments.
1464         if ($thislib =~ s/^(-[LR])//){  # save path flag type
1465             my($ptype) = $1;
1466             unless (-d $thislib){
1467                 warn "$ptype$thislib ignored, directory does not exist\n"
1468                         if $Verbose;
1469                 next;
1470             }
1471             if ($thislib !~ m|^/|) {
1472               warn "Warning: $ptype$thislib changed to $ptype$pwd/$thislib\n";
1473               $thislib = "$pwd/$thislib";
1474             }
1475             push(@searchpath, $thislib);
1476             push(@extralibs,  "$ptype$thislib");
1477             push(@ldloadlibs, "$ptype$thislib");
1478             next;
1479         }
1480
1481         # Handle possible library arguments.
1482         unless ($thislib =~ s/^-l//){
1483           warn "Unrecognized argument in LIBS ignored: '$thislib'\n";
1484           next;
1485         }
1486
1487         my($found_lib)=0;
1488         foreach $thispth (@searchpath, @libpath){
1489
1490             if (@fullname=<${thispth}/lib${thislib}.${so}.[0-9]*>){
1491                 $fullname=$fullname[-1]; #ATTN: 10 looses against 9!
1492             } elsif (-f ($fullname="$thispth/lib$thislib.$so")){
1493             } elsif (-f ($fullname="$thispth/lib${thislib}_s.a")
1494                 && ($thislib .= "_s") ){ # we must explicitly ask for _s version
1495             } elsif (-f ($fullname="$thispth/lib$thislib.a")){
1496             } elsif (-f ($fullname="$thispth/Slib$thislib.a")){
1497             } else { 
1498                 warn "$thislib not found in $thispth\n" if $Verbose;
1499                 next;
1500             }
1501             warn "'-l$thislib' found at $fullname\n" if $Verbose;
1502             $found_lib++;
1503
1504             # Now update library lists
1505
1506             # what do we know about this library...
1507             my $is_dyna = ($fullname !~ /\.a$/);
1508             my $in_perl = ($libs =~ /\B-l${thislib}\b/s);
1509
1510             # Do not add it into the list if it is already linked in
1511             # with the main perl executable.
1512             # We have to special-case the NeXT, because all the math is also in libsys_s
1513             unless ( $in_perl || ($Config{'osname'} eq 'next' && $thislib eq 'm') ){
1514                 push(@extralibs, "-l$thislib");
1515             }
1516                         
1517
1518             # We might be able to load this archive file dynamically
1519             if ( $Config{'dlsrc'} =~ /dl_next|dl_dld/){
1520                 # We push -l$thislib instead of $fullname because
1521                 # it avoids hardwiring a fixed path into the .bs file.
1522                 # mkbootstrap will automatically add dl_findfile() to
1523                 # the .bs file if it sees a name in the -l format.
1524                 # USE THIS LATER: push(@bsloadlibs, "-l$thislib"); # " $fullname";
1525                 # USE THIS while checking results against old_extliblist
1526                 push(@bsloadlibs, "$fullname");
1527             } else {
1528                 if ($is_dyna){
1529                     # For SunOS4, do not add in this shared library if
1530                     # it is already linked in the main perl executable
1531                     push(@ldloadlibs, "-l$thislib")
1532                         unless ($in_perl and $Config{'osname'} eq 'sunos');
1533                 } else {
1534                     push(@ldloadlibs, "-l$thislib");
1535                 }
1536             }
1537             last;       # found one here so don't bother looking further
1538         }
1539         warn "Warning (non-fatal): No library found for -l$thislib\n" unless $found_lib>0;
1540     }
1541     ("@extralibs", "@bsloadlibs", "@ldloadlibs");
1542 }
1543
1544
1545 # --- Write a DynaLoader bootstrap file if required
1546
1547 sub mkbootstrap {
1548
1549 =head1 NAME
1550
1551 mkbootstrap
1552
1553 =head1 DESCRIPTION
1554
1555 Make a bootstrap file for use by this system's DynaLoader.
1556 It typically gets called from an extension Makefile.
1557
1558 There is no .bs file supplied with the extension. Instead a _BS file
1559 which has code for the special cases, like posix for berkeley db on the
1560 NeXT.
1561
1562 This file will get parsed, and produce a maybe empty
1563 @DynaLoader::dl_resolve_using array for the current architecture.
1564 That will be extended by $BSLOADLIBS, which was computed by Andy's
1565 extliblist script. If this array still is empty, we do nothing, else
1566 we write a .bs file with an @DynaLoader::dl_resolve_using array, but
1567 without any C<if>s, because there is no longer a need to deal with
1568 special cases.
1569
1570 The _BS file can put some code into the generated .bs file by placing
1571 it in $bscode. This is a handy 'escape' mechanism that may prove
1572 useful in complex situations.
1573
1574 If @DynaLoader::dl_resolve_using contains C<-L*> or C<-l*> entries then
1575 mkbootstrap will automatically add a dl_findfile() call to the
1576 generated .bs file.
1577
1578 =head1 AUTHORS
1579
1580 Andreas Koenig <k@otto.ww.TU-Berlin.DE>, Tim Bunce
1581 <Tim.Bunce@ig.co.uk>, Andy Dougherty <doughera@lafcol.lafayette.edu>
1582
1583 =cut
1584
1585     my($self, @bsloadlibs)=@_;
1586
1587     @bsloadlibs = grep($_, @bsloadlibs); # strip empty libs
1588
1589     print STDERR "      bsloadlibs=@bsloadlibs\n" if $Verbose;
1590
1591     # We need DynaLoader here because we and/or the *_BS file may
1592     # call dl_findfile(). We don't say `use' here because when
1593     # first building perl extensions the DynaLoader will not have
1594     # been built when MakeMaker gets first used.
1595     require DynaLoader;
1596     import DynaLoader;
1597
1598     initialize(@ARGV) unless defined $att{'BASEEXT'};
1599
1600     rename "$att{BASEEXT}.bs", "$att{BASEEXT}.bso";
1601
1602     if (-f "$att{BASEEXT}_BS"){
1603         $_ = "$att{BASEEXT}_BS";
1604         package DynaLoader; # execute code as if in DynaLoader
1605         local($osname, $dlsrc) = (); # avoid warnings
1606         ($osname, $dlsrc) = @Config::Config{qw(osname dlsrc)};
1607         $bscode = "";
1608         unshift @INC, ".";
1609         require $_;
1610         shift @INC;
1611     }
1612
1613     if ($Config{'dlsrc'} =~ /^dl_dld/){
1614         package DynaLoader;
1615         push(@dl_resolve_using, dl_findfile('-lc'));
1616     }
1617
1618     my(@all) = (@bsloadlibs, @DynaLoader::dl_resolve_using);
1619     my($method) = '';
1620     if (@all){
1621         open BS, ">$att{BASEEXT}.bs"
1622                 or die "Unable to open $att{BASEEXT}.bs: $!";
1623         print STDOUT "Writing $att{BASEEXT}.bs\n";
1624         print STDOUT "  containing: @all" if $Verbose;
1625         print BS "# $att{BASEEXT} DynaLoader bootstrap file for $Config{'osname'} architecture.\n";
1626         print BS "# Do not edit this file, changes will be lost.\n";
1627         print BS "# This file was automatically generated by the\n";
1628         print BS "# mkbootstrap routine in ExtUtils/MakeMaker.pm.\n";
1629         print BS "\@DynaLoader::dl_resolve_using = ";
1630         # If @all contains names in the form -lxxx or -Lxxx then it's asking for
1631         # runtime library location so we automatically add a call to dl_findfile()
1632         if (" @all" =~ m/ -[lLR]/){
1633             print BS "  dl_findfile(qw(\n  @all\n  ));\n";
1634         }else{
1635             print BS "  qw(@all);\n";
1636         }
1637         # write extra code if *_BS says so
1638         print BS $DynaLoader::bscode if $DynaLoader::bscode;
1639         print BS "\n1;\n";
1640         close BS;
1641     }
1642
1643     # special handling for systems which needs a list of all global
1644     # symbols exported by a modules to be dynamically linked.
1645     if ($Config{'dlsrc'} =~ /^dl_aix/){
1646        my($bootfunc);
1647        ($bootfunc = $att{NAME}) =~ s/\W/_/g;
1648        open EXP, ">$att{BASEEXT}.exp";
1649        print EXP "#!\nboot_$bootfunc\n";
1650        close EXP;
1651     }
1652 }
1653
1654
1655 # --- Output postprocessing section ---
1656 #nicetext is included to make VMS support easier
1657 sub nicetext { # Just return the input - no action needed
1658     my($self,$text) = @_;
1659     $text;
1660 }
1661  
1662 # the following keeps AutoSplit happy
1663 package ExtUtils::MakeMaker;
1664 1;
1665
1666 __END__
1667