Added Cyg-Win

This commit is contained in:
Frank Harris 2026-06-06 18:46:40 -04:00
parent 82cbc206eb
commit 413c315806
10586 changed files with 3806249 additions and 0 deletions

View file

@ -0,0 +1,298 @@
package ExtUtils::CBuilder;
use File::Spec ();
use File::Path ();
use File::Basename ();
use Perl::OSType qw/os_type/;
use warnings;
use strict;
our $VERSION = '0.280240'; # VERSION
our @ISA;
# We only use this once - don't waste a symbol table entry on it.
# More importantly, don't make it an inheritable method.
my $load = sub {
my $mod = shift;
eval "use $mod";
die $@ if $@;
@ISA = ($mod);
};
{
my @package = split /::/, __PACKAGE__;
my $ostype = os_type();
if (grep {-e File::Spec->catfile($_, @package, 'Platform', $^O) . '.pm'} @INC) {
$load->(__PACKAGE__ . "::Platform::$^O");
} elsif ( $ostype &&
grep {-e File::Spec->catfile($_, @package, 'Platform', $ostype) . '.pm'} @INC) {
$load->(__PACKAGE__ . "::Platform::$ostype");
} else {
$load->(__PACKAGE__ . "::Base");
}
}
1;
__END__
=head1 NAME
ExtUtils::CBuilder - Compile and link C code for Perl modules
=head1 SYNOPSIS
use ExtUtils::CBuilder;
my $b = ExtUtils::CBuilder->new(%options);
$obj_file = $b->compile(source => 'MyModule.c');
$lib_file = $b->link(objects => $obj_file);
=head1 DESCRIPTION
This module can build the C portions of Perl modules by invoking the
appropriate compilers and linkers in a cross-platform manner. It was
motivated by the C<Module::Build> project, but may be useful for other
purposes as well. However, it is I<not> intended as a general
cross-platform interface to all your C building needs. That would
have been a much more ambitious goal!
=head1 METHODS
=over 4
=item new
Returns a new C<ExtUtils::CBuilder> object. A C<config> parameter
lets you override C<Config.pm> settings for all operations performed
by the object, as in the following example:
# Use a different compiler than Config.pm says
my $b = ExtUtils::CBuilder->new( config =>
{ ld => 'gcc' } );
A C<quiet> parameter tells C<CBuilder> to not print its C<system()>
commands before executing them:
# Be quieter than normal
my $b = ExtUtils::CBuilder->new( quiet => 1 );
=item have_compiler
Returns true if the current system has a working C compiler and
linker, false otherwise. To determine this, we actually compile and
link a sample C library. The sample will be compiled in the system
tempdir or, if that fails for some reason, in the current directory.
=item have_cplusplus
Just like have_compiler but for C++ instead of C.
=item compile
Compiles a C source file and produces an object file. The name of the
object file is returned. The source file is specified in a C<source>
parameter, which is required; the other parameters listed below are
optional.
=over 4
=item C<object_file>
Specifies the name of the output file to create. Otherwise the
C<object_file()> method will be consulted, passing it the name of the
C<source> file.
=item C<include_dirs>
Specifies any additional directories in which to search for header
files. May be given as a string indicating a single directory, or as
a list reference indicating multiple directories.
=item C<extra_compiler_flags>
Specifies any additional arguments to pass to the compiler. Should be
given as a list reference containing the arguments individually, or if
this is not possible, as a string containing all the arguments
together.
=item C<C++>
Specifies that the source file is a C++ source file and sets appropriate
compiler flags
=back
The operation of this method is also affected by the
C<archlibexp>, C<cccdlflags>, C<ccflags>, C<optimize>, and C<cc>
entries in C<Config.pm>.
=item link
Invokes the linker to produce a library file from object files. In
scalar context, the name of the library file is returned. In list
context, the library file and any temporary files created are
returned. A required C<objects> parameter contains the name of the
object files to process, either in a string (for one object file) or
list reference (for one or more files). The following parameters are
optional:
=over 4
=item lib_file
Specifies the name of the output library file to create. Otherwise
the C<lib_file()> method will be consulted, passing it the name of
the first entry in C<objects>.
=item module_name
Specifies the name of the Perl module that will be created by linking.
On platforms that need to do prelinking (Win32, OS/2, etc.) this is a
required parameter.
=item extra_linker_flags
Any additional flags you wish to pass to the linker.
=back
On platforms where C<need_prelink()> returns true, C<prelink()>
will be called automatically.
The operation of this method is also affected by the C<lddlflags>,
C<shrpenv>, and C<ld> entries in C<Config.pm>.
=item link_executable
Invokes the linker to produce an executable file from object files. In
scalar context, the name of the executable file is returned. In list
context, the executable file and any temporary files created are
returned. A required C<objects> parameter contains the name of the
object files to process, either in a string (for one object file) or
list reference (for one or more files). The optional parameters are
the same as C<link> with exception for
=over 4
=item exe_file
Specifies the name of the output executable file to create. Otherwise
the C<exe_file()> method will be consulted, passing it the name of the
first entry in C<objects>.
=back
=item object_file
my $object_file = $b->object_file($source_file);
Converts the name of a C source file to the most natural name of an
output object file to create from it. For instance, on Unix the
source file F<foo.c> would result in the object file F<foo.o>.
=item lib_file
my $lib_file = $b->lib_file($object_file);
Converts the name of an object file to the most natural name of a
output library file to create from it. For instance, on Mac OS X the
object file F<foo.o> would result in the library file F<foo.bundle>.
=item exe_file
my $exe_file = $b->exe_file($object_file);
Converts the name of an object file to the most natural name of an
executable file to create from it. For instance, on Mac OS X the
object file F<foo.o> would result in the executable file F<foo>, and
on Windows it would result in F<foo.exe>.
=item prelink
On certain platforms like Win32, OS/2, VMS, and AIX, it is necessary
to perform some actions before invoking the linker. The
C<ExtUtils::Mksymlists> module does this, writing files used by the
linker during the creation of shared libraries for dynamic extensions.
The names of any files written will be returned as a list.
Several parameters correspond to C<ExtUtils::Mksymlists::Mksymlists()>
options, as follows:
Mksymlists() prelink() type
-------------|-------------------|-------------------
NAME | dl_name | string (required)
DLBASE | dl_base | string
FILE | dl_file | string
DL_VARS | dl_vars | array reference
DL_FUNCS | dl_funcs | hash reference
FUNCLIST | dl_func_list | array reference
IMPORTS | dl_imports | hash reference
VERSION | dl_version | string
Please see the documentation for C<ExtUtils::Mksymlists> for the
details of what these parameters do.
=item need_prelink
Returns true on platforms where C<prelink()> should be called
during linking, and false otherwise.
=item extra_link_args_after_prelink
Returns list of extra arguments to give to the link command; the arguments
are the same as for prelink(), with addition of array reference to the
results of prelink(); this reference is indexed by key C<prelink_res>.
=back
=head1 TO DO
Currently this has only been tested on Unix and doesn't contain any of
the Windows-specific code from the C<Module::Build> project. I'll do
that next.
=head1 HISTORY
This module is an outgrowth of the C<Module::Build> project, to which
there have been many contributors. Notably, Randy W. Sims submitted
lots of code to support 3 compilers on Windows and helped with various
other platform-specific issues. Ilya Zakharevich has contributed
fixes for OS/2; John E. Malmberg and Peter Prymmer have done likewise
for VMS.
=head1 SUPPORT
ExtUtils::CBuilder is maintained as part of the Perl 5 core. Please
submit any bug reports via the F<perlbug> tool included with Perl 5.
Bug reports will be included in the Perl 5 ticket system at
L<https://rt.perl.org>.
The Perl 5 source code is available at L<https://perl5.git.perl.org/perl.git>
and ExtUtils-CBuilder may be found in the F<dist/ExtUtils-CBuilder> directory
of the repository.
=head1 AUTHOR
Ken Williams, kwilliams@cpan.org
Additional contributions by The Perl 5 Porters.
=head1 COPYRIGHT
Copyright (c) 2003-2005 Ken Williams. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.
=head1 SEE ALSO
perl(1), Module::Build(3)
=cut

View file

@ -0,0 +1,425 @@
package ExtUtils::CBuilder::Base;
use strict;
use warnings;
use File::Spec;
use File::Basename;
use Cwd ();
use Config;
use Text::ParseWords;
use IPC::Cmd qw(can_run);
use File::Temp qw(tempfile);
our $VERSION = '0.280240'; # VERSION
# More details about C/C++ compilers:
# http://developers.sun.com/sunstudio/documentation/product/compiler.jsp
# http://gcc.gnu.org/
# http://publib.boulder.ibm.com/infocenter/comphelp/v101v121/index.jsp
# http://msdn.microsoft.com/en-us/vstudio/default.aspx
my %cc2cxx = (
# first line order is important to support wrappers like in pkgsrc
cc => [ 'c++', 'CC', 'aCC', 'cxx', ], # Sun Studio, HP ANSI C/C++ Compilers
gcc => [ 'g++' ], # GNU Compiler Collection
xlc => [ 'xlC' ], # IBM C/C++ Set, xlc without thread-safety
xlc_r => [ 'xlC_r' ], # IBM C/C++ Set, xlc with thread-safety
cl => [ 'cl' ], # Microsoft Visual Studio
);
sub new {
my $class = shift;
my $self = bless {@_}, $class;
$self->{properties}{perl} = $class->find_perl_interpreter
or warn "Warning: Can't locate your perl binary";
while (my ($k,$v) = each %Config) {
$self->{config}{$k} = $v unless exists $self->{config}{$k};
}
$self->{config}{cc} = $ENV{CC} if defined $ENV{CC};
$self->{config}{ccflags} = join(" ", $self->{config}{ccflags}, $ENV{CFLAGS})
if defined $ENV{CFLAGS};
$self->{config}{cxx} = $ENV{CXX} if defined $ENV{CXX};
$self->{config}{cxxflags} = $ENV{CXXFLAGS} if defined $ENV{CXXFLAGS};
$self->{config}{ld} = $ENV{LD} if defined $ENV{LD};
$self->{config}{ldflags} = join(" ", $self->{config}{ldflags}, $ENV{LDFLAGS})
if defined $ENV{LDFLAGS};
unless ( exists $self->{config}{cxx} ) {
my ($ccbase, $ccpath, $ccsfx ) = fileparse($self->{config}{cc}, qr/\.[^.]*/);
## If the path is just "cc", fileparse returns $ccpath as "./"
$ccpath = "" if $self->{config}{cc} =~ /^\Q$ccbase$ccsfx\E$/;
foreach my $cxx (@{$cc2cxx{$ccbase}}) {
my $cxx1 = File::Spec->catfile( $ccpath, $cxx . $ccsfx);
if( can_run( $cxx1 ) ) {
$self->{config}{cxx} = $cxx1;
last;
}
my $cxx2 = $cxx . $ccsfx;
if( can_run( $cxx2 ) ) {
$self->{config}{cxx} = $cxx2;
last;
}
if( can_run( $cxx ) ) {
$self->{config}{cxx} = $cxx;
last;
}
}
unless ( exists $self->{config}{cxx} ) {
$self->{config}{cxx} = $self->{config}{cc};
my $cflags = $self->{config}{ccflags};
$self->{config}{cxxflags} = '-x c++';
$self->{config}{cxxflags} .= " $cflags" if defined $cflags;
}
}
return $self;
}
sub find_perl_interpreter {
my $perl;
File::Spec->file_name_is_absolute($perl = $^X)
or -f ($perl = $Config::Config{perlpath})
or ($perl = $^X); # XXX how about using IPC::Cmd::can_run here?
return $perl;
}
sub add_to_cleanup {
my $self = shift;
foreach (@_) {
$self->{files_to_clean}{$_} = 1;
}
}
sub cleanup {
my $self = shift;
foreach my $file (keys %{$self->{files_to_clean}}) {
unlink $file;
}
}
sub get_config {
return %{ $_[0]->{config} };
}
sub object_file {
my ($self, $filename) = @_;
# File name, minus the suffix
(my $file_base = $filename) =~ s/\.[^.]+$//;
return "$file_base$self->{config}{obj_ext}";
}
sub arg_include_dirs {
my $self = shift;
return map {"-I$_"} @_;
}
sub arg_nolink { '-c' }
sub arg_object_file {
my ($self, $file) = @_;
return ('-o', $file);
}
sub arg_share_object_file {
my ($self, $file) = @_;
return ($self->split_like_shell($self->{config}{lddlflags}), '-o', $file);
}
sub arg_exec_file {
my ($self, $file) = @_;
return ('-o', $file);
}
sub arg_defines {
my ($self, %args) = @_;
return map "-D$_=$args{$_}", sort keys %args;
}
sub compile {
my ($self, %args) = @_;
die "Missing 'source' argument to compile()" unless defined $args{source};
my $cf = $self->{config}; # For convenience
my $object_file = $args{object_file}
? $args{object_file}
: $self->object_file($args{source});
my $include_dirs_ref =
(exists($args{include_dirs}) && ref($args{include_dirs}) ne "ARRAY")
? [ $args{include_dirs} ]
: $args{include_dirs};
my @include_dirs = $self->arg_include_dirs(
@{ $include_dirs_ref || [] },
$self->perl_inc(),
);
my @defines = $self->arg_defines( %{$args{defines} || {}} );
my @extra_compiler_flags =
$self->split_like_shell($args{extra_compiler_flags});
my @cccdlflags = $self->split_like_shell($cf->{cccdlflags});
my @ccflags = $self->split_like_shell($args{'C++'} ? $cf->{cxxflags} : $cf->{ccflags});
my @optimize = $self->split_like_shell($cf->{optimize});
my @flags = (
@include_dirs,
@defines,
@cccdlflags,
@extra_compiler_flags,
$self->arg_nolink,
@ccflags,
@optimize,
$self->arg_object_file($object_file),
);
my @cc = $self->split_like_shell($args{'C++'} ? $cf->{cxx} : $cf->{cc});
$self->do_system(@cc, @flags, $args{source})
or die "error building $object_file from '$args{source}'";
return $object_file;
}
sub have_compiler {
my ($self, $is_cplusplus) = @_;
my $have_compiler_flag = $is_cplusplus ? "have_cxx" : "have_cc";
my $suffix = $is_cplusplus ? ".cc" : ".c";
return $self->{$have_compiler_flag} if defined $self->{$have_compiler_flag};
my $result;
my $attempts = 3;
# tmpdir has issues for some people so fall back to current dir
# don't clobber existing files (rare, but possible)
my ( $FH, $tmpfile ) = tempfile( "compilet-XXXXX", SUFFIX => $suffix );
binmode $FH;
if ( $is_cplusplus ) {
print $FH q<namespace Bogus { extern "C" int boot_compilet() { return 1; } };> . "\n";
}
else {
# Use extern "C" if "cc" was set to a C++ compiler.
print $FH <<EOF;
#ifdef __cplusplus
extern "C"
#endif
int boot_compilet(void) { return 1; }
EOF
}
close $FH;
my ($obj_file, @lib_files);
eval {
local $^W = 0;
local $self->{quiet} = 1;
$obj_file = $self->compile('C++' => $is_cplusplus, source => $tmpfile);
@lib_files = $self->link(objects => $obj_file, module_name => 'compilet');
};
$result = $@ ? 0 : 1;
foreach (grep defined, $tmpfile, $obj_file, @lib_files) {
1 while unlink;
}
return $self->{$have_compiler_flag} = $result;
}
sub have_cplusplus {
push @_, 1;
goto &have_compiler;
}
sub lib_file {
my ($self, $dl_file, %args) = @_;
$dl_file =~ s/\.[^.]+$//;
$dl_file =~ tr/"//d;
if (defined $args{module_name} and length $args{module_name}) {
# Need to create with the same name as DynaLoader will load with.
require DynaLoader;
if (defined &DynaLoader::mod2fname) {
my $lib = DynaLoader::mod2fname([split /::/, $args{module_name}]);
my ($dev, $lib_dir, undef) = File::Spec->splitpath($dl_file);
$dl_file = File::Spec->catpath($dev, $lib_dir, $lib);
}
}
$dl_file .= ".$self->{config}{dlext}";
return $dl_file;
}
sub exe_file {
my ($self, $dl_file) = @_;
$dl_file =~ s/\.[^.]+$//;
$dl_file =~ tr/"//d;
return "$dl_file$self->{config}{_exe}";
}
sub need_prelink { 0 }
sub extra_link_args_after_prelink { return }
sub prelink {
my ($self, %args) = @_;
my ($dl_file_out, $mksymlists_args) = _prepare_mksymlists_args(\%args);
require ExtUtils::Mksymlists;
# dl. abbrev for dynamic library
ExtUtils::Mksymlists::Mksymlists( %{ $mksymlists_args } );
# Mksymlists will create one of these files
return grep -e, map "$dl_file_out.$_", qw(ext def opt);
}
sub _prepare_mksymlists_args {
my $args = shift;
($args->{dl_file} = $args->{dl_name}) =~ s/.*::// unless $args->{dl_file};
my %mksymlists_args = (
DL_VARS => $args->{dl_vars} || [],
DL_FUNCS => $args->{dl_funcs} || {},
FUNCLIST => $args->{dl_func_list} || [],
IMPORTS => $args->{dl_imports} || {},
NAME => $args->{dl_name}, # Name of the Perl module
DLBASE => $args->{dl_base}, # Basename of DLL file
FILE => $args->{dl_file}, # Dir + Basename of symlist file
VERSION => (defined $args->{dl_version} ? $args->{dl_version} : '0.0'),
);
return ($args->{dl_file}, \%mksymlists_args);
}
sub link {
my ($self, %args) = @_;
return $self->_do_link('lib_file', lddl => 1, %args);
}
sub link_executable {
my ($self, %args) = @_;
return $self->_do_link('exe_file', lddl => 0, %args);
}
sub _do_link {
my ($self, $type, %args) = @_;
my $cf = $self->{config}; # For convenience
my $objects = delete $args{objects};
$objects = [$objects] unless ref $objects;
my $out = $args{$type} || $self->$type($objects->[0], %args);
my @temp_files;
@temp_files =
$self->prelink(%args, dl_name => $args{module_name})
if $args{lddl} && $self->need_prelink;
my @linker_flags = (
$self->split_like_shell($args{extra_linker_flags}),
$self->extra_link_args_after_prelink(
%args, dl_name => $args{module_name}, prelink_res => \@temp_files
)
);
my @output = $args{lddl}
? $self->arg_share_object_file($out)
: $self->arg_exec_file($out);
my @shrp = $self->split_like_shell($cf->{shrpenv});
my @ld = $self->split_like_shell($cf->{ld});
$self->do_system(@shrp, @ld, @output, @$objects, @linker_flags)
or die "error building $out from @$objects";
return wantarray ? ($out, @temp_files) : $out;
}
sub quote_literal {
my ($self, $string) = @_;
if (length $string && $string !~ /[^a-zA-Z0-9,._+@%\/-]/) {
return $string;
}
$string =~ s{'}{'\\''}g;
return "'$string'";
}
sub do_system {
my ($self, @cmd) = @_;
if (!$self->{quiet}) {
my $full = join ' ', map $self->quote_literal($_), @cmd;
print $full . "\n";
}
return !system(@cmd);
}
sub split_like_shell {
my ($self, $string) = @_;
return () unless defined($string);
return @$string if UNIVERSAL::isa($string, 'ARRAY');
$string =~ s/^\s+|\s+$//g;
return () unless length($string);
# Text::ParseWords replaces all 'escaped' characters with themselves, which completely
# breaks paths under windows. As such, we forcibly replace backwards slashes with forward
# slashes on windows.
$string =~ s@\\@/@g if $^O eq 'MSWin32';
return Text::ParseWords::shellwords($string);
}
# if building perl, perl's main source directory
sub perl_src {
# N.B. makemaker actually searches regardless of PERL_CORE, but
# only squawks at not finding it if PERL_CORE is set
return unless $ENV{PERL_CORE};
my $Updir = File::Spec->updir;
my $dir = File::Spec->curdir;
# Try up to 5 levels upwards
for (0..10) {
if (
-f File::Spec->catfile($dir,"config_h.SH")
&&
-f File::Spec->catfile($dir,"perl.h")
&&
-f File::Spec->catfile($dir,"lib","Exporter.pm")
) {
return Cwd::realpath( $dir );
}
$dir = File::Spec->catdir($dir, $Updir);
}
warn "PERL_CORE is set but I can't find your perl source!\n";
return ''; # return empty string if $ENV{PERL_CORE} but can't find dir ???
}
# directory of perl's include files
sub perl_inc {
my $self = shift;
$self->perl_src() || File::Spec->catdir($self->{config}{archlibexp},"CORE");
}
sub DESTROY {
my $self = shift;
local($., $@, $!, $^E, $?);
$self->cleanup();
}
1;
# vim: ts=2 sw=2 et:

View file

@ -0,0 +1,40 @@
package ExtUtils::CBuilder::Platform::Unix;
use warnings;
use strict;
use ExtUtils::CBuilder::Base;
our $VERSION = '0.280240'; # VERSION
our @ISA = qw(ExtUtils::CBuilder::Base);
sub link_executable {
my $self = shift;
# On some platforms (which ones??) $Config{cc} seems to be a better
# bet for linking executables than $Config{ld}. Cygwin is a notable
# exception.
local $self->{config}{ld} =
$self->{config}{cc} . " " . $self->{config}{ldflags};
return $self->SUPER::link_executable(@_);
}
sub link {
my $self = shift;
my $cf = $self->{config};
# Some platforms (notably Mac OS X 10.3, but some others too) expect
# the syntax "FOO=BAR /bin/command arg arg" to work in %Config
# (notably $Config{ld}). It usually works in system(SCALAR), but we
# use system(LIST). We fix it up here with 'env'.
local $cf->{ld} = $cf->{ld};
if (ref $cf->{ld}) {
unshift @{$cf->{ld}}, 'env' if $cf->{ld}[0] =~ /^\s*\w+=/;
} else {
$cf->{ld} =~ s/^(\s*\w+=)/env $1/;
}
return $self->SUPER::link(@_);
}
1;

View file

@ -0,0 +1,290 @@
package ExtUtils::CBuilder::Platform::VMS;
use warnings;
use strict;
use ExtUtils::CBuilder::Base;
our $VERSION = '0.280240'; # VERSION
our @ISA = qw(ExtUtils::CBuilder::Base);
use File::Spec::Functions qw(catfile catdir);
use Config;
# We do prelink, but don't want the parent to redo it.
sub need_prelink { 0 }
sub arg_defines {
my ($self, %args) = @_;
s/"/""/g foreach values %args;
my @config_defines;
# VMS can only have one define qualifier; add the one from config, if any.
if ($self->{config}{ccflags} =~ s{/ def[^=]+ =+ \(? ([^\/\)]*) } {}ix) {
push @config_defines, $1;
}
return '' unless keys(%args) || @config_defines;
return ('/define=('
. join(',',
@config_defines,
map "\"$_" . ( length($args{$_}) ? "=$args{$_}" : '') . "\"",
sort keys %args)
. ')');
}
sub arg_include_dirs {
my ($self, @dirs) = @_;
# VMS can only have one include list, add the one from config.
if ($self->{config}{ccflags} =~ s{/inc[^=]+(?:=)+(?:\()?([^\/\)]*)} {}i) {
unshift @dirs, $1;
}
return unless @dirs;
return ('/include=(' . join(',', @dirs) . ')');
}
# We override the compile method because we consume the includes and defines
# parts of ccflags in the process of compiling but don't save those parts
# anywhere, so $self->{config}{ccflags} needs to be reset for each compile
# operation.
sub compile {
my ($self, %args) = @_;
$self->{config}{ccflags} = $Config{ccflags};
$self->{config}{ccflags} = $ENV{CFLAGS} if defined $ENV{CFLAGS};
return $self->SUPER::compile(%args);
}
sub _do_link {
my ($self, $type, %args) = @_;
my $objects = delete $args{objects};
$objects = [$objects] unless ref $objects;
if ($args{lddl}) {
# prelink will call Mksymlists, which creates the extension-specific
# linker options file and populates it with the boot symbol.
my @temp_files = $self->prelink(%args, dl_name => $args{module_name});
# We now add the rest of what we need to the linker options file. We
# should replicate the functionality of C<ExtUtils::MM_VMS::dlsyms>,
# but there is as yet no infrastructure for handling object libraries,
# so for now we depend on object files being listed individually on the
# command line, which should work for simple cases. We do bring in our
# own version of C<ExtUtils::Liblist::Kid::ext> so that any additional
# libraries (including PERLSHR) can be added to the options file.
my @optlibs = $self->_liblist_ext( $args{'libs'} );
my $optfile = 'sys$disk:[]' . $temp_files[0];
open my $opt_fh, '>>', $optfile
or die "_do_link: Unable to open $optfile: $!";
for my $lib (@optlibs) {print $opt_fh "$lib\n" if length $lib }
close $opt_fh;
$objects->[-1] .= ',';
push @$objects, $optfile . '/OPTIONS,';
# This one not needed for DEC C, but leave for completeness.
push @$objects, $self->perl_inc() . 'perlshr_attr.opt/OPTIONS';
}
return $self->SUPER::_do_link($type, %args, objects => $objects);
}
sub arg_nolink { return; }
sub arg_object_file {
my ($self, $file) = @_;
return "/obj=$file";
}
sub arg_exec_file {
my ($self, $file) = @_;
return ("/exe=$file");
}
sub arg_share_object_file {
my ($self, $file) = @_;
return ("$self->{config}{lddlflags}=$file");
}
# The following is reproduced almost verbatim from ExtUtils::Liblist::Kid::_vms_ext.
# We can't just call that because it's tied up with the MakeMaker object hierarchy.
sub _liblist_ext {
my($self, $potential_libs,$verbose,$give_libs) = @_;
$verbose ||= 0;
my(@crtls,$crtlstr);
@crtls = ( ($self->{'config'}{'ldflags'} =~ m-/Debug-i ? $self->{'config'}{'dbgprefix'} : '')
. 'PerlShr/Share' );
push(@crtls, grep { not /\(/ } split /\s+/, $self->{'config'}{'perllibs'});
push(@crtls, grep { not /\(/ } split /\s+/, $self->{'config'}{'libc'});
# In general, we pass through the basic libraries from %Config unchanged.
# The one exception is that if we're building in the Perl source tree, and
# a library spec could be resolved via a logical name, we go to some trouble
# to ensure that the copy in the local tree is used, rather than one to
# which a system-wide logical may point.
if ($self->perl_src) {
my($lib,$locspec,$type);
foreach $lib (@crtls) {
if (($locspec,$type) = $lib =~ m{^([\w\$-]+)(/\w+)?} and $locspec =~ /perl/i) {
if (lc $type eq '/share') { $locspec .= $self->{'config'}{'exe_ext'}; }
elsif (lc $type eq '/library') { $locspec .= $self->{'config'}{'lib_ext'}; }
else { $locspec .= $self->{'config'}{'obj_ext'}; }
$locspec = catfile($self->perl_src, $locspec);
$lib = "$locspec$type" if -e $locspec;
}
}
}
$crtlstr = @crtls ? join(' ',@crtls) : '';
unless ($potential_libs) {
warn "Result:\n\tEXTRALIBS: \n\tLDLOADLIBS: $crtlstr\n" if $verbose;
return ('', '', $crtlstr, '', ($give_libs ? [] : ()));
}
my(@dirs,@libs,$dir,$lib,%found,@fndlibs,$ldlib);
my $cwd = cwd();
my($so,$lib_ext,$obj_ext) = @{$self->{'config'}}{'so','lib_ext','obj_ext'};
# List of common Unix library names and their VMS equivalents
# (VMS equivalent of '' indicates that the library is automatically
# searched by the linker, and should be skipped here.)
my(@flibs, %libs_seen);
my %libmap = ( 'm' => '', 'f77' => '', 'F77' => '', 'V77' => '', 'c' => '',
'malloc' => '', 'crypt' => '', 'resolv' => '', 'c_s' => '',
'socket' => '', 'X11' => 'DECW$XLIBSHR',
'Xt' => 'DECW$XTSHR', 'Xm' => 'DECW$XMLIBSHR',
'Xmu' => 'DECW$XMULIBSHR');
warn "Potential libraries are '$potential_libs'\n" if $verbose;
# First, sort out directories and library names in the input
foreach $lib (split ' ',$potential_libs) {
push(@dirs,$1), next if $lib =~ /^-L(.*)/;
push(@dirs,$lib), next if $lib =~ /[:>\]]$/;
push(@dirs,$lib), next if -d $lib;
push(@libs,$1), next if $lib =~ /^-l(.*)/;
push(@libs,$lib);
}
push(@dirs,split(' ',$self->{'config'}{'libpth'}));
# Now make sure we've got VMS-syntax absolute directory specs
# (We don't, however, check whether someone's hidden a relative
# path in a logical name.)
foreach $dir (@dirs) {
unless (-d $dir) {
warn "Skipping nonexistent Directory $dir\n" if $verbose > 1;
$dir = '';
next;
}
warn "Resolving directory $dir\n" if $verbose;
if (!File::Spec->file_name_is_absolute($dir)) {
$dir = catdir($cwd,$dir);
}
}
@dirs = grep { length($_) } @dirs;
unshift(@dirs,''); # Check each $lib without additions first
LIB: foreach $lib (@libs) {
if (exists $libmap{$lib}) {
next unless length $libmap{$lib};
$lib = $libmap{$lib};
}
my(@variants,$variant,$cand);
my($ctype) = '';
# If we don't have a file type, consider it a possibly abbreviated name and
# check for common variants. We try these first to grab libraries before
# a like-named executable image (e.g. -lperl resolves to perlshr.exe
# before perl.exe).
if ($lib !~ /\.[^:>\]]*$/) {
push(@variants,"${lib}shr","${lib}rtl","${lib}lib");
push(@variants,"lib$lib") if $lib !~ /[:>\]]/;
}
push(@variants,$lib);
warn "Looking for $lib\n" if $verbose;
foreach $variant (@variants) {
my($fullname, $name);
foreach $dir (@dirs) {
my($type);
$name = "$dir$variant";
warn "\tChecking $name\n" if $verbose > 2;
$fullname = VMS::Filespec::rmsexpand($name);
if (defined $fullname and -f $fullname) {
# It's got its own suffix, so we'll have to figure out the type
if ($fullname =~ /(?:$so|exe)$/i) { $type = 'SHR'; }
elsif ($fullname =~ /(?:$lib_ext|olb)$/i) { $type = 'OLB'; }
elsif ($fullname =~ /(?:$obj_ext|obj)$/i) {
warn "Note (probably harmless): "
."Plain object file $fullname found in library list\n";
$type = 'OBJ';
}
else {
warn "Note (probably harmless): "
."Unknown library type for $fullname; assuming shared\n";
$type = 'SHR';
}
}
elsif (-f ($fullname = VMS::Filespec::rmsexpand($name,$so)) or
-f ($fullname = VMS::Filespec::rmsexpand($name,'.exe'))) {
$type = 'SHR';
$name = $fullname unless $fullname =~ /exe;?\d*$/i;
}
elsif (not length($ctype) and # If we've got a lib already,
# don't bother
( -f ($fullname = VMS::Filespec::rmsexpand($name,$lib_ext)) or
-f ($fullname = VMS::Filespec::rmsexpand($name,'.olb')))) {
$type = 'OLB';
$name = $fullname unless $fullname =~ /olb;?\d*$/i;
}
elsif (not length($ctype) and # If we've got a lib already,
# don't bother
( -f ($fullname = VMS::Filespec::rmsexpand($name,$obj_ext)) or
-f ($fullname = VMS::Filespec::rmsexpand($name,'.obj')))) {
warn "Note (probably harmless): "
."Plain object file $fullname found in library list\n";
$type = 'OBJ';
$name = $fullname unless $fullname =~ /obj;?\d*$/i;
}
if (defined $type) {
$ctype = $type; $cand = $name;
last if $ctype eq 'SHR';
}
}
if ($ctype) {
push @{$found{$ctype}}, $cand;
warn "\tFound as $cand (really $fullname), type $ctype\n"
if $verbose > 1;
push @flibs, $name unless $libs_seen{$fullname}++;
next LIB;
}
}
warn "Note (probably harmless): "
."No library found for $lib\n";
}
push @fndlibs, @{$found{OBJ}} if exists $found{OBJ};
push @fndlibs, map { "$_/Library" } @{$found{OLB}} if exists $found{OLB};
push @fndlibs, map { "$_/Share" } @{$found{SHR}} if exists $found{SHR};
$lib = join(' ',@fndlibs);
$ldlib = $crtlstr ? "$lib $crtlstr" : $lib;
warn "Result:\n\tEXTRALIBS: $lib\n\tLDLOADLIBS: $ldlib\n" if $verbose;
wantarray ? ($lib, '', $ldlib, '', ($give_libs ? \@flibs : ())) : $lib;
}
1;

View file

@ -0,0 +1,310 @@
package ExtUtils::CBuilder::Platform::Windows;
use strict;
use warnings;
use File::Basename;
use File::Spec;
use ExtUtils::CBuilder::Base;
use IO::File;
our $VERSION = '0.280240'; # VERSION
our @ISA = qw(ExtUtils::CBuilder::Base);
=begin comment
The compiler-specific packages implement functions for generating properly
formatted commandlines for the compiler being used. Each package
defines two primary functions 'format_linker_cmd()' &
'format_compiler_cmd()' that accepts a list of named arguments (a
hash) and returns a list of formatted options suitable for invoking the
compiler. By default, if the compiler supports scripting of its
operation then a script file is built containing the options while
those options are removed from the commandline, and a reference to the
script is pushed onto the commandline in their place. Scripting the
compiler in this way helps to avoid the problems associated with long
commandlines under some shells.
=end comment
=cut
sub new {
my $class = shift;
my $self = $class->SUPER::new(@_);
my $cf = $self->{config};
# Inherit from an appropriate compiler driver class
my $driver = "ExtUtils::CBuilder::Platform::Windows::" . $self->_compiler_type;
eval "require $driver" or die "Could not load compiler driver: $@";
unshift @ISA, $driver;
return $self;
}
sub _compiler_type {
my $self = shift;
my $cc = $self->{config}{cc};
return ( $cc =~ /cl(\.exe)?$/ ? 'MSVC'
: $cc =~ /bcc32(\.exe)?$/ ? 'BCC'
: 'GCC');
}
# native quoting, not shell quoting
sub quote_literal {
my ($self, $string) = @_;
# some of these characters don't need to be quoted for "native" quoting, but
# quote them anyway so they are more likely to make it through cmd.exe
if (length $string && $string !~ /[ \t\n\x0b"|<>%]/) {
return $string;
}
$string =~ s{(\\*)(?="|\z)}{$1$1}g;
$string =~ s{"}{\\"}g;
return qq{"$string"};
}
sub split_like_shell {
# Since Windows will pass the whole command string (not an argument
# array) to the target program and make the program parse it itself,
# we don't actually need to do any processing here.
(my $self, local $_) = @_;
return @$_ if defined() && UNIVERSAL::isa($_, 'ARRAY');
return unless defined() && length();
return ($_);
}
sub do_system {
# See above
my $self = shift;
my $cmd = join ' ',
grep length,
map {$a=$_;$a=~s/\t/ /g;$a=~s/^\s+|\s+$//;$a}
grep defined, @_;
if (!$self->{quiet}) {
print $cmd . "\n";
}
local $self->{quiet} = 1;
return $self->SUPER::do_system($cmd);
}
sub arg_defines {
my ($self, %args) = @_;
s/"/\\"/g foreach values %args;
return map qq{"-D$_=$args{$_}"}, sort keys %args;
}
sub compile {
my ($self, %args) = @_;
my $cf = $self->{config};
die "Missing 'source' argument to compile()" unless defined $args{source};
$args{include_dirs} = [ $args{include_dirs} ]
if exists($args{include_dirs}) && ref($args{include_dirs}) ne "ARRAY";
my ($basename, $srcdir) =
( File::Basename::fileparse($args{source}, '\.[^.]+$') )[0,1];
$srcdir ||= File::Spec->curdir();
my @defines = $self->arg_defines( %{ $args{defines} || {} } );
my %spec = (
srcdir => $srcdir,
builddir => $srcdir,
basename => $basename,
source => $args{source},
output => $args{object_file} || File::Spec->catfile($srcdir, $basename) . $cf->{obj_ext},
cc => $cf->{cc},
cflags => [
$self->split_like_shell($cf->{ccflags}),
$self->split_like_shell($cf->{cccdlflags}),
$self->split_like_shell($args{extra_compiler_flags}),
],
optimize => [ $self->split_like_shell($cf->{optimize}) ],
defines => \@defines,
includes => [ @{$args{include_dirs} || []} ],
perlinc => [
$self->perl_inc(),
$self->split_like_shell($cf->{incpath}),
],
use_scripts => 1, # XXX provide user option to change this???
);
$self->normalize_filespecs(
\$spec{source},
\$spec{output},
$spec{includes},
$spec{perlinc},
);
my @cmds = $self->format_compiler_cmd(%spec);
while ( my $cmd = shift @cmds ) {
$self->do_system( @$cmd )
or die "error building $cf->{dlext} file from '$args{source}'";
}
(my $out = $spec{output}) =~ tr/'"//d;
return $out;
}
sub need_prelink { 1 }
sub link {
my ($self, %args) = @_;
my $cf = $self->{config};
my @objects = ( ref $args{objects} eq 'ARRAY' ? @{$args{objects}} : $args{objects} );
my $to = join '', (File::Spec->splitpath($objects[0]))[0,1];
$to ||= File::Spec->curdir();
(my $file_base = $args{module_name}) =~ s/.*:://;
my $output = $args{lib_file} ||
File::Spec->catfile($to, "$file_base.$cf->{dlext}");
# if running in perl source tree, look for libs there, not installed
my $lddlflags = $cf->{lddlflags};
my $perl_src = $self->perl_src();
$lddlflags =~ s{\Q$cf->{archlibexp}\E[\\/]CORE}{$perl_src/lib/CORE} if $perl_src;
my %spec = (
srcdir => $to,
builddir => $to,
startup => [ ],
objects => \@objects,
libs => [ ],
output => $output,
ld => $cf->{ld},
libperl => $cf->{libperl},
perllibs => [ $self->split_like_shell($cf->{perllibs}) ],
libpath => [ $self->split_like_shell($cf->{libpth}) ],
lddlflags => [ $self->split_like_shell($lddlflags) ],
other_ldflags => [ $self->split_like_shell($args{extra_linker_flags} || '') ],
use_scripts => 1, # XXX provide user option to change this???
);
unless ( $spec{basename} ) {
($spec{basename} = $args{module_name}) =~ s/.*:://;
}
$spec{srcdir} = File::Spec->canonpath( $spec{srcdir} );
$spec{builddir} = File::Spec->canonpath( $spec{builddir} );
$spec{output} ||= File::Spec->catfile( $spec{builddir},
$spec{basename} . '.'.$cf->{dlext} );
$spec{manifest} ||= $spec{output} . '.manifest';
$spec{implib} ||= File::Spec->catfile( $spec{builddir},
$spec{basename} . $cf->{lib_ext} );
$spec{explib} ||= File::Spec->catfile( $spec{builddir},
$spec{basename} . '.exp' );
if ($cf->{cc} eq 'cl') {
$spec{dbg_file} ||= File::Spec->catfile( $spec{builddir},
$spec{basename} . '.pdb' );
}
elsif ($cf->{cc} eq 'bcc32') {
$spec{dbg_file} ||= File::Spec->catfile( $spec{builddir},
$spec{basename} . '.tds' );
}
$spec{def_file} ||= File::Spec->catfile( $spec{srcdir} ,
$spec{basename} . '.def' );
$spec{base_file} ||= File::Spec->catfile( $spec{srcdir} ,
$spec{basename} . '.base' );
$self->add_to_cleanup(
grep defined,
@{[ @spec{qw(manifest implib explib dbg_file def_file base_file map_file)} ]}
);
foreach my $opt ( qw(output manifest implib explib dbg_file def_file map_file base_file) ) {
$self->normalize_filespecs( \$spec{$opt} );
}
foreach my $opt ( qw(libpath startup objects) ) {
$self->normalize_filespecs( $spec{$opt} );
}
(my $def_base = $spec{def_file}) =~ tr/'"//d;
$def_base =~ s/\.def$//;
$self->prelink( %args,
dl_name => $args{module_name},
dl_file => $def_base,
dl_base => $spec{basename} );
my @cmds = $self->format_linker_cmd(%spec);
while ( my $cmd = shift @cmds ) {
$self->do_system( @$cmd ) or die "error building $output from @objects"
}
$spec{output} =~ tr/'"//d;
return wantarray
? grep defined, @spec{qw[output manifest implib explib dbg_file def_file map_file base_file]}
: $spec{output};
}
# canonize & quote paths
sub normalize_filespecs {
my ($self, @specs) = @_;
foreach my $spec ( grep defined, @specs ) {
if ( ref $spec eq 'ARRAY') {
$self->normalize_filespecs( map {\$_} grep defined, @$spec )
} elsif ( ref $spec eq 'SCALAR' ) {
$$spec =~ tr/"//d if $$spec;
next unless $$spec;
$$spec = '"' . File::Spec->canonpath($$spec) . '"';
} elsif ( ref $spec eq '' ) {
$spec = '"' . File::Spec->canonpath($spec) . '"';
} else {
die "Don't know how to normalize " . (ref $spec || $spec) . "\n";
}
}
}
# directory of perl's include files
sub perl_inc {
my $self = shift;
my $perl_src = $self->perl_src();
if ($perl_src) {
File::Spec->catdir($perl_src, "lib", "CORE");
} else {
File::Spec->catdir($self->{config}{archlibexp},"CORE");
}
}
1;
__END__
=head1 NAME
ExtUtils::CBuilder::Platform::Windows - Builder class for Windows platforms
=head1 DESCRIPTION
This module implements the Windows-specific parts of ExtUtils::CBuilder.
Most of the Windows-specific stuff has to do with compiling and
linking C code. Currently we support the 3 compilers perl itself
supports: MSVC, BCC, and GCC.
This module inherits from C<ExtUtils::CBuilder::Base>, so any functionality
not implemented here will be implemented there. The interfaces are
defined by the L<ExtUtils::CBuilder> documentation.
=head1 AUTHOR
Ken Williams <ken@mathforum.org>
Most of the code here was written by Randy W. Sims <RandyS@ThePierianSpring.org>.
=head1 SEE ALSO
perl(1), ExtUtils::CBuilder(3), ExtUtils::MakeMaker(3)
=cut

View file

@ -0,0 +1,132 @@
package ExtUtils::CBuilder::Platform::Windows::BCC;
our $VERSION = '0.280240'; # VERSION
use strict;
use warnings;
sub format_compiler_cmd {
my ($self, %spec) = @_;
foreach my $path ( @{ $spec{includes} || [] },
@{ $spec{perlinc} || [] } ) {
$path = '-I' . $path;
}
%spec = $self->write_compiler_script(%spec)
if $spec{use_scripts};
return [ grep {defined && length} (
$spec{cc}, '-c' ,
@{$spec{includes}} ,
@{$spec{cflags}} ,
@{$spec{optimize}} ,
@{$spec{defines}} ,
@{$spec{perlinc}} ,
"-o$spec{output}" ,
$spec{source} ,
) ];
}
sub write_compiler_script {
my ($self, %spec) = @_;
my $script = File::Spec->catfile( $spec{srcdir},
$spec{basename} . '.ccs' );
$self->add_to_cleanup($script);
print "Generating script '$script'\n" if !$self->{quiet};
my $SCRIPT = IO::File->new( ">$script" )
or die( "Could not create script '$script': $!" );
# XXX Borland "response files" seem to be unable to accept macro
# definitions containing quoted strings. Escaping strings with
# backslash doesn't work, and any level of quotes are stripped. The
# result is a floating point number in the source file where a
# string is expected. So we leave the macros on the command line.
print $SCRIPT join( "\n",
map { ref $_ ? @{$_} : $_ }
grep defined,
delete(
@spec{ qw(includes cflags optimize perlinc) } )
);
push @{$spec{includes}}, '@"' . $script . '"';
return %spec;
}
sub format_linker_cmd {
my ($self, %spec) = @_;
foreach my $path ( @{$spec{libpath}} ) {
$path = "-L$path";
}
push( @{$spec{startup}}, 'c0d32.obj' )
unless ( $spec{startup} && @{$spec{startup}} );
%spec = $self->write_linker_script(%spec)
if $spec{use_scripts};
return [ grep {defined && length} (
$spec{ld} ,
@{$spec{lddlflags}} ,
@{$spec{libpath}} ,
@{$spec{other_ldflags}} ,
@{$spec{startup}} ,
@{$spec{objects}} , ',',
$spec{output} , ',',
$spec{map_file} , ',',
$spec{libperl} ,
@{$spec{perllibs}} , ',',
$spec{def_file}
) ];
}
sub write_linker_script {
my ($self, %spec) = @_;
# To work around Borlands "unique" commandline syntax,
# two scripts are used:
my $ld_script = File::Spec->catfile( $spec{srcdir},
$spec{basename} . '.lds' );
my $ld_libs = File::Spec->catfile( $spec{srcdir},
$spec{basename} . '.lbs' );
$self->add_to_cleanup($ld_script, $ld_libs);
print "Generating scripts '$ld_script' and '$ld_libs'.\n" if !$self->{quiet};
# Script 1: contains options & names of object files.
my $LD_SCRIPT = IO::File->new( ">$ld_script" )
or die( "Could not create linker script '$ld_script': $!" );
print $LD_SCRIPT join( " +\n",
map { @{$_} }
grep defined,
delete(
@spec{ qw(lddlflags libpath other_ldflags startup objects) } )
);
# Script 2: contains name of libs to link against.
my $LD_LIBS = IO::File->new( ">$ld_libs" )
or die( "Could not create linker script '$ld_libs': $!" );
print $LD_LIBS join( " +\n",
(delete $spec{libperl} || ''),
@{delete $spec{perllibs} || []},
);
push @{$spec{lddlflags}}, '@"' . $ld_script . '"';
push @{$spec{perllibs}}, '@"' . $ld_libs . '"';
return %spec;
}
1;

View file

@ -0,0 +1,111 @@
package ExtUtils::CBuilder::Platform::Windows::GCC;
our $VERSION = '0.280240'; # VERSION
use warnings;
use strict;
sub format_compiler_cmd {
my ($self, %spec) = @_;
foreach my $path ( @{ $spec{includes} || [] },
@{ $spec{perlinc} || [] } ) {
$path = '-I' . $path;
}
# split off any -arguments included in cc
my @cc = split / (?=-)/, $spec{cc};
return [ grep {defined && length} (
@cc, '-c' ,
@{$spec{includes}} ,
@{$spec{cflags}} ,
@{$spec{optimize}} ,
@{$spec{defines}} ,
@{$spec{perlinc}} ,
'-o', $spec{output} ,
$spec{source} ,
) ];
}
sub format_linker_cmd {
my ($self, %spec) = @_;
my $cf = $self->{config};
# The Config.pm variable 'libperl' is hardcoded to the full name
# of the perl import library (i.e. 'libperl56.a'). GCC will not
# find it unless the 'lib' prefix & the extension are stripped.
$spec{libperl} =~ s/^(?:lib)?([^.]+).*$/-l$1/;
unshift( @{$spec{other_ldflags}}, '-nostartfiles' )
if ( $spec{startup} && @{$spec{startup}} );
%spec = $self->write_linker_script(%spec)
if $spec{use_scripts};
foreach my $path ( @{$spec{libpath}} ) {
$path = "-L$path";
}
# split off any -arguments included in ld
my @ld = split / (?=-)/, $spec{ld};
return [ grep {defined && length} (
@ld ,
$spec{def_file} ,
'-o', $spec{output} ,
"-Wl,--enable-auto-image-base" ,
@{$spec{lddlflags}} ,
@{$spec{libpath}} ,
@{$spec{startup}} ,
@{$spec{objects}} ,
@{$spec{other_ldflags}} ,
$spec{libperl} ,
@{$spec{perllibs}} ,
$spec{map_file} ? ('-Map', $spec{map_file}) : ''
) ];
}
sub write_linker_script {
my ($self, %spec) = @_;
my $script = File::Spec->catfile( $spec{srcdir},
$spec{basename} . '.lds' );
$self->add_to_cleanup($script);
print "Generating script '$script'\n" if !$self->{quiet};
my $SCRIPT = IO::File->new( ">$script" )
or die( "Could not create script '$script': $!" );
print $SCRIPT ( 'SEARCH_DIR(' . $_ . ")\n" )
for @{delete $spec{libpath} || []};
# gcc takes only one startup file, so the first object in startup is
# specified as the startup file and any others are shifted into the
# beginning of the list of objects.
if ( $spec{startup} && @{$spec{startup}} ) {
print $SCRIPT 'STARTUP(' . shift( @{$spec{startup}} ) . ")\n";
unshift @{$spec{objects}},
@{delete $spec{startup} || []};
}
print $SCRIPT 'INPUT(' . join( ',',
@{delete $spec{objects} || []}
) . ")\n";
print $SCRIPT 'INPUT(' . join( ' ',
(delete $spec{libperl} || ''),
@{delete $spec{perllibs} || []},
) . ")\n";
#it is important to keep the order 1.linker_script - 2.other_ldflags
unshift @{$spec{other_ldflags}}, '"' . $script . '"';
return %spec;
}
1;

View file

@ -0,0 +1,134 @@
package ExtUtils::CBuilder::Platform::Windows::MSVC;
our $VERSION = '0.280240'; # VERSION
use warnings;
use strict;
sub arg_exec_file {
my ($self, $file) = @_;
return "/OUT:$file";
}
sub format_compiler_cmd {
my ($self, %spec) = @_;
foreach my $path ( @{ $spec{includes} || [] },
@{ $spec{perlinc} || [] } ) {
$path = '-I' . $path;
}
%spec = $self->write_compiler_script(%spec)
if $spec{use_scripts};
return [ grep {defined && length} (
$spec{cc},'-nologo','-c',
@{$spec{includes}} ,
@{$spec{cflags}} ,
@{$spec{optimize}} ,
@{$spec{defines}} ,
@{$spec{perlinc}} ,
"-Fo$spec{output}" ,
$spec{source} ,
) ];
}
sub write_compiler_script {
my ($self, %spec) = @_;
my $script = File::Spec->catfile( $spec{srcdir},
$spec{basename} . '.ccs' );
$self->add_to_cleanup($script);
print "Generating script '$script'\n" if !$self->{quiet};
my $SCRIPT = IO::File->new( ">$script" )
or die( "Could not create script '$script': $!" );
print $SCRIPT join( "\n",
map { ref $_ ? @{$_} : $_ }
grep defined,
delete(
@spec{ qw(includes cflags optimize defines perlinc) } )
);
push @{$spec{includes}}, '@"' . $script . '"';
return %spec;
}
sub format_linker_cmd {
my ($self, %spec) = @_;
my $cf = $self->{config};
foreach my $path ( @{$spec{libpath}} ) {
$path = "-libpath:$path";
}
my $output = $spec{output};
my $manifest = $spec{manifest};
$spec{def_file} &&= '-def:' . $spec{def_file};
$spec{output} &&= '-out:' . $spec{output};
$spec{manifest} &&= '-manifest ' . $spec{manifest};
$spec{implib} &&= '-implib:' . $spec{implib};
$spec{map_file} &&= '-map:' . $spec{map_file};
%spec = $self->write_linker_script(%spec)
if $spec{use_scripts};
my @cmds; # Stores the series of commands needed to build the module.
push @cmds, [ grep {defined && length} (
$spec{ld} ,
@{$spec{lddlflags}} ,
@{$spec{libpath}} ,
@{$spec{other_ldflags}} ,
@{$spec{startup}} ,
@{$spec{objects}} ,
$spec{map_file} ,
$spec{libperl} ,
@{$spec{perllibs}} ,
$spec{def_file} ,
$spec{implib} ,
$spec{output} ,
) ];
# Embed the manifest file if it exists
push @cmds, [
'if', 'exist', $manifest, 'mt', '-nologo', $spec{manifest}, '-outputresource:' . "$output;2"
];
return @cmds;
}
sub write_linker_script {
my ($self, %spec) = @_;
my $script = File::Spec->catfile( $spec{srcdir},
$spec{basename} . '.lds' );
$self->add_to_cleanup($script);
print "Generating script '$script'\n" if !$self->{quiet};
my $SCRIPT = IO::File->new( ">$script" )
or die( "Could not create script '$script': $!" );
print $SCRIPT join( "\n",
map { ref $_ ? @{$_} : $_ }
grep defined,
delete(
@spec{ qw(lddlflags libpath other_ldflags
startup objects libperl perllibs
def_file implib map_file) } )
);
push @{$spec{lddlflags}}, '@"' . $script . '"';
return %spec;
}
1;

View file

@ -0,0 +1,31 @@
package ExtUtils::CBuilder::Platform::aix;
use warnings;
use strict;
use ExtUtils::CBuilder::Platform::Unix;
use File::Spec;
our $VERSION = '0.280240'; # VERSION
our @ISA = qw(ExtUtils::CBuilder::Platform::Unix);
sub need_prelink { 1 }
sub link {
my ($self, %args) = @_;
my $cf = $self->{config};
(my $baseext = $args{module_name}) =~ s/.*:://;
my $perl_inc = $self->perl_inc();
# Massage some very naughty bits in %Config
local $cf->{lddlflags} = $cf->{lddlflags};
for ($cf->{lddlflags}) {
s/\Q$(BASEEXT)\E/$baseext/;
s/\Q$(PERL_INC)\E/$perl_inc/;
}
return $self->SUPER::link(%args);
}
1;

View file

@ -0,0 +1,39 @@
package ExtUtils::CBuilder::Platform::android;
use warnings;
use strict;
use File::Spec;
use ExtUtils::CBuilder::Platform::Unix;
use Config;
our $VERSION = '0.280240'; # VERSION
our @ISA = qw(ExtUtils::CBuilder::Platform::Unix);
# The Android linker will not recognize symbols from
# libperl unless the module explicitly depends on it.
sub link {
my ($self, %args) = @_;
if ($self->{config}{useshrplib} eq 'true') {
$args{extra_linker_flags} = [
$self->split_like_shell($args{extra_linker_flags}),
'-L' . $self->perl_inc(),
'-lperl',
$self->split_like_shell($Config{perllibs}),
];
}
# Several modules on CPAN rather rightfully expect being
# able to pass $so_file to DynaLoader::dl_load_file and
# have it Just Work. However, $so_file will more likely
# than not be a relative path, and unless the module
# author subclasses MakeMaker/Module::Build to modify
# LD_LIBRARY_PATH, which would be insane, Android's linker
# won't find the .so
# So we make this all work by returning an absolute path.
my($so_file, @so_tmps) = $self->SUPER::link(%args);
$so_file = File::Spec->rel2abs($so_file);
return wantarray ? ($so_file, @so_tmps) : $so_file;
}
1;

View file

@ -0,0 +1,33 @@
package ExtUtils::CBuilder::Platform::cygwin;
use warnings;
use strict;
use File::Spec;
use ExtUtils::CBuilder::Platform::Unix;
our $VERSION = '0.280240'; # VERSION
our @ISA = qw(ExtUtils::CBuilder::Platform::Unix);
# TODO: If a specific exe_file name is requested, if the exe created
# doesn't have that name, we might want to rename it. Apparently asking
# for an exe of "foo" might result in "foo.exe". Alternatively, we should
# make sure the return value is correctly "foo.exe".
# C.f http://rt.cpan.org/Public/Bug/Display.html?id=41003
sub link_executable {
my $self = shift;
return $self->SUPER::link_executable(@_);
}
sub link {
my ($self, %args) = @_;
my $lib = $self->{config}{useshrplib} ? 'libperl.dll.a' : 'libperl.a';
$args{extra_linker_flags} = [
File::Spec->catfile($self->perl_inc(), $lib),
$self->split_like_shell($args{extra_linker_flags})
];
return $self->SUPER::link(%args);
}
1;

View file

@ -0,0 +1,43 @@
package ExtUtils::CBuilder::Platform::darwin;
use warnings;
use strict;
use ExtUtils::CBuilder::Platform::Unix;
use Config;
our $VERSION = '0.280240'; # VERSION
our @ISA = qw(ExtUtils::CBuilder::Platform::Unix);
my ($osver) = split /\./, $Config{osvers};
my $apple_cor = $^X eq "/usr/bin/perl" && $osver >= 18;
sub compile {
my $self = shift;
my $cf = $self->{config};
# -flat_namespace isn't a compile flag, it's a linker flag. But
# it's mistakenly in Config.pm as both. Make the correction here.
local $cf->{ccflags} = $cf->{ccflags};
$cf->{ccflags} =~ s/-flat_namespace//;
# XCode 12 makes this fatal, breaking tons of XS modules
$cf->{ccflags} .= ($cf->{ccflags} ? ' ' : '').'-Wno-error=implicit-function-declaration';
$self->SUPER::compile(@_);
}
sub arg_include_dirs {
my $self = shift;
if ($apple_cor) {
my $perl_inc = $self->perl_inc;
return map {
$_ eq $perl_inc ? ("-iwithsysroot", $_ ) : "-I$_"
} @_;
}
else {
return $self->SUPER::arg_include_dirs(@_);
}
}
1;

View file

@ -0,0 +1,18 @@
package ExtUtils::CBuilder::Platform::dec_osf;
use warnings;
use strict;
use ExtUtils::CBuilder::Platform::Unix;
use File::Spec;
our $VERSION = '0.280240'; # VERSION
our @ISA = qw(ExtUtils::CBuilder::Platform::Unix);
sub link_executable {
my $self = shift;
# $Config{ld} is 'ld' but that won't work: use the cc instead.
local $self->{config}{ld} = $self->{config}{cc};
return $self->SUPER::link_executable(@_);
}
1;

View file

@ -0,0 +1,74 @@
package ExtUtils::CBuilder::Platform::os2;
use warnings;
use strict;
use ExtUtils::CBuilder::Platform::Unix;
our $VERSION = '0.280240'; # VERSION
our @ISA = qw(ExtUtils::CBuilder::Platform::Unix);
sub need_prelink { 1 }
sub prelink {
# Generate import libraries (XXXX currently near .DEF; should be near DLL!)
my $self = shift;
my %args = @_;
my @res = $self->SUPER::prelink(%args);
die "Unexpected number of DEF files" unless @res == 1;
die "Can't find DEF file in the output"
unless $res[0] =~ m,^(.*)\.def$,si;
my $libname = "$1$self->{config}{lib_ext}"; # Put .LIB file near .DEF file
$self->do_system('emximp', '-o', $libname, $res[0]) or die "emxexp: res=$?";
return (@res, $libname);
}
sub _do_link {
my $self = shift;
my ($how, %args) = @_;
if ($how eq 'lib_file'
and (defined $args{module_name} and length $args{module_name})) {
# Now know the basename, find directory parts via lib_file, or objects
my $objs = ( (ref $args{objects}) ? $args{objects} : [$args{objects}] );
my $near_obj = $self->lib_file(@$objs);
my $exp_dir = ($near_obj =~ m,(.*)[/\\],s ? "$1/" : '' );
$args{dl_file} = $1 if $near_obj =~ m,(.*)\.,s; # put ExportList near OBJ
# XXX _do_link does not have place to put libraries?
push @$objs, $self->perl_inc() . "/libperl$self->{config}{lib_ext}";
$args{objects} = $objs;
}
# Some 'env' do exec(), thus return too early when run from ksh;
# To avoid 'env', remove (useless) shrpenv
local $self->{config}{shrpenv} = '';
return $self->SUPER::_do_link($how, %args);
}
sub extra_link_args_after_prelink {
# Add .DEF file to the link line
my ($self, %args) = @_;
my @DEF = grep /\.def$/i, @{$args{prelink_res}};
die "More than one .def files created by 'prelink' stage" if @DEF > 1;
# XXXX No "$how" argument here, so how to test for dynamic link?
die "No .def file created by 'prelink' stage"
unless @DEF or not @{$args{prelink_res}};
my @after_libs = ($OS2::is_aout ? ()
: $self->perl_inc() . "/libperl_override$self->{config}{lib_ext}");
# , "-L", "-lperl"
(@after_libs, @DEF);
}
sub link_executable {
# ldflags is not expecting .exe extension given on command line; remove -Zexe
my $self = shift;
local $self->{config}{ldflags} = $self->{config}{ldflags};
$self->{config}{ldflags} =~ s/(?<!\S)-Zexe(?!\S)//;
return $self->SUPER::link_executable(@_);
}
1;

View file

@ -0,0 +1,381 @@
package ExtUtils::Command;
use 5.00503;
use strict;
use warnings;
require Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw(cp rm_f rm_rf mv cat eqtime mkpath touch test_f test_d chmod
dos2unix);
our $VERSION = '7.70';
$VERSION =~ tr/_//d;
my $Is_VMS = $^O eq 'VMS';
my $Is_VMS_mode = $Is_VMS;
my $Is_VMS_noefs = $Is_VMS;
my $Is_Win32 = $^O eq 'MSWin32';
if( $Is_VMS ) {
my $vms_unix_rpt;
my $vms_efs;
my $vms_case;
if (eval { local $SIG{__DIE__};
local @INC = @INC;
pop @INC if $INC[-1] eq '.';
require VMS::Feature; }) {
$vms_unix_rpt = VMS::Feature::current("filename_unix_report");
$vms_efs = VMS::Feature::current("efs_charset");
$vms_case = VMS::Feature::current("efs_case_preserve");
} else {
my $unix_rpt = $ENV{'DECC$FILENAME_UNIX_REPORT'} || '';
my $efs_charset = $ENV{'DECC$EFS_CHARSET'} || '';
my $efs_case = $ENV{'DECC$EFS_CASE_PRESERVE'} || '';
$vms_unix_rpt = $unix_rpt =~ /^[ET1]/i;
$vms_efs = $efs_charset =~ /^[ET1]/i;
$vms_case = $efs_case =~ /^[ET1]/i;
}
$Is_VMS_mode = 0 if $vms_unix_rpt;
$Is_VMS_noefs = 0 if ($vms_efs);
}
=head1 NAME
ExtUtils::Command - utilities to replace common UNIX commands in Makefiles etc.
=head1 SYNOPSIS
perl -MExtUtils::Command -e cat files... > destination
perl -MExtUtils::Command -e mv source... destination
perl -MExtUtils::Command -e cp source... destination
perl -MExtUtils::Command -e touch files...
perl -MExtUtils::Command -e rm_f files...
perl -MExtUtils::Command -e rm_rf directories...
perl -MExtUtils::Command -e mkpath directories...
perl -MExtUtils::Command -e eqtime source destination
perl -MExtUtils::Command -e test_f file
perl -MExtUtils::Command -e test_d directory
perl -MExtUtils::Command -e chmod mode files...
...
=head1 DESCRIPTION
The module is used to replace common UNIX commands. In all cases the
functions work from @ARGV rather than taking arguments. This makes
them easier to deal with in Makefiles. Call them like this:
perl -MExtUtils::Command -e some_command some files to work on
and I<NOT> like this:
perl -MExtUtils::Command -e 'some_command qw(some files to work on)'
For that use L<Shell::Command>.
Filenames with * and ? will be glob expanded.
=head2 FUNCTIONS
=over 4
=cut
# VMS uses % instead of ? to mean "one character"
my $wild_regex = $Is_VMS ? '*%' : '*?';
sub expand_wildcards
{
@ARGV = map(/[$wild_regex]/o ? glob($_) : $_,@ARGV);
}
=item cat
cat file ...
Concatenates all files mentioned on command line to STDOUT.
=cut
sub cat ()
{
expand_wildcards();
print while (<>);
}
=item eqtime
eqtime source destination
Sets modified time of destination to that of source.
=cut
sub eqtime
{
my ($src,$dst) = @ARGV;
local @ARGV = ($dst); touch(); # in case $dst doesn't exist
utime((stat($src))[8,9],$dst);
}
=item rm_rf
rm_rf files or directories ...
Removes files and directories - recursively (even if readonly)
=cut
sub rm_rf
{
expand_wildcards();
require File::Path;
File::Path::rmtree([grep -e $_,@ARGV],0,0);
}
=item rm_f
rm_f file ...
Removes files (even if readonly)
=cut
sub rm_f {
expand_wildcards();
foreach my $file (@ARGV) {
next unless -f $file;
next if _unlink($file);
chmod(0777, $file);
next if _unlink($file);
require Carp;
Carp::carp("Cannot delete $file: $!");
}
}
sub _unlink {
my $files_unlinked = 0;
foreach my $file (@_) {
my $delete_count = 0;
$delete_count++ while unlink $file;
$files_unlinked++ if $delete_count;
}
return $files_unlinked;
}
=item touch
touch file ...
Makes files exist, with current timestamp
=cut
sub touch {
my $t = time;
expand_wildcards();
foreach my $file (@ARGV) {
open(FILE,">>$file") || die "Cannot write $file:$!";
close(FILE);
utime($t,$t,$file);
}
}
=item mv
mv source_file destination_file
mv source_file source_file destination_dir
Moves source to destination. Multiple sources are allowed if
destination is an existing directory.
Returns true if all moves succeeded, false otherwise.
=cut
sub mv {
expand_wildcards();
my @src = @ARGV;
my $dst = pop @src;
if (@src > 1 && ! -d $dst) {
require Carp;
Carp::croak("Too many arguments");
}
require File::Copy;
my $nok = 0;
foreach my $src (@src) {
$nok ||= !File::Copy::move($src,$dst);
}
return !$nok;
}
=item cp
cp source_file destination_file
cp source_file source_file destination_dir
Copies sources to the destination. Multiple sources are allowed if
destination is an existing directory.
Returns true if all copies succeeded, false otherwise.
=cut
sub cp {
expand_wildcards();
my @src = @ARGV;
my $dst = pop @src;
if (@src > 1 && ! -d $dst) {
require Carp;
Carp::croak("Too many arguments");
}
require File::Copy;
my $nok = 0;
foreach my $src (@src) {
$nok ||= !File::Copy::copy($src,$dst);
# Win32 does not update the mod time of a copied file, just the
# created time which make does not look at.
utime(time, time, $dst) if $Is_Win32;
}
return $nok;
}
=item chmod
chmod mode files ...
Sets UNIX like permissions 'mode' on all the files. e.g. 0666
=cut
sub chmod {
local @ARGV = @ARGV;
my $mode = shift(@ARGV);
expand_wildcards();
if( $Is_VMS_mode && $Is_VMS_noefs) {
require File::Spec;
foreach my $idx (0..$#ARGV) {
my $path = $ARGV[$idx];
next unless -d $path;
# chmod 0777, [.foo.bar] doesn't work on VMS, you have to do
# chmod 0777, [.foo]bar.dir
my @dirs = File::Spec->splitdir( $path );
$dirs[-1] .= '.dir';
$path = File::Spec->catfile(@dirs);
$ARGV[$idx] = $path;
}
}
chmod(oct $mode,@ARGV) || die "Cannot chmod ".join(' ',$mode,@ARGV).":$!";
}
=item mkpath
mkpath directory ...
Creates directories, including any parent directories.
=cut
sub mkpath
{
expand_wildcards();
require File::Path;
File::Path::mkpath([@ARGV],0,0777);
}
=item test_f
test_f file
Tests if a file exists. I<Exits> with 0 if it does, 1 if it does not (ie.
shell's idea of true and false).
=cut
sub test_f
{
exit(-f $ARGV[0] ? 0 : 1);
}
=item test_d
test_d directory
Tests if a directory exists. I<Exits> with 0 if it does, 1 if it does
not (ie. shell's idea of true and false).
=cut
sub test_d
{
exit(-d $ARGV[0] ? 0 : 1);
}
=item dos2unix
dos2unix files or dirs ...
Converts DOS and OS/2 linefeeds to Unix style recursively.
=cut
sub dos2unix {
require File::Find;
File::Find::find(sub {
return if -d;
return unless -w _;
return unless -r _;
return if -B _;
local $\;
my $orig = $_;
my $temp = '.dos2unix_tmp';
open ORIG, $_ or do { warn "dos2unix can't open $_: $!"; return };
open TEMP, ">$temp" or
do { warn "dos2unix can't create .dos2unix_tmp: $!"; return };
binmode ORIG; binmode TEMP;
while (my $line = <ORIG>) {
$line =~ s/\015\012/\012/g;
print TEMP $line;
}
close ORIG;
close TEMP;
rename $temp, $orig;
}, @ARGV);
}
=back
=head1 SEE ALSO
Shell::Command which is these same functions but take arguments normally.
=head1 AUTHOR
Nick Ing-Simmons C<ni-s@cpan.org>
Maintained by Michael G Schwern C<schwern@pobox.com> within the
ExtUtils-MakeMaker package and, as a separate CPAN package, by
Randy Kobes C<r.kobes@uwinnipeg.ca>.
=cut

View file

@ -0,0 +1,323 @@
package ExtUtils::Command::MM;
require 5.006;
use strict;
use warnings;
require Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw(test_harness pod2man perllocal_install uninstall
warn_if_old_packlist test_s cp_nonempty);
our $VERSION = '7.70';
$VERSION =~ tr/_//d;
my $Is_VMS = $^O eq 'VMS';
sub mtime {
no warnings 'redefine';
local $@;
*mtime = (eval { require Time::HiRes } && defined &Time::HiRes::stat)
? sub { (Time::HiRes::stat($_[0]))[9] }
: sub { ( stat($_[0]))[9] }
;
goto &mtime;
}
=head1 NAME
ExtUtils::Command::MM - Commands for the MM's to use in Makefiles
=head1 SYNOPSIS
perl "-MExtUtils::Command::MM" -e "function" "--" arguments...
=head1 DESCRIPTION
B<FOR INTERNAL USE ONLY!> The interface is not stable.
ExtUtils::Command::MM encapsulates code which would otherwise have to
be done with large "one" liners.
Any $(FOO) used in the examples are make variables, not Perl.
=over 4
=item B<test_harness>
test_harness($verbose, @test_libs);
Runs the tests on @ARGV via Test::Harness passing through the $verbose
flag. Any @test_libs will be unshifted onto the test's @INC.
@test_libs are run in alphabetical order.
=cut
sub test_harness {
require Test::Harness;
require File::Spec;
$Test::Harness::verbose = shift;
# Because Windows doesn't do this for us and listing all the *.t files
# out on the command line can blow over its exec limit.
require ExtUtils::Command;
my @argv = ExtUtils::Command::expand_wildcards(@ARGV);
local @INC = @INC;
unshift @INC, map { File::Spec->rel2abs($_) } @_;
Test::Harness::runtests(sort { lc $a cmp lc $b } @argv);
}
=item B<pod2man>
pod2man( '--option=value',
$podfile1 => $manpage1,
$podfile2 => $manpage2,
...
);
# or args on @ARGV
pod2man() is a function performing most of the duties of the pod2man
program. Its arguments are exactly the same as pod2man as of 5.8.0
with the addition of:
--perm_rw octal permission to set the resulting manpage to
And the removal of:
--verbose/-v
--help/-h
If no arguments are given to pod2man it will read from @ARGV.
If Pod::Man is unavailable, this function will warn and return undef.
=cut
sub pod2man {
local @ARGV = @_ ? @_ : @ARGV;
{
local $@;
if( !eval { require Pod::Man } ) {
warn "Pod::Man is not available: $@".
"Man pages will not be generated during this install.\n";
return 0;
}
}
require Getopt::Long;
# We will cheat and just use Getopt::Long. We fool it by putting
# our arguments into @ARGV. Should be safe.
my %options = ();
Getopt::Long::config ('bundling_override');
Getopt::Long::GetOptions (\%options,
'section|s=s', 'release|r=s', 'center|c=s',
'date|d=s', 'fixed=s', 'fixedbold=s', 'fixeditalic=s',
'fixedbolditalic=s', 'official|o', 'quotes|q=s', 'lax|l',
'name|n=s', 'perm_rw=i', 'utf8|u'
);
delete $options{utf8} unless $Pod::Man::VERSION >= 2.17;
# If there's no files, don't bother going further.
return 0 unless @ARGV;
# Official sets --center, but don't override things explicitly set.
if ($options{official} && !defined $options{center}) {
$options{center} = q[Perl Programmer's Reference Guide];
}
# This isn't a valid Pod::Man option and is only accepted for backwards
# compatibility.
delete $options{lax};
my $count = scalar @ARGV / 2;
my $plural = $count == 1 ? 'document' : 'documents';
print "Manifying $count pod $plural\n";
do {{ # so 'next' works
my ($pod, $man) = splice(@ARGV, 0, 2);
next if ((-e $man) &&
(mtime($man) > mtime($pod)) &&
(mtime($man) > mtime("Makefile")));
my $parser = Pod::Man->new(%options);
$parser->parse_from_file($pod, $man)
or do { warn("Could not install $man\n"); next };
if (exists $options{perm_rw}) {
chmod(oct($options{perm_rw}), $man)
or do { warn("chmod $options{perm_rw} $man: $!\n"); next };
}
}} while @ARGV;
return 1;
}
=item B<warn_if_old_packlist>
perl "-MExtUtils::Command::MM" -e warn_if_old_packlist <somefile>
Displays a warning that an old packlist file was found. Reads the
filename from @ARGV.
=cut
sub warn_if_old_packlist {
my $packlist = $ARGV[0];
return unless -f $packlist;
print <<"PACKLIST_WARNING";
WARNING: I have found an old package in
$packlist.
Please make sure the two installations are not conflicting
PACKLIST_WARNING
}
=item B<perllocal_install>
perl "-MExtUtils::Command::MM" -e perllocal_install
<type> <module name> <key> <value> ...
# VMS only, key|value pairs come on STDIN
perl "-MExtUtils::Command::MM" -e perllocal_install
<type> <module name> < <key>|<value> ...
Prints a fragment of POD suitable for appending to perllocal.pod.
Arguments are read from @ARGV.
'type' is the type of what you're installing. Usually 'Module'.
'module name' is simply the name of your module. (Foo::Bar)
Key/value pairs are extra information about the module. Fields include:
installed into which directory your module was out into
LINKTYPE dynamic or static linking
VERSION module version number
EXE_FILES any executables installed in a space separated
list
=cut
sub perllocal_install {
my($type, $name) = splice(@ARGV, 0, 2);
# VMS feeds args as a piped file on STDIN since it usually can't
# fit all the args on a single command line.
my @mod_info = $Is_VMS ? split /\|/, <STDIN>
: @ARGV;
my $pod;
my $time = gmtime($ENV{SOURCE_DATE_EPOCH} || time);
$pod = sprintf <<'POD', scalar($time), $type, $name, $name;
=head2 %s: C<%s> L<%s|%s>
=over 4
POD
do {
my($key, $val) = splice(@mod_info, 0, 2);
$pod .= <<POD
=item *
C<$key: $val>
POD
} while(@mod_info);
$pod .= "=back\n\n";
$pod =~ s/^ //mg;
print $pod;
return 1;
}
=item B<uninstall>
perl "-MExtUtils::Command::MM" -e uninstall <packlist>
A wrapper around ExtUtils::Install::uninstall(). Warns that
uninstallation is deprecated and doesn't actually perform the
uninstallation.
=cut
sub uninstall {
my($packlist) = shift @ARGV;
require ExtUtils::Install;
print <<'WARNING';
Uninstall is unsafe and deprecated, the uninstallation was not performed.
We will show what would have been done.
WARNING
ExtUtils::Install::uninstall($packlist, 1, 1);
print <<'WARNING';
Uninstall is unsafe and deprecated, the uninstallation was not performed.
Please check the list above carefully, there may be errors.
Remove the appropriate files manually.
Sorry for the inconvenience.
WARNING
}
=item B<test_s>
perl "-MExtUtils::Command::MM" -e test_s <file>
Tests if a file exists and is not empty (size > 0).
I<Exits> with 0 if it does, 1 if it does not.
=cut
sub test_s {
exit(-s $ARGV[0] ? 0 : 1);
}
=item B<cp_nonempty>
perl "-MExtUtils::Command::MM" -e cp_nonempty <srcfile> <dstfile> <perm>
Tests if the source file exists and is not empty (size > 0). If it is not empty
it copies it to the given destination with the given permissions.
=back
=cut
sub cp_nonempty {
my @args = @ARGV;
return 0 unless -s $args[0];
require ExtUtils::Command;
{
local @ARGV = @args[0,1];
ExtUtils::Command::cp(@ARGV);
}
{
local @ARGV = @args[2,1];
ExtUtils::Command::chmod(@ARGV);
}
}
1;

View file

@ -0,0 +1,567 @@
package ExtUtils::Constant;
use vars qw (@ISA $VERSION @EXPORT_OK %EXPORT_TAGS);
$VERSION = '0.25';
=head1 NAME
ExtUtils::Constant - generate XS code to import C header constants
=head1 SYNOPSIS
use ExtUtils::Constant qw (WriteConstants);
WriteConstants(
NAME => 'Foo',
NAMES => [qw(FOO BAR BAZ)],
);
# Generates wrapper code to make the values of the constants FOO BAR BAZ
# available to perl
=head1 DESCRIPTION
ExtUtils::Constant facilitates generating C and XS wrapper code to allow
perl modules to AUTOLOAD constants defined in C library header files.
It is principally used by the C<h2xs> utility, on which this code is based.
It doesn't contain the routines to scan header files to extract these
constants.
=head1 USAGE
Generally one only needs to call the C<WriteConstants> function, and then
#include "const-c.inc"
in the C section of C<Foo.xs>
INCLUDE: const-xs.inc
in the XS section of C<Foo.xs>.
For greater flexibility use C<constant_types()>, C<C_constant> and
C<XS_constant>, with which C<WriteConstants> is implemented.
Currently this module understands the following types. h2xs may only know
a subset. The sizes of the numeric types are chosen by the C<Configure>
script at compile time.
=over 4
=item IV
signed integer, at least 32 bits.
=item UV
unsigned integer, the same size as I<IV>
=item NV
floating point type, probably C<double>, possibly C<long double>
=item PV
NUL terminated string, length will be determined with C<strlen>
=item PVN
A fixed length thing, given as a [pointer, length] pair. If you know the
length of a string at compile time you may use this instead of I<PV>
=item SV
A B<mortal> SV.
=item YES
Truth. (C<PL_sv_yes>) The value is not needed (and ignored).
=item NO
Defined Falsehood. (C<PL_sv_no>) The value is not needed (and ignored).
=item UNDEF
C<undef>. The value of the macro is not needed.
=back
=head1 FUNCTIONS
=over 4
=cut
if ($] >= 5.006) {
eval "use warnings; 1" or die $@;
}
use strict;
use Carp qw(croak cluck);
use Exporter;
use ExtUtils::Constant::Utils qw(C_stringify);
use ExtUtils::Constant::XS qw(%XS_Constant %XS_TypeSet);
@ISA = 'Exporter';
%EXPORT_TAGS = ( 'all' => [ qw(
XS_constant constant_types return_clause memEQ_clause C_stringify
C_constant autoload WriteConstants WriteMakefileSnippet
) ] );
@EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
=item constant_types
A function returning a single scalar with C<#define> definitions for the
constants used internally between the generated C and XS functions.
=cut
sub constant_types {
ExtUtils::Constant::XS->header();
}
sub memEQ_clause {
cluck "ExtUtils::Constant::memEQ_clause is deprecated";
ExtUtils::Constant::XS->memEQ_clause({name=>$_[0], checked_at=>$_[1],
indent=>$_[2]});
}
sub return_clause ($$) {
cluck "ExtUtils::Constant::return_clause is deprecated";
my $indent = shift;
ExtUtils::Constant::XS->return_clause({indent=>$indent}, @_);
}
sub switch_clause {
cluck "ExtUtils::Constant::switch_clause is deprecated";
my $indent = shift;
my $comment = shift;
ExtUtils::Constant::XS->switch_clause({indent=>$indent, comment=>$comment},
@_);
}
sub C_constant {
my ($package, $subname, $default_type, $what, $indent, $breakout, @items)
= @_;
ExtUtils::Constant::XS->C_constant({package => $package, subname => $subname,
default_type => $default_type,
types => $what, indent => $indent,
breakout => $breakout}, @items);
}
=item XS_constant PACKAGE, TYPES, XS_SUBNAME, C_SUBNAME
A function to generate the XS code to implement the perl subroutine
I<PACKAGE>::constant used by I<PACKAGE>::AUTOLOAD to load constants.
This XS code is a wrapper around a C subroutine usually generated by
C<C_constant>, and usually named C<constant>.
I<TYPES> should be given either as a comma separated list of types that the
C subroutine C<constant> will generate or as a reference to a hash. It should
be the same list of types as C<C_constant> was given.
[Otherwise C<XS_constant> and C<C_constant> may have different ideas about
the number of parameters passed to the C function C<constant>]
You can call the perl visible subroutine something other than C<constant> if
you give the parameter I<XS_SUBNAME>. The C subroutine it calls defaults to
the name of the perl visible subroutine, unless you give the parameter
I<C_SUBNAME>.
=cut
sub XS_constant {
my $package = shift;
my $what = shift;
my $XS_subname = shift;
my $C_subname = shift;
$XS_subname ||= 'constant';
$C_subname ||= $XS_subname;
if (!ref $what) {
# Convert line of the form IV,UV,NV to hash
$what = {map {$_ => 1} split /,\s*/, ($what)};
}
my $params = ExtUtils::Constant::XS->params ($what);
my $type;
my $xs = <<"EOT";
void
$XS_subname(sv)
PREINIT:
#ifdef dXSTARG
dXSTARG; /* Faster if we have it. */
#else
dTARGET;
#endif
STRLEN len;
int type;
EOT
if ($params->{IV}) {
$xs .= " IV iv = 0; /* avoid uninit var warning */\n";
} else {
$xs .= " /* IV\t\tiv;\tUncomment this if you need to return IVs */\n";
}
if ($params->{NV}) {
$xs .= " NV nv = 0.0; /* avoid uninit var warning */\n";
} else {
$xs .= " /* NV\t\tnv;\tUncomment this if you need to return NVs */\n";
}
if ($params->{PV}) {
$xs .= " const char *pv = NULL; /* avoid uninit var warning */\n";
} else {
$xs .=
" /* const char\t*pv;\tUncomment this if you need to return PVs */\n";
}
$xs .= << 'EOT';
INPUT:
SV * sv;
const char * s = SvPV(sv, len);
EOT
if ($params->{''}) {
$xs .= << 'EOT';
INPUT:
int utf8 = SvUTF8(sv);
EOT
}
$xs .= << 'EOT';
PPCODE:
EOT
if ($params->{IV} xor $params->{NV}) {
$xs .= << "EOT";
/* Change this to $C_subname(aTHX_ s, len, &iv, &nv);
if you need to return both NVs and IVs */
EOT
}
$xs .= " type = $C_subname(aTHX_ s, len";
$xs .= ', utf8' if $params->{''};
$xs .= ', &iv' if $params->{IV};
$xs .= ', &nv' if $params->{NV};
$xs .= ', &pv' if $params->{PV};
$xs .= ', &sv' if $params->{SV};
$xs .= ");\n";
# If anyone is insane enough to suggest a package name containing %
my $package_sprintf_safe = $package;
$package_sprintf_safe =~ s/%/%%/g;
$xs .= << "EOT";
/* Return 1 or 2 items. First is error message, or undef if no error.
Second, if present, is found value */
switch (type) {
case PERL_constant_NOTFOUND:
sv =
sv_2mortal(newSVpvf("%s is not a valid $package_sprintf_safe macro", s));
PUSHs(sv);
break;
case PERL_constant_NOTDEF:
sv = sv_2mortal(newSVpvf(
"Your vendor has not defined $package_sprintf_safe macro %s, used",
s));
PUSHs(sv);
break;
EOT
foreach $type (sort keys %XS_Constant) {
# '' marks utf8 flag needed.
next if $type eq '';
$xs .= "\t/* Uncomment this if you need to return ${type}s\n"
unless $what->{$type};
$xs .= " case PERL_constant_IS$type:\n";
if (length $XS_Constant{$type}) {
$xs .= << "EOT";
EXTEND(SP, 2);
PUSHs(&PL_sv_undef);
$XS_Constant{$type};
EOT
} else {
# Do nothing. return (), which will be correctly interpreted as
# (undef, undef)
}
$xs .= " break;\n";
unless ($what->{$type}) {
chop $xs; # Yes, another need for chop not chomp.
$xs .= " */\n";
}
}
$xs .= << "EOT";
default:
sv = sv_2mortal(newSVpvf(
"Unexpected return type %d while processing $package_sprintf_safe macro %s, used",
type, s));
PUSHs(sv);
}
EOT
return $xs;
}
=item autoload PACKAGE, VERSION, AUTOLOADER
A function to generate the AUTOLOAD subroutine for the module I<PACKAGE>
I<VERSION> is the perl version the code should be backwards compatible with.
It defaults to the version of perl running the subroutine. If I<AUTOLOADER>
is true, the AUTOLOAD subroutine falls back on AutoLoader::AUTOLOAD for all
names that the constant() routine doesn't recognise.
=cut
# ' # Grr. syntax highlighters that don't grok pod.
sub autoload {
my ($module, $compat_version, $autoloader) = @_;
$compat_version ||= $];
croak "Can't maintain compatibility back as far as version $compat_version"
if $compat_version < 5;
my $func = "sub AUTOLOAD {\n"
. " # This AUTOLOAD is used to 'autoload' constants from the constant()\n"
. " # XS function.";
$func .= " If a constant is not found then control is passed\n"
. " # to the AUTOLOAD in AutoLoader." if $autoloader;
$func .= "\n\n"
. " my \$constname;\n";
$func .=
" our \$AUTOLOAD;\n" if ($compat_version >= 5.006);
$func .= <<"EOT";
(\$constname = \$AUTOLOAD) =~ s/.*:://;
croak "&${module}::constant not defined" if \$constname eq 'constant';
my (\$error, \$val) = constant(\$constname);
EOT
if ($autoloader) {
$func .= <<'EOT';
if ($error) {
if ($error =~ /is not a valid/) {
$AutoLoader::AUTOLOAD = $AUTOLOAD;
goto &AutoLoader::AUTOLOAD;
} else {
croak $error;
}
}
EOT
} else {
$func .=
" if (\$error) { croak \$error; }\n";
}
$func .= <<'END';
{
no strict 'refs';
# Fixed between 5.005_53 and 5.005_61
#XXX if ($] >= 5.00561) {
#XXX *$AUTOLOAD = sub () { $val };
#XXX }
#XXX else {
*$AUTOLOAD = sub { $val };
#XXX }
}
goto &$AUTOLOAD;
}
END
return $func;
}
=item WriteMakefileSnippet
WriteMakefileSnippet ATTRIBUTE =E<gt> VALUE [, ...]
A function to generate perl code for Makefile.PL that will regenerate
the constant subroutines. Parameters are named as passed to C<WriteConstants>,
with the addition of C<INDENT> to specify the number of leading spaces
(default 2).
Currently only C<INDENT>, C<NAME>, C<DEFAULT_TYPE>, C<NAMES>, C<C_FILE> and
C<XS_FILE> are recognised.
=cut
sub WriteMakefileSnippet {
my %args = @_;
my $indent = $args{INDENT} || 2;
my $result = <<"EOT";
ExtUtils::Constant::WriteConstants(
NAME => '$args{NAME}',
NAMES => \\\@names,
DEFAULT_TYPE => '$args{DEFAULT_TYPE}',
EOT
foreach (qw (C_FILE XS_FILE)) {
next unless exists $args{$_};
$result .= sprintf " %-12s => '%s',\n",
$_, $args{$_};
}
$result .= <<'EOT';
);
EOT
$result =~ s/^/' 'x$indent/gem;
return ExtUtils::Constant::XS->dump_names({default_type=>$args{DEFAULT_TYPE},
indent=>$indent,},
@{$args{NAMES}})
. $result;
}
=item WriteConstants ATTRIBUTE =E<gt> VALUE [, ...]
Writes a file of C code and a file of XS code which you should C<#include>
and C<INCLUDE> in the C and XS sections respectively of your module's XS
code. You probably want to do this in your C<Makefile.PL>, so that you can
easily edit the list of constants without touching the rest of your module.
The attributes supported are
=over 4
=item NAME
Name of the module. This must be specified
=item DEFAULT_TYPE
The default type for the constants. If not specified C<IV> is assumed.
=item BREAKOUT_AT
The names of the constants are grouped by length. Generate child subroutines
for each group with this number or more names in.
=item NAMES
An array of constants' names, either scalars containing names, or hashrefs
as detailed in L<"C_constant">.
=item PROXYSUBS
If true, uses proxy subs. See L<ExtUtils::Constant::ProxySubs>.
=item C_FH
A filehandle to write the C code to. If not given, then I<C_FILE> is opened
for writing.
=item C_FILE
The name of the file to write containing the C code. The default is
C<const-c.inc>. The C<-> in the name ensures that the file can't be
mistaken for anything related to a legitimate perl package name, and
not naming the file C<.c> avoids having to override Makefile.PL's
C<.xs> to C<.c> rules.
=item XS_FH
A filehandle to write the XS code to. If not given, then I<XS_FILE> is opened
for writing.
=item XS_FILE
The name of the file to write containing the XS code. The default is
C<const-xs.inc>.
=item XS_SUBNAME
The perl visible name of the XS subroutine generated which will return the
constants. The default is C<constant>.
=item C_SUBNAME
The name of the C subroutine generated which will return the constants.
The default is I<XS_SUBNAME>. Child subroutines have C<_> and the name
length appended, so constants with 10 character names would be in
C<constant_10> with the default I<XS_SUBNAME>.
=back
=cut
sub WriteConstants {
my %ARGS =
( # defaults
C_FILE => 'const-c.inc',
XS_FILE => 'const-xs.inc',
XS_SUBNAME => 'constant',
DEFAULT_TYPE => 'IV',
@_);
$ARGS{C_SUBNAME} ||= $ARGS{XS_SUBNAME}; # No-one sane will have C_SUBNAME eq '0'
croak "Module name not specified" unless length $ARGS{NAME};
# Do this before creating (empty) files, in case it fails:
require ExtUtils::Constant::ProxySubs if $ARGS{PROXYSUBS};
my $c_fh = $ARGS{C_FH};
if (!$c_fh) {
if ($] <= 5.008) {
# We need these little games, rather than doing things
# unconditionally, because we're used in core Makefile.PLs before
# IO is available (needed by filehandle), but also we want to work on
# older perls where undefined scalars do not automatically turn into
# anonymous file handles.
require FileHandle;
$c_fh = FileHandle->new();
}
open $c_fh, ">$ARGS{C_FILE}" or die "Can't open $ARGS{C_FILE}: $!";
}
my $xs_fh = $ARGS{XS_FH};
if (!$xs_fh) {
if ($] <= 5.008) {
require FileHandle;
$xs_fh = FileHandle->new();
}
open $xs_fh, ">$ARGS{XS_FILE}" or die "Can't open $ARGS{XS_FILE}: $!";
}
# As this subroutine is intended to make code that isn't edited, there's no
# need for the user to specify any types that aren't found in the list of
# names.
if ($ARGS{PROXYSUBS}) {
$ARGS{C_FH} = $c_fh;
$ARGS{XS_FH} = $xs_fh;
ExtUtils::Constant::ProxySubs->WriteConstants(%ARGS);
} else {
my $types = {};
print $c_fh constant_types(); # macro defs
print $c_fh "\n";
# indent is still undef. Until anyone implements indent style rules with
# it.
foreach (ExtUtils::Constant::XS->C_constant({package => $ARGS{NAME},
subname => $ARGS{C_SUBNAME},
default_type =>
$ARGS{DEFAULT_TYPE},
types => $types,
breakout =>
$ARGS{BREAKOUT_AT}},
@{$ARGS{NAMES}})) {
print $c_fh $_, "\n"; # C constant subs
}
print $xs_fh XS_constant ($ARGS{NAME}, $types, $ARGS{XS_SUBNAME},
$ARGS{C_SUBNAME});
}
close $c_fh or warn "Error closing $ARGS{C_FILE}: $!" unless $ARGS{C_FH};
close $xs_fh or warn "Error closing $ARGS{XS_FILE}: $!" unless $ARGS{XS_FH};
}
1;
__END__
=back
=head1 AUTHOR
Nicholas Clark <nick@ccl4.org> based on the code in C<h2xs> by Larry Wall and
others
=cut

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,682 @@
package ExtUtils::Constant::ProxySubs;
use strict;
use vars qw($VERSION @ISA %type_to_struct %type_from_struct %type_to_sv
%type_to_C_value %type_is_a_problem %type_num_args
%type_temporary);
use Carp;
require ExtUtils::Constant::XS;
use ExtUtils::Constant::Utils qw(C_stringify);
use ExtUtils::Constant::XS qw(%XS_TypeSet);
$VERSION = '0.09';
@ISA = 'ExtUtils::Constant::XS';
%type_to_struct =
(
IV => '{const char *name; I32 namelen; IV value;}',
NV => '{const char *name; I32 namelen; NV value;}',
UV => '{const char *name; I32 namelen; UV value;}',
PV => '{const char *name; I32 namelen; const char *value;}',
PVN => '{const char *name; I32 namelen; const char *value; STRLEN len;}',
YES => '{const char *name; I32 namelen;}',
NO => '{const char *name; I32 namelen;}',
UNDEF => '{const char *name; I32 namelen;}',
'' => '{const char *name; I32 namelen;} ',
);
%type_from_struct =
(
IV => sub { $_[0] . '->value' },
NV => sub { $_[0] . '->value' },
UV => sub { $_[0] . '->value' },
PV => sub { $_[0] . '->value' },
PVN => sub { $_[0] . '->value', $_[0] . '->len' },
YES => sub {},
NO => sub {},
UNDEF => sub {},
'' => sub {},
);
%type_to_sv =
(
IV => sub { "newSViv($_[0])" },
NV => sub { "newSVnv($_[0])" },
UV => sub { "newSVuv($_[0])" },
PV => sub { "newSVpv($_[0], 0)" },
PVN => sub { "newSVpvn($_[0], $_[1])" },
YES => sub { '&PL_sv_yes' },
NO => sub { '&PL_sv_no' },
UNDEF => sub { '&PL_sv_undef' },
'' => sub { '&PL_sv_yes' },
SV => sub {"SvREFCNT_inc($_[0])"},
);
%type_to_C_value =
(
YES => sub {},
NO => sub {},
UNDEF => sub {},
'' => sub {},
);
sub type_to_C_value {
my ($self, $type) = @_;
return $type_to_C_value{$type} || sub {return map {ref $_ ? @$_ : $_} @_};
}
# TODO - figure out if there is a clean way for the type_to_sv code to
# attempt s/sv_2mortal// and if it succeeds tell type_to_sv not to add
# SvREFCNT_inc
%type_is_a_problem =
(
# The documentation says *mortal SV*, but we now need a non-mortal copy.
SV => 1,
);
%type_temporary =
(
SV => ['SV *'],
PV => ['const char *'],
PVN => ['const char *', 'STRLEN'],
);
$type_temporary{$_} = [$_] foreach qw(IV UV NV);
while (my ($type, $value) = each %XS_TypeSet) {
$type_num_args{$type}
= defined $value ? ref $value ? scalar @$value : 1 : 0;
}
$type_num_args{''} = 0;
sub partition_names {
my ($self, $default_type, @items) = @_;
my (%found, @notfound, @trouble);
while (my $item = shift @items) {
my $default = delete $item->{default};
if ($default) {
# If we find a default value, convert it into a regular item and
# append it to the queue of items to process
my $default_item = {%$item};
$default_item->{invert_macro} = 1;
$default_item->{pre} = delete $item->{def_pre};
$default_item->{post} = delete $item->{def_post};
$default_item->{type} = shift @$default;
$default_item->{value} = $default;
push @items, $default_item;
} else {
# It can be "not found" unless it's the default (invert the macro)
# or the "macro" is an empty string (ie no macro)
push @notfound, $item unless $item->{invert_macro}
or !$self->macro_to_ifdef($self->macro_from_item($item));
}
if ($item->{pre} or $item->{post} or $item->{not_constant}
or $type_is_a_problem{$item->{type}}) {
push @trouble, $item;
} else {
push @{$found{$item->{type}}}, $item;
}
}
# use Data::Dumper; print Dumper \%found;
(\%found, \@notfound, \@trouble);
}
sub boottime_iterator {
my ($self, $type, $iterator, $hash, $subname, $push) = @_;
my $extractor = $type_from_struct{$type};
die "Can't find extractor code for type $type"
unless defined $extractor;
my $generator = $type_to_sv{$type};
die "Can't find generator code for type $type"
unless defined $generator;
my $athx = $self->C_constant_prefix_param();
if ($push) {
return sprintf <<"EOBOOT", &$generator(&$extractor($iterator));
while ($iterator->name) {
he = $subname($athx $hash, $iterator->name,
$iterator->namelen, %s);
av_push(push, newSVhek(HeKEY_hek(he)));
++$iterator;
}
EOBOOT
} else {
return sprintf <<"EOBOOT", &$generator(&$extractor($iterator));
while ($iterator->name) {
$subname($athx $hash, $iterator->name,
$iterator->namelen, %s);
++$iterator;
}
EOBOOT
}
}
sub name_len_value_macro {
my ($self, $item) = @_;
my $name = $item->{name};
my $value = $item->{value};
$value = $item->{name} unless defined $value;
my $namelen = length $name;
if ($name =~ tr/\0-\377// != $namelen) {
# the hash API signals UTF-8 by passing the length negated.
utf8::encode($name);
$namelen = -length $name;
}
$name = C_stringify($name);
my $macro = $self->macro_from_item($item);
($name, $namelen, $value, $macro);
}
sub WriteConstants {
my $self = shift;
my $ARGS = {@_};
my ($c_fh, $xs_fh, $c_subname, $default_type, $package)
= @{$ARGS}{qw(C_FH XS_FH C_SUBNAME DEFAULT_TYPE NAME)};
my $xs_subname
= exists $ARGS->{XS_SUBNAME} ? $ARGS->{XS_SUBNAME} : 'constant';
my $options = $ARGS->{PROXYSUBS};
$options = {} unless ref $options;
my $push = $options->{push};
my $explosives = $options->{croak_on_read};
my $croak_on_error = $options->{croak_on_error};
my $autoload = $options->{autoload};
{
my $exclusive = 0;
++$exclusive if $explosives;
++$exclusive if $croak_on_error;
++$exclusive if $autoload;
# Until someone patches this (with test cases):
carp ("PROXYSUBS options 'autoload', 'croak_on_read' and 'croak_on_error' cannot be used together")
if $exclusive > 1;
}
# Strictly it requires Perl_caller_cx
carp ("PROXYSUBS option 'croak_on_error' requires v5.13.5 or later")
if $croak_on_error && $^V < v5.13.5;
# Strictly this is actually 5.8.9, but it's not well tested there
my $can_do_pcs = $] >= 5.009;
# Until someone patches this (with test cases)
carp ("PROXYSUBS option 'push' requires v5.10 or later")
if $push && !$can_do_pcs;
# Until someone patches this (with test cases)
carp ("PROXYSUBS options 'push' and 'croak_on_read' cannot be used together")
if $explosives && $push;
# If anyone is insane enough to suggest a package name containing %
my $package_sprintf_safe = $package;
$package_sprintf_safe =~ s/%/%%/g;
# All the types we see
my $what = {};
# A hash to lookup items with.
my $items = {};
my @items = $self->normalise_items ({disable_utf8_duplication => 1},
$default_type, $what, $items,
@{$ARGS->{NAMES}});
# Partition the values by type. Also include any defaults in here
# Everything that doesn't have a default needs alternative code for
# "I'm missing"
# And everything that has pre or post code ends up in a private block
my ($found, $notfound, $trouble)
= $self->partition_names($default_type, @items);
my $pthx = $self->C_constant_prefix_param_defintion();
my $athx = $self->C_constant_prefix_param();
my $symbol_table = C_stringify($package) . '::';
$push = C_stringify($package . '::' . $push) if $push;
my $cast_CONSTSUB = $] < 5.010 ? '(char *)' : '';
print $c_fh $self->header();
if ($autoload || $croak_on_error) {
print $c_fh <<'EOC';
/* This allows slightly more efficient code on !USE_ITHREADS: */
#ifdef USE_ITHREADS
# define COP_FILE(c) CopFILE(c)
# define COP_FILE_F "s"
#else
# define COP_FILE(c) CopFILESV(c)
# define COP_FILE_F SVf
#endif
EOC
}
my $return_type = $push ? 'HE *' : 'void';
print $c_fh <<"EOADD";
static $return_type
${c_subname}_add_symbol($pthx HV *hash, const char *name, I32 namelen, SV *value) {
EOADD
if (!$can_do_pcs) {
print $c_fh <<'EO_NOPCS';
if (namelen == namelen) {
EO_NOPCS
} else {
print $c_fh <<"EO_PCS";
HE *he = (HE*) hv_common_key_len(hash, name, namelen, HV_FETCH_LVALUE, NULL,
0);
SV *sv;
if (!he) {
croak("Couldn't add key '%s' to %%$package_sprintf_safe\::",
name);
}
sv = HeVAL(he);
if (SvOK(sv) || SvTYPE(sv) == SVt_PVGV) {
/* Someone has been here before us - have to make a real sub. */
EO_PCS
}
# This piece of code is common to both
print $c_fh <<"EOADD";
newCONSTSUB(hash, ${cast_CONSTSUB}name, value);
EOADD
if ($can_do_pcs) {
print $c_fh <<'EO_PCS';
} else {
SvUPGRADE(sv, SVt_RV);
SvRV_set(sv, value);
SvROK_on(sv);
SvREADONLY_on(value);
}
EO_PCS
} else {
print $c_fh <<'EO_NOPCS';
}
EO_NOPCS
}
print $c_fh " return he;\n" if $push;
print $c_fh <<'EOADD';
}
EOADD
print $c_fh $explosives ? <<"EXPLODE" : "\n";
static int
Im_sorry_Dave(pTHX_ SV *sv, MAGIC *mg)
{
PERL_UNUSED_ARG(mg);
croak("Your vendor has not defined $package_sprintf_safe macro %"SVf
" used", sv);
NORETURN_FUNCTION_END;
}
static MGVTBL not_defined_vtbl = {
Im_sorry_Dave, /* get - I'm afraid I can't do that */
Im_sorry_Dave, /* set */
0, /* len */
0, /* clear */
0, /* free */
0, /* copy */
0, /* dup */
};
EXPLODE
{
my $key = $symbol_table;
# Just seems tidier (and slightly more space efficient) not to have keys
# such as Fcntl::
$key =~ s/::$//;
my $key_len = length $key;
print $c_fh <<"MISSING";
#ifndef SYMBIAN
/* Store a hash of all symbols missing from the package. To avoid trampling on
the package namespace (uninvited) put each package's hash in our namespace.
To avoid creating lots of typeblogs and symbol tables for sub-packages, put
each package's hash into one hash in our namespace. */
static HV *
get_missing_hash(pTHX) {
HV *const parent
= get_hv("ExtUtils::Constant::ProxySubs::Missing", GVf_MULTI);
/* We could make a hash of hashes directly, but this would confuse anything
at Perl space that looks at us, and as we're visible in Perl space,
best to play nice. */
SV *const *const ref
= hv_fetch(parent, "$key", $key_len, TRUE);
HV *new_hv;
if (!ref)
return NULL;
if (SvROK(*ref))
return (HV*) SvRV(*ref);
new_hv = newHV();
SvUPGRADE(*ref, SVt_RV);
SvRV_set(*ref, (SV *)new_hv);
SvROK_on(*ref);
return new_hv;
}
#endif
MISSING
}
print $xs_fh <<"EOBOOT";
BOOT:
{
#if defined(dTHX) && !defined(PERL_NO_GET_CONTEXT)
dTHX;
#endif
HV *symbol_table = get_hv("$symbol_table", GV_ADD);
EOBOOT
if ($push) {
print $xs_fh <<"EOC";
AV *push = get_av(\"$push\", GV_ADD);
HE *he;
EOC
}
my %iterator;
$found->{''}
= [map {{%$_, type=>'', invert_macro => 1}} @$notfound];
foreach my $type (sort keys %$found) {
my $struct = $type_to_struct{$type};
my $type_to_value = $self->type_to_C_value($type);
my $number_of_args = $type_num_args{$type};
die "Can't find structure definition for type $type"
unless defined $struct;
my $lc_type = $type ? lc($type) : 'notfound';
my $struct_type = $lc_type . '_s';
my $array_name = 'values_for_' . $lc_type;
$iterator{$type} = 'value_for_' . $lc_type;
# Give the notfound struct file scope. The others are scoped within the
# BOOT block
my $struct_fh = $type ? $xs_fh : $c_fh;
print $c_fh "struct $struct_type $struct;\n";
print $struct_fh <<"EOBOOT";
static const struct $struct_type $array_name\[] =
{
EOBOOT
foreach my $item (@{$found->{$type}}) {
my ($name, $namelen, $value, $macro)
= $self->name_len_value_macro($item);
my $ifdef = $self->macro_to_ifdef($macro);
if (!$ifdef && $item->{invert_macro}) {
carp("Attempting to supply a default for '$name' which has no conditional macro");
next;
}
if ($item->{invert_macro}) {
print $struct_fh $self->macro_to_ifndef($macro);
print $struct_fh
" /* This is the default value: */\n" if $type;
} else {
print $struct_fh $ifdef;
}
print $struct_fh " { ", join (', ', "\"$name\"", $namelen,
&$type_to_value($value)),
" },\n",
$self->macro_to_endif($macro);
}
# Terminate the list with a NULL
print $struct_fh " { NULL, 0", (", 0" x $number_of_args), " } };\n";
print $xs_fh <<"EOBOOT" if $type;
const struct $struct_type *$iterator{$type} = $array_name;
EOBOOT
}
delete $found->{''};
my $add_symbol_subname = $c_subname . '_add_symbol';
foreach my $type (sort keys %$found) {
print $xs_fh $self->boottime_iterator($type, $iterator{$type},
'symbol_table',
$add_symbol_subname, $push);
}
print $xs_fh <<"EOBOOT";
if (C_ARRAY_LENGTH(values_for_notfound) > 1) {
#ifndef SYMBIAN
HV *const ${c_subname}_missing = get_missing_hash(aTHX);
#endif
const struct notfound_s *value_for_notfound = values_for_notfound;
do {
EOBOOT
print $xs_fh $explosives ? <<"EXPLODE" : << "DONT";
SV *tripwire = newSV(0);
sv_magicext(tripwire, 0, PERL_MAGIC_ext, &not_defined_vtbl, 0, 0);
SvPV_set(tripwire, (char *)value_for_notfound->name);
if(value_for_notfound->namelen >= 0) {
SvCUR_set(tripwire, value_for_notfound->namelen);
} else {
SvCUR_set(tripwire, -value_for_notfound->namelen);
SvUTF8_on(tripwire);
}
SvPOKp_on(tripwire);
SvREADONLY_on(tripwire);
assert(SvLEN(tripwire) == 0);
$add_symbol_subname($athx symbol_table, value_for_notfound->name,
value_for_notfound->namelen, tripwire);
EXPLODE
/* Need to add prototypes, else parsing will vary by platform. */
HE *he = (HE*) hv_common_key_len(symbol_table,
value_for_notfound->name,
value_for_notfound->namelen,
HV_FETCH_LVALUE, NULL, 0);
SV *sv;
#ifndef SYMBIAN
HEK *hek;
#endif
if (!he) {
croak("Couldn't add key '%s' to %%$package_sprintf_safe\::",
value_for_notfound->name);
}
sv = HeVAL(he);
if (!SvOK(sv) && SvTYPE(sv) != SVt_PVGV) {
/* Nothing was here before, so mark a prototype of "" */
sv_setpvn(sv, "", 0);
} else if (SvPOK(sv) && SvCUR(sv) == 0) {
/* There is already a prototype of "" - do nothing */
} else {
/* Someone has been here before us - have to make a real
typeglob. */
/* It turns out to be incredibly hard to deal with all the
corner cases of sub foo (); and reporting errors correctly,
so lets cheat a bit. Start with a constant subroutine */
CV *cv = newCONSTSUB(symbol_table,
${cast_CONSTSUB}value_for_notfound->name,
&PL_sv_yes);
/* and then turn it into a non constant declaration only. */
SvREFCNT_dec(CvXSUBANY(cv).any_ptr);
CvCONST_off(cv);
CvXSUB(cv) = NULL;
CvXSUBANY(cv).any_ptr = NULL;
}
#ifndef SYMBIAN
hek = HeKEY_hek(he);
if (!hv_common(${c_subname}_missing, NULL, HEK_KEY(hek),
HEK_LEN(hek), HEK_FLAGS(hek), HV_FETCH_ISSTORE,
&PL_sv_yes, HEK_HASH(hek)))
croak("Couldn't add key '%s' to missing_hash",
value_for_notfound->name);
#endif
DONT
print $xs_fh " av_push(push, newSVhek(hek));\n"
if $push;
print $xs_fh <<"EOBOOT";
} while ((++value_for_notfound)->name);
}
EOBOOT
foreach my $item (@$trouble) {
my ($name, $namelen, $value, $macro)
= $self->name_len_value_macro($item);
my $ifdef = $self->macro_to_ifdef($macro);
my $type = $item->{type};
my $type_to_value = $self->type_to_C_value($type);
print $xs_fh $ifdef;
if ($item->{invert_macro}) {
print $xs_fh
" /* This is the default value: */\n" if $type;
print $xs_fh "#else\n";
}
my $generator = $type_to_sv{$type};
die "Can't find generator code for type $type"
unless defined $generator;
print $xs_fh " {\n";
# We need to use a temporary value because some really troublesome
# items use C pre processor directives in their values, and in turn
# these don't fit nicely in the macro-ised generator functions
my $counter = 0;
printf $xs_fh " %s temp%d;\n", $_, $counter++
foreach @{$type_temporary{$type}};
print $xs_fh " $item->{pre}\n" if $item->{pre};
# And because the code in pre might be both declarations and
# statements, we can't declare and assign to the temporaries in one.
$counter = 0;
printf $xs_fh " temp%d = %s;\n", $counter++, $_
foreach &$type_to_value($value);
my @tempvarnames = map {sprintf 'temp%d', $_} 0 .. $counter - 1;
printf $xs_fh <<"EOBOOT", $name, &$generator(@tempvarnames);
${c_subname}_add_symbol($athx symbol_table, "%s",
$namelen, %s);
EOBOOT
print $xs_fh " $item->{post}\n" if $item->{post};
print $xs_fh " }\n";
print $xs_fh $self->macro_to_endif($macro);
}
if ($] >= 5.009) {
print $xs_fh <<EOBOOT;
/* As we've been creating subroutines, we better invalidate any cached
methods */
mro_method_changed_in(symbol_table);
}
EOBOOT
} else {
print $xs_fh <<EOBOOT;
/* As we've been creating subroutines, we better invalidate any cached
methods */
++PL_sub_generation;
}
EOBOOT
}
return if !defined $xs_subname;
if ($croak_on_error || $autoload) {
print $xs_fh $croak_on_error ? <<"EOC" : <<'EOA';
void
$xs_subname(sv)
INPUT:
SV * sv;
PREINIT:
const PERL_CONTEXT *cx = caller_cx(0, NULL);
/* cx is NULL if we've been called from the top level. PL_curcop isn't
ideal, but it's much cheaper than other ways of not going SEGV. */
const COP *cop = cx ? cx->blk_oldcop : PL_curcop;
EOC
void
AUTOLOAD()
PROTOTYPE: DISABLE
PREINIT:
SV *sv = newSVpvn_flags(SvPVX(cv), SvCUR(cv), SVs_TEMP | SvUTF8(cv));
const COP *cop = PL_curcop;
EOA
print $xs_fh <<"EOC";
PPCODE:
#ifndef SYMBIAN
/* It's not obvious how to calculate this at C pre-processor time.
However, any compiler optimiser worth its salt should be able to
remove the dead code, and hopefully the now-obviously-unused static
function too. */
HV *${c_subname}_missing = (C_ARRAY_LENGTH(values_for_notfound) > 1)
? get_missing_hash(aTHX) : NULL;
if ((C_ARRAY_LENGTH(values_for_notfound) > 1)
? hv_exists_ent(${c_subname}_missing, sv, 0) : 0) {
sv = newSVpvf("Your vendor has not defined $package_sprintf_safe macro %" SVf
", used at %" COP_FILE_F " line %" UVuf "\\n",
sv, COP_FILE(cop), (UV)CopLINE(cop));
} else
#endif
{
sv = newSVpvf("%" SVf
" is not a valid $package_sprintf_safe macro at %"
COP_FILE_F " line %" UVuf "\\n",
sv, COP_FILE(cop), (UV)CopLINE(cop));
}
croak_sv(sv_2mortal(sv));
EOC
} else {
print $xs_fh $explosives ? <<"EXPLODE" : <<"DONT";
void
$xs_subname(sv)
INPUT:
SV * sv;
PPCODE:
sv = newSVpvf("Your vendor has not defined $package_sprintf_safe macro %" SVf
", used", sv);
PUSHs(sv_2mortal(sv));
EXPLODE
void
$xs_subname(sv)
INPUT:
SV * sv;
PPCODE:
#ifndef SYMBIAN
/* It's not obvious how to calculate this at C pre-processor time.
However, any compiler optimiser worth its salt should be able to
remove the dead code, and hopefully the now-obviously-unused static
function too. */
HV *${c_subname}_missing = (C_ARRAY_LENGTH(values_for_notfound) > 1)
? get_missing_hash(aTHX) : NULL;
if ((C_ARRAY_LENGTH(values_for_notfound) > 1)
? hv_exists_ent(${c_subname}_missing, sv, 0) : 0) {
sv = newSVpvf("Your vendor has not defined $package_sprintf_safe macro %" SVf
", used", sv);
} else
#endif
{
sv = newSVpvf("%" SVf " is not a valid $package_sprintf_safe macro",
sv);
}
PUSHs(sv_2mortal(sv));
DONT
}
}
1;

View file

@ -0,0 +1,135 @@
package ExtUtils::Constant::Utils;
use strict;
use vars qw($VERSION @EXPORT_OK @ISA);
use Carp;
@ISA = 'Exporter';
@EXPORT_OK = qw(C_stringify perl_stringify);
$VERSION = '0.04';
use constant is_perl55 => ($] < 5.005_50);
use constant is_perl56 => ($] < 5.007 && $] > 5.005_50);
use constant is_sane_perl => $] > 5.007;
=head1 NAME
ExtUtils::Constant::Utils - helper functions for ExtUtils::Constant
=head1 SYNOPSIS
use ExtUtils::Constant::Utils qw (C_stringify);
$C_code = C_stringify $stuff;
=head1 DESCRIPTION
ExtUtils::Constant::Utils packages up utility subroutines used by
ExtUtils::Constant, ExtUtils::Constant::Base and derived classes. All its
functions are explicitly exportable.
=head1 USAGE
=over 4
=item C_stringify NAME
A function which returns a 7 bit ASCII correctly \ escaped version of the
string passed suitable for C's "" or ''. It will die if passed Unicode
characters.
=cut
# Hopefully make a happy C identifier.
sub C_stringify {
local $_ = shift;
return unless defined $_;
# grr 5.6.1
confess "Wide character in '$_' intended as a C identifier"
if tr/\0-\377// != length;
# grr 5.6.1 more so because its regexps will break on data that happens to
# be utf8, which includes my 8 bit test cases.
$_ = pack 'C*', unpack 'U*', $_ . pack 'U*' if is_perl56;
s/\\/\\\\/g;
s/([\"\'])/\\$1/g; # Grr. fix perl mode.
s/\n/\\n/g; # Ensure newlines don't end up in octal
s/\r/\\r/g;
s/\t/\\t/g;
s/\f/\\f/g;
s/\a/\\a/g;
unless (is_perl55) {
# This will elicit a warning on 5.005_03 about [: :] being reserved unless
# I cheat
my $cheat = '([[:^print:]])';
if (ord('A') == 193) { # EBCDIC has no ^\0-\177 workalike.
s/$cheat/sprintf "\\%03o", ord $1/ge;
} else {
s/([^\0-\177])/sprintf "\\%03o", ord $1/ge;
}
s/$cheat/sprintf "\\%03o", ord $1/ge;
} else {
require POSIX;
s/([^A-Za-z0-9_])/POSIX::isprint($1) ? $1 : sprintf "\\%03o", ord $1/ge;
}
$_;
}
=item perl_stringify NAME
A function which returns a 7 bit ASCII correctly \ escaped version of the
string passed suitable for a perl "" string.
=cut
# Hopefully make a happy perl identifier.
sub perl_stringify {
local $_ = shift;
return unless defined $_;
s/\\/\\\\/g;
s/([\"\'])/\\$1/g; # Grr. fix perl mode.
s/\n/\\n/g; # Ensure newlines don't end up in octal
s/\r/\\r/g;
s/\t/\\t/g;
s/\f/\\f/g;
s/\a/\\a/g;
unless (is_perl55) {
# This will elicit a warning on 5.005_03 about [: :] being reserved unless
# I cheat
my $cheat = '([[:^print:]])';
if (is_sane_perl) {
if (ord('A') == 193) { # EBCDIC has no ^\0-\177 workalike.
s/$cheat/sprintf "\\x{%X}", ord $1/ge;
} else {
s/([^\0-\177])/sprintf "\\x{%X}", ord $1/ge;
}
} else {
# Grr 5.6.1. And I don't think I can use utf8; to force the regexp
# because 5.005_03 will fail.
# This is grim, but I also can't split on //
my $copy;
foreach my $index (0 .. length ($_) - 1) {
my $char = substr ($_, $index, 1);
$copy .= ($char le "\177") ? $char : sprintf "\\x{%X}", ord $char;
}
$_ = $copy;
}
s/$cheat/sprintf "\\%03o", ord $1/ge;
} else {
# Turns out "\x{}" notation only arrived with 5.6
s/([^\0-\177])/sprintf "\\x%02X", ord $1/ge;
require POSIX;
s/([^A-Za-z0-9_])/POSIX::isprint($1) ? $1 : sprintf "\\%03o", ord $1/ge;
}
$_;
}
1;
__END__
=back
=head1 AUTHOR
Nicholas Clark <nick@ccl4.org> based on the code in C<h2xs> by Larry Wall and
others

View file

@ -0,0 +1,259 @@
package ExtUtils::Constant::XS;
use strict;
use vars qw($VERSION %XS_Constant %XS_TypeSet @ISA @EXPORT_OK $is_perl56);
use Carp;
use ExtUtils::Constant::Utils 'perl_stringify';
require ExtUtils::Constant::Base;
@ISA = qw(ExtUtils::Constant::Base Exporter);
@EXPORT_OK = qw(%XS_Constant %XS_TypeSet);
$VERSION = '0.03';
$is_perl56 = ($] < 5.007 && $] > 5.005_50);
=head1 NAME
ExtUtils::Constant::XS - generate C code for XS modules' constants.
=head1 SYNOPSIS
require ExtUtils::Constant::XS;
=head1 DESCRIPTION
ExtUtils::Constant::XS overrides ExtUtils::Constant::Base to generate C
code for XS modules' constants.
=head1 BUGS
Nothing is documented.
Probably others.
=head1 AUTHOR
Nicholas Clark <nick@ccl4.org> based on the code in C<h2xs> by Larry Wall and
others
=cut
# '' is used as a flag to indicate non-ascii macro names, and hence the need
# to pass in the utf8 on/off flag.
%XS_Constant = (
'' => '',
IV => 'PUSHi(iv)',
UV => 'PUSHu((UV)iv)',
NV => 'PUSHn(nv)',
PV => 'PUSHp(pv, strlen(pv))',
PVN => 'PUSHp(pv, iv)',
SV => 'PUSHs(sv)',
YES => 'PUSHs(&PL_sv_yes)',
NO => 'PUSHs(&PL_sv_no)',
UNDEF => '', # implicit undef
);
%XS_TypeSet = (
IV => '*iv_return = ',
UV => '*iv_return = (IV)',
NV => '*nv_return = ',
PV => '*pv_return = ',
PVN => ['*pv_return = ', '*iv_return = (IV)'],
SV => '*sv_return = ',
YES => undef,
NO => undef,
UNDEF => undef,
);
sub header {
my $start = 1;
my @lines;
push @lines, "#define PERL_constant_NOTFOUND\t$start\n"; $start++;
push @lines, "#define PERL_constant_NOTDEF\t$start\n"; $start++;
foreach (sort keys %XS_Constant) {
next if $_ eq '';
push @lines, "#define PERL_constant_IS$_\t$start\n"; $start++;
}
push @lines, << 'EOT';
#ifndef NVTYPE
typedef double NV; /* 5.6 and later define NVTYPE, and typedef NV to it. */
#endif
#ifndef aTHX_
#define aTHX_ /* 5.6 or later define this for threading support. */
#endif
#ifndef pTHX_
#define pTHX_ /* 5.6 or later define this for threading support. */
#endif
EOT
return join '', @lines;
}
sub valid_type {
my ($self, $type) = @_;
return exists $XS_TypeSet{$type};
}
# This might actually be a return statement
sub assignment_clause_for_type {
my $self = shift;
my $args = shift;
my $type = $args->{type};
my $typeset = $XS_TypeSet{$type};
if (ref $typeset) {
die "Type $type is aggregate, but only single value given"
if @_ == 1;
return map {"$typeset->[$_]$_[$_];"} 0 .. $#$typeset;
} elsif (defined $typeset) {
confess "Aggregate value given for type $type"
if @_ > 1;
return "$typeset$_[0];";
}
return ();
}
sub return_statement_for_type {
my ($self, $type) = @_;
# In the future may pass in an options hash
$type = $type->{type} if ref $type;
"return PERL_constant_IS$type;";
}
sub return_statement_for_notdef {
# my ($self) = @_;
"return PERL_constant_NOTDEF;";
}
sub return_statement_for_notfound {
# my ($self) = @_;
"return PERL_constant_NOTFOUND;";
}
sub default_type {
'IV';
}
sub macro_from_name {
my ($self, $item) = @_;
my $macro = $item->{name};
$macro = $item->{value} unless defined $macro;
$macro;
}
sub macro_from_item {
my ($self, $item) = @_;
my $macro = $item->{macro};
$macro = $self->macro_from_name($item) unless defined $macro;
$macro;
}
# Keep to the traditional perl source macro
sub memEQ {
"memEQ";
}
sub params {
my ($self, $what) = @_;
foreach (sort keys %$what) {
warn "ExtUtils::Constant doesn't know how to handle values of type $_" unless defined $XS_Constant{$_};
}
my $params = {};
$params->{''} = 1 if $what->{''};
$params->{IV} = 1 if $what->{IV} || $what->{UV} || $what->{PVN};
$params->{NV} = 1 if $what->{NV};
$params->{PV} = 1 if $what->{PV} || $what->{PVN};
$params->{SV} = 1 if $what->{SV};
return $params;
}
sub C_constant_prefix_param {
"aTHX_ ";
}
sub C_constant_prefix_param_defintion {
"pTHX_ ";
}
sub namelen_param_definition {
'STRLEN ' . $_[0] -> namelen_param;
}
sub C_constant_other_params_defintion {
my ($self, $params) = @_;
my $body = '';
$body .= ", int utf8" if $params->{''};
$body .= ", IV *iv_return" if $params->{IV};
$body .= ", NV *nv_return" if $params->{NV};
$body .= ", const char **pv_return" if $params->{PV};
$body .= ", SV **sv_return" if $params->{SV};
$body;
}
sub C_constant_other_params {
my ($self, $params) = @_;
my $body = '';
$body .= ", utf8" if $params->{''};
$body .= ", iv_return" if $params->{IV};
$body .= ", nv_return" if $params->{NV};
$body .= ", pv_return" if $params->{PV};
$body .= ", sv_return" if $params->{SV};
$body;
}
sub dogfood {
my ($self, $args, @items) = @_;
my ($package, $subname, $default_type, $what, $indent, $breakout) =
@{$args}{qw(package subname default_type what indent breakout)};
my $result = <<"EOT";
/* When generated this function returned values for the list of names given
in this section of perl code. Rather than manually editing these functions
to add or remove constants, which would result in this comment and section
of code becoming inaccurate, we recommend that you edit this section of
code, and use it to regenerate a new set of constant functions which you
then use to replace the originals.
Regenerate these constant functions by feeding this entire source file to
perl -x
#!$^X -w
use ExtUtils::Constant qw (constant_types C_constant XS_constant);
EOT
$result .= $self->dump_names ({default_type=>$default_type, what=>$what,
indent=>0, declare_types=>1},
@items);
$result .= <<'EOT';
print constant_types(), "\n"; # macro defs
EOT
$package = perl_stringify($package);
$result .=
"foreach (C_constant (\"$package\", '$subname', '$default_type', \$types, ";
# The form of the indent parameter isn't defined. (Yet)
if (defined $indent) {
require Data::Dumper;
$Data::Dumper::Terse=1;
$Data::Dumper::Terse=1; # Not used once. :-)
chomp ($indent = Data::Dumper::Dumper ($indent));
$result .= $indent;
} else {
$result .= 'undef';
}
$result .= ", $breakout" . ', @names) ) {
print $_, "\n"; # C constant subs
}
print "\n#### XS Section:\n";
print XS_constant ("' . $package . '", $types);
__END__
*/
';
$result;
}
1;

View file

@ -0,0 +1,491 @@
package ExtUtils::Embed;
require Exporter;
use Config;
require File::Spec;
our ( @Extensions, $opt_o, $opt_s );
use strict;
# This is not a dual-life module, so no need for development version numbers
our $VERSION = '1.35';
our @ISA = qw(Exporter);
our @EXPORT = qw(&xsinit &ldopts
&ccopts &ccflags &ccdlflags &perl_inc
&xsi_header &xsi_protos &xsi_body);
our $Verbose = 0;
our $lib_ext = $Config{lib_ext} || '.a';
sub is_cmd { $0 eq '-e' }
sub my_return {
my $val = shift;
if(is_cmd) {
print $val;
}
else {
return $val;
}
}
sub xsinit {
my($file, $std, $mods) = @_;
my($fh,@mods,%seen);
$file ||= "perlxsi.c";
my $xsinit_proto = "pTHX";
if (@_) {
@mods = @$mods if $mods;
}
else {
require Getopt::Std;
Getopt::Std::getopts('o:s:');
$file = $opt_o if defined $opt_o;
$std = $opt_s if defined $opt_s;
@mods = @ARGV;
}
$std = 1 unless scalar @mods;
if ($file eq "STDOUT") {
$fh = \*STDOUT;
}
else {
open $fh, '>', $file
or die "Can't open '$file': $!";
}
push(@mods, static_ext()) if defined $std;
@mods = grep(!$seen{$_}++, @mods);
print $fh &xsi_header();
print $fh "\nEXTERN_C void xs_init ($xsinit_proto);\n\n";
print $fh &xsi_protos(@mods);
print $fh "\nEXTERN_C void\nxs_init($xsinit_proto)\n{\n";
print $fh &xsi_body(@mods);
print $fh "}\n";
}
sub xsi_header {
return <<EOF;
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
EOF
}
sub xsi_protos {
my @exts = @_;
my %seen;
my $retval = '';
foreach my $cname (canon('__', @exts)) {
my $ccode = "EXTERN_C void boot_${cname} (pTHX_ CV* cv);\n";
$retval .= $ccode
unless $seen{$ccode}++;
}
return $retval;
}
sub xsi_body {
my @exts = @_;
my %seen;
my $retval;
$retval .= " static const char file[] = __FILE__;\n"
if @exts;
$retval .= <<'EOT';
dXSUB_SYS;
PERL_UNUSED_CONTEXT;
EOT
$retval .= "\n"
if @exts;
foreach my $pname (canon('/', @exts)) {
next
if $seen{$pname}++;
(my $mname = $pname) =~ s!/!::!g;
(my $cname = $pname) =~ s!/!__!g;
my $fname;
if ($pname eq 'DynaLoader'){
# Must NOT install 'DynaLoader::boot_DynaLoader' as 'bootstrap'!
# boot_DynaLoader is called directly in DynaLoader.pm
$retval .= " /* DynaLoader is a special case */\n";
$fname = "${mname}::boot_DynaLoader";
} else {
$fname = "${mname}::bootstrap";
}
$retval .= " newXS(\"$fname\", boot_${cname}, file);\n"
}
return $retval;
}
sub static_ext {
@Extensions = ('DynaLoader', sort $Config{static_ext} =~ /(\S+)/g)
unless @Extensions;
@Extensions;
}
sub _escape {
my $arg = shift;
return $$arg if $^O eq 'VMS'; # parens legal in qualifier lists
$$arg =~ s/([\(\)])/\\$1/g;
}
sub _ldflags {
my $ldflags = $Config{ldflags};
_escape(\$ldflags);
return $ldflags;
}
sub _ccflags {
my $ccflags = $Config{ccflags};
_escape(\$ccflags);
return $ccflags;
}
sub _ccdlflags {
my $ccdlflags = $Config{ccdlflags};
_escape(\$ccdlflags);
return $ccdlflags;
}
sub ldopts {
require ExtUtils::MakeMaker;
require ExtUtils::Liblist;
my($std,$mods,$link_args,$path) = @_;
my(@mods,@link_args,@argv);
my($dllib,$config_libs,@potential_libs,@path);
local($") = ' ' unless $" eq ' ';
if (scalar @_) {
@link_args = @$link_args if $link_args;
@mods = @$mods if $mods;
}
else {
@argv = @ARGV;
#hmm
while($_ = shift @argv) {
/^-std$/ && do { $std = 1; next; };
/^--$/ && do { @link_args = @argv; last; };
/^-I(.*)/ && do { $path = $1 || shift @argv; next; };
push(@mods, $_);
}
}
$std = 1 unless scalar @link_args;
my $sep = $Config{path_sep} || ':';
@path = $path ? split(/\Q$sep/, $path) : @INC;
push(@potential_libs, @link_args) if scalar @link_args;
# makemaker includes std libs on windows by default
if ($^O ne 'MSWin32' and defined($std)) {
push(@potential_libs, $Config{perllibs});
}
push(@mods, static_ext()) if $std;
my($mod,@ns,$root,$sub,$extra,$archive,@archives);
print STDERR "Searching (@path) for archives\n" if $Verbose;
foreach $mod (@mods) {
@ns = split(/::|\/|\\/, $mod);
$sub = $ns[-1];
$root = File::Spec->catdir(@ns);
print STDERR "searching for '$sub${lib_ext}'\n" if $Verbose;
foreach (@path) {
next unless -e ($archive = File::Spec->catdir($_,"auto",$root,"$sub$lib_ext"));
push @archives, $archive;
if(-e ($extra = File::Spec->catdir($_,"auto",$root,"extralibs.ld"))) {
local(*FH);
if(open(FH, '<', $extra)) {
my($libs) = <FH>; chomp $libs;
push @potential_libs, split /\s+/, $libs;
}
else {
warn "Couldn't open '$extra'";
}
}
last;
}
}
#print STDERR "\@potential_libs = @potential_libs\n";
my $libperl;
if ($^O eq 'MSWin32') {
$libperl = $Config{libperl};
}
elsif ($^O eq 'os390' && $Config{usedl}) {
# Nothing for OS/390 (z/OS) dynamic.
} else {
$libperl = (grep(/^-l\w*perl\w*$/, @link_args))[0]
|| ($Config{libperl} =~ /^lib(\w+)(\Q$lib_ext\E|\.\Q$Config{dlext}\E)$/
? "-l$1" : '')
|| "-lperl";
}
my $lpath = File::Spec->catdir($Config{archlibexp}, 'CORE');
$lpath = qq["$lpath"] if $^O eq 'MSWin32';
my($extralibs, $bsloadlibs, $ldloadlibs, $ld_run_path) =
MM->ext(join ' ', "-L$lpath", $libperl, @potential_libs);
my $ld_or_bs = $bsloadlibs || $ldloadlibs;
print STDERR "bs: $bsloadlibs ** ld: $ldloadlibs" if $Verbose;
my $ccdlflags = _ccdlflags();
my $ldflags = _ldflags();
my $linkage = "$ccdlflags $ldflags @archives $ld_or_bs";
print STDERR "ldopts: '$linkage'\n" if $Verbose;
return $linkage if scalar @_;
my_return("$linkage\n");
}
sub ccflags {
my $ccflags = _ccflags();
my_return(" $ccflags ");
}
sub ccdlflags {
my $ccdlflags = _ccdlflags();
my_return(" $ccdlflags ");
}
sub perl_inc {
my $dir = File::Spec->catdir($Config{archlibexp}, 'CORE');
$dir = qq["$dir"] if $^O eq 'MSWin32';
my_return(" -I$dir ");
}
sub ccopts {
ccflags . perl_inc;
}
sub canon {
my($as, @ext) = @_;
foreach(@ext) {
# might be X::Y or lib/auto/X/Y/Y.a
next
if s!::!/!g;
s!^(?:lib|ext|dist|cpan)/(?:auto/)?!!;
s!/\w+\.\w+$!!;
}
if ($as ne '/') {
s!/!$as!g
foreach @ext;
}
@ext;
}
__END__
=head1 NAME
ExtUtils::Embed - Utilities for embedding Perl in C/C++ applications
=head1 SYNOPSIS
perl -MExtUtils::Embed -e xsinit
perl -MExtUtils::Embed -e ccopts
perl -MExtUtils::Embed -e ldopts
=head1 DESCRIPTION
C<ExtUtils::Embed> provides utility functions for embedding a Perl interpreter
and extensions in your C/C++ applications.
Typically, an application F<Makefile> will invoke C<ExtUtils::Embed>
functions while building your application.
=head1 @EXPORT
C<ExtUtils::Embed> exports the following functions:
xsinit(), ldopts(), ccopts(), perl_inc(), ccflags(),
ccdlflags(), xsi_header(), xsi_protos(), xsi_body()
=head1 FUNCTIONS
=over 4
=item xsinit()
Generate C/C++ code for the XS initializer function.
When invoked as C<`perl -MExtUtils::Embed -e xsinit --`>
the following options are recognized:
B<-o> E<lt>output filenameE<gt> (Defaults to B<perlxsi.c>)
B<-o STDOUT> will print to STDOUT.
B<-std> (Write code for extensions that are linked with the current Perl.)
Any additional arguments are expected to be names of modules
to generate code for.
When invoked with parameters the following are accepted and optional:
C<xsinit($filename,$std,[@modules])>
Where,
B<$filename> is equivalent to the B<-o> option.
B<$std> is boolean, equivalent to the B<-std> option.
B<[@modules]> is an array ref, same as additional arguments mentioned above.
=item Examples
perl -MExtUtils::Embed -e xsinit -- -o xsinit.c Socket
This will generate code with an C<xs_init> function that glues the perl C<Socket::bootstrap> function
to the C C<boot_Socket> function and writes it to a file named F<xsinit.c>.
Note that L<DynaLoader> is a special case where it must call C<boot_DynaLoader> directly.
perl -MExtUtils::Embed -e xsinit
This will generate code for linking with C<DynaLoader> and
each static extension found in C<$Config{static_ext}>.
The code is written to the default file name F<perlxsi.c>.
perl -MExtUtils::Embed -e xsinit -- -o xsinit.c \
-std DBI DBD::Oracle
Here, code is written for all the currently linked extensions along with code
for C<DBI> and C<DBD::Oracle>.
If you have a working C<DynaLoader> then there is rarely any need to statically link in any
other extensions.
=item ldopts()
Output arguments for linking the Perl library and extensions to your
application.
When invoked as C<`perl -MExtUtils::Embed -e ldopts --`>
the following options are recognized:
B<-std>
Output arguments for linking the Perl library and any extensions linked
with the current Perl.
B<-I> E<lt>path1:path2E<gt>
Search path for ModuleName.a archives.
Default path is C<@INC>.
Library archives are expected to be found as
F</some/path/auto/ModuleName/ModuleName.a>
For example, when looking for F<Socket.a> relative to a search path,
we should find F<auto/Socket/Socket.a>
When looking for C<DBD::Oracle> relative to a search path,
we should find F<auto/DBD/Oracle/Oracle.a>
Keep in mind that you can always supply F</my/own/path/ModuleName.a>
as an additional linker argument.
B<--> E<lt>list of linker argsE<gt>
Additional linker arguments to be considered.
Any additional arguments found before the B<--> token
are expected to be names of modules to generate code for.
When invoked with parameters the following are accepted and optional:
C<ldopts($std,[@modules],[@link_args],$path)>
Where:
B<$std> is boolean, equivalent to the B<-std> option.
B<[@modules]> is equivalent to additional arguments found before the B<--> token.
B<[@link_args]> is equivalent to arguments found after the B<--> token.
B<$path> is equivalent to the B<-I> option.
In addition, when ldopts is called with parameters, it will return the argument string
rather than print it to STDOUT.
=item Examples
perl -MExtUtils::Embed -e ldopts
This will print arguments for linking with C<libperl> and
extensions found in C<$Config{static_ext}>. This includes libraries
found in C<$Config{libs}> and the first ModuleName.a library
for each extension that is found by searching C<@INC> or the path
specified by the B<-I> option.
In addition, when ModuleName.a is found, additional linker arguments
are picked up from the F<extralibs.ld> file in the same directory.
perl -MExtUtils::Embed -e ldopts -- -std Socket
This will do the same as the above example, along with printing additional
arguments for linking with the C<Socket> extension.
perl -MExtUtils::Embed -e ldopts -- -std Msql -- \
-L/usr/msql/lib -lmsql
Any arguments after the second '--' token are additional linker
arguments that will be examined for potential conflict. If there is no
conflict, the additional arguments will be part of the output.
=item perl_inc()
For including perl header files this function simply prints:
-I$Config{archlibexp}/CORE
So, rather than having to say:
perl -MConfig -e 'print "-I$Config{archlibexp}/CORE"'
Just say:
perl -MExtUtils::Embed -e perl_inc
=item ccflags(), ccdlflags()
These functions simply print $Config{ccflags} and $Config{ccdlflags}
=item ccopts()
This function combines C<perl_inc()>, C<ccflags()> and C<ccdlflags()> into one.
=item xsi_header()
This function simply returns a string defining the same C<EXTERN_C> macro as
F<perlmain.c> along with #including F<perl.h> and F<EXTERN.h>.
=item xsi_protos(@modules)
This function returns a string of C<boot_$ModuleName> prototypes for each @modules.
=item xsi_body(@modules)
This function returns a string of calls to C<newXS()> that glue the module I<bootstrap>
function to I<boot_ModuleName> for each @modules.
C<xsinit()> uses the xsi_* functions to generate most of its code.
=back
=head1 EXAMPLES
For examples on how to use C<ExtUtils::Embed> for building C/C++ applications
with embedded perl, see L<perlembed>.
=head1 SEE ALSO
L<perlembed>
=head1 AUTHOR
Doug MacEachern E<lt>C<dougm@osf.org>E<gt>
Based on ideas from Tim Bunce E<lt>C<Tim.Bunce@ig.co.uk>E<gt> and
F<minimod.pl> by Andreas Koenig E<lt>C<k@anna.in-berlin.de>E<gt> and Tim Bunce.
=cut

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,469 @@
use strict;
package ExtUtils::Installed;
#use warnings; # XXX requires 5.6
use Carp qw();
use ExtUtils::Packlist;
use ExtUtils::MakeMaker;
use Config;
use File::Find;
use File::Basename;
use File::Spec;
my $Is_VMS = $^O eq 'VMS';
my $DOSISH = ($^O =~ /^(MSWin\d\d|os2|dos|mint)$/);
require VMS::Filespec if $Is_VMS;
our $VERSION = '2.22';
$VERSION = eval $VERSION;
sub _is_prefix {
my ($self, $path, $prefix) = @_;
return unless defined $prefix && defined $path;
if( $Is_VMS ) {
$prefix = VMS::Filespec::unixify($prefix);
$path = VMS::Filespec::unixify($path);
}
# Unix path normalization.
$prefix = File::Spec->canonpath($prefix);
return 1 if substr($path, 0, length($prefix)) eq $prefix;
if ($DOSISH) {
$path =~ s|\\|/|g;
$prefix =~ s|\\|/|g;
return 1 if $path =~ m{^\Q$prefix\E}i;
}
return(0);
}
sub _is_doc {
my ($self, $path) = @_;
my $man1dir = $self->{':private:'}{Config}{man1direxp};
my $man3dir = $self->{':private:'}{Config}{man3direxp};
return(($man1dir && $self->_is_prefix($path, $man1dir))
||
($man3dir && $self->_is_prefix($path, $man3dir))
? 1 : 0)
}
sub _is_type {
my ($self, $path, $type) = @_;
return 1 if $type eq "all";
return($self->_is_doc($path)) if $type eq "doc";
my $conf= $self->{':private:'}{Config};
if ($type eq "prog") {
return($self->_is_prefix($path, $conf->{prefix} || $conf->{prefixexp})
&& !($self->_is_doc($path)) ? 1 : 0);
}
return(0);
}
sub _is_under {
my ($self, $path, @under) = @_;
$under[0] = "" if (! @under);
foreach my $dir (@under) {
return(1) if ($self->_is_prefix($path, $dir));
}
return(0);
}
sub _fix_dirs {
my ($self, @dirs)= @_;
# File::Find does not know how to deal with VMS filepaths.
if( $Is_VMS ) {
$_ = VMS::Filespec::unixify($_)
for @dirs;
}
if ($DOSISH) {
s|\\|/|g for @dirs;
}
return wantarray ? @dirs : $dirs[0];
}
sub _make_entry {
my ($self, $module, $packlist_file, $modfile)= @_;
my $data= {
module => $module,
packlist => scalar(ExtUtils::Packlist->new($packlist_file)),
packlist_file => $packlist_file,
};
if (!$modfile) {
$data->{version} = $self->{':private:'}{Config}{version};
} else {
$data->{modfile} = $modfile;
# Find the top-level module file in @INC
$data->{version} = '';
foreach my $dir (@{$self->{':private:'}{INC}}) {
my $p = File::Spec->catfile($dir, $modfile);
if (-r $p) {
$module = _module_name($p, $module) if $Is_VMS;
$data->{version} = MM->parse_version($p);
$data->{version_from} = $p;
$data->{packlist_valid} = exists $data->{packlist}{$p};
last;
}
}
}
$self->{$module}= $data;
}
our $INSTALLED;
sub new {
my ($class) = shift(@_);
$class = ref($class) || $class;
my %args = @_;
return $INSTALLED if $INSTALLED and ($args{default_get} || $args{default});
my $self = bless {}, $class;
$INSTALLED= $self if $args{default_set} || $args{default};
if ($args{config_override}) {
eval {
$self->{':private:'}{Config} = { %{$args{config_override}} };
} or Carp::croak(
"The 'config_override' parameter must be a hash reference."
);
}
else {
$self->{':private:'}{Config} = \%Config;
}
for my $tuple ([inc_override => INC => [ @INC ] ],
[ extra_libs => EXTRA => [] ])
{
my ($arg,$key,$val)=@$tuple;
if ( $args{$arg} ) {
eval {
$self->{':private:'}{$key} = [ @{$args{$arg}} ];
} or Carp::croak(
"The '$arg' parameter must be an array reference."
);
}
elsif ($val) {
$self->{':private:'}{$key} = $val;
}
}
{
my %dupe;
@{$self->{':private:'}{LIBDIRS}} =
grep { $_ ne '.' || ! $args{skip_cwd} }
grep { -e $_ && !$dupe{$_}++ }
@{$self->{':private:'}{EXTRA}}, @{$self->{':private:'}{INC}};
}
my @dirs= $self->_fix_dirs(@{$self->{':private:'}{LIBDIRS}});
# Read the core packlist
my $archlib = $self->_fix_dirs($self->{':private:'}{Config}{archlibexp});
$self->_make_entry("Perl",File::Spec->catfile($archlib, '.packlist'));
my $root;
# Read the module packlists
my $sub = sub {
# Only process module .packlists
return if $_ ne ".packlist" || $File::Find::dir eq $archlib;
# Hack of the leading bits of the paths & convert to a module name
my $module = $File::Find::name;
my $found = $module =~ s!^.*?/auto/(.*)/.packlist!$1!s
or do {
# warn "Woah! \$_=$_\n\$module=$module\n\$File::Find::dir=$File::Find::dir\n",
# join ("\n",@dirs);
return;
};
my $modfile = "$module.pm";
$module =~ s!/!::!g;
return if $self->{$module}; #shadowing?
$self->_make_entry($module,$File::Find::name,$modfile);
};
while (@dirs) {
$root= shift @dirs;
next if !-d $root;
find($sub,$root);
}
return $self;
}
# VMS's non-case preserving file-system means the package name can't
# be reconstructed from the filename.
sub _module_name {
my($file, $orig_module) = @_;
my $module = '';
if (open PACKFH, $file) {
while (<PACKFH>) {
if (/package\s+(\S+)\s*;/) {
my $pack = $1;
# Make a sanity check, that lower case $module
# is identical to lowercase $pack before
# accepting it
if (lc($pack) eq lc($orig_module)) {
$module = $pack;
last;
}
}
}
close PACKFH;
}
print STDERR "Couldn't figure out the package name for $file\n"
unless $module;
return $module;
}
sub modules {
my ($self) = @_;
$self= $self->new(default=>1) if !ref $self;
# Bug/feature of sort in scalar context requires this.
return wantarray
? sort grep { not /^:private:$/ } keys %$self
: grep { not /^:private:$/ } keys %$self;
}
sub files {
my ($self, $module, $type, @under) = @_;
$self= $self->new(default=>1) if !ref $self;
# Validate arguments
Carp::croak("$module is not installed") if (! exists($self->{$module}));
$type = "all" if (! defined($type));
Carp::croak('type must be "all", "prog" or "doc"')
if ($type ne "all" && $type ne "prog" && $type ne "doc");
my (@files);
foreach my $file (keys(%{$self->{$module}{packlist}})) {
push(@files, $file)
if ($self->_is_type($file, $type) &&
$self->_is_under($file, @under));
}
return(@files);
}
sub directories {
my ($self, $module, $type, @under) = @_;
$self= $self->new(default=>1) if !ref $self;
my (%dirs);
foreach my $file ($self->files($module, $type, @under)) {
$dirs{dirname($file)}++;
}
return sort keys %dirs;
}
sub directory_tree {
my ($self, $module, $type, @under) = @_;
$self= $self->new(default=>1) if !ref $self;
my (%dirs);
foreach my $dir ($self->directories($module, $type, @under)) {
$dirs{$dir}++;
my ($last) = ("");
while ($last ne $dir) {
$last = $dir;
$dir = dirname($dir);
last if !$self->_is_under($dir, @under);
$dirs{$dir}++;
}
}
return(sort(keys(%dirs)));
}
sub validate {
my ($self, $module, $remove) = @_;
$self= $self->new(default=>1) if !ref $self;
Carp::croak("$module is not installed") if (! exists($self->{$module}));
return($self->{$module}{packlist}->validate($remove));
}
sub packlist {
my ($self, $module) = @_;
$self= $self->new(default=>1) if !ref $self;
Carp::croak("$module is not installed") if (! exists($self->{$module}));
return($self->{$module}{packlist});
}
sub version {
my ($self, $module) = @_;
$self= $self->new(default=>1) if !ref $self;
Carp::croak("$module is not installed") if (! exists($self->{$module}));
return($self->{$module}{version});
}
sub _debug_dump {
my ($self, $module) = @_;
$self= $self->new(default=>1) if !ref $self;
local $self->{":private:"}{Config};
require Data::Dumper;
print Data::Dumper->new([$self])->Sortkeys(1)->Indent(1)->Dump();
}
1;
__END__
=head1 NAME
ExtUtils::Installed - Inventory management of installed modules
=head1 SYNOPSIS
use ExtUtils::Installed;
my ($inst) = ExtUtils::Installed->new( skip_cwd => 1 );
my (@modules) = $inst->modules();
my (@missing) = $inst->validate("DBI");
my $all_files = $inst->files("DBI");
my $files_below_usr_local = $inst->files("DBI", "all", "/usr/local");
my $all_dirs = $inst->directories("DBI");
my $dirs_below_usr_local = $inst->directory_tree("DBI", "prog");
my $packlist = $inst->packlist("DBI");
=head1 DESCRIPTION
ExtUtils::Installed provides a standard way to find out what core and module
files have been installed. It uses the information stored in .packlist files
created during installation to provide this information. In addition it
provides facilities to classify the installed files and to extract directory
information from the .packlist files.
=head1 USAGE
The new() function searches for all the installed .packlists on the system, and
stores their contents. The .packlists can be queried with the functions
described below. Where it searches by default is determined by the settings found
in C<%Config::Config>, and what the value is of the PERL5LIB environment variable.
=head1 METHODS
Unless specified otherwise all method can be called as class methods, or as object
methods. If called as class methods then the "default" object will be used, and if
necessary created using the current processes %Config and @INC. See the
'default' option to new() for details.
=over 4
=item new()
This takes optional named parameters. Without parameters, this
searches for all the installed .packlists on the system using
information from C<%Config::Config> and the default module search
paths C<@INC>. The packlists are read using the
L<ExtUtils::Packlist> module.
If the named parameter C<skip_cwd> is true, the current directory C<.> will
be stripped from C<@INC> before searching for .packlists. This keeps
ExtUtils::Installed from finding modules installed in other perls that
happen to be located below the current directory.
If the named parameter C<config_override> is specified,
it should be a reference to a hash which contains all information
usually found in C<%Config::Config>. For example, you can obtain
the configuration information for a separate perl installation and
pass that in.
my $yoda_cfg = get_fake_config('yoda');
my $yoda_inst =
ExtUtils::Installed->new(config_override=>$yoda_cfg);
Similarly, the parameter C<inc_override> may be a reference to an
array which is used in place of the default module search paths
from C<@INC>.
use Config;
my @dirs = split(/\Q$Config{path_sep}\E/, $ENV{PERL5LIB});
my $p5libs = ExtUtils::Installed->new(inc_override=>\@dirs);
B<Note>: You probably do not want to use these options alone, almost always
you will want to set both together.
The parameter C<extra_libs> can be used to specify B<additional> paths to
search for installed modules. For instance
my $installed =
ExtUtils::Installed->new(extra_libs=>["/my/lib/path"]);
This should only be necessary if F</my/lib/path> is not in PERL5LIB.
Finally there is the 'default', and the related 'default_get' and 'default_set'
options. These options control the "default" object which is provided by the
class interface to the methods. Setting C<default_get> to true tells the constructor
to return the default object if it is defined. Setting C<default_set> to true tells
the constructor to make the default object the constructed object. Setting the
C<default> option is like setting both to true. This is used primarily internally
and probably isn't interesting to any real user.
=item modules()
This returns a list of the names of all the installed modules. The perl 'core'
is given the special name 'Perl'.
=item files()
This takes one mandatory parameter, the name of a module. It returns a list of
all the filenames from the package. To obtain a list of core perl files, use
the module name 'Perl'. Additional parameters are allowed. The first is one
of the strings "prog", "doc" or "all", to select either just program files,
just manual files or all files. The remaining parameters are a list of
directories. The filenames returned will be restricted to those under the
specified directories.
=item directories()
This takes one mandatory parameter, the name of a module. It returns a list of
all the directories from the package. Additional parameters are allowed. The
first is one of the strings "prog", "doc" or "all", to select either just
program directories, just manual directories or all directories. The remaining
parameters are a list of directories. The directories returned will be
restricted to those under the specified directories. This method returns only
the leaf directories that contain files from the specified module.
=item directory_tree()
This is identical in operation to directories(), except that it includes all the
intermediate directories back up to the specified directories.
=item validate()
This takes one mandatory parameter, the name of a module. It checks that all
the files listed in the modules .packlist actually exist, and returns a list of
any missing files. If an optional second argument which evaluates to true is
given any missing files will be removed from the .packlist
=item packlist()
This returns the ExtUtils::Packlist object for the specified module.
=item version()
This returns the version number for the specified module.
=back
=head1 EXAMPLE
See the example in L<ExtUtils::Packlist>.
=head1 AUTHOR
Alan Burlison <Alan.Burlison@uk.sun.com>
=cut

View file

@ -0,0 +1,288 @@
package ExtUtils::Liblist;
use strict;
use warnings;
our $VERSION = '7.70';
$VERSION =~ tr/_//d;
use File::Spec;
require ExtUtils::Liblist::Kid;
our @ISA = qw(ExtUtils::Liblist::Kid File::Spec);
# Backwards compatibility with old interface.
sub ext {
goto &ExtUtils::Liblist::Kid::ext;
}
sub lsdir {
shift;
my $rex = qr/$_[1]/;
opendir my $dir_fh, $_[0];
my @out = grep /$rex/, readdir $dir_fh;
closedir $dir_fh;
return @out;
}
__END__
=head1 NAME
ExtUtils::Liblist - determine libraries to use and how to use them
=head1 SYNOPSIS
require ExtUtils::Liblist;
$MM->ext($potential_libs, $verbose, $need_names);
# Usually you can get away with:
ExtUtils::Liblist->ext($potential_libs, $verbose, $need_names)
=head1 DESCRIPTION
This utility takes a list of libraries in the form C<-llib1 -llib2
-llib3> and returns lines suitable for inclusion in an extension
Makefile. Extra library paths may be included with the form
C<-L/another/path> this will affect the searches for all subsequent
libraries.
It returns an array of four or five scalar values: EXTRALIBS,
BSLOADLIBS, LDLOADLIBS, LD_RUN_PATH, and, optionally, a reference to
the array of the filenames of actual libraries. Some of these don't
mean anything unless on Unix. See the details about those platform
specifics below. The list of the filenames is returned only if
$need_names argument is true.
Dependent libraries can be linked in one of three ways:
=over 2
=item * For static extensions
by the ld command when the perl binary is linked with the extension
library. See EXTRALIBS below.
=item * For dynamic extensions at build/link time
by the ld command when the shared object is built/linked. See
LDLOADLIBS below.
=item * For dynamic extensions at load time
by the DynaLoader when the shared object is loaded. See BSLOADLIBS
below.
=back
=head2 EXTRALIBS
List of libraries that need to be linked with when linking a perl
binary which includes this extension. Only those libraries that
actually exist are included. These are written to a file and used
when linking perl.
=head2 LDLOADLIBS and LD_RUN_PATH
List of those libraries which can or must be linked into the shared
library when created using ld. These may be static or dynamic
libraries. LD_RUN_PATH is a colon separated list of the directories
in LDLOADLIBS. It is passed as an environment variable to the process
that links the shared library.
=head2 BSLOADLIBS
List of those libraries that are needed but can be linked in
dynamically at run time on this platform. SunOS/Solaris does not need
this because ld records the information (from LDLOADLIBS) into the
object file. This list is used to create a .bs (bootstrap) file.
=head1 PORTABILITY
This module deals with a lot of system dependencies and has quite a
few architecture specific C<if>s in the code.
=head2 VMS implementation
The version of ext() which is executed under VMS differs from the
Unix-OS/2 version in several respects:
=over 2
=item *
Input library and path specifications are accepted with or without the
C<-l> and C<-L> prefixes used by Unix linkers. If neither prefix is
present, a token is considered a directory to search if it is in fact
a directory, and a library to search for otherwise. Authors who wish
their extensions to be portable to Unix or OS/2 should use the Unix
prefixes, since the Unix-OS/2 version of ext() requires them.
=item *
Wherever possible, shareable images are preferred to object libraries,
and object libraries to plain object files. In accordance with VMS
naming conventions, ext() looks for files named I<lib>shr and I<lib>rtl;
it also looks for I<lib>lib and libI<lib> to accommodate Unix conventions
used in some ported software.
=item *
For each library that is found, an appropriate directive for a linker options
file is generated. The return values are space-separated strings of
these directives, rather than elements used on the linker command line.
=item *
LDLOADLIBS contains both the libraries found based on C<$potential_libs> and
the CRTLs, if any, specified in Config.pm. EXTRALIBS contains just those
libraries found based on C<$potential_libs>. BSLOADLIBS and LD_RUN_PATH
are always empty.
=back
In addition, an attempt is made to recognize several common Unix library
names, and filter them out or convert them to their VMS equivalents, as
appropriate.
In general, the VMS version of ext() should properly handle input from
extensions originally designed for a Unix or VMS environment. If you
encounter problems, or discover cases where the search could be improved,
please let us know.
=head2 Win32 implementation
The version of ext() which is executed under Win32 differs from the
Unix-OS/2 version in several respects:
=over 2
=item *
If C<$potential_libs> is empty, the return value will be empty.
Otherwise, the libraries specified by C<$Config{perllibs}> (see Config.pm)
will be appended to the list of C<$potential_libs>. The libraries
will be searched for in the directories specified in C<$potential_libs>,
C<$Config{libpth}>, and in C<$Config{installarchlib}/CORE>.
For each library that is found, a space-separated list of fully qualified
library pathnames is generated.
=item *
Input library and path specifications are accepted with or without the
C<-l> and C<-L> prefixes used by Unix linkers.
An entry of the form C<-La:\foo> specifies the C<a:\foo> directory to look
for the libraries that follow.
An entry of the form C<-lfoo> specifies the library C<foo>, which may be
spelled differently depending on what kind of compiler you are using. If
you are using GCC, it gets translated to C<libfoo.a>, but for other win32
compilers, it becomes C<foo.lib>. If no files are found by those translated
names, one more attempt is made to find them using either C<foo.a> or
C<libfoo.lib>, depending on whether GCC or some other win32 compiler is
being used, respectively.
If neither the C<-L> or C<-l> prefix is present in an entry, the entry is
considered a directory to search if it is in fact a directory, and a
library to search for otherwise. The C<$Config{lib_ext}> suffix will
be appended to any entries that are not directories and don't already have
the suffix.
Note that the C<-L> and C<-l> prefixes are B<not required>, but authors
who wish their extensions to be portable to Unix or OS/2 should use the
prefixes, since the Unix-OS/2 version of ext() requires them.
=item *
Entries cannot be plain object files, as many Win32 compilers will
not handle object files in the place of libraries.
=item *
Entries in C<$potential_libs> beginning with a colon and followed by
alphanumeric characters are treated as flags. Unknown flags will be ignored.
An entry that matches C</:nodefault/i> disables the appending of default
libraries found in C<$Config{perllibs}> (this should be only needed very rarely).
An entry that matches C</:nosearch/i> disables all searching for
the libraries specified after it. Translation of C<-Lfoo> and
C<-lfoo> still happens as appropriate (depending on compiler being used,
as reflected by C<$Config{cc}>), but the entries are not verified to be
valid files or directories.
An entry that matches C</:search/i> reenables searching for
the libraries specified after it. You can put it at the end to
enable searching for default libraries specified by C<$Config{perllibs}>.
=item *
The libraries specified may be a mixture of static libraries and
import libraries (to link with DLLs). Since both kinds are used
pretty transparently on the Win32 platform, we do not attempt to
distinguish between them.
=item *
LDLOADLIBS and EXTRALIBS are always identical under Win32, and BSLOADLIBS
and LD_RUN_PATH are always empty (this may change in future).
=item *
You must make sure that any paths and path components are properly
surrounded with double-quotes if they contain spaces. For example,
C<$potential_libs> could be (literally):
"-Lc:\Program Files\vc\lib" msvcrt.lib "la test\foo bar.lib"
Note how the first and last entries are protected by quotes in order
to protect the spaces.
=item *
Since this module is most often used only indirectly from extension
C<Makefile.PL> files, here is an example C<Makefile.PL> entry to add
a library to the build process for an extension:
LIBS => ['-lgl']
When using GCC, that entry specifies that MakeMaker should first look
for C<libgl.a> (followed by C<gl.a>) in all the locations specified by
C<$Config{libpth}>.
When using a compiler other than GCC, the above entry will search for
C<gl.lib> (followed by C<libgl.lib>).
If the library happens to be in a location not in C<$Config{libpth}>,
you need:
LIBS => ['-Lc:\gllibs -lgl']
Here is a less often used example:
LIBS => ['-lgl', ':nosearch -Ld:\mesalibs -lmesa -luser32']
This specifies a search for library C<gl> as before. If that search
fails to find the library, it looks at the next item in the list. The
C<:nosearch> flag will prevent searching for the libraries that follow,
so it simply returns the value as C<-Ld:\mesalibs -lmesa -luser32>,
since GCC can use that value as is with its linker.
When using the Visual C compiler, the second item is returned as
C<-libpath:d:\mesalibs mesa.lib user32.lib>.
When using the Borland compiler, the second item is returned as
C<-Ld:\mesalibs mesa.lib user32.lib>, and MakeMaker takes care of
moving the C<-Ld:\mesalibs> to the correct place in the linker
command line.
=back
=head1 SEE ALSO
L<ExtUtils::MakeMaker>
=cut

View file

@ -0,0 +1,664 @@
package ExtUtils::Liblist::Kid;
# XXX Splitting this out into its own .pm is a temporary solution.
# This kid package is to be used by MakeMaker. It will not work if
# $self is not a Makemaker.
use 5.006;
# Broken out of MakeMaker from version 4.11
use strict;
use warnings;
our $VERSION = '7.70';
$VERSION =~ tr/_//d;
use ExtUtils::MakeMaker::Config;
use Cwd 'cwd';
use File::Basename;
use File::Spec;
sub ext {
if ( $^O eq 'VMS' ) { return &_vms_ext; }
elsif ( $^O eq 'MSWin32' ) { return &_win32_ext; }
else { return &_unix_os2_ext; }
}
sub _unix_os2_ext {
my ( $self, $potential_libs, $verbose, $give_libs ) = @_;
$verbose ||= 0;
if ( $^O =~ /os2|android/ and $Config{perllibs} ) {
# Dynamic libraries are not transitive, so we may need including
# the libraries linked against perl.dll/libperl.so again.
$potential_libs .= " " if $potential_libs;
$potential_libs .= $Config{perllibs};
}
return ( "", "", "", "", ( $give_libs ? [] : () ) ) unless $potential_libs;
warn "Potential libraries are '$potential_libs':\n" if $verbose;
my ( $so ) = $Config{so};
my ( $libs ) = defined $Config{perllibs} ? $Config{perllibs} : $Config{libs};
my $Config_libext = $Config{lib_ext} || ".a";
my $Config_dlext = $Config{dlext};
# compute $extralibs, $bsloadlibs and $ldloadlibs from
# $potential_libs
# this is a rewrite of Andy Dougherty's extliblist in perl
require Text::ParseWords;
my ( @searchpath ); # from "-L/path" entries in $potential_libs
my ( @libpath ) = Text::ParseWords::shellwords( $Config{'libpth'} || '' );
my ( @ldloadlibs, @bsloadlibs, @extralibs, @ld_run_path, %ld_run_path_seen );
my ( @libs, %libs_seen );
my ( $fullname, @fullname );
my ( $pwd ) = cwd(); # from Cwd.pm
my ( $found ) = 0;
if ($Config{gccversion}) {
chomp(my @incpath = grep s/^ //, grep { /^#include </ .. /^End of search / } `$Config{cc} -E -v - </dev/null 2>&1 >/dev/null`);
unshift @libpath, map { s{/include[^/]*}{/lib}; $_ } @incpath
}
@libpath = grep -d, @libpath;
if ( $^O eq 'darwin' or $^O eq 'next' ) {
# 'escape' Mach-O ld -framework and -F flags, so they aren't dropped later on
$potential_libs =~ s/(^|\s)(-(?:weak_|reexport_|lazy_)?framework)\s+(\S+)/$1-Wl,$2 -Wl,$3/g;
$potential_libs =~ s/(^|\s)(-F)\s*(\S+)/$1-Wl,$2 -Wl,$3/g;
}
foreach my $thislib ( Text::ParseWords::shellwords($potential_libs) ) {
my ( $custom_name ) = '';
# Handle possible linker path arguments.
if ( $thislib =~ s/^(-[LR]|-Wl,-R|-Wl,-rpath,)// ) { # save path flag type
my ( $ptype ) = $1;
unless ( -d $thislib ) {
warn "$ptype$thislib ignored, directory does not exist\n"
if $verbose;
next;
}
my ( $rtype ) = $ptype;
if ( ( $ptype eq '-R' ) or ( $ptype =~ m!^-Wl,-[Rr]! ) ) {
if ( $Config{'lddlflags'} =~ /-Wl,-[Rr]/ ) {
$rtype = '-Wl,-R';
}
elsif ( $Config{'lddlflags'} =~ /-R/ ) {
$rtype = '-R';
}
}
unless ( File::Spec->file_name_is_absolute( $thislib ) ) {
warn "Warning: $ptype$thislib changed to $ptype$pwd/$thislib\n";
$thislib = $self->catdir( $pwd, $thislib );
}
push( @searchpath, $thislib );
$thislib = qq{"$thislib"} if $thislib =~ / /; # protect spaces if there
push( @extralibs, "$ptype$thislib" );
push( @ldloadlibs, "$rtype$thislib" );
next;
}
if ( $thislib =~ m!^-Wl,! ) {
push( @extralibs, $thislib );
push( @ldloadlibs, $thislib );
next;
}
# Handle possible library arguments.
if ( $thislib =~ s/^-l(:)?// ) {
# Handle -l:foo.so, which means that the library will
# actually be called foo.so, not libfoo.so. This
# is used in Android by ExtUtils::Depends to allow one XS
# module to link to another.
$custom_name = $1 || '';
}
else {
warn "Unrecognized argument in LIBS ignored: '$thislib'\n";
next;
}
my ( $found_lib ) = 0;
foreach my $thispth ( @searchpath, @libpath ) {
# Try to find the full name of the library. We need this to
# determine whether it's a dynamically-loadable library or not.
# This tends to be subject to various os-specific quirks.
# For gcc-2.6.2 on linux (March 1995), DLD can not load
# .sa libraries, with the exception of libm.sa, so we
# deliberately skip them.
if ((@fullname =
$self->lsdir($thispth, "^\Qlib$thislib.$so.\E[0-9]+")) ||
(@fullname =
$self->lsdir($thispth, "^\Qlib$thislib.\E[0-9]+\Q\.$so"))) {
# Take care that libfoo.so.10 wins against libfoo.so.9.
# Compare two libraries to find the most recent version
# number. E.g. if you have libfoo.so.9.0.7 and
# libfoo.so.10.1, first convert all digits into two
# decimal places. Then we'll add ".00" to the shorter
# strings so that we're comparing strings of equal length
# Thus we'll compare libfoo.so.09.07.00 with
# libfoo.so.10.01.00. Some libraries might have letters
# in the version. We don't know what they mean, but will
# try to skip them gracefully -- we'll set any letter to
# '0'. Finally, sort in reverse so we can take the
# first element.
#TODO: iterate through the directory instead of sorting
$fullname = "$thispth/" . (
sort {
my ( $ma ) = $a;
my ( $mb ) = $b;
$ma =~ tr/A-Za-z/0/s;
$ma =~ s/\b(\d)\b/0$1/g;
$mb =~ tr/A-Za-z/0/s;
$mb =~ s/\b(\d)\b/0$1/g;
while ( length( $ma ) < length( $mb ) ) { $ma .= ".00"; }
while ( length( $mb ) < length( $ma ) ) { $mb .= ".00"; }
# Comparison deliberately backwards
$mb cmp $ma;
} @fullname
)[0];
}
elsif ( -f ( $fullname = "$thispth/lib$thislib.$so" )
&& ( ( $Config{'dlsrc'} ne "dl_dld.xs" ) || ( $thislib eq "m" ) ) )
{
}
elsif (-f ( $fullname = "$thispth/lib${thislib}_s$Config_libext" )
&& ( $Config{'archname'} !~ /RM\d\d\d-svr4/ )
&& ( $thislib .= "_s" ) )
{ # we must explicitly use _s version
}
elsif ( -f ( $fullname = "$thispth/lib$thislib$Config_libext" ) ) {
}
elsif ( defined( $Config_dlext )
&& -f ( $fullname = "$thispth/lib$thislib.$Config_dlext" ) )
{
}
elsif ( $^O eq 'darwin' && require DynaLoader && defined &DynaLoader::dl_load_file
&& DynaLoader::dl_load_file( $fullname = "$thispth/lib$thislib.$so", 0 ) )
{
}
elsif ( -f ( $fullname = "$thispth/$thislib$Config_libext" ) ) {
}
elsif ( -f ( $fullname = "$thispth/lib$thislib.dll$Config_libext" ) ) {
}
elsif ( $^O eq 'cygwin' && -f ( $fullname = "$thispth/$thislib.dll" ) ) {
}
elsif ( -f ( $fullname = "$thispth/Slib$thislib$Config_libext" ) ) {
}
elsif ($^O eq 'dgux'
&& -l ( $fullname = "$thispth/lib$thislib$Config_libext" )
&& readlink( $fullname ) =~ /^elink:/s )
{
# Some of DG's libraries look like misconnected symbolic
# links, but development tools can follow them. (They
# look like this:
#
# libm.a -> elink:${SDE_PATH:-/usr}/sde/\
# ${TARGET_BINARY_INTERFACE:-m88kdgux}/usr/lib/libm.a
#
# , the compilation tools expand the environment variables.)
}
elsif ( $custom_name && -f ( $fullname = "$thispth/$thislib" ) ) {
}
else {
warn "$thislib not found in $thispth\n" if $verbose;
next;
}
warn "'-l$thislib' found at $fullname\n" if $verbose;
push @libs, $fullname unless $libs_seen{$fullname}++;
$found++;
$found_lib++;
# Now update library lists
# what do we know about this library...
# "Sounds like we should always assume it's a dynamic library on AIX."
my $is_dyna = $^O eq 'aix' ? 1 : ( $fullname !~ /\Q$Config_libext\E\z/ );
my $in_perl = ( $libs =~ /\B-l:?\Q${thislib}\E\b/s );
# include the path to the lib once in the dynamic linker path
# but only if it is a dynamic lib and not in Perl itself
my ( $fullnamedir ) = dirname( $fullname );
push @ld_run_path, $fullnamedir
if $is_dyna
&& !$in_perl
&& !$ld_run_path_seen{$fullnamedir}++;
# Do not add it into the list if it is already linked in
# with the main perl executable.
# We have to special-case the NeXT, because math and ndbm
# are both in libsys_s
unless (
$in_perl
|| ( $Config{'osname'} eq 'next'
&& ( $thislib eq 'm' || $thislib eq 'ndbm' ) )
)
{
push( @extralibs, "-l$custom_name$thislib" );
}
# We might be able to load this archive file dynamically
if ( ( $Config{'dlsrc'} =~ /dl_next/ && $Config{'osvers'} lt '4_0' )
|| ( $Config{'dlsrc'} =~ /dl_dld/ ) )
{
# We push -l$thislib instead of $fullname because
# it avoids hardwiring a fixed path into the .bs file.
# Mkbootstrap will automatically add dl_findfile() to
# the .bs file if it sees a name in the -l format.
# USE THIS, when dl_findfile() is fixed:
# push(@bsloadlibs, "-l$thislib");
# OLD USE WAS while checking results against old_extliblist
push( @bsloadlibs, "$fullname" );
}
else {
if ( $is_dyna ) {
# For SunOS4, do not add in this shared library if
# it is already linked in the main perl executable
push( @ldloadlibs, "-l$custom_name$thislib" )
unless ( $in_perl and $^O eq 'sunos' );
}
else {
push( @ldloadlibs, "-l$custom_name$thislib" );
}
}
last; # found one here so don't bother looking further
}
warn "Warning (mostly harmless): " . "No library found for -l$thislib\n"
unless $found_lib > 0;
}
unless ( $found ) {
return ( '', '', '', '', ( $give_libs ? \@libs : () ) );
}
else {
return ( "@extralibs", "@bsloadlibs", "@ldloadlibs", join( ":", @ld_run_path ), ( $give_libs ? \@libs : () ) );
}
}
sub _win32_ext {
require Text::ParseWords;
my ( $self, $potential_libs, $verbose, $give_libs ) = @_;
$verbose ||= 0;
# If user did not supply a list, we punt.
# (caller should probably use the list in $Config{libs})
return ( "", "", "", "", ( $give_libs ? [] : () ) ) unless $potential_libs;
# TODO: make this use MM_Win32.pm's compiler detection
my %libs_seen;
my @extralibs;
my $cc = $Config{cc} || '';
my $VC = $cc =~ /\bcl\b/i;
my $GC = $cc =~ /\bgcc\b/i;
my $libext = _win32_lib_extensions();
my @searchpath = ( '' ); # from "-L/path" entries in $potential_libs
my @libpath = _win32_default_search_paths( $VC, $GC );
my $pwd = cwd(); # from Cwd.pm
my $search = 1;
# compute @extralibs from $potential_libs
my @lib_search_list = _win32_make_lib_search_list( $potential_libs, $verbose );
for ( @lib_search_list ) {
my $thislib = $_;
# see if entry is a flag
if ( /^:\w+$/ ) {
$search = 0 if lc eq ':nosearch';
$search = 1 if lc eq ':search';
_debug( "Ignoring unknown flag '$thislib'\n", $verbose ) if !/^:(no)?(search|default)$/i;
next;
}
# if searching is disabled, do compiler-specific translations
unless ( $search ) {
s/^-l(.+)$/$1.lib/ unless $GC;
s/^-L/-libpath:/ if $VC;
push( @extralibs, $_ );
next;
}
# handle possible linker path arguments
if ( s/^-L// and not -d ) {
_debug( "$thislib ignored, directory does not exist\n", $verbose );
next;
}
elsif ( -d ) {
unless ( File::Spec->file_name_is_absolute( $_ ) ) {
warn "Warning: '$thislib' changed to '-L$pwd/$_'\n";
$_ = $self->catdir( $pwd, $_ );
}
push( @searchpath, $_ );
next;
}
my @paths = ( @searchpath, @libpath );
my ( $fullname, $path ) = _win32_search_file( $thislib, $libext, \@paths, $verbose, $GC );
if ( !$fullname ) {
warn "Warning (mostly harmless): No library found for $thislib\n";
next;
}
_debug( "'$thislib' found as '$fullname'\n", $verbose );
push( @extralibs, $fullname );
$libs_seen{$fullname} = 1 if $path; # why is this a special case?
}
my @libs = sort keys %libs_seen;
return ( '', '', '', '', ( $give_libs ? \@libs : () ) ) unless @extralibs;
# make sure paths with spaces are properly quoted
@extralibs = map { qq["$_"] } @extralibs;
@libs = map { qq["$_"] } @libs;
my $lib = join( ' ', @extralibs );
# normalize back to backward slashes (to help braindead tools)
# XXX this may break equally braindead GNU tools that don't understand
# backslashes, either. Seems like one can't win here. Cursed be CP/M.
$lib =~ s,/,\\,g;
_debug( "Result: $lib\n", $verbose );
wantarray ? ( $lib, '', $lib, '', ( $give_libs ? \@libs : () ) ) : $lib;
}
sub _win32_make_lib_search_list {
my ( $potential_libs, $verbose ) = @_;
# If Config.pm defines a set of default libs, we always
# tack them on to the user-supplied list, unless the user
# specified :nodefault
my $libs = $Config{'perllibs'};
$potential_libs = join( ' ', $potential_libs, $libs ) if $libs and $potential_libs !~ /:nodefault/i;
_debug( "Potential libraries are '$potential_libs':\n", $verbose );
$potential_libs =~ s,\\,/,g; # normalize to forward slashes
my @list = Text::ParseWords::quotewords( '\s+', 0, $potential_libs );
return @list;
}
sub _win32_default_search_paths {
my ( $VC, $GC ) = @_;
my $libpth = $Config{'libpth'} || '';
$libpth =~ s,\\,/,g; # normalize to forward slashes
my @libpath = Text::ParseWords::quotewords( '\s+', 0, $libpth );
push @libpath, "$Config{installarchlib}/CORE"; # add "$Config{installarchlib}/CORE" to default search path
push @libpath, split /;/, $ENV{LIB} if $VC and $ENV{LIB};
push @libpath, split /;/, $ENV{LIBRARY_PATH} if $GC and $ENV{LIBRARY_PATH};
return @libpath;
}
sub _win32_search_file {
my ( $thislib, $libext, $paths, $verbose, $GC ) = @_;
my @file_list = _win32_build_file_list( $thislib, $GC, $libext );
for my $lib_file ( @file_list ) {
for my $path ( @{$paths} ) {
my $fullname = $lib_file;
$fullname = "$path\\$fullname" if $path;
return ( $fullname, $path ) if -f $fullname;
_debug( "'$thislib' not found as '$fullname'\n", $verbose );
}
}
return;
}
sub _win32_build_file_list {
my ( $lib, $GC, $extensions ) = @_;
my @pre_fixed = _win32_build_prefixed_list( $lib, $GC );
return map _win32_attach_extensions( $_, $extensions ), @pre_fixed;
}
sub _win32_build_prefixed_list {
my ( $lib, $GC ) = @_;
return $lib if $lib !~ s/^-l//;
return $lib if $lib =~ /^lib/ and !$GC;
( my $no_prefix = $lib ) =~ s/^lib//i;
$lib = "lib$lib" if $no_prefix eq $lib;
return ( $lib, $no_prefix ) if $GC;
return ( $no_prefix, $lib );
}
sub _win32_attach_extensions {
my ( $lib, $extensions ) = @_;
return map _win32_try_attach_extension( $lib, $_ ), @{$extensions};
}
sub _win32_try_attach_extension {
my ( $lib, $extension ) = @_;
return $lib if $lib =~ /\Q$extension\E$/i;
return "$lib$extension";
}
sub _win32_lib_extensions {
my @extensions;
push @extensions, $Config{'lib_ext'} if $Config{'lib_ext'};
push @extensions, '.dll.a' if grep { m!^\.a$! } @extensions;
push @extensions, '.lib' unless grep { m!^\.lib$! } @extensions;
return \@extensions;
}
sub _debug {
my ( $message, $verbose ) = @_;
return if !$verbose;
warn $message;
return;
}
sub _vms_ext {
my ( $self, $potential_libs, $verbose, $give_libs ) = @_;
$verbose ||= 0;
my ( @crtls, $crtlstr );
@crtls = ( ( $Config{'ldflags'} =~ m-/Debug-i ? $Config{'dbgprefix'} : '' ) . 'PerlShr/Share' );
push( @crtls, grep { not /\(/ } split /\s+/, $Config{'perllibs'} );
push( @crtls, grep { not /\(/ } split /\s+/, $Config{'libc'} );
# In general, we pass through the basic libraries from %Config unchanged.
# The one exception is that if we're building in the Perl source tree, and
# a library spec could be resolved via a logical name, we go to some trouble
# to insure that the copy in the local tree is used, rather than one to
# which a system-wide logical may point.
if ( $self->{PERL_SRC} ) {
my ( $locspec, $type );
foreach my $lib ( @crtls ) {
if ( ( $locspec, $type ) = $lib =~ m{^([\w\$-]+)(/\w+)?} and $locspec =~ /perl/i ) {
if ( lc $type eq '/share' ) { $locspec .= $Config{'exe_ext'}; }
elsif ( lc $type eq '/library' ) { $locspec .= $Config{'lib_ext'}; }
else { $locspec .= $Config{'obj_ext'}; }
$locspec = $self->catfile( $self->{PERL_SRC}, $locspec );
$lib = "$locspec$type" if -e $locspec;
}
}
}
$crtlstr = @crtls ? join( ' ', @crtls ) : '';
unless ( $potential_libs ) {
warn "Result:\n\tEXTRALIBS: \n\tLDLOADLIBS: $crtlstr\n" if $verbose;
return ( '', '', $crtlstr, '', ( $give_libs ? [] : () ) );
}
my ( %found, @fndlibs, $ldlib );
my $cwd = cwd();
my ( $so, $lib_ext, $obj_ext ) = @Config{ 'so', 'lib_ext', 'obj_ext' };
# List of common Unix library names and their VMS equivalents
# (VMS equivalent of '' indicates that the library is automatically
# searched by the linker, and should be skipped here.)
my ( @flibs, %libs_seen );
my %libmap = (
'm' => '',
'f77' => '',
'F77' => '',
'V77' => '',
'c' => '',
'malloc' => '',
'crypt' => '',
'resolv' => '',
'c_s' => '',
'socket' => '',
'X11' => 'DECW$XLIBSHR',
'Xt' => 'DECW$XTSHR',
'Xm' => 'DECW$XMLIBSHR',
'Xmu' => 'DECW$XMULIBSHR'
);
warn "Potential libraries are '$potential_libs'\n" if $verbose;
# First, sort out directories and library names in the input
my ( @dirs, @libs );
foreach my $lib ( split ' ', $potential_libs ) {
push( @dirs, $1 ), next if $lib =~ /^-L(.*)/;
push( @dirs, $lib ), next if $lib =~ /[:>\]]$/;
push( @dirs, $lib ), next if -d $lib;
push( @libs, $1 ), next if $lib =~ /^-l(.*)/;
push( @libs, $lib );
}
push( @dirs, split( ' ', $Config{'libpth'} ) );
# Now make sure we've got VMS-syntax absolute directory specs
# (We don't, however, check whether someone's hidden a relative
# path in a logical name.)
foreach my $dir ( @dirs ) {
unless ( -d $dir ) {
warn "Skipping nonexistent Directory $dir\n" if $verbose > 1;
$dir = '';
next;
}
warn "Resolving directory $dir\n" if $verbose;
if ( File::Spec->file_name_is_absolute( $dir ) ) {
$dir = VMS::Filespec::vmspath( $dir );
}
else {
$dir = $self->catdir( $cwd, $dir );
}
}
@dirs = grep { length( $_ ) } @dirs;
unshift( @dirs, '' ); # Check each $lib without additions first
LIB: foreach my $lib ( @libs ) {
if ( exists $libmap{$lib} ) {
next unless length $libmap{$lib};
$lib = $libmap{$lib};
}
my ( @variants, $cand );
my ( $ctype ) = '';
# If we don't have a file type, consider it a possibly abbreviated name and
# check for common variants. We try these first to grab libraries before
# a like-named executable image (e.g. -lperl resolves to perlshr.exe
# before perl.exe).
if ( $lib !~ /\.[^:>\]]*$/ ) {
push( @variants, "${lib}shr", "${lib}rtl", "${lib}lib" );
push( @variants, "lib$lib" ) if $lib !~ /[:>\]]/;
}
push( @variants, $lib );
warn "Looking for $lib\n" if $verbose;
foreach my $variant ( @variants ) {
my ( $fullname, $name );
foreach my $dir ( @dirs ) {
my ( $type );
$name = "$dir$variant";
warn "\tChecking $name\n" if $verbose > 2;
$fullname = VMS::Filespec::rmsexpand( $name );
if ( defined $fullname and -f $fullname ) {
# It's got its own suffix, so we'll have to figure out the type
if ( $fullname =~ /(?:$so|exe)$/i ) { $type = 'SHR'; }
elsif ( $fullname =~ /(?:$lib_ext|olb)$/i ) { $type = 'OLB'; }
elsif ( $fullname =~ /(?:$obj_ext|obj)$/i ) {
warn "Warning (mostly harmless): " . "Plain object file $fullname found in library list\n";
$type = 'OBJ';
}
else {
warn "Warning (mostly harmless): " . "Unknown library type for $fullname; assuming shared\n";
$type = 'SHR';
}
}
elsif (-f ( $fullname = VMS::Filespec::rmsexpand( $name, $so ) )
or -f ( $fullname = VMS::Filespec::rmsexpand( $name, '.exe' ) ) )
{
$type = 'SHR';
$name = $fullname unless $fullname =~ /exe;?\d*$/i;
}
elsif (
not length( $ctype ) and # If we've got a lib already,
# don't bother
( -f ( $fullname = VMS::Filespec::rmsexpand( $name, $lib_ext ) ) or -f ( $fullname = VMS::Filespec::rmsexpand( $name, '.olb' ) ) )
)
{
$type = 'OLB';
$name = $fullname unless $fullname =~ /olb;?\d*$/i;
}
elsif (
not length( $ctype ) and # If we've got a lib already,
# don't bother
( -f ( $fullname = VMS::Filespec::rmsexpand( $name, $obj_ext ) ) or -f ( $fullname = VMS::Filespec::rmsexpand( $name, '.obj' ) ) )
)
{
warn "Warning (mostly harmless): " . "Plain object file $fullname found in library list\n";
$type = 'OBJ';
$name = $fullname unless $fullname =~ /obj;?\d*$/i;
}
if ( defined $type ) {
$ctype = $type;
$cand = $name;
last if $ctype eq 'SHR';
}
}
if ( $ctype ) {
push @{ $found{$ctype} }, $cand;
warn "\tFound as $cand (really $fullname), type $ctype\n"
if $verbose > 1;
push @flibs, $name unless $libs_seen{$fullname}++;
next LIB;
}
}
warn "Warning (mostly harmless): " . "No library found for $lib\n";
}
push @fndlibs, @{ $found{OBJ} } if exists $found{OBJ};
push @fndlibs, map { "$_/Library" } @{ $found{OLB} } if exists $found{OLB};
push @fndlibs, map { "$_/Share" } @{ $found{SHR} } if exists $found{SHR};
my $lib = join( ' ', @fndlibs );
$ldlib = $crtlstr ? "$lib $crtlstr" : $lib;
$ldlib =~ s/^\s+|\s+$//g;
warn "Result:\n\tEXTRALIBS: $lib\n\tLDLOADLIBS: $ldlib\n" if $verbose;
wantarray ? ( $lib, '', $ldlib, '', ( $give_libs ? \@flibs : () ) ) : $lib;
}
1;

View file

@ -0,0 +1,78 @@
# Avoid version control files.
\bRCS\b
\bCVS\b
\bSCCS\b
,v$
\B\.svn\b
\B\.git\b
^\.github\b
\B\.gitignore\b
\b_darcs\b
\B\.cvsignore$
\B\.bzr\b
\B\.bzrignore$
# Avoid VMS specific MakeMaker generated files
\bDescrip.MMS$
\bDESCRIP.MMS$
\bdescrip.mms$
# Avoid Makemaker generated and utility files.
\bMANIFEST\.bak
\bMakefile$
\bblib/
\bMakeMaker-\d
\bpm_to_blib\.ts$
\bpm_to_blib$
\bblibdirs\.ts$ # 6.18 through 6.25 generated this
\b_eumm/ # 7.05_05 and above
# Avoid Module::Build generated and utility files.
\bBuild$
\b_build/
\bBuild.bat$
\bBuild.COM$
\bBUILD.COM$
\bbuild.com$
# and Module::Build::Tiny generated files
\b_build_params$
# Avoid temp and backup files.
~$
\.old$
\#$
\b\.#
\.bak$
\.tmp$
\.#
\.rej$
\..*\.sw.?$
\.~\d+~$
# Avoid OS-specific files/dirs
# Mac OSX metadata
\B\.DS_Store
# Mac OSX SMB mount metadata files
\B\._
# Placeholder files created when iCloud will "optimize Mac storage"
\.i[cC]loud$
# Avoid Devel::Cover and Devel::CoverX::Covered files.
\bcover_db\b
\bcovered\b
# Avoid prove files
\B\.prove$
# Avoid MYMETA files
^MYMETA\.
# Temp files for new META
^META_new\.(?:json|yml)
# Avoid travis-ci.org file
^\.travis\.yml
# Avoid AppVeyor file
^\.?appveyor.yml

View file

@ -0,0 +1,93 @@
package ExtUtils::MM;
use strict;
use warnings;
use ExtUtils::MakeMaker::Config;
our $VERSION = '7.70';
$VERSION =~ tr/_//d;
require ExtUtils::Liblist;
require ExtUtils::MakeMaker;
our @ISA = qw(ExtUtils::Liblist ExtUtils::MakeMaker);
=head1 NAME
ExtUtils::MM - OS adjusted ExtUtils::MakeMaker subclass
=head1 SYNOPSIS
require ExtUtils::MM;
my $mm = MM->new(...);
=head1 DESCRIPTION
B<FOR INTERNAL USE ONLY>
ExtUtils::MM is a subclass of L<ExtUtils::MakeMaker> which automatically
chooses the appropriate OS specific subclass for you
(ie. L<ExtUtils::MM_Unix>, etc...).
It also provides a convenient alias via the MM class (I didn't want
MakeMaker modules outside of ExtUtils/).
This class might turn out to be a temporary solution, but MM won't go
away.
=cut
{
# Convenient alias.
package MM;
our @ISA = qw(ExtUtils::MM);
sub DESTROY {}
}
sub _is_win95 {
# miniperl might not have the Win32 functions available and we need
# to run in miniperl.
my $have_win32 = eval { require Win32 };
return $have_win32 && defined &Win32::IsWin95 ? Win32::IsWin95()
: ! defined $ENV{SYSTEMROOT};
}
my %Is = ();
$Is{VMS} = $^O eq 'VMS';
$Is{OS2} = $^O eq 'os2';
$Is{MacOS} = $^O eq 'MacOS';
if( $^O eq 'MSWin32' ) {
_is_win95() ? $Is{Win95} = 1 : $Is{Win32} = 1;
}
$Is{UWIN} = $^O =~ /^uwin(-nt)?$/;
$Is{Cygwin} = $^O eq 'cygwin';
$Is{NW5} = $Config{osname} eq 'NetWare'; # intentional
$Is{BeOS} = ($^O =~ /beos/i or $^O eq 'haiku');
$Is{DOS} = $^O eq 'dos';
if( $Is{NW5} ) {
$^O = 'NetWare';
delete $Is{Win32};
}
$Is{VOS} = $^O eq 'vos';
$Is{QNX} = $^O eq 'qnx';
$Is{AIX} = $^O eq 'aix';
$Is{Darwin} = $^O eq 'darwin';
$Is{OS390} = $^O eq 'os390';
$Is{Unix} = !grep { $_ } values %Is;
map { delete $Is{$_} unless $Is{$_} } keys %Is;
_assert( keys %Is == 1 );
my($OS) = keys %Is;
my $class = "ExtUtils::MM_$OS";
eval "require $class" unless $INC{"ExtUtils/MM_$OS.pm"}; ## no critic
die $@ if $@;
unshift @ISA, $class;
sub _assert {
my $sanity = shift;
die sprintf "Assert failed at %s line %d\n", (caller)[1,2] unless $sanity;
return;
}

View file

@ -0,0 +1,80 @@
package ExtUtils::MM_AIX;
use strict;
use warnings;
our $VERSION = '7.70';
$VERSION =~ tr/_//d;
use ExtUtils::MakeMaker::Config;
require ExtUtils::MM_Unix;
our @ISA = qw(ExtUtils::MM_Unix);
=head1 NAME
ExtUtils::MM_AIX - AIX specific subclass of ExtUtils::MM_Unix
=head1 SYNOPSIS
Don't use this module directly.
Use ExtUtils::MM and let it choose.
=head1 DESCRIPTION
This is a subclass of L<ExtUtils::MM_Unix> which contains functionality for
AIX.
Unless otherwise stated it works just like ExtUtils::MM_Unix.
=head2 Overridden methods
=head3 dlsyms
Define DL_FUNCS and DL_VARS and write the *.exp files.
=cut
sub dlsyms {
my($self,%attribs) = @_;
return '' unless $self->needs_linking;
join "\n", $self->xs_dlsyms_iterator(\%attribs);
}
=head3 xs_dlsyms_ext
On AIX, is C<.exp>.
=cut
sub xs_dlsyms_ext {
'.exp';
}
sub xs_dlsyms_arg {
my($self, $file) = @_;
my $arg = qq{-bE:${file}};
$arg = '-Wl,'.$arg if $Config{lddlflags} =~ /-Wl,-bE:/;
return $arg;
}
sub init_others {
my $self = shift;
$self->SUPER::init_others;
# perl "hints" add -bE:$(BASEEXT).exp to LDDLFLAGS. strip that out
# so right value can be added by xs_make_dynamic_lib to work for XSMULTI
$self->{LDDLFLAGS} ||= $Config{lddlflags};
$self->{LDDLFLAGS} =~ s#(\s*)\S*\Q$(BASEEXT)\E\S*(\s*)#$1$2#;
return;
}
=head1 AUTHOR
Michael G Schwern <schwern@pobox.com> with code from ExtUtils::MM_Unix
=head1 SEE ALSO
L<ExtUtils::MakeMaker>
=cut
1;

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,66 @@
package ExtUtils::MM_BeOS;
use strict;
use warnings;
=head1 NAME
ExtUtils::MM_BeOS - methods to override UN*X behaviour in ExtUtils::MakeMaker
=head1 SYNOPSIS
use ExtUtils::MM_BeOS; # Done internally by ExtUtils::MakeMaker if needed
=head1 DESCRIPTION
See L<ExtUtils::MM_Unix> for a documentation of the methods provided
there. This package overrides the implementation of these methods, not
the semantics.
=over 4
=cut
use ExtUtils::MakeMaker::Config;
use File::Spec;
require ExtUtils::MM_Any;
require ExtUtils::MM_Unix;
our @ISA = qw( ExtUtils::MM_Any ExtUtils::MM_Unix );
our $VERSION = '7.70';
$VERSION =~ tr/_//d;
=item os_flavor
BeOS is BeOS.
=cut
sub os_flavor {
return('BeOS');
}
=item init_linker
libperl.a equivalent to be linked to dynamic extensions.
=cut
sub init_linker {
my($self) = shift;
$self->{PERL_ARCHIVE} ||=
File::Spec->catdir('$(PERL_INC)',$Config{libperl});
$self->{PERL_ARCHIVEDEP} ||= '';
$self->{PERL_ARCHIVE_AFTER} ||= '';
$self->{EXPORT_LIST} ||= '';
}
=back
=cut
1;
__END__

View file

@ -0,0 +1,156 @@
package ExtUtils::MM_Cygwin;
use strict;
use warnings;
use ExtUtils::MakeMaker::Config;
use File::Spec;
require ExtUtils::MM_Unix;
require ExtUtils::MM_Win32;
our @ISA = qw( ExtUtils::MM_Unix );
our $VERSION = '7.70_01';
$VERSION =~ tr/_//d;
=head1 NAME
ExtUtils::MM_Cygwin - methods to override UN*X behaviour in ExtUtils::MakeMaker
=head1 SYNOPSIS
use ExtUtils::MM_Cygwin; # Done internally by ExtUtils::MakeMaker if needed
=head1 DESCRIPTION
See L<ExtUtils::MM_Unix> for a documentation of the methods provided there.
=over 4
=item os_flavor
We're Unix and Cygwin.
=cut
sub os_flavor {
return('Unix', 'Cygwin');
}
=item cflags
if configured for dynamic loading, triggers #define EXT in EXTERN.h
=cut
sub cflags {
my($self,$libperl)=@_;
return $self->{CFLAGS} if $self->{CFLAGS};
return '' unless $self->needs_linking();
my $base = $self->SUPER::cflags($libperl);
foreach (split /\n/, $base) {
/^(\S*)\s*=\s*(\S*)$/ and $self->{$1} = $2;
};
$self->{CCFLAGS} .= " -DUSEIMPORTLIB" if ($Config{useshrplib} eq 'true');
return $self->{CFLAGS} = qq{
CCFLAGS = $self->{CCFLAGS}
OPTIMIZE = $self->{OPTIMIZE}
PERLTYPE = $self->{PERLTYPE}
};
}
=item replace_manpage_separator
replaces strings '::' with '.' in MAN*POD man page names
=cut
sub replace_manpage_separator {
my($self, $man) = @_;
$man =~ s{/+}{.}g;
return $man;
}
=item init_linker
points to libperl.a
=cut
sub init_linker {
my $self = shift;
if ($Config{useshrplib} eq 'true') {
my $libperl = '$(PERL_INC)' .'/'. "$Config{libperl}";
if( "$]" >= 5.006002 ) {
$libperl =~ s/(dll\.)?a$/dll.a/;
}
$self->{PERL_ARCHIVE} = $libperl;
} else {
$self->{PERL_ARCHIVE} =
'$(PERL_INC)' .'/'. ("$Config{libperl}" or "libperl.a");
}
$self->{PERL_ARCHIVEDEP} ||= '';
$self->{PERL_ARCHIVE_AFTER} ||= '';
$self->{EXPORT_LIST} ||= '';
}
sub init_others {
my $self = shift;
$self->SUPER::init_others;
$self->{LDLOADLIBS} ||= $Config{perllibs};
return;
}
=item dynamic_lib
Use the default to produce the *.dll's.
But for new archdir dll's use the same rebase address if the old exists.
=cut
sub dynamic_lib {
my($self, %attribs) = @_;
my $s = ExtUtils::MM_Unix::dynamic_lib($self, %attribs);
return '' unless $s;
return $s unless %{$self->{XS}};
# do an ephemeral rebase so the new DLL fits to the current rebase map
$s .= "\t/bin/find \$\(INST_ARCHLIB\)/auto -xdev -name \\*.$self->{DLEXT} | /bin/rebase -sOT -" if (( $Config{myarchname} eq 'i686-cygwin' ) and not ( exists $ENV{CYGPORT_PACKAGE_VERSION} ));
$s;
}
=item install
Rebase dll's with the global rebase database after installation.
=cut
sub install {
my($self, %attribs) = @_;
my $s = ExtUtils::MM_Unix::install($self, %attribs);
return '' unless $s;
return $s unless %{$self->{XS}};
my $INSTALLDIRS = $self->{INSTALLDIRS};
my $INSTALLLIB = $self->{"INSTALL". ($INSTALLDIRS eq 'perl' ? 'ARCHLIB' : uc($INSTALLDIRS)."ARCH")};
my $dop = "\$\(DESTDIR\)$INSTALLLIB/auto/";
my $dll = "$dop/$self->{FULLEXT}/$self->{BASEEXT}.$self->{DLEXT}";
$s =~ s|^(pure_install :: pure_\$\(INSTALLDIRS\)_install\n\t)\$\(NOECHO\) \$\(NOOP\)\n|$1\$(CHMOD) \$(PERM_RWX) $dll\n\t/bin/find $dop -xdev -name \\*.$self->{DLEXT} \| /bin/rebase -sOT -\n|m if (( $Config{myarchname} eq 'i686-cygwin') and not ( exists $ENV{CYGPORT_PACKAGE_VERSION} ));
$s;
}
=back
=cut
1;

View file

@ -0,0 +1,75 @@
package ExtUtils::MM_DOS;
use strict;
use warnings;
our $VERSION = '7.70';
$VERSION =~ tr/_//d;
require ExtUtils::MM_Any;
require ExtUtils::MM_Unix;
our @ISA = qw( ExtUtils::MM_Any ExtUtils::MM_Unix );
=head1 NAME
ExtUtils::MM_DOS - DOS specific subclass of ExtUtils::MM_Unix
=head1 SYNOPSIS
Don't use this module directly.
Use ExtUtils::MM and let it choose.
=head1 DESCRIPTION
This is a subclass of L<ExtUtils::MM_Unix> which contains functionality
for DOS.
Unless otherwise stated, it works just like ExtUtils::MM_Unix.
=head2 Overridden methods
=over 4
=item os_flavor
=cut
sub os_flavor {
return('DOS');
}
=item B<replace_manpage_separator>
Generates Foo__Bar.3 style man page names
=cut
sub replace_manpage_separator {
my($self, $man) = @_;
$man =~ s,/+,__,g;
return $man;
}
=item xs_static_lib_is_xs
=cut
sub xs_static_lib_is_xs {
return 1;
}
=back
=head1 AUTHOR
Michael G Schwern <schwern@pobox.com> with code from ExtUtils::MM_Unix
=head1 SEE ALSO
L<ExtUtils::MM_Unix>, L<ExtUtils::MakeMaker>
=cut
1;

View file

@ -0,0 +1,74 @@
package ExtUtils::MM_Darwin;
use strict;
use warnings;
BEGIN {
require ExtUtils::MM_Unix;
our @ISA = qw( ExtUtils::MM_Unix );
}
our $VERSION = '7.70';
$VERSION =~ tr/_//d;
=head1 NAME
ExtUtils::MM_Darwin - special behaviors for OS X
=head1 SYNOPSIS
For internal MakeMaker use only
=head1 DESCRIPTION
See L<ExtUtils::MM_Unix> or L<ExtUtils::MM_Any> for documentation on the
methods overridden here.
=head2 Overridden Methods
=head3 init_dist
Turn off Apple tar's tendency to copy resource forks as "._foo" files.
=cut
sub init_dist {
my $self = shift;
# Thank you, Apple, for breaking tar and then breaking the work around.
# 10.4 wants COPY_EXTENDED_ATTRIBUTES_DISABLE while 10.5 wants
# COPYFILE_DISABLE. I'm not going to push my luck and instead just
# set both.
$self->{TAR} ||=
'COPY_EXTENDED_ATTRIBUTES_DISABLE=1 COPYFILE_DISABLE=1 tar';
$self->SUPER::init_dist(@_);
}
=head3 cflags
Over-ride Apple's automatic setting of -Werror
=cut
sub cflags {
my($self,$libperl)=@_;
return $self->{CFLAGS} if $self->{CFLAGS};
return '' unless $self->needs_linking();
my $base = $self->SUPER::cflags($libperl);
foreach (split /\n/, $base) {
/^(\S*)\s*=\s*(\S*)$/ and $self->{$1} = $2;
};
$self->{CCFLAGS} .= " -Wno-error=implicit-function-declaration";
return $self->{CFLAGS} = qq{
CCFLAGS = $self->{CCFLAGS}
OPTIMIZE = $self->{OPTIMIZE}
PERLTYPE = $self->{PERLTYPE}
};
}
1;

View file

@ -0,0 +1,35 @@
package ExtUtils::MM_MacOS;
use strict;
use warnings;
our $VERSION = '7.70';
$VERSION =~ tr/_//d;
sub new {
die 'MacOS Classic (MacPerl) is no longer supported by MakeMaker';
}
=head1 NAME
ExtUtils::MM_MacOS - once produced Makefiles for MacOS Classic
=head1 SYNOPSIS
# MM_MacOS no longer contains any code. This is just a stub.
=head1 DESCRIPTION
Once upon a time, MakeMaker could produce an approximation of a correct
Makefile on MacOS Classic (MacPerl). Due to a lack of maintainers, this
fell out of sync with the rest of MakeMaker and hadn't worked in years.
Since there's little chance of it being repaired, MacOS Classic is fading
away, and the code was icky to begin with, the code has been deleted to
make maintenance easier.
Anyone interested in resurrecting this file should pull the old version
from the MakeMaker CVS repository and contact makemaker@perl.org.
=cut
1;

View file

@ -0,0 +1,209 @@
package ExtUtils::MM_NW5;
=head1 NAME
ExtUtils::MM_NW5 - methods to override UN*X behaviour in ExtUtils::MakeMaker
=head1 SYNOPSIS
use ExtUtils::MM_NW5; # Done internally by ExtUtils::MakeMaker if needed
=head1 DESCRIPTION
See L<ExtUtils::MM_Unix> for a documentation of the methods provided
there. This package overrides the implementation of these methods, not
the semantics.
=over
=cut
use strict;
use warnings;
use ExtUtils::MakeMaker::Config;
use File::Basename;
our $VERSION = '7.70';
$VERSION =~ tr/_//d;
require ExtUtils::MM_Win32;
our @ISA = qw(ExtUtils::MM_Win32);
use ExtUtils::MakeMaker qw(&neatvalue &_sprintf562);
$ENV{EMXSHELL} = 'sh'; # to run `commands`
my $BORLAND = $Config{'cc'} =~ /\bbcc/i;
my $GCC = $Config{'cc'} =~ /\bgcc/i;
=item os_flavor
We're Netware in addition to being Windows.
=cut
sub os_flavor {
my $self = shift;
return ($self->SUPER::os_flavor, 'Netware');
}
=item init_platform
Add Netware macros.
LIBPTH, BASE_IMPORT, NLM_VERSION, MPKTOOL, TOOLPATH, BOOT_SYMBOL,
NLM_SHORT_NAME, INCLUDE, PATH, MM_NW5_REVISION
=item platform_constants
Add Netware macros initialized above to the Makefile.
=cut
sub init_platform {
my($self) = shift;
# To get Win32's setup.
$self->SUPER::init_platform;
# incpath is copied to makefile var INCLUDE in constants sub, here just
# make it empty
my $libpth = $Config{'libpth'};
$libpth =~ s( )(;);
$self->{'LIBPTH'} = $libpth;
$self->{'BASE_IMPORT'} = $Config{'base_import'};
# Additional import file specified from Makefile.pl
if($self->{'base_import'}) {
$self->{'BASE_IMPORT'} .= ', ' . $self->{'base_import'};
}
$self->{'NLM_VERSION'} = $Config{'nlm_version'};
$self->{'MPKTOOL'} = $Config{'mpktool'};
$self->{'TOOLPATH'} = $Config{'toolpath'};
(my $boot = $self->{'NAME'}) =~ s/:/_/g;
$self->{'BOOT_SYMBOL'}=$boot;
# If the final binary name is greater than 8 chars,
# truncate it here.
if(length($self->{'BASEEXT'}) > 8) {
$self->{'NLM_SHORT_NAME'} = substr($self->{'BASEEXT'},0,8);
}
# Get the include path and replace the spaces with ;
# Copy this to makefile as INCLUDE = d:\...;d:\;
($self->{INCLUDE} = $Config{'incpath'}) =~ s/([ ]*)-I/;/g;
# Set the path to CodeWarrior binaries which might not have been set in
# any other place
$self->{PATH} = '$(PATH);$(TOOLPATH)';
$self->{MM_NW5_VERSION} = $VERSION;
}
sub platform_constants {
my($self) = shift;
my $make_frag = '';
# Setup Win32's constants.
$make_frag .= $self->SUPER::platform_constants;
foreach my $macro (qw(LIBPTH BASE_IMPORT NLM_VERSION MPKTOOL
TOOLPATH BOOT_SYMBOL NLM_SHORT_NAME INCLUDE PATH
MM_NW5_VERSION
))
{
next unless defined $self->{$macro};
$make_frag .= "$macro = $self->{$macro}\n";
}
return $make_frag;
}
=item static_lib_pure_cmd
Defines how to run the archive utility
=cut
sub static_lib_pure_cmd {
my ($self, $src) = @_;
$src =~ s/(\$\(\w+)(\))/$1:^"+"$2/g if $BORLAND;
sprintf qq{\t\$(AR) %s\n}, ($BORLAND ? '$@ ' . $src
: ($GCC ? '-ru $@ ' . $src
: '-type library -o $@ ' . $src));
}
=item xs_static_lib_is_xs
=cut
sub xs_static_lib_is_xs {
return 1;
}
=item dynamic_lib
Override of utility methods for OS-specific work.
=cut
sub xs_make_dynamic_lib {
my ($self, $attribs, $from, $to, $todir, $ldfrom, $exportlist) = @_;
my @m;
# Taking care of long names like FileHandle, ByteLoader, SDBM_File etc
if ($to =~ /^\$/) {
if ($self->{NLM_SHORT_NAME}) {
# deal with shortnames
my $newto = q{$(INST_AUTODIR)\\$(NLM_SHORT_NAME).$(DLEXT)};
push @m, "$to: $newto\n\n";
$to = $newto;
}
} else {
my ($v, $d, $f) = File::Spec->splitpath($to);
# relies on $f having a literal "." in it, unlike for $(OBJ_EXT)
if ($f =~ /[^\.]{9}\./) {
# 9+ chars before '.', need to shorten
$f = substr $f, 0, 8;
}
my $newto = File::Spec->catpath($v, $d, $f);
push @m, "$to: $newto\n\n";
$to = $newto;
}
# bits below should be in dlsyms, not here
# 1 2 3 4
push @m, _sprintf562 <<'MAKE_FRAG', $to, $from, $todir, $exportlist;
# Create xdc data for an MT safe NLM in case of mpk build
%1$s: %2$s $(MYEXTLIB) $(BOOTSTRAP) %3$s$(DFSEP).exists
$(NOECHO) $(ECHO) Export boot_$(BOOT_SYMBOL) > %4$s
$(NOECHO) $(ECHO) $(BASE_IMPORT) >> %4$s
$(NOECHO) $(ECHO) Import @$(PERL_INC)\perl.imp >> %4$s
MAKE_FRAG
if ( $self->{CCFLAGS} =~ m/ -DMPK_ON /) {
(my $xdc = $exportlist) =~ s#def\z#xdc#;
$xdc = '$(BASEEXT).xdc';
push @m, sprintf <<'MAKE_FRAG', $xdc, $exportlist;
$(MPKTOOL) $(XDCFLAGS) %s
$(NOECHO) $(ECHO) xdcdata $(BASEEXT).xdc >> %s
MAKE_FRAG
}
# Reconstruct the X.Y.Z version.
my $version = join '.', map { sprintf "%d", $_ }
"$]" =~ /(\d)\.(\d{3})(\d{2})/;
push @m, sprintf <<'EOF', $from, $version, $to, $exportlist;
$(LD) $(LDFLAGS) %s -desc "Perl %s Extension ($(BASEEXT)) XS_VERSION: $(XS_VERSION)" -nlmversion $(NLM_VERSION) -o %s $(MYEXTLIB) $(PERL_INC)\Main.lib -commandfile %s
$(CHMOD) 755 $@
EOF
join '', @m;
}
1;
__END__
=back
=cut

View file

@ -0,0 +1,147 @@
package ExtUtils::MM_OS2;
use strict;
use warnings;
use ExtUtils::MakeMaker qw(neatvalue);
use File::Spec;
our $VERSION = '7.70';
$VERSION =~ tr/_//d;
require ExtUtils::MM_Any;
require ExtUtils::MM_Unix;
our @ISA = qw(ExtUtils::MM_Any ExtUtils::MM_Unix);
=pod
=head1 NAME
ExtUtils::MM_OS2 - methods to override UN*X behaviour in ExtUtils::MakeMaker
=head1 SYNOPSIS
use ExtUtils::MM_OS2; # Done internally by ExtUtils::MakeMaker if needed
=head1 DESCRIPTION
See L<ExtUtils::MM_Unix> for a documentation of the methods provided
there. This package overrides the implementation of these methods, not
the semantics.
=head1 METHODS
=over 4
=item init_dist
Define TO_UNIX to convert OS2 linefeeds to Unix style.
=cut
sub init_dist {
my($self) = @_;
$self->{TO_UNIX} ||= <<'MAKE_TEXT';
$(NOECHO) $(TEST_F) tmp.zip && $(RM_F) tmp.zip; $(ZIP) -ll -mr tmp.zip $(DISTVNAME) && unzip -o tmp.zip && $(RM_F) tmp.zip
MAKE_TEXT
$self->SUPER::init_dist;
}
sub dlsyms {
my($self,%attribs) = @_;
if ($self->{IMPORTS} && %{$self->{IMPORTS}}) {
# Make import files (needed for static build)
-d 'tmp_imp' or mkdir 'tmp_imp', 0777 or die "Can't mkdir tmp_imp";
open my $imp, '>', 'tmpimp.imp' or die "Can't open tmpimp.imp";
foreach my $name (sort keys %{$self->{IMPORTS}}) {
my $exp = $self->{IMPORTS}->{$name};
my ($lib, $id) = ($exp =~ /(.*)\.(.*)/) or die "Malformed IMPORT `$exp'";
print $imp "$name $lib $id ?\n";
}
close $imp or die "Can't close tmpimp.imp";
# print "emximp -o tmpimp$Config::Config{lib_ext} tmpimp.imp\n";
system "emximp -o tmpimp$Config::Config{lib_ext} tmpimp.imp"
and die "Cannot make import library: $!, \$?=$?";
# May be running under miniperl, so have no glob...
eval { unlink <tmp_imp/*>; 1 } or system "rm tmp_imp/*";
system "cd tmp_imp; $Config::Config{ar} x ../tmpimp$Config::Config{lib_ext}"
and die "Cannot extract import objects: $!, \$?=$?";
}
return '' if $self->{SKIPHASH}{'dynamic'};
$self->xs_dlsyms_iterator(\%attribs);
}
sub xs_dlsyms_ext {
'.def';
}
sub xs_dlsyms_extra {
join '', map { qq{, "$_" => "\$($_)"} } qw(VERSION DISTNAME INSTALLDIRS);
}
sub static_lib_pure_cmd {
my($self) = @_;
my $old = $self->SUPER::static_lib_pure_cmd;
return $old unless $self->{IMPORTS} && %{$self->{IMPORTS}};
$old . <<'EOC';
$(AR) $(AR_STATIC_ARGS) "$@" tmp_imp/*
$(RANLIB) "$@"
EOC
}
sub replace_manpage_separator {
my($self,$man) = @_;
$man =~ s,/+,.,g;
$man;
}
sub maybe_command {
my($self,$file) = @_;
$file =~ s,[/\\]+,/,g;
return $file if -x $file && ! -d _;
return "$file.exe" if -x "$file.exe" && ! -d _;
return "$file.cmd" if -x "$file.cmd" && ! -d _;
return;
}
=item init_linker
=cut
sub init_linker {
my $self = shift;
$self->{PERL_ARCHIVE} = "\$(PERL_INC)/libperl\$(LIB_EXT)";
$self->{PERL_ARCHIVEDEP} ||= '';
$self->{PERL_ARCHIVE_AFTER} = $OS2::is_aout
? ''
: '$(PERL_INC)/libperl_override$(LIB_EXT)';
$self->{EXPORT_LIST} = '$(BASEEXT).def';
}
=item os_flavor
OS/2 is OS/2
=cut
sub os_flavor {
return('OS/2');
}
=item xs_static_lib_is_xs
=cut
sub xs_static_lib_is_xs {
return 1;
}
=back
=cut
1;

View file

@ -0,0 +1,86 @@
package ExtUtils::MM_OS390;
use strict;
use warnings;
our $VERSION = '7.70';
$VERSION =~ tr/_//d;
use ExtUtils::MakeMaker::Config;
require ExtUtils::MM_Unix;
our @ISA = qw(ExtUtils::MM_Unix);
=head1 NAME
ExtUtils::MM_OS390 - OS390 specific subclass of ExtUtils::MM_Unix
=head1 SYNOPSIS
Don't use this module directly.
Use ExtUtils::MM and let it choose.
=head1 DESCRIPTION
This is a subclass of L<ExtUtils::MM_Unix> which contains functionality for
OS390.
Unless otherwise stated it works just like ExtUtils::MM_Unix.
=head2 Overriden methods
=over
=item xs_make_dynamic_lib
Defines the recipes for the C<dynamic_lib> section.
=cut
sub xs_make_dynamic_lib {
my ($self, $attribs, $object, $to, $todir, $ldfrom, $exportlist, $dlsyms) = @_;
$exportlist = '' if $exportlist ne '$(EXPORT_LIST)';
my $armaybe = $self->_xs_armaybe($attribs);
my @m = sprintf '%s : %s $(MYEXTLIB) %s$(DFSEP).exists %s $(PERL_ARCHIVEDEP) $(PERL_ARCHIVE_AFTER) $(INST_DYNAMIC_DEP) %s'."\n", $to, $object, $todir, $exportlist, ($dlsyms || '');
my $dlsyms_arg = $self->xs_dlsyms_arg($dlsyms);
if ($armaybe ne ':'){
$ldfrom = 'tmp$(LIB_EXT)';
push(@m," \$(ARMAYBE) cr $ldfrom $object\n");
push(@m," \$(RANLIB) $ldfrom\n");
}
# For example in AIX the shared objects/libraries from previous builds
# linger quite a while in the shared dynalinker cache even when nobody
# is using them. This is painful if one for instance tries to restart
# a failed build because the link command will fail unnecessarily 'cos
# the shared object/library is 'busy'.
push(@m," \$(RM_F) \$\@\n");
my $libs = '$(LDLOADLIBS)';
my $ld_run_path_shell = "";
if ($self->{LD_RUN_PATH} ne "") {
$ld_run_path_shell = 'LD_RUN_PATH="$(LD_RUN_PATH)" ';
}
push @m, sprintf <<'MAKE', $ld_run_path_shell, $self->xs_obj_opt('$@'), $dlsyms_arg, $ldfrom, $libs, $exportlist;
%s$(LD) %s $(LDDLFLAGS) %s $(OTHERLDFLAGS) %s $(MYEXTLIB) \
$(PERL_ARCHIVE) %s $(PERL_ARCHIVE_AFTER) %s \
$(INST_DYNAMIC_FIX)
$(CHMOD) $(PERM_RWX) $@
MAKE
join '', @m;
}
1;
=back
=head1 AUTHOR
Michael G Schwern <schwern@pobox.com> with code from ExtUtils::MM_Unix
=head1 SEE ALSO
L<ExtUtils::MakeMaker>
=cut
__END__

View file

@ -0,0 +1,59 @@
package ExtUtils::MM_QNX;
use strict;
use warnings;
our $VERSION = '7.70';
$VERSION =~ tr/_//d;
require ExtUtils::MM_Unix;
our @ISA = qw(ExtUtils::MM_Unix);
=head1 NAME
ExtUtils::MM_QNX - QNX specific subclass of ExtUtils::MM_Unix
=head1 SYNOPSIS
Don't use this module directly.
Use ExtUtils::MM and let it choose.
=head1 DESCRIPTION
This is a subclass of L<ExtUtils::MM_Unix> which contains functionality for
QNX.
Unless otherwise stated it works just like ExtUtils::MM_Unix.
=head2 Overridden methods
=head3 extra_clean_files
Add .err files corresponding to each .c file.
=cut
sub extra_clean_files {
my $self = shift;
my @errfiles = @{$self->{C}};
for ( @errfiles ) {
s/.c$/.err/;
}
return( @errfiles, 'perlmain.err' );
}
=head1 AUTHOR
Michael G Schwern <schwern@pobox.com> with code from ExtUtils::MM_Unix
=head1 SEE ALSO
L<ExtUtils::MakeMaker>
=cut
1;

View file

@ -0,0 +1,66 @@
package ExtUtils::MM_UWIN;
use strict;
use warnings;
our $VERSION = '7.70';
$VERSION =~ tr/_//d;
require ExtUtils::MM_Unix;
our @ISA = qw(ExtUtils::MM_Unix);
=head1 NAME
ExtUtils::MM_UWIN - U/WIN specific subclass of ExtUtils::MM_Unix
=head1 SYNOPSIS
Don't use this module directly.
Use ExtUtils::MM and let it choose.
=head1 DESCRIPTION
This is a subclass of L<ExtUtils::MM_Unix> which contains functionality for
the AT&T U/WIN UNIX on Windows environment.
Unless otherwise stated it works just like ExtUtils::MM_Unix.
=head2 Overridden methods
=over 4
=item os_flavor
In addition to being Unix, we're U/WIN.
=cut
sub os_flavor {
return('Unix', 'U/WIN');
}
=item B<replace_manpage_separator>
=cut
sub replace_manpage_separator {
my($self, $man) = @_;
$man =~ s,/+,.,g;
return $man;
}
=back
=head1 AUTHOR
Michael G Schwern <schwern@pobox.com> with code from ExtUtils::MM_Unix
=head1 SEE ALSO
L<ExtUtils::MM_Win32>, L<ExtUtils::MakeMaker>
=cut
1;

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,52 @@
package ExtUtils::MM_VOS;
use strict;
use warnings;
our $VERSION = '7.70';
$VERSION =~ tr/_//d;
require ExtUtils::MM_Unix;
our @ISA = qw(ExtUtils::MM_Unix);
=head1 NAME
ExtUtils::MM_VOS - VOS specific subclass of ExtUtils::MM_Unix
=head1 SYNOPSIS
Don't use this module directly.
Use ExtUtils::MM and let it choose.
=head1 DESCRIPTION
This is a subclass of L<ExtUtils::MM_Unix> which contains functionality for
VOS.
Unless otherwise stated it works just like ExtUtils::MM_Unix.
=head2 Overridden methods
=head3 extra_clean_files
Cleanup VOS core files
=cut
sub extra_clean_files {
return qw(*.kp);
}
=head1 AUTHOR
Michael G Schwern <schwern@pobox.com> with code from ExtUtils::MM_Unix
=head1 SEE ALSO
L<ExtUtils::MakeMaker>
=cut
1;

View file

@ -0,0 +1,663 @@
package ExtUtils::MM_Win32;
use strict;
use warnings;
=head1 NAME
ExtUtils::MM_Win32 - methods to override UN*X behaviour in ExtUtils::MakeMaker
=head1 SYNOPSIS
use ExtUtils::MM_Win32; # Done internally by ExtUtils::MakeMaker if needed
=head1 DESCRIPTION
See L<ExtUtils::MM_Unix> for a documentation of the methods provided
there. This package overrides the implementation of these methods, not
the semantics.
=cut
use ExtUtils::MakeMaker::Config;
use File::Basename;
use File::Spec;
use ExtUtils::MakeMaker qw(neatvalue _sprintf562);
require ExtUtils::MM_Any;
require ExtUtils::MM_Unix;
our @ISA = qw( ExtUtils::MM_Any ExtUtils::MM_Unix );
our $VERSION = '7.70';
$VERSION =~ tr/_//d;
$ENV{EMXSHELL} = 'sh'; # to run `commands`
my ( $BORLAND, $GCC, $MSVC ) = _identify_compiler_environment( \%Config );
sub _identify_compiler_environment {
my ( $config ) = @_;
my $BORLAND = $config->{cc} =~ /\bbcc/i ? 1 : 0;
my $GCC = $config->{cc} =~ /\bgcc\b/i ? 1 : 0;
my $MSVC = $config->{cc} =~ /\b(?:cl|icl)/i ? 1 : 0; # MSVC can come as clarm.exe, icl=Intel C
return ( $BORLAND, $GCC, $MSVC );
}
=head2 Overridden methods
=over 4
=item B<dlsyms>
=cut
sub dlsyms {
my($self,%attribs) = @_;
return '' if $self->{SKIPHASH}{'dynamic'};
$self->xs_dlsyms_iterator(\%attribs);
}
=item xs_dlsyms_ext
On Win32, is C<.def>.
=cut
sub xs_dlsyms_ext {
'.def';
}
=item replace_manpage_separator
Changes the path separator with .
=cut
sub replace_manpage_separator {
my($self,$man) = @_;
$man =~ s,[/\\]+,.,g;
$man;
}
=item B<maybe_command>
Since Windows has nothing as simple as an executable bit, we check the
file extension.
The PATHEXT env variable will be used to get a list of extensions that
might indicate a command, otherwise .com, .exe, .bat and .cmd will be
used by default.
=cut
sub maybe_command {
my($self,$file) = @_;
my @e = exists($ENV{'PATHEXT'})
? split(/;/, $ENV{PATHEXT})
: qw(.com .exe .bat .cmd);
my $e = '';
for (@e) { $e .= "\Q$_\E|" }
chop $e;
# see if file ends in one of the known extensions
if ($file =~ /($e)$/i) {
return $file if -e $file;
}
else {
for (@e) {
return "$file$_" if -e "$file$_";
}
}
return;
}
=item B<init_DIRFILESEP>
Using \ for Windows, except for "gmake" where it is /.
=cut
sub init_DIRFILESEP {
my($self) = shift;
# The ^ makes sure its not interpreted as an escape in nmake
$self->{DIRFILESEP} = $self->is_make_type('nmake') ? '^\\' :
$self->is_make_type('dmake') ? '\\\\' :
$self->is_make_type('gmake') ? '/'
: '\\';
}
=item init_tools
Override some of the slower, portable commands with Windows specific ones.
=cut
sub init_tools {
my ($self) = @_;
$self->{NOOP} ||= 'rem';
$self->{DEV_NULL} ||= '> NUL';
$self->{FIXIN} ||= $self->{PERL_CORE} ?
"\$(PERLRUN) -I$self->{PERL_SRC}\\cpan\\ExtUtils-PL2Bat\\lib $self->{PERL_SRC}\\win32\\bin\\pl2bat.pl" :
'pl2bat.bat';
$self->SUPER::init_tools;
# Setting SHELL from $Config{sh} can break dmake. Its ok without it.
delete $self->{SHELL};
return;
}
=item init_others
Override the default link and compile tools.
LDLOADLIBS's default is changed to $Config{libs}.
Adjustments are made for Borland's quirks needing -L to come first.
=cut
sub init_others {
my $self = shift;
$self->{LD} ||= 'link';
$self->{AR} ||= 'lib';
$self->SUPER::init_others;
$self->{LDLOADLIBS} ||= $Config{libs};
# -Lfoo must come first for Borland, so we put it in LDDLFLAGS
if ($BORLAND) {
my $libs = $self->{LDLOADLIBS};
my $libpath = '';
while ($libs =~ s/(?:^|\s)(("?)-L.+?\2)(?:\s|$)/ /) {
$libpath .= ' ' if length $libpath;
$libpath .= $1;
}
$self->{LDLOADLIBS} = $libs;
$self->{LDDLFLAGS} ||= $Config{lddlflags};
$self->{LDDLFLAGS} .= " $libpath";
}
return;
}
=item init_platform
Add MM_Win32_VERSION.
=item platform_constants
=cut
sub init_platform {
my($self) = shift;
$self->{MM_Win32_VERSION} = $VERSION;
return;
}
sub platform_constants {
my($self) = shift;
my $make_frag = '';
foreach my $macro (qw(MM_Win32_VERSION))
{
next unless defined $self->{$macro};
$make_frag .= "$macro = $self->{$macro}\n";
}
return $make_frag;
}
=item specify_shell
Set SHELL to $ENV{COMSPEC} only if make is type 'gmake'.
=cut
sub specify_shell {
my $self = shift;
return '' unless $self->is_make_type('gmake');
"\nSHELL = $ENV{COMSPEC}\n";
}
=item constants
Add MAXLINELENGTH for dmake before all the constants are output.
=cut
sub constants {
my $self = shift;
my $make_text = $self->SUPER::constants;
return $make_text unless $self->is_make_type('dmake');
# dmake won't read any single "line" (even those with escaped newlines)
# larger than a certain size which can be as small as 8k. PM_TO_BLIB
# on large modules like DateTime::TimeZone can create lines over 32k.
# So we'll crank it up to a <ironic>WHOPPING</ironic> 64k.
#
# This has to come here before all the constants and not in
# platform_constants which is after constants.
my $size = $self->{MAXLINELENGTH} || 800000;
my $prefix = qq{
# Get dmake to read long commands like PM_TO_BLIB
MAXLINELENGTH = $size
};
return $prefix . $make_text;
}
=item special_targets
Add .USESHELL target for dmake.
=cut
sub special_targets {
my($self) = @_;
my $make_frag = $self->SUPER::special_targets;
$make_frag .= <<'MAKE_FRAG' if $self->is_make_type('dmake');
.USESHELL :
MAKE_FRAG
return $make_frag;
}
=item static_lib_pure_cmd
Defines how to run the archive utility
=cut
sub static_lib_pure_cmd {
my ($self, $from) = @_;
$from =~ s/(\$\(\w+)(\))/$1:^"+"$2/g if $BORLAND;
sprintf qq{\t\$(AR) %s\n}, ($BORLAND ? '$@ ' . $from
: ($GCC ? '-ru $@ ' . $from
: '-out:$@ ' . $from));
}
=item dynamic_lib
Methods are overridden here: not dynamic_lib itself, but the utility
ones that do the OS-specific work.
=cut
sub xs_make_dynamic_lib {
my ($self, $attribs, $from, $to, $todir, $ldfrom, $exportlist) = @_;
my @m = sprintf '%s : %s $(MYEXTLIB) %s$(DFSEP).exists %s $(PERL_ARCHIVEDEP) $(INST_DYNAMIC_DEP)'."\n", $to, $from, $todir, $exportlist;
if ($GCC) {
# per https://rt.cpan.org/Ticket/Display.html?id=78395 no longer
# uses dlltool - relies on post 2002 MinGW
# 1 2
push @m, _sprintf562 <<'EOF', $exportlist, $ldfrom;
$(LD) %1$s -o $@ $(LDDLFLAGS) %2$s $(OTHERLDFLAGS) $(MYEXTLIB) "$(PERL_ARCHIVE)" $(LDLOADLIBS) -Wl,--enable-auto-image-base
EOF
} elsif ($BORLAND) {
my $ldargs = $self->is_make_type('dmake')
? q{"$(PERL_ARCHIVE:s,/,\,)" $(LDLOADLIBS:s,/,\,) $(MYEXTLIB:s,/,\,),}
: q{"$(subst /,\,$(PERL_ARCHIVE))" $(subst /,\,$(LDLOADLIBS)) $(subst /,\,$(MYEXTLIB)),};
my $subbed;
if ($exportlist eq '$(EXPORT_LIST)') {
$subbed = $self->is_make_type('dmake')
? q{$(EXPORT_LIST:s,/,\,)}
: q{$(subst /,\,$(EXPORT_LIST))};
} else {
# in XSMULTI, exportlist is per-XS, so have to sub in perl not make
($subbed = $exportlist) =~ s#/#\\#g;
}
push @m, sprintf <<'EOF', $ldfrom, $ldargs . $subbed;
$(LD) $(LDDLFLAGS) $(OTHERLDFLAGS) %s,$@,,%s,$(RESFILES)
EOF
} else { # VC
push @m, sprintf <<'EOF', $ldfrom, $exportlist;
$(LD) -out:$@ $(LDDLFLAGS) %s $(OTHERLDFLAGS) $(MYEXTLIB) "$(PERL_ARCHIVE)" $(LDLOADLIBS) -def:%s
EOF
# Embed the manifest file if it exists
push(@m, q{ if exist $@.manifest mt -nologo -manifest $@.manifest -outputresource:$@;2
if exist $@.manifest del $@.manifest});
}
push @m, "\n\t\$(CHMOD) \$(PERM_RWX) \$\@\n";
join '', @m;
}
sub xs_dynamic_lib_macros {
my ($self, $attribs) = @_;
my $otherldflags = $attribs->{OTHERLDFLAGS} || ($BORLAND ? 'c0d32.obj': '');
my $inst_dynamic_dep = $attribs->{INST_DYNAMIC_DEP} || "";
sprintf <<'EOF', $otherldflags, $inst_dynamic_dep;
# This section creates the dynamically loadable objects from relevant
# objects and possibly $(MYEXTLIB).
OTHERLDFLAGS = %s
INST_DYNAMIC_DEP = %s
EOF
}
=item extra_clean_files
Clean out some extra dll.{base,exp} files which might be generated by
gcc. Otherwise, take out all *.pdb files.
=cut
sub extra_clean_files {
my $self = shift;
return $GCC ? (qw(dll.base dll.exp)) : ('*.pdb');
}
=item init_linker
=cut
sub init_linker {
my $self = shift;
$self->{PERL_ARCHIVE} = "\$(PERL_INC)\\$Config{libperl}";
$self->{PERL_ARCHIVEDEP} = "\$(PERL_INCDEP)\\$Config{libperl}";
$self->{PERL_ARCHIVE_AFTER} = '';
$self->{EXPORT_LIST} = '$(BASEEXT).def';
}
=item perl_script
Checks for the perl program under several common perl extensions.
=cut
sub perl_script {
my($self,$file) = @_;
return $file if -r $file && -f _;
return "$file.pl" if -r "$file.pl" && -f _;
return "$file.plx" if -r "$file.plx" && -f _;
return "$file.bat" if -r "$file.bat" && -f _;
return;
}
sub can_dep_space {
my ($self) = @_;
return 0 unless $self->can_load_xs;
require Win32;
require File::Spec;
my ($vol, $dir) = File::Spec->splitpath($INC{'ExtUtils/MakeMaker.pm'});
# can_dep_space via GetShortPathName, if short paths are supported
my $canary = Win32::GetShortPathName(File::Spec->catpath($vol, $dir, 'MakeMaker.pm'));
(undef, undef, my $file) = File::Spec->splitpath($canary);
return (length $file > 11) ? 0 : 1;
}
=item quote_dep
=cut
sub quote_dep {
my ($self, $arg) = @_;
if ($arg =~ / / and not $self->is_make_type('gmake')) {
require Win32;
$arg = Win32::GetShortPathName($arg);
die <<EOF if not defined $arg or $arg =~ / /;
Tried to use make dependency with space for non-GNU make:
'$arg'
Fallback to short pathname failed.
EOF
return $arg;
}
return $self->SUPER::quote_dep($arg);
}
=item xs_obj_opt
Override to fixup -o flags for MSVC.
=cut
sub xs_obj_opt {
my ($self, $output_file) = @_;
($MSVC ? "/Fo" : "-o ") . $output_file;
}
=item pasthru
All we send is -nologo to nmake to prevent it from printing its damned
banner.
=cut
sub pasthru {
my($self) = shift;
my $old = $self->SUPER::pasthru;
return $old unless $self->is_make_type('nmake');
$old =~ s/(PASTHRU\s*=\s*)/$1 -nologo /;
$old;
}
=item arch_check (override)
Normalize all arguments for consistency of comparison.
=cut
sub arch_check {
my $self = shift;
# Win32 is an XS module, minperl won't have it.
# arch_check() is not critical, so just fake it.
return 1 unless $self->can_load_xs;
return $self->SUPER::arch_check( map { $self->_normalize_path_name($_) } @_);
}
sub _normalize_path_name {
my $self = shift;
my $file = shift;
require Win32;
my $short = Win32::GetShortPathName($file);
return defined $short ? lc $short : lc $file;
}
=item oneliner
These are based on what command.com does on Win98. They may be wrong
for other Windows shells, I don't know.
=cut
sub oneliner {
my($self, $cmd, $switches) = @_;
$switches = [] unless defined $switches;
# Strip leading and trailing newlines
$cmd =~ s{^\n+}{};
$cmd =~ s{\n+$}{};
$cmd = $self->quote_literal($cmd);
$cmd = $self->escape_newlines($cmd);
$switches = join ' ', @$switches;
return qq{\$(ABSPERLRUN) $switches -e $cmd --};
}
sub quote_literal {
my($self, $text, $opts) = @_;
$opts->{allow_variables} = 1 unless defined $opts->{allow_variables};
# See: http://www.autohotkey.net/~deleyd/parameters/parameters.htm#CPP
# Apply the Microsoft C/C++ parsing rules
$text =~ s{\\\\"}{\\\\\\\\\\"}g; # \\" -> \\\\\"
$text =~ s{(?<!\\)\\"}{\\\\\\"}g; # \" -> \\\"
$text =~ s{(?<!\\)"}{\\"}g; # " -> \"
$text = qq{"$text"} if $text =~ /[ \t#]/; # hash because gmake 4.2.1
# Apply the Command Prompt parsing rules (cmd.exe)
my @text = split /("[^"]*")/, $text;
# We should also escape parentheses, but it breaks one-liners containing
# $(MACRO)s in makefiles.
s{([<>|&^@!])}{^$1}g foreach grep { !/^"[^"]*"$/ } @text;
$text = join('', @text);
# dmake expands {{ to { and }} to }.
if( $self->is_make_type('dmake') ) {
$text =~ s/{/{{/g;
$text =~ s/}/}}/g;
}
$text = $opts->{allow_variables}
? $self->escape_dollarsigns($text) : $self->escape_all_dollarsigns($text);
return $text;
}
sub escape_newlines {
my($self, $text) = @_;
# Escape newlines
$text =~ s{\n}{\\\n}g;
return $text;
}
=item cd
dmake can handle Unix style cd'ing but nmake (at least 1.5) cannot. It
wants:
cd dir1\dir2
command
another_command
cd ..\..
=cut
sub cd {
my($self, $dir, @cmds) = @_;
return $self->SUPER::cd($dir, @cmds) unless $self->is_make_type('nmake');
my $cmd = join "\n\t", map "$_", @cmds;
my $updirs = $self->catdir(map { $self->updir } $self->splitdir($dir));
# No leading tab and no trailing newline makes for easier embedding.
my $make_frag = sprintf <<'MAKE_FRAG', $dir, $cmd, $updirs;
cd %s
%s
cd %s
MAKE_FRAG
chomp $make_frag;
return $make_frag;
}
=item max_exec_len
nmake 1.50 limits command length to 2048 characters.
=cut
sub max_exec_len {
my $self = shift;
return $self->{_MAX_EXEC_LEN} ||= 2 * 1024;
}
=item os_flavor
Windows is Win32.
=cut
sub os_flavor {
return('Win32');
}
=item dbgoutflag
Returns a CC flag that tells the CC to emit a separate debugging symbol file
when compiling an object file.
=cut
sub dbgoutflag {
$MSVC ? '-Fd$(*).pdb' : '';
}
=item cflags
Defines the PERLDLL symbol if we are configured for static building since all
code destined for the perl5xx.dll must be compiled with the PERLDLL symbol
defined.
=cut
sub cflags {
my($self,$libperl)=@_;
return $self->{CFLAGS} if $self->{CFLAGS};
return '' unless $self->needs_linking();
my $base = $self->SUPER::cflags($libperl);
foreach (split /\n/, $base) {
/^(\S*)\s*=\s*(\S*)$/ and $self->{$1} = $2;
};
$self->{CCFLAGS} .= " -DPERLDLL" if ($self->{LINKTYPE} eq 'static');
return $self->{CFLAGS} = qq{
CCFLAGS = $self->{CCFLAGS}
OPTIMIZE = $self->{OPTIMIZE}
PERLTYPE = $self->{PERLTYPE}
};
}
=item make_type
Returns a suitable string describing the type of makefile being written.
=cut
sub make_type {
my ($self) = @_;
my $make = $self->make;
$make = +( File::Spec->splitpath( $make ) )[-1];
$make =~ s!\.exe$!!i;
if ( $make =~ m![^A-Z0-9]!i ) {
($make) = grep { m!make!i } split m![^A-Z0-9]!i, $make;
}
return "$make-style";
}
1;
__END__
=back

View file

@ -0,0 +1,77 @@
package ExtUtils::MM_Win95;
use strict;
use warnings;
our $VERSION = '7.70';
$VERSION =~ tr/_//d;
require ExtUtils::MM_Win32;
our @ISA = qw(ExtUtils::MM_Win32);
use ExtUtils::MakeMaker::Config;
=head1 NAME
ExtUtils::MM_Win95 - method to customize MakeMaker for Win9X
=head1 SYNOPSIS
You should not be using this module directly.
=head1 DESCRIPTION
This is a subclass of L<ExtUtils::MM_Win32> containing changes necessary
to get MakeMaker playing nice with command.com and other Win9Xisms.
=head2 Overridden methods
Most of these make up for limitations in the Win9x/nmake command shell.
=over 4
=item max_exec_len
Win98 chokes on things like Encode if we set the max length to nmake's max
of 2K. So we go for a more conservative value of 1K.
=cut
sub max_exec_len {
my $self = shift;
return $self->{_MAX_EXEC_LEN} ||= 1024;
}
=item os_flavor
Win95 and Win98 and WinME are collectively Win9x and Win32
=cut
sub os_flavor {
my $self = shift;
return ($self->SUPER::os_flavor, 'Win9x');
}
=back
=head1 AUTHOR
Code originally inside MM_Win32. Original author unknown.
Currently maintained by Michael G Schwern C<schwern@pobox.com>.
Send patches and ideas to C<makemaker@perl.org>.
See https://metacpan.org/release/ExtUtils-MakeMaker.
=cut
1;

View file

@ -0,0 +1,41 @@
package ExtUtils::MY;
use strict;
require ExtUtils::MM;
our $VERSION = '7.70';
$VERSION =~ tr/_//d;
our @ISA = qw(ExtUtils::MM);
{
package MY;
our @ISA = qw(ExtUtils::MY);
}
sub DESTROY {}
=head1 NAME
ExtUtils::MY - ExtUtils::MakeMaker subclass for customization
=head1 SYNOPSIS
# in your Makefile.PL
sub MY::whatever {
...
}
=head1 DESCRIPTION
B<FOR INTERNAL USE ONLY>
ExtUtils::MY is a subclass of L<ExtUtils::MM>. It is provided in your
Makefile.PL for you to add and override MakeMaker functionality.
It also provides a convenient alias via the MY class.
ExtUtils::MY might turn out to be a temporary solution, but MY won't
go away.
=cut

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,41 @@
package ExtUtils::MakeMaker::Config;
use strict;
use warnings;
our $VERSION = '7.70';
$VERSION =~ tr/_//d;
use Config ();
# Give us an overridable config.
our %Config = %Config::Config;
sub import {
my $caller = caller;
no strict 'refs'; ## no critic
*{$caller.'::Config'} = \%Config;
}
1;
=head1 NAME
ExtUtils::MakeMaker::Config - Wrapper around Config.pm
=head1 SYNOPSIS
use ExtUtils::MakeMaker::Config;
print $Config{installbin}; # or whatever
=head1 DESCRIPTION
B<FOR INTERNAL USE ONLY>
A very thin wrapper around Config.pm so MakeMaker is easier to test.
=cut

View file

@ -0,0 +1,667 @@
package ExtUtils::MakeMaker::FAQ;
our $VERSION = '7.70';
$VERSION =~ tr/_//d;
1;
__END__
=head1 NAME
ExtUtils::MakeMaker::FAQ - Frequently Asked Questions About MakeMaker
=head1 DESCRIPTION
FAQs, tricks and tips for L<ExtUtils::MakeMaker>.
=head2 Module Installation
=over 4
=item How do I install a module into my home directory?
If you're not the Perl administrator you probably don't have
permission to install a module to its default location. Ways of handling
this with a B<lot> less manual effort on your part are L<perlbrew>
and L<local::lib>.
Otherwise, you can install it for your own use into your home directory
like so:
# Non-unix folks, replace ~ with /path/to/your/home/dir
perl Makefile.PL INSTALL_BASE=~
This will put modules into F<~/lib/perl5>, man pages into F<~/man> and
programs into F<~/bin>.
To ensure your Perl programs can see these newly installed modules,
set your C<PERL5LIB> environment variable to F<~/lib/perl5> or tell
each of your programs to look in that directory with the following:
use lib "$ENV{HOME}/lib/perl5";
or if $ENV{HOME} isn't set and you don't want to set it for some
reason, do it the long way.
use lib "/path/to/your/home/dir/lib/perl5";
=item How do I get MakeMaker and Module::Build to install to the same place?
Module::Build, as of 0.28, supports two ways to install to the same
location as MakeMaker.
We highly recommend the install_base method, its the simplest and most
closely approximates the expected behavior of an installation prefix.
1) Use INSTALL_BASE / C<--install_base>
MakeMaker (as of 6.31) and Module::Build (as of 0.28) both can install
to the same locations using the "install_base" concept. See
L<ExtUtils::MakeMaker/INSTALL_BASE> for details. To get MM and MB to
install to the same location simply set INSTALL_BASE in MM and
C<--install_base> in MB to the same location.
perl Makefile.PL INSTALL_BASE=/whatever
perl Build.PL --install_base /whatever
This works most like other language's behavior when you specify a
prefix. We recommend this method.
2) Use PREFIX / C<--prefix>
Module::Build 0.28 added support for C<--prefix> which works like
MakeMaker's PREFIX.
perl Makefile.PL PREFIX=/whatever
perl Build.PL --prefix /whatever
We highly discourage this method. It should only be used if you know
what you're doing and specifically need the PREFIX behavior. The
PREFIX algorithm is complicated and focused on matching the system
installation.
=item How do I keep from installing man pages?
Recent versions of MakeMaker will only install man pages on Unix-like
operating systems by default. To generate manpages on non-Unix operating
systems, make the "manifypods" target.
For an individual module:
perl Makefile.PL INSTALLMAN1DIR=none INSTALLMAN3DIR=none
If you want to suppress man page installation for all modules you have
to reconfigure Perl and tell it 'none' when it asks where to install
man pages.
=item How do I use a module without installing it?
Two ways. One is to build the module normally...
perl Makefile.PL
make
make test
...and then use L<blib> to point Perl at the built but uninstalled module:
perl -Mblib script.pl
perl -Mblib -e '...'
The other is to install the module in a temporary location.
perl Makefile.PL INSTALL_BASE=~/tmp
make
make test
make install
And then set PERL5LIB to F<~/tmp/lib/perl5>. This works well when you
have multiple modules to work with. It also ensures that the module
goes through its full installation process which may modify it.
Again, L<local::lib> may assist you here.
=item How can I organize tests into subdirectories and have them run?
Let's take the following test directory structure:
t/foo/sometest.t
t/bar/othertest.t
t/bar/baz/anothertest.t
Now, inside of the C<WriteMakefile()> function in your F<Makefile.PL>, specify
where your tests are located with the C<test> directive:
test => {TESTS => 't/*.t t/*/*.t t/*/*/*.t'}
The first entry in the string will run all tests in the top-level F<t/>
directory. The second will run all test files located in any subdirectory under
F<t/>. The third, runs all test files within any subdirectory within any other
subdirectory located under F<t/>.
Note that you do not have to use wildcards. You can specify explicitly which
subdirectories to run tests in:
test => {TESTS => 't/*.t t/foo/*.t t/bar/baz/*.t'}
=item PREFIX vs INSTALL_BASE from Module::Build::Cookbook
The behavior of PREFIX is complicated and depends closely on how your
Perl is configured. The resulting installation locations will vary
from machine to machine and even different installations of Perl on the
same machine. Because of this, its difficult to document where prefix
will place your modules.
In contrast, INSTALL_BASE has predictable, easy to explain installation
locations. Now that Module::Build and MakeMaker both have INSTALL_BASE
there is little reason to use PREFIX other than to preserve your existing
installation locations. If you are starting a fresh Perl installation we
encourage you to use INSTALL_BASE. If you have an existing installation
installed via PREFIX, consider moving it to an installation structure
matching INSTALL_BASE and using that instead.
=item Generating *.pm files with substitutions eg of $VERSION
If you want to configure your module files for local conditions, or to
automatically insert a version number, you can use EUMM's C<PL_FILES>
capability, where it will automatically run each F<*.PL> it finds to
generate its basename. For instance:
# Makefile.PL:
require 'common.pl';
my $version = get_version();
my @pms = qw(Foo.pm);
WriteMakefile(
NAME => 'Foo',
VERSION => $version,
PM => { map { ($_ => "\$(INST_LIB)/$_") } @pms },
clean => { FILES => join ' ', @pms },
);
# common.pl:
sub get_version { '0.04' }
sub process { my $v = get_version(); s/__VERSION__/$v/g; }
1;
# Foo.pm.PL:
require 'common.pl';
$_ = join '', <DATA>;
process();
my $file = shift;
open my $fh, '>', $file or die "$file: $!";
print $fh $_;
__DATA__
package Foo;
our $VERSION = '__VERSION__';
1;
You may notice that C<PL_FILES> is not specified above, since the default
of mapping each .PL file to its basename works well.
If the generated module were architecture-specific, you could replace
C<$(INST_LIB)> above with C<$(INST_ARCHLIB)>, although if you locate
modules under F<lib>, that would involve ensuring any C<lib/> in front
of the module location were removed.
=back
=head2 Common errors and problems
=over 4
=item "No rule to make target `/usr/lib/perl5/CORE/config.h', needed by `Makefile'"
Just what it says, you're missing that file. MakeMaker uses it to
determine if perl has been rebuilt since the Makefile was made. It's
a bit of a bug that it halts installation.
Some operating systems don't ship the CORE directory with their base
perl install. To solve the problem, you likely need to install a perl
development package such as perl-devel (CentOS, Fedora and other
Redhat systems) or perl (Ubuntu and other Debian systems).
=back
=head2 Philosophy and History
=over 4
=item Why not just use <insert other build config tool here>?
Why did MakeMaker reinvent the build configuration wheel? Why not
just use autoconf or automake or ppm or Ant or ...
There are many reasons, but the major one is cross-platform
compatibility.
Perl is one of the most ported pieces of software ever. It works on
operating systems I've never even heard of (see perlport for details).
It needs a build tool that can work on all those platforms and with
any wacky C compilers and linkers they might have.
No such build tool exists. Even make itself has wildly different
dialects. So we have to build our own.
=item What is Module::Build and how does it relate to MakeMaker?
Module::Build is a project by Ken Williams to supplant MakeMaker.
Its primary advantages are:
=over 8
=item * pure perl. no make, no shell commands
=item * easier to customize
=item * cleaner internals
=item * less cruft
=back
Module::Build was long the official heir apparent to MakeMaker. The
rate of both its development and adoption has slowed in recent years,
though, and it is unclear what the future holds for it. That said,
Module::Build set the stage for I<something> to become the heir to
MakeMaker. MakeMaker's maintainers have long said that it is a dead
end and should be kept functioning, while being cautious about extending
with new features.
=back
=head2 Module Writing
=over 4
=item How do I keep my $VERSION up to date without resetting it manually?
Often you want to manually set the $VERSION in the main module
distribution because this is the version that everybody sees on CPAN
and maybe you want to customize it a bit. But for all the other
modules in your dist, $VERSION is really just bookkeeping and all that's
important is it goes up every time the module is changed. Doing this
by hand is a pain and you often forget.
Probably the easiest way to do this is using F<perl-reversion> in
L<Perl::Version>:
perl-reversion -bump
If your version control system supports revision numbers (git doesn't
easily), the simplest way to do it automatically is to use its revision
number (you are using version control, right?).
In CVS, RCS and SVN you use $Revision$ (see the documentation of your
version control system for details). Every time the file is checked
in the $Revision$ will be updated, updating your $VERSION.
SVN uses a simple integer for $Revision$ so you can adapt it for your
$VERSION like so:
($VERSION) = q$Revision$ =~ /(\d+)/;
In CVS and RCS version 1.9 is followed by 1.10. Since CPAN compares
version numbers numerically we use a sprintf() to convert 1.9 to 1.009
and 1.10 to 1.010 which compare properly.
$VERSION = sprintf "%d.%03d", q$Revision$ =~ /(\d+)\.(\d+)/g;
If branches are involved (ie. $Revision: 1.5.3.4$) it's a little more
complicated.
# must be all on one line or MakeMaker will get confused.
$VERSION = do { my @r = (q$Revision$ =~ /\d+/g); sprintf "%d."."%03d" x $#r, @r };
In SVN, $Revision$ should be the same for every file in the project so
they would all have the same $VERSION. CVS and RCS have a different
$Revision$ per file so each file will have a different $VERSION.
Distributed version control systems, such as SVK, may have a different
$Revision$ based on who checks out the file, leading to a different $VERSION
on each machine! Finally, some distributed version control systems, such
as darcs, have no concept of revision number at all.
=item What's this F<META.yml> thing and how did it get in my F<MANIFEST>?!
F<META.yml> is a module meta-data file pioneered by Module::Build and
automatically generated as part of the 'distdir' target (and thus
'dist'). See L<ExtUtils::MakeMaker/"Module Meta-Data">.
To shut off its generation, pass the C<NO_META> flag to C<WriteMakefile()>.
=item How do I delete everything not in my F<MANIFEST>?
Some folks are surprised that C<make distclean> does not delete
everything not listed in their MANIFEST (thus making a clean
distribution) but only tells them what they need to delete. This is
done because it is considered too dangerous. While developing your
module you might write a new file, not add it to the MANIFEST, then
run a C<distclean> and be sad because your new work was deleted.
If you really want to do this, you can use
C<ExtUtils::Manifest::manifind()> to read the MANIFEST and File::Find
to delete the files. But you have to be careful. Here's a script to
do that. Use at your own risk. Have fun blowing holes in your foot.
#!/usr/bin/perl -w
use strict;
use File::Spec;
use File::Find;
use ExtUtils::Manifest qw(maniread);
my %manifest = map {( $_ => 1 )}
grep { File::Spec->canonpath($_) }
keys %{ maniread() };
if( !keys %manifest ) {
print "No files found in MANIFEST. Stopping.\n";
exit;
}
find({
wanted => sub {
my $path = File::Spec->canonpath($_);
return unless -f $path;
return if exists $manifest{ $path };
print "unlink $path\n";
unlink $path;
},
no_chdir => 1
},
"."
);
=item Which tar should I use on Windows?
We recommend ptar from Archive::Tar not older than 1.66 with '-C' option.
=item Which zip should I use on Windows for '[ndg]make zipdist'?
We recommend InfoZIP: L<http://www.info-zip.org/Zip.html>
=back
=head2 XS
=over 4
=item How do I prevent "object version X.XX does not match bootstrap parameter Y.YY" errors?
XS code is very sensitive to the module version number and will
complain if the version number in your Perl module doesn't match. If
you change your module's version # without rerunning Makefile.PL the old
version number will remain in the Makefile, causing the XS code to be built
with the wrong number.
To avoid this, you can force the Makefile to be rebuilt whenever you
change the module containing the version number by adding this to your
WriteMakefile() arguments.
depend => { '$(FIRST_MAKEFILE)' => '$(VERSION_FROM)' }
=item How do I make two or more XS files coexist in the same directory?
Sometimes you need to have two and more XS files in the same package.
There are three ways: C<XSMULTI>, separate directories, and bootstrapping
one XS from another.
=over 8
=item XSMULTI
Structure your modules so they are all located under F<lib>, such that
C<Foo::Bar> is in F<lib/Foo/Bar.pm> and F<lib/Foo/Bar.xs>, etc. Have your
top-level C<WriteMakefile> set the variable C<XSMULTI> to a true value.
Er, that's it.
=item Separate directories
Put each XS files into separate directories, each with their own
F<Makefile.PL>. Make sure each of those F<Makefile.PL>s has the correct
C<CFLAGS>, C<INC>, C<LIBS> etc. You will need to make sure the top-level
F<Makefile.PL> refers to each of these using C<DIR>.
=item Bootstrapping
Let's assume that we have a package C<Cool::Foo>, which includes
C<Cool::Foo> and C<Cool::Bar> modules each having a separate XS
file. First we use the following I<Makefile.PL>:
use ExtUtils::MakeMaker;
WriteMakefile(
NAME => 'Cool::Foo',
VERSION_FROM => 'Foo.pm',
OBJECT => q/$(O_FILES)/,
# ... other attrs ...
);
Notice the C<OBJECT> attribute. MakeMaker generates the following
variables in I<Makefile>:
# Handy lists of source code files:
XS_FILES= Bar.xs \
Foo.xs
C_FILES = Bar.c \
Foo.c
O_FILES = Bar.o \
Foo.o
Therefore we can use the C<O_FILES> variable to tell MakeMaker to use
these objects into the shared library.
That's pretty much it. Now write I<Foo.pm> and I<Foo.xs>, I<Bar.pm>
and I<Bar.xs>, where I<Foo.pm> bootstraps the shared library and
I<Bar.pm> simply loading I<Foo.pm>.
The only issue left is to how to bootstrap I<Bar.xs>. This is done
from I<Foo.xs>:
MODULE = Cool::Foo PACKAGE = Cool::Foo
BOOT:
# boot the second XS file
boot_Cool__Bar(aTHX_ cv);
If you have more than two files, this is the place where you should
boot extra XS files from.
The following four files sum up all the details discussed so far.
Foo.pm:
-------
package Cool::Foo;
require DynaLoader;
our @ISA = qw(DynaLoader);
our $VERSION = '0.01';
bootstrap Cool::Foo $VERSION;
1;
Bar.pm:
-------
package Cool::Bar;
use Cool::Foo; # bootstraps Bar.xs
1;
Foo.xs:
-------
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
MODULE = Cool::Foo PACKAGE = Cool::Foo
BOOT:
# boot the second XS file
boot_Cool__Bar(aTHX_ cv);
MODULE = Cool::Foo PACKAGE = Cool::Foo PREFIX = cool_foo_
void
cool_foo_perl_rules()
CODE:
fprintf(stderr, "Cool::Foo says: Perl Rules\n");
Bar.xs:
-------
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
MODULE = Cool::Bar PACKAGE = Cool::Bar PREFIX = cool_bar_
void
cool_bar_perl_rules()
CODE:
fprintf(stderr, "Cool::Bar says: Perl Rules\n");
And of course a very basic test:
t/cool.t:
--------
use Test::More tests => 1;
use Cool::Foo;
use Cool::Bar;
Cool::Foo::perl_rules();
Cool::Bar::perl_rules();
ok 1;
This tip has been brought to you by Nick Ing-Simmons and Stas Bekman.
An alternative way to achieve this can be seen in L<Gtk2::CodeGen>
and L<Glib::CodeGen>.
=back
=back
=head1 DESIGN
=head2 MakeMaker object hierarchy (simplified)
What most people need to know (superclasses on top.)
ExtUtils::MM_Any
|
ExtUtils::MM_Unix
|
ExtUtils::MM_{Current OS}
|
ExtUtils::MakeMaker
|
MY
The object actually used is of the class L<MY|ExtUtils::MY> which allows you to
override bits of MakeMaker inside your Makefile.PL by declaring
MY::foo() methods.
=head2 MakeMaker object hierarchy (real)
Here's how it really works:
ExtUtils::MM_Any
|
ExtUtils::MM_Unix
|
ExtUtils::Liblist::Kid ExtUtils::MM_{Current OS} (if necessary)
| |
ExtUtils::Liblist ExtUtils::MakeMaker |
| | |
| | |-----------------------
ExtUtils::MM
| |
ExtUtils::MY MM (created by ExtUtils::MM)
| |
MY (created by ExtUtils::MY) |
. |
(mixin) |
. |
PACK### (created each call to ExtUtils::MakeMaker->new)
NOTE: Yes, this is a mess. See
L<http://archive.develooper.com/makemaker@perl.org/msg00134.html>
for some history.
NOTE: When L<ExtUtils::MM> is loaded it chooses a superclass for MM from
amongst the ExtUtils::MM_* modules based on the current operating
system.
NOTE: ExtUtils::MM_{Current OS} represents one of the ExtUtils::MM_*
modules except L<ExtUtils::MM_Any> chosen based on your operating system.
NOTE: The main object used by MakeMaker is a PACK### object, *not*
L<ExtUtils::MakeMaker>. It is, effectively, a subclass of L<MY|ExtUtils::MY>,
L<ExtUtils::MakeMaker>, L<ExtUtils::Liblist> and ExtUtils::MM_{Current OS}
NOTE: The methods in L<MY|ExtUtils::MY> are simply copied into PACK### rather
than MY being a superclass of PACK###. I don't remember the rationale.
NOTE: L<ExtUtils::Liblist> should be removed from the inheritance hiearchy
and simply be called as functions.
NOTE: Modules like L<File::Spec> and L<Exporter> have been omitted for clarity.
=head2 The MM_* hierarchy
MM_Win95 MM_NW5
\ /
MM_BeOS MM_Cygwin MM_OS2 MM_VMS MM_Win32 MM_DOS MM_UWIN
\ | | | / / /
------------------------------------------------
| |
MM_Unix |
| |
MM_Any
NOTE: Each direct L<MM_Unix|ExtUtils::MM_Unix> subclass is also an
L<MM_Any|ExtUtils::MM_Any> subclass. This
is a temporary hack because MM_Unix overrides some MM_Any methods with
Unix specific code. It allows the non-Unix modules to see the
original MM_Any implementations.
NOTE: Modules like L<File::Spec> and L<Exporter> have been omitted for clarity.
=head1 PATCHING
If you have a question you'd like to see added to the FAQ (whether or
not you have the answer) please either:
=over 2
=item * make a pull request on the MakeMaker github repository
=item * raise a issue on the MakeMaker github repository
=item * file an RT ticket
=item * email makemaker@perl.org
=back
=head1 AUTHOR
The denizens of makemaker@perl.org.
=head1 SEE ALSO
L<ExtUtils::MakeMaker>
=cut

View file

@ -0,0 +1,384 @@
package ExtUtils::MakeMaker::Locale;
use strict;
use warnings;
our $VERSION = "7.70";
$VERSION =~ tr/_//d;
use base 'Exporter';
our @EXPORT_OK = qw(
decode_argv env
$ENCODING_LOCALE $ENCODING_LOCALE_FS
$ENCODING_CONSOLE_IN $ENCODING_CONSOLE_OUT
);
use Encode ();
use Encode::Alias ();
our $ENCODING_LOCALE;
our $ENCODING_LOCALE_FS;
our $ENCODING_CONSOLE_IN;
our $ENCODING_CONSOLE_OUT;
sub DEBUG () { 0 }
sub _init {
if ($^O eq "MSWin32") {
unless ($ENCODING_LOCALE) {
# Try to obtain what the Windows ANSI code page is
eval {
unless (defined &GetConsoleCP) {
require Win32;
# manually "import" it since Win32->import refuses
*GetConsoleCP = sub { &Win32::GetConsoleCP } if defined &Win32::GetConsoleCP;
}
unless (defined &GetConsoleCP) {
require Win32::API;
Win32::API->Import('kernel32', 'int GetConsoleCP()');
}
if (defined &GetConsoleCP) {
my $cp = GetConsoleCP();
$ENCODING_LOCALE = "cp$cp" if $cp;
}
};
}
unless ($ENCODING_CONSOLE_IN) {
# only test one since set together
unless (defined &GetInputCP) {
eval {
require Win32;
eval {
local $SIG{__WARN__} = sub {} if ( "$]" < 5.014 ); # suppress deprecation warning for inherited AUTOLOAD of Win32::GetConsoleCP()
Win32::GetConsoleCP();
};
# manually "import" it since Win32->import refuses
*GetInputCP = sub { &Win32::GetConsoleCP } if defined &Win32::GetConsoleCP;
*GetOutputCP = sub { &Win32::GetConsoleOutputCP } if defined &Win32::GetConsoleOutputCP;
};
unless (defined &GetInputCP) {
eval {
# try Win32::Console module for codepage to use
require Win32::Console;
*GetInputCP = sub { &Win32::Console::InputCP }
if defined &Win32::Console::InputCP;
*GetOutputCP = sub { &Win32::Console::OutputCP }
if defined &Win32::Console::OutputCP;
};
}
unless (defined &GetInputCP) {
# final fallback
*GetInputCP = *GetOutputCP = sub {
# another fallback that could work is:
# reg query HKLM\System\CurrentControlSet\Control\Nls\CodePage /v ACP
((qx(chcp) || '') =~ /^Active code page: (\d+)/)
? $1 : ();
};
}
}
my $cp = GetInputCP();
$ENCODING_CONSOLE_IN = "cp$cp" if $cp;
$cp = GetOutputCP();
$ENCODING_CONSOLE_OUT = "cp$cp" if $cp;
}
}
unless ($ENCODING_LOCALE) {
eval {
require I18N::Langinfo;
$ENCODING_LOCALE = I18N::Langinfo::langinfo(I18N::Langinfo::CODESET());
# Workaround of Encode < v2.25. The "646" encoding alias was
# introduced in Encode-2.25, but we don't want to require that version
# quite yet. Should avoid the CPAN testers failure reported from
# openbsd-4.7/perl-5.10.0 combo.
$ENCODING_LOCALE = "ascii" if $ENCODING_LOCALE eq "646";
# https://rt.cpan.org/Ticket/Display.html?id=66373
$ENCODING_LOCALE = "hp-roman8" if $^O eq "hpux" && $ENCODING_LOCALE eq "roman8";
};
$ENCODING_LOCALE ||= $ENCODING_CONSOLE_IN;
}
# Workaround of Encode < v2.71 for "cp65000" and "cp65001"
# The "cp65000" and "cp65001" aliases were added in [Encode v2.71](https://github.com/dankogai/p5-encode/commit/7874bd95aa10967a3b5dbae333d16bcd703ac6c6)
# via commit <https://github.com/dankogai/p5-encode/commit/84b9c1101d5251d37e226f80d1c6781718779047>.
# This will avoid test failures for Win32 machines using the UTF-7 or UTF-8 code pages.
$ENCODING_LOCALE = 'UTF-7' if $ENCODING_LOCALE && lc($ENCODING_LOCALE) eq "cp65000";
$ENCODING_LOCALE = 'utf-8-strict' if $ENCODING_LOCALE && lc($ENCODING_LOCALE) eq "cp65001";
if ($^O eq "darwin") {
$ENCODING_LOCALE_FS ||= "UTF-8";
}
# final fallback
$ENCODING_LOCALE ||= $^O eq "MSWin32" ? "cp1252" : "UTF-8";
$ENCODING_LOCALE_FS ||= $ENCODING_LOCALE;
$ENCODING_CONSOLE_IN ||= $ENCODING_LOCALE;
$ENCODING_CONSOLE_OUT ||= $ENCODING_CONSOLE_IN;
unless (Encode::find_encoding($ENCODING_LOCALE)) {
my $foundit;
if (lc($ENCODING_LOCALE) eq "gb18030") {
eval {
require Encode::HanExtra;
};
if ($@) {
die "Need Encode::HanExtra to be installed to support locale codeset ($ENCODING_LOCALE), stopped";
}
$foundit++ if Encode::find_encoding($ENCODING_LOCALE);
}
die "The locale codeset ($ENCODING_LOCALE) isn't one that perl can decode, stopped"
unless $foundit;
}
# use Data::Dump; ddx $ENCODING_LOCALE, $ENCODING_LOCALE_FS, $ENCODING_CONSOLE_IN, $ENCODING_CONSOLE_OUT;
}
_init();
Encode::Alias::define_alias(sub {
no strict 'refs';
no warnings 'once';
return ${"ENCODING_" . uc(shift)};
}, "locale");
sub _flush_aliases {
no strict 'refs';
for my $a (sort keys %Encode::Alias::Alias) {
if (defined ${"ENCODING_" . uc($a)}) {
delete $Encode::Alias::Alias{$a};
warn "Flushed alias cache for $a" if DEBUG;
}
}
}
sub reinit {
$ENCODING_LOCALE = shift;
$ENCODING_LOCALE_FS = shift;
$ENCODING_CONSOLE_IN = $ENCODING_LOCALE;
$ENCODING_CONSOLE_OUT = $ENCODING_LOCALE;
_init();
_flush_aliases();
}
sub decode_argv {
die if defined wantarray;
for (@ARGV) {
$_ = Encode::decode(locale => $_, @_);
}
}
sub env {
my $k = Encode::encode(locale => shift);
my $old = $ENV{$k};
if (@_) {
my $v = shift;
if (defined $v) {
$ENV{$k} = Encode::encode(locale => $v);
}
else {
delete $ENV{$k};
}
}
return Encode::decode(locale => $old) if defined wantarray;
}
1;
__END__
=head1 NAME
ExtUtils::MakeMaker::Locale - bundled Encode::Locale
=head1 SYNOPSIS
use Encode::Locale;
use Encode;
$string = decode(locale => $bytes);
$bytes = encode(locale => $string);
if (-t) {
binmode(STDIN, ":encoding(console_in)");
binmode(STDOUT, ":encoding(console_out)");
binmode(STDERR, ":encoding(console_out)");
}
# Processing file names passed in as arguments
my $uni_filename = decode(locale => $ARGV[0]);
open(my $fh, "<", encode(locale_fs => $uni_filename))
|| die "Can't open '$uni_filename': $!";
binmode($fh, ":encoding(locale)");
...
=head1 DESCRIPTION
In many applications it's wise to let Perl use Unicode for the strings it
processes. Most of the interfaces Perl has to the outside world are still byte
based. Programs therefore need to decode byte strings that enter the program
from the outside and encode them again on the way out.
The POSIX locale system is used to specify both the language conventions
requested by the user and the preferred character set to consume and
output. The C<Encode::Locale> module looks up the charset and encoding (called
a CODESET in the locale jargon) and arranges for the L<Encode> module to know
this encoding under the name "locale". It means bytes obtained from the
environment can be converted to Unicode strings by calling C<<
Encode::encode(locale => $bytes) >> and converted back again with C<<
Encode::decode(locale => $string) >>.
Where file systems interfaces pass file names in and out of the program we also
need care. The trend is for operating systems to use a fixed file encoding
that don't actually depend on the locale; and this module determines the most
appropriate encoding for file names. The L<Encode> module will know this
encoding under the name "locale_fs". For traditional Unix systems this will
be an alias to the same encoding as "locale".
For programs running in a terminal window (called a "Console" on some systems)
the "locale" encoding is usually a good choice for what to expect as input and
output. Some systems allows us to query the encoding set for the terminal and
C<Encode::Locale> will do that if available and make these encodings known
under the C<Encode> aliases "console_in" and "console_out". For systems where
we can't determine the terminal encoding these will be aliased as the same
encoding as "locale". The advice is to use "console_in" for input known to
come from the terminal and "console_out" for output to the terminal.
In addition to arranging for various Encode aliases the following functions and
variables are provided:
=over
=item decode_argv( )
=item decode_argv( Encode::FB_CROAK )
This will decode the command line arguments to perl (the C<@ARGV> array) in-place.
The function will by default replace characters that can't be decoded by
"\x{FFFD}", the Unicode replacement character.
Any argument provided is passed as CHECK to underlying Encode::decode() call.
Pass the value C<Encode::FB_CROAK> to have the decoding croak if not all the
command line arguments can be decoded. See L<Encode/"Handling Malformed Data">
for details on other options for CHECK.
=item env( $uni_key )
=item env( $uni_key => $uni_value )
Interface to get/set environment variables. Returns the current value as a
Unicode string. The $uni_key and $uni_value arguments are expected to be
Unicode strings as well. Passing C<undef> as $uni_value deletes the
environment variable named $uni_key.
The returned value will have the characters that can't be decoded replaced by
"\x{FFFD}", the Unicode replacement character.
There is no interface to request alternative CHECK behavior as for
decode_argv(). If you need that you need to call encode/decode yourself.
For example:
my $key = Encode::encode(locale => $uni_key, Encode::FB_CROAK);
my $uni_value = Encode::decode(locale => $ENV{$key}, Encode::FB_CROAK);
=item reinit( )
=item reinit( $encoding )
Reinitialize the encodings from the locale. You want to call this function if
you changed anything in the environment that might influence the locale.
This function will croak if the determined encoding isn't recognized by
the Encode module.
With argument force $ENCODING_... variables to set to the given value.
=item $ENCODING_LOCALE
The encoding name determined to be suitable for the current locale.
L<Encode> know this encoding as "locale".
=item $ENCODING_LOCALE_FS
The encoding name determined to be suitable for file system interfaces
involving file names.
L<Encode> know this encoding as "locale_fs".
=item $ENCODING_CONSOLE_IN
=item $ENCODING_CONSOLE_OUT
The encodings to be used for reading and writing output to the a console.
L<Encode> know these encodings as "console_in" and "console_out".
=back
=head1 NOTES
This table summarizes the mapping of the encodings set up
by the C<Encode::Locale> module:
Encode | | |
Alias | Windows | Mac OS X | POSIX
------------+---------+--------------+------------
locale | ANSI | nl_langinfo | nl_langinfo
locale_fs | ANSI | UTF-8 | nl_langinfo
console_in | OEM | nl_langinfo | nl_langinfo
console_out | OEM | nl_langinfo | nl_langinfo
=head2 Windows
Windows has basically 2 sets of APIs. A wide API (based on passing UTF-16
strings) and a byte based API based a character set called ANSI. The
regular Perl interfaces to the OS currently only uses the ANSI APIs.
Unfortunately ANSI is not a single character set.
The encoding that corresponds to ANSI varies between different editions of
Windows. For many western editions of Windows ANSI corresponds to CP-1252
which is a character set similar to ISO-8859-1. Conceptually the ANSI
character set is a similar concept to the POSIX locale CODESET so this module
figures out what the ANSI code page is and make this available as
$ENCODING_LOCALE and the "locale" Encoding alias.
Windows systems also operate with another byte based character set.
It's called the OEM code page. This is the encoding that the Console
takes as input and output. It's common for the OEM code page to
differ from the ANSI code page.
=head2 Mac OS X
On Mac OS X the file system encoding is always UTF-8 while the locale
can otherwise be set up as normal for POSIX systems.
File names on Mac OS X will at the OS-level be converted to
NFD-form. A file created by passing a NFC-filename will come
in NFD-form from readdir(). See L<Unicode::Normalize> for details
of NFD/NFC.
Actually, Apple does not follow the Unicode NFD standard since not all
character ranges are decomposed. The claim is that this avoids problems with
round trip conversions from old Mac text encodings. See L<Encode::UTF8Mac> for
details.
=head2 POSIX (Linux and other Unixes)
File systems might vary in what encoding is to be used for
filenames. Since this module has no way to actually figure out
what the is correct it goes with the best guess which is to
assume filenames are encoding according to the current locale.
Users are advised to always specify UTF-8 as the locale charset.
=head1 SEE ALSO
L<I18N::Langinfo>, L<Encode>, L<Term::Encoding>
=head1 AUTHOR
Copyright 2010 Gisle Aas <gisle@aas.no>.
This library is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.
=cut

View file

@ -0,0 +1,213 @@
package ExtUtils::MakeMaker::Tutorial;
our $VERSION = '7.70';
$VERSION =~ tr/_//d;
=head1 NAME
ExtUtils::MakeMaker::Tutorial - Writing a module with MakeMaker
=head1 SYNOPSIS
use ExtUtils::MakeMaker;
WriteMakefile(
NAME => 'Your::Module',
VERSION_FROM => 'lib/Your/Module.pm'
);
=head1 DESCRIPTION
This is a short tutorial on writing a simple module with MakeMaker.
It's really not that hard.
=head2 The Mantra
MakeMaker modules are installed using this simple mantra
perl Makefile.PL
make
make test
make install
There are lots more commands and options, but the above will do it.
=head2 The Layout
The basic files in a module look something like this.
Makefile.PL
MANIFEST
lib/Your/Module.pm
That's all that's strictly necessary. There's additional files you might
want:
lib/Your/Other/Module.pm
t/some_test.t
t/some_other_test.t
Changes
README
INSTALL
MANIFEST.SKIP
bin/some_program
=over 4
=item Makefile.PL
When you run Makefile.PL, it makes a Makefile. That's the whole point of
MakeMaker. The Makefile.PL is a simple program which loads
ExtUtils::MakeMaker and runs the WriteMakefile() function to generate a
Makefile.
Here's an example of what you need for a simple module:
use ExtUtils::MakeMaker;
WriteMakefile(
NAME => 'Your::Module',
VERSION_FROM => 'lib/Your/Module.pm'
);
NAME is the top-level namespace of your module. VERSION_FROM is the file
which contains the $VERSION variable for the entire distribution. Typically
this is the same as your top-level module.
=item MANIFEST
A simple listing of all the files in your distribution.
Makefile.PL
MANIFEST
lib/Your/Module.pm
File paths in a MANIFEST always use Unix conventions (ie. /) even if you're
not on Unix.
You can write this by hand or generate it with 'make manifest'.
See L<ExtUtils::Manifest> for more details.
=item lib/
This is the directory where the .pm and .pod files you wish to have
installed go. They are laid out according to namespace. So Foo::Bar
is F<lib/Foo/Bar.pm>.
=item t/
Tests for your modules go here. Each test filename ends with a .t.
So F<t/foo.t> 'make test' will run these tests.
Typically, the F<t/> test directory is flat, with all test files located
directly within it. However, you can nest tests within subdirectories, for
example:
t/foo/subdir_test.t
To do this, you need to inform C<WriteMakefile()> in your I<Makefile.PL> file
in the following fashion:
test => {TESTS => 't/*.t t/*/*.t'}
That will run all tests in F<t/>, as well as all tests in all subdirectories
that reside under F<t/>. You can nest as deeply as makes sense for your project.
Simply add another entry in the test location string. For example, to test:
t/foo/bar/subdir_test.t
You would use the following C<test> directive:
test => {TESTS => 't/*.t t/*/*/*.t'}
Note that in the above example, tests in the first subdirectory will not be
run. To run all tests in the intermediary subdirectory preceding the one
the test files are in, you need to explicitly note it:
test => {TESTS => 't/*.t t/*/*.t t/*/*/*.t'}
You don't need to specify wildcards if you only want to test within specific
subdirectories. The following example will only run tests in F<t/foo>:
test => {TESTS => 't/foo/*.t'}
Tests are run from the top level of your distribution. So inside a test
you would refer to ./lib to enter the lib directory, for example.
=item Changes
A log of changes you've made to this module. The layout is free-form.
Here's an example:
1.01 Fri Apr 11 00:21:25 PDT 2003
- thing() does some stuff now
- fixed the wiggy bug in withit()
1.00 Mon Apr 7 00:57:15 PDT 2003
- "Rain of Frogs" now supported
=item README
A short description of your module, what it does, why someone would use it
and its limitations. CPAN automatically pulls your README file out of
the archive and makes it available to CPAN users, it is the first thing
they will read to decide if your module is right for them.
=item INSTALL
Instructions on how to install your module along with any dependencies.
Suggested information to include here:
any extra modules required for use
the minimum version of Perl required
if only works on certain operating systems
=item MANIFEST.SKIP
A file full of regular expressions to exclude when using 'make
manifest' to generate the MANIFEST. These regular expressions
are checked against each file path found in the distribution (so
you're matching against "t/foo.t" not "foo.t").
Here's a sample:
~$ # ignore emacs and vim backup files
.bak$ # ignore manual backups
\# # ignore CVS old revision files and emacs temp files
Since # can be used for comments, # must be escaped.
MakeMaker comes with a default MANIFEST.SKIP to avoid things like
version control directories and backup files. Specifying your own
will override this default.
=item bin/
=back
=head1 SEE ALSO
L<perlmodstyle> gives stylistic help writing a module.
L<perlnewmod> gives more information about how to write a module.
There are modules to help you through the process of writing a module:
L<ExtUtils::ModuleMaker>, L<Module::Starter>, L<Minilla::Tutorial>,
L<Dist::Milla::Tutorial>, L<Dist::Zilla::Starter>
=cut
1;

View file

@ -0,0 +1,57 @@
#--------------------------------------------------------------------------#
# This is a modified copy of version.pm 0.9909, bundled exclusively for
# use by ExtUtils::Makemaker and its dependencies to bootstrap when
# version.pm is not available. It should not be used by ordinary modules.
#
# When loaded, it will try to load version.pm. If that fails, it will load
# ExtUtils::MakeMaker::version::vpp and alias various *version functions
# to functions in that module. It will also override UNIVERSAL::VERSION.
#--------------------------------------------------------------------------#
package ExtUtils::MakeMaker::version;
use 5.006001;
use strict;
use warnings;
use vars qw(@ISA $VERSION $CLASS $STRICT $LAX *declare *qv);
$VERSION = '7.70';
$VERSION =~ tr/_//d;
$CLASS = 'version';
{
local $SIG{'__DIE__'};
eval "use version";
if ( $@ ) { # don't have any version.pm installed
eval "use ExtUtils::MakeMaker::version::vpp";
die "$@" if ( $@ );
no warnings;
delete $INC{'version.pm'};
$INC{'version.pm'} = $INC{'ExtUtils/MakeMaker/version.pm'};
push @version::ISA, "ExtUtils::MakeMaker::version::vpp";
$version::VERSION = $VERSION;
*version::qv = \&ExtUtils::MakeMaker::version::vpp::qv;
*version::declare = \&ExtUtils::MakeMaker::version::vpp::declare;
*version::_VERSION = \&ExtUtils::MakeMaker::version::vpp::_VERSION;
*version::vcmp = \&ExtUtils::MakeMaker::version::vpp::vcmp;
*version::new = \&ExtUtils::MakeMaker::version::vpp::new;
if ("$]" >= 5.009000) {
no strict 'refs';
*version::stringify = \&ExtUtils::MakeMaker::version::vpp::stringify;
*{'version::(""'} = \&ExtUtils::MakeMaker::version::vpp::stringify;
*{'version::(<=>'} = \&ExtUtils::MakeMaker::version::vpp::vcmp;
*version::parse = \&ExtUtils::MakeMaker::version::vpp::parse;
}
require ExtUtils::MakeMaker::version::regex;
*version::is_lax = \&ExtUtils::MakeMaker::version::regex::is_lax;
*version::is_strict = \&ExtUtils::MakeMaker::version::regex::is_strict;
*LAX = \$ExtUtils::MakeMaker::version::regex::LAX;
*STRICT = \$ExtUtils::MakeMaker::version::regex::STRICT;
}
elsif ( ! version->can('is_qv') ) {
*version::is_qv = sub { exists $_[0]->{qv} };
}
}
1;

View file

@ -0,0 +1,865 @@
package ExtUtils::Manifest; # git description: 1.74-10-g1bddbb0
require Exporter;
use Config;
use File::Basename;
use File::Copy 'copy';
use File::Find;
use File::Spec 0.8;
use Carp;
use strict;
use warnings;
our $VERSION = '1.75';
our @ISA = ('Exporter');
our @EXPORT_OK = qw(mkmanifest
manicheck filecheck fullcheck skipcheck
manifind maniread manicopy maniadd
maniskip
);
our $Is_VMS = $^O eq 'VMS';
our $Is_VMS_mode = 0;
our $Is_VMS_lc = 0;
our $Is_VMS_nodot = 0; # No dots in dir names or double dots in files
if ($Is_VMS) {
require VMS::Filespec if $Is_VMS;
my $vms_unix_rpt;
my $vms_efs;
my $vms_case;
$Is_VMS_mode = 1;
$Is_VMS_lc = 1;
$Is_VMS_nodot = 1;
if (eval { local $SIG{__DIE__}; require VMS::Feature; }) {
$vms_unix_rpt = VMS::Feature::current("filename_unix_report");
$vms_efs = VMS::Feature::current("efs_charset");
$vms_case = VMS::Feature::current("efs_case_preserve");
} else {
my $unix_rpt = $ENV{'DECC$FILENAME_UNIX_REPORT'} || '';
my $efs_charset = $ENV{'DECC$EFS_CHARSET'} || '';
my $efs_case = $ENV{'DECC$EFS_CASE_PRESERVE'} || '';
$vms_unix_rpt = $unix_rpt =~ /^[ET1]/i;
$vms_efs = $efs_charset =~ /^[ET1]/i;
$vms_case = $efs_case =~ /^[ET1]/i;
}
$Is_VMS_lc = 0 if ($vms_case);
$Is_VMS_mode = 0 if ($vms_unix_rpt);
$Is_VMS_nodot = 0 if ($vms_efs);
}
our $Debug = $ENV{PERL_MM_MANIFEST_DEBUG} || 0;
our $Verbose = defined $ENV{PERL_MM_MANIFEST_VERBOSE} ?
$ENV{PERL_MM_MANIFEST_VERBOSE} : 1;
our $Quiet = 0;
our $MANIFEST = 'MANIFEST';
our $DEFAULT_MSKIP = File::Spec->rel2abs(File::Spec->catfile( dirname(__FILE__), "$MANIFEST.SKIP" ));
=head1 NAME
ExtUtils::Manifest - Utilities to write and check a MANIFEST file
=head1 VERSION
version 1.75
=head1 SYNOPSIS
use ExtUtils::Manifest qw(...funcs to import...);
mkmanifest();
my @missing_files = manicheck;
my @skipped = skipcheck;
my @extra_files = filecheck;
my($missing, $extra) = fullcheck;
my $found = manifind();
my $manifest = maniread();
manicopy($read,$target);
maniadd({$file => $comment, ...});
=head1 DESCRIPTION
...
=head1 FUNCTIONS
ExtUtils::Manifest exports no functions by default. The following are
exported on request:
=head2 mkmanifest
mkmanifest();
Writes all files in and below the current directory to your F<MANIFEST>.
It works similar to the result of the Unix command
find . > MANIFEST
All files that match any regular expression in a file F<MANIFEST.SKIP>
(if it exists) are ignored.
Any existing F<MANIFEST> file will be saved as F<MANIFEST.bak>.
=cut
sub _sort {
return sort { lc $a cmp lc $b } @_;
}
sub mkmanifest {
my $manimiss = 0;
my $read = (-r 'MANIFEST' && maniread()) or $manimiss++;
$read = {} if $manimiss;
my $bakbase = $MANIFEST;
$bakbase =~ s/\./_/g if $Is_VMS_nodot; # avoid double dots
rename $MANIFEST, "$bakbase.bak" unless $manimiss;
open my $fh, '>', $MANIFEST or die "Could not open $MANIFEST: $!";
binmode $fh, ':raw';
my $skip = maniskip();
my $found = manifind();
my($key,$val,$file,%all);
%all = (%$found, %$read);
$all{$MANIFEST} = ($Is_VMS_mode ? "$MANIFEST\t\t" : '') .
'This list of files'
if $manimiss; # add new MANIFEST to known file list
foreach $file (_sort keys %all) {
if ($skip->($file)) {
# Policy: only remove files if they're listed in MANIFEST.SKIP.
# Don't remove files just because they don't exist.
warn "Removed from $MANIFEST: $file\n" if $Verbose and exists $read->{$file};
next;
}
if ($Verbose){
warn "Added to $MANIFEST: $file\n" unless exists $read->{$file};
}
my $text = $all{$file};
my $tabs = (5 - (length($file)+1)/8);
$tabs = 1 if $tabs < 1;
$tabs = 0 unless $text;
if ($file =~ /\s/) {
$file =~ s/([\\'])/\\$1/g;
$file = "'$file'";
}
print $fh $file, "\t" x $tabs, $text, "\n";
}
}
# Geez, shouldn't this use File::Spec or File::Basename or something?
# Why so careful about dependencies?
sub clean_up_filename {
my $filename = shift;
$filename =~ s|^\./||;
if ( $Is_VMS ) {
$filename =~ s/\.$//; # trim trailing dot
$filename = VMS::Filespec::unixify($filename); # unescape spaces, etc.
if( $Is_VMS_lc ) {
$filename = lc($filename);
$filename = uc($filename) if $filename =~ /^MANIFEST(\.SKIP)?$/i;
}
}
return $filename;
}
=head2 manifind
my $found = manifind();
returns a hash reference. The keys of the hash are the files found
below the current directory.
=cut
sub manifind {
my $p = shift || {};
my $found = {};
my $wanted = sub {
my $name = clean_up_filename($File::Find::name);
warn "Debug: diskfile $name\n" if $Debug;
return if -d $_;
$found->{$name} = "";
};
# We have to use "$File::Find::dir/$_" in preprocess, because
# $File::Find::name is unavailable.
# Also, it's okay to use / here, because MANIFEST files use Unix-style
# paths.
find({wanted => $wanted, follow_fast => 1}, ".");
return $found;
}
=head2 manicheck
my @missing_files = manicheck();
checks if all the files within a C<MANIFEST> in the current directory
really do exist. If C<MANIFEST> and the tree below the current
directory are in sync it silently returns an empty list.
Otherwise it returns a list of files which are listed in the
C<MANIFEST> but missing from the directory, and by default also
outputs these names to STDERR.
=cut
sub manicheck {
return _check_files();
}
=head2 filecheck
my @extra_files = filecheck();
finds files below the current directory that are not mentioned in the
C<MANIFEST> file. An optional file C<MANIFEST.SKIP> will be
consulted. Any file matching a regular expression in such a file will
not be reported as missing in the C<MANIFEST> file. The list of any
extraneous files found is returned, and by default also reported to
STDERR.
=cut
sub filecheck {
return _check_manifest();
}
=head2 fullcheck
my($missing, $extra) = fullcheck();
does both a manicheck() and a filecheck(), returning then as two array
refs.
=cut
sub fullcheck {
return [_check_files()], [_check_manifest()];
}
=head2 skipcheck
my @skipped = skipcheck();
lists all the files that are skipped due to your C<MANIFEST.SKIP>
file.
=cut
sub skipcheck {
my($p) = @_;
my $found = manifind();
my $matches = maniskip();
my @skipped = ();
foreach my $file (_sort keys %$found){
if (&$matches($file)){
warn "Skipping $file\n" unless $Quiet;
push @skipped, $file;
next;
}
}
return @skipped;
}
sub _check_files {
my $p = shift;
my $dosnames=(defined(&Dos::UseLFN) && Dos::UseLFN()==0);
my $read = maniread() || {};
my $found = manifind($p);
my(@missfile) = ();
foreach my $file (_sort keys %$read){
warn "Debug: manicheck checking from $MANIFEST $file\n" if $Debug;
if ($dosnames){
$file = lc $file;
$file =~ s=(\.(\w|-)+)=substr ($1,0,4)=ge;
$file =~ s=((\w|-)+)=substr ($1,0,8)=ge;
}
unless ( exists $found->{$file} ) {
warn "No such file: $file\n" unless $Quiet;
push @missfile, $file;
}
}
return @missfile;
}
sub _check_manifest {
my($p) = @_;
my $read = maniread() || {};
my $found = manifind($p);
my $skip = maniskip();
my @missentry = ();
foreach my $file (_sort keys %$found){
next if $skip->($file);
warn "Debug: manicheck checking from disk $file\n" if $Debug;
unless ( exists $read->{$file} ) {
warn "Not in $MANIFEST: $file\n" unless $Quiet;
push @missentry, $file;
}
}
return @missentry;
}
=head2 maniread
my $manifest = maniread();
my $manifest = maniread($manifest_file);
reads a named C<MANIFEST> file (defaults to C<MANIFEST> in the current
directory) and returns a HASH reference with files being the keys and
comments being the values of the HASH. Blank lines and lines which
start with C<#> in the C<MANIFEST> file are discarded.
=cut
sub maniread {
my ($mfile) = @_;
$mfile ||= $MANIFEST;
my $read = {};
my $fh;
unless (open $fh, '<', $mfile){
warn "Problem opening $mfile: $!";
return $read;
}
local $_;
while (<$fh>){
chomp;
next if /^\s*#/;
my($file, $comment);
# filename may contain spaces if enclosed in ''
# (in which case, \\ and \' are escapes)
if (($file, $comment) = /^'((?:\\[\\']|.+)+)'\s*(.*)/) {
$file =~ s/\\([\\'])/$1/g;
}
else {
($file, $comment) = /^(\S+)\s*(.*)/;
}
next unless $file;
if ($Is_VMS_mode) {
require File::Basename;
my($base,$dir) = File::Basename::fileparse($file);
# Resolve illegal file specifications in the same way as tar
if ($Is_VMS_nodot) {
$dir =~ tr/./_/;
my(@pieces) = split(/\./,$base);
if (@pieces > 2)
{ $base = shift(@pieces) . '.' . join('_',@pieces); }
my $okfile = "$dir$base";
warn "Debug: Illegal name $file changed to $okfile\n" if $Debug;
$file = $okfile;
}
if( $Is_VMS_lc ) {
$file = lc($file);
$file = uc($file) if $file =~ /^MANIFEST(\.SKIP)?$/i;
}
}
$read->{$file} = $comment;
}
$read;
}
=head2 maniskip
my $skipchk = maniskip();
my $skipchk = maniskip($manifest_skip_file);
if ($skipchk->($file)) { .. }
reads a named C<MANIFEST.SKIP> file (defaults to C<MANIFEST.SKIP> in
the current directory) and returns a CODE reference that tests whether
a given filename should be skipped.
=cut
sub _process_skipline {
local $_ = shift;
chomp;
s/\r//;
$_ =~ qr{^\s*(?:(?:'([^\\']*(?:\\.[^\\']*)*)')|([^#\s]\S*))?(?:(?:\s*)|(?:\s+(.*?)\s*))$};
#my $comment = $3;
my $filename = $2;
if ( defined($1) ) {
$filename = $1;
$filename =~ s/\\(['\\])/$1/g;
}
$filename;
}
# returns an anonymous sub that decides if an argument matches
sub maniskip {
my @skip ;
my $mfile = shift || "$MANIFEST.SKIP";
_check_mskip_directives($mfile) if -f $mfile;
local $_;
my $fh;
open $fh, '<', $mfile or open $fh, '<', $DEFAULT_MSKIP or return sub {0};
while (<$fh>){
if (/^#!include_default\s*$/) {
if (my @default = _include_mskip_file()) {
warn "Debug: Including default MANIFEST.SKIP\n" if $Debug;
push @skip, grep $_, map _process_skipline($_), @default;
}
next;
}
next unless my $filename = _process_skipline($_);
push @skip, $filename;
}
return sub {0} unless (scalar @skip > 0);
my $opts = $Is_VMS_mode ? '(?i)' : '';
# Make sure each entry is isolated in its own parentheses, in case
# any of them contain alternations
my $regex = join '|', map "(?:$_)", @skip;
return sub { $_[0] =~ qr{$opts$regex} };
}
sub _get_homedir {
$^O eq 'MSWin32' && "$]" < 5.016 ? $ENV{HOME} || $ENV{USERPROFILE} : (glob('~'))[0];
}
# checks for the special directives
# #!include_default
# #!include /path/to/some/manifest.skip
# in a custom MANIFEST.SKIP for, for including
# the content of, respectively, the default MANIFEST.SKIP
# and an external manifest.skip file
sub _check_mskip_directives {
my $mfile = shift;
local $_;
my $fh;
my @lines = ();
my $flag = 0;
unless (open $fh, '<', $mfile) {
warn "Problem opening $mfile: $!";
return;
}
while (<$fh>) {
if (/^#!include\s+(.*)\s*$/) {
my $external_file = $1;
$external_file =~ s{^~/}{_get_homedir().'/'}e;
if (my @external = _include_mskip_file($external_file)) {
push @lines, @external;
warn "Debug: Including external $external_file\n" if $Debug;
$flag++;
}
next;
}
push @lines, $_;
}
close $fh;
return unless $flag;
my $bakbase = $mfile;
$bakbase =~ s/\./_/g if $Is_VMS_nodot; # avoid double dots
rename $mfile, "$bakbase.bak";
warn "Debug: Saving original $mfile as $bakbase.bak\n" if $Debug;
unless (open $fh, '>', $mfile) {
warn "Problem opening $mfile: $!";
return;
}
binmode $fh, ':raw';
print $fh $_ for (@lines);
return;
}
# returns an array containing the lines of an external
# manifest.skip file, if given, or $DEFAULT_MSKIP
sub _include_mskip_file {
my $mskip = shift || $DEFAULT_MSKIP;
unless (-f $mskip) {
warn qq{Included file "$mskip" not found - skipping};
return;
}
local $_;
my $fh;
unless (open $fh, '<', $mskip) {
warn "Problem opening $mskip: $!";
return;
}
my @lines = ();
push @lines, "\n#!start included $mskip\n";
push @lines, $_ while <$fh>;
push @lines, "#!end included $mskip\n\n";
return @lines;
}
=head2 manicopy
manicopy(\%src, $dest_dir);
manicopy(\%src, $dest_dir, $how);
Copies the files that are the keys in %src to the $dest_dir. %src is
typically returned by the maniread() function.
manicopy( maniread(), $dest_dir );
This function is useful for producing a directory tree identical to the
intended distribution tree.
$how can be used to specify a different methods of "copying". Valid
values are C<cp>, which actually copies the files, C<ln> which creates
hard links, and C<best> which mostly links the files but copies any
symbolic link to make a tree without any symbolic link. C<cp> is the
default.
=cut
sub manicopy {
my($read,$target,$how)=@_;
croak "manicopy() called without target argument" unless defined $target;
$how ||= 'cp';
require File::Path;
require File::Basename;
$target = VMS::Filespec::unixify($target) if $Is_VMS_mode;
File::Path::mkpath([ $target ],! $Quiet,$Is_VMS ? undef : 0755);
foreach my $file (keys %$read){
$file = VMS::Filespec::unixify($file) if $Is_VMS_mode;
if ($file =~ m!/!) { # Ilya, that hurts, I fear, or maybe not?
my $dir = File::Basename::dirname($file);
$dir = VMS::Filespec::unixify($dir) if $Is_VMS_mode;
File::Path::mkpath(["$target/$dir"],! $Quiet,$Is_VMS ? undef : 0755);
}
cp_if_diff($file, "$target/$file", $how);
}
}
sub cp_if_diff {
my($from, $to, $how)=@_;
if (! -f $from) {
carp "$from not found";
return;
}
my($diff) = 0;
my ($fromfh, $tofh);
open($fromfh, '<', $from) or die "Can't read $from: $!\n";
if (open($tofh, '<', $to)) {
local $_;
while (<$fromfh>) { $diff++,last if $_ ne <$tofh>; }
$diff++ unless eof($tofh);
close $tofh;
}
else { $diff++; }
close $fromfh;
if ($diff) {
if (-e $to) {
unlink($to) or confess "unlink $to: $!";
}
STRICT_SWITCH: {
best($from,$to), last STRICT_SWITCH if $how eq 'best';
cp($from,$to), last STRICT_SWITCH if $how eq 'cp';
ln($from,$to), last STRICT_SWITCH if $how eq 'ln';
croak("ExtUtils::Manifest::cp_if_diff " .
"called with illegal how argument [$how]. " .
"Legal values are 'best', 'cp', and 'ln'.");
}
}
}
sub cp {
my ($srcFile, $dstFile) = @_;
my ($access,$mod) = (stat $srcFile)[8,9];
copy($srcFile,$dstFile);
utime $access, $mod + ($Is_VMS ? 1 : 0), $dstFile;
_manicopy_chmod($srcFile, $dstFile);
}
sub ln {
my ($srcFile, $dstFile) = @_;
# Fix-me - VMS can support links.
return &cp if $Is_VMS or ($^O eq 'MSWin32' and Win32::IsWin95());
link($srcFile, $dstFile);
unless( _manicopy_chmod($srcFile, $dstFile) ) {
unlink $dstFile;
return;
}
1;
}
# 1) Strip off all group and world permissions.
# 2) Let everyone read it.
# 3) If the owner can execute it, everyone can.
sub _manicopy_chmod {
my($srcFile, $dstFile) = @_;
my $perm = 0444 | (stat $srcFile)[2] & 0700;
chmod( $perm | ( $perm & 0100 ? 0111 : 0 ), $dstFile );
}
# Files that are often modified in the distdir. Don't hard link them.
my @Exceptions = qw(MANIFEST META.yml SIGNATURE);
sub best {
my ($srcFile, $dstFile) = @_;
my $is_exception = grep $srcFile =~ /$_/, @Exceptions;
if ($is_exception or !$Config{d_link} or -l $srcFile) {
cp($srcFile, $dstFile);
} else {
ln($srcFile, $dstFile) or cp($srcFile, $dstFile);
}
}
=head2 maniadd
maniadd({ $file => $comment, ...});
Adds an entry to an existing F<MANIFEST> unless its already there.
$file will be normalized (ie. Unixified). B<UNIMPLEMENTED>
=cut
sub maniadd {
my($additions) = shift;
_normalize($additions);
_fix_manifest($MANIFEST);
my $manifest = maniread();
my @needed = grep !exists $manifest->{$_}, keys %$additions;
return 1 unless @needed;
open(my $fh, '>>', $MANIFEST) or
die "maniadd() could not open $MANIFEST: $!";
binmode $fh, ':raw';
foreach my $file (_sort @needed) {
my $comment = $additions->{$file} || '';
if ($file =~ /\s/) {
$file =~ s/([\\'])/\\$1/g;
$file = "'$file'";
}
printf $fh "%-40s %s\n", $file, $comment;
}
close $fh or die "Error closing $MANIFEST: $!";
return 1;
}
# Make sure this MANIFEST is consistently written with native
# newlines and has a terminal newline.
sub _fix_manifest {
my $manifest_file = shift;
open my $fh, '<', $MANIFEST or die "Could not open $MANIFEST: $!";
local $/;
my @manifest = split /(\015\012|\012|\015)/, <$fh>, -1;
close $fh;
my $must_rewrite = "";
if ($manifest[-1] eq ""){
# sane case: last line had a terminal newline
pop @manifest;
for (my $i=1; $i<=$#manifest; $i+=2) {
unless ($manifest[$i] eq "\n") {
$must_rewrite = "not a newline at pos $i";
last;
}
}
} else {
$must_rewrite = "last line without newline";
}
if ( $must_rewrite ) {
1 while unlink $MANIFEST; # avoid multiple versions on VMS
open $fh, ">", $MANIFEST or die "(must_rewrite=$must_rewrite) Could not open >$MANIFEST: $!";
binmode $fh, ':raw';
for (my $i=0; $i<=$#manifest; $i+=2) {
print $fh "$manifest[$i]\n";
}
close $fh or die "could not write $MANIFEST: $!";
}
}
# UNIMPLEMENTED
sub _normalize {
return;
}
=head2 MANIFEST
A list of files in the distribution, one file per line. The MANIFEST
always uses Unix filepath conventions even if you're not on Unix. This
means F<foo/bar> style not F<foo\bar>.
Anything between white space and an end of line within a C<MANIFEST>
file is considered to be a comment. Any line beginning with # is also
a comment. Beginning with ExtUtils::Manifest 1.52, a filename may
contain whitespace characters if it is enclosed in single quotes; single
quotes or backslashes in that filename must be backslash-escaped.
# this a comment
some/file
some/other/file comment about some/file
'some/third file' comment
=head2 MANIFEST.SKIP
The file MANIFEST.SKIP may contain regular expressions of files that
should be ignored by mkmanifest() and filecheck(). The regular
expressions should appear one on each line. Blank lines and lines
which start with C<#> are skipped. Use C<\#> if you need a regular
expression to start with a C<#>.
For example:
# Version control files and dirs.
\bRCS\b
\bCVS\b
,v$
\B\.svn\b
# Makemaker generated files and dirs.
^MANIFEST\.
^Makefile$
^blib/
^MakeMaker-\d
# Temp, old and emacs backup files.
~$
\.old$
^#.*#$
^\.#
If no MANIFEST.SKIP file is found, a default set of skips will be
used, similar to the example above. If you want nothing skipped,
simply make an empty MANIFEST.SKIP file.
In one's own MANIFEST.SKIP file, certain directives
can be used to include the contents of other MANIFEST.SKIP
files. At present two such directives are recognized.
=over 4
=item #!include_default
This tells ExtUtils::Manifest to read the default F<MANIFEST.SKIP>
file and skip files accordingly, but I<not> to include it in the local
F<MANIFEST.SKIP>. This is intended to skip files according to a system
default, which can change over time without requiring further changes
to the distribution's F<MANIFEST.SKIP>.
=item #!include /Path/to/another/manifest.skip
This inserts the contents of the specified external file in the local
F<MANIFEST.SKIP>. This is intended for authors to have a central
F<MANIFEST.SKIP> file, and to include it with their various distributions.
=back
The included contents will be inserted into the MANIFEST.SKIP
file in between I<#!start included /path/to/manifest.skip>
and I<#!end included /path/to/manifest.skip> markers.
The original MANIFEST.SKIP is saved as MANIFEST.SKIP.bak.
=head2 EXPORT_OK
C<&mkmanifest>, C<&manicheck>, C<&filecheck>, C<&fullcheck>,
C<&maniread>, and C<&manicopy> are exportable.
=head2 GLOBAL VARIABLES
C<$ExtUtils::Manifest::MANIFEST> defaults to C<MANIFEST>. Changing it
results in both a different C<MANIFEST> and a different
C<MANIFEST.SKIP> file. This is useful if you want to maintain
different distributions for different audiences (say a user version
and a developer version including RCS).
C<$ExtUtils::Manifest::Quiet> defaults to 0. If set to a true value,
all functions act silently.
C<$ExtUtils::Manifest::Debug> defaults to 0. If set to a true value,
or if PERL_MM_MANIFEST_DEBUG is true, debugging output will be
produced.
=head1 DIAGNOSTICS
All diagnostic output is sent to C<STDERR>.
=over 4
=item C<Not in MANIFEST:> I<file>
is reported if a file is found which is not in C<MANIFEST>.
=item C<Skipping> I<file>
is reported if a file is skipped due to an entry in C<MANIFEST.SKIP>.
=item C<No such file:> I<file>
is reported if a file mentioned in a C<MANIFEST> file does not
exist.
=item C<MANIFEST:> I<$!>
is reported if C<MANIFEST> could not be opened.
=item C<Added to MANIFEST:> I<file>
is reported by mkmanifest() if $Verbose is set and a file is added
to MANIFEST. $Verbose is set to 1 by default.
=back
=head1 ENVIRONMENT
=over 4
=item B<PERL_MM_MANIFEST_DEBUG>
Turns on debugging
=back
=head1 SEE ALSO
L<ExtUtils::MakeMaker> which has handy targets for most of the functionality.
=head1 AUTHOR
Andreas Koenig C<andreas.koenig@anima.de>
Currently maintained by the Perl Toolchain Gang.
=head1 COPYRIGHT AND LICENSE
This software is copyright (c) 1996- by Andreas Koenig.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
=cut
1;

View file

@ -0,0 +1,235 @@
#!./perl -w
package ExtUtils::Miniperl;
use strict;
use Exporter 'import';
use ExtUtils::Embed 1.31, qw(xsi_header xsi_protos xsi_body);
our @EXPORT = qw(writemain);
our $VERSION = '1.14';
# blead will run this with miniperl, hence we can't use autodie or File::Temp
my $temp;
END {
return if !defined $temp || !-e $temp;
unlink $temp or warn "Can't unlink '$temp': $!";
}
sub writemain{
my ($fh, $real);
if (ref $_[0] eq 'SCALAR') {
$real = ${+shift};
$temp = $real;
$temp =~ s/(?:.c)?\z/.new/;
open $fh, '>', $temp
or die "Can't open '$temp' for writing: $!";
} elsif (ref $_[0]) {
$fh = shift;
} else {
$fh = \*STDOUT;
}
my(@exts) = @_;
printf $fh <<'EOF!HEAD', xsi_header();
/* miniperlmain.c or perlmain.c - a generated file
*
* Copyright (C) 1994, 1995, 1996, 1997, 1999, 2000, 2001, 2002, 2003,
* 2004, 2005, 2006, 2007, 2016 by Larry Wall and others
*
* You may distribute under the terms of either the GNU General Public
* License or the Artistic License, as specified in the README file.
*
*/
/*
* The Road goes ever on and on
* Down from the door where it began.
*
* [Bilbo on p.35 of _The Lord of the Rings_, I/i: "A Long-Expected Party"]
* [Frodo on p.73 of _The Lord of the Rings_, I/iii: "Three Is Company"]
*/
/* This file contains the main() function for the perl interpreter.
* Note that miniperlmain.c contains main() for the 'miniperl' binary,
* while perlmain.c contains main() for the 'perl' binary. The typical
* difference being that the latter includes Dynaloader.
*
* Miniperl is like perl except that it does not support dynamic loading,
* and in fact is used to build the dynamic modules needed for the 'real'
* perl executable.
*
* The content of the body of this generated file is mostly contained
* in Miniperl.pm - edit that file if you want to change anything.
* miniperlmain.c is generated by running regen/miniperlmain.pl, while
* perlmain.c is built automatically by Makefile (so the former is
* included in the tarball while the latter isn't).
*/
#ifdef OEMVS
#ifdef MYMALLOC
/* sbrk is limited to first heap segment so make it big */
#pragma runopts(HEAP(8M,500K,ANYWHERE,KEEP,8K,4K) STACK(,,ANY,) ALL31(ON))
#else
#pragma runopts(HEAP(2M,500K,ANYWHERE,KEEP,8K,4K) STACK(,,ANY,) ALL31(ON))
#endif
#endif
#define PERL_IN_MINIPERLMAIN_C
/* work round bug in MakeMaker which doesn't currently (2019) supply this
* flag when making a statically linked perl */
#define PERL_CORE 1
%s
static void xs_init (pTHX);
static PerlInterpreter *my_perl;
#ifdef NO_ENV_ARRAY_IN_MAIN
extern char **environ;
int
main(int argc, char **argv)
#else
int
main(int argc, char **argv, char **env)
#endif
{
int exitstatus, i;
#ifndef NO_ENV_ARRAY_IN_MAIN
PERL_UNUSED_ARG(env);
#endif
/* if user wants control of gprof profiling off by default */
/* noop unless Configure is given -Accflags=-DPERL_GPROF_CONTROL */
PERL_GPROF_MONCONTROL(0);
#ifdef NO_ENV_ARRAY_IN_MAIN
PERL_SYS_INIT3(&argc,&argv,&environ);
#else
PERL_SYS_INIT3(&argc,&argv,&env);
#endif
#if defined(USE_ITHREADS)
/* XXX Ideally, this should really be happening in perl_alloc() or
* perl_construct() to keep libperl.a transparently fork()-safe.
* It is currently done here only because Apache/mod_perl have
* problems due to lack of a call to cancel pthread_atfork()
* handlers when shared objects that contain the handlers may
* be dlclose()d. This forces applications that embed perl to
* call PTHREAD_ATFORK() explicitly, but if and only if it hasn't
* been called at least once before in the current process.
* --GSAR 2001-07-20 */
PTHREAD_ATFORK(Perl_atfork_lock,
Perl_atfork_unlock,
Perl_atfork_unlock);
#endif
PERL_SYS_FPU_INIT;
if (!PL_do_undump) {
my_perl = perl_alloc();
if (!my_perl)
exit(1);
perl_construct(my_perl);
PL_perl_destruct_level = 0;
}
PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
if (!perl_parse(my_perl, xs_init, argc, argv, (char **)NULL)) {
/* perl_parse() may end up starting its own run loops, which
* might end up "leaking" PL_restartop from the parse phase into
* the run phase which then ends up confusing run_body(). This
* leakage shouldn't happen and if it does its a bug.
*
* Note we do not do this assert in perl_run() or perl_parse()
* as there are modules out there which explicitly set
* PL_restartop before calling perl_run() directly from XS code
* (Coro), and it is conceivable PL_restartop could be set prior
* to calling perl_parse() by XS code as well.
*
* What we want to check is that the top level perl_parse(),
* perl_run() pairing does not allow a leaking PL_restartop, as
* that indicates a bug in perl. By putting the assert here we
* can validate that Perl itself is operating correctly without
* risking breakage to XS code under DEBUGGING. - Yves
*/
assert(!PL_restartop);
perl_run(my_perl);
}
/* Unregister our signal handler before destroying my_perl */
for (i = 1; PL_sig_name[i]; i++) {
if (rsignal_state(PL_sig_num[i]) == (Sighandler_t) PL_csighandlerp) {
rsignal(PL_sig_num[i], (Sighandler_t) SIG_DFL);
}
}
exitstatus = perl_destruct(my_perl);
perl_free(my_perl);
PERL_SYS_TERM();
exit(exitstatus);
}
/* Register any extra external extensions */
EOF!HEAD
print $fh xsi_protos(@exts), <<'EOT', xsi_body(@exts), "}\n";
static void
xs_init(pTHX)
{
EOT
if ($real) {
close $fh or die "Can't close '$temp': $!";
rename $temp, $real or die "Can't rename '$temp' to '$real': $!";
}
}
1;
__END__
=head1 NAME
ExtUtils::Miniperl - write the C code for miniperlmain.c and perlmain.c
=head1 SYNOPSIS
use ExtUtils::Miniperl;
writemain(@directories);
# or
writemain($fh, @directories);
# or
writemain(\$filename, @directories);
=head1 DESCRIPTION
C<writemain()> takes an argument list of zero or more directories
containing archive
libraries that relate to perl modules and should be linked into a new
perl binary. It writes a corresponding F<miniperlmain.c> or F<perlmain.c>
file that
is a plain C file containing all the bootstrap code to make the
modules associated with the libraries available from within perl.
If the first argument to C<writemain()> is a reference to a scalar it is
used as the filename to open for output. Any other reference is used as
the filehandle to write to. Otherwise output defaults to C<STDOUT>.
The typical usage is from within perl's own Makefile (to build
F<perlmain.c>) or from F<regen/miniperlmain.pl> (to build miniperlmain.c).
So under normal circumstances you won't have to deal with this module
directly.
=head1 SEE ALSO
L<ExtUtils::MakeMaker>
=cut
# ex: set ts=8 sts=4 sw=4 et:

View file

@ -0,0 +1,114 @@
package ExtUtils::Mkbootstrap;
use strict;
use warnings;
our $VERSION = '7.70';
$VERSION =~ tr/_//d;
require Exporter;
our @ISA = ('Exporter');
our @EXPORT = ('&Mkbootstrap');
use Config;
our $Verbose = 0;
sub Mkbootstrap {
my($baseext, @bsloadlibs)=@_;
@bsloadlibs = grep($_, @bsloadlibs); # strip empty libs
print " bsloadlibs=@bsloadlibs\n" if $Verbose;
# We need DynaLoader here because we and/or the *_BS file may
# call dl_findfile(). We don't say `use' here because when
# first building perl extensions the DynaLoader will not have
# been built when MakeMaker gets first used.
require DynaLoader;
rename "$baseext.bs", "$baseext.bso"
if -s "$baseext.bs";
if (-f "${baseext}_BS"){
$_ = "${baseext}_BS";
package DynaLoader; # execute code as if in DynaLoader
no strict 'vars';
local($osname, $dlsrc) = (); # avoid warnings
($osname, $dlsrc) = @Config::Config{qw(osname dlsrc)};
$bscode = "";
unshift @INC, ".";
require $_;
shift @INC;
}
if ($Config{'dlsrc'} =~ /^dl_dld/){
package DynaLoader;
no strict 'vars';
push(@dl_resolve_using, dl_findfile('-lc'));
}
my(@all) = (@bsloadlibs, @DynaLoader::dl_resolve_using);
my($method) = '';
if (@all || (defined $DynaLoader::bscode && length $DynaLoader::bscode)){
open my $bs, ">", "$baseext.bs"
or die "Unable to open $baseext.bs: $!";
print "Writing $baseext.bs\n";
print " containing: @all" if $Verbose;
print $bs "# $baseext DynaLoader bootstrap file for $^O architecture.\n";
print $bs "# Do not edit this file, changes will be lost.\n";
print $bs "# This file was automatically generated by the\n";
print $bs "# Mkbootstrap routine in ExtUtils::Mkbootstrap (v$VERSION).\n";
if (@all) {
print $bs "\@DynaLoader::dl_resolve_using = ";
# If @all contains names in the form -lxxx or -Lxxx then it's asking for
# runtime library location so we automatically add a call to dl_findfile()
if (" @all" =~ m/ -[lLR]/){
print $bs " dl_findfile(qw(\n @all\n ));\n";
} else {
print $bs " qw(@all);\n";
}
}
# write extra code if *_BS says so
print $bs $DynaLoader::bscode if $DynaLoader::bscode;
print $bs "\n1;\n";
close $bs;
}
}
1;
__END__
=head1 NAME
ExtUtils::Mkbootstrap - make a bootstrap file for use by DynaLoader
=head1 SYNOPSIS
Mkbootstrap
=head1 DESCRIPTION
Mkbootstrap typically gets called from an extension Makefile.
There is no C<*.bs> file supplied with the extension. Instead, there may
be a C<*_BS> file which has code for the special cases, like posix for
berkeley db on the NeXT.
This file will get parsed, and produce a maybe empty
C<@DynaLoader::dl_resolve_using> array for the current architecture.
That will be extended by $BSLOADLIBS, which was computed by
ExtUtils::Liblist::ext(). If this array still is empty, we do nothing,
else we write a .bs file with an C<@DynaLoader::dl_resolve_using>
array.
The C<*_BS> file can put some code into the generated C<*.bs> file by
placing it in C<$bscode>. This is a handy 'escape' mechanism that may
prove useful in complex situations.
If @DynaLoader::dl_resolve_using contains C<-L*> or C<-l*> entries then
Mkbootstrap will automatically add a dl_findfile() call to the
generated C<*.bs> file.
=cut

View file

@ -0,0 +1,319 @@
package ExtUtils::Mksymlists;
use 5.006;
use strict qw[ subs refs ];
# no strict 'vars'; # until filehandles are exempted
use warnings;
use Carp;
use Exporter;
use Config;
our @ISA = qw(Exporter);
our @EXPORT = qw(&Mksymlists);
our $VERSION = '7.70';
$VERSION =~ tr/_//d;
sub Mksymlists {
my(%spec) = @_;
my($osname) = $^O;
croak("Insufficient information specified to Mksymlists")
unless ( $spec{NAME} or
($spec{FILE} and ($spec{DL_FUNCS} or $spec{FUNCLIST})) );
$spec{DL_VARS} = [] unless $spec{DL_VARS};
($spec{FILE} = $spec{NAME}) =~ s/.*::// unless $spec{FILE};
$spec{FUNCLIST} = [] unless $spec{FUNCLIST};
$spec{DL_FUNCS} = { $spec{NAME} => [] }
unless ( ($spec{DL_FUNCS} and keys %{$spec{DL_FUNCS}}) or
@{$spec{FUNCLIST}});
if (defined $spec{DL_FUNCS}) {
foreach my $package (sort keys %{$spec{DL_FUNCS}}) {
my($packprefix,$bootseen);
($packprefix = $package) =~ s/\W/_/g;
foreach my $sym (@{$spec{DL_FUNCS}->{$package}}) {
if ($sym =~ /^boot_/) {
push(@{$spec{FUNCLIST}},$sym);
$bootseen++;
}
else {
push(@{$spec{FUNCLIST}},"XS_${packprefix}_$sym");
}
}
push(@{$spec{FUNCLIST}},"boot_$packprefix") unless $bootseen;
}
}
# We'll need this if we ever add any OS which uses mod2fname
# not as pseudo-builtin.
# require DynaLoader;
if (defined &DynaLoader::mod2fname and not $spec{DLBASE}) {
$spec{DLBASE} = DynaLoader::mod2fname([ split(/::/,$spec{NAME}) ]);
}
if ($osname eq 'aix') { _write_aix(\%spec); }
elsif ($osname eq 'MacOS'){ _write_aix(\%spec) }
elsif ($osname eq 'VMS') { _write_vms(\%spec) }
elsif ($osname eq 'os2') { _write_os2(\%spec) }
elsif ($osname eq 'MSWin32') { _write_win32(\%spec) }
else {
croak("Don't know how to create linker option file for $osname\n");
}
}
sub _write_aix {
my($data) = @_;
rename "$data->{FILE}.exp", "$data->{FILE}.exp_old";
open( my $exp, ">", "$data->{FILE}.exp")
or croak("Can't create $data->{FILE}.exp: $!\n");
print $exp join("\n",@{$data->{DL_VARS}}, "\n") if @{$data->{DL_VARS}};
print $exp join("\n",@{$data->{FUNCLIST}}, "\n") if @{$data->{FUNCLIST}};
close $exp;
}
sub _write_os2 {
my($data) = @_;
require Config;
my $threaded = ($Config::Config{archname} =~ /-thread/ ? " threaded" : "");
if (not $data->{DLBASE}) {
($data->{DLBASE} = $data->{NAME}) =~ s/.*:://;
$data->{DLBASE} = substr($data->{DLBASE},0,7) . '_';
}
my $distname = $data->{DISTNAME} || $data->{NAME};
$distname = "Distribution $distname";
my $patchlevel = " pl$Config{perl_patchlevel}" || '';
my $comment = sprintf "Perl (v%s%s%s) module %s",
$Config::Config{version}, $threaded, $patchlevel, $data->{NAME};
chomp $comment;
if ($data->{INSTALLDIRS} and $data->{INSTALLDIRS} eq 'perl') {
$distname = 'perl5-porters@perl.org';
$comment = "Core $comment";
}
$comment = "$comment (Perl-config: $Config{config_args})";
$comment = substr($comment, 0, 200) . "...)" if length $comment > 203;
rename "$data->{FILE}.def", "$data->{FILE}_def.old";
open(my $def, ">", "$data->{FILE}.def")
or croak("Can't create $data->{FILE}.def: $!\n");
print $def "LIBRARY '$data->{DLBASE}' INITINSTANCE TERMINSTANCE\n";
print $def "DESCRIPTION '\@#$distname:$data->{VERSION}#\@ $comment'\n";
print $def "CODE LOADONCALL\n";
print $def "DATA LOADONCALL NONSHARED MULTIPLE\n";
print $def "EXPORTS\n ";
print $def join("\n ",@{$data->{DL_VARS}}, "\n") if @{$data->{DL_VARS}};
print $def join("\n ",@{$data->{FUNCLIST}}, "\n") if @{$data->{FUNCLIST}};
_print_imports($def, $data);
close $def;
}
sub _print_imports {
my ($def, $data)= @_;
my $imports= $data->{IMPORTS}
or return;
if ( keys %$imports ) {
print $def "IMPORTS\n";
foreach my $name (sort keys %$imports) {
print $def " $name=$imports->{$name}\n";
}
}
}
sub _write_win32 {
my($data) = @_;
require Config;
if (not $data->{DLBASE}) {
($data->{DLBASE} = $data->{NAME}) =~ s/.*:://;
$data->{DLBASE} = substr($data->{DLBASE},0,7) . '_';
}
rename "$data->{FILE}.def", "$data->{FILE}_def.old";
open( my $def, ">", "$data->{FILE}.def" )
or croak("Can't create $data->{FILE}.def: $!\n");
# put library name in quotes (it could be a keyword, like 'Alias')
if ($Config::Config{'cc'} !~ /\bgcc/i) {
print $def "LIBRARY \"$data->{DLBASE}\"\n";
}
print $def "EXPORTS\n ";
my @syms;
# Export public symbols both with and without underscores to
# ensure compatibility between DLLs from Borland C and Visual C
# NOTE: DynaLoader itself only uses the names without underscores,
# so this is only to cover the case when the extension DLL may be
# linked to directly from C. GSAR 97-07-10
#bcc dropped in 5.16, so dont create useless extra symbols for export table
unless("$]" >= 5.016) {
if ($Config::Config{'cc'} =~ /^bcc/i) {
push @syms, "_$_", "$_ = _$_"
for (@{$data->{DL_VARS}}, @{$data->{FUNCLIST}});
}
else {
push @syms, "$_", "_$_ = $_"
for (@{$data->{DL_VARS}}, @{$data->{FUNCLIST}});
}
} else {
push @syms, "$_"
for (@{$data->{DL_VARS}}, @{$data->{FUNCLIST}});
}
print $def join("\n ",@syms, "\n") if @syms;
_print_imports($def, $data);
close $def;
}
sub _write_vms {
my($data) = @_;
require Config; # a reminder for once we do $^O
require ExtUtils::XSSymSet;
my($isvax) = $Config::Config{'archname'} =~ /VAX/i;
my($set) = new ExtUtils::XSSymSet;
rename "$data->{FILE}.opt", "$data->{FILE}.opt_old";
open(my $opt,">", "$data->{FILE}.opt")
or croak("Can't create $data->{FILE}.opt: $!\n");
# Options file declaring universal symbols
# Used when linking shareable image for dynamic extension,
# or when linking PerlShr into which we've added this package
# as a static extension
# We don't do anything to preserve order, so we won't relax
# the GSMATCH criteria for a dynamic extension
print $opt "case_sensitive=yes\n"
if $Config::Config{d_vms_case_sensitive_symbols};
foreach my $sym (@{$data->{FUNCLIST}}) {
my $safe = $set->addsym($sym);
if ($isvax) { print $opt "UNIVERSAL=$safe\n" }
else { print $opt "SYMBOL_VECTOR=($safe=PROCEDURE)\n"; }
}
foreach my $sym (@{$data->{DL_VARS}}) {
my $safe = $set->addsym($sym);
print $opt "PSECT_ATTR=${sym},PIC,OVR,RD,NOEXE,WRT,NOSHR\n";
if ($isvax) { print $opt "UNIVERSAL=$safe\n" }
else { print $opt "SYMBOL_VECTOR=($safe=DATA)\n"; }
}
close $opt;
}
1;
__END__
=head1 NAME
ExtUtils::Mksymlists - write linker options files for dynamic extension
=head1 SYNOPSIS
use ExtUtils::Mksymlists;
Mksymlists( NAME => $name ,
DL_VARS => [ $var1, $var2, $var3 ],
DL_FUNCS => { $pkg1 => [ $func1, $func2 ],
$pkg2 => [ $func3 ] );
=head1 DESCRIPTION
C<ExtUtils::Mksymlists> produces files used by the linker under some OSs
during the creation of shared libraries for dynamic extensions. It is
normally called from a MakeMaker-generated Makefile when the extension
is built. The linker option file is generated by calling the function
C<Mksymlists>, which is exported by default from C<ExtUtils::Mksymlists>.
It takes one argument, a list of key-value pairs, in which the following
keys are recognized:
=over 4
=item DLBASE
This item specifies the name by which the linker knows the
extension, which may be different from the name of the
extension itself (for instance, some linkers add an '_' to the
name of the extension). If it is not specified, it is derived
from the NAME attribute. It is presently used only by OS2 and Win32.
=item DL_FUNCS
This is identical to the DL_FUNCS attribute available via MakeMaker,
from which it is usually taken. Its value is a reference to an
associative array, in which each key is the name of a package, and
each value is an a reference to an array of function names which
should be exported by the extension. For instance, one might say
C<DL_FUNCS =E<gt> { Homer::Iliad =E<gt> [ qw(trojans greeks) ],
Homer::Odyssey =E<gt> [ qw(travellers family suitors) ] }>. The
function names should be identical to those in the XSUB code;
C<Mksymlists> will alter the names written to the linker option
file to match the changes made by F<xsubpp>. In addition, if
none of the functions in a list begin with the string B<boot_>,
C<Mksymlists> will add a bootstrap function for that package,
just as xsubpp does. (If a B<boot_E<lt>pkgE<gt>> function is
present in the list, it is passed through unchanged.) If
DL_FUNCS is not specified, it defaults to the bootstrap
function for the extension specified in NAME.
=item DL_VARS
This is identical to the DL_VARS attribute available via MakeMaker,
and, like DL_FUNCS, it is usually specified via MakeMaker. Its
value is a reference to an array of variable names which should
be exported by the extension.
=item FILE
This key can be used to specify the name of the linker option file
(minus the OS-specific extension), if for some reason you do not
want to use the default value, which is the last word of the NAME
attribute (I<e.g.> for C<Tk::Canvas>, FILE defaults to C<Canvas>).
=item FUNCLIST
This provides an alternate means to specify function names to be
exported from the extension. Its value is a reference to an
array of function names to be exported by the extension. These
names are passed through unaltered to the linker options file.
Specifying a value for the FUNCLIST attribute suppresses automatic
generation of the bootstrap function for the package. To still create
the bootstrap name you have to specify the package name in the
DL_FUNCS hash:
Mksymlists( NAME => $name ,
FUNCLIST => [ $func1, $func2 ],
DL_FUNCS => { $pkg => [] } );
=item IMPORTS
This attribute is used to specify names to be imported into the
extension. It is currently only used by OS/2 and Win32.
=item NAME
This gives the name of the extension (I<e.g.> C<Tk::Canvas>) for which
the linker option file will be produced.
=back
When calling C<Mksymlists>, one should always specify the NAME
attribute. In most cases, this is all that's necessary. In
the case of unusual extensions, however, the other attributes
can be used to provide additional information to the linker.
=head1 AUTHOR
Charles Bailey I<E<lt>bailey@newman.upenn.eduE<gt>>
=head1 REVISION
Last revised 14-Feb-1996, for Perl 5.002.

View file

@ -0,0 +1,194 @@
package ExtUtils::PL2Bat;
$ExtUtils::PL2Bat::VERSION = '0.005';
use strict;
use warnings;
use 5.006;
use Config;
use Carp qw/croak/;
# In core, we can't use any other modules except those that already live in
# lib/, so Exporter is not available to us.
sub import {
my ($self, @functions) = @_;
@functions = 'pl2bat' if not @functions;
my $caller = caller;
for my $function (@functions) {
no strict 'refs';
*{"$caller\::$function"} = \&{$function};
}
}
sub pl2bat {
my %opts = @_;
# NOTE: %0 is already enclosed in doublequotes by cmd.exe, as appropriate
$opts{ntargs} = '-x -S %0 %*' unless exists $opts{ntargs};
$opts{otherargs} = '-x -S "%0" %1 %2 %3 %4 %5 %6 %7 %8 %9' unless exists $opts{otherargs};
$opts{stripsuffix} = qr/\.plx?/ unless exists $opts{stripsuffix};
if (not exists $opts{out}) {
$opts{out} = $opts{in};
$opts{out} =~ s/$opts{stripsuffix}$//i;
$opts{out} .= '.bat' unless $opts{in} =~ /\.bat$/i or $opts{in} eq '-';
}
my $head = <<"EOT";
\@rem = '--*-Perl-*--
\@set "ErrorLevel="
\@if "%OS%" == "Windows_NT" \@goto WinNT
\@perl $opts{otherargs}
\@set ErrorLevel=%ErrorLevel%
\@goto endofperl
:WinNT
\@perl $opts{ntargs}
\@set ErrorLevel=%ErrorLevel%
\@if NOT "%COMSPEC%" == "%SystemRoot%\\system32\\cmd.exe" \@goto endofperl
\@if %ErrorLevel% == 9009 \@echo You do not have Perl in your PATH.
\@goto endofperl
\@rem ';
EOT
$head =~ s/^\s+//gm;
my $headlines = 2 + ($head =~ tr/\n/\n/);
my $tail = <<'EOT';
__END__
:endofperl
@set "ErrorLevel=" & @goto _undefined_label_ 2>NUL || @"%COMSPEC%" /d/c @exit %ErrorLevel%
EOT
$tail =~ s/^\s+//gm;
my $linedone = 0;
my $taildone = 0;
my $linenum = 0;
my $skiplines = 0;
my $start = $Config{startperl};
$start = '#!perl' unless $start =~ /^#!.*perl/;
open my $in, '<', $opts{in} or croak "Can't open $opts{in}: $!";
my @file = <$in>;
close $in;
foreach my $line ( @file ) {
$linenum++;
if ( $line =~ /^:endofperl\b/ ) {
if (!exists $opts{update}) {
warn "$opts{in} has already been converted to a batch file!\n";
return;
}
$taildone++;
}
if ( not $linedone and $line =~ /^#!.*perl/ ) {
if (exists $opts{update}) {
$skiplines = $linenum - 1;
$line .= '#line '.(1+$headlines)."\n";
} else {
$line .= '#line '.($linenum+$headlines)."\n";
}
$linedone++;
}
if ( $line =~ /^#\s*line\b/ and $linenum == 2 + $skiplines ) {
$line = '';
}
}
open my $out, '>', $opts{out} or croak "Can't open $opts{out}: $!";
print $out $head;
print $out $start, ( $opts{usewarnings} ? ' -w' : '' ),
"\n#line ", ($headlines+1), "\n" unless $linedone;
print $out @file[$skiplines..$#file];
print $out $tail unless $taildone;
close $out;
return $opts{out};
}
1;
# ABSTRACT: Batch file creation to run perl scripts on Windows
__END__
=pod
=encoding UTF-8
=head1 NAME
ExtUtils::PL2Bat - Batch file creation to run perl scripts on Windows
=head1 VERSION
version 0.005
=head1 OVERVIEW
This module converts a perl script into a batch file that can be executed on Windows/DOS-like operating systems. This is intended to allow you to use a Perl script like regular programs and batch files where you just enter the name of the script [probably minus the extension] plus any command-line arguments and the script is found in your B<PATH> and run.
=head1 FUNCTIONS
=head2 pl2bat(%opts)
This function takes a perl script and write a batch file that contains the script. This is sometimes necessary
=over 8
=item * C<in>
The name of the script that is to be batchified. This argument is mandatory.
=item * C<out>
The name of the output batch file. If not given, it will be generated using C<in> and C<stripsuffix>.
=item * C<ntargs>
Arguments to invoke perl with in generated batch file when run from
Windows NT. Defaults to S<'-x -S %0 %*'>.
=item * C<otherargs>
Arguments to invoke perl with in generated batch file except when
run from Windows NT (ie. when run from DOS, Windows 3.1, or Windows 95).
Defaults to S<'-x -S "%0" %1 %2 %3 %4 %5 %6 %7 %8 %9'>.
=item * C<stripsuffix>
Strip a suffix string from file name before appending a ".bat"
suffix. The suffix is not case-sensitive. It can be a regex or a string and a trailing
C<$> is always assumed). Defaults to C<qr/\.plx?/>.
=item * C<usewarnings>
With the C<usewarnings>
option, C<" -w"> is added after the value of C<$Config{startperl}>.
If a line matching C</^#!.*perl/> already exists in the script,
then it is not changed and the B<-w> option is ignored.
=item * C<update>
If the script appears to have already been processed by B<pl2bat>,
then the script is skipped and not processed unless C<update> was
specified. If C<update> is specified, the existing preamble is replaced.
=back
=head1 ACKNOWLEDGEMENTS
This code was taken from Module::Build and then modified; which had taken it from perl's pl2bat script. This module is an attempt at unifying all three implementations.
=head1 AUTHOR
Leon Timmermans <leont@cpan.org>
=head1 COPYRIGHT AND LICENSE
This software is copyright (c) 2015 by Leon Timmermans.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
=cut

View file

@ -0,0 +1,352 @@
package ExtUtils::Packlist;
use strict;
use Carp qw();
use Config;
our $Relocations;
our $VERSION = '2.22';
$VERSION = eval $VERSION;
# Used for generating filehandle globs. IO::File might not be available!
my $fhname = "FH1";
=begin _undocumented
=over
=item mkfh()
Make a filehandle. Same kind of idea as Symbol::gensym().
=cut
sub mkfh()
{
no strict;
local $^W;
my $fh = \*{$fhname++};
use strict;
return($fh);
}
=item __find_relocations
Works out what absolute paths in the configuration have been located at run
time relative to $^X, and generates a regexp that matches them
=back
=end _undocumented
=cut
sub __find_relocations
{
my %paths;
while (my ($raw_key, $raw_val) = each %Config) {
my $exp_key = $raw_key . "exp";
next unless exists $Config{$exp_key};
next unless $raw_val =~ m!\.\.\./!;
$paths{$Config{$exp_key}}++;
}
# Longest prefixes go first in the alternatives
my $alternations = join "|", map {quotemeta $_}
sort {length $b <=> length $a} keys %paths;
qr/^($alternations)/o;
}
sub new($$)
{
my ($class, $packfile) = @_;
$class = ref($class) || $class;
my %self;
tie(%self, $class, $packfile);
return(bless(\%self, $class));
}
sub TIEHASH
{
my ($class, $packfile) = @_;
my $self = { packfile => $packfile };
bless($self, $class);
$self->read($packfile) if (defined($packfile) && -f $packfile);
return($self);
}
sub STORE
{
$_[0]->{data}->{$_[1]} = $_[2];
}
sub FETCH
{
return($_[0]->{data}->{$_[1]});
}
sub FIRSTKEY
{
my $reset = scalar(keys(%{$_[0]->{data}}));
return(each(%{$_[0]->{data}}));
}
sub NEXTKEY
{
return(each(%{$_[0]->{data}}));
}
sub EXISTS
{
return(exists($_[0]->{data}->{$_[1]}));
}
sub DELETE
{
return(delete($_[0]->{data}->{$_[1]}));
}
sub CLEAR
{
%{$_[0]->{data}} = ();
}
sub DESTROY
{
}
sub read($;$)
{
my ($self, $packfile) = @_;
$self = tied(%$self) || $self;
if (defined($packfile)) { $self->{packfile} = $packfile; }
else { $packfile = $self->{packfile}; }
Carp::croak("No packlist filename specified") if (! defined($packfile));
my $fh = mkfh();
open($fh, "<$packfile") || Carp::croak("Can't open file $packfile: $!");
$self->{data} = {};
my ($line);
while (defined($line = <$fh>))
{
chomp $line;
my ($key, $data) = $line;
if ($key =~ /^(.*?)( \w+=.*)$/)
{
$key = $1;
$data = { map { split('=', $_) } split(' ', $2)};
if ($Config{userelocatableinc} && $data->{relocate_as})
{
require File::Spec;
require Cwd;
my ($vol, $dir) = File::Spec->splitpath($packfile);
my $newpath = File::Spec->catpath($vol, $dir, $data->{relocate_as});
$key = Cwd::realpath($newpath);
}
}
$key =~ s!/\./!/!g; # Some .packlists have spurious '/./' bits in the paths
$self->{data}->{$key} = $data;
}
close($fh);
}
sub write($;$)
{
my ($self, $packfile) = @_;
$self = tied(%$self) || $self;
if (defined($packfile)) { $self->{packfile} = $packfile; }
else { $packfile = $self->{packfile}; }
Carp::croak("No packlist filename specified") if (! defined($packfile));
my $fh = mkfh();
open($fh, ">$packfile") || Carp::croak("Can't open file $packfile: $!");
foreach my $key (sort(keys(%{$self->{data}})))
{
my $data = $self->{data}->{$key};
if ($Config{userelocatableinc}) {
$Relocations ||= __find_relocations();
if ($packfile =~ $Relocations) {
# We are writing into a subdirectory of a run-time relocated
# path. Figure out if the this file is also within a subdir.
my $prefix = $1;
if (File::Spec->no_upwards(File::Spec->abs2rel($key, $prefix)))
{
# The relocated path is within the found prefix
my $packfile_prefix;
(undef, $packfile_prefix)
= File::Spec->splitpath($packfile);
my $relocate_as
= File::Spec->abs2rel($key, $packfile_prefix);
if (!ref $data) {
$data = {};
}
$data->{relocate_as} = $relocate_as;
}
}
}
print $fh ("$key");
if (ref($data))
{
foreach my $k (sort(keys(%$data)))
{
print $fh (" $k=$data->{$k}");
}
}
print $fh ("\n");
}
close($fh);
}
sub validate($;$)
{
my ($self, $remove) = @_;
$self = tied(%$self) || $self;
my @missing;
foreach my $key (sort(keys(%{$self->{data}})))
{
if (! -e $key)
{
push(@missing, $key);
delete($self->{data}{$key}) if ($remove);
}
}
return(@missing);
}
sub packlist_file($)
{
my ($self) = @_;
$self = tied(%$self) || $self;
return($self->{packfile});
}
1;
__END__
=head1 NAME
ExtUtils::Packlist - manage .packlist files
=head1 SYNOPSIS
use ExtUtils::Packlist;
my ($pl) = ExtUtils::Packlist->new('.packlist');
$pl->read('/an/old/.packlist');
my @missing_files = $pl->validate();
$pl->write('/a/new/.packlist');
$pl->{'/some/file/name'}++;
or
$pl->{'/some/other/file/name'} = { type => 'file',
from => '/some/file' };
=head1 DESCRIPTION
ExtUtils::Packlist provides a standard way to manage .packlist files.
Functions are provided to read and write .packlist files. The original
.packlist format is a simple list of absolute pathnames, one per line. In
addition, this package supports an extended format, where as well as a filename
each line may contain a list of attributes in the form of a space separated
list of key=value pairs. This is used by the installperl script to
differentiate between files and links, for example.
=head1 USAGE
The hash reference returned by the new() function can be used to examine and
modify the contents of the .packlist. Items may be added/deleted from the
.packlist by modifying the hash. If the value associated with a hash key is a
scalar, the entry written to the .packlist by any subsequent write() will be a
simple filename. If the value is a hash, the entry written will be the
filename followed by the key=value pairs from the hash. Reading back the
.packlist will recreate the original entries.
=head1 FUNCTIONS
=over 4
=item new()
This takes an optional parameter, the name of a .packlist. If the file exists,
it will be opened and the contents of the file will be read. The new() method
returns a reference to a hash. This hash holds an entry for each line in the
.packlist. In the case of old-style .packlists, the value associated with each
key is undef. In the case of new-style .packlists, the value associated with
each key is a hash containing the key=value pairs following the filename in the
.packlist.
=item read()
This takes an optional parameter, the name of the .packlist to be read. If
no file is specified, the .packlist specified to new() will be read. If the
.packlist does not exist, Carp::croak will be called.
=item write()
This takes an optional parameter, the name of the .packlist to be written. If
no file is specified, the .packlist specified to new() will be overwritten.
=item validate()
This checks that every file listed in the .packlist actually exists. If an
argument which evaluates to true is given, any missing files will be removed
from the internal hash. The return value is a list of the missing files, which
will be empty if they all exist.
=item packlist_file()
This returns the name of the associated .packlist file
=back
=head1 EXAMPLE
Here's C<modrm>, a little utility to cleanly remove an installed module.
#!/usr/local/bin/perl -w
use strict;
use IO::Dir;
use ExtUtils::Packlist;
use ExtUtils::Installed;
sub emptydir($) {
my ($dir) = @_;
my $dh = IO::Dir->new($dir) || return(0);
my @count = $dh->read();
$dh->close();
return(@count == 2 ? 1 : 0);
}
# Find all the installed packages
print("Finding all installed modules...\n");
my $installed = ExtUtils::Installed->new();
foreach my $module (grep(!/^Perl$/, $installed->modules())) {
my $version = $installed->version($module) || "???";
print("Found module $module Version $version\n");
print("Do you want to delete $module? [n] ");
my $r = <STDIN>; chomp($r);
if ($r && $r =~ /^y/i) {
# Remove all the files
foreach my $file (sort($installed->files($module))) {
print("rm $file\n");
unlink($file);
}
my $pf = $installed->packlist($module)->packlist_file();
print("rm $pf\n");
unlink($pf);
foreach my $dir (sort($installed->directory_tree($module))) {
if (emptydir($dir)) {
print("rmdir $dir\n");
rmdir($dir);
}
}
}
}
=head1 AUTHOR
Alan Burlison <Alan.Burlison@uk.sun.com>
=cut

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,187 @@
=head1 NAME
ExtUtils::ParseXS - converts Perl XS code into C code
=head1 SYNOPSIS
use ExtUtils::ParseXS;
my $pxs = ExtUtils::ParseXS->new;
$pxs->process_file( filename => 'foo.xs' );
$pxs->process_file( filename => 'foo.xs',
output => 'bar.c',
'C++' => 1,
typemap => 'path/to/typemap',
hiertype => 1,
except => 1,
versioncheck => 1,
linenumbers => 1,
optimize => 1,
prototypes => 1,
die_on_error => 0,
);
# Legacy non-OO interface using a singleton:
use ExtUtils::ParseXS qw(process_file);
process_file( filename => 'foo.xs' );
=head1 DESCRIPTION
C<ExtUtils::ParseXS> will compile XS code into C code by embedding the constructs
necessary to let C functions manipulate Perl values and creates the glue
necessary to let Perl access those functions. The compiler uses typemaps to
determine how to map C function parameters and variables to Perl values.
The compiler will search for typemap files called I<typemap>. It will use
the following search path to find default typemaps, with the rightmost
typemap taking precedence.
../../../typemap:../../typemap:../typemap:typemap
=head1 EXPORT
None by default. C<process_file()> and/or C<report_error_count()>
may be exported upon request. Using the functional interface is
discouraged.
=head1 METHODS
=over 4
=item $pxs->new()
Returns a new, empty XS parser/compiler object.
=item $pxs->process_file()
This method processes an XS file and sends output to a C file.
The method may be called as a function (this is the legacy
interface) and will then use a singleton as invocant.
Named parameters control how the processing is done.
The following parameters are accepted:
=over 4
=item B<C++>
Adds C<extern "C"> to the C code. Default is false.
=item B<hiertype>
Retains C<::> in type names so that C++ hierarchical types can be
mapped. Default is false.
=item B<except>
Adds exception handling stubs to the C code. Default is false.
=item B<typemap>
Indicates that a user-supplied typemap should take precedence over the
default typemaps. A single typemap may be specified as a string, or
multiple typemaps can be specified in an array reference, with the
last typemap having the highest precedence.
=item B<prototypes>
Generates prototype code for all xsubs. Default is false.
=item B<versioncheck>
Makes sure at run time that the object file (derived from the C<.xs>
file) and the C<.pm> files have the same version number. Default is
true.
=item B<linenumbers>
Adds C<#line> directives to the C output so error messages will look
like they came from the original XS file. Default is true.
=item B<optimize>
Enables certain optimizations. The only optimization that is currently
affected is the use of I<target>s by the output C code (see L<perlguts>).
Not optimizing may significantly slow down the generated code, but this is the way
B<xsubpp> of 5.005 and earlier operated. Default is to optimize.
=item B<inout>
Enable recognition of C<IN>, C<OUT_LIST> and C<INOUT_LIST>
declarations. Default is true.
=item B<argtypes>
Enable recognition of ANSI-like descriptions of function signature.
Default is true.
=item B<s>
I<Maintainer note:> I have no clue what this does. Strips function prefixes?
=item B<die_on_error>
Normally ExtUtils::ParseXS will terminate the program with an C<exit(1)> after
printing the details of the exception to STDERR via (warn). This can be awkward
when it is used programmatically and not via xsubpp, so this option can be used
to cause it to die instead by providing a true value. When not provided this
defaults to the value of C<$ExtUtils::ParseXS::DIE_ON_ERROR> which in turn
defaults to false.
=back
=item $pxs->report_error_count()
This method returns the number of [a certain kind of] errors
encountered during processing of the XS file.
The method may be called as a function (this is the legacy
interface) and will then use a singleton as invocant.
=back
=head1 AUTHOR
Based on xsubpp code, written by Larry Wall.
Maintained by:
=over 4
=item *
Ken Williams, <ken@mathforum.org>
=item *
David Golden, <dagolden@cpan.org>
=item *
James Keenan, <jkeenan@cpan.org>
=item *
Steffen Mueller, <smueller@cpan.org>
=back
=head1 COPYRIGHT
Copyright 2002-2014 by Ken Williams, David Golden and other contributors. All
rights reserved.
This library is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.
Based on the C<ExtUtils::xsubpp> code by Larry Wall and the Perl 5
Porters, which was released under the same license terms.
=head1 SEE ALSO
L<perl>, ExtUtils::xsubpp, ExtUtils::MakeMaker, L<perlxs>, L<perlxstut>.
=cut

View file

@ -0,0 +1,44 @@
package ExtUtils::ParseXS::Constants;
use strict;
use warnings;
use Symbol;
our $VERSION = '3.51';
=head1 NAME
ExtUtils::ParseXS::Constants - Initialization values for some globals
=head1 SYNOPSIS
use ExtUtils::ParseXS::Constants ();
$PrototypeRegexp = $ExtUtils::ParseXS::Constants::PrototypeRegexp;
=head1 DESCRIPTION
Initialization of certain non-subroutine variables in ExtUtils::ParseXS and some of its
supporting packages has been moved into this package so that those values can
be defined exactly once and then re-used in any package.
Nothing is exported. Use fully qualified variable names.
=cut
# FIXME: THESE ARE NOT CONSTANTS!
our @InitFileCode;
# Note that to reduce maintenance, $PrototypeRegexp is used
# by ExtUtils::Typemaps, too!
our $PrototypeRegexp = "[" . quotemeta('\$%&*@;[]_') . "]";
our @XSKeywords = qw(
REQUIRE BOOT CASE PREINIT INPUT INIT CODE PPCODE
OUTPUT CLEANUP ALIAS ATTRS PROTOTYPES PROTOTYPE
VERSIONCHECK INCLUDE INCLUDE_COMMAND SCOPE INTERFACE
INTERFACE_MACRO C_ARGS POSTCALL OVERLOAD FALLBACK
EXPORT_XSUB_SYMBOLS
);
our $XSKeywordsAlternation = join('|', @XSKeywords);
1;

View file

@ -0,0 +1,54 @@
package ExtUtils::ParseXS::CountLines;
use strict;
our $VERSION = '3.51';
our $SECTION_END_MARKER;
sub TIEHANDLE {
my ($class, $cfile, $fh) = @_;
$cfile =~ s/\\/\\\\/g;
$cfile =~ s/"/\\"/g;
$SECTION_END_MARKER = qq{#line --- "$cfile"};
return bless {
buffer => '',
fh => $fh,
line_no => 1,
}, $class;
}
sub PRINT {
my $self = shift;
for (@_) {
$self->{buffer} .= $_;
while ($self->{buffer} =~ s/^([^\n]*\n)//) {
my $line = $1;
++$self->{line_no};
$line =~ s|^\#line\s+---(?=\s)|#line $self->{line_no}|;
print {$self->{fh}} $line;
}
}
}
sub PRINTF {
my $self = shift;
my $fmt = shift;
$self->PRINT(sprintf($fmt, @_));
}
sub DESTROY {
# Not necessary if we're careful to end with a "\n"
my $self = shift;
print {$self->{fh}} $self->{buffer};
}
sub UNTIE {
# This sub does nothing, but is necessary for references to be released.
}
sub end_marker {
return $SECTION_END_MARKER;
}
1;

View file

@ -0,0 +1,97 @@
package ExtUtils::ParseXS::Eval;
use strict;
use warnings;
our $VERSION = '3.51';
=head1 NAME
ExtUtils::ParseXS::Eval - Clean package to evaluate code in
=head1 SYNOPSIS
use ExtUtils::ParseXS::Eval;
my $rv = ExtUtils::ParseXS::Eval::eval_typemap_code(
$parsexs_obj, "some Perl code"
);
=head1 SUBROUTINES
=head2 $pxs->eval_output_typemap_code($typemapcode, $other_hashref)
Sets up various bits of previously global state
(formerly ExtUtils::ParseXS package variables)
for eval'ing output typemap code that may refer to these
variables.
Warns the contents of C<$@> if any.
Not all these variables are necessarily considered "public" wrt. use in
typemaps, so beware. Variables set up from the ExtUtils::ParseXS object:
$Package $ALIAS $func_name $Full_func_name $pname
Variables set up from C<$other_hashref>:
$var $type $ntype $subtype $arg
=cut
sub eval_output_typemap_code {
my ($_pxs, $_code, $_other) = @_;
my ($Package, $ALIAS, $func_name, $Full_func_name, $pname)
= @{$_pxs}{qw(Package ALIAS func_name Full_func_name pname)};
my ($var, $type, $ntype, $subtype, $arg)
= @{$_other}{qw(var type ntype subtype arg)};
my $rv = eval $_code;
warn $@ if $@;
return $rv;
}
=head2 $pxs->eval_input_typemap_code($typemapcode, $other_hashref)
Sets up various bits of previously global state
(formerly ExtUtils::ParseXS package variables)
for eval'ing output typemap code that may refer to these
variables.
Warns the contents of C<$@> if any.
Not all these variables are necessarily considered "public" wrt. use in
typemaps, so beware. Variables set up from the ExtUtils::ParseXS object:
$Package $ALIAS $func_name $Full_func_name $pname
Variables set up from C<$other_hashref>:
$var $type $ntype $subtype $num $init $printed_name $arg $argoff
=cut
sub eval_input_typemap_code {
my ($_pxs, $_code, $_other) = @_;
my ($Package, $ALIAS, $func_name, $Full_func_name, $pname)
= @{$_pxs}{qw(Package ALIAS func_name Full_func_name pname)};
my ($var, $type, $num, $init, $printed_name, $arg, $ntype, $argoff, $subtype)
= @{$_other}{qw(var type num init printed_name arg ntype argoff subtype)};
my $rv = eval $_code;
warn $@ if $@;
return $rv;
}
=head1 TODO
Eventually, with better documentation and possible some cleanup,
this could be part of C<ExtUtils::Typemaps>.
=cut
1;
# vim: ts=2 sw=2 et:

View file

@ -0,0 +1,894 @@
package ExtUtils::ParseXS::Utilities;
use strict;
use warnings;
use Exporter;
use File::Spec;
use ExtUtils::ParseXS::Constants ();
our $VERSION = '3.51';
our (@ISA, @EXPORT_OK);
@ISA = qw(Exporter);
@EXPORT_OK = qw(
standard_typemap_locations
trim_whitespace
C_string
valid_proto_string
process_typemaps
map_type
standard_XS_defs
assign_func_args
analyze_preprocessor_statements
set_cond
Warn
WarnHint
current_line_number
blurt
death
check_conditional_preprocessor_statements
escape_file_for_line_directive
report_typemap_failure
);
=head1 NAME
ExtUtils::ParseXS::Utilities - Subroutines used with ExtUtils::ParseXS
=head1 SYNOPSIS
use ExtUtils::ParseXS::Utilities qw(
standard_typemap_locations
trim_whitespace
C_string
valid_proto_string
process_typemaps
map_type
standard_XS_defs
assign_func_args
analyze_preprocessor_statements
set_cond
Warn
blurt
death
check_conditional_preprocessor_statements
escape_file_for_line_directive
report_typemap_failure
);
=head1 SUBROUTINES
The following functions are not considered to be part of the public interface.
They are documented here for the benefit of future maintainers of this module.
=head2 C<standard_typemap_locations()>
=over 4
=item * Purpose
Provide a list of filepaths where F<typemap> files may be found. The
filepaths -- relative paths to files (not just directory paths) -- appear in this list in lowest-to-highest priority.
The highest priority is to look in the current directory.
'typemap'
The second and third highest priorities are to look in the parent of the
current directory and a directory called F<lib/ExtUtils> underneath the parent
directory.
'../typemap',
'../lib/ExtUtils/typemap',
The fourth through ninth highest priorities are to look in the corresponding
grandparent, great-grandparent and great-great-grandparent directories.
'../../typemap',
'../../lib/ExtUtils/typemap',
'../../../typemap',
'../../../lib/ExtUtils/typemap',
'../../../../typemap',
'../../../../lib/ExtUtils/typemap',
The tenth and subsequent priorities are to look in directories named
F<ExtUtils> which are subdirectories of directories found in C<@INC> --
I<provided> a file named F<typemap> actually exists in such a directory.
Example:
'/usr/local/lib/perl5/5.10.1/ExtUtils/typemap',
However, these filepaths appear in the list returned by
C<standard_typemap_locations()> in reverse order, I<i.e.>, lowest-to-highest.
'/usr/local/lib/perl5/5.10.1/ExtUtils/typemap',
'../../../../lib/ExtUtils/typemap',
'../../../../typemap',
'../../../lib/ExtUtils/typemap',
'../../../typemap',
'../../lib/ExtUtils/typemap',
'../../typemap',
'../lib/ExtUtils/typemap',
'../typemap',
'typemap'
=item * Arguments
my @stl = standard_typemap_locations( \@INC );
Reference to C<@INC>.
=item * Return Value
Array holding list of directories to be searched for F<typemap> files.
=back
=cut
SCOPE: {
my @tm_template;
sub standard_typemap_locations {
my $include_ref = shift;
if (not @tm_template) {
@tm_template = qw(typemap);
my $updir = File::Spec->updir();
foreach my $dir (
File::Spec->catdir(($updir) x 1),
File::Spec->catdir(($updir) x 2),
File::Spec->catdir(($updir) x 3),
File::Spec->catdir(($updir) x 4),
) {
unshift @tm_template, File::Spec->catfile($dir, 'typemap');
unshift @tm_template, File::Spec->catfile($dir, lib => ExtUtils => 'typemap');
}
}
my @tm = @tm_template;
foreach my $dir (@{ $include_ref}) {
my $file = File::Spec->catfile($dir, ExtUtils => 'typemap');
unshift @tm, $file if -e $file;
}
return @tm;
}
} # end SCOPE
=head2 C<trim_whitespace()>
=over 4
=item * Purpose
Perform an in-place trimming of leading and trailing whitespace from the
first argument provided to the function.
=item * Argument
trim_whitespace($arg);
=item * Return Value
None. Remember: this is an I<in-place> modification of the argument.
=back
=cut
sub trim_whitespace {
$_[0] =~ s/^\s+|\s+$//go;
}
=head2 C<C_string()>
=over 4
=item * Purpose
Escape backslashes (C<\>) in prototype strings.
=item * Arguments
$ProtoThisXSUB = C_string($_);
String needing escaping.
=item * Return Value
Properly escaped string.
=back
=cut
sub C_string {
my($string) = @_;
$string =~ s[\\][\\\\]g;
$string;
}
=head2 C<valid_proto_string()>
=over 4
=item * Purpose
Validate prototype string.
=item * Arguments
String needing checking.
=item * Return Value
Upon success, returns the same string passed as argument.
Upon failure, returns C<0>.
=back
=cut
sub valid_proto_string {
my ($string) = @_;
if ( $string =~ /^$ExtUtils::ParseXS::Constants::PrototypeRegexp+$/ ) {
return $string;
}
return 0;
}
=head2 C<process_typemaps()>
=over 4
=item * Purpose
Process all typemap files.
=item * Arguments
my $typemaps_object = process_typemaps( $args{typemap}, $pwd );
List of two elements: C<typemap> element from C<%args>; current working
directory.
=item * Return Value
Upon success, returns an L<ExtUtils::Typemaps> object.
=back
=cut
sub process_typemaps {
my ($tmap, $pwd) = @_;
my @tm = ref $tmap ? @{$tmap} : ($tmap);
foreach my $typemap (@tm) {
die "Can't find $typemap in $pwd\n" unless -r $typemap;
}
push @tm, standard_typemap_locations( \@INC );
require ExtUtils::Typemaps;
my $typemap = ExtUtils::Typemaps->new;
foreach my $typemap_loc (@tm) {
next unless -f $typemap_loc;
# skip directories, binary files etc.
warn("Warning: ignoring non-text typemap file '$typemap_loc'\n"), next
unless -T $typemap_loc;
$typemap->merge(file => $typemap_loc, replace => 1);
}
return $typemap;
}
=head2 C<map_type()>
=over 4
=item * Purpose
Performs a mapping at several places inside C<PARAGRAPH> loop.
=item * Arguments
$type = map_type($self, $type, $varname);
List of three arguments.
=item * Return Value
String holding augmented version of second argument.
=back
=cut
sub map_type {
my ($self, $type, $varname) = @_;
# C++ has :: in types too so skip this
$type =~ tr/:/_/ unless $self->{RetainCplusplusHierarchicalTypes};
$type =~ s/^array\(([^,]*),(.*)\).*/$1 */s;
if ($varname) {
if ($type =~ / \( \s* \* (?= \s* \) ) /xg) {
(substr $type, pos $type, 0) = " $varname ";
}
else {
$type .= "\t$varname";
}
}
return $type;
}
=head2 C<standard_XS_defs()>
=over 4
=item * Purpose
Writes to the C<.c> output file certain preprocessor directives and function
headers needed in all such files.
=item * Arguments
None.
=item * Return Value
Returns true.
=back
=cut
sub standard_XS_defs {
print <<"EOF";
#ifndef PERL_UNUSED_VAR
# define PERL_UNUSED_VAR(var) if (0) var = var
#endif
#ifndef dVAR
# define dVAR dNOOP
#endif
/* This stuff is not part of the API! You have been warned. */
#ifndef PERL_VERSION_DECIMAL
# define PERL_VERSION_DECIMAL(r,v,s) (r*1000000 + v*1000 + s)
#endif
#ifndef PERL_DECIMAL_VERSION
# define PERL_DECIMAL_VERSION \\
PERL_VERSION_DECIMAL(PERL_REVISION,PERL_VERSION,PERL_SUBVERSION)
#endif
#ifndef PERL_VERSION_GE
# define PERL_VERSION_GE(r,v,s) \\
(PERL_DECIMAL_VERSION >= PERL_VERSION_DECIMAL(r,v,s))
#endif
#ifndef PERL_VERSION_LE
# define PERL_VERSION_LE(r,v,s) \\
(PERL_DECIMAL_VERSION <= PERL_VERSION_DECIMAL(r,v,s))
#endif
/* XS_INTERNAL is the explicit static-linkage variant of the default
* XS macro.
*
* XS_EXTERNAL is the same as XS_INTERNAL except it does not include
* "STATIC", ie. it exports XSUB symbols. You probably don't want that
* for anything but the BOOT XSUB.
*
* See XSUB.h in core!
*/
/* TODO: This might be compatible further back than 5.10.0. */
#if PERL_VERSION_GE(5, 10, 0) && PERL_VERSION_LE(5, 15, 1)
# undef XS_EXTERNAL
# undef XS_INTERNAL
# if defined(__CYGWIN__) && defined(USE_DYNAMIC_LOADING)
# define XS_EXTERNAL(name) __declspec(dllexport) XSPROTO(name)
# define XS_INTERNAL(name) STATIC XSPROTO(name)
# endif
# if defined(__SYMBIAN32__)
# define XS_EXTERNAL(name) EXPORT_C XSPROTO(name)
# define XS_INTERNAL(name) EXPORT_C STATIC XSPROTO(name)
# endif
# ifndef XS_EXTERNAL
# if defined(HASATTRIBUTE_UNUSED) && !defined(__cplusplus)
# define XS_EXTERNAL(name) void name(pTHX_ CV* cv __attribute__unused__)
# define XS_INTERNAL(name) STATIC void name(pTHX_ CV* cv __attribute__unused__)
# else
# ifdef __cplusplus
# define XS_EXTERNAL(name) extern "C" XSPROTO(name)
# define XS_INTERNAL(name) static XSPROTO(name)
# else
# define XS_EXTERNAL(name) XSPROTO(name)
# define XS_INTERNAL(name) STATIC XSPROTO(name)
# endif
# endif
# endif
#endif
/* perl >= 5.10.0 && perl <= 5.15.1 */
/* The XS_EXTERNAL macro is used for functions that must not be static
* like the boot XSUB of a module. If perl didn't have an XS_EXTERNAL
* macro defined, the best we can do is assume XS is the same.
* Dito for XS_INTERNAL.
*/
#ifndef XS_EXTERNAL
# define XS_EXTERNAL(name) XS(name)
#endif
#ifndef XS_INTERNAL
# define XS_INTERNAL(name) XS(name)
#endif
/* Now, finally, after all this mess, we want an ExtUtils::ParseXS
* internal macro that we're free to redefine for varying linkage due
* to the EXPORT_XSUB_SYMBOLS XS keyword. This is internal, use
* XS_EXTERNAL(name) or XS_INTERNAL(name) in your code if you need to!
*/
#undef XS_EUPXS
#if defined(PERL_EUPXS_ALWAYS_EXPORT)
# define XS_EUPXS(name) XS_EXTERNAL(name)
#else
/* default to internal */
# define XS_EUPXS(name) XS_INTERNAL(name)
#endif
EOF
print <<"EOF";
#ifndef PERL_ARGS_ASSERT_CROAK_XS_USAGE
#define PERL_ARGS_ASSERT_CROAK_XS_USAGE assert(cv); assert(params)
/* prototype to pass -Wmissing-prototypes */
STATIC void
S_croak_xs_usage(const CV *const cv, const char *const params);
STATIC void
S_croak_xs_usage(const CV *const cv, const char *const params)
{
const GV *const gv = CvGV(cv);
PERL_ARGS_ASSERT_CROAK_XS_USAGE;
if (gv) {
const char *const gvname = GvNAME(gv);
const HV *const stash = GvSTASH(gv);
const char *const hvname = stash ? HvNAME(stash) : NULL;
if (hvname)
Perl_croak_nocontext("Usage: %s::%s(%s)", hvname, gvname, params);
else
Perl_croak_nocontext("Usage: %s(%s)", gvname, params);
} else {
/* Pants. I don't think that it should be possible to get here. */
Perl_croak_nocontext("Usage: CODE(0x%" UVxf ")(%s)", PTR2UV(cv), params);
}
}
#undef PERL_ARGS_ASSERT_CROAK_XS_USAGE
#define croak_xs_usage S_croak_xs_usage
#endif
/* NOTE: the prototype of newXSproto() is different in versions of perls,
* so we define a portable version of newXSproto()
*/
#ifdef newXS_flags
#define newXSproto_portable(name, c_impl, file, proto) newXS_flags(name, c_impl, file, proto, 0)
#else
#define newXSproto_portable(name, c_impl, file, proto) (PL_Sv=(SV*)newXS(name, c_impl, file), sv_setpv(PL_Sv, proto), (CV*)PL_Sv)
#endif /* !defined(newXS_flags) */
#if PERL_VERSION_LE(5, 21, 5)
# define newXS_deffile(a,b) Perl_newXS(aTHX_ a,b,file)
#else
# define newXS_deffile(a,b) Perl_newXS_deffile(aTHX_ a,b)
#endif
EOF
return 1;
}
=head2 C<assign_func_args()>
=over 4
=item * Purpose
Perform assignment to the C<func_args> attribute.
=item * Arguments
$string = assign_func_args($self, $argsref, $class);
List of three elements. Second is an array reference; third is a string.
=item * Return Value
String.
=back
=cut
sub assign_func_args {
my ($self, $argsref, $class) = @_;
my @func_args = @{$argsref};
shift @func_args if defined($class);
for my $arg (@func_args) {
$arg =~ s/^/&/ if $self->{in_out}->{$arg};
}
return join(", ", @func_args);
}
=head2 C<analyze_preprocessor_statements()>
=over 4
=item * Purpose
Within each function inside each Xsub, print to the F<.c> output file certain
preprocessor statements.
=item * Arguments
( $self, $XSS_work_idx, $BootCode_ref ) =
analyze_preprocessor_statements(
$self, $statement, $XSS_work_idx, $BootCode_ref
);
List of four elements.
=item * Return Value
Modifed values of three of the arguments passed to the function. In
particular, the C<XSStack> and C<InitFileCode> attributes are modified.
=back
=cut
sub analyze_preprocessor_statements {
my ($self, $statement, $XSS_work_idx, $BootCode_ref) = @_;
if ($statement eq 'if') {
$XSS_work_idx = @{ $self->{XSStack} };
push(@{ $self->{XSStack} }, {type => 'if'});
}
else {
$self->death("Error: '$statement' with no matching 'if'")
if $self->{XSStack}->[-1]{type} ne 'if';
if ($self->{XSStack}->[-1]{varname}) {
push(@{ $self->{InitFileCode} }, "#endif\n");
push(@{ $BootCode_ref }, "#endif");
}
my(@fns) = keys %{$self->{XSStack}->[-1]{functions}};
if ($statement ne 'endif') {
# Hide the functions defined in other #if branches, and reset.
@{$self->{XSStack}->[-1]{other_functions}}{@fns} = (1) x @fns;
@{$self->{XSStack}->[-1]}{qw(varname functions)} = ('', {});
}
else {
my($tmp) = pop(@{ $self->{XSStack} });
0 while (--$XSS_work_idx
&& $self->{XSStack}->[$XSS_work_idx]{type} ne 'if');
# Keep all new defined functions
push(@fns, keys %{$tmp->{other_functions}});
@{$self->{XSStack}->[$XSS_work_idx]{functions}}{@fns} = (1) x @fns;
}
}
return ($self, $XSS_work_idx, $BootCode_ref);
}
=head2 C<set_cond()>
=over 4
=item * Purpose
=item * Arguments
=item * Return Value
=back
=cut
sub set_cond {
my ($ellipsis, $min_args, $num_args) = @_;
my $cond;
if ($ellipsis) {
$cond = ($min_args ? qq(items < $min_args) : 0);
}
elsif ($min_args == $num_args) {
$cond = qq(items != $min_args);
}
else {
$cond = qq(items < $min_args || items > $num_args);
}
return $cond;
}
=head2 C<current_line_number()>
=over 4
=item * Purpose
Figures out the current line number in the XS file.
=item * Arguments
C<$self>
=item * Return Value
The current line number.
=back
=cut
sub current_line_number {
my $self = shift;
my $line_number = $self->{line_no}->[@{ $self->{line_no} } - @{ $self->{line} } -1];
return $line_number;
}
=head2 C<Warn()>
=over 4
=item * Purpose
Print warnings with line number details at the end.
=item * Arguments
List of text to output.
=item * Return Value
None.
=back
=cut
sub Warn {
my ($self)=shift;
$self->WarnHint(@_,undef);
}
=head2 C<WarnHint()>
=over 4
=item * Purpose
Prints warning with line number details. The last argument is assumed
to be a hint string.
=item * Arguments
List of strings to warn, followed by one argument representing a hint.
If that argument is defined then it will be split on newlines and output
line by line after the main warning.
=item * Return Value
None.
=back
=cut
sub WarnHint {
warn _MsgHint(@_);
}
=head2 C<_MsgHint()>
=over 4
=item * Purpose
Constructs an exception message with line number details. The last argument is
assumed to be a hint string.
=item * Arguments
List of strings to warn, followed by one argument representing a hint.
If that argument is defined then it will be split on newlines and concatenated
line by line (parenthesized) after the main message.
=item * Return Value
The constructed string.
=back
=cut
sub _MsgHint {
my $self = shift;
my $hint = pop;
my $warn_line_number = $self->current_line_number();
my $ret = join("",@_) . " in $self->{filename}, line $warn_line_number\n";
if ($hint) {
$ret .= " ($_)\n" for split /\n/, $hint;
}
return $ret;
}
=head2 C<blurt()>
=over 4
=item * Purpose
=item * Arguments
=item * Return Value
=back
=cut
sub blurt {
my $self = shift;
$self->Warn(@_);
$self->{errors}++
}
=head2 C<death()>
=over 4
=item * Purpose
=item * Arguments
=item * Return Value
=back
=cut
sub death {
my ($self) = (@_);
my $message = _MsgHint(@_,"");
if ($self->{die_on_error}) {
die $message;
} else {
warn $message;
}
exit 1;
}
=head2 C<check_conditional_preprocessor_statements()>
=over 4
=item * Purpose
=item * Arguments
=item * Return Value
=back
=cut
sub check_conditional_preprocessor_statements {
my ($self) = @_;
my @cpp = grep(/^\#\s*(?:if|e\w+)/, @{ $self->{line} });
if (@cpp) {
my $cpplevel;
for my $cpp (@cpp) {
if ($cpp =~ /^\#\s*if/) {
$cpplevel++;
}
elsif (!$cpplevel) {
$self->Warn("Warning: #else/elif/endif without #if in this function");
print STDERR " (precede it with a blank line if the matching #if is outside the function)\n"
if $self->{XSStack}->[-1]{type} eq 'if';
return;
}
elsif ($cpp =~ /^\#\s*endif/) {
$cpplevel--;
}
}
$self->Warn("Warning: #if without #endif in this function") if $cpplevel;
}
}
=head2 C<escape_file_for_line_directive()>
=over 4
=item * Purpose
Escapes a given code source name (typically a file name but can also
be a command that was read from) so that double-quotes and backslashes are escaped.
=item * Arguments
A string.
=item * Return Value
A string with escapes for double-quotes and backslashes.
=back
=cut
sub escape_file_for_line_directive {
my $string = shift;
$string =~ s/\\/\\\\/g;
$string =~ s/"/\\"/g;
return $string;
}
=head2 C<report_typemap_failure>
=over 4
=item * Purpose
Do error reporting for missing typemaps.
=item * Arguments
The C<ExtUtils::ParseXS> object.
An C<ExtUtils::Typemaps> object.
The string that represents the C type that was not found in the typemap.
Optionally, the string C<death> or C<blurt> to choose
whether the error is immediately fatal or not. Default: C<blurt>
=item * Return Value
Returns nothing. Depending on the arguments, this
may call C<death> or C<blurt>, the former of which is
fatal.
=back
=cut
sub report_typemap_failure {
my ($self, $tm, $ctype, $error_method) = @_;
$error_method ||= 'blurt';
my @avail_ctypes = $tm->list_mapped_ctypes;
my $err = "Could not find a typemap for C type '$ctype'.\n"
. "The following C types are mapped by the current typemap:\n'"
. join("', '", @avail_ctypes) . "'\n";
$self->$error_method($err);
return();
}
1;
# vim: ts=2 sw=2 et:

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,168 @@
package ExtUtils::Typemaps::Cmd;
use 5.006001;
use strict;
use warnings;
our $VERSION = '3.51';
use ExtUtils::Typemaps;
require Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw(embeddable_typemap);
our %EXPORT_TAGS = (all => \@EXPORT);
sub embeddable_typemap {
my @tms = @_;
# Get typemap objects
my @tm_objs = map [$_, _intuit_typemap_source($_)], @tms;
# merge or short-circuit
my $final_tm;
if (@tm_objs == 1) {
# just one, merge would be pointless
$final_tm = shift(@tm_objs)->[1];
}
else {
# multiple, need merge
$final_tm = ExtUtils::Typemaps->new;
foreach my $other_tm (@tm_objs) {
my ($tm_ident, $tm_obj) = @$other_tm;
eval {
$final_tm->merge(typemap => $tm_obj);
1
} or do {
my $err = $@ || 'Zombie error';
die "Failed to merge typ";
}
}
}
# stringify for embedding
return $final_tm->as_embedded_typemap();
}
sub _load_module {
my $name = shift;
return eval "require $name; 1";
}
SCOPE: {
my %sources = (
module => sub {
my $ident = shift;
my $tm;
if (/::/) { # looks like FQ module name, try that first
foreach my $module ($ident, "ExtUtils::Typemaps::$ident") {
if (_load_module($module)) {
eval { $tm = $module->new }
and return $tm;
}
}
}
else {
foreach my $module ("ExtUtils::Typemaps::$ident", "$ident") {
if (_load_module($module)) {
eval { $tm = $module->new }
and return $tm;
}
}
}
return();
},
file => sub {
my $ident = shift;
return unless -e $ident and -r _;
return ExtUtils::Typemaps->new(file => $ident);
},
);
# Try to find typemap either from module or file
sub _intuit_typemap_source {
my $identifier = shift;
my @locate_attempts;
if ($identifier =~ /::/ || $identifier !~ /[^\w_]/) {
@locate_attempts = qw(module file);
}
else {
@locate_attempts = qw(file module);
}
foreach my $source (@locate_attempts) {
my $tm = $sources{$source}->($identifier);
return $tm if defined $tm;
}
die "Unable to find typemap for '$identifier': "
. "Tried to load both as file or module and failed.\n";
}
} # end SCOPE
=head1 NAME
ExtUtils::Typemaps::Cmd - Quick commands for handling typemaps
=head1 SYNOPSIS
From XS:
INCLUDE_COMMAND: $^X -MExtUtils::Typemaps::Cmd \
-e "print embeddable_typemap(q{Excommunicated})"
Loads C<ExtUtils::Typemaps::Excommunicated>, instantiates an object,
and dumps it as an embeddable typemap for use directly in your XS file.
=head1 DESCRIPTION
This is a helper module for L<ExtUtils::Typemaps> for quick
one-liners, specifically for inclusion of shared typemaps
that live on CPAN into an XS file (see SYNOPSIS).
For this reason, the following functions are exported by default:
=head1 EXPORTED FUNCTIONS
=head2 embeddable_typemap
Given a list of identifiers, C<embeddable_typemap>
tries to load typemaps from a file of the given name(s),
or from a module that is an C<ExtUtils::Typemaps> subclass.
Returns a string representation of the merged typemaps that can
be included verbatim into XS. Example:
print embeddable_typemap(
"Excommunicated", "ExtUtils::Typemaps::Basic", "./typemap"
);
This will try to load a module C<ExtUtils::Typemaps::Excommunicated>
and use it as an C<ExtUtils::Typemaps> subclass. If that fails, it'll
try loading C<Excommunicated> as a module, if that fails, it'll try to
read a file called F<Excommunicated>. It'll work similarly for the
second argument, but the third will be loaded as a file first.
After loading all typemap files or modules, it will merge them in the
specified order and dump the result as an embeddable typemap.
=head1 SEE ALSO
L<ExtUtils::Typemaps>
L<perlxs>
=head1 AUTHOR
Steffen Mueller C<<smueller@cpan.org>>
=head1 COPYRIGHT & LICENSE
Copyright 2012 Steffen Mueller
This program is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.
=cut
1;

View file

@ -0,0 +1,116 @@
package ExtUtils::Typemaps::InputMap;
use 5.006001;
use strict;
use warnings;
our $VERSION = '3.51';
=head1 NAME
ExtUtils::Typemaps::InputMap - Entry in the INPUT section of a typemap
=head1 SYNOPSIS
use ExtUtils::Typemaps;
...
my $input = $typemap->get_input_map('T_NV');
my $code = $input->code();
$input->code("...");
=head1 DESCRIPTION
Refer to L<ExtUtils::Typemaps> for details.
=head1 METHODS
=cut
=head2 new
Requires C<xstype> and C<code> parameters.
=cut
sub new {
my $prot = shift;
my $class = ref($prot)||$prot;
my %args = @_;
if (!ref($prot)) {
if (not defined $args{xstype} or not defined $args{code}) {
die("Need xstype and code parameters");
}
}
my $self = bless(
(ref($prot) ? {%$prot} : {})
=> $class
);
$self->{xstype} = $args{xstype} if defined $args{xstype};
$self->{code} = $args{code} if defined $args{code};
$self->{code} =~ s/^(?=\S)/\t/mg;
return $self;
}
=head2 code
Returns or sets the INPUT mapping code for this entry.
=cut
sub code {
$_[0]->{code} = $_[1] if @_ > 1;
return $_[0]->{code};
}
=head2 xstype
Returns the name of the XS type of the INPUT map.
=cut
sub xstype {
return $_[0]->{xstype};
}
=head2 cleaned_code
Returns a cleaned-up copy of the code to which certain transformations
have been applied to make it more ANSI compliant.
=cut
sub cleaned_code {
my $self = shift;
my $code = $self->code;
$code =~ s/(?:;+\s*|;*\s+)\z//s;
# Move C pre-processor instructions to column 1 to be strictly ANSI
# conformant. Some pre-processors are fussy about this.
$code =~ s/^\s+#/#/mg;
$code =~ s/\s*\z/\n/;
return $code;
}
=head1 SEE ALSO
L<ExtUtils::Typemaps>
=head1 AUTHOR
Steffen Mueller C<<smueller@cpan.org>>
=head1 COPYRIGHT & LICENSE
Copyright 2009, 2010, 2011, 2012 Steffen Mueller
This program is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.
=cut
1;

View file

@ -0,0 +1,209 @@
package ExtUtils::Typemaps::OutputMap;
use 5.006001;
use strict;
use warnings;
our $VERSION = '3.51';
=head1 NAME
ExtUtils::Typemaps::OutputMap - Entry in the OUTPUT section of a typemap
=head1 SYNOPSIS
use ExtUtils::Typemaps;
...
my $output = $typemap->get_output_map('T_NV');
my $code = $output->code();
$output->code("...");
=head1 DESCRIPTION
Refer to L<ExtUtils::Typemaps> for details.
=head1 METHODS
=cut
=head2 new
Requires C<xstype> and C<code> parameters.
=cut
sub new {
my $prot = shift;
my $class = ref($prot)||$prot;
my %args = @_;
if (!ref($prot)) {
if (not defined $args{xstype} or not defined $args{code}) {
die("Need xstype and code parameters");
}
}
my $self = bless(
(ref($prot) ? {%$prot} : {})
=> $class
);
$self->{xstype} = $args{xstype} if defined $args{xstype};
$self->{code} = $args{code} if defined $args{code};
$self->{code} =~ s/^(?=\S)/\t/mg;
return $self;
}
=head2 code
Returns or sets the OUTPUT mapping code for this entry.
=cut
sub code {
$_[0]->{code} = $_[1] if @_ > 1;
return $_[0]->{code};
}
=head2 xstype
Returns the name of the XS type of the OUTPUT map.
=cut
sub xstype {
return $_[0]->{xstype};
}
=head2 cleaned_code
Returns a cleaned-up copy of the code to which certain transformations
have been applied to make it more ANSI compliant.
=cut
sub cleaned_code {
my $self = shift;
my $code = $self->code;
# Move C pre-processor instructions to column 1 to be strictly ANSI
# conformant. Some pre-processors are fussy about this.
$code =~ s/^\s+#/#/mg;
$code =~ s/\s*\z/\n/;
return $code;
}
=head2 targetable
This is an obscure but effective optimization that used to
live in C<ExtUtils::ParseXS> directly. Not implementing it
should never result in incorrect use of typemaps, just less
efficient code.
In a nutshell, this will check whether the output code
involves calling C<sv_setiv>, C<sv_setuv>, C<sv_setnv>, C<sv_setpv> or
C<sv_setpvn> to set the special C<$arg> placeholder to a new value
B<AT THE END OF THE OUTPUT CODE>. If that is the case, the code is
eligible for using the C<TARG>-related macros to optimize this.
Thus the name of the method: C<targetable>.
If this optimization is applicable, C<ExtUtils::ParseXS> will
emit a C<dXSTARG;> definition at the start of the generated XSUB code,
and type (see below) dependent code to set C<TARG> and push it on
the stack at the end of the generated XSUB code.
If the optimization can not be applied, this returns undef.
If it can be applied, this method returns a hash reference containing
the following information:
type: Any of the characters i, u, n, p
with_size: Bool indicating whether this is the sv_setpvn variant
what: The code that actually evaluates to the output scalar
what_size: If "with_size", this has the string length (as code,
not constant, including leading comma)
=cut
sub targetable {
my $self = shift;
return $self->{targetable} if exists $self->{targetable};
our $bal; # ()-balanced
$bal = qr[
(?:
(?>[^()]+)
|
\( (??{ $bal }) \)
)*
]x;
my $bal_no_comma = qr[
(?:
(?>[^(),]+)
|
\( (??{ $bal }) \)
)+
]x;
# matches variations on (SV*)
my $sv_cast = qr[
(?:
\( \s* SV \s* \* \s* \) \s*
)?
]x;
my $size = qr[ # Third arg (to setpvn)
, \s* (??{ $bal })
]xo;
my $code = $self->code;
# We can still bootstrap compile 're', because in code re.pm is
# available to miniperl, and does not attempt to load the XS code.
use re 'eval';
my ($type, $with_size, $arg, $sarg) =
($code =~
m[^
\s+
sv_set([iunp])v(n)? # Type, is_setpvn
\s*
\( \s*
$sv_cast \$arg \s* , \s*
( $bal_no_comma ) # Set from
( $size )? # Possible sizeof set-from
\s* \) \s* ; \s* $
]xo
);
my $rv = undef;
if ($type) {
$rv = {
type => $type,
with_size => $with_size,
what => $arg,
what_size => $sarg,
};
}
$self->{targetable} = $rv;
return $rv;
}
=head1 SEE ALSO
L<ExtUtils::Typemaps>
=head1 AUTHOR
Steffen Mueller C<<smueller@cpan.org>>
=head1 COPYRIGHT & LICENSE
Copyright 2009, 2010, 2011, 2012 Steffen Mueller
This program is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.
=cut
1;

View file

@ -0,0 +1,121 @@
package ExtUtils::Typemaps::Type;
use 5.006001;
use strict;
use warnings;
require ExtUtils::Typemaps;
our $VERSION = '3.51';
=head1 NAME
ExtUtils::Typemaps::Type - Entry in the TYPEMAP section of a typemap
=head1 SYNOPSIS
use ExtUtils::Typemaps;
...
my $type = $typemap->get_type_map('char*');
my $input = $typemap->get_input_map($type->xstype);
=head1 DESCRIPTION
Refer to L<ExtUtils::Typemaps> for details.
Object associates C<ctype> with C<xstype>, which is the index
into the in- and output mapping tables.
=head1 METHODS
=cut
=head2 new
Requires C<xstype> and C<ctype> parameters.
Optionally takes C<prototype> parameter.
=cut
sub new {
my $prot = shift;
my $class = ref($prot)||$prot;
my %args = @_;
if (!ref($prot)) {
if (not defined $args{xstype} or not defined $args{ctype}) {
die("Need xstype and ctype parameters");
}
}
my $self = bless(
(ref($prot) ? {%$prot} : {proto => ''})
=> $class
);
$self->{xstype} = $args{xstype} if defined $args{xstype};
$self->{ctype} = $args{ctype} if defined $args{ctype};
$self->{tidy_ctype} = ExtUtils::Typemaps::tidy_type($self->{ctype});
$self->{proto} = $args{'prototype'} if defined $args{'prototype'};
return $self;
}
=head2 proto
Returns or sets the prototype.
=cut
sub proto {
$_[0]->{proto} = $_[1] if @_ > 1;
return $_[0]->{proto};
}
=head2 xstype
Returns the name of the XS type that this C type is associated to.
=cut
sub xstype {
return $_[0]->{xstype};
}
=head2 ctype
Returns the name of the C type as it was set on construction.
=cut
sub ctype {
return defined($_[0]->{ctype}) ? $_[0]->{ctype} : $_[0]->{tidy_ctype};
}
=head2 tidy_ctype
Returns the canonicalized name of the C type.
=cut
sub tidy_ctype {
return $_[0]->{tidy_ctype};
}
=head1 SEE ALSO
L<ExtUtils::Typemaps>
=head1 AUTHOR
Steffen Mueller C<<smueller@cpan.org>>
=head1 COPYRIGHT & LICENSE
Copyright 2009, 2010, 2011, 2012 Steffen Mueller
This program is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.
=cut
1;

View file

@ -0,0 +1,42 @@
package ExtUtils::testlib;
use strict;
use warnings;
our $VERSION = '7.70';
$VERSION =~ tr/_//d;
use Cwd;
use File::Spec;
# So the tests can chdir around and not break @INC.
# We use getcwd() because otherwise rel2abs will blow up under taint
# mode pre-5.8. We detaint is so @INC won't be tainted. This is
# no worse, and probably better, than just shoving an untainted,
# relative "blib/lib" onto @INC.
my $cwd;
BEGIN {
($cwd) = getcwd() =~ /(.*)/;
}
use lib map { File::Spec->rel2abs($_, $cwd) } qw(blib/arch blib/lib);
1;
__END__
=head1 NAME
ExtUtils::testlib - add blib/* directories to @INC
=head1 SYNOPSIS
use ExtUtils::testlib;
=head1 DESCRIPTION
After an extension has been built and before it is installed it may be
desirable to test it bypassing C<make test>. By adding
use ExtUtils::testlib;
to a test program the intermediate directories used by C<make> are
added to @INC.

View file

@ -0,0 +1,471 @@
# basic C types
int T_IV
unsigned T_UV
unsigned int T_UV
long T_IV
unsigned long T_UV
short T_IV
unsigned short T_UV
char T_CHAR
unsigned char T_U_CHAR
char * T_PV
unsigned char * T_PV
const char * T_PV
caddr_t T_PV
wchar_t * T_PV
wchar_t T_IV
# bool_t is defined in <rpc/rpc.h>
bool_t T_IV
size_t T_UV
ssize_t T_IV
time_t T_NV
unsigned long * T_OPAQUEPTR
char ** T_PACKEDARRAY
void * T_PTR
Time_t * T_PV
SV * T_SV
# These are the backwards-compatibility AV*/HV* typemaps that
# do not decrement refcounts. Locally override with
# "AV* T_AVREF_REFCOUNT_FIXED", "HV* T_HVREF_REFCOUNT_FIXED",
# "CV* T_CVREF_REFCOUNT_FIXED", "SVREF T_SVREF_REFCOUNT_FIXED",
# to get the fixed versions.
SVREF T_SVREF
CV * T_CVREF
AV * T_AVREF
HV * T_HVREF
IV T_IV
UV T_UV
NV T_NV
I32 T_IV
I16 T_IV
I8 T_IV
STRLEN T_UV
U32 T_U_LONG
U16 T_U_SHORT
U8 T_UV
Result T_U_CHAR
Boolean T_BOOL
float T_FLOAT
double T_DOUBLE
SysRet T_SYSRET
SysRetLong T_SYSRET
FILE * T_STDIO
PerlIO * T_INOUT
FileHandle T_PTROBJ
InputStream T_IN
InOutStream T_INOUT
OutputStream T_OUT
bool T_BOOL
#############################################################################
INPUT
T_SV
$var = $arg
T_SVREF
STMT_START {
SV* const xsub_tmp_sv = $arg;
SvGETMAGIC(xsub_tmp_sv);
if (SvROK(xsub_tmp_sv)){
$var = SvRV(xsub_tmp_sv);
}
else{
Perl_croak_nocontext(\"%s: %s is not a reference\",
${$ALIAS?\q[GvNAME(CvGV(cv))]:\qq[\"$pname\"]},
\"$var\");
}
} STMT_END
T_SVREF_REFCOUNT_FIXED
STMT_START {
SV* const xsub_tmp_sv = $arg;
SvGETMAGIC(xsub_tmp_sv);
if (SvROK(xsub_tmp_sv)){
$var = SvRV(xsub_tmp_sv);
}
else{
Perl_croak_nocontext(\"%s: %s is not a reference\",
${$ALIAS?\q[GvNAME(CvGV(cv))]:\qq[\"$pname\"]},
\"$var\");
}
} STMT_END
T_AVREF
STMT_START {
SV* const xsub_tmp_sv = $arg;
SvGETMAGIC(xsub_tmp_sv);
if (SvROK(xsub_tmp_sv) && SvTYPE(SvRV(xsub_tmp_sv)) == SVt_PVAV){
$var = (AV*)SvRV(xsub_tmp_sv);
}
else{
Perl_croak_nocontext(\"%s: %s is not an ARRAY reference\",
${$ALIAS?\q[GvNAME(CvGV(cv))]:\qq[\"$pname\"]},
\"$var\");
}
} STMT_END
T_AVREF_REFCOUNT_FIXED
STMT_START {
SV* const xsub_tmp_sv = $arg;
SvGETMAGIC(xsub_tmp_sv);
if (SvROK(xsub_tmp_sv) && SvTYPE(SvRV(xsub_tmp_sv)) == SVt_PVAV){
$var = (AV*)SvRV(xsub_tmp_sv);
}
else{
Perl_croak_nocontext(\"%s: %s is not an ARRAY reference\",
${$ALIAS?\q[GvNAME(CvGV(cv))]:\qq[\"$pname\"]},
\"$var\");
}
} STMT_END
T_HVREF
STMT_START {
SV* const xsub_tmp_sv = $arg;
SvGETMAGIC(xsub_tmp_sv);
if (SvROK(xsub_tmp_sv) && SvTYPE(SvRV(xsub_tmp_sv)) == SVt_PVHV){
$var = (HV*)SvRV(xsub_tmp_sv);
}
else{
Perl_croak_nocontext(\"%s: %s is not a HASH reference\",
${$ALIAS?\q[GvNAME(CvGV(cv))]:\qq[\"$pname\"]},
\"$var\");
}
} STMT_END
T_HVREF_REFCOUNT_FIXED
STMT_START {
SV* const xsub_tmp_sv = $arg;
SvGETMAGIC(xsub_tmp_sv);
if (SvROK(xsub_tmp_sv) && SvTYPE(SvRV(xsub_tmp_sv)) == SVt_PVHV){
$var = (HV*)SvRV(xsub_tmp_sv);
}
else{
Perl_croak_nocontext(\"%s: %s is not a HASH reference\",
${$ALIAS?\q[GvNAME(CvGV(cv))]:\qq[\"$pname\"]},
\"$var\");
}
} STMT_END
T_CVREF
STMT_START {
HV *st;
GV *gvp;
SV * const xsub_tmp_sv = $arg;
SvGETMAGIC(xsub_tmp_sv);
$var = sv_2cv(xsub_tmp_sv, &st, &gvp, 0);
if (!$var) {
Perl_croak_nocontext(\"%s: %s is not a CODE reference\",
${$ALIAS?\q[GvNAME(CvGV(cv))]:\qq[\"$pname\"]},
\"$var\");
}
} STMT_END
T_CVREF_REFCOUNT_FIXED
STMT_START {
HV *st;
GV *gvp;
SV * const xsub_tmp_sv = $arg;
SvGETMAGIC(xsub_tmp_sv);
$var = sv_2cv(xsub_tmp_sv, &st, &gvp, 0);
if (!$var) {
Perl_croak_nocontext(\"%s: %s is not a CODE reference\",
${$ALIAS?\q[GvNAME(CvGV(cv))]:\qq[\"$pname\"]},
\"$var\");
}
} STMT_END
T_SYSRET
$var NOT IMPLEMENTED
T_UV
$var = ($type)SvUV($arg)
T_IV
$var = ($type)SvIV($arg)
T_INT
$var = (int)SvIV($arg)
T_ENUM
$var = ($type)SvIV($arg)
T_BOOL
$var = (bool)SvTRUE($arg)
T_U_INT
$var = (unsigned int)SvUV($arg)
T_SHORT
$var = (short)SvIV($arg)
T_U_SHORT
$var = (unsigned short)SvUV($arg)
T_LONG
$var = (long)SvIV($arg)
T_U_LONG
$var = (unsigned long)SvUV($arg)
T_CHAR
$var = (char)*SvPV_nolen($arg)
T_U_CHAR
$var = (unsigned char)SvUV($arg)
T_FLOAT
$var = (float)SvNV($arg)
T_NV
$var = ($type)SvNV($arg)
T_DOUBLE
$var = (double)SvNV($arg)
T_PV
$var = ($type)SvPV_nolen($arg)
T_PTR
$var = INT2PTR($type,SvIV($arg))
T_PTRREF
if (SvROK($arg)) {
IV tmp = SvIV((SV*)SvRV($arg));
$var = INT2PTR($type,tmp);
}
else
Perl_croak_nocontext(\"%s: %s is not a reference\",
${$ALIAS?\q[GvNAME(CvGV(cv))]:\qq[\"$pname\"]},
\"$var\")
T_REF_IV_REF
if (sv_isa($arg, \"${ntype}\")) {
IV tmp = SvIV((SV*)SvRV($arg));
$var = *INT2PTR($type *, tmp);
}
else {
const char* refstr = SvROK($arg) ? \"\" : SvOK($arg) ? \"scalar \" : \"undef\";
Perl_croak_nocontext(\"%s: Expected %s to be of type %s; got %s%\" SVf \" instead\",
${$ALIAS?\q[GvNAME(CvGV(cv))]:\qq[\"$pname\"]},
\"$var\", \"$ntype\",
refstr, $arg
);
}
T_REF_IV_PTR
if (sv_isa($arg, \"${ntype}\")) {
IV tmp = SvIV((SV*)SvRV($arg));
$var = INT2PTR($type, tmp);
}
else {
const char* refstr = SvROK($arg) ? \"\" : SvOK($arg) ? \"scalar \" : \"undef\";
Perl_croak_nocontext(\"%s: Expected %s to be of type %s; got %s%\" SVf \" instead\",
${$ALIAS?\q[GvNAME(CvGV(cv))]:\qq[\"$pname\"]},
\"$var\", \"$ntype\",
refstr, $arg
);
}
T_PTROBJ
if (SvROK($arg) && sv_derived_from($arg, \"${ntype}\")) {
IV tmp = SvIV((SV*)SvRV($arg));
$var = INT2PTR($type,tmp);
}
else {
const char* refstr = SvROK($arg) ? \"\" : SvOK($arg) ? \"scalar \" : \"undef\";
Perl_croak_nocontext(\"%s: Expected %s to be of type %s; got %s%\" SVf \" instead\",
${$ALIAS?\q[GvNAME(CvGV(cv))]:\qq[\"$pname\"]},
\"$var\", \"$ntype\",
refstr, $arg
);
}
T_PTRDESC
if (sv_isa($arg, \"${ntype}\")) {
IV tmp = SvIV((SV*)SvRV($arg));
${type}_desc = (\U${type}_DESC\E*) tmp;
$var = ${type}_desc->ptr;
}
else {
const char* refstr = SvROK($arg) ? \"\" : SvOK($arg) ? \"scalar \" : \"undef\";
Perl_croak_nocontext(\"%s: Expected %s to be of type %s; got %s%\" SVf \" instead\",
${$ALIAS?\q[GvNAME(CvGV(cv))]:\qq[\"$pname\"]},
\"$var\", \"$ntype\",
refstr, $arg
);
}
T_REFREF
if (SvROK($arg)) {
IV tmp = SvIV((SV*)SvRV($arg));
$var = *INT2PTR($type,tmp);
}
else
Perl_croak_nocontext(\"%s: %s is not a reference\",
${$ALIAS?\q[GvNAME(CvGV(cv))]:\qq[\"$pname\"]},
\"$var\")
T_REFOBJ
if (sv_isa($arg, \"${ntype}\")) {
IV tmp = SvIV((SV*)SvRV($arg));
$var = *INT2PTR($type,tmp);
}
else {
const char* refstr = SvROK($arg) ? \"\" : SvOK($arg) ? \"scalar \" : \"undef\";
Perl_croak_nocontext(\"%s: Expected %s to be of type %s; got %s%\" SVf \" instead\",
${$ALIAS?\q[GvNAME(CvGV(cv))]:\qq[\"$pname\"]},
\"$var\", \"$ntype\",
refstr, $arg
);
}
T_OPAQUE
$var = *($type *)SvPV_nolen($arg)
T_OPAQUEPTR
$var = ($type)SvPV_nolen($arg)
T_PACKED
$var = XS_unpack_$ntype($arg)
T_PACKEDARRAY
$var = XS_unpack_$ntype($arg)
T_ARRAY
U32 ix_$var = $argoff;
$var = $ntype(items -= $argoff);
while (items--) {
DO_ARRAY_ELEM;
ix_$var++;
}
/* this is the number of elements in the array */
ix_$var -= $argoff
T_STDIO
$var = PerlIO_findFILE(IoIFP(sv_2io($arg)))
T_IN
$var = IoIFP(sv_2io($arg))
T_INOUT
$var = IoIFP(sv_2io($arg))
T_OUT
$var = IoOFP(sv_2io($arg))
#############################################################################
OUTPUT
T_SV
${ "$var" eq "RETVAL" ? \"$arg = $var;" : \"sv_setsv_mg($arg, $var);" }
T_SVREF
$arg = newRV((SV*)$var);
T_SVREF_REFCOUNT_FIXED
${ "$var" eq "RETVAL" ? \"$arg = newRV_noinc((SV*)$var);" : \"sv_setrv_noinc($arg, (SV*)$var);" }
T_AVREF
$arg = newRV((SV*)$var);
T_AVREF_REFCOUNT_FIXED
${ "$var" eq "RETVAL" ? \"$arg = newRV_noinc((SV*)$var);" : \"sv_setrv_noinc($arg, (SV*)$var);" }
T_HVREF
$arg = newRV((SV*)$var);
T_HVREF_REFCOUNT_FIXED
${ "$var" eq "RETVAL" ? \"$arg = newRV_noinc((SV*)$var);" : \"sv_setrv_noinc($arg, (SV*)$var);" }
T_CVREF
$arg = newRV((SV*)$var);
T_CVREF_REFCOUNT_FIXED
${ "$var" eq "RETVAL" ? \"$arg = newRV_noinc((SV*)$var);" : \"sv_setrv_noinc($arg, (SV*)$var);" }
T_IV
sv_setiv($arg, (IV)$var);
T_UV
sv_setuv($arg, (UV)$var);
T_INT
sv_setiv($arg, (IV)$var);
T_SYSRET
if ($var != -1) {
if ($var == 0)
sv_setpvn($arg, "0 but true", 10);
else
sv_setiv($arg, (IV)$var);
}
T_ENUM
sv_setiv($arg, (IV)$var);
T_BOOL
${"$var" eq "RETVAL" ? \"$arg = boolSV($var);" : \"sv_setsv($arg, boolSV($var));"}
T_U_INT
sv_setuv($arg, (UV)$var);
T_SHORT
sv_setiv($arg, (IV)$var);
T_U_SHORT
sv_setuv($arg, (UV)$var);
T_LONG
sv_setiv($arg, (IV)$var);
T_U_LONG
sv_setuv($arg, (UV)$var);
T_CHAR
sv_setpvn($arg, (char *)&$var, 1);
T_U_CHAR
sv_setuv($arg, (UV)$var);
T_FLOAT
sv_setnv($arg, (double)$var);
T_NV
sv_setnv($arg, (NV)$var);
T_DOUBLE
sv_setnv($arg, (double)$var);
T_PV
sv_setpv((SV*)$arg, $var);
T_PTR
sv_setiv($arg, PTR2IV($var));
T_PTRREF
sv_setref_pv($arg, Nullch, (void*)$var);
T_REF_IV_REF
sv_setref_pv($arg, \"${ntype}\", (void*)new $ntype($var));
T_REF_IV_PTR
sv_setref_pv($arg, \"${ntype}\", (void*)$var);
T_PTROBJ
sv_setref_pv($arg, \"${ntype}\", (void*)$var);
T_PTRDESC
sv_setref_pv($arg, \"${ntype}\", (void*)new\U${type}_DESC\E($var));
T_REFREF
NOT_IMPLEMENTED
T_REFOBJ
NOT IMPLEMENTED
T_OPAQUE
sv_setpvn($arg, (char *)&$var, sizeof($var));
T_OPAQUEPTR
sv_setpvn($arg, (char *)$var, sizeof(*$var));
T_PACKED
XS_pack_$ntype($arg, $var);
T_PACKEDARRAY
XS_pack_$ntype($arg, $var, count_$ntype);
T_ARRAY
{
U32 ix_$var;
SSize_t extend_size =
/* The weird way this is written is because g++ is dumb
* enough to warn "comparison is always false" on something
* like:
*
* sizeof(a) > sizeof(b) && a > B_t_MAX
*
* (where the LH condition is false)
*/
(size_$var > (sizeof(size_$var) > sizeof(SSize_t)
? SSize_t_MAX : size_$var))
? -1 : (SSize_t)size_$var;
EXTEND(SP, extend_size);
for (ix_$var = 0; ix_$var < size_$var; ix_$var++) {
ST(ix_$var) = sv_newmortal();
DO_ARRAY_ELEM
}
}
T_STDIO
{
GV *gv = (GV *)sv_newmortal();
PerlIO *fp = PerlIO_importFILE($var,0);
gv_init_pvn(gv, gv_stashpvs("$Package",1),"__ANONIO__",10,0);
if ( fp && do_open(gv, "+<&", 3, FALSE, 0, 0, fp) ) {
SV *rv = newRV_inc((SV*)gv);
rv = sv_bless(rv, GvSTASH(gv));
${"$var" eq "RETVAL" ? \"$arg = sv_2mortal(rv);"
: \"sv_setsv($arg, rv);\n\t\tSvREFCNT_dec_NN(rv);"}
}${"$var" ne "RETVAL" ? \"
else
sv_setsv($arg, &PL_sv_undef);\n" : \""}
}
T_IN
{
GV *gv = (GV *)sv_newmortal();
gv_init_pvn(gv, gv_stashpvs("$Package",1),"__ANONIO__",10,0);
if ( do_open(gv, "<&", 2, FALSE, 0, 0, $var) ) {
SV *rv = newRV_inc((SV*)gv);
rv = sv_bless(rv, GvSTASH(gv));
${"$var" eq "RETVAL" ? \"$arg = sv_2mortal(rv);"
: \"sv_setsv($arg, rv);\n\t\tSvREFCNT_dec_NN(rv);"}
}${"$var" ne "RETVAL" ? \"
else
sv_setsv($arg, &PL_sv_undef);\n" : \""}
}
T_INOUT
{
GV *gv = (GV *)sv_newmortal();
gv_init_pvn(gv, gv_stashpvs("$Package",1),"__ANONIO__",10,0);
if ( do_open(gv, "+<&", 3, FALSE, 0, 0, $var) ) {
SV *rv = newRV_inc((SV*)gv);
rv = sv_bless(rv, GvSTASH(gv));
${"$var" eq "RETVAL" ? \"$arg = sv_2mortal(rv);"
: \"sv_setsv($arg, rv);\n\t\tSvREFCNT_dec_NN(rv);"}
}${"$var" ne "RETVAL" ? \"
else
sv_setsv($arg, &PL_sv_undef);\n" : \""}
}
T_OUT
{
GV *gv = (GV *)sv_newmortal();
gv_init_pvn(gv, gv_stashpvs("$Package",1),"__ANONIO__",10,0);
if ( do_open(gv, "+>&", 3, FALSE, 0, 0, $var) ) {
SV *rv = newRV_inc((SV*)gv);
rv = sv_bless(rv, GvSTASH(gv));
${"$var" eq "RETVAL" ? \"$arg = sv_2mortal(rv);"
: \"sv_setsv($arg, rv);\n\t\tSvREFCNT_dec_NN(rv);"}
}${"$var" ne "RETVAL" ? \"
else
sv_setsv($arg, &PL_sv_undef);\n" : \""}
}

View file

@ -0,0 +1,185 @@
#!perl
use 5.006;
BEGIN { pop @INC if $INC[-1] eq '.' }
use strict;
eval {
require ExtUtils::ParseXS;
1;
}
or do {
my $err = $@ || 'Zombie error';
my $v = $ExtUtils::ParseXS::VERSION;
$v = '<undef>' if not defined $v;
die "Failed to load or import from ExtUtils::ParseXS (version $v). Please check that ExtUtils::ParseXS is installed correctly and that the newest version will be found in your \@INC path: $err";
};
use Getopt::Long;
my %args = ();
my $usage = "Usage: xsubpp [-v] [-csuffix csuffix] [-except] [-prototypes] [-noversioncheck] [-nolinenumbers] [-nooptimize] [-noinout] [-noargtypes] [-strip|s pattern] [-typemap typemap]... file.xs\n";
Getopt::Long::Configure qw(no_auto_abbrev no_ignore_case);
@ARGV = grep {$_ ne '-C++'} @ARGV; # Allow -C++ for backward compatibility
GetOptions(\%args, qw(hiertype!
prototypes!
versioncheck!
linenumbers!
optimize!
inout!
argtypes!
object_capi!
except!
v
typemap=s@
output=s
s|strip=s
csuffix=s
))
or die $usage;
if ($args{v}) {
print "xsubpp version $ExtUtils::ParseXS::VERSION\n";
exit;
}
@ARGV == 1 or die $usage;
$args{filename} = shift @ARGV;
my $pxs = ExtUtils::ParseXS->new;
$pxs->process_file(%args);
exit( $pxs->report_error_count() ? 1 : 0 );
__END__
=head1 NAME
xsubpp - compiler to convert Perl XS code into C code
=head1 SYNOPSIS
B<xsubpp> [B<-v>] [B<-except>] [B<-s pattern>] [B<-prototypes>] [B<-noversioncheck>] [B<-nolinenumbers>] [B<-nooptimize>] [B<-typemap typemap>] [B<-output filename>]... file.xs
=head1 DESCRIPTION
This compiler is typically run by the makefiles created by L<ExtUtils::MakeMaker>
or by L<Module::Build> or other Perl module build tools.
I<xsubpp> will compile XS code into C code by embedding the constructs
necessary to let C functions manipulate Perl values and creates the glue
necessary to let Perl access those functions. The compiler uses typemaps to
determine how to map C function parameters and variables to Perl values.
The compiler will search for typemap files called I<typemap>. It will use
the following search path to find default typemaps, with the rightmost
typemap taking precedence.
../../../typemap:../../typemap:../typemap:typemap
It will also use a default typemap installed as C<ExtUtils::typemap>.
=head1 OPTIONS
Note that the C<XSOPT> MakeMaker option may be used to add these options to
any makefiles generated by MakeMaker.
=over 5
=item B<-hiertype>
Retains '::' in type names so that C++ hierarchical types can be mapped.
=item B<-except>
Adds exception handling stubs to the C code.
=item B<-typemap typemap>
Indicates that a user-supplied typemap should take precedence over the
default typemaps. This option may be used multiple times, with the last
typemap having the highest precedence.
=item B<-output filename>
Specifies the name of the output file to generate. If no file is
specified, output will be written to standard output.
=item B<-v>
Prints the I<xsubpp> version number to standard output, then exits.
=item B<-prototypes>
By default I<xsubpp> will not automatically generate prototype code for
all xsubs. This flag will enable prototypes.
=item B<-noversioncheck>
Disables the run time test that determines if the object file (derived
from the C<.xs> file) and the C<.pm> files have the same version
number.
=item B<-nolinenumbers>
Prevents the inclusion of '#line' directives in the output.
=item B<-nooptimize>
Disables certain optimizations. The only optimization that is currently
affected is the use of I<target>s by the output C code (see L<perlguts>).
This may significantly slow down the generated code, but this is the way
B<xsubpp> of 5.005 and earlier operated.
=item B<-noinout>
Disable recognition of C<IN>, C<OUT_LIST> and C<INOUT_LIST> declarations.
=item B<-noargtypes>
Disable recognition of ANSI-like descriptions of function signature.
=item B<-C++>
Currently doesn't do anything at all. This flag has been a no-op for
many versions of perl, at least as far back as perl5.003_07. It's
allowed here for backwards compatibility.
=item B<-s=...> or B<-strip=...>
I<This option is obscure and discouraged.>
If specified, the given string will be stripped off from the beginning
of the C function name in the generated XS functions (if it starts with that prefix).
This only applies to XSUBs without C<CODE> or C<PPCODE> blocks.
For example, the XS:
void foo_bar(int i);
when C<xsubpp> is invoked with C<-s foo_> will install a C<foo_bar>
function in Perl, but really call C<bar(i)> in C. Most of the time,
this is the opposite of what you want and failure modes are somewhat
obscure, so please avoid this option where possible.
=back
=head1 ENVIRONMENT
No environment variables are used.
=head1 AUTHOR
Originally by Larry Wall. Turned into the C<ExtUtils::ParseXS> module
by Ken Williams.
=head1 MODIFICATION HISTORY
See the file F<Changes>.
=head1 SEE ALSO
perl(1), perlxs(1), perlxstut(1), ExtUtils::ParseXS
=cut