diff --git a/git/usr/bin/core_perl/corelist b/git/usr/bin/core_perl/corelist new file mode 100644 index 0000000000000000000000000000000000000000..0765892b78896aa31a746fd62b170d3abc59c20b --- /dev/null +++ b/git/usr/bin/core_perl/corelist @@ -0,0 +1,577 @@ +#!/usr/bin/perl + eval 'exec /usr/bin/perl -S $0 ${1+"$@"}' + if 0; # ^ Run only under a shell +#!/usr/bin/perl + +=head1 NAME + +corelist - a commandline frontend to Module::CoreList + +=head1 DESCRIPTION + +See L for one. + +=head1 SYNOPSIS + + corelist -v + corelist [-a|-d] | // [] ... + corelist [-v ] [ | // ] ... + corelist [-r ] ... + corelist --utils [-d] [] ... + corelist --utils -v + corelist --feature [] ... + corelist --diff PerlVersion PerlVersion + corelist --upstream + +=head1 OPTIONS + +=over + +=item -a + +lists all versions of the given module (or the matching modules, in case you +used a module regexp) in the perls Module::CoreList knows about. + + corelist -a Unicode + + Unicode was first released with perl v5.6.2 + v5.6.2 3.0.1 + v5.8.0 3.2.0 + v5.8.1 4.0.0 + v5.8.2 4.0.0 + v5.8.3 4.0.0 + v5.8.4 4.0.1 + v5.8.5 4.0.1 + v5.8.6 4.0.1 + v5.8.7 4.1.0 + v5.8.8 4.1.0 + v5.8.9 5.1.0 + v5.9.0 4.0.0 + v5.9.1 4.0.0 + v5.9.2 4.0.1 + v5.9.3 4.1.0 + v5.9.4 4.1.0 + v5.9.5 5.0.0 + v5.10.0 5.0.0 + v5.10.1 5.1.0 + v5.11.0 5.1.0 + v5.11.1 5.1.0 + v5.11.2 5.1.0 + v5.11.3 5.2.0 + v5.11.4 5.2.0 + v5.11.5 5.2.0 + v5.12.0 5.2.0 + v5.12.1 5.2.0 + v5.12.2 5.2.0 + v5.12.3 5.2.0 + v5.12.4 5.2.0 + v5.13.0 5.2.0 + v5.13.1 5.2.0 + v5.13.2 5.2.0 + v5.13.3 5.2.0 + v5.13.4 5.2.0 + v5.13.5 5.2.0 + v5.13.6 5.2.0 + v5.13.7 6.0.0 + v5.13.8 6.0.0 + v5.13.9 6.0.0 + v5.13.10 6.0.0 + v5.13.11 6.0.0 + v5.14.0 6.0.0 + v5.14.1 6.0.0 + v5.15.0 6.0.0 + +=item -d + +finds the first perl version where a module has been released by +date, and not by version number (as is the default). + +=item --diff + +Given two versions of perl, this prints a human-readable table of all module +changes between the two. The output format may change in the future, and is +meant for I, not programs. For programs, use the L +API. + +=item -? or -help + +help! help! help! to see more help, try --man. + +=item -man + +all of the help + +=item -v + +lists all of the perl release versions we got the CoreList for. + +If you pass a version argument (value of C<$]>, like C<5.00503> or C<5.008008>), +you get a list of all the modules and their respective versions. +(If you have the C module, you can also use new-style version numbers, +like C<5.8.8>.) + +In module filtering context, it can be used as Perl version filter. + +=item -r + +lists all of the perl releases and when they were released + +If you pass a perl version you get the release date for that version only. + +=item --utils + +lists the first version of perl each named utility program was released with + +May be used with -d to modify the first release criteria. + +If used with -v then all utilities released with that version of perl +are listed, and any utility programs named on the command line are ignored. + +=item --feature, -f + +lists the first version bundle of each named feature given + +=item --upstream, -u + +Shows if the given module is primarily maintained in perl core or on CPAN +and bug tracker URL. + +=back + +As a special case, if you specify the module name C, you'll get +the version number of the Unicode Character Database bundled with the +requested perl versions. + +=cut + +BEGIN { pop @INC if $INC[-1] eq '.' } +use Module::CoreList; +use Getopt::Long qw(:config no_ignore_case); +use Pod::Usage; +use strict; +use warnings; +use List::Util qw/maxstr/; + +my %Opts; + +GetOptions( + \%Opts, + qw[ help|?! man! r|release:s v|version:s a! d diff|D utils feature|f u|upstream ] +); + +pod2usage(1) if $Opts{help}; +pod2usage(-verbose=>2) if $Opts{man}; + +if(exists $Opts{r} ){ + if ( !$Opts{r} ) { + print "\nModule::CoreList has release info for the following perl versions:\n"; + my $versions = { }; + my $max_ver_len = max_mod_len(\%Module::CoreList::released); + for my $ver ( grep !/0[01]0$/, sort keys %Module::CoreList::released ) { + printf "%-${max_ver_len}s %s\n", format_perl_version($ver), $Module::CoreList::released{$ver}; + } + print "\n"; + exit 0; + } + + my $num_r = numify_version( $Opts{r} ); + my $version_hash = Module::CoreList->find_version($num_r); + + if( !$version_hash ) { + print "\nModule::CoreList has no info on perl $Opts{r}\n\n"; + exit 1; + } + + printf "Perl %s was released on %s\n\n", format_perl_version($num_r), $Module::CoreList::released{$num_r}; + exit 0; +} + +if(exists $Opts{v} ){ + if( !$Opts{v} ) { + print "\nModule::CoreList has info on the following perl versions:\n"; + print format_perl_version($_)."\n" for grep !/0[01]0$/, sort keys %Module::CoreList::version; + print "\n"; + exit 0; + } + + my $num_v = numify_version( $Opts{v} ); + + if ($Opts{utils}) { + utilities_in_version($num_v); + exit 0; + } + + my $version_hash = Module::CoreList->find_version($num_v); + + if( !$version_hash ) { + print "\nModule::CoreList has no info on perl $Opts{v}\n\n"; + exit 1; + } + + if ( !@ARGV ) { + print "\nThe following modules were in perl $Opts{v} CORE\n"; + my $max_mod_len = max_mod_len($version_hash); + for my $mod ( sort keys %$version_hash ) { + printf "%-${max_mod_len}s %s\n", $mod, $version_hash->{$mod} || ""; + } + print "\n"; + exit 0; + } +} + +if ($Opts{diff}) { + if(@ARGV != 2) { + die "\nprovide exactly two perl core versions to diff with --diff\n"; + } + + my ($old_ver, $new_ver) = @ARGV; + + my $old = numify_version($old_ver); + if ( !Module::CoreList->find_version($old) ) { + print "\nModule::CoreList has no info on perl $old_ver\n\n"; + exit 1; + } + my $new = numify_version($new_ver); + if ( !Module::CoreList->find_version($new) ) { + print "\nModule::CoreList has no info on perl $new_ver\n\n"; + exit 1; + } + + my %diff = Module::CoreList::changes_between($old, $new); + + for my $lib (sort keys %diff) { + my $diff = $diff{$lib}; + + my $was = ! exists $diff->{left} ? '(absent)' + : ! defined $diff->{left} ? '(undef)' + : $diff->{left}; + + my $now = ! exists $diff->{right} ? '(absent)' + : ! defined $diff->{right} ? '(undef)' + : $diff->{right}; + + printf "%-35s %10s %10s\n", $lib, $was, $now; + } + exit(0); +} + +if ($Opts{utils}) { + die "\n--utils only available with perl v5.19.1 or greater\n" + if $] < 5.019001; + + die "\nprovide at least one utility name to --utils\n" + unless @ARGV; + + warn "\n-a has no effect when --utils is used\n" if $Opts{a}; + warn "\n--diff has no effect when --utils is used\n" if $Opts{diff}; + warn "\n--upstream, or -u, has no effect when --utils is used\n" if $Opts{u}; + + my $when = maxstr(values %Module::CoreList::released); + print "\n","Data for $when\n"; + + utility_version($_) for @ARGV; + + exit(0); +} + +if ($Opts{feature}) { + die "\n--feature is only available with perl v5.16.0 or greater\n" + if $] < 5.016; + + die "\nprovide at least one feature name to --feature\n" + unless @ARGV; + + no warnings 'once'; + require feature; + + my %feature2version; + my @bundles = map { $_->[0] } + sort { $b->[1] <=> $a->[1] } + map { [$_, numify_version($_)] } + grep { not /[^0-9.]/ } + keys %feature::feature_bundle; + + for my $version (@bundles) { + $feature2version{$_} = $version =~ /^\d\.\d+$/ ? "$version.0" : $version + for @{ $feature::feature_bundle{$version} }; + } + + # allow internal feature names, just in case someone gives us __SUB__ + # instead of current_sub. + while (my ($name, $internal) = each %feature::feature) { + $internal =~ s/^feature_//; + $feature2version{$internal} = $feature2version{$name} + if $feature2version{$name}; + } + + my $when = maxstr(values %Module::CoreList::released); + print "\n","Data for $when\n"; + + for my $feature (@ARGV) { + print "feature \"$feature\" ", + exists $feature2version{$feature} + ? "was first released with the perl " + . format_perl_version(numify_version($feature2version{$feature})) + . " feature bundle\n" + : "doesn't exist (or so I think)\n"; + } + exit(0); +} + +if ( !@ARGV ) { + pod2usage(0); +} + +while (@ARGV) { + my ($mod, $ver); + if ($ARGV[0] =~ /=/) { + ($mod, $ver) = split /=/, shift @ARGV; + } else { + $mod = shift @ARGV; + $ver = (@ARGV && $ARGV[0] =~ /^\d/) ? shift @ARGV : ""; + } + + if ($mod !~ m|^/(.*)/([imosx]*)$|) { # not a regex + module_version($mod,$ver); + } else { + my $re; + eval { $re = $2 ? qr/(?$2)($1)/ : qr/$1/; }; # trap exceptions while building regex + if ($@) { + # regex errors are usually like 'Quantifier follow nothing in regex; marked by ...' + # then we drop text after ';' to shorten message + my $errmsg = $@ =~ /(.*);/ ? $1 : $@; + warn "\n$mod is a bad regex: $errmsg\n"; + next; + } + my @mod = Module::CoreList->find_modules($re); + if (@mod) { + module_version($_, $ver) for @mod; + } else { + $ver |= ''; + print "\n$mod $ver has no match in CORE (or so I think)\n"; + } + + } +} + +exit(); + +sub module_version { + my($mod,$ver) = @_; + + if ( $Opts{v} ) { + my $numeric_v = numify_version($Opts{v}); + my $version_hash = Module::CoreList->find_version($numeric_v); + if ($version_hash) { + print $mod, " ", $version_hash->{$mod} || 'undef', "\n"; + return; + } + else { die "Shouldn't happen" } + } + + my $ret = $Opts{d} + ? Module::CoreList->first_release_by_date(@_) + : Module::CoreList->first_release(@_); + my $msg = $mod; + $msg .= " $ver" if $ver; + + my $rem = $Opts{d} + ? Module::CoreList->removed_from_by_date($mod) + : Module::CoreList->removed_from($mod); + + my $when = maxstr(values %Module::CoreList::released); + print "\n","Data for $when\n"; + + if( defined $ret ) { + my $deprecated = Module::CoreList->deprecated_in($mod); + $msg .= " was "; + $msg .= "first " unless $ver; + $msg .= "released with perl " . format_perl_version($ret); + $msg .= ( $rem ? ',' : ' and' ) . " deprecated (will be CPAN-only) in " . format_perl_version($deprecated) if $deprecated; + $msg .= " and removed from " . format_perl_version($rem) if $rem; + } else { + $msg .= " was not in CORE (or so I think)"; + } + + print $msg,"\n"; + + if( defined $ret and exists $Opts{u} ) { + my $upstream = $Module::CoreList::upstream{$mod}; + $upstream = 'undef' unless $upstream; + print "upstream: $upstream\n"; + if ( $upstream ne 'blead' ) { + my $bugtracker = $Module::CoreList::bug_tracker{$mod}; + $bugtracker = 'unknown' unless $bugtracker; + print "bug tracker: $bugtracker\n"; + } + } + + if(defined $ret and exists $Opts{a} and $Opts{a}){ + display_a($mod); + } +} + +sub utility_version { + my ($utility) = @_; + + require Module::CoreList::Utils; + + my $released = $Opts{d} + ? Module::CoreList::Utils->first_release_by_date($utility) + : Module::CoreList::Utils->first_release($utility); + + my $removed = $Opts{d} + ? Module::CoreList::Utils->removed_from_by_date($utility) + : Module::CoreList::Utils->removed_from($utility); + + if ($released) { + print "$utility was first released with perl ", format_perl_version($released); + print " and later removed in ", format_perl_version($removed) + if $removed; + print "\n"; + } else { + print "$utility was not in CORE (or so I think)\n"; + } +} + +sub utilities_in_version { + my ($version) = @_; + + require Module::CoreList::Utils; + + my @utilities = Module::CoreList::Utils->utilities($version); + + if (not @utilities) { + print "\nModule::CoreList::Utils has no info on perl $version\n\n"; + exit 1; + } + + print "\nThe following utilities were in perl ", + format_perl_version($version), " CORE\n"; + print "$_\n" for sort { lc($a) cmp lc($b) } @utilities; + print "\n"; +} + + +sub max_mod_len { + my $versions = shift; + my $max = 0; + for my $mod (keys %$versions) { + $max = max($max, length $mod); + } + + return $max; +} + +sub max { + my($this, $that) = @_; + return $this if $this > $that; + return $that; +} + +sub display_a { + my $mod = shift; + + for my $v (grep !/0[01]0$/, sort keys %Module::CoreList::version ) { + next unless exists $Module::CoreList::version{$v}{$mod}; + + my $mod_v = $Module::CoreList::version{$v}{$mod} || 'undef'; + printf " %-10s %-10s\n", format_perl_version($v), $mod_v; + } + print "\n"; +} + + +{ + my $have_version_pm; + sub have_version_pm { + return $have_version_pm if defined $have_version_pm; + return $have_version_pm = eval { require version; 1 }; + } +} + + +sub format_perl_version { + my $v = shift; + return $v if $v < 5.006 or !have_version_pm; + return version->new($v)->normal; +} + + +sub numify_version { + my $ver = shift; + if ($ver =~ /\..+\./) { + have_version_pm() + or die "You need to install version.pm to use dotted version numbers\n"; + $ver = version->new($ver)->numify; + } + $ver += 0; + return $ver; +} + +=head1 EXAMPLES + + $ corelist File::Spec + + File::Spec was first released with perl 5.005 + + $ corelist File::Spec 0.83 + + File::Spec 0.83 was released with perl 5.007003 + + $ corelist File::Spec 0.89 + + File::Spec 0.89 was not in CORE (or so I think) + + $ corelist File::Spec::Aliens + + File::Spec::Aliens was not in CORE (or so I think) + + $ corelist /IPC::Open/ + + IPC::Open2 was first released with perl 5 + + IPC::Open3 was first released with perl 5 + + $ corelist /MANIFEST/i + + ExtUtils::Manifest was first released with perl 5.001 + + $ corelist /Template/ + + /Template/ has no match in CORE (or so I think) + + $ corelist -v 5.8.8 B + + B 1.09_01 + + $ corelist -v 5.8.8 /^B::/ + + B::Asmdata 1.01 + B::Assembler 0.07 + B::Bblock 1.02_01 + B::Bytecode 1.01_01 + B::C 1.04_01 + B::CC 1.00_01 + B::Concise 0.66 + B::Debug 1.02_01 + B::Deparse 0.71 + B::Disassembler 1.05 + B::Lint 1.03 + B::O 1.00 + B::Showlex 1.02 + B::Stackobj 1.00 + B::Stash 1.00 + B::Terse 1.03_01 + B::Xref 1.01 + +=head1 COPYRIGHT + +Copyright (c) 2002-2007 by D.H. aka PodMaster + +Currently maintained by the perl 5 porters Eperl5-porters@perl.orgE. + +This program is distributed under the same terms as perl itself. +See http://perl.org/ or http://cpan.org/ for more info on that. + +=cut diff --git a/git/usr/bin/core_perl/cpan b/git/usr/bin/core_perl/cpan new file mode 100644 index 0000000000000000000000000000000000000000..5e54f7f07eb1c2a42b7fdef541b3ee1a5792dfee --- /dev/null +++ b/git/usr/bin/core_perl/cpan @@ -0,0 +1,352 @@ +#!/usr/bin/perl + eval 'exec /usr/bin/perl -S $0 ${1+"$@"}' + if 0; # ^ Run only under a shell +#!/usr/local/bin/perl + +BEGIN { pop @INC if $INC[-1] eq '.' } +use strict; +use vars qw($VERSION); + +use App::Cpan; +use CPAN::Version; +my $minver = '1.64'; +if ( CPAN::Version->vlt($App::Cpan::VERSION, $minver) ) { + warn "WARNING: your version of App::Cpan is $App::Cpan::VERSION while we would expect at least $minver"; +} +$VERSION = '1.64'; + +my $rc = App::Cpan->run( @ARGV ); + +# will this work under Strawberry Perl? +exit( $rc || 0 ); + +=head1 NAME + +cpan - easily interact with CPAN from the command line + +=head1 SYNOPSIS + + # with arguments and no switches, installs specified modules + cpan module_name [ module_name ... ] + + # with switches, installs modules with extra behavior + cpan [-cfFimtTw] module_name [ module_name ... ] + + # use local::lib + cpan -I module_name [ module_name ... ] + + # one time mirror override for faster mirrors + cpan -p ... + + # with just the dot, install from the distribution in the + # current directory + cpan . + + # without arguments, starts CPAN.pm shell + cpan + + # without arguments, but some switches + cpan [-ahpruvACDLOPX] + +=head1 DESCRIPTION + +This script provides a command interface (not a shell) to CPAN. At the +moment it uses CPAN.pm to do the work, but it is not a one-shot command +runner for CPAN.pm. + +=head2 Options + +=over 4 + +=item -a + +Creates a CPAN.pm autobundle with CPAN::Shell->autobundle. + +=item -A module [ module ... ] + +Shows the primary maintainers for the specified modules. + +=item -c module + +Runs a `make clean` in the specified module's directories. + +=item -C module [ module ... ] + +Show the F files for the specified modules + +=item -D module [ module ... ] + +Show the module details. This prints one line for each out-of-date module +(meaning, modules locally installed but have newer versions on CPAN). +Each line has three columns: module name, local version, and CPAN +version. + +=item -f + +Force the specified action, when it normally would have failed. Use this +to install a module even if its tests fail. When you use this option, +-i is not optional for installing a module when you need to force it: + + % cpan -f -i Module::Foo + +=item -F + +Turn off CPAN.pm's attempts to lock anything. You should be careful with +this since you might end up with multiple scripts trying to muck in the +same directory. This isn't so much of a concern if you're loading a special +config with C<-j>, and that config sets up its own work directories. + +=item -g module [ module ... ] + +Downloads to the current directory the latest distribution of the module. + +=item -G module [ module ... ] + +UNIMPLEMENTED + +Download to the current directory the latest distribution of the +modules, unpack each distribution, and create a git repository for each +distribution. + +If you want this feature, check out Yanick Champoux's C +distribution. + +=item -h + +Print a help message and exit. When you specify C<-h>, it ignores all +of the other options and arguments. + +=item -i module [ module ... ] + +Install the specified modules. With no other switches, this switch +is implied. + +=item -I + +Load C (think like C<-I> for loading lib paths). Too bad +C<-l> was already taken. + +=item -j Config.pm + +Load the file that has the CPAN configuration data. This should have the +same format as the standard F file, which defines +C<$CPAN::Config> as an anonymous hash. + +=item -J + +Dump the configuration in the same format that CPAN.pm uses. This is useful +for checking the configuration as well as using the dump as a starting point +for a new, custom configuration. + +=item -l + +List all installed modules with their versions + +=item -L author [ author ... ] + +List the modules by the specified authors. + +=item -m + +Make the specified modules. + +=item -M mirror1,mirror2,... + +A comma-separated list of mirrors to use for just this run. The C<-P> +option can find them for you automatically. + +=item -n + +Do a dry run, but don't actually install anything. (unimplemented) + +=item -O + +Show the out-of-date modules. + +=item -p + +Ping the configured mirrors and print a report + +=item -P + +Find the best mirrors you could be using and use them for the current +session. + +=item -r + +Recompiles dynamically loaded modules with CPAN::Shell->recompile. + +=item -s + +Drop in the CPAN.pm shell. This command does this automatically if you don't +specify any arguments. + +=item -t module [ module ... ] + +Run a `make test` on the specified modules. + +=item -T + +Do not test modules. Simply install them. + +=item -u + +Upgrade all installed modules. Blindly doing this can really break things, +so keep a backup. + +=item -v + +Print the script version and CPAN.pm version then exit. + +=item -V + +Print detailed information about the cpan client. + +=item -w + +UNIMPLEMENTED + +Turn on cpan warnings. This checks various things, like directory permissions, +and tells you about problems you might have. + +=item -x module [ module ... ] + +Find close matches to the named modules that you think you might have +mistyped. This requires the optional installation of Text::Levenshtein or +Text::Levenshtein::Damerau. + +=item -X + +Dump all the namespaces to standard output. + +=back + +=head2 Examples + + # print a help message + cpan -h + + # print the version numbers + cpan -v + + # create an autobundle + cpan -a + + # recompile modules + cpan -r + + # upgrade all installed modules + cpan -u + + # install modules ( sole -i is optional ) + cpan -i Netscape::Booksmarks Business::ISBN + + # force install modules ( must use -i ) + cpan -fi CGI::Minimal URI + + # install modules but without testing them + cpan -Ti CGI::Minimal URI + +=head2 Environment variables + +There are several components in CPAN.pm that use environment variables. +The build tools, L and L use some, +while others matter to the levels above them. Some of these are specified +by the Perl Toolchain Gang: + +Lancaster Consensus: L + +Oslo Consensus: L + +=over 4 + +=item NONINTERACTIVE_TESTING + +Assume no one is paying attention and skips prompts for distributions +that do that correctly. C sets this to C<1> unless it already +has a value (even if that value is false). + +=item PERL_MM_USE_DEFAULT + +Use the default answer for a prompted questions. C sets this +to C<1> unless it already has a value (even if that value is false). + +=item CPAN_OPTS + +As with C, a string of additional C options to +add to those you specify on the command line. + +=item CPANSCRIPT_LOGLEVEL + +The log level to use, with either the embedded, minimal logger or +L if it is installed. Possible values are the same as +the C levels: C, C, C, C, +C, and C. The default is C. + +=item GIT_COMMAND + +The path to the C binary to use for the Git features. The default +is C. + +=back + +=head1 EXIT VALUES + +The script exits with zero if it thinks that everything worked, or a +positive number if it thinks that something failed. Note, however, that +in some cases it has to divine a failure by the output of things it does +not control. For now, the exit codes are vague: + + 1 An unknown error + + 2 The was an external problem + + 4 There was an internal problem with the script + + 8 A module failed to install + +=head1 TO DO + +* one shot configuration values from the command line + +=head1 BUGS + +* none noted + +=head1 SEE ALSO + +Most behaviour, including environment variables and configuration, +comes directly from CPAN.pm. + +=head1 SOURCE AVAILABILITY + +This code is in Github in the CPAN.pm repository: + + https://github.com/andk/cpanpm + +The source used to be tracked separately in another GitHub repo, +but the canonical source is now in the above repo. + +=head1 CREDITS + +Japheth Cleaver added the bits to allow a forced install (-f). + +Jim Brandt suggest and provided the initial implementation for the +up-to-date and Changes features. + +Adam Kennedy pointed out that exit() causes problems on Windows +where this script ends up with a .bat extension + +=head1 AUTHOR + +brian d foy, C<< >> + +=head1 COPYRIGHT + +Copyright (c) 2001-2015, brian d foy, All Rights Reserved. + +You may redistribute this under the same terms as Perl itself. + +=cut + +1; diff --git a/git/usr/bin/core_perl/enc2xs b/git/usr/bin/core_perl/enc2xs new file mode 100644 index 0000000000000000000000000000000000000000..c185b02669aa5923ed679d825cd7c41979887506 --- /dev/null +++ b/git/usr/bin/core_perl/enc2xs @@ -0,0 +1,1484 @@ +#!/usr/bin/perl + eval 'exec /usr/bin/perl -S $0 ${1+"$@"}' + if 0; # ^ Run only under a shell +#!./perl +BEGIN { + # @INC poking no longer needed w/ new MakeMaker and Makefile.PL's + # with $ENV{PERL_CORE} set + # In case we need it in future... + require Config; Config->import(); + pop @INC if $INC[-1] eq '.'; +} +use strict; +use warnings; +use Getopt::Std; +use Config; +my @orig_ARGV = @ARGV; +our $VERSION = do { my @r = (q$Revision: 2.25 $ =~ /\d+/g); sprintf "%d."."%02d" x $#r, @r }; + +# These may get re-ordered. +# RAW is a do_now as inserted by &enter +# AGG is an aggregated do_now, as built up by &process + +use constant { + RAW_NEXT => 0, + RAW_IN_LEN => 1, + RAW_OUT_BYTES => 2, + RAW_FALLBACK => 3, + + AGG_MIN_IN => 0, + AGG_MAX_IN => 1, + AGG_OUT_BYTES => 2, + AGG_NEXT => 3, + AGG_IN_LEN => 4, + AGG_OUT_LEN => 5, + AGG_FALLBACK => 6, +}; + +# (See the algorithm in encengine.c - we're building structures for it) + +# There are two sorts of structures. +# "do_now" (an array, two variants of what needs storing) is whatever we need +# to do now we've read an input byte. +# It's housed in a "do_next" (which is how we got to it), and in turn points +# to a "do_next" which contains all the "do_now"s for the next input byte. + +# There will be a "do_next" which is the start state. +# For a single byte encoding it's the only "do_next" - each "do_now" points +# back to it, and each "do_now" will cause bytes. There is no state. + +# For a multi-byte encoding where all characters in the input are the same +# length, then there will be a tree of "do_now"->"do_next"->"do_now" +# branching out from the start state, one step for each input byte. +# The leaf "do_now"s will all be at the same distance from the start state, +# only the leaf "do_now"s cause output bytes, and they in turn point back to +# the start state. + +# For an encoding where there are variable length input byte sequences, you +# will encounter a leaf "do_now" sooner for the shorter input sequences, but +# as before the leaves will point back to the start state. + +# The system will cope with escape encodings (imagine them as a mostly +# self-contained tree for each escape state, and cross links between trees +# at the state-switching characters) but so far no input format defines these. + +# The system will also cope with having output "leaves" in the middle of +# the bifurcating branches, not just at the extremities, but again no +# input format does this yet. + +# There are two variants of the "do_now" structure. The first, smaller variant +# is generated by &enter as the input file is read. There is one structure +# for each input byte. Say we are mapping a single byte encoding to a +# single byte encoding, with "ABCD" going "abcd". There will be +# 4 "do_now"s, {"A" => [...,"a",...], "B" => [...,"b",...], "C"=>..., "D"=>...} + +# &process then walks the tree, building aggregate "do_now" structures for +# adjacent bytes where possible. The aggregate is for a contiguous range of +# bytes which each produce the same length of output, each move to the +# same next state, and each have the same fallback flag. +# So our 4 RAW "do_now"s above become replaced by a single structure +# containing: +# ["A", "D", "abcd", 1, ...] +# ie, for an input byte $_ in "A".."D", output 1 byte, found as +# substr ("abcd", (ord $_ - ord "A") * 1, 1) +# which maps very nicely into pointer arithmetic in C for encengine.c + +sub encode_U +{ + # UTF-8 encode long hand - only covers part of perl's range + ## my $uv = shift; + # chr() works in native space so convert value from table + # into that space before using chr(). + my $ch = chr(utf8::unicode_to_native($_[0])); + # Now get core perl to encode that the way it likes. + utf8::encode($ch); + return $ch; +} + +sub encode_S +{ + # encode single byte + ## my ($ch,$page) = @_; return chr($ch); + return chr $_[0]; +} + +sub encode_D +{ + # encode double byte MS byte first + ## my ($ch,$page) = @_; return chr($page).chr($ch); + return chr ($_[1]) . chr $_[0]; +} + +sub encode_M +{ + # encode Multi-byte - single for 0..255 otherwise double + ## my ($ch,$page) = @_; + ## return &encode_D if $page; + ## return &encode_S; + return chr ($_[1]) . chr $_[0] if $_[1]; + return chr $_[0]; +} + +my %encode_types = (U => \&encode_U, + S => \&encode_S, + D => \&encode_D, + M => \&encode_M, + ); + +# Win32 does not expand globs on command line +if ($^O eq 'MSWin32' and !$ENV{PERL_CORE}) { + eval "\@ARGV = map(glob(\$_),\@ARGV)"; + @ARGV = @orig_ARGV unless @ARGV; +} + +my %opt; +# I think these are: +# -Q to disable the duplicate codepoint test +# -S make mapping errors fatal +# -q to remove comments written to output files +# -O to enable the (brute force) substring optimiser +# -o to specify the output file name (else it's the first arg) +# -f to give a file with a list of input files (else use the args) +# -n to name the encoding (else use the basename of the input file. +#Getopt::Long::Configure("bundling"); +#GetOptions(\%opt, qw(C M=s S Q q O o=s f=s n=s v)); +getopts('CM:SQqOo:f:n:v',\%opt); + +$opt{M} and make_makefile_pl($opt{M}, @ARGV); +$opt{C} and make_configlocal_pm($opt{C}, @ARGV); +$opt{v} ||= $ENV{ENC2XS_VERBOSE}; +$opt{q} ||= $ENV{ENC2XS_NO_COMMENTS}; + +sub verbose { + print STDERR @_ if $opt{v}; +} +sub verbosef { + printf STDERR @_ if $opt{v}; +} + + +# ($cpp, $static, $sized) = compiler_info($declaration) +# +# return some information about the compiler and compile options we're using: +# +# $declaration - true if we're doing a declaration rather than a definition. +# +# $cpp - we're using C++ +# $static - ok to declare the arrays as static +# $sized - the array declarations should be sized + +sub compiler_info { + my ($declaration) = @_; + + my $ccflags = $Config{ccflags}; + if (defined $Config{ccwarnflags}) { + $ccflags .= " " . $Config{ccwarnflags}; + } + my $compat = $ccflags =~ /\Q-Wc++-compat/; + my $pedantic = $ccflags =~ /-pedantic/; + + my $cpp = ($Config{d_cplusplus} || '') eq 'define'; + + # The encpage_t tables contain recursive and mutually recursive + # references. To allow them to compile under C++ and some restrictive + # cc options, it may be necessary to make the tables non-static/const + # (thus moving them from the text to the data segment) and/or not + # include the size in the declaration. + + my $static = !( + $cpp + || ($compat && $pedantic) + || ($^O eq 'MacOS' && $declaration) + ); + + # -Wc++-compat on its own warns if the array declaration is sized. + # The easiest way to avoid this warning is simply not to include + # the size in the declaration. + # With -pedantic as well, the issue doesn't arise because $static + # above becomes false. + my $sized = $declaration && !($compat && !$pedantic); + + return ($cpp, $static, $sized); +} + + +# This really should go first, else the die here causes empty (non-erroneous) +# output files to be written. +my @encfiles; +if (exists $opt{f}) { + # -F is followed by name of file containing list of filenames + my $flist = $opt{f}; + open(FLIST,$flist) || die "Cannot open $flist:$!"; + chomp(@encfiles = ); + close(FLIST); +} else { + @encfiles = @ARGV; +} + +my $cname = $opt{o} ? $opt{o} : shift(@ARGV); +unless ($cname) { # Debugging a Win32 nmake error-only; works via cmdline. + print "\nARGV:"; + print "$_ " for @ARGV; + print "\nopt:"; + print " $_ => ",defined $opt{$_}?$opt{$_}:"undef","\n" for keys %opt; +} +chmod(0666,$cname) if -f $cname && !-w $cname; +open(C,">", $cname) || die "Cannot open $cname:$!"; + +my $dname = $cname; +my $hname = $cname; + +my ($doC,$doEnc,$doUcm,$doPet); + +if ($cname =~ /\.(c|xs)$/i) # VMS may have upcased filenames with DECC$ARGV_PARSE_STYLE defined + { + $doC = 1; + $dname =~ s/(\.[^\.]*)?$/.exh/; + chmod(0666,$dname) if -f $cname && !-w $dname; + open(D,">", $dname) || die "Cannot open $dname:$!"; + $hname =~ s/(\.[^\.]*)?$/.h/; + chmod(0666,$hname) if -f $cname && !-w $hname; + open(H,">", $hname) || die "Cannot open $hname:$!"; + + foreach my $fh (\*C,\*D,\*H) + { + print $fh <<"END" unless $opt{'q'}; +/* + !!!!!!! DO NOT EDIT THIS FILE !!!!!!! + This file was autogenerated by: + $^X $0 @orig_ARGV + enc2xs VERSION $VERSION +*/ +END + } + + if ($cname =~ /\.c$/i && $Config{ccname} eq "gcc") + { + print C qq(#pragma GCC diagnostic ignored "-Wc++-compat"\n); + } + + if ($cname =~ /\.xs$/i) + { + print C "#define PERL_NO_GET_CONTEXT\n"; + print C "#include \n"; + print C "#include \n"; + print C "#include \n"; + } + print C "#include \"encode.h\"\n\n"; + + } +elsif ($cname =~ /\.enc$/i) + { + $doEnc = 1; + } +elsif ($cname =~ /\.ucm$/i) + { + $doUcm = 1; + } +elsif ($cname =~ /\.pet$/i) + { + $doPet = 1; + } + +my %encoding; +my %strings; +my $string_acc; +my %strings_in_acc; + +my $saved = 0; +my $subsave = 0; +my $strings = 0; + +sub cmp_name +{ + if ($a =~ /^.*-(\d+)/) + { + my $an = $1; + if ($b =~ /^.*-(\d+)/) + { + my $r = $an <=> $1; + return $r if $r; + } + } + return $a cmp $b; +} + + +foreach my $enc (sort cmp_name @encfiles) + { + my ($name,$sfx) = $enc =~ /^.*?([\w-]+)\.(enc|ucm)$/; + $name = $opt{'n'} if exists $opt{'n'}; + if (open(E,$enc)) + { + if ($sfx eq 'enc') + { + compile_enc(\*E,lc($name)); + } + else + { + compile_ucm(\*E,lc($name)); + } + } + else + { + warn "Cannot open $enc for $name:$!"; + } + } + +if ($doC) + { + verbose "Writing compiled form\n"; + foreach my $name (sort cmp_name keys %encoding) + { + my ($e2u,$u2e,$erep,$min_el,$max_el) = @{$encoding{$name}}; + process($name.'_utf8',$e2u); + addstrings(\*C,$e2u); + + process('utf8_'.$name,$u2e); + addstrings(\*C,$u2e); + } + outbigstring(\*C,"enctable"); + foreach my $name (sort cmp_name keys %encoding) + { + my ($e2u,$u2e,$erep,$min_el,$max_el) = @{$encoding{$name}}; + outtable(\*C,$e2u, "enctable"); + outtable(\*C,$u2e, "enctable"); + + # push(@{$encoding{$name}},outstring(\*C,$e2u->{Cname}.'_def',$erep)); + } + my ($cpp) = compiler_info(0); + my $ext = $cpp ? 'extern "C"' : "extern"; + my $exta = $cpp ? 'extern "C"' : "static"; + my $extb = $cpp ? 'extern "C"' : ""; + foreach my $enc (sort cmp_name keys %encoding) + { + # my ($e2u,$u2e,$rep,$min_el,$max_el,$rsym) = @{$encoding{$enc}}; + my ($e2u,$u2e,$rep,$min_el,$max_el) = @{$encoding{$enc}}; + #my @info = ($e2u->{Cname},$u2e->{Cname},$rsym,length($rep),$min_el,$max_el); + my $replen = 0; + $replen++ while($rep =~ /\G\\x[0-9A-Fa-f]/g); + my $sym = "${enc}_encoding"; + $sym =~ s/\W+/_/g; + my @info = ($e2u->{Cname},$u2e->{Cname},"${sym}_rep_character",$replen, + $min_el,$max_el); + print C "${exta} const U8 ${sym}_rep_character[] = \"$rep\";\n"; + print C "${exta} const char ${sym}_enc_name[] = \"$enc\";\n\n"; + print C "${extb} const encode_t $sym = \n"; + # This is to make null encoding work -- dankogai + for (my $i = (scalar @info) - 1; $i >= 0; --$i){ + $info[$i] ||= 1; + } + # end of null tweak -- dankogai + print C " {",join(',',@info,"{${sym}_enc_name,(const char *)0}"),"};\n\n"; + } + + foreach my $enc (sort cmp_name keys %encoding) + { + my $sym = "${enc}_encoding"; + $sym =~ s/\W+/_/g; + print H "${ext} encode_t $sym;\n"; + print D " Encode_XSEncoding(aTHX_ &$sym);\n"; + } + + if ($cname =~ /(\w+)\.xs$/) + { + my $mod = $1; + print C <<'END'; + +static void +Encode_XSEncoding(pTHX_ encode_t *enc) +{ + dSP; + HV *stash = gv_stashpv("Encode::XS", TRUE); + SV *iv = newSViv(PTR2IV(enc)); + SV *sv = sv_bless(newRV_noinc(iv),stash); + int i = 0; + /* with the SvLEN() == 0 hack, PVX won't be freed. We cast away name's + constness, in the hope that perl won't mess with it. */ + assert(SvTYPE(iv) >= SVt_PV); assert(SvLEN(iv) == 0); + SvFLAGS(iv) |= SVp_POK; + SvPVX(iv) = (char*) enc->name[0]; + PUSHMARK(sp); + XPUSHs(sv); + while (enc->name[i]) + { + const char *name = enc->name[i++]; + XPUSHs(sv_2mortal(newSVpvn(name,strlen(name)))); + } + PUTBACK; + call_pv("Encode::define_encoding",G_DISCARD); + SvREFCNT_dec(sv); +} + +END + + print C "\nMODULE = Encode::$mod\tPACKAGE = Encode::$mod\n\n"; + print C "BOOT:\n{\n"; + print C "#include \"$dname\"\n"; + print C "}\n"; + } + # Close in void context is bad, m'kay + close(D) or warn "Error closing '$dname': $!"; + close(H) or warn "Error closing '$hname': $!"; + + my $perc_saved = $saved/($strings + $saved) * 100; + my $perc_subsaved = $subsave/($strings + $subsave) * 100; + verbosef "%d bytes in string tables\n",$strings; + verbosef "%d bytes (%.3g%%) saved spotting duplicates\n", + $saved, $perc_saved if $saved; + verbosef "%d bytes (%.3g%%) saved using substrings\n", + $subsave, $perc_subsaved if $subsave; + } +elsif ($doEnc) + { + foreach my $name (sort cmp_name keys %encoding) + { + my ($e2u,$u2e,$erep,$min_el,$max_el) = @{$encoding{$name}}; + output_enc(\*C,$name,$e2u); + } + } +elsif ($doUcm) + { + foreach my $name (sort cmp_name keys %encoding) + { + my ($e2u,$u2e,$erep,$min_el,$max_el) = @{$encoding{$name}}; + output_ucm(\*C,$name,$u2e,$erep,$min_el,$max_el); + } + } + +# writing half meg files and then not checking to see if you just filled the +# disk is bad, m'kay +close(C) or die "Error closing '$cname': $!"; + +# End of the main program. + +sub compile_ucm +{ + my ($fh,$name) = @_; + my $e2u = {}; + my $u2e = {}; + my $cs; + my %attr; + while (<$fh>) + { + s/#.*$//; + last if /^\s*CHARMAP\s*$/i; + if (/^\s*<(\w+)>\s+"?([^"]*)"?\s*$/i) # " # Grrr + { + $attr{$1} = $2; + } + } + if (!defined($cs = $attr{'code_set_name'})) + { + warn "No in $name\n"; + } + else + { + $name = $cs unless exists $opt{'n'}; + } + my $erep; + my $urep; + my $max_el; + my $min_el; + if (exists $attr{'subchar'}) + { + #my @byte; + #$attr{'subchar'} =~ /^\s*/cg; + #push(@byte,$1) while $attr{'subchar'} =~ /\G\\x([0-9a-f]+)/icg; + #$erep = join('',map(chr(hex($_)),@byte)); + $erep = $attr{'subchar'}; + $erep =~ s/^\s+//; $erep =~ s/\s+$//; + } + print "Reading $name ($cs)\n" + unless defined $ENV{MAKEFLAGS} + and $ENV{MAKEFLAGS} =~ /\b(s|silent|quiet)\b/; + my $nfb = 0; + my $hfb = 0; + while (<$fh>) + { + s/#.*$//; + last if /^\s*END\s+CHARMAP\s*$/i; + next if /^\s*$/; + my (@uni, @byte) = (); + my ($uni, $byte, $fb) = m/^(\S+)\s+(\S+)\s+(\S+)\s+/o + or die "Bad line: $_"; + while ($uni =~ m/\G<([U0-9a-fA-F\+]+)>/g){ + push @uni, map { substr($_, 1) } split(/\+/, $1); + } + while ($byte =~ m/\G\\x([0-9a-fA-F]+)/g){ + push @byte, $1; + } + if (@uni) + { + my $uch = join('', map { encode_U(hex($_)) } @uni ); + my $ech = join('',map(chr(hex($_)),@byte)); + my $el = length($ech); + $max_el = $el if (!defined($max_el) || $el > $max_el); + $min_el = $el if (!defined($min_el) || $el < $min_el); + if (length($fb)) + { + $fb = substr($fb,1); + $hfb++; + } + else + { + $nfb++; + $fb = '0'; + } + # $fb is fallback flag + # 0 - round trip safe + # 1 - fallback for unicode -> enc + # 2 - skip sub-char mapping + # 3 - fallback enc -> unicode + enter($u2e,$uch,$ech,$u2e,$fb+0) if ($fb =~ /[01]/); + enter($e2u,$ech,$uch,$e2u,$fb+0) if ($fb =~ /[03]/); + } + else + { + warn $_; + } + } + if ($nfb && $hfb) + { + die "$nfb entries without fallback, $hfb entries with\n"; + } + $encoding{$name} = [$e2u,$u2e,$erep,$min_el,$max_el]; +} + + + +sub compile_enc +{ + my ($fh,$name) = @_; + my $e2u = {}; + my $u2e = {}; + + my $type; + while ($type = <$fh>) + { + last if $type !~ /^\s*#/; + } + chomp($type); + return if $type eq 'E'; + # Do the hash lookup once, rather than once per function call. 4% speedup. + my $type_func = $encode_types{$type}; + my ($def,$sym,$pages) = split(/\s+/,scalar(<$fh>)); + warn "$type encoded $name\n"; + my $rep = ''; + # Save a defined test by setting these to defined values. + my $min_el = ~0; # A very big integer + my $max_el = 0; # Anything must be longer than 0 + { + my $v = hex($def); + $rep = &$type_func($v & 0xFF, ($v >> 8) & 0xffe); + } + my $errors; + my $seen; + # use -Q to silence the seen test. Makefile.PL uses this by default. + $seen = {} unless $opt{Q}; + do + { + my $line = <$fh>; + chomp($line); + my $page = hex($line); + my $ch = 0; + my $i = 16; + do + { + # So why is it 1% faster to leave the my here? + my $line = <$fh>; + $line =~ s/\r\n$/\n/; + die "$.:${line}Line should be exactly 65 characters long including + newline (".length($line).")" unless length ($line) == 65; + # Split line into groups of 4 hex digits, convert groups to ints + # This takes 65.35 + # map {hex $_} $line =~ /(....)/g + # This takes 63.75 (2.5% less time) + # unpack "n*", pack "H*", $line + # There's an implicit loop in map. Loops are bad, m'kay. Ops are bad, m'kay + # Doing it as while ($line =~ /(....)/g) took 74.63 + foreach my $val (unpack "n*", pack "H*", $line) + { + next if $val == 0xFFFD; + my $ech = &$type_func($ch,$page); + if ($val || (!$ch && !$page)) + { + my $el = length($ech); + $max_el = $el if $el > $max_el; + $min_el = $el if $el < $min_el; + my $uch = encode_U($val); + if ($seen) { + # We're doing the test. + # We don't need to read this quickly, so storing it as a scalar, + # rather than 3 (anon array, plus the 2 scalars it holds) saves + # RAM and may make us faster on low RAM systems. [see __END__] + if (exists $seen->{$uch}) + { + warn sprintf("U%04X is %02X%02X and %04X\n", + $val,$page,$ch,$seen->{$uch}); + $errors++; + } + else + { + $seen->{$uch} = $page << 8 | $ch; + } + } + # Passing 2 extra args each time is 3.6% slower! + # Even with having to add $fallback ||= 0 later + enter_fb0($e2u,$ech,$uch); + enter_fb0($u2e,$uch,$ech); + } + else + { + # No character at this position + # enter($e2u,$ech,undef,$e2u); + } + $ch++; + } + } while --$i; + } while --$pages; + die "\$min_el=$min_el, \$max_el=$max_el - seems we read no lines" + if $min_el > $max_el; + die "$errors mapping conflicts\n" if ($errors && $opt{'S'}); + $encoding{$name} = [$e2u,$u2e,$rep,$min_el,$max_el]; +} + +# my ($a,$s,$d,$t,$fb) = @_; +sub enter { + my ($current,$inbytes,$outbytes,$next,$fallback) = @_; + # state we shift to after this (multibyte) input character defaults to same + # as current state. + $next ||= $current; + # Making sure it is defined seems to be faster than {no warnings;} in + # &process, or passing it in as 0 explicitly. + # XXX $fallback ||= 0; + + # Start at the beginning and work forwards through the string to zero. + # effectively we are removing 1 character from the front each time + # but we don't actually edit the string. [this alone seems to be 14% speedup] + # Hence -$pos is the length of the remaining string. + my $pos = -length $inbytes; + while (1) { + my $byte = substr $inbytes, $pos, 1; + # RAW_NEXT => 0, + # RAW_IN_LEN => 1, + # RAW_OUT_BYTES => 2, + # RAW_FALLBACK => 3, + # to unicode an array would seem to be better, because the pages are dense. + # from unicode can be very sparse, favouring a hash. + # hash using the bytes (all length 1) as keys rather than ord value, + # as it's easier to sort these in &process. + + # It's faster to always add $fallback even if it's undef, rather than + # choosing between 3 and 4 element array. (hence why we set it defined + # above) + my $do_now = $current->{Raw}{$byte} ||= [{},-$pos,'',$fallback]; + # When $pos was -1 we were at the last input character. + unless (++$pos) { + $do_now->[RAW_OUT_BYTES] = $outbytes; + $do_now->[RAW_NEXT] = $next; + return; + } + # Tail recursion. The intermediate state may not have a name yet. + $current = $do_now->[RAW_NEXT]; + } +} + +# This is purely for optimisation. It's just &enter hard coded for $fallback +# of 0, using only a 3 entry array ref to save memory for every entry. +sub enter_fb0 { + my ($current,$inbytes,$outbytes,$next) = @_; + $next ||= $current; + + my $pos = -length $inbytes; + while (1) { + my $byte = substr $inbytes, $pos, 1; + my $do_now = $current->{Raw}{$byte} ||= [{},-$pos,'']; + unless (++$pos) { + $do_now->[RAW_OUT_BYTES] = $outbytes; + $do_now->[RAW_NEXT] = $next; + return; + } + $current = $do_now->[RAW_NEXT]; + } +} + +sub process +{ + my ($name,$a) = @_; + $name =~ s/\W+/_/g; + $a->{Cname} = $name; + my $raw = $a->{Raw}; + my ($l, $agg_max_in, $agg_next, $agg_in_len, $agg_out_len, $agg_fallback); + my @ent; + $agg_max_in = 0; + foreach my $key (sort keys %$raw) { + # RAW_NEXT => 0, + # RAW_IN_LEN => 1, + # RAW_OUT_BYTES => 2, + # RAW_FALLBACK => 3, + my ($next, $in_len, $out_bytes, $fallback) = @{$raw->{$key}}; + # Now we are converting from raw to aggregate, switch from 1 byte strings + # to numbers + my $b = ord $key; + $fallback ||= 0; + if ($l && + # If this == fails, we're going to reset $agg_max_in below anyway. + $b == ++$agg_max_in && + # References in numeric context give the pointer as an int. + $agg_next == $next && + $agg_in_len == $in_len && + $agg_out_len == length $out_bytes && + $agg_fallback == $fallback + # && length($l->[AGG_OUT_BYTES]) < 16 + ) { + # my $i = ord($b)-ord($l->[AGG_MIN_IN]); + # we can aggregate this byte onto the end. + $l->[AGG_MAX_IN] = $b; + $l->[AGG_OUT_BYTES] .= $out_bytes; + } else { + # AGG_MIN_IN => 0, + # AGG_MAX_IN => 1, + # AGG_OUT_BYTES => 2, + # AGG_NEXT => 3, + # AGG_IN_LEN => 4, + # AGG_OUT_LEN => 5, + # AGG_FALLBACK => 6, + # Reset the last thing we saw, plus set 5 lexicals to save some derefs. + # (only gains .6% on euc-jp -- is it worth it?) + push @ent, $l = [$b, $agg_max_in = $b, $out_bytes, $agg_next = $next, + $agg_in_len = $in_len, $agg_out_len = length $out_bytes, + $agg_fallback = $fallback]; + } + if (exists $next->{Cname}) { + $next->{'Forward'} = 1 if $next != $a; + } else { + process(sprintf("%s_%02x",$name,$b),$next); + } + } + # encengine.c rules say that last entry must be for 255 + if ($agg_max_in < 255) { + push @ent, [1+$agg_max_in, 255,undef,$a,0,0]; + } + $a->{'Entries'} = \@ent; +} + + +sub addstrings +{ + my ($fh,$a) = @_; + my $name = $a->{'Cname'}; + # String tables + foreach my $b (@{$a->{'Entries'}}) + { + next unless $b->[AGG_OUT_LEN]; + $strings{$b->[AGG_OUT_BYTES]} = undef; + } + if ($a->{'Forward'}) + { + my ($cpp, $static, $sized) = compiler_info(1); + my $count = $sized ? scalar(@{$a->{'Entries'}}) : ''; + if ($static) { + # we cannot ask Config for d_plusplus since we can override CC=g++-6 on the cmdline + print $fh "#ifdef __cplusplus\n"; # -fpermissive since g++-6 + print $fh "extern encpage_t $name\[$count];\n"; + print $fh "#else\n"; + print $fh "static const encpage_t $name\[$count];\n"; + print $fh "#endif\n"; + } else { + print $fh "extern encpage_t $name\[$count];\n"; + } + } + $a->{'DoneStrings'} = 1; + foreach my $b (@{$a->{'Entries'}}) + { + my ($s,$e,$out,$t,$end,$l) = @$b; + addstrings($fh,$t) unless $t->{'DoneStrings'}; + } +} + +sub outbigstring +{ + my ($fh,$name) = @_; + + $string_acc = ''; + + # Make the big string in the string accumulator. Longest first, on the hope + # that this makes it more likely that we find the short strings later on. + # Not sure if it helps sorting strings of the same length lexically. + foreach my $s (sort {length $b <=> length $a || $a cmp $b} keys %strings) { + my $index = index $string_acc, $s; + if ($index >= 0) { + $saved += length($s); + $strings_in_acc{$s} = $index; + } else { + OPTIMISER: { + if ($opt{'O'}) { + my $sublength = length $s; + while (--$sublength > 0) { + # progressively lop characters off the end, to see if the start of + # the new string overlaps the end of the accumulator. + if (substr ($string_acc, -$sublength) + eq substr ($s, 0, $sublength)) { + $subsave += $sublength; + $strings_in_acc{$s} = length ($string_acc) - $sublength; + # append the last bit on the end. + $string_acc .= substr ($s, $sublength); + last OPTIMISER; + } + # or if the end of the new string overlaps the start of the + # accumulator + next unless substr ($string_acc, 0, $sublength) + eq substr ($s, -$sublength); + # well, the last $sublength characters of the accumulator match. + # so as we're prepending to the accumulator, need to shift all our + # existing offsets forwards + $_ += $sublength foreach values %strings_in_acc; + $subsave += $sublength; + $strings_in_acc{$s} = 0; + # append the first bit on the start. + $string_acc = substr ($s, 0, -$sublength) . $string_acc; + last OPTIMISER; + } + } + # Optimiser (if it ran) found nothing, so just going have to tack the + # whole thing on the end. + $strings_in_acc{$s} = length $string_acc; + $string_acc .= $s; + }; + } + } + + $strings = length $string_acc; + my ($cpp) = compiler_info(0); + my $var = $cpp ? '' : 'static'; + my $definition = "\n$var const U8 $name\[$strings] = { " . + join(',',unpack "C*",$string_acc); + # We have a single long line. Split it at convenient commas. + print $fh $1, "\n" while $definition =~ /\G(.{74,77},)/gcs; + print $fh substr ($definition, pos $definition), " };\n"; +} + +sub findstring { + my ($name,$s) = @_; + my $offset = $strings_in_acc{$s}; + die "Can't find string " . join (',',unpack "C*",$s) . " in accumulator" + unless defined $offset; + "$name + $offset"; +} + +sub outtable +{ + my ($fh,$a,$bigname) = @_; + my $name = $a->{'Cname'}; + $a->{'Done'} = 1; + foreach my $b (@{$a->{'Entries'}}) + { + my ($s,$e,$out,$t,$end,$l) = @$b; + outtable($fh,$t,$bigname) unless $t->{'Done'}; + } + my ($cpp, $static) = compiler_info(0); + my $count = scalar(@{$a->{'Entries'}}); + if ($static) { + print $fh "#ifdef __cplusplus\n"; # -fpermissive since g++-6 + print $fh "encpage_t $name\[$count] = {\n"; + print $fh "#else\n"; + print $fh "static const encpage_t $name\[$count] = {\n"; + print $fh "#endif\n"; + } else { + print $fh "\nencpage_t $name\[$count] = {\n"; + } + foreach my $b (@{$a->{'Entries'}}) + { + my ($sc,$ec,$out,$t,$end,$l,$fb) = @$b; + # $end |= 0x80 if $fb; # what the heck was on your mind, Nick? -- Dan + print $fh "{"; + if ($l) + { + printf $fh findstring($bigname,$out); + } + else + { + print $fh "0"; + } + print $fh ",",$t->{Cname}; + printf $fh ",0x%02x,0x%02x,$l,$end},\n",$sc,$ec; + } + print $fh "};\n"; +} + +sub output_enc +{ + my ($fh,$name,$a) = @_; + die "Changed - fix me for new structure"; + foreach my $b (sort keys %$a) + { + my ($s,$e,$out,$t,$end,$l,$fb) = @{$a->{$b}}; + } +} + +sub decode_U +{ + my $s = shift; +} + +my @uname; +sub char_names{} # cf. https://rt.cpan.org/Ticket/Display.html?id=132471 + +sub output_ucm_page +{ + my ($cmap,$a,$t,$pre) = @_; + # warn sprintf("Page %x\n",$pre); + my $raw = $t->{Raw}; + foreach my $key (sort keys %$raw) { + # RAW_NEXT => 0, + # RAW_IN_LEN => 1, + # RAW_OUT_BYTES => 2, + # RAW_FALLBACK => 3, + my ($next, $in_len, $out_bytes, $fallback) = @{$raw->{$key}}; + my $u = ord $key; + $fallback ||= 0; + + if ($next != $a && $next != $t) { + output_ucm_page($cmap,$a,$next,(($pre|($u &0x3F)) << 6)&0xFFFF); + } elsif (length $out_bytes) { + if ($pre) { + $u = $pre|($u &0x3f); + } + my $s = sprintf " ",$u; + #foreach my $c (split(//,$out_bytes)) { + # $s .= sprintf "\\x%02X",ord($c); + #} + # 9.5% faster changing that loop to this: + $s .= sprintf +("\\x%02X" x length $out_bytes), unpack "C*", $out_bytes; + $s .= sprintf " |%d # %s\n",($fallback ? 1 : 0),$uname[$u]; + push(@$cmap,$s); + } else { + warn join(',',$u, @{$raw->{$key}},$a,$t); + } + } +} + +sub output_ucm +{ + my ($fh,$name,$h,$rep,$min_el,$max_el) = @_; + print $fh "# $0 @orig_ARGV\n" unless $opt{'q'}; + print $fh " \"$name\"\n"; + char_names(); + if (defined $min_el) + { + print $fh " $min_el\n"; + } + if (defined $max_el) + { + print $fh " $max_el\n"; + } + if (defined $rep) + { + print $fh " "; + foreach my $c (split(//,$rep)) + { + printf $fh "\\x%02X",ord($c); + } + print $fh "\n"; + } + my @cmap; + output_ucm_page(\@cmap,$h,$h,0); + print $fh "#\nCHARMAP\n"; + foreach my $line (sort { substr($a,8) cmp substr($b,8) } @cmap) + { + print $fh $line; + } + print $fh "END CHARMAP\n"; +} + +use vars qw( + $_Enc2xs + $_Version + $_Inc + $_E2X + $_Name + $_TableFiles + $_Now +); + +sub find_e2x{ + eval { require File::Find; }; + my (@inc, %e2x_dir); + for my $inc (@INC){ + push @inc, $inc unless $inc eq '.'; #skip current dir + } + File::Find::find( + sub { + my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, + $atime,$mtime,$ctime,$blksize,$blocks) + = lstat($_) or return; + -f _ or return; + if (/^.*\.e2x$/o){ + no warnings 'once'; + $e2x_dir{$File::Find::dir} ||= $mtime; + } + return; + }, @inc); + warn join("\n", keys %e2x_dir), "\n"; + for my $d (sort {$e2x_dir{$a} <=> $e2x_dir{$b}} keys %e2x_dir){ + $_E2X = $d; + # warn "$_E2X => ", scalar localtime($e2x_dir{$d}); + return $_E2X; + } +} + +sub make_makefile_pl +{ + eval { require Encode } or die "You need to install Encode to use enc2xs -M\nerror: $@\n"; + # our used for variable expansion + $_Enc2xs = $0; + $_Version = $VERSION; + $_E2X = find_e2x(); + $_Name = shift; + $_TableFiles = join(",", map {qq('$_')} @_); + $_Now = scalar localtime(); + + eval { require File::Spec; }; + _print_expand(File::Spec->catfile($_E2X,"Makefile_PL.e2x"),"Makefile.PL"); + _print_expand(File::Spec->catfile($_E2X,"_PM.e2x"), "$_Name.pm"); + _print_expand(File::Spec->catfile($_E2X,"_T.e2x"), "t/$_Name.t"); + _print_expand(File::Spec->catfile($_E2X,"README.e2x"), "README"); + _print_expand(File::Spec->catfile($_E2X,"Changes.e2x"), "Changes"); + exit; +} + +use vars qw( + $_ModLines + $_LocalVer + ); + +sub make_configlocal_pm { + eval { require Encode } or die "Unable to require Encode: $@\n"; + eval { require File::Spec; }; + + # our used for variable expantion + my %in_core = map { $_ => 1 } ( + 'ascii', 'iso-8859-1', 'utf8', + 'ascii-ctrl', 'null', 'utf-8-strict' + ); + my %LocalMod = (); + # check @enc; + use File::Find (); + my $wanted = sub{ + -f $_ or return; + $File::Find::name =~ /\A\./ and return; + $File::Find::name =~ /\.pm\z/ or return; + $File::Find::name =~ m/\bEncode\b/ or return; + my $mod = $File::Find::name; + $mod =~ s/.*\bEncode\b/Encode/o; + $mod =~ s/\.pm\z//o; + $mod =~ s,/,::,og; + eval qq{ require $mod; } or return; + warn qq{ require $mod;\n}; + for my $enc ( Encode->encodings() ) { + no warnings; + $in_core{$enc} and next; + $Encode::Config::ExtModule{$enc} and next; + $LocalMod{$enc} ||= $mod; + } + }; + File::Find::find({wanted => $wanted}, @INC); + $_ModLines = ""; + for my $enc ( sort keys %LocalMod ) { + $_ModLines .= + qq(\$Encode::ExtModule{'$enc'} = "$LocalMod{$enc}";\n); + } + warn $_ModLines if $_ModLines; + $_LocalVer = _mkversion(); + $_E2X = find_e2x(); + $_Inc = $INC{"Encode.pm"}; + $_Inc =~ s/\.pm$//o; + _print_expand( File::Spec->catfile( $_E2X, "ConfigLocal_PM.e2x" ), + File::Spec->catfile( $_Inc, "ConfigLocal.pm" ), 1 ); + exit; +} + +sub _mkversion{ + # v-string is now depreciated; use time() instead; + #my ($ss,$mm,$hh,$dd,$mo,$yyyy) = localtime(); + #$yyyy += 1900, $mo +=1; + #return sprintf("v%04d.%04d.%04d", $yyyy, $mo*100+$dd, $hh*100+$mm); + return time(); +} + +sub _print_expand{ + eval { require File::Basename } or die "File::Basename needed. Are you on miniperl?;\nerror: $@\n"; + File::Basename->import(); + my ($src, $dst, $clobber) = @_; + if (!$clobber and -e $dst){ + warn "$dst exists. skipping\n"; + return; + } + warn "Generating $dst...\n"; + open my $in, $src or die "$src : $!"; + if ((my $d = dirname($dst)) ne '.'){ + -d $d or mkdir $d, 0755 or die "mkdir $d : $!"; + } + open my $out, ">", $dst or die "$!"; + my $asis = 0; + while (<$in>){ + if (/^#### END_OF_HEADER/){ + $asis = 1; next; + } + s/(\$_[A-Z][A-Za-z0-9]+)_/$1/gee unless $asis; + print $out $_; + } +} +__END__ + +=head1 NAME + +enc2xs -- Perl Encode Module Generator + +=head1 SYNOPSIS + + enc2xs -[options] + enc2xs -M ModName mapfiles... + enc2xs -C + +=head1 DESCRIPTION + +F builds a Perl extension for use by Encode from either +Unicode Character Mapping files (.ucm) or Tcl Encoding Files (.enc). +Besides being used internally during the build process of the Encode +module, you can use F to add your own encoding to perl. +No knowledge of XS is necessary. + +=head1 Quick Guide + +If you want to know as little about Perl as possible but need to +add a new encoding, just read this chapter and forget the rest. + +=over 4 + +=item 0.Z<> + +Have a .ucm file ready. You can get it from somewhere or you can write +your own from scratch or you can grab one from the Encode distribution +and customize it. For the UCM format, see the next Chapter. In the +example below, I'll call my theoretical encoding myascii, defined +in I. C<$> is a shell prompt. + + $ ls -F + my.ucm + +=item 1.Z<> + +Issue a command as follows; + + $ enc2xs -M My my.ucm + generating Makefile.PL + generating My.pm + generating README + generating Changes + +Now take a look at your current directory. It should look like this. + + $ ls -F + Makefile.PL My.pm my.ucm t/ + +The following files were created. + + Makefile.PL - MakeMaker script + My.pm - Encode submodule + t/My.t - test file + +=over 4 + +=item 1.1.Z<> + +If you want *.ucm installed together with the modules, do as follows; + + $ mkdir Encode + $ mv *.ucm Encode + $ enc2xs -M My Encode/*ucm + +=back + +=item 2.Z<> + +Edit the files generated. You don't have to if you have no time AND no +intention to give it to someone else. But it is a good idea to edit +the pod and to add more tests. + +=item 3.Z<> + +Now issue a command all Perl Mongers love: + + $ perl Makefile.PL + Writing Makefile for Encode::My + +=item 4.Z<> + +Now all you have to do is make. + + $ make + cp My.pm blib/lib/Encode/My.pm + /usr/local/bin/perl /usr/local/bin/enc2xs -Q -O \ + -o encode_t.c -f encode_t.fnm + Reading myascii (myascii) + Writing compiled form + 128 bytes in string tables + 384 bytes (75%) saved spotting duplicates + 1 bytes (0.775%) saved using substrings + .... + chmod 644 blib/arch/auto/Encode/My/My.bs + $ + +The time it takes varies depending on how fast your machine is and +how large your encoding is. Unless you are working on something big +like euc-tw, it won't take too long. + +=item 5.Z<> + +You can "make install" already but you should test first. + + $ make test + PERL_DL_NONLAZY=1 /usr/local/bin/perl -Iblib/arch -Iblib/lib \ + -e 'use Test::Harness qw(&runtests $verbose); \ + $verbose=0; runtests @ARGV;' t/*.t + t/My....ok + All tests successful. + Files=1, Tests=2, 0 wallclock secs + ( 0.09 cusr + 0.01 csys = 0.09 CPU) + +=item 6.Z<> + +If you are content with the test result, just "make install" + +=item 7.Z<> + +If you want to add your encoding to Encode's demand-loading list +(so you don't have to "use Encode::YourEncoding"), run + + enc2xs -C + +to update Encode::ConfigLocal, a module that controls local settings. +After that, "use Encode;" is enough to load your encodings on demand. + +=back + +=head1 The Unicode Character Map + +Encode uses the Unicode Character Map (UCM) format for source character +mappings. This format is used by IBM's ICU package and was adopted +by Nick Ing-Simmons for use with the Encode module. Since UCM is +more flexible than Tcl's Encoding Map and far more user-friendly, +this is the recommended format for Encode now. + +A UCM file looks like this. + + # + # Comments + # + "US-ascii" # Required + "ascii" # Optional + 1 # Required; usually 1 + 1 # Max. # of bytes/char + \x3F # Substitution char + # + CHARMAP + \x00 |0 # + \x01 |0 # + \x02 |0 # + .... + \x7C |0 # VERTICAL LINE + \x7D |0 # RIGHT CURLY BRACKET + \x7E |0 # TILDE + \x7F |0 # + END CHARMAP + +=over 4 + +=item * + +Anything that follows C<#> is treated as a comment. + +=item * + +The header section continues until a line containing the word +CHARMAP. This section has a form of IkeywordE value>, one +pair per line. Strings used as values must be quoted. Barewords are +treated as numbers. I<\xXX> represents a byte. + +Most of the keywords are self-explanatory. I means +substitution character, not subcharacter. When you decode a Unicode +sequence to this encoding but no matching character is found, the byte +sequence defined here will be used. For most cases, the value here is +\x3F; in ASCII, this is a question mark. + +=item * + +CHARMAP starts the character map section. Each line has a form as +follows: + + \xXX.. |0 # comment + ^ ^ ^ + | | +- Fallback flag + | +-------- Encoded byte sequence + +-------------- Unicode Character ID in hex + +The format is roughly the same as a header section except for the +fallback flag: | followed by 0..3. The meaning of the possible +values is as follows: + +=over 4 + +=item |0 + +Round trip safe. A character decoded to Unicode encodes back to the +same byte sequence. Most characters have this flag. + +=item |1 + +Fallback for unicode -> encoding. When seen, enc2xs adds this +character for the encode map only. + +=item |2 + +Skip sub-char mapping should there be no code point. + +=item |3 + +Fallback for encoding -> unicode. When seen, enc2xs adds this +character for the decode map only. + +=back + +=item * + +And finally, END OF CHARMAP ends the section. + +=back + +When you are manually creating a UCM file, you should copy ascii.ucm +or an existing encoding which is close to yours, rather than write +your own from scratch. + +When you do so, make sure you leave at least B to B as +is, unless your environment is EBCDIC. + +B: not all features in UCM are implemented. For example, +icu:state is not used. Because of that, you need to write a perl +module if you want to support algorithmical encodings, notably +the ISO-2022 series. Such modules include L, +L, and L. + +=head2 Coping with duplicate mappings + +When you create a map, you SHOULD make your mappings round-trip safe. +That is, C stands for all characters that are marked as C<|0>. Here is +how to make sure: + +=over 4 + +=item * + +Sort your map in Unicode order. + +=item * + +When you have a duplicate entry, mark either one with '|1' or '|3'. + +=item * + +And make sure the '|1' or '|3' entry FOLLOWS the '|0' entry. + +=back + +Here is an example from big5-eten. + + \xF9\xF9 |0 + \xA2\xA4 |3 + +Internally Encoding -> Unicode and Unicode -> Encoding Map looks like +this; + + E to U U to E + -------------------------------------- + \xF9\xF9 => U2550 U2550 => \xF9\xF9 + \xA2\xA4 => U2550 + +So it is round-trip safe for \xF9\xF9. But if the line above is upside +down, here is what happens. + + E to U U to E + -------------------------------------- + \xA2\xA4 => U2550 U2550 => \xF9\xF9 + (\xF9\xF9 => U2550 is now overwritten!) + +The Encode package comes with F, a crude but sufficient +utility to check the integrity of a UCM file. Check under the +Encode/bin directory for this. + +When in doubt, you can use F, yet another utility under +Encode/bin directory. + +=head1 Bookmarks + +=over 4 + +=item * + +ICU Home Page +L + +=item * + +ICU Character Mapping Tables +L + +=item * + +ICU:Conversion Data +L + +=back + +=head1 SEE ALSO + +L, +L, +L + +=cut + +# -Q to disable the duplicate codepoint test +# -S make mapping errors fatal +# -q to remove comments written to output files +# -O to enable the (brute force) substring optimiser +# -o to specify the output file name (else it's the first arg) +# -f to give a file with a list of input files (else use the args) +# -n to name the encoding (else use the basename of the input file. + +With %seen holding array refs: + + 865.66 real 28.80 user 8.79 sys + 7904 maximum resident set size + 1356 average shared memory size + 18566 average unshared data size + 229 average unshared stack size + 46080 page reclaims + 33373 page faults + +With %seen holding simple scalars: + + 342.16 real 27.11 user 3.54 sys + 8388 maximum resident set size + 1394 average shared memory size + 14969 average unshared data size + 236 average unshared stack size + 28159 page reclaims + 9839 page faults + +Yes, 5 minutes is faster than 15. Above is for CP936 in CN. Only difference is +how %seen is storing things its seen. So it is pathalogically bad on a 16M +RAM machine, but it's going to help even on modern machines. +Swapping is bad, m'kay :-) diff --git a/git/usr/bin/core_perl/encguess b/git/usr/bin/core_perl/encguess new file mode 100644 index 0000000000000000000000000000000000000000..2aca38583a7837e894ad55662af279bc7ef09557 --- /dev/null +++ b/git/usr/bin/core_perl/encguess @@ -0,0 +1,149 @@ +#!/usr/bin/perl + eval 'exec /usr/bin/perl -S $0 ${1+"$@"}' + if 0; # ^ Run only under a shell +#!./perl +use 5.008001; +BEGIN { pop @INC if $INC[-1] eq '.' } +use strict; +use warnings; +use Encode; +use Getopt::Std; +use Carp; +use Encode::Guess; +$Getopt::Std::STANDARD_HELP_VERSION = 1; + +my %opt; +getopts( "huSs:", \%opt ); +my @suspect_list; +list_valid_suspects() and exit if $opt{S}; +@suspect_list = split /:,/, $opt{s} if $opt{s}; +HELP_MESSAGE() if $opt{h}; +HELP_MESSAGE() unless @ARGV; +do_guess($_) for @ARGV; + +sub read_file { + my $filename = shift; + local $/; + open my $fh, '<:raw', $filename or croak "$filename:$!"; + my $content = <$fh>; + close $fh; + return $content; +} + +sub do_guess { + my $filename = shift; + my $data = read_file($filename); + my $enc = guess_encoding( $data, @suspect_list ); + if ( !ref($enc) && $opt{u} ) { + return 1; + } + print "$filename\t"; + if ( ref($enc) ) { + print $enc->mime_name(); + } + else { + print "unknown"; + } + print "\n"; + return 1; +} + +sub list_valid_suspects { + print join( "\n", Encode->encodings(":all") ); + print "\n"; + return 1; +} + +sub HELP_MESSAGE { + exec 'pod2usage', $0 or die "pod2usage: $!" +} +__END__ +=head1 NAME + +encguess - guess character encodings of files + +=head1 VERSION + +$Id: encguess,v 0.4 2023/11/10 01:10:50 dankogai Exp $ + +=head1 SYNOPSIS + + encguess [switches] filename... + +=head2 SWITCHES + +=over 2 + +=item -h + +show this message and exit. + +=item -s + +specify a list of "suspect encoding types" to test, +separated by either C<:> or C<,> + +=item -S + +output a list of all acceptable encoding types that can be used with +the -s param + +=item -u + +suppress display of unidentified types + +=back + +=head2 EXAMPLES: + +=over 2 + +=item * + +Guess encoding of a file named C, using only the default +suspect types. + + encguess test.txt + +=item * + +Guess the encoding type of a file named C, using the suspect +types C. + + encguess -s euc-jp,shiftjis,7bit-jis test.txt + encguess -s euc-jp:shiftjis:7bit-jis test.txt + +=item * + +Guess the encoding type of several files, do not display results for +unidentified files. + + encguess -us euc-jp,shiftjis,7bit-jis test*.txt + +=back + +=head1 DESCRIPTION + +The encoding identification is done by checking one encoding type at a +time until all but the right type are eliminated. The set of encoding +types to try is defined by the -s parameter and defaults to ascii, +utf8 and UTF-16/32 with BOM. This can be overridden by passing one or +more encoding types via the -s parameter. If you need to pass in +multiple suspect encoding types, use a quoted string with the a space +separating each value. + +=head1 SEE ALSO + +L, L + +=head1 LICENSE AND COPYRIGHT + +Copyright 2015 Michael LaGrasta and Dan Kogai. + +This program is free software; you can redistribute it and/or modify it +under the terms of the Artistic License (2.0). You may obtain a +copy of the full license at: + +L + +=cut diff --git a/git/usr/bin/core_perl/h2ph b/git/usr/bin/core_perl/h2ph new file mode 100644 index 0000000000000000000000000000000000000000..c8caf1b5f4df2d873a37b1b48b6c8a72ad1bff57 --- /dev/null +++ b/git/usr/bin/core_perl/h2ph @@ -0,0 +1,977 @@ +#!/usr/bin/perl + eval 'exec /usr/bin/perl -S $0 ${1+"$@"}' + if 0; # ^ Run only under a shell + +BEGIN { pop @INC if $INC[-1] eq '.' } + +use strict; + +use Config; +use File::Path qw(mkpath); +use Getopt::Std; + +# Make sure read permissions for all are set: +if (defined umask && (umask() & 0444)) { + umask (umask() & ~0444); +} + +getopts('Dd:rlhaQe'); +use vars qw($opt_D $opt_d $opt_r $opt_l $opt_h $opt_a $opt_Q $opt_e); +die "-r and -a options are mutually exclusive\n" if ($opt_r and $opt_a); +my @inc_dirs = inc_dirs() if $opt_a; + +my $Exit = 0; + +my $Dest_dir = $opt_d || $Config{installsitearch}; +die "Destination directory $Dest_dir doesn't exist or isn't a directory\n" + unless -d $Dest_dir; + +my @isatype = qw( + char uchar u_char + short ushort u_short + int uint u_int + long ulong u_long + FILE key_t caddr_t + float double size_t +); + +my %isatype; +@isatype{@isatype} = (1) x @isatype; +my $inif = 0; +my %Is_converted; +my %bad_file = (); + +@ARGV = ('-') unless @ARGV; + +build_preamble_if_necessary(); + +sub reindent($) { + my($text) = shift; + $text =~ s/\n/\n /g; + $text =~ s/ /\t/g; + $text; +} + +my ($t, $tab, %curargs, $new, $eval_index, $dir, $name, $args, $outfile); +my ($incl, $incl_type, $incl_quote, $next); +while (defined (my $file = next_file())) { + if (-l $file and -d $file) { + link_if_possible($file) if ($opt_l); + next; + } + + # Recover from header files with unbalanced cpp directives + $t = ''; + $tab = 0; + + # $eval_index goes into '#line' directives, to help locate syntax errors: + $eval_index = 1; + + if ($file eq '-') { + open(IN, "-"); + open(OUT, ">-"); + } else { + ($outfile = $file) =~ s/\.h$/.ph/ || next; + print "$file -> $outfile\n" unless $opt_Q; + if ($file =~ m|^(.*)/|) { + $dir = $1; + mkpath "$Dest_dir/$dir"; + } + + if ($opt_a) { # automagic mode: locate header file in @inc_dirs + foreach (@inc_dirs) { + chdir $_; + last if -f $file; + } + } + + open(IN, "<", "$file") || (($Exit = 1),(warn "Can't open $file: $!\n"),next); + open(OUT, ">", "$Dest_dir/$outfile") || die "Can't create $outfile: $!\n"; + } + + print OUT + "require '_h2ph_pre.ph';\n\n", + "no warnings qw(redefine misc);\n\n"; + + while (defined (local $_ = next_line($file))) { + if (s/^\s*\#\s*//) { + if (s/^define\s+(\w+)//) { + $name = $1; + $new = ''; + s/\s+$//; + s/\(\w+\s*\(\*\)\s*\(\w*\)\)\s*(-?\d+)/$1/; # (int (*)(foo_t))0 + if (s/^\(([\w,\s]*)\)//) { + $args = $1; + my $proto = '() '; + if ($args ne '') { + $proto = ''; + foreach my $arg (split(/,\s*/,$args)) { + $arg =~ s/^\s*([^\s].*[^\s])\s*$/$1/; + $curargs{$arg} = 1; + } + $args =~ s/\b(\w)/\$$1/g; + $args = "my($args) = \@_;\n$t "; + } + s/^\s+//; + expr(); + $new =~ s/(["\\])/\\$1/g; #"]); + EMIT($proto); + } else { + s/^\s+//; + expr(); + + $new = 1 if $new eq ''; + + # Shunt around such directives as '#define FOO FOO': + next if $new =~ /^\s*&\Q$name\E\s*\z/; + + $new = reindent($new); + $args = reindent($args); + $new =~ s/(['\\])/\\$1/g; #']); + + print OUT $t, 'eval '; + if ($opt_h) { + print OUT "\"\\n#line $eval_index $outfile\\n\" . "; + $eval_index++; + } + print OUT "'sub $name () {$new;}' unless defined(&$name);\n"; + } + } elsif (/^(include|import|include_next)\s*([<\"])(.*)[>\"]/) { + $incl_type = $1; + $incl_quote = $2; + $incl = $3; + if (($incl_type eq 'include_next') || + ($opt_e && exists($bad_file{$incl}))) { + $incl =~ s/\.h$/.ph/; + print OUT ($t, + "eval {\n"); + $tab += 4; + $t = "\t" x ($tab / 8) . ' ' x ($tab % 8); + print OUT ($t, "my(\@REM);\n"); + if ($incl_type eq 'include_next') { + print OUT ($t, + "my(\%INCD) = map { \$INC{\$_} => 1 } ", + "(grep { \$_ eq \"$incl\" } ", + "keys(\%INC));\n"); + print OUT ($t, + "\@REM = map { \"\$_/$incl\" } ", + "(grep { not exists(\$INCD{\"\$_/$incl\"})", + " and -f \"\$_/$incl\" } \@INC);\n"); + } else { + print OUT ($t, + "\@REM = map { \"\$_/$incl\" } ", + "(grep {-r \"\$_/$incl\" } \@INC);\n"); + } + print OUT ($t, + "require \"\$REM[0]\" if \@REM;\n"); + $tab -= 4; + $t = "\t" x ($tab / 8) . ' ' x ($tab % 8); + print OUT ($t, + "};\n"); + print OUT ($t, + "warn(\$\@) if \$\@;\n"); + } else { + $incl =~ s/\.h$/.ph/; + # copy the prefix in the quote syntax (#include "x.h") case + if ($incl !~ m|/| && $incl_quote eq q{"} && $file =~ m|^(.*)/|) { + $incl = "$1/$incl"; + } + print OUT $t,"require '$incl';\n"; + } + } elsif (/^ifdef\s+(\w+)/) { + print OUT $t,"if(defined(&$1)) {\n"; + $tab += 4; + $t = "\t" x ($tab / 8) . ' ' x ($tab % 8); + } elsif (/^ifndef\s+(\w+)/) { + print OUT $t,"unless(defined(&$1)) {\n"; + $tab += 4; + $t = "\t" x ($tab / 8) . ' ' x ($tab % 8); + } elsif (s/^if\s+//) { + $new = ''; + $inif = 1; + expr(); + $inif = 0; + print OUT $t,"if($new) {\n"; + $tab += 4; + $t = "\t" x ($tab / 8) . ' ' x ($tab % 8); + } elsif (s/^elif\s+//) { + $new = ''; + $inif = 1; + expr(); + $inif = 0; + $tab -= 4; + $t = "\t" x ($tab / 8) . ' ' x ($tab % 8); + print OUT $t,"}\n elsif($new) {\n"; + $tab += 4; + $t = "\t" x ($tab / 8) . ' ' x ($tab % 8); + } elsif (/^else/) { + $tab -= 4; + $t = "\t" x ($tab / 8) . ' ' x ($tab % 8); + print OUT $t,"} else {\n"; + $tab += 4; + $t = "\t" x ($tab / 8) . ' ' x ($tab % 8); + } elsif (/^endif/) { + $tab -= 4; + $t = "\t" x ($tab / 8) . ' ' x ($tab % 8); + print OUT $t,"}\n"; + } elsif(/^undef\s+(\w+)/) { + print OUT $t, "undef(&$1) if defined(&$1);\n"; + } elsif(/^error\s+(".*")/) { + print OUT $t, "die($1);\n"; + } elsif(/^error\s+(.*)/) { + print OUT $t, "die(\"", quotemeta($1), "\");\n"; + } elsif(/^warning\s+(.*)/) { + print OUT $t, "warn(\"", quotemeta($1), "\");\n"; + } elsif(/^ident\s+(.*)/) { + print OUT $t, "# $1\n"; + } + } elsif (/^\s*(typedef\s*)?enum\s*(\s+[a-zA-Z_]\w*\s*)?/) { # { for vi + until(/\{[^}]*\}.*;/ || /;/) { + last unless defined ($next = next_line($file)); + chomp $next; + # drop "#define FOO FOO" in enums + $next =~ s/^\s*#\s*define\s+(\w+)\s+\1\s*$//; + # #defines in enums (aliases) + $next =~ s/^\s*#\s*define\s+(\w+)\s+(\w+)\s*$/$1 = $2,/; + $_ .= $next; + print OUT "# $next\n" if $opt_D; + } + s/#\s*if.*?#\s*endif//g; # drop #ifdefs + s@/\*.*?\*/@@g; + s/\s+/ /g; + next unless /^\s?(typedef\s?)?enum\s?([a-zA-Z_]\w*)?\s?\{(.*)\}\s?([a-zA-Z_]\w*)?\s?;/; + (my $enum_subs = $3) =~ s/\s//g; + my @enum_subs = split(/,/, $enum_subs); + my $enum_val = -1; + foreach my $enum (@enum_subs) { + my ($enum_name, $enum_value) = $enum =~ /^([a-zA-Z_]\w*)(=.+)?$/; + $enum_name or next; + $enum_value =~ s/^=//; + $enum_val = (length($enum_value) ? $enum_value : $enum_val + 1); + if ($opt_h) { + print OUT ($t, + "eval(\"\\n#line $eval_index $outfile\\n", + "sub $enum_name () \{ $enum_val; \}\") ", + "unless defined(\&$enum_name);\n"); + ++ $eval_index; + } else { + print OUT ($t, + "eval(\"sub $enum_name () \{ $enum_val; \}\") ", + "unless defined(\&$enum_name);\n"); + } + } + } elsif (/^(?:__extension__\s+)?(?:extern|static)\s+(?:__)?inline(?:__)?\s+/ + and !/;\s*$/ and !/{\s*}\s*$/) + { # { for vi + # This is a hack to parse the inline functions in the glibc headers. + # Warning: massive kludge ahead. We suppose inline functions + # are mainly constructed like macros. + while (1) { + last unless defined ($next = next_line($file)); + chomp $next; + undef $_, last if $next =~ /__THROW\s*;/ + or $next =~ /^(__extension__|extern|static)\b/; + $_ .= " $next"; + print OUT "# $next\n" if $opt_D; + last if $next =~ /^}|^{.*}\s*$/; + } + next if not defined; # because it's only a prototype + s/\b(__extension__|extern|static|(?:__)?inline(?:__)?)\b//g; + # violently drop #ifdefs + s/#\s*if.*?#\s*endif//g + and print OUT "# some #ifdef were dropped here -- fill in the blanks\n"; + if (s/^(?:\w|\s|\*)*\s(\w+)\s*//) { + $name = $1; + } else { + warn "name not found"; next; # shouldn't occur... + } + my @args; + if (s/^\(([^()]*)\)\s*(\w+\s*)*//) { + for my $arg (split /,/, $1) { + if ($arg =~ /(\w+)\s*$/) { + $curargs{$1} = 1; + push @args, $1; + } + } + } + $args = ( + @args + ? "my(" . (join ',', map "\$$_", @args) . ") = \@_;\n$t " + : "" + ); + my $proto = @args ? '' : '() '; + $new = ''; + s/\breturn\b//g; # "return" doesn't occur in macros usually... + expr(); + # try to find and perlify local C variables + our @local_variables = (); # needs to be a our(): (?{...}) bug workaround + { + use re "eval"; + my $typelist = join '|', keys %isatype; + $new =~ s[' + (?:(?:__)?const(?:__)?\s+)? + (?:(?:un)?signed\s+)? + (?:long\s+)? + (?:$typelist)\s+ + (\w+) + (?{ push @local_variables, $1 }) + '] + [my \$$1]gx; + $new =~ s[' + (?:(?:__)?const(?:__)?\s+)? + (?:(?:un)?signed\s+)? + (?:long\s+)? + (?:$typelist)\s+ + ' \s+ &(\w+) \s* ; + (?{ push @local_variables, $1 }) + ] + [my \$$1;]gx; + } + $new =~ s/&$_\b/\$$_/g for @local_variables; + $new =~ s/(["\\])/\\$1/g; #"]); + # now that's almost like a macro (we hope) + EMIT($proto); + } + } + $Is_converted{$file} = 1; + if ($opt_e && exists($bad_file{$file})) { + unlink($Dest_dir . '/' . $outfile); + $next = ''; + } else { + print OUT "1;\n"; + queue_includes_from($file) if $opt_a; + } +} + +if ($opt_e && (scalar(keys %bad_file) > 0)) { + warn "Was unable to convert the following files:\n"; + warn "\t" . join("\n\t",sort(keys %bad_file)) . "\n"; +} + +exit $Exit; + +sub EMIT { + my $proto = shift; + + $new = reindent($new); + $args = reindent($args); + $new =~ s/(['\\])/\\$1/g; #']); + if ($opt_h) { + print OUT $t, + "eval \"\\n#line $eval_index $outfile\\n\" . 'sub $name $proto\{\n$t ${args}eval q($new);\n$t}' unless defined(\&$name);\n"; + $eval_index++; + } else { + print OUT $t, + "eval 'sub $name $proto\{\n$t ${args}eval q($new);\n$t}' unless defined(\&$name);\n"; + } + %curargs = (); + return; +} + +sub expr { + if (/\b__asm__\b/) { # freak out + $new = '"(assembly code)"'; + return + } + my $joined_args; + if(keys(%curargs)) { + $joined_args = join('|', keys(%curargs)); + } + while ($_ ne '') { + s/^\&\&// && do { $new .= " &&"; next;}; # handle && operator + s/^\&([\(a-z\)]+)/$1/i; # hack for things that take the address of + s/^(\s+)// && do {$new .= ' '; next;}; + s/^0X([0-9A-F]+)[UL]*//i + && do {my $hex = $1; + $hex =~ s/^0+//; + if (length $hex > 8 && !$Config{use64bitint}) { + # Croak if nv_preserves_uv_bits < 64 ? + $new .= hex(substr($hex, -8)) + + 2**32 * hex(substr($hex, 0, -8)); + # The above will produce "erroneous" code + # if the hex constant was e.g. inside UINT64_C + # macro, but then again, h2ph is an approximation. + } else { + $new .= lc("0x$hex"); + } + next;}; + s/^(-?\d+\.\d+E[-+]?\d+)[FL]?//i && do {$new .= $1; next;}; + s/^(\d+)\s*[LU]*//i && do {$new .= $1; next;}; + s/^("(\\"|[^"])*")// && do {$new .= $1; next;}; + s/^'((\\"|[^"])*)'// && do { + if ($curargs{$1}) { + $new .= "ord('\$$1')"; + } else { + $new .= "ord('$1')"; + } + next; + }; + # replace "sizeof(foo)" with "{foo}" + # also, remove * (C dereference operator) to avoid perl syntax + # problems. Where the %sizeof array comes from is anyone's + # guess (c2ph?), but this at least avoids fatal syntax errors. + # Behavior is undefined if sizeof() delimiters are unbalanced. + # This code was modified to able to handle constructs like this: + # sizeof(*(p)), which appear in the HP-UX 10.01 header files. + s/^sizeof\s*\(// && do { + $new .= '$sizeof'; + my $lvl = 1; # already saw one open paren + # tack { on the front, and skip it in the loop + $_ = "{" . "$_"; + my $index = 1; + # find balanced closing paren + while ($index <= length($_) && $lvl > 0) { + $lvl++ if substr($_, $index, 1) eq "("; + $lvl-- if substr($_, $index, 1) eq ")"; + $index++; + } + # tack } on the end, replacing ) + substr($_, $index - 1, 1) = "}"; + # remove pesky * operators within the sizeof argument + substr($_, 0, $index - 1) =~ s/\*//g; + next; + }; + # Eliminate typedefs + /\(([\w\s]+)[\*\s]*\)\s*[\w\(]/ && do { + my $doit = 1; + foreach (split /\s+/, $1) { # Make sure all the words are types, + unless($isatype{$_} or $_ eq 'struct' or $_ eq 'union'){ + $doit = 0; + last; + } + } + if( $doit ){ + s/\([\w\s]+[\*\s]*\)// && next; # then eliminate them. + } + }; + # struct/union member, including arrays: + s/^([_A-Z]\w*(\[[^\]]+\])?((\.|->)[_A-Z]\w*(\[[^\]]+\])?)+)//i && do { + my $id = $1; + $id =~ s/(\.|(->))([^\.\-]*)/->\{$3\}/g; + $id =~ s/\b([^\$])($joined_args)/$1\$$2/g if length($joined_args); + while($id =~ /\[\s*([^\$\&\d\]]+)\]/) { + my($index) = $1; + $index =~ s/\s//g; + if(exists($curargs{$index})) { + $index = "\$$index"; + } else { + $index = "&$index"; + } + $id =~ s/\[\s*([^\$\&\d\]]+)\]/[$index]/; + } + $new .= " (\$$id)"; + }; + s/^([_a-zA-Z]\w*)// && do { + my $id = $1; + if ($id eq 'struct' || $id eq 'union') { + s/^\s+(\w+)//; + $id .= ' ' . $1; + $isatype{$id} = 1; + } elsif ($id =~ /^((un)?signed)|(long)|(short)$/) { + while (s/^\s+(\w+)//) { $id .= ' ' . $1; } + $isatype{$id} = 1; + } + if ($curargs{$id}) { + $new .= "\$$id"; + $new .= '->' if /^[\[\{]/; + } elsif ($id eq 'defined') { + $new .= 'defined'; + } elsif (/^\s*\(/) { + s/^\s*\((\w),/("$1",/ if $id =~ /^_IO[WR]*$/i; # cheat + $new .= " &$id"; + } elsif ($isatype{$id}) { + if ($new =~ /\{\s*$/) { + $new .= "'$id'"; + } elsif ($new =~ /\(\s*$/ && /^[\s*]*\)/) { + $new =~ s/\(\s*$//; + s/^[\s*]*\)//; + } else { + $new .= q(').$id.q('); + } + } else { + if ($inif) { + if ($new =~ /defined\s*$/) { + $new .= '(&' . $id . ')'; + } elsif ($new =~ /defined\s*\($/) { + $new .= '&' . $id; + } else { + $new .= '(defined(&' . $id . ') ? &' . $id . ' : undef)'; + } + } elsif (/^\[/) { + $new .= " \$$id"; + } else { + $new .= ' &' . $id; + } + } + next; + }; + s/^(.)// && do { if ($1 ne '#') { $new .= $1; } next;}; + } +} + + +sub next_line +{ + my $file = shift; + my ($in, $out); + my $pre_sub_tri_graphs = 1; + + READ: while (not eof IN) { + $in .= ; + chomp $in; + next unless length $in; + + while (length $in) { + if ($pre_sub_tri_graphs) { + # Preprocess all tri-graphs + # including things stuck in quoted string constants. + $in =~ s/\?\?=/#/g; # | ??=| #| + $in =~ s/\?\?\!/|/g; # | ??!| || + $in =~ s/\?\?'/^/g; # | ??'| ^| + $in =~ s/\?\?\(/[/g; # | ??(| [| + $in =~ s/\?\?\)/]/g; # | ??)| ]| + $in =~ s/\?\?\-/~/g; # | ??-| ~| + $in =~ s/\?\?\//\\/g; # | ??/| \| + $in =~ s/\?\?/}/g; # | ??>| }| + } + if ($in =~ /^\#ifdef __LANGUAGE_PASCAL__/) { + # Tru64 disassembler.h evilness: mixed C and Pascal. + while () { + last if /^\#endif/; + } + $in = ""; + next READ; + } + if ($in =~ /^extern inline / && # Inlined assembler. + $^O eq 'linux' && $file =~ m!(?:^|/)asm/[^/]+\.h$!) { + while () { + last if /^}/; + } + $in = ""; + next READ; + } + if ($in =~ s/\\$//) { # \-newline + $out .= ' '; + next READ; + } elsif ($in =~ s/^([^"'\\\/]+)//) { # Passthrough + $out .= $1; + } elsif ($in =~ s/^(\\.)//) { # \... + $out .= $1; + } elsif ($in =~ /^'/) { # '... + if ($in =~ s/^('(\\.|[^'\\])*')//) { + $out .= $1; + } else { + next READ; + } + } elsif ($in =~ /^"/) { # "... + if ($in =~ s/^("(\\.|[^"\\])*")//) { + $out .= $1; + } else { + next READ; + } + } elsif ($in =~ s/^\/\/.*//) { # //... + # fall through + } elsif ($in =~ m/^\/\*/) { # /*... + # C comment removal adapted from perlfaq6: + if ($in =~ s/^\/\*[^*]*\*+([^\/*][^*]*\*+)*\///) { + $out .= ' '; + } else { # Incomplete /* */ + next READ; + } + } elsif ($in =~ s/^(\/)//) { # /... + $out .= $1; + } elsif ($in =~ s/^([^\'\"\\\/]+)//) { + $out .= $1; + } elsif ($^O eq 'linux' && + $file =~ m!(?:^|/)linux/byteorder/pdp_endian\.h$! && + $in =~ s!\'T KNOW!!) { + $out =~ s!I DON$!I_DO_NOT_KNOW!; + } else { + if ($opt_e) { + warn "Cannot parse $file:\n$in\n"; + $bad_file{$file} = 1; + $in = ''; + $out = undef; + last READ; + } else { + die "Cannot parse:\n$in\n"; + } + } + } + + last READ if $out =~ /\S/; + } + + return $out; +} + + +# Handle recursive subdirectories without getting a grotesquely big stack. +# Could this be implemented using File::Find? +sub next_file +{ + my $file; + + while (@ARGV) { + $file = shift @ARGV; + + if ($file eq '-' or -f $file or -l $file) { + return $file; + } elsif (-d $file) { + if ($opt_r) { + expand_glob($file); + } else { + print STDERR "Skipping directory '$file'\n"; + } + } elsif ($opt_a) { + return $file; + } else { + print STDERR "Skipping '$file': not a file or directory\n"; + } + } + + return undef; +} + + +# Put all the files in $directory into @ARGV for processing. +sub expand_glob +{ + my ($directory) = @_; + + $directory =~ s:/$::; + + opendir DIR, $directory; + foreach (readdir DIR) { + next if ($_ eq '.' or $_ eq '..'); + + # expand_glob() is going to be called until $ARGV[0] isn't a + # directory; so push directories, and unshift everything else. + if (-d "$directory/$_") { push @ARGV, "$directory/$_" } + else { unshift @ARGV, "$directory/$_" } + } + closedir DIR; +} + + +# Given $file, a symbolic link to a directory in the C include directory, +# make an equivalent symbolic link in $Dest_dir, if we can figure out how. +# Otherwise, just duplicate the file or directory. +sub link_if_possible +{ + my ($dirlink) = @_; + my $target = eval 'readlink($dirlink)'; + + if ($target =~ m:^\.\./: or $target =~ m:^/:) { + # The target of a parent or absolute link could leave the $Dest_dir + # hierarchy, so let's put all of the contents of $dirlink (actually, + # the contents of $target) into @ARGV; as a side effect down the + # line, $dirlink will get created as an _actual_ directory. + expand_glob($dirlink); + } else { + if (-l "$Dest_dir/$dirlink") { + unlink "$Dest_dir/$dirlink" or + print STDERR "Could not remove link $Dest_dir/$dirlink: $!\n"; + } + + if (eval 'symlink($target, "$Dest_dir/$dirlink")') { + print "Linking $target -> $Dest_dir/$dirlink\n"; + + # Make sure that the link _links_ to something: + if (! -e "$Dest_dir/$target") { + mkpath("$Dest_dir/$target", 0755) or + print STDERR "Could not create $Dest_dir/$target/\n"; + } + } else { + print STDERR "Could not symlink $target -> $Dest_dir/$dirlink: $!\n"; + } + } +} + + +# Push all #included files in $file onto our stack, except for STDIN +# and files we've already processed. +sub queue_includes_from +{ + my ($file) = @_; + my $line; + + return if ($file eq "-"); + + open HEADER, "<", $file or return; + while (defined($line =
)) { + while (/\\$/) { # Handle continuation lines + chop $line; + $line .=
; + } + + if ($line =~ /^#\s*include\s+([<"])(.*?)[>"]/) { + my ($delimiter, $new_file) = ($1, $2); + # copy the prefix in the quote syntax (#include "x.h") case + if ($delimiter eq q{"} && $file =~ m|^(.*)/|) { + $new_file = "$1/$new_file"; + } + push(@ARGV, $new_file) unless $Is_converted{$new_file}; + } + } + close HEADER; +} + + +# Determine include directories; $Config{usrinc} should be enough for (all +# non-GCC?) C compilers, but gcc uses additional include directories. +sub inc_dirs +{ + my $from_gcc = `LC_ALL=C $Config{cc} -v -E - < /dev/null 2>&1 | awk '/^#include/, /^End of search list/' | grep '^ '`; + length($from_gcc) ? (split(' ', $from_gcc), $Config{usrinc}) : ($Config{usrinc}); +} + + +# Create "_h2ph_pre.ph", if it doesn't exist or was built by a different +# version of h2ph. +sub build_preamble_if_necessary +{ + # Increment $VERSION every time this function is modified: + my $VERSION = 5; + my $preamble = "$Dest_dir/_h2ph_pre.ph"; + + # Can we skip building the preamble file? + if (-r $preamble) { + # Extract version number from first line of preamble: + open PREAMBLE, "<", $preamble or die "Cannot open $preamble: $!"; + my $line = ; + $line =~ /(\b\d+\b)/; + close PREAMBLE or die "Cannot close $preamble: $!"; + + # Don't build preamble if a compatible preamble exists: + return if $1 == $VERSION; + } + + my (%define) = _extract_cc_defines(); + + open PREAMBLE, ">", $preamble or die "Cannot open $preamble: $!"; + print PREAMBLE "# This file was created by h2ph version $VERSION\n"; + # Prevent non-portable hex constants from warning. + # + # We still produce an overflow warning if we can't represent + # a hex constant as an integer. + print PREAMBLE "no warnings qw(portable);\n"; + + foreach (sort keys %define) { + if ($opt_D) { + print PREAMBLE "# $_=$define{$_}\n"; + } + if ($define{$_} =~ /^\((.*)\)$/) { + # parenthesized value: d=(v) + $define{$_} = $1; + } + if (/^(\w+)\((\w)\)$/) { + my($macro, $arg) = ($1, $2); + my $def = $define{$_}; + $def =~ s/$arg/\$\{$arg\}/g; + print PREAMBLE < 10; + print PREAMBLE "sub $_() { $code }\n\n"; + } elsif ($define{$_} =~ /^\w+$/) { + my $def = $define{$_}; + if ($isatype{$def}) { + print PREAMBLE "sub $_() { \"$def\" }\n\n"; + } else { + print PREAMBLE "sub $_() { &$def }\n\n"; + } + } else { + print PREAMBLE "sub $_() { \"\Q$define{$_}\E\" }\n\n"; + } + } + print PREAMBLE "\n1;\n"; # avoid 'did not return a true value' when empty + close PREAMBLE or die "Cannot close $preamble: $!"; +} + + +# %Config contains information on macros that are pre-defined by the +# system's compiler. We need this information to make the .ph files +# function with perl as the .h files do with cc. +sub _extract_cc_defines +{ + my %define; + my $allsymbols = join " ", + @Config{'ccsymbols', 'cppsymbols', 'cppccsymbols'}; + + # Split compiler pre-definitions into 'key=value' pairs: + while ($allsymbols =~ /([^\s]+)=((\\\s|[^\s])+)/g) { + $define{$1} = $2; + if ($opt_D) { + print STDERR "$_: $1 -> $2\n"; + } + } + + return %define; +} + + +1; + +############################################################################## +__END__ + +=head1 NAME + +h2ph - convert .h C header files to .ph Perl header files + +=head1 SYNOPSIS + +B + +=head1 DESCRIPTION + +I +converts any C header files specified to the corresponding Perl header file +format. +It is most easily run while in /usr/include: + + cd /usr/include; h2ph * sys/* + +or + + cd /usr/include; h2ph * sys/* arpa/* netinet/* + +or + + cd /usr/include; h2ph -r -l . + +The output files are placed in the hierarchy rooted at Perl's +architecture dependent library directory. You can specify a different +hierarchy with a B<-d> switch. + +If run with no arguments, filters standard input to standard output. + +=head1 OPTIONS + +=over 4 + +=item -d destination_dir + +Put the resulting B<.ph> files beneath B, instead of +beneath the default Perl library location (C<$Config{'installsitearch'}>). + +=item -r + +Run recursively; if any of B are directories, then run I +on all files in those directories (and their subdirectories, etc.). B<-r> +and B<-a> are mutually exclusive. + +=item -a + +Run automagically; convert B, as well as any B<.h> files +which they include. This option will search for B<.h> files in all +directories which your C compiler ordinarily uses. B<-a> and B<-r> are +mutually exclusive. + +=item -l + +Symbolic links will be replicated in the destination directory. If B<-l> +is not specified, then links are skipped over. + +=item -h + +Put 'hints' in the .ph files which will help in locating problems with +I. In those cases when you B a B<.ph> file containing syntax +errors, instead of the cryptic + + [ some error condition ] at (eval mmm) line nnn + +you will see the slightly more helpful + + [ some error condition ] at filename.ph line nnn + +However, the B<.ph> files almost double in size when built using B<-h>. + +=item -e + +If an error is encountered during conversion, output file will be removed and +a warning emitted instead of terminating the conversion immediately. + +=item -D + +Include the code from the B<.h> file as a comment in the B<.ph> file. +This is primarily used for debugging I. + +=item -Q + +'Quiet' mode; don't print out the names of the files being converted. + +=back + +=head1 ENVIRONMENT + +No environment variables are used. + +=head1 FILES + + /usr/include/*.h + /usr/include/sys/*.h + +etc. + +=head1 AUTHOR + +Larry Wall + +=head1 SEE ALSO + +perl(1) + +=head1 DIAGNOSTICS + +The usual warnings if it can't read or write the files involved. + +=head1 BUGS + +Doesn't construct the %sizeof array for you. + +It doesn't handle all C constructs, but it does attempt to isolate +definitions inside evals so that you can get at the definitions +that it can translate. + +It's only intended as a rough tool. +You may need to dicker with the files produced. + +You have to run this program by hand; it's not run as part of the Perl +installation. + +Doesn't handle complicated expressions built piecemeal, a la: + + enum { + FIRST_VALUE, + SECOND_VALUE, + #ifdef ABC + THIRD_VALUE + #endif + }; + +Doesn't necessarily locate all of your C compiler's internally-defined +symbols. + +=cut + diff --git a/git/usr/bin/core_perl/h2xs b/git/usr/bin/core_perl/h2xs new file mode 100644 index 0000000000000000000000000000000000000000..cee765ea59adefc547a53ab43b21cba587479864 --- /dev/null +++ b/git/usr/bin/core_perl/h2xs @@ -0,0 +1,2207 @@ +#!/usr/bin/perl + eval 'exec /usr/bin/perl -S $0 ${1+"$@"}' + if 0; # ^ Run only under a shell + +BEGIN { pop @INC if $INC[-1] eq '.' } + +use warnings; + +=head1 NAME + +h2xs - convert .h C header files to Perl extensions + +=head1 SYNOPSIS + +B [B ...] [headerfile ... [extra_libraries]] + +B B<-h>|B<-?>|B<--help> + +=head1 DESCRIPTION + +I builds a Perl extension from C header files. The extension +will include functions which can be used to retrieve the value of any +#define statement which was in the C header files. + +The I will be used for the name of the extension. If +module_name is not supplied then the name of the first header file +will be used, with the first character capitalized. + +If the extension might need extra libraries, they should be included +here. The extension Makefile.PL will take care of checking whether +the libraries actually exist and how they should be loaded. The extra +libraries should be specified in the form -lm -lposix, etc, just as on +the cc command line. By default, the Makefile.PL will search through +the library path determined by Configure. That path can be augmented +by including arguments of the form B<-L/another/library/path> in the +extra-libraries argument. + +In spite of its name, I may also be used to create a skeleton pure +Perl module. See the B<-X> option. + +=head1 OPTIONS + +=over 5 + +=item B<-A>, B<--omit-autoload> + +Omit all autoload facilities. This is the same as B<-c> but also +removes the S> statement from the .pm file. + +=item B<-B>, B<--beta-version> + +Use an alpha/beta style version number. Causes version number to +be "0.00_01" unless B<-v> is specified. + +=item B<-C>, B<--omit-changes> + +Omits creation of the F file, and adds a HISTORY section to +the POD template. + +=item B<-F>, B<--cpp-flags>=I + +Additional flags to specify to C preprocessor when scanning header for +function declarations. Writes these options in the generated F +too. + +=item B<-M>, B<--func-mask>=I + +selects functions/macros to process. + +=item B<-O>, B<--overwrite-ok> + +Allows a pre-existing extension directory to be overwritten. + +=item B<-P>, B<--omit-pod> + +Omit the autogenerated stub POD section. + +=item B<-X>, B<--omit-XS> + +Omit the XS portion. Used to generate a skeleton pure Perl module. +C<-c> and C<-f> are implicitly enabled. + +=item B<-a>, B<--gen-accessors> + +Generate an accessor method for each element of structs and unions. The +generated methods are named after the element name; will return the current +value of the element if called without additional arguments; and will set +the element to the supplied value (and return the new value) if called with +an additional argument. Embedded structures and unions are returned as a +pointer rather than the complete structure, to facilitate chained calls. + +These methods all apply to the Ptr type for the structure; additionally +two methods are constructed for the structure type itself, C<_to_ptr> +which returns a Ptr type pointing to the same structure, and a C +method to construct and return a new structure, initialised to zeroes. + +=item B<-b>, B<--compat-version>=I + +Generates a .pm file which is backwards compatible with the specified +perl version. + +For versions < 5.6.0, the changes are. + - no use of 'our' (uses 'use vars' instead) + - no 'use warnings' + +Specifying a compatibility version higher than the version of perl you +are using to run h2xs will have no effect. If unspecified h2xs will default +to compatibility with the version of perl you are using to run h2xs. + +=item B<-c>, B<--omit-constant> + +Omit C from the .xs file and corresponding specialised +C from the .pm file. + +=item B<-d>, B<--debugging> + +Turn on debugging messages. + +=item B<-e>, B<--omit-enums>=[I] + +If I is not given, skip all constants that are defined in +a C enumeration. Otherwise skip only those constants that are defined in an +enum whose name matches I. + +Since I is optional, make sure that this switch is followed +by at least one other switch if you omit I and have some +pending arguments such as header-file names. This is ok: + + h2xs -e -n Module::Foo foo.h + +This is not ok: + + h2xs -n Module::Foo -e foo.h + +In the latter, foo.h is taken as I. + +=item B<-f>, B<--force> + +Allows an extension to be created for a header even if that header is +not found in standard include directories. + +=item B<-g>, B<--global> + +Include code for safely storing static data in the .xs file. +Extensions that do no make use of static data can ignore this option. + +=item B<-h>, B<-?>, B<--help> + +Print the usage, help and version for this h2xs and exit. + +=item B<-k>, B<--omit-const-func> + +For function arguments declared as C, omit the const attribute in the +generated XS code. + +=item B<-m>, B<--gen-tied-var> + +B: for each variable declared in the header file(s), declare +a perl variable of the same name magically tied to the C variable. + +=item B<-n>, B<--name>=I + +Specifies a name to be used for the extension, e.g., S<-n RPC::DCE> + +=item B<-o>, B<--opaque-re>=I + +Use "opaque" data type for the C types matched by the regular +expression, even if these types are C-equivalent to types +from typemaps. Should not be used without B<-x>. + +This may be useful since, say, types which are C-equivalent +to integers may represent OS-related handles, and one may want to work +with these handles in OO-way, as in C<$handle-Edo_something()>. +Use C<-o .> if you want to handle all the Ced types as opaque +types. + +The type-to-match is whitewashed (except for commas, which have no +whitespace before them, and multiple C<*> which have no whitespace +between them). + +=item B<-p>, B<--remove-prefix>=I + +Specify a prefix which should be removed from the Perl function names, +e.g., S<-p sec_rgy_> This sets up the XS B keyword and removes +the prefix from functions that are autoloaded via the C +mechanism. + +=item B<-s>, B<--const-subs>=I + +Create a perl subroutine for the specified macros rather than autoload +with the constant() subroutine. These macros are assumed to have a +return type of B, e.g., +S<-s sec_rgy_wildcard_name,sec_rgy_wildcard_sid>. + +=item B<-t>, B<--default-type>=I + +Specify the internal type that the constant() mechanism uses for macros. +The default is IV (signed integer). Currently all macros found during the +header scanning process will be assumed to have this type. Future versions +of C may gain the ability to make educated guesses. + +=item B<--use-new-tests> + +When B<--compat-version> (B<-b>) is present the generated tests will use +C rather than C which is the default for versions before +5.6.2. C will be added to PREREQ_PM in the generated +C. + +=item B<--use-old-tests> + +Will force the generation of test code that uses the older C module. + +=item B<--skip-exporter> + +Do not use C and/or export any symbol. + +=item B<--skip-ppport> + +Do not use C: no portability to older version. + +=item B<--skip-autoloader> + +Do not use the module C; but keep the constant() function +and C for constants. + +=item B<--skip-strict> + +Do not use the pragma C. + +=item B<--skip-warnings> + +Do not use the pragma C. + +=item B<-v>, B<--version>=I + +Specify a version number for this extension. This version number is added +to the templates. The default is 0.01, or 0.00_01 if C<-B> is specified. +The version specified should be numeric. + +=item B<-x>, B<--autogen-xsubs> + +Automatically generate XSUBs basing on function declarations in the +header file. The package C should be installed. If this +option is specified, the name of the header file may look like +C. In this case NAME1 is used instead of the specified +string, but XSUBs are emitted only for the declarations included from +file NAME2. + +Note that some types of arguments/return-values for functions may +result in XSUB-declarations/typemap-entries which need +hand-editing. Such may be objects which cannot be converted from/to a +pointer (like C), pointers to functions, or arrays. See +also the section on L>. + +=back + +=head1 EXAMPLES + + + # Default behavior, extension is Rusers + h2xs rpcsvc/rusers + + # Same, but extension is RUSERS + h2xs -n RUSERS rpcsvc/rusers + + # Extension is rpcsvc::rusers. Still finds + h2xs rpcsvc::rusers + + # Extension is ONC::RPC. Still finds + h2xs -n ONC::RPC rpcsvc/rusers + + # Without constant() or AUTOLOAD + h2xs -c rpcsvc/rusers + + # Creates templates for an extension named RPC + h2xs -cfn RPC + + # Extension is ONC::RPC. + h2xs -cfn ONC::RPC + + # Extension is a pure Perl module with no XS code. + h2xs -X My::Module + + # Extension is Lib::Foo which works at least with Perl5.005_03. + # Constants are created for all #defines and enums h2xs can find + # in foo.h. + h2xs -b 5.5.3 -n Lib::Foo foo.h + + # Extension is Lib::Foo which works at least with Perl5.005_03. + # Constants are created for all #defines but only for enums + # whose names do not start with 'bar_'. + h2xs -b 5.5.3 -e '^bar_' -n Lib::Foo foo.h + + # Makefile.PL will look for library -lrpc in + # additional directory /opt/net/lib + h2xs rpcsvc/rusers -L/opt/net/lib -lrpc + + # Extension is DCE::rgynbase + # prefix "sec_rgy_" is dropped from perl function names + h2xs -n DCE::rgynbase -p sec_rgy_ dce/rgynbase + + # Extension is DCE::rgynbase + # prefix "sec_rgy_" is dropped from perl function names + # subroutines are created for sec_rgy_wildcard_name and + # sec_rgy_wildcard_sid + h2xs -n DCE::rgynbase -p sec_rgy_ \ + -s sec_rgy_wildcard_name,sec_rgy_wildcard_sid dce/rgynbase + + # Make XS without defines in perl.h, but with function declarations + # visible from perl.h. Name of the extension is perl1. + # When scanning perl.h, define -DEXT=extern -DdEXT= -DINIT(x)= + # Extra backslashes below because the string is passed to shell. + # Note that a directory with perl header files would + # be added automatically to include path. + h2xs -xAn perl1 -F "-DEXT=extern -DdEXT= -DINIT\(x\)=" perl.h + + # Same with function declaration in proto.h as visible from perl.h. + h2xs -xAn perl2 perl.h,proto.h + + # Same but select only functions which match /^av_/ + h2xs -M '^av_' -xAn perl2 perl.h,proto.h + + # Same but treat SV* etc as "opaque" types + h2xs -o '^[S]V \*$' -M '^av_' -xAn perl2 perl.h,proto.h + +=head2 Extension based on F<.h> and F<.c> files + +Suppose that you have some C files implementing some functionality, +and the corresponding header files. How to create an extension which +makes this functionality accessible in Perl? The example below +assumes that the header files are F and +I, and you want the perl module be named as +C. If you need some preprocessor directives and/or +linking with external libraries, see the flags C<-F>, C<-L> and C<-l> +in L<"OPTIONS">. + +=over + +=item Find the directory name + +Start with a dummy run of h2xs: + + h2xs -Afn Ext::Ension + +The only purpose of this step is to create the needed directories, and +let you know the names of these directories. From the output you can +see that the directory for the extension is F. + +=item Copy C files + +Copy your header files and C files to this directory F. + +=item Create the extension + +Run h2xs, overwriting older autogenerated files: + + h2xs -Oxan Ext::Ension interface_simple.h interface_hairy.h + +h2xs looks for header files I changing to the extension +directory, so it will find your header files OK. + +=item Archive and test + +As usual, run + + cd Ext/Ension + perl Makefile.PL + make dist + make + make test + +=item Hints + +It is important to do C as early as possible. This way you +can easily merge(1) your changes to autogenerated files if you decide +to edit your C<.h> files and rerun h2xs. + +Do not forget to edit the documentation in the generated F<.pm> file. + +Consider the autogenerated files as skeletons only, you may invent +better interfaces than what h2xs could guess. + +Consider this section as a guideline only, some other options of h2xs +may better suit your needs. + +=back + +=head1 ENVIRONMENT + +No environment variables are used. + +=head1 AUTHOR + +Larry Wall and others + +=head1 SEE ALSO + +L, L, L, and L. + +=head1 DIAGNOSTICS + +The usual warnings if it cannot read or write the files involved. + +=head1 LIMITATIONS of B<-x> + +F would not distinguish whether an argument to a C function +which is of the form, say, C, is an input, output, or +input/output parameter. In particular, argument declarations of the +form + + int + foo(n) + int *n + +should be better rewritten as + + int + foo(n) + int &n + +if C is an input parameter. + +Additionally, F has no facilities to intuit that a function + + int + foo(addr,l) + char *addr + int l + +takes a pair of address and length of data at this address, so it is better +to rewrite this function as + + int + foo(sv) + SV *addr + PREINIT: + STRLEN len; + char *s; + CODE: + s = SvPV(sv,len); + RETVAL = foo(s, len); + OUTPUT: + RETVAL + +or alternately + + static int + my_foo(SV *sv) + { + STRLEN len; + char *s = SvPV(sv,len); + + return foo(s, len); + } + + MODULE = foo PACKAGE = foo PREFIX = my_ + + int + foo(sv) + SV *sv + +See L and L for additional details. + +=cut + +# ' # Grr +use strict; + + +my( $H2XS_VERSION ) = ' $Revision: 1.23 $ ' =~ /\$Revision:\s+([^\s]+)/; +my $TEMPLATE_VERSION = '0.01'; +my @ARGS = @ARGV; +my $compat_version = $]; + +use Getopt::Long; +use Config; +use Text::Wrap; +$Text::Wrap::huge = 'overflow'; +$Text::Wrap::columns = 80; +use ExtUtils::Constant qw (WriteConstants WriteMakefileSnippet autoload); +use File::Compare; +use File::Path; + +sub usage { + warn "@_\n" if @_; + die <. + --skip-strict Do not use the pragma C. + --skip-warnings Do not use the pragma C. + -v, --version Specify a version number for this extension. + -x, --autogen-xsubs Autogenerate XSUBs using C::Scan. + --use-xsloader Use XSLoader in backward compatible modules (ignored + when used with -X). + +extra_libraries + are any libraries that might be needed for loading the + extension, e.g. -lm would try to link in the math library. +EOFUSAGE +} + +my ($opt_A, + $opt_B, + $opt_C, + $opt_F, + $opt_M, + $opt_O, + $opt_P, + $opt_X, + $opt_a, + $opt_c, + $opt_d, + $opt_e, + $opt_f, + $opt_g, + $opt_h, + $opt_k, + $opt_m, + $opt_n, + $opt_o, + $opt_p, + $opt_s, + $opt_v, + $opt_x, + $opt_b, + $opt_t, + $new_test, + $old_test, + $skip_exporter, + $skip_ppport, + $skip_autoloader, + $skip_strict, + $skip_warnings, + $use_xsloader + ); + +Getopt::Long::Configure('bundling'); +Getopt::Long::Configure('pass_through'); + +my %options = ( + 'omit-autoload|A' => \$opt_A, + 'beta-version|B' => \$opt_B, + 'omit-changes|C' => \$opt_C, + 'cpp-flags|F=s' => \$opt_F, + 'func-mask|M=s' => \$opt_M, + 'overwrite_ok|O' => \$opt_O, + 'omit-pod|P' => \$opt_P, + 'omit-XS|X' => \$opt_X, + 'gen-accessors|a' => \$opt_a, + 'compat-version|b=s' => \$opt_b, + 'omit-constant|c' => \$opt_c, + 'debugging|d' => \$opt_d, + 'omit-enums|e:s' => \$opt_e, + 'force|f' => \$opt_f, + 'global|g' => \$opt_g, + 'help|h|?' => \$opt_h, + 'omit-const-func|k' => \$opt_k, + 'gen-tied-var|m' => \$opt_m, + 'name|n=s' => \$opt_n, + 'opaque-re|o=s' => \$opt_o, + 'remove-prefix|p=s' => \$opt_p, + 'const-subs|s=s' => \$opt_s, + 'default-type|t=s' => \$opt_t, + 'version|v=s' => \$opt_v, + 'autogen-xsubs|x' => \$opt_x, + 'use-new-tests' => \$new_test, + 'use-old-tests' => \$old_test, + 'skip-exporter' => \$skip_exporter, + 'skip-ppport' => \$skip_ppport, + 'skip-autoloader' => \$skip_autoloader, + 'skip-warnings' => \$skip_warnings, + 'skip-strict' => \$skip_strict, + 'use-xsloader' => \$use_xsloader, + ); + +GetOptions(%options) || usage; + +usage if $opt_h; + +if( $opt_b ){ + usage "You cannot use -b and -m at the same time.\n" if ($opt_b && $opt_m); + $opt_b =~ /^v?(\d+)\.(\d+)\.(\d+)/ || + usage "You must provide the backwards compatibility version in X.Y.Z form. " + . "(i.e. 5.5.0)\n"; + my ($maj,$min,$sub) = ($1,$2,$3); + if ($maj < 5 || ($maj == 5 && $min < 6)) { + $compat_version = + $sub ? sprintf("%d.%03d%02d",$maj,$min,$sub) : + sprintf("%d.%03d", $maj,$min); + } else { + $compat_version = sprintf("%d.%03d%03d",$maj,$min,$sub); + } +} else { + my ($maj,$min,$sub) = $compat_version =~ /(\d+)\.(\d\d\d)(\d*)/; + $sub ||= 0; + warn sprintf <<'EOF', $maj,$min,$sub; +Defaulting to backwards compatibility with perl %d.%d.%d +If you intend this module to be compatible with earlier perl versions, please +specify a minimum perl version with the -b option. + +EOF +} + +if( $opt_B ){ + $TEMPLATE_VERSION = '0.00_01'; +} + +if( $opt_v ){ + $TEMPLATE_VERSION = $opt_v; + + # check if it is numeric + my $temp_version = $TEMPLATE_VERSION; + my $beta_version = $temp_version =~ s/(\d)_(\d\d)/$1$2/; + my $notnum; + { + local $SIG{__WARN__} = sub { $notnum = 1 }; + use warnings 'numeric'; + $temp_version = 0+$temp_version; + } + + if ($notnum) { + my $module = $opt_n || 'Your::Module'; + warn <<"EOF"; +You have specified a non-numeric version. Unless you supply an +appropriate VERSION class method, users may not be able to specify a +minimum required version with C. + +EOF + } + else { + $opt_B = $beta_version; + } +} + +# -A implies -c. +$skip_autoloader = $opt_c = 1 if $opt_A; + +# -X implies -c and -f +$opt_c = $opt_f = 1 if $opt_X; + +$opt_t ||= 'IV'; + +my %const_xsub; +%const_xsub = map { $_,1 } split(/,+/, $opt_s) if $opt_s; + +my $extralibs = ''; + +my @path_h; + +while (my $arg = shift) { + if ($arg =~ /^-l/i) { + $extralibs .= "$arg "; + next; + } + last if $extralibs; + push(@path_h, $arg); +} + +usage "Must supply header file or module name\n" + unless (@path_h or $opt_n); + +my $fmask; +my $tmask; + +$fmask = qr{$opt_M} if defined $opt_M; +$tmask = qr{$opt_o} if defined $opt_o; +my $tmask_all = $tmask && $opt_o eq '.'; + +if ($opt_x) { + eval {require C::Scan; 1} + or die <= 0.70 + or die <curdir(), $Config{usrinc}, + (split / +/, $Config{locincpth} // ""), '/usr/include'); + } + foreach my $path_h (@path_h) { + $name ||= $path_h; + $module ||= do { + $name =~ s/\.h$//; + if ( $name !~ /::/ ) { + $name =~ s#^.*/##; + $name = "\u$name"; + } + $name; + }; + + if( $path_h =~ s#::#/#g && $opt_n ){ + warn "Nesting of headerfile ignored with -n\n"; + } + $path_h .= ".h" unless $path_h =~ /\.h$/; + my $fullpath = $path_h; + $path_h =~ s/,.*$// if $opt_x; + $fullpath{$path_h} = $fullpath; + + # Minor trickery: we can't chdir() before we processed the headers + # (so know the name of the extension), but the header may be in the + # extension directory... + my $tmp_path_h = $path_h; + my $rel_path_h = $path_h; + my @dirs = @paths; + if (not -f $path_h) { + my $found; + for my $dir (@paths) { + $found++, last + if -f ($path_h = File::Spec->catfile($dir, $tmp_path_h)); + } + if ($found) { + $rel_path_h = $path_h; + $fullpath{$path_h} = $fullpath; + } else { + (my $epath = $module) =~ s,::,/,g; + $epath = File::Spec->catdir('ext', $epath) if -d 'ext'; + $rel_path_h = File::Spec->catfile($epath, $tmp_path_h); + $path_h = $tmp_path_h; # Used during -x + push @dirs, $epath; + } + } + + if (!$opt_c) { + die "Can't find $tmp_path_h in @dirs\n" + if ( ! $opt_f && ! -f "$rel_path_h" ); + # Scan the header file (we should deal with nested header files) + # Record the names of simple #define constants into const_names + # Function prototypes are processed below. + open(CH, "<", "$rel_path_h") || die "Can't open $rel_path_h: $!\n"; + defines: + while () { + if ($pre_sub_tri_graphs) { + # Preprocess all tri-graphs + # including things stuck in quoted string constants. + s/\?\?=/#/g; # | ??=| #| + s/\?\?\!/|/g; # | ??!| || + s/\?\?'/^/g; # | ??'| ^| + s/\?\?\(/[/g; # | ??(| [| + s/\?\?\)/]/g; # | ??)| ]| + s/\?\?\-/~/g; # | ??-| ~| + s/\?\?\//\\/g; # | ??/| \| + s/\?\?/}/g; # | ??>| }| + } + if (/^[ \t]*#[ \t]*define\s+([\$\w]+)\b(?!\()\s*(?=[^"\s])(.*)/) { + my $def = $1; + my $rest = $2; + $rest =~ s!/\*.*?(\*/|\n)|//.*!!g; # Remove comments + $rest =~ s/^\s+//; + $rest =~ s/\s+$//; + if ($rest eq '') { + print("Skip empty $def\n") if $opt_d; + next defines; + } + # Cannot do: (-1) and ((LHANDLE)3) are OK: + #print("Skip non-wordy $def => $rest\n"), + # next defines if $rest =~ /[^\w\$]/; + if ($rest =~ /"/) { + print("Skip stringy $def => $rest\n") if $opt_d; + next defines; + } + print "Matched $_ ($def)\n" if $opt_d; + $seen_define{$def} = $rest; + $_ = $def; + next if /^_.*_h_*$/i; # special case, but for what? + if (defined $opt_p) { + if (!/^$opt_p(\d)/) { + ++$prefix{$_} if s/^$opt_p//; + } + else { + warn "can't remove $opt_p prefix from '$_'!\n"; + } + } + $prefixless{$def} = $_; + if (!$fmask or /$fmask/) { + print "... Passes mask of -M.\n" if $opt_d and $fmask; + $const_names{$_}++; + } + } + } + if (defined $opt_e and !$opt_e) { + close(CH); + } + else { + # Work from miniperl too - on "normal" systems + my $SEEK_SET = eval 'use Fcntl qw/SEEK_SET/; SEEK_SET' || 0; + seek CH, 0, $SEEK_SET; + my $src = do { local $/; }; + close CH; + no warnings 'uninitialized'; + + # Remove C and C++ comments + $src =~ s#/\*[^*]*\*+([^/*][^*]*\*+)*/|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)#$2#gs; + $src =~ s#//.*$##gm; + + while ($src =~ /\benum\s*([\w_]*)\s*\{\s([^}]+)\}/gsc) { + my ($enum_name, $enum_body) = ($1, $2); + # skip enums matching $opt_e + next if $opt_e && $enum_name =~ /$opt_e/; + my $val = 0; + for my $item (split /,/, $enum_body) { + next if $item =~ /\A\s*\Z/; + my ($key, $declared_val) = $item =~ /(\w+)\s*(?:=\s*(.*))?/; + $val = defined($declared_val) && length($declared_val) ? $declared_val : 1 + $val; + $seen_define{$key} = $val; + $const_names{$key} = { name => $key, macro => 1 }; + } + } # while (...) + } # if (!defined $opt_e or $opt_e) + } + } +} + +# Save current directory so that C::Scan can use it +my $cwd = File::Spec->rel2abs( File::Spec->curdir ); + +# As Ilya suggested, use a name that contains - and then it can't clash with +# the names of any packages. A directory 'fallback' will clash with any +# new pragmata down the fallback:: tree, but that seems unlikely. +my $constscfname = 'const-c.inc'; +my $constsxsfname = 'const-xs.inc'; +my $fallbackdirname = 'fallback'; + +my $ext = chdir 'ext' ? 'ext/' : ''; + +my @modparts = split(/::/,$module); +my $modpname = join('-', @modparts); +my $modfname = pop @modparts; +my $modpmdir = join '/', 'lib', @modparts; +my $modpmname = join '/', $modpmdir, $modfname.'.pm'; + +if ($opt_O) { + warn "Overwriting existing $ext$modpname!!!\n" if -e $modpname; +} +else { + die "Won't overwrite existing $ext$modpname\n" if -e $modpname; +} +-d "$modpname" || mkpath([$modpname], 0, 0775); +chdir($modpname) || die "Can't chdir $ext$modpname: $!\n"; + +my %types_seen; +my %std_types; +my $fdecls = []; +my $fdecls_parsed = []; +my $typedef_rex; +my %typedefs_pre; +my %known_fnames; +my %structs; + +my @fnames; +my @fnames_no_prefix; +my %vdecl_hash; +my @vdecls; + +if( ! $opt_X ){ # use XS, unless it was disabled + unless ($skip_ppport) { + require Devel::PPPort; + warn "Writing $ext$modpname/ppport.h\n"; + Devel::PPPort::WriteFile('ppport.h') + || die "Can't create $ext$modpname/ppport.h: $!\n"; + } + open(XS, ">", "$modfname.xs") || die "Can't create $ext$modpname/$modfname.xs: $!\n"; + if ($opt_x) { + warn "Scanning typemaps...\n"; + get_typemap(); + my @td; + my @good_td; + my $addflags = $opt_F || ''; + + foreach my $filename (@path_h) { + my $c; + my $filter; + + if ($fullpath{$filename} =~ /,/) { + $filename = $`; + $filter = $'; + } + warn "Scanning $filename for functions...\n"; + my @styles = $Config{gccversion} ? qw(C++ C9X GNU) : qw(C++ C9X); + $c = C::Scan->new('filename' => $filename, 'filename_filter' => $filter, + 'add_cppflags' => $addflags, 'c_styles' => \@styles); + $c->set('includeDirs' => ["$Config::Config{archlib}/CORE", $cwd]); + + $c->get('keywords')->{'__restrict'} = 1; + + push @$fdecls_parsed, @{ $c->get('parsed_fdecls') }; + push(@$fdecls, @{$c->get('fdecls')}); + + push @td, @{$c->get('typedefs_maybe')}; + if ($opt_a) { + my $structs = $c->get('typedef_structs'); + @structs{keys %$structs} = values %$structs; + } + + if ($opt_m) { + %vdecl_hash = %{ $c->get('vdecl_hash') }; + @vdecls = sort keys %vdecl_hash; + for (local $_ = 0; $_ < @vdecls; ++$_) { + my $var = $vdecls[$_]; + my($type, $post) = @{ $vdecl_hash{$var} }; + if (defined $post) { + warn "Can't handle variable '$type $var $post', skipping.\n"; + splice @vdecls, $_, 1; + redo; + } + $type = normalize_type($type); + $vdecl_hash{$var} = $type; + } + } + + unless ($tmask_all) { + warn "Scanning $filename for typedefs...\n"; + my $td = $c->get('typedef_hash'); + # eval {require 'dumpvar.pl'; ::dumpValue($td)} or warn $@ if $opt_d; + my @f_good_td = grep $td->{$_}[1] eq '', keys %$td; + push @good_td, @f_good_td; + @typedefs_pre{@f_good_td} = map $_->[0], @$td{@f_good_td}; + } + } + { local $" = '|'; + $typedef_rex = qr(\b(?[$i][1] =~ /$fmask/; # [1] is NAME + push @good, $i; + print "... Function $fdecls_parsed->[$i][1] passes -M mask.\n" + if $opt_d; + } + $fdecls = [@$fdecls[@good]]; + $fdecls_parsed = [@$fdecls_parsed[@good]]; + } + @fnames = sort map $_->[1], @$fdecls_parsed; # 1 is NAME + # Sort declarations: + { + my %h = map( ($_->[1], $_), @$fdecls_parsed); + $fdecls_parsed = [ @h{@fnames} ]; + } + @fnames_no_prefix = @fnames; + @fnames_no_prefix + = sort map { ++$prefix{$_} if s/^$opt_p(?!\d)//; $_ } @fnames_no_prefix + if defined $opt_p; + # Remove macros which expand to typedefs + print "Typedefs are @td.\n" if $opt_d; + my %td = map {($_, $_)} @td; + # Add some other possible but meaningless values for macros + for my $k (qw(char double float int long short unsigned signed void)) { + $td{"$_$k"} = "$_$k" for ('', 'signed ', 'unsigned '); + } + # eval {require 'dumpvar.pl'; ::dumpValue( [\@td, \%td] ); 1} or warn $@; + my $n = 0; + my %bad_macs; + while (keys %td > $n) { + $n = keys %td; + my ($k, $v); + while (($k, $v) = each %seen_define) { + # print("found '$k'=>'$v'\n"), + $bad_macs{$k} = $td{$k} = $td{$v} if exists $td{$v}; + } + } + # Now %bad_macs contains names of bad macros + for my $k (keys %bad_macs) { + delete $const_names{$prefixless{$k}}; + print "Ignoring macro $k which expands to a typedef name '$bad_macs{$k}'\n" if $opt_d; + } + } +} +my (@const_specs, @const_names); + +for (sort(keys(%const_names))) { + my $v = $const_names{$_}; + + push(@const_specs, ref($v) ? $v : $_); + push(@const_names, $_); +} + +-d $modpmdir || mkpath([$modpmdir], 0, 0775); +open(PM, ">", "$modpmname") || die "Can't create $ext$modpname/$modpmname: $!\n"; + +$" = "\n\t"; +warn "Writing $ext$modpname/$modpmname\n"; + +print PM <<"END"; +package $module; + +use $compat_version; +END + +print PM <<"END" unless $skip_strict; +use strict; +END + +print PM "use warnings;\n" unless $skip_warnings or $compat_version < 5.006; + +unless( $opt_X || $opt_c || $opt_A ){ + # we'll have an AUTOLOAD(), and it will have $AUTOLOAD and + # will want Carp. + print PM <<'END'; +use Carp; +END +} + +print PM <<'END' unless $skip_exporter; + +require Exporter; +END + +my $use_Dyna = (not $opt_X and $compat_version < 5.006 and not $use_xsloader); +print PM <<"END" if $use_Dyna; # use DynaLoader, unless XS was disabled +require DynaLoader; +END + + +# Are we using AutoLoader or not? +unless ($skip_autoloader) { # no autoloader whatsoever. + unless ($opt_c) { # we're doing the AUTOLOAD + print PM "use AutoLoader;\n"; + } + else { + print PM "use AutoLoader qw(AUTOLOAD);\n" + } +} + +if ( $compat_version < 5.006 ) { + my $vars = '$VERSION @ISA'; + $vars .= ' @EXPORT @EXPORT_OK %EXPORT_TAGS' unless $skip_exporter; + $vars .= ' $AUTOLOAD' unless $opt_X || $opt_c || $opt_A; + $vars .= ' $XS_VERSION' if $opt_B && !$opt_X; + print PM "use vars qw($vars);"; +} + +# Determine @ISA. +my @modISA; +push @modISA, 'Exporter' unless $skip_exporter; +push @modISA, 'DynaLoader' if $use_Dyna; # no XS +my $myISA = "our \@ISA = qw(@modISA);"; +$myISA =~ s/^our // if $compat_version < 5.006; + +print PM "\n$myISA\n\n"; + +my @exported_names = (@const_names, @fnames_no_prefix, map '$'.$_, @vdecls); + +my $tmp=''; +$tmp .= <<"END" unless $skip_exporter; +# Items to export into callers namespace by default. Note: do not export +# names by default without a very good reason. Use EXPORT_OK instead. +# Do not simply export all your public functions/methods/constants. + +# This allows declaration use $module ':all'; +# If you do not need this, moving things directly into \@EXPORT or \@EXPORT_OK +# will save memory. +our %EXPORT_TAGS = ( 'all' => [ qw( + @exported_names +) ] ); + +our \@EXPORT_OK = ( \@{ \$EXPORT_TAGS{'all'} } ); + +our \@EXPORT = qw( + @const_names +); + +END + +$tmp .= "our \$VERSION = '$TEMPLATE_VERSION';\n"; +if ($opt_B) { + $tmp .= "our \$XS_VERSION = \$VERSION;\n" unless $opt_X; + $tmp .= "\$VERSION = eval \$VERSION; # see L\n"; +} +$tmp .= "\n"; + +$tmp =~ s/^our //mg if $compat_version < 5.006; +print PM $tmp; + +if (@vdecls) { + printf PM "our(@{[ join ', ', map '$'.$_, @vdecls ]});\n\n"; +} + + +print PM autoload ($module, $compat_version) unless $opt_c or $opt_X; + +if( ! $opt_X ){ # print bootstrap, unless XS is disabled + if ($use_Dyna) { + $tmp = <<"END"; +bootstrap $module \$VERSION; +END + } else { + $tmp = <<"END"; +require XSLoader; +XSLoader::load('$module', \$VERSION); +END + } + $tmp =~ s:\$VERSION:\$XS_VERSION:g if $opt_B; + print PM $tmp; +} + +# tying the variables can happen only after bootstrap +if (@vdecls) { + printf PM <))[0,6]; + if (defined $username && defined $author) { + $author =~ s/,.*$//; # in case of sub fields + my $domain = $Config{'mydomain'}; + $domain =~ s/^\.//; + $email = "$username\@$domain"; + } + }; + +$author =~ s/'/\\'/g if defined $author; +$author ||= "A. U. Thor"; +$email ||= 'a.u.thor@a.galaxy.far.far.away'; + +$licence = sprintf << "DEFAULT", $^V; +Copyright (C) ${\(1900 + (localtime) [5])} by $author + +This library is free software; you can redistribute it and/or modify +it under the same terms as Perl itself, either Perl version %vd or, +at your option, any later version of Perl 5 you may have available. +DEFAULT + +my $revhist = ''; +$revhist = < should be removed. +# +#EOD + $exp_doc .= <${email}E +# +#=head1 COPYRIGHT AND LICENSE +# +$licence_hash +# +#=cut +END + +$pod =~ s/^\#//gm unless $opt_P; +print PM $pod unless $opt_P; + +close PM; + + +if( ! $opt_X ){ # print XS, unless it is disabled +warn "Writing $ext$modpname/$modfname.xs\n"; + +print XS <<"END"; +#define PERL_NO_GET_CONTEXT +#include "EXTERN.h" +#include "perl.h" +#include "XSUB.h" + +END + +print XS <<"END" unless $skip_ppport; +#include "ppport.h" + +END + +if( @path_h ){ + foreach my $path_h (@path_h_ini) { + my($h) = $path_h; + $h =~ s#^/usr/include/##; + if ($^O eq 'VMS') { $h =~ s#.*vms\]#sys/# or $h =~ s#.*[:>\]]##; } + print XS qq{#include <$h>\n}; + } + print XS "\n"; +} + +print XS <<"END" if $opt_g; + +/* Global Data */ + +#define MY_CXT_KEY "${module}::_guts" XS_VERSION + +typedef struct { + /* Put Global Data in here */ + int dummy; /* you can access this elsewhere as MY_CXT.dummy */ +} my_cxt_t; + +START_MY_CXT + +END + +my %pointer_typedefs; +my %struct_typedefs; + +sub td_is_pointer { + my $type = shift; + my $out = $pointer_typedefs{$type}; + return $out if defined $out; + my $otype = $type; + $out = ($type =~ /\*$/); + # This converts only the guys which do not have trailing part in the typedef + if (not $out + and $typedef_rex and $type =~ s/($typedef_rex)/$typedefs_pre{$1}/go) { + $type = normalize_type($type); + print "Is-Pointer: Type mutation via typedefs: $otype ==> $type\n" + if $opt_d; + $out = td_is_pointer($type); + } + return ($pointer_typedefs{$otype} = $out); +} + +sub td_is_struct { + my $type = shift; + my $out = $struct_typedefs{$type}; + return $out if defined $out; + my $otype = $type; + $out = ($type =~ /^(struct|union)\b/) && !td_is_pointer($type); + # This converts only the guys which do not have trailing part in the typedef + if (not $out + and $typedef_rex and $type =~ s/($typedef_rex)/$typedefs_pre{$1}/go) { + $type = normalize_type($type); + print "Is-Struct: Type mutation via typedefs: $otype ==> $type\n" + if $opt_d; + $out = td_is_struct($type); + } + return ($struct_typedefs{$otype} = $out); +} + +print_tievar_subs(\*XS, $_, $vdecl_hash{$_}) for @vdecls; + +if( ! $opt_c ) { + # We write the "sample" files used when this module is built by perl without + # ExtUtils::Constant. + # h2xs will later check that these are the same as those generated by the + # code embedded into Makefile.PL + unless (-d $fallbackdirname) { + mkdir "$fallbackdirname" or die "Cannot mkdir $fallbackdirname: $!\n"; + } + warn "Writing $ext$modpname/$fallbackdirname/$constscfname\n"; + warn "Writing $ext$modpname/$fallbackdirname/$constsxsfname\n"; + my $cfallback = File::Spec->catfile($fallbackdirname, $constscfname); + my $xsfallback = File::Spec->catfile($fallbackdirname, $constsxsfname); + WriteConstants ( C_FILE => $cfallback, + XS_FILE => $xsfallback, + DEFAULT_TYPE => $opt_t, + NAME => $module, + NAMES => \@const_specs, + ); + print XS "#include \"$constscfname\"\n"; +} + + +my $prefix = defined $opt_p ? "PREFIX = $opt_p" : ''; + +# Now switch from C to XS by issuing the first MODULE declaration: +print XS <<"END"; + +MODULE = $module PACKAGE = $module $prefix + +END + +# If a constant() function was #included then output a corresponding +# XS declaration: +print XS "INCLUDE: $constsxsfname\n" unless $opt_c; + +print XS <<"END" if $opt_g; + +BOOT: +{ + MY_CXT_INIT; + /* If any of the fields in the my_cxt_t struct need + to be initialised, do it here. + */ +} + +END + +foreach (sort keys %const_xsub) { + print XS <<"END"; +char * +$_() + + CODE: +#ifdef $_ + RETVAL = $_; +#else + croak("Your vendor has not defined the $module macro $_"); +#endif + + OUTPUT: + RETVAL + +END +} + +my %seen_decl; +my %typemap; + +sub print_decl { + my $fh = shift; + my $decl = shift; + my ($type, $name, $args) = @$decl; + return if $seen_decl{$name}++; # Need to do the same for docs as well? + + my @argnames = map {$_->[1]} @$args; + my @argtypes = map { normalize_type( $_->[0], 1 ) } @$args; + if ($opt_k) { + s/^\s*const\b\s*// for @argtypes; + } + my @argarrays = map { $_->[4] || '' } @$args; + my $numargs = @$args; + if ($numargs and $argtypes[-1] eq '...') { + $numargs--; + $argnames[-1] = '...'; + } + local $" = ', '; + $type = normalize_type($type, 1); + + print $fh <<"EOP"; + +$type +$name(@argnames) +EOP + + for my $arg (0 .. $numargs - 1) { + print $fh <<"EOP"; + $argtypes[$arg] $argnames[$arg]$argarrays[$arg] +EOP + } +} + +sub print_tievar_subs { + my($fh, $name, $type) = @_; + print $fh <[0] =~ /_ANON/) { + if (defined $item->[2]) { + push @items, map [ + @$_[0, 1], "$item->[2]_$_->[2]", "$item->[2].$_->[2]", + ], @{ $structs{$item->[0]} }; + } else { + push @items, @{ $structs{$item->[0]} }; + } + } else { + my $type = normalize_type($item->[0]); + my $ttype = $structs{$type} ? normalize_type("$type *") : $type; + print $fh <<"EOF"; +$ttype +$item->[2](THIS, __value = NO_INIT) + $ptrname THIS + $type __value + PROTOTYPE: \$;\$ + CODE: + if (items > 1) + THIS->$item->[-1] = __value; + RETVAL = @{[ + $type eq $ttype ? "THIS->$item->[-1]" : "&(THIS->$item->[-1])" + ]}; + OUTPUT: + RETVAL + +EOF + } + } +} + +sub accessor_docs { + my($name, $struct) = @_; + return unless defined $struct && $name !~ /\s|_ANON/; + $name = normalize_type($name); + my $ptrname = $name . 'Ptr'; + my @items = @$struct; + my @list; + while (@items) { + my $item = shift @items; + if ($item->[0] =~ /_ANON/) { + if (defined $item->[2]) { + push @items, map [ + @$_[0, 1], "$item->[2]_$_->[2]", "$item->[2].$_->[2]", + ], @{ $structs{$item->[0]} }; + } else { + push @items, @{ $structs{$item->[0]} }; + } + } else { + push @list, $item->[2]; + } + } + my $methods = (join '(...)>, C<', @list) . '(...)'; + + my $pod = <<"EOF"; +# +#=head2 Object and class methods for C<$name>/C<$ptrname> +# +#The principal Perl representation of a C object of type C<$name> is an +#object of class C<$ptrname> which is a reference to an integer +#representation of a C pointer. To create such an object, one may use +#a combination +# +# my \$buffer = $name->new(); +# my \$obj = \$buffer->_to_ptr(); +# +#This exercises the following two methods, and an additional class +#C<$name>, the internal representation of which is a reference to a +#packed string with the C structure. Keep in mind that \$buffer should +#better survive longer than \$obj. +# +#=over +# +#=item C<\$object_of_type_$name-E_to_ptr()> +# +#Converts an object of type C<$name> to an object of type C<$ptrname>. +# +#=item C<$name-Enew()> +# +#Creates an empty object of type C<$name>. The corresponding packed +#string is zeroed out. +# +#=item C<$methods> +# +#return the current value of the corresponding element if called +#without additional arguments. Set the element to the supplied value +#(and return the new value) if called with an additional argument. +# +#Applicable to objects of type C<$ptrname>. +# +#=back +# +EOF + $pod =~ s/^\#//gm; + return $pod; +} + +# Should be called before any actual call to normalize_type(). +sub get_typemap { + # We do not want to read ./typemap by obvios reasons. + my @tm = qw(../../../typemap ../../typemap ../typemap); + my $stdtypemap = "$Config::Config{privlib}/ExtUtils/typemap"; + unshift @tm, $stdtypemap; + my $proto_re = "[" . quotemeta('\$%&*@;') . "]" ; + + # Start with useful default values + $typemap{float} = 'T_NV'; + + foreach my $typemap (@tm) { + next unless -e $typemap ; + # skip directories, binary files etc. + warn " Scanning $typemap\n"; + warn("Warning: ignoring non-text typemap file '$typemap'\n"), next + unless -T $typemap ; + open(TYPEMAP, "<", $typemap) + or warn ("Warning: could not open typemap file '$typemap': $!\n"), next; + my $mode = 'Typemap'; + while () { + next if /^\s*\#/; + if (/^INPUT\s*$/) { $mode = 'Input'; next; } + elsif (/^OUTPUT\s*$/) { $mode = 'Output'; next; } + elsif (/^TYPEMAP\s*$/) { $mode = 'Typemap'; next; } + elsif ($mode eq 'Typemap') { + next if /^\s*($|\#)/ ; + my ($type, $image); + if ( ($type, $image) = + /^\s*(.*?\S)\s+(\S+)\s*($proto_re*)\s*$/o + # This may reference undefined functions: + and not ($image eq 'T_PACKED' and $typemap eq $stdtypemap)) { + $typemap{normalize_type($type)} = $image; + } + } + } + close(TYPEMAP) or die "Cannot close $typemap: $!"; + } + %std_types = %types_seen; + %types_seen = (); +} + + +sub normalize_type { # Second arg: do not strip const's before \* + my $type = shift; + my $do_keep_deep_const = shift; + # If $do_keep_deep_const this is heuristic only + my $keep_deep_const = ($do_keep_deep_const ? '\b(?![^(,)]*\*)' : ''); + my $ignore_mods + = "(?:\\b(?:(?:__const__|const)$keep_deep_const|static|inline|__inline__)\\b\\s*)*"; + if ($do_keep_deep_const) { # Keep different compiled /RExen/o separately! + $type =~ s/$ignore_mods//go; + } + else { + $type =~ s/$ignore_mods//go; + } + $type =~ s/([^\s\w])/ $1 /g; + $type =~ s/\s+$//; + $type =~ s/^\s+//; + $type =~ s/\s+/ /g; + $type =~ s/\* (?=\*)/*/g; + $type =~ s/\. \. \./.../g; + $type =~ s/ ,/,/g; + $types_seen{$type}++ + unless $type eq '...' or $type eq 'void' or $std_types{$type}; + $type; +} + +my $need_opaque; + +sub assign_typemap_entry { + my $type = shift; + my $otype = $type; + my $entry; + if ($tmask and $type =~ /$tmask/) { + print "Type $type matches -o mask\n" if $opt_d; + $entry = (td_is_struct($type) ? "T_OPAQUE_STRUCT" : "T_PTROBJ"); + } + elsif ($typedef_rex and $type =~ s/($typedef_rex)/$typedefs_pre{$1}/go) { + $type = normalize_type $type; + print "Type mutation via typedefs: $otype ==> $type\n" if $opt_d; + $entry = assign_typemap_entry($type); + } + # XXX good do better if our UV happens to be long long + return "T_NV" if $type =~ /^(unsigned\s+)?long\s+(long|double)\z/; + $entry ||= $typemap{$otype} + || (td_is_struct($type) ? "T_OPAQUE_STRUCT" : "T_PTROBJ"); + $typemap{$otype} = $entry; + $need_opaque = 1 if $entry eq "T_OPAQUE_STRUCT"; + return $entry; +} + +for (@vdecls) { + print_tievar_xsubs(\*XS, $_, $vdecl_hash{$_}); +} + +if ($opt_x) { + for my $decl (@$fdecls_parsed) { print_decl(\*XS, $decl) } + if ($opt_a) { + while (my($name, $struct) = each %structs) { + print_accessors(\*XS, $name, $struct); + } + } +} + +close XS; + +if (%types_seen) { + my $type; + warn "Writing $ext$modpname/typemap\n"; + open TM, ">", "typemap" or die "Cannot open typemap file for write: $!"; + + for $type (sort keys %types_seen) { + my $entry = assign_typemap_entry $type; + print TM $type, "\t" x (5 - int((length $type)/8)), "\t$entry\n" + } + + print TM <<'EOP' if $need_opaque; # Older Perls do not have correct entry +############################################################################# +INPUT +T_OPAQUE_STRUCT + if (sv_derived_from($arg, \"${ntype}\")) { + STRLEN len; + char *s = SvPV((SV*)SvRV($arg), len); + + if (len != sizeof($var)) + croak(\"Size %d of packed data != expected %d\", + len, sizeof($var)); + $var = *($type *)s; + } + else + croak(\"$var is not of type ${ntype}\") +############################################################################# +OUTPUT +T_OPAQUE_STRUCT + sv_setref_pvn($arg, \"${ntype}\", (char *)&$var, sizeof($var)); +EOP + + close TM or die "Cannot close typemap file for write: $!"; +} + +} # if( ! $opt_X ) + +warn "Writing $ext$modpname/Makefile.PL\n"; +open(PL, ">", "Makefile.PL") || die "Can't create $ext$modpname/Makefile.PL: $!\n"; + +my $prereq_pm = ''; + +if ( $compat_version < 5.006002 and $new_test ) +{ + $prereq_pm .= q%'Test::More' => 0, %; +} +elsif ( $compat_version < 5.006002 ) +{ + $prereq_pm .= q%'Test' => 0, %; +} + +if (!$opt_X and $use_xsloader) +{ + $prereq_pm .= q%'XSLoader' => 0, %; +} + +print PL <<"END"; +use $compat_version; +use ExtUtils::MakeMaker; +# See lib/ExtUtils/MakeMaker.pm for details of how to influence +# the contents of the Makefile that is written. +WriteMakefile( + NAME => '$module', + VERSION_FROM => '$modpmname', # finds \$VERSION, requires EU::MM from perl >= 5.5 + PREREQ_PM => {$prereq_pm}, # e.g., Module::Name => 1.1 + ABSTRACT_FROM => '$modpmname', # retrieve abstract from module + AUTHOR => '$author <$email>', + #LICENSE => 'perl', + #Value must be from legacy list of licenses here + #https://metacpan.org/pod/Module::Build::API +END +if (!$opt_X) { # print C stuff, unless XS is disabled + $opt_F = '' unless defined $opt_F; + my $I = (((glob '*.h') || (glob '*.hh')) ? '-I.' : ''); + my $Ihelp = ($I ? '-I. ' : ''); + my $Icomment = ($I ? '' : < ['$extralibs'], # e.g., '-lm' + DEFINE => '$opt_F', # e.g., '-DHAVE_SOMETHING' +$Icomment INC => '$I', # e.g., '${Ihelp}-I/usr/include/other' +END + + my $C = grep {$_ ne "$modfname.c"} + (glob '*.c'), (glob '*.cc'), (glob '*.C'); + my $Cpre = ($C ? '' : '# '); + my $Ccomment = ($C ? '' : < '\$(O_FILES)', # link all the C files too +END +} # ' # Grr +print PL ");\n"; +if (!$opt_c) { + my $generate_code = + WriteMakefileSnippet ( C_FILE => $constscfname, + XS_FILE => $constsxsfname, + DEFAULT_TYPE => $opt_t, + NAME => $module, + NAMES => \@const_specs, + ); + print PL <<"END"; +if (eval {require ExtUtils::Constant; 1}) { + # If you edit these definitions to change the constants used by this module, + # you will need to use the generated $constscfname and $constsxsfname + # files to replace their "fallback" counterparts before distributing your + # changes. +$generate_code +} +else { + use File::Copy; + use File::Spec; + foreach my \$file ('$constscfname', '$constsxsfname') { + my \$fallback = File::Spec->catfile('$fallbackdirname', \$file); + copy (\$fallback, \$file) or die "Can't copy \$fallback to \$file: \$!"; + } +} +END + + eval $generate_code; + if ($@) { + warn <<"EOM"; +Attempting to test constant code in $ext$modpname/Makefile.PL: +$generate_code +__END__ +gave unexpected error $@ +Please report the circumstances of this bug in h2xs version $H2XS_VERSION +using the issue tracker at https://github.com/Perl/perl5/issues. +EOM + } else { + my $fail; + + foreach my $file ($constscfname, $constsxsfname) { + my $fallback = File::Spec->catfile($fallbackdirname, $file); + if (compare($file, $fallback)) { + warn << "EOM"; +Files "$ext$modpname/$fallbackdirname/$file" and "$ext$modpname/$file" differ. +EOM + $fail++; + } + } + if ($fail) { + warn fill ('','', <<"EOM") . "\n"; +It appears that the code in $ext$modpname/Makefile.PL does not autogenerate +the files $ext$modpname/$constscfname and $ext$modpname/$constsxsfname +correctly. + +Please report the circumstances of this bug in h2xs version $H2XS_VERSION +using the issue tracker at https://github.com/Perl/perl5/issues. +EOM + } else { + unlink $constscfname, $constsxsfname; + } + } +} +close(PL) || die "Can't close $ext$modpname/Makefile.PL: $!\n"; + +# Create a simple README since this is a CPAN requirement +# and it doesn't hurt to have one +warn "Writing $ext$modpname/README\n"; +open(RM, ">", "README") || die "Can't create $ext$modpname/README:$!\n"; +my $thisyear = (gmtime)[5] + 1900; +my $rmhead = "$modpname version $TEMPLATE_VERSION"; +my $rmheadeq = "=" x length($rmhead); + +my $rm_prereq; + +if ( $compat_version < 5.006002 and $new_test ) +{ + $rm_prereq = 'Test::More'; +} +elsif ( $compat_version < 5.006002 ) +{ + $rm_prereq = 'Test'; +} +else +{ + $rm_prereq = 'blah blah blah'; +} + +print RM <<_RMEND_; +$rmhead +$rmheadeq + +The README is used to introduce the module and provide instructions on +how to install the module, any machine dependencies it may have (for +example C compilers and installed libraries) and any other information +that should be provided before the module is installed. + +A README file is required for CPAN modules since CPAN extracts the +README file from a module distribution so that people browsing the +archive can use it get an idea of the modules uses. It is usually a +good idea to provide version information here so that people can +decide whether fixes for the module are worth downloading. + +INSTALLATION + +To install this module type the following: + + perl Makefile.PL + make + make test + make install + +DEPENDENCIES + +This module requires these other modules and libraries: + + $rm_prereq + +COPYRIGHT AND LICENCE + +Put the correct copyright and licence information here. + +$licence + +_RMEND_ +close(RM) || die "Can't close $ext$modpname/README: $!\n"; + +my $testdir = "t"; +my $testfile = "$testdir/$modpname.t"; +unless (-d "$testdir") { + mkdir "$testdir" or die "Cannot mkdir $testdir: $!\n"; +} +warn "Writing $ext$modpname/$testfile\n"; +my $tests = @const_names ? 2 : 1; + +open EX, ">", "$testfile" or die "Can't create $ext$modpname/$testfile: $!\n"; + +print EX <<_END_; +# Before 'make install' is performed this script should be runnable with +# 'make test'. After 'make install' it should work as 'perl $modpname.t' + +######################### + +# change 'tests => $tests' to 'tests => last_test_to_print'; + +use strict; +use warnings; + +_END_ + +my $test_mod = 'Test::More'; + +if ( $old_test or ($compat_version < 5.006002 and not $new_test )) +{ + my $test_mod = 'Test'; + + print EX <<_END_; +use Test; +BEGIN { plan tests => $tests }; +use $module; +ok(1); # If we made it this far, we're ok. + +_END_ + + if (@const_names) { + my $const_names = join " ", @const_names; + print EX <<'_END_'; + +my $fail; +foreach my $constname (qw( +_END_ + + print EX wrap ("\t", "\t", $const_names); + print EX (")) {\n"); + + print EX <<_END_; + next if (eval "my \\\$a = \$constname; 1"); + if (\$\@ =~ /^Your vendor has not defined $module macro \$constname/) { + print "# pass: \$\@"; + } else { + print "# fail: \$\@"; + \$fail = 1; + } +} +if (\$fail) { + print "not ok 2\\n"; +} else { + print "ok 2\\n"; +} + +_END_ + } +} +else +{ + print EX <<_END_; +use Test::More tests => $tests; +BEGIN { use_ok('$module') }; + +_END_ + + if (@const_names) { + my $const_names = join " ", @const_names; + print EX <<'_END_'; + +my $fail = 0; +foreach my $constname (qw( +_END_ + + print EX wrap ("\t", "\t", $const_names); + print EX (")) {\n"); + + print EX <<_END_; + next if (eval "my \\\$a = \$constname; 1"); + if (\$\@ =~ /^Your vendor has not defined $module macro \$constname/) { + print "# pass: \$\@"; + } else { + print "# fail: \$\@"; + \$fail = 1; + } + +} + +ok( \$fail == 0 , 'Constants' ); +_END_ + } +} + +print EX <<_END_; +######################### + +# Insert your test code below, the $test_mod module is use()ed here so read +# its man page ( perldoc $test_mod ) for help writing this test script. + +_END_ + +close(EX) || die "Can't close $ext$modpname/$testfile: $!\n"; + +unless ($opt_C) { + warn "Writing $ext$modpname/Changes\n"; + $" = ' '; + open(EX, ">", "Changes") || die "Can't create $ext$modpname/Changes: $!\n"; + @ARGS = map {/[\s\"\'\`\$*?^|&<>\[\]\{\}\(\)]/ ? "'$_'" : $_} @ARGS; + print EX <', 'MANIFEST') or die "Can't create MANIFEST: $!"; +my @files = grep { -f } (<*>, , <$fallbackdirname/*>, <$modpmdir/*>); +if (!@files) { + eval {opendir(D,'.');}; + unless ($@) { @files = readdir(D); closedir(D); } +} +if (!@files) { @files = map {chomp && $_} `ls`; } +if ($^O eq 'VMS') { + foreach (@files) { + # Clip trailing '.' for portability -- non-VMS OSs don't expect it + s%\.$%%; + # Fix up for case-sensitive file systems + s/$modfname/$modfname/i && next; + $_ = "\U$_" if $_ eq 'manifest' or $_ eq 'changes'; + $_ = 'Makefile.PL' if $_ eq 'makefile.pl'; + } +} +print MANI join("\n",@files), "\n"; +close MANI; diff --git a/git/usr/bin/core_perl/instmodsh b/git/usr/bin/core_perl/instmodsh new file mode 100644 index 0000000000000000000000000000000000000000..96b25c79ed564c0d6336cdb29831a2451fb4d7c6 --- /dev/null +++ b/git/usr/bin/core_perl/instmodsh @@ -0,0 +1,196 @@ +#!/usr/bin/perl + eval 'exec /usr/bin/perl -S $0 ${1+"$@"}' + if 0; # ^ Run only under a shell +#!/usr/bin/perl -w + +BEGIN { pop @INC if $INC[-1] eq '.' } +use strict; +use IO::File; +use ExtUtils::Packlist; +use ExtUtils::Installed; + +use vars qw($Inst @Modules); + + +=head1 NAME + +instmodsh - A shell to examine installed modules + +=head1 SYNOPSIS + + instmodsh + +=head1 DESCRIPTION + +A little interface to ExtUtils::Installed to examine installed modules, +validate your packlists and even create a tarball from an installed module. + +=head1 SEE ALSO + +ExtUtils::Installed + +=cut + + +my $Module_Help = < - Create a tar archive of the module + h - Display module help + q - Quit the module +EOF + +my %Module_Commands = ( + f => \&list_installed, + d => \&list_directories, + v => \&validate_packlist, + t => \&create_archive, + h => \&module_help, + ); + +sub do_module($) { + my ($module) = @_; + + print($Module_Help); + MODULE_CMD: while (1) { + print("$module cmd? "); + + my $reply = ; chomp($reply); + my($cmd) = $reply =~ /^(\w)\b/; + + last if $cmd eq 'q'; + + if( $Module_Commands{$cmd} ) { + $Module_Commands{$cmd}->($reply, $module); + } + elsif( $cmd eq 'q' ) { + last MODULE_CMD; + } + else { + module_help(); + } + } +} + + +sub list_installed { + my($reply, $module) = @_; + + my $class = (split(' ', $reply))[1]; + $class = 'all' unless $class; + + my @files; + if (eval { @files = $Inst->files($module, $class); }) { + print("$class files in $module are:\n ", + join("\n ", @files), "\n"); + } + else { + print($@); + } +}; + + +sub list_directories { + my($reply, $module) = @_; + + my $class = (split(' ', $reply))[1]; + $class = 'all' unless $class; + + my @dirs; + if (eval { @dirs = $Inst->directories($module, $class); }) { + print("$class directories in $module are:\n ", + join("\n ", @dirs), "\n"); + } + else { + print($@); + } +} + + +sub create_archive { + my($reply, $module) = @_; + + my $file = (split(' ', $reply))[1]; + + if( !(defined $file and length $file) ) { + print "No tar file specified\n"; + } + elsif( eval { require Archive::Tar } ) { + Archive::Tar->create_archive($file, 0, $Inst->files($module)); + } + else { + my($first, @rest) = $Inst->files($module); + system('tar', 'cvf', $file, $first); + for my $f (@rest) { + system('tar', 'rvf', $file, $f); + } + print "Can't use tar\n" if $?; + } +} + + +sub validate_packlist { + my($reply, $module) = @_; + + if (my @missing = $Inst->validate($module)) { + print("Files missing from $module are:\n ", + join("\n ", @missing), "\n"); + } + else { + print("$module has no missing files\n"); + } +} + +sub module_help { + print $Module_Help; +} + + + +############################################################################## + +sub toplevel() +{ +my $help = < - Select a module + q - Quit the program +EOF +print($help); +while (1) + { + print("cmd? "); + my $reply = ; chomp($reply); + CASE: + { + $reply eq 'l' and do + { + print("Installed modules are:\n ", join("\n ", @Modules), "\n"); + last CASE; + }; + $reply =~ /^m\s+/ and do + { + do_module((split(' ', $reply))[1]); + last CASE; + }; + $reply eq 'q' and do + { + exit(0); + }; + # Default + print($help); + } + } +} + + +############################################################################### + +$Inst = ExtUtils::Installed->new(); +@Modules = $Inst->modules(); +toplevel(); + +############################################################################### diff --git a/git/usr/bin/core_perl/json_pp b/git/usr/bin/core_perl/json_pp new file mode 100644 index 0000000000000000000000000000000000000000..ff3432540cedb83ba4201eb7a6668c11bd606e8a --- /dev/null +++ b/git/usr/bin/core_perl/json_pp @@ -0,0 +1,240 @@ +#!/usr/bin/perl + eval 'exec /usr/bin/perl -S $0 ${1+"$@"}' + if 0; # ^ Run only under a shell +#!/usr/bin/perl + +BEGIN { pop @INC if $INC[-1] eq '.' } +use strict; +use Getopt::Long; +use Encode (); + +use JSON::PP (); + +# imported from JSON-XS/bin/json_xs + +my %allow_json_opt = map { $_ => 1 } qw( + ascii latin1 utf8 pretty indent space_before space_after relaxed canonical allow_nonref + allow_singlequote allow_barekey allow_bignum loose escape_slash indent_length +); + + +GetOptions( + 'v' => \( my $opt_verbose ), + 'f=s' => \( my $opt_from = 'json' ), + 't=s' => \( my $opt_to = 'json' ), + 'json_opt=s' => \( my $json_opt = 'pretty' ), + 'V' => \( my $version ), +) or die "Usage: $0 [-V] [-f from_format] [-t to_format] [-json_opt options_to_json1[,options_to_json2[,...]]]\n"; + + +if ( $version ) { + print "$JSON::PP::VERSION\n"; + exit; +} + + +$json_opt = '' if $json_opt eq '-'; + +my %json_opt; +for my $opt (split /,/, $json_opt) { + my ($key, $value) = split /=/, $opt, 2; + $value = 1 unless defined $value; + die "'$_' is not a valid json option" unless $allow_json_opt{$key}; + $json_opt{$key} = $value; +} + +my %F = ( + 'json' => sub { + my $json = JSON::PP->new; + my $enc = + /^\x00\x00\x00/s ? "utf-32be" + : /^\x00.\x00/s ? "utf-16be" + : /^.\x00\x00\x00/s ? "utf-32le" + : /^.\x00.\x00/s ? "utf-16le" + : "utf-8"; + for my $key (keys %json_opt) { + next if $key eq 'utf8'; + $json->$key($json_opt{$key}); + } + $json->decode( Encode::decode($enc, $_) ); + }, + 'eval' => sub { + my $v = eval "no strict;\n#line 1 \"input\"\n$_"; + die "$@" if $@; + return $v; + }, +); + + +my %T = ( + 'null' => sub { "" }, + 'json' => sub { + my $json = JSON::PP->new->utf8; + for my $key (keys %json_opt) { + $json->$key($json_opt{$key}); + } + $json->canonical if $json_opt{pretty}; + $json->encode( $_ ); + }, + 'dumper' => sub { + require Data::Dumper; + local $Data::Dumper::Terse = 1; + local $Data::Dumper::Indent = 1; + local $Data::Dumper::Useqq = 1; + local $Data::Dumper::Quotekeys = 0; + local $Data::Dumper::Sortkeys = 1; + Data::Dumper::Dumper($_) + }, +); + + + +$F{$opt_from} + or die "$opt_from: not a valid fromformat\n"; + +$T{$opt_to} + or die "$opt_from: not a valid toformat\n"; + +{ + local $/; + binmode STDIN; + $_ = ; +} + +$_ = $F{$opt_from}->(); +$_ = $T{$opt_to}->(); + +print $_; + + +__END__ + +=pod + +=encoding utf8 + +=head1 NAME + +json_pp - JSON::PP command utility + +=head1 SYNOPSIS + + json_pp [-v] [-f from_format] [-t to_format] [-json_opt options_to_json1[,options_to_json2[,...]]] + +=head1 DESCRIPTION + +json_pp converts between some input and output formats (one of them is JSON). +This program was copied from L and modified. + +The default input format is json and the default output format is json with pretty option. + +=head1 OPTIONS + +=head2 -f + + -f from_format + +Reads a data in the given format from STDIN. + +Format types: + +=over + +=item json + +as JSON + +=item eval + +as Perl code + +=back + +=head2 -t + +Writes a data in the given format to STDOUT. + +=over + +=item null + +no action. + +=item json + +as JSON + +=item dumper + +as Data::Dumper + +=back + +=head2 -json_opt + +options to JSON::PP + +Acceptable options are: + + ascii latin1 utf8 pretty indent space_before space_after relaxed canonical allow_nonref + allow_singlequote allow_barekey allow_bignum loose escape_slash indent_length + +Multiple options must be separated by commas: + + Right: -json_opt pretty,canonical + + Wrong: -json_opt pretty -json_opt canonical + +=head2 -v + +Verbose option, but currently no action in fact. + +=head2 -V + +Prints version and exits. + + +=head1 EXAMPLES + + $ perl -e'print q|{"foo":"ã‚ã„","bar":1234567890000000000000000}|' |\ + json_pp -f json -t dumper -json_opt pretty,utf8,allow_bignum + + $VAR1 = { + 'bar' => bless( { + 'value' => [ + '0000000', + '0000000', + '5678900', + '1234' + ], + 'sign' => '+' + }, 'Math::BigInt' ), + 'foo' => "\x{3042}\x{3044}" + }; + + $ perl -e'print q|{"foo":"ã‚ã„","bar":1234567890000000000000000}|' |\ + json_pp -f json -t dumper -json_opt pretty + + $VAR1 = { + 'bar' => '1234567890000000000000000', + 'foo' => "\x{e3}\x{81}\x{82}\x{e3}\x{81}\x{84}" + }; + +=head1 SEE ALSO + +L, L + +=head1 AUTHOR + +Makamaka Hannyaharamitu, Emakamaka[at]cpan.orgE + + +=head1 COPYRIGHT AND LICENSE + +Copyright 2010 by Makamaka Hannyaharamitu + +This library is free software; you can redistribute it and/or modify +it under the same terms as Perl itself. + +=cut + diff --git a/git/usr/bin/core_perl/libnetcfg b/git/usr/bin/core_perl/libnetcfg new file mode 100644 index 0000000000000000000000000000000000000000..6a4a1da0172b54de5af1a11ee718cdea0f36345c --- /dev/null +++ b/git/usr/bin/core_perl/libnetcfg @@ -0,0 +1,722 @@ +#!/usr/bin/perl + eval 'exec /usr/bin/perl -S $0 ${1+"$@"}' + if 0; # ^ Run only under a shell + +=head1 NAME + +libnetcfg - configure libnet + +=head1 DESCRIPTION + +The libnetcfg utility can be used to configure the libnet. +Starting from perl 5.8 libnet is part of the standard Perl +distribution, but the libnetcfg can be used for any libnet +installation. + +=head1 USAGE + +Without arguments libnetcfg displays the current configuration. + + $ libnetcfg + # old config ./libnet.cfg + daytime_hosts ntp1.none.such + ftp_int_passive 0 + ftp_testhost ftp.funet.fi + inet_domain none.such + nntp_hosts nntp.none.such + ph_hosts + pop3_hosts pop.none.such + smtp_hosts smtp.none.such + snpp_hosts + test_exist 1 + test_hosts 1 + time_hosts ntp.none.such + # libnetcfg -h for help + $ + +It tells where the old configuration file was found (if found). + +The C<-h> option will show a usage message. + +To change the configuration you will need to use either the C<-c> or +the C<-d> options. + +The default name of the old configuration file is by default +"libnet.cfg", unless otherwise specified using the -i option, +C<-i oldfile>, and it is searched first from the current directory, +and then from your module path. + +The default name of the new configuration file is "libnet.cfg", and by +default it is written to the current directory, unless otherwise +specified using the -o option, C<-o newfile>. + +=head1 SEE ALSO + +L, L + +=head1 AUTHORS + +Graham Barr, the original Configure script of libnet. + +Jarkko Hietaniemi, conversion into libnetcfg for inclusion into Perl 5.8. + +=cut + +# $Id: Configure,v 1.8 1997/03/04 09:22:32 gbarr Exp $ + +BEGIN { pop @INC if $INC[-1] eq '.' } +use strict; +use IO::File; +use Getopt::Std; +use ExtUtils::MakeMaker qw(prompt); +use File::Spec; + +use vars qw($opt_d $opt_c $opt_h $opt_o $opt_i); + +## +## +## + +my %cfg = (); +my @cfg = (); + +my($libnet_cfg_in,$libnet_cfg_out,$msg,$ans,$def,$have_old); + +## +## +## + +sub valid_host +{ + my $h = shift; + + defined($h) && (($cfg{'test_exist'} == 0) || gethostbyname($h)); +} + +## +## +## + +sub test_hostnames (\@) +{ + my $hlist = shift; + my @h = (); + my $host; + my $err = 0; + + foreach $host (@$hlist) + { + if(valid_host($host)) + { + push(@h, $host); + next; + } + warn "Bad hostname: '$host'\n"; + $err++; + } + @$hlist = @h; + $err ? join(" ",@h) : undef; +} + +## +## +## + +sub Prompt +{ + my($prompt,$def) = @_; + + $def = "" unless defined $def; + + chomp($prompt); + + if($opt_d) + { + print $prompt,," [",$def,"]\n"; + return $def; + } + prompt($prompt,$def); +} + +## +## +## + +sub get_host_list +{ + my($prompt,$def) = @_; + + $def = join(" ",@$def) if ref($def); + + my @hosts; + + do + { + my $ans = Prompt($prompt,$def); + + $ans =~ s/(\A\s+|\s+\Z)//g; + + @hosts = split(/\s+/, $ans); + } + while(@hosts && defined($def = test_hostnames(@hosts))); + + \@hosts; +} + +## +## +## + +sub get_hostname +{ + my($prompt,$def) = @_; + + my $host; + + while(1) + { + my $ans = Prompt($prompt,$def); + $host = ($ans =~ /(\S*)/)[0]; + last + if(!length($host) || valid_host($host)); + + $def ="" + if $def eq $host; + + print <<"EDQ"; + +*** ERROR: + Hostname '$host' does not seem to exist, please enter again + or a single space to clear any default + +EDQ + } + + length $host + ? $host + : undef; +} + +## +## +## + +sub get_bool ($$) +{ + my($prompt,$def) = @_; + + chomp($prompt); + + my $val = Prompt($prompt,$def ? "yes" : "no"); + + $val =~ /^y/i ? 1 : 0; +} + +## +## +## + +sub get_netmask ($$) +{ + my($prompt,$def) = @_; + + chomp($prompt); + + my %list; + @list{@$def} = (); + +MASK: + while(1) { + my $bad = 0; + my $ans = Prompt($prompt) or last; + + if($ans eq '*') { + %list = (); + next; + } + + if($ans eq '=') { + print "\n",( %list ? join("\n", sort keys %list) : 'none'),"\n\n"; + next; + } + + unless ($ans =~ m{^\s*(?:(-?\s*)(\d+(?:\.\d+){0,3})/(\d+))}) { + warn "Bad netmask '$ans'\n"; + next; + } + + my($remove,$bits,@ip) = ($1,$3,split(/\./, $2),0,0,0); + if ( $ip[0] < 1 || $bits < 1 || $bits > 32) { + warn "Bad netmask '$ans'\n"; + next MASK; + } + foreach my $byte (@ip) { + if ( $byte > 255 ) { + warn "Bad netmask '$ans'\n"; + next MASK; + } + } + + my $mask = sprintf("%d.%d.%d.%d/%d",@ip[0..3],$bits); + + if ($remove) { + delete $list{$mask}; + } + else { + $list{$mask} = 1; + } + + } + + [ keys %list ]; +} + +## +## +## + +sub default_hostname +{ + my $host; + my @host; + + foreach $host (@_) + { + if(defined($host) && valid_host($host)) + { + return $host + unless wantarray; + push(@host,$host); + } + } + + return wantarray ? @host : undef; +} + +## +## +## + +getopts('dcho:i:'); + +$libnet_cfg_in = "libnet.cfg" + unless(defined($libnet_cfg_in = $opt_i)); + +$libnet_cfg_out = "libnet.cfg" + unless(defined($libnet_cfg_out = $opt_o)); + +my %oldcfg = (); + +$Net::Config::CONFIGURE = 1; # Suppress load of user overrides +if( -f $libnet_cfg_in ) + { + %oldcfg = ( %{ local @INC = '.'; do $libnet_cfg_in } ); + } +elsif (eval { require Net::Config }) + { + $have_old = 1; + %oldcfg = %Net::Config::NetConfig; + } + +map { $cfg{lc $_} = $cfg{$_}; delete $cfg{$_} if /[A-Z]/ } keys %cfg; + +#--------------------------------------------------------------------------- + +if ($opt_h) { + print <, and it is searched first from the current directory, +and then from your module path. + +The default name of the new configuration file is "libnet.cfg", and by +default it is written to the current directory, unless otherwise +specified using the -o option. + +EOU + exit(0); +} + +#--------------------------------------------------------------------------- + +{ + my $oldcfgfile; + my @inc; + push @inc, $ENV{PERL5LIB} if exists $ENV{PERL5LIB}; + push @inc, $ENV{PERLLIB} if exists $ENV{PERLLIB}; + push @inc, @INC; + for (@inc) { + my $trycfgfile = File::Spec->catfile($_, $libnet_cfg_in); + if (-f $trycfgfile && -r $trycfgfile) { + $oldcfgfile = $trycfgfile; + last; + } + } + print "# old config $oldcfgfile\n" if defined $oldcfgfile; + for (sort keys %oldcfg) { + printf "%-20s %s\n", $_, + ref $oldcfg{$_} ? @{$oldcfg{$_}} : $oldcfg{$_}; + } + unless ($opt_c || $opt_d) { + print "# $0 -h for help\n"; + exit(0); + } +} + +#--------------------------------------------------------------------------- + +$oldcfg{'test_exist'} = 1 unless exists $oldcfg{'test_exist'}; +$oldcfg{'test_hosts'} = 1 unless exists $oldcfg{'test_hosts'}; + +#--------------------------------------------------------------------------- + +if($have_old && !$opt_d) + { + $msg = <. To accept the +default, hit + +EDQ + +$msg = 'Enter a list of available NNTP hosts :'; + +$def = $oldcfg{'nntp_hosts'} || + [ default_hostname($ENV{NNTPSERVER},$ENV{NEWSHOST},'news') ]; + +$cfg{'nntp_hosts'} = get_host_list($msg,$def); + +#--------------------------------------------------------------------------- + +$msg = 'Enter a list of available SMTP hosts :'; + +$def = $oldcfg{'smtp_hosts'} || + [ default_hostname(split(/:/,$ENV{SMTPHOSTS} || ""), 'mailhost') ]; + +$cfg{'smtp_hosts'} = get_host_list($msg,$def); + +#--------------------------------------------------------------------------- + +$msg = 'Enter a list of available POP3 hosts :'; + +$def = $oldcfg{'pop3_hosts'} || []; + +$cfg{'pop3_hosts'} = get_host_list($msg,$def); + +#--------------------------------------------------------------------------- + +$msg = 'Enter a list of available SNPP hosts :'; + +$def = $oldcfg{'snpp_hosts'} || []; + +$cfg{'snpp_hosts'} = get_host_list($msg,$def); + +#--------------------------------------------------------------------------- + +$msg = 'Enter a list of available PH Hosts :' ; + +$def = $oldcfg{'ph_hosts'} || + [ default_hostname('dirserv') ]; + +$cfg{'ph_hosts'} = get_host_list($msg,$def); + +#--------------------------------------------------------------------------- + +$msg = 'Enter a list of available TIME Hosts :' ; + +$def = $oldcfg{'time_hosts'} || []; + +$cfg{'time_hosts'} = get_host_list($msg,$def); + +#--------------------------------------------------------------------------- + +$msg = 'Enter a list of available DAYTIME Hosts :' ; + +$def = $oldcfg{'daytime_hosts'} || $oldcfg{'time_hosts'}; + +$cfg{'daytime_hosts'} = get_host_list($msg,$def); + +#--------------------------------------------------------------------------- + +$msg = < external user & password +fwuser/fwpass => firewall user & password + +0) None +1) ----------------------- + USER user@remote.host + PASS pass +2) ----------------------- + USER fwuser + PASS fwpass + USER user@remote.host + PASS pass +3) ----------------------- + USER fwuser + PASS fwpass + SITE remote.site + USER user + PASS pass +4) ----------------------- + USER fwuser + PASS fwpass + OPEN remote.site + USER user + PASS pass +5) ----------------------- + USER user@fwuser@remote.site + PASS pass@fwpass +6) ----------------------- + USER fwuser@remote.site + PASS fwpass + USER user + PASS pass +7) ----------------------- + USER user@remote.host + PASS pass + AUTH fwuser + RESP fwpass + +Choice: +EDQ + $def = exists $oldcfg{'ftp_firewall_type'} ? $oldcfg{'ftp_firewall_type'} : 1; + $ans = Prompt($msg,$def); + $cfg{'ftp_firewall_type'} = 0+$ans; + $def = $oldcfg{'ftp_firewall'} || $ENV{FTP_FIREWALL}; + + $cfg{'ftp_firewall'} = get_hostname("FTP proxy hostname :", $def); +} +else { + delete $cfg{'ftp_firewall'}; +} + + +#--------------------------------------------------------------------------- + +if (defined $cfg{'ftp_firewall'}) + { + print <new($libnet_cfg_out, "w") or + die "Cannot create '$libnet_cfg_out': $!"; + +print "Writing $libnet_cfg_out\n"; + +print $fh "{\n"; + +my $key; +foreach $key (keys %cfg) { + my $val = $cfg{$key}; + if(!defined($val)) { + $val = "undef"; + } + elsif(ref($val)) { + $val = '[' . join(",", + map { + my $v = "undef"; + if(defined $_) { + ($v = $_) =~ s/'/\'/sog; + $v = "'" . $v . "'"; + } + $v; + } @$val ) . ']'; + } + else { + $val =~ s/'/\'/sog; + $val = "'" . $val . "'" if $val =~ /\D/; + } + print $fh "\t'",$key,"' => ",$val,",\n"; +} + +print $fh "}\n"; + +$fh->close; + +############################################################################ +############################################################################ + +exit 0; diff --git a/git/usr/bin/core_perl/perlbug b/git/usr/bin/core_perl/perlbug new file mode 100644 index 0000000000000000000000000000000000000000..95bcf62c20b6fd50df5e0ef5ea65446f2527d116 --- /dev/null +++ b/git/usr/bin/core_perl/perlbug @@ -0,0 +1,1537 @@ +#!/usr/bin/perl + eval 'exec /usr/bin/perl -S $0 ${1+"$@"}' + if 0; # ^ Run only under a shell + +my $config_tag1 = '5.42.2 - Thu Apr 2 19:54:57 UTC 2026'; + +my $patchlevel_date = 1774202317; +my @patches = Config::local_patches(); +my $patch_tags = join "", map /(\S+)/ ? "+$1 " : (), @patches; + +BEGIN { pop @INC if $INC[-1] eq '.' } +use warnings; +use strict; +use Config; +use File::Spec; # keep perlbug Perl 5.005 compatible +use Getopt::Std; +use File::Basename 'basename'; + +$Getopt::Std::STANDARD_HELP_VERSION = 1; + +sub paraprint; + +BEGIN { + eval { require Mail::Send;}; + $::HaveSend = ($@ eq ""); + eval { require Mail::Util; } ; + $::HaveUtil = (!$ENV{PERL_BUILD_PACKAGING} and $@ eq ""); + # use secure tempfiles wherever possible + eval { require File::Temp; }; + $::HaveTemp = ($@ eq ""); + eval { require Module::CoreList; }; + $::HaveCoreList = ($@ eq ""); + eval { require Text::Wrap; }; + $::HaveWrap = ($@ eq ""); +}; + +our $VERSION = "1.43"; + +#TODO: +# make sure failure (transmission-wise) of Mail::Send is accounted for. +# (This may work now. Unsure of the original author's issue -JESSE 2008-06-08) +# - Test -b option + +my( $file, $usefile, $cc, $address, $thanksaddress, + $filename, $messageid, $domain, $subject, $from, $verbose, $ed, $outfile, + $fh, $me, $body, $andcc, %REP, $ok, $thanks, $progname, + $Is_MSWin32, $Is_Linux, $Is_VMS, $Is_OpenBSD, + $report_about_module, $category, $severity, + %opt, $have_attachment, $attachments, $has_patch, $mime_boundary +); + +my $running_noninteractively = !-t STDIN; + +my $perl_version = $^V ? sprintf("%vd", $^V) : $]; + +my $config_tag2 = "$perl_version - $Config{cf_time}"; + +Init(); + +if ($opt{h}) { Help(); exit; } +if ($opt{d}) { Dump(*STDOUT); exit; } +if ($running_noninteractively && !$opt{t} && !($ok and not $opt{n})) { + paraprint <<"EOF"; +Please use $progname interactively. If you want to +include a file, you can use the -f switch. +EOF + die "\n"; +} + +Query(); +Edit() unless $usefile || ($ok and not $opt{n}); +NowWhat(); +if ($address) { + Send(); + if ($thanks) { + print "\nThank you for taking the time to send a thank-you message!\n\n"; + + paraprint < { + 'default' => 'core', + 'ok' => 'install', + # Inevitably some of these will end up in RT whatever we do: + 'thanks' => 'thanks', + 'opts' => [qw(core docs install library utilities)], # patch, notabug + }, + 'severity' => { + 'default' => 'low', + 'ok' => 'none', + 'thanks' => 'none', + 'opts' => [qw(critical high medium low wishlist none)], # zero + }, + ); + die "Invalid alternative ($name) requested\n" unless grep(/^$name$/, keys %alts); + my $alt = ""; + my $what = $ok || $thanks; + if ($what) { + $alt = $alts{$name}{$what}; + } else { + my @alts = @{$alts{$name}{'opts'}}; + print "\n\n"; + paraprint < 5) { + die "Invalid $name: aborting.\n"; + } + $alt = _prompt('', "\u$name", $alts{$name}{'default'}); + $alt ||= $alts{$name}{'default'}; + } while !((($alt) = grep(/^$alt/i, @alts))); + } + lc $alt; +} + +sub HELP_MESSAGE { Help(); exit; } +sub VERSION_MESSAGE { print "perlbug version $VERSION\n"; } + +sub Init { + # -------- Setup -------- + + $Is_MSWin32 = $^O eq 'MSWin32'; + $Is_VMS = $^O eq 'VMS'; + $Is_Linux = lc($^O) eq 'linux'; + $Is_OpenBSD = lc($^O) eq 'openbsd'; + + # Thanks address + $thanksaddress = 'perl-thanks@perl.org'; + + # Defaults if getopts fails. + $outfile = (basename($0) =~ /^perlthanks/i) ? "perlthanks.rep" : "perlbug.rep"; + $cc = $::Config{'perladmin'} || $::Config{'cf_email'} || $::Config{'cf_by'} || ''; + + HELP_MESSAGE() unless getopts("Adhva:s:b:f:F:r:e:SCc:to:n:T:p:", \%opt); + + # This comment is needed to notify metaconfig that we are + # using the $perladmin, $cf_by, and $cf_time definitions. + # -------- Configuration --------- + + if (basename ($0) =~ /^perlthanks/i) { + # invoked as perlthanks + $opt{T} = 1; + $opt{C} = 1; # don't send a copy to the local admin + } + + if ($opt{T}) { + $thanks = 'thanks'; + } + + $progname = $thanks ? 'perlthanks' : 'perlbug'; + # Target address + $address = $opt{a} || ($thanks ? $thanksaddress : ""); + + # Users address, used in message and in From and Reply-To headers + $from = $opt{r} || ""; + + # Include verbose configuration information + $verbose = $opt{v} || 0; + + # Subject of bug-report message + $subject = $opt{s} || ""; + + # Send a file + $usefile = ($opt{f} || 0); + + # File to send as report + $file = $opt{f} || ""; + + # We have one or more attachments + $have_attachment = ($opt{p} || 0); + $mime_boundary = ('-' x 12) . "$VERSION.perlbug" if $have_attachment; + + # Comma-separated list of attachments + $attachments = $opt{p} || ""; + $has_patch = 0; # TBD based on file type + + for my $attachment (split /\s*,\s*/, $attachments) { + unless (-f $attachment && -r $attachment) { + die "The attachment $attachment is not a readable file: $!\n"; + } + $has_patch = 1 if $attachment =~ m/\.(patch|diff)$/; + } + + # File to output to + $outfile = $opt{F} || "$progname.rep"; + + # Body of report + $body = $opt{b} || ""; + + # Editor + $ed = $opt{e} || $ENV{VISUAL} || $ENV{EDITOR} || $ENV{EDIT} + || ($Is_VMS && "edit/tpu") + || ($Is_MSWin32 && "notepad") + || "vi"; + + # Not OK - provide build failure template by finessing OK report + if ($opt{n}) { + if (substr($opt{n}, 0, 2) eq 'ok' ) { + $opt{o} = substr($opt{n}, 1); + } else { + Help(); + exit(); + } + } + + # OK - send "OK" report for build on this system + $ok = ''; + if ($opt{o}) { + if ($opt{o} eq 'k' or $opt{o} eq 'kay') { + my $age = time - $patchlevel_date; + if ($opt{o} eq 'k' and $age > 60 * 24 * 60 * 60 ) { + my $date = localtime $patchlevel_date; + print <<"EOF"; +"perlbug -ok" and "perlbug -nok" do not report on Perl versions which +are more than 60 days old. This Perl version was constructed on +$date. If you really want to report this, use +"perlbug -okay" or "perlbug -nokay". +EOF + exit(); + } + # force these options + unless ($opt{n}) { + $opt{S} = 1; # don't prompt for send + $opt{b} = 1; # we have a body + $body = "Perl reported to build OK on this system.\n"; + } + $opt{C} = 1; # don't send a copy to the local admin + $opt{s} = 1; # we have a subject line + $subject = ($opt{n} ? 'Not ' : '') + . "OK: perl $perl_version ${patch_tags}on" + ." $::Config{'archname'} $::Config{'osvers'} $subject"; + $ok = 'ok'; + } else { + Help(); + exit(); + } + } + + # Possible administrator addresses, in order of confidence + # (Note that cf_email is not mentioned to metaconfig, since + # we don't really want it. We'll just take it if we have to.) + # + # This has to be after the $ok stuff above because of the way + # that $opt{C} is forced. + $cc = $opt{C} ? "" : ( + $opt{c} || $::Config{'perladmin'} + || $::Config{'cf_email'} || $::Config{'cf_by'} + ); + + if ($::HaveUtil) { + $domain = Mail::Util::maildomain(); + } elsif ($Is_MSWin32) { + $domain = $ENV{'USERDOMAIN'}; + } else { + require Sys::Hostname; + $domain = Sys::Hostname::hostname(); + } + + # Message-Id - rjsf + $messageid = "<$::Config{'version'}_${$}_".time."\@$domain>"; + + # My username + $me = $Is_MSWin32 ? $ENV{'USERNAME'} + : $^O eq 'os2' ? $ENV{'USER'} || $ENV{'LOGNAME'} + : eval { getpwuid($<) }; # May be missing + + $from = $::Config{'cf_email'} + if !$from && $::Config{'cf_email'} && $::Config{'cf_by'} && $me && + ($me eq $::Config{'cf_by'}); +} # sub Init + +sub Query { + # Explain what perlbug is + unless ($ok) { + if ($thanks) { + paraprint <<'EOF'; +This program provides an easy way to send a thank-you message back to the +authors and maintainers of perl. + +If you wish to generate a bug report, please run it without the -T flag +(or run the program perlbug rather than perlthanks) +EOF + } else { + paraprint <<"EOF"; +This program provides an easy way to generate a bug report for the core +perl distribution (along with tests or patches). To send a thank-you +note to $thanksaddress instead of a bug report, please run 'perlthanks'. + +The GitHub issue tracker at https://github.com/Perl/perl5/issues is the +best place to submit your report so it can be tracked and resolved. + +Please do not use $0 to report bugs in perl modules from CPAN. + +Suggestions for how to find help using Perl can be found at +https://perldoc.perl.org/perlcommunity.html +EOF + } + } + + # Prompt for subject of message, if needed + + if ($subject && TrivialSubject($subject)) { + $subject = ''; + } + + unless ($subject) { + print +"First of all, please provide a subject for the report.\n"; + if ( not $thanks) { + paraprint <first_release($entry); + if ($entry and not $first_release) { + paraprint <:raw', $filename) or die "Unable to create report file '$filename': $!\n"; + binmode(REP, ':raw :crlf') if $Is_MSWin32; + + my $reptype = !$ok ? ($thanks ? 'thank-you' : 'bug') + : $opt{n} ? "build failure" : "success"; + + print REP <) { + print REP $_ + } + close(F) or die "Error closing '$file': $!"; + } else { + if ($thanks) { + print REP <<'EOF'; + +----------------------------------------------------------------- +[Please enter your thank-you message here] + + + +[You're welcome to delete anything below this line] +----------------------------------------------------------------- +EOF + } else { + print REP <<'EOF'; + +----------------------------------------------------------------- + + +**Description** + + + + +**Steps to Reproduce** + + + + +**Expected behavior** + + + + + + +EOF + } + } + Dump(*REP); + close(REP) or die "Error closing report file: $!"; + + # Set up an initial report fingerprint so we can compare it later + _fingerprint_lines_in_report(); + +} # sub Query + +sub Dump { + local(*OUT) = @_; + + # these won't have been set if run with -d + $category ||= 'core'; + $severity ||= 'low'; + + print OUT <etry dit + next; + } elsif ( $action =~ /^[cq]/i ) { # ancel, uit + Cancel(); # cancel exits + } + } + # Ok. the user did what they needed to; + return; + + } +} + + +sub Cancel { + 1 while unlink($filename); # remove all versions under VMS + print "\nQuitting without generating a report.\n"; + exit(0); +} + +sub NowWhat { + # Report is done, prompt for further action + if( !$opt{S} ) { + while(1) { + my $send_to = $address || 'the Perl developers'; + my $menu = <ile/ve + if ( SaveMessage() ) { exit } + } elsif ($action =~ /^(d|l|sh)/i ) { # isplay, ist, ow + # Display the message + print _read_report($filename); + if ($have_attachment) { + print "\n\n---\nAttachment(s):\n"; + for my $att (split /\s*,\s*/, $attachments) { print " $att\n"; } + } + } elsif ($action =~ /^su/i) { # bject + my $reply = _prompt( "Subject: $subject", "If the above subject is fine, press Enter. Otherwise, type a replacement now\nSubject"); + if ($reply ne '') { + unless (TrivialSubject($reply)) { + $subject = $reply; + print "Subject: $subject\n"; + } + } + } elsif ($action =~ /^se/i) { # end + # Send the message + if (not $thanks) { + print <dit, e-edit + # edit the message + Edit(); + } elsif ($action =~ /^[qc]/i) { # ancel, uit + Cancel(); + } elsif ($action =~ /^s/i) { + paraprint < 1); + close($fh); + return $filename; + } else { + # Bah. Fall back to doing things less securely. + my $dir = File::Spec->tmpdir(); + $filename = "bugrep0$$"; + $filename++ while -e File::Spec->catfile($dir, $filename); + $filename = File::Spec->catfile($dir, $filename); + } +} + +sub paraprint { + my @paragraphs = split /\n{2,}/, "@_"; + for (@paragraphs) { # implicit local $_ + s/(\S)\s*\n/$1 /g; + write; + print "\n"; + } +} + +sub _prompt { + my ($explanation, $prompt, $default) = (@_); + if ($explanation) { + print "\n\n"; + paraprint $explanation; + } + print $prompt. ($default ? " [$default]" :''). ": "; + my $result = scalar(<>); + return $default if !defined $result; # got eof + chomp($result); + $result =~ s/^\s*(.*?)\s*$/$1/s; + if ($default && $result eq '') { + return $default; + } else { + return $result; + } +} + +sub _build_header { + my %attr = (@_); + + my $head = ''; + for my $header (keys %attr) { + $head .= "$header: ".$attr{$header}."\n"; + } + return $head; +} + +sub _message_headers { + my %headers = ( To => $address || 'perl5-porters@perl.org', Subject => $subject ); + $headers{'Cc'} = $cc if ($cc); + $headers{'Message-Id'} = $messageid if ($messageid); + $headers{'Reply-To'} = $from if ($from); + $headers{'From'} = $from if ($from); + if ($have_attachment) { + $headers{'MIME-Version'} = '1.0'; + $headers{'Content-Type'} = qq{multipart/mixed; boundary=\"$mime_boundary\"}; + } + return \%headers; +} + +sub _add_body_start { + my $body_start = <<"BODY_START"; +This is a multi-part message in MIME format. +--$mime_boundary +Content-Type: text/plain; format=fixed +Content-Transfer-Encoding: 8bit + +BODY_START + return $body_start; +} + +sub _add_attachments { + my $attach = ''; + for my $attachment (split /\s*,\s*/, $attachments) { + my $attach_file = basename($attachment); + $attach .= <<"ATTACHMENT"; + +--$mime_boundary +Content-Type: text/x-patch; name="$attach_file" +Content-Transfer-Encoding: 8bit +Content-Disposition: attachment; filename="$attach_file" + +ATTACHMENT + + open my $attach_fh, '<:raw', $attachment + or die "Couldn't open attachment '$attachment': $!\n"; + while (<$attach_fh>) { $attach .= $_; } + close($attach_fh) or die "Error closing attachment '$attachment': $!"; + } + + $attach .= "\n--$mime_boundary--\n"; + return $attach; +} + +sub _read_report { + my $fname = shift; + my $content; + open( REP, "<:raw", $fname ) or die "Couldn't open file '$fname': $!\n"; + binmode(REP, ':raw :crlf') if $Is_MSWin32; + # wrap long lines to make sure the report gets delivered + local $Text::Wrap::columns = 900; + local $Text::Wrap::huge = 'overflow'; + while () { + if ($::HaveWrap && /\S/) { # wrap() would remove empty lines + $content .= Text::Wrap::wrap(undef, undef, $_); + } else { + $content .= $_; + } + } + close(REP) or die "Error closing report file '$fname': $!"; + return $content; +} + +sub build_complete_message { + my $content = _build_header(%{_message_headers()}) . "\n\n"; + $content .= _add_body_start() if $have_attachment; + $content .= _read_report($filename); + $content .= _add_attachments() if $have_attachment; + return $content; +} + +sub save_message_to_disk { + my $file = shift; + + if (-e $file) { + my $response = _prompt( '', "Overwrite existing '$file'", 'n' ); + return undef unless $response =~ / yes | y /xi; + } + open OUTFILE, '>:raw', $file or do { warn "Couldn't open '$file': $!\n"; return undef}; + binmode(OUTFILE, ':raw :crlf') if $Is_MSWin32; + + print OUTFILE build_complete_message(); + close(OUTFILE) or do { warn "Error closing $file: $!"; return undef }; + print "\nReport saved to '$file'. Please submit it to https://github.com/Perl/perl5/issues\n"; + return 1; +} + +sub _send_message_vms { + + my $mail_from = $from; + my $rcpt_to_to = $address; + my $rcpt_to_cc = $cc; + + map { $_ =~ s/^[^<]*[^>]*//; } ($mail_from, $rcpt_to_to, $rcpt_to_cc); + + if ( open my $sff_fh, '|-:raw', 'MCR TCPIP$SYSTEM:TCPIP$SMTP_SFF.EXE SYS$INPUT:' ) { + print $sff_fh "MAIL FROM:<$mail_from>\n"; + print $sff_fh "RCPT TO:<$rcpt_to_to>\n"; + print $sff_fh "RCPT TO:<$rcpt_to_cc>\n" if $rcpt_to_cc; + print $sff_fh "DATA\n"; + print $sff_fh build_complete_message(); + my $success = close $sff_fh; + if ($success ) { + print "\nMessage sent\n"; + return; + } + } + die "Mail transport failed (leaving bug report in $filename): $^E\n"; +} + +sub _send_message_mailsend { + my $msg = Mail::Send->new(); + my %headers = %{_message_headers()}; + for my $key ( keys %headers) { + $msg->add($key => $headers{$key}); + } + + $fh = $msg->open; + binmode($fh, ':raw'); + print $fh _add_body_start() if $have_attachment; + print $fh _read_report($filename); + print $fh _add_attachments() if $have_attachment; + $fh->close or die "Error sending mail: $!"; + + print "\nMessage sent.\n"; +} + +sub _probe_for_sendmail { + my $sendmail = ""; + for (qw(/usr/lib/sendmail /usr/sbin/sendmail /usr/ucblib/sendmail)) { + $sendmail = $_, last if -e $_; + } + if ( $^O eq 'os2' and $sendmail eq "" ) { + my $path = $ENV{PATH}; + $path =~ s:\\:/:; + my @path = split /$Config{'path_sep'}/, $path; + for (@path) { + $sendmail = "$_/sendmail", last if -e "$_/sendmail"; + $sendmail = "$_/sendmail.exe", last if -e "$_/sendmail.exe"; + } + } + return $sendmail; +} + +sub _send_message_sendmail { + my $sendmail = _probe_for_sendmail(); + unless ($sendmail) { + my $message_start = !$Is_Linux && !$Is_OpenBSD ? <<'EOT' : <<'EOT'; +It appears that there is no program which looks like "sendmail" on +your system and that the Mail::Send library from CPAN isn't available. +EOT +It appears that there is no program which looks like "sendmail" on +your system. +EOT + paraprint(<<"EOF"), die "\n"; +$message_start +Because of this, there's no easy way to automatically send your +report. + +A copy of your report has been saved in '$filename' for you to +send to '$address' with your normal mail client. +EOF + } + + open( SENDMAIL, "|-:raw", $sendmail, "-t", "-oi", "-f", $from ) + || die "'|$sendmail -t -oi -f $from' failed: $!"; + print SENDMAIL build_complete_message(); + if ( close(SENDMAIL) ) { + print "\nMessage sent\n"; + } else { + warn "\nSendmail returned status '", $? >> 8, "'\n"; + } +} + + + +# a strange way to check whether any significant editing +# has been done: check whether any new non-empty lines +# have been added. + +sub _fingerprint_lines_in_report { + my $new_lines = 0; + # read in the report template once so that + # we can track whether the user does any editing. + # yes, *all* whitespace is ignored. + + open(REP, '<:raw', $filename) or die "Unable to open report file '$filename': $!\n"; + binmode(REP, ':raw :crlf') if $Is_MSWin32; + while (my $line = ) { + $line =~ s/\s+//g; + $new_lines++ if (!$REP{$line}); + + } + close(REP) or die "Error closing report file '$filename': $!"; + # returns the number of lines with content that wasn't there when last we looked + return $new_lines; +} + + + +format STDOUT = +^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~~ +$_ +. + +__END__ + +=head1 NAME + +perlbug - how to submit bug reports on Perl + +=head1 SYNOPSIS + +B + +B S<[ B<-v> ]> S<[ B<-a> I
]> S<[ B<-s> I ]> +S<[ B<-b> I | B<-f> I ]> S<[ B<-F> I ]> +S<[ B<-r> I ]> +S<[ B<-e> I ]> S<[ B<-c> I | B<-C> ]> +S<[ B<-S> ]> S<[ B<-t> ]> S<[ B<-d> ]> S<[ B<-h> ]> S<[ B<-T> ]> + +B S<[ B<-v> ]> S<[ B<-r> I ]> + S<[ B<-ok> | B<-okay> | B<-nok> | B<-nokay> ]> + +B + +=head1 DESCRIPTION + + +This program is designed to help you generate bug reports +(and thank-you notes) about perl5 and the modules which ship with it. + +In most cases, you can just run it interactively from a command +line without any special arguments and follow the prompts. + +If you have found a bug with a non-standard port (one that was not +part of the I), a binary distribution, or a +non-core module (such as Tk, DBI, etc), then please see the +documentation that came with that distribution to determine the +correct place to report bugs. + +Bug reports should be submitted to the GitHub issue tracker at +L. The B +address no longer automatically opens tickets. You can use this tool +to compose your report and save it to a file which you can then submit +to the issue tracker. + +In extreme cases, B may not work well enough on your system +to guide you through composing a bug report. In those cases, you +may be able to use B or B to get system +configuration information to include in your issue report. + + +When reporting a bug, please run through this checklist: + +=over 4 + +=item What version of Perl you are running? + +Type C at the command line to find out. + +=item Are you running the latest released version of perl? + +Look at L to find out. If you are not using the +latest released version, please try to replicate your bug on the +latest stable release. + +Note that reports about bugs in old versions of Perl, especially +those which indicate you haven't also tested the current stable +release of Perl, are likely to receive less attention from the +volunteers who build and maintain Perl than reports about bugs in +the current release. + +=item Are you sure what you have is a bug? + +A significant number of the bug reports we get turn out to be +documented features in Perl. Make sure the issue you've run into +isn't intentional by glancing through the documentation that comes +with the Perl distribution. + +Given the sheer volume of Perl documentation, this isn't a trivial +undertaking, but if you can point to documentation that suggests +the behaviour you're seeing is I, your issue is likely to +receive more attention. You may want to start with B +L for pointers to common traps that new (and experienced) +Perl programmers run into. + +If you're unsure of the meaning of an error message you've run +across, B L for an explanation. If the message +isn't in perldiag, it probably isn't generated by Perl. You may +have luck consulting your operating system documentation instead. + +If you are on a non-UNIX platform B L, as some +features may be unimplemented or work differently. + +You may be able to figure out what's going wrong using the Perl +debugger. For information about how to use the debugger B +L. + +=item Do you have a proper test case? + +The easier it is to reproduce your bug, the more likely it will be +fixed -- if nobody can duplicate your problem, it probably won't be +addressed. + +A good test case has most of these attributes: short, simple code; +few dependencies on external commands, modules, or libraries; no +platform-dependent code (unless it's a platform-specific bug); +clear, simple documentation. + +A good test case is almost always a good candidate to be included in +Perl's test suite. If you have the time, consider writing your test case so +that it can be easily included into the standard test suite. + +=item Have you included all relevant information? + +Be sure to include the B error messages, if any. +"Perl gave an error" is not an exact error message. + +If you get a core dump (or equivalent), you may use a debugger +(B, B, etc) to produce a stack trace to include in the bug +report. + +NOTE: unless your Perl has been compiled with debug info +(often B<-g>), the stack trace is likely to be somewhat hard to use +because it will most probably contain only the function names and not +their arguments. If possible, recompile your Perl with debug info and +reproduce the crash and the stack trace. + +=item Can you describe the bug in plain English? + +The easier it is to understand a reproducible bug, the more likely +it will be fixed. Any insight you can provide into the problem +will help a great deal. In other words, try to analyze the problem +(to the extent you can) and report your discoveries. + +=item Can you fix the bug yourself? + +If so, that's great news; bug reports with patches are likely to +receive significantly more attention and interest than those without +patches. Please submit your patch via the GitHub Pull Request workflow +as described in B L. You may also send patches to +B. When sending a patch, create it using +C if possible, though a unified diff created with +C will do nearly as well. + +Your patch may be returned with requests for changes, or requests for more +detailed explanations about your fix. + +Here are a few hints for creating high-quality patches: + +Make sure the patch is not reversed (the first argument to diff is +typically the original file, the second argument your changed file). +Make sure you test your patch by applying it with C or the +C program before you send it on its way. Try to follow the +same style as the code you are trying to patch. Make sure your patch +really does work (C, if the thing you're patching is covered +by Perl's test suite). + +=item Can you use C to submit a thank-you note? + +Yes, you can do this by either using the C<-T> option, or by invoking +the program as C. Thank-you notes are good. It makes people +smile. + +=back + +Please make your issue title informative. "a bug" is not informative. +Neither is "perl crashes" nor is "HELP!!!". These don't help. A compact +description of what's wrong is fine. + +Having done your bit, please be prepared to wait, to be told the +bug is in your code, or possibly to get no reply at all. The +volunteers who maintain Perl are busy folks, so if your problem is +an obvious bug in your own code, is difficult to understand or is +a duplicate of an existing report, you may not receive a personal +reply. + +If it is important to you that your bug be fixed, do monitor the +issue tracker (you will be subscribed to notifications for issues you +submit or comment on) and the commit logs to development +versions of Perl, and encourage the maintainers with kind words or +offers of frosty beverages. (Please do be kind to the maintainers. +Harassing or flaming them is likely to have the opposite effect of the +one you want.) + +Feel free to update the ticket about your bug on +L +if a new version of Perl is released and your bug is still present. + +=head1 OPTIONS + +=over 8 + +=item B<-a> + +Address to send the report to instead of saving to a file. + +=item B<-b> + +Body of the report. If not included on the command line, or +in a file with B<-f>, you will get a chance to edit the report. + +=item B<-C> + +Don't send copy to administrator when sending report by mail. + +=item B<-c> + +Address to send copy of report to when sending report by mail. +Defaults to the address of the +local perl administrator (recorded when perl was built). + +=item B<-d> + +Data mode (the default if you redirect or pipe output). This prints out +your configuration data, without saving or mailing anything. You can use +this with B<-v> to get more complete data. + +=item B<-e> + +Editor to use. + +=item B<-f> + +File containing the body of the report. Use this to quickly send a +prepared report. + +=item B<-F> + +File to output the results to. Defaults to B. + +=item B<-h> + +Prints a brief summary of the options. + +=item B<-ok> + +Report successful build on this system to perl porters. Forces B<-S> +and B<-C>. Forces and supplies values for B<-s> and B<-b>. Only +prompts for a return address if it cannot guess it (for use with +B). Honors return address specified with B<-r>. You can use this +with B<-v> to get more complete data. Only makes a report if this +system is less than 60 days old. + +=item B<-okay> + +As B<-ok> except it will report on older systems. + +=item B<-nok> + +Report unsuccessful build on this system. Forces B<-C>. Forces and +supplies a value for B<-s>, then requires you to edit the report +and say what went wrong. Alternatively, a prepared report may be +supplied using B<-f>. Only prompts for a return address if it +cannot guess it (for use with B). Honors return address +specified with B<-r>. You can use this with B<-v> to get more +complete data. Only makes a report if this system is less than 60 +days old. + +=item B<-nokay> + +As B<-nok> except it will report on older systems. + +=item B<-p> + +The names of one or more patch files or other text attachments to be +included with the report. Multiple files must be separated with commas. + +=item B<-r> + +Your return address. The program will ask you to confirm its default +if you don't use this option. + +=item B<-S> + +Save or send the report without asking for confirmation. + +=item B<-s> + +Subject to include with the report. You will be prompted if you don't +supply one on the command line. + +=item B<-t> + +Test mode. Makes it possible to command perlbug from a pipe or file, for +testing purposes. + +=item B<-T> + +Send a thank-you note instead of a bug report. + +=item B<-v> + +Include verbose configuration data in the report. + +=back + +=head1 AUTHORS + +Kenneth Albanowski (Ekjahds@kjahds.comE), subsequently +Itored by Gurusamy Sarathy (Egsar@activestate.comE), +Tom Christiansen (Etchrist@perl.comE), Nathan Torkington +(Egnat@frii.comE), Charles F. Randall (Ecfr@pobox.comE), +Mike Guy (Emjtg@cam.ac.ukE), Dominic Dunlop +(Edomo@computer.orgE), Hugo van der Sanden (Ehv@crypt.orgE), +Jarkko Hietaniemi (Ejhi@iki.fiE), Chris Nandor +(Epudge@pobox.comE), Jon Orwant (Eorwant@media.mit.eduE, +Richard Foley (Erichard.foley@rfi.netE), Jesse Vincent +(Ejesse@bestpractical.comE), and Craig A. Berry (Ecraigberry@mac.comE). + +=head1 SEE ALSO + +perl(1), perldebug(1), perldiag(1), perlport(1), perltrap(1), +diff(1), patch(1), dbx(1), gdb(1) + +=head1 BUGS + +None known (guess what must have been used to report them?) + +=cut + diff --git a/git/usr/bin/core_perl/perlivp b/git/usr/bin/core_perl/perlivp new file mode 100644 index 0000000000000000000000000000000000000000..f4fcdcde4be62fe5f79b1e357dc35cabadedc840 --- /dev/null +++ b/git/usr/bin/core_perl/perlivp @@ -0,0 +1,392 @@ +#!/usr/bin/perl + eval 'exec /usr/bin/perl -S $0 ${1+"$@"}' + if 0; # ^ Run only under a shell + +# perlivp v5.42.2 + +BEGIN { pop @INC if $INC[-1] eq '.' } + +sub usage { + warn "@_\n" if @_; + print << " EOUSAGE"; +Usage: + + $0 [-p] [-v] | [-h] + + -p Print a preface before each test telling what it will test. + -v Verbose mode in which extra information about test results + is printed. Test failures always print out some extra information + regardless of whether or not this switch is set. + -h Prints this help message. + EOUSAGE + exit; +} + +use vars qw(%opt); # allow testing with older versions (do not use our) + +@opt{ qw/? H h P p V v/ } = qw(0 0 0 0 0 0 0); + +while ($ARGV[0] =~ /^-/) { + $ARGV[0] =~ s/^-//; + for my $flag (split(//,$ARGV[0])) { + usage() if '?' =~ /\Q$flag/; + usage() if 'h' =~ /\Q$flag/; + usage() if 'H' =~ /\Q$flag/; + usage("unknown flag: '$flag'") unless 'HhPpVv' =~ /\Q$flag/; + warn "$0: '$flag' flag already set\n" if $opt{$flag}++; + } + shift; +} + +$opt{p}++ if $opt{P}; +$opt{v}++ if $opt{V}; + +my $pass__total = 0; +my $error_total = 0; +my $tests_total = 0; + +my $perlpath = '/usr/bin/perl'; +my $useithreads = 'define'; + +print "## Checking Perl binary via variable '\$perlpath' = $perlpath.\n" if $opt{'p'}; + +my $label = 'Executable perl binary'; + +if (-x $perlpath) { + print "## Perl binary '$perlpath' appears executable.\n" if $opt{'v'}; + print "ok 1 $label\n"; + $pass__total++; +} +else { + print "# Perl binary '$perlpath' does not appear executable.\n"; + print "not ok 1 $label\n"; + $error_total++; +} +$tests_total++; + + +print "## Checking Perl version via variable '\$]'.\n" if $opt{'p'}; + +my $ivp_VERSION = "5.042002"; + + +$label = 'Perl version correct'; +if ($ivp_VERSION eq $]) { + print "## Perl version '$]' appears installed as expected.\n" if $opt{'v'}; + print "ok 2 $label\n"; + $pass__total++; +} +else { + print "# Perl version '$]' installed, expected $ivp_VERSION.\n"; + print "not ok 2 $label\n"; + $error_total++; +} +$tests_total++; + +# We have the right perl and version, so now reset @INC so we ignore +# PERL5LIB and '.' +{ + local $ENV{PERL5LIB}; + my $perl_V = qx($perlpath -V); + $perl_V =~ s{.*\@INC:\n}{}ms; + @INC = grep { length && $_ ne '.' } split ' ', $perl_V; +} + +print "## Checking roots of the Perl library directory tree via variable '\@INC'.\n" if $opt{'p'}; + +my $INC_total = 0; +my $INC_there = 0; +foreach (@INC) { + next if $_ eq '.'; # skip -d test here + if (-d $_) { + print "## Perl \@INC directory '$_' exists.\n" if $opt{'v'}; + $INC_there++; + } + else { + print "# Perl \@INC directory '$_' does not appear to exist.\n"; + } + $INC_total++; +} + +$label = '@INC directories exist'; +if ($INC_total == $INC_there) { + print "ok 3 $label\n"; + $pass__total++; +} +else { + print "not ok 3 $label\n"; + $error_total++; +} +$tests_total++; + + +print "## Checking installations of modules necessary for ivp.\n" if $opt{'p'}; + +my $needed_total = 0; +my $needed_there = 0; +foreach (qw(Config.pm ExtUtils/Installed.pm)) { + $@ = undef; + $needed_total++; + eval "require \"$_\";"; + if (!$@) { + print "## Module '$_' appears to be installed.\n" if $opt{'v'}; + $needed_there++; + } + else { + print "# Needed module '$_' does not appear to be properly installed.\n"; + } + $@ = undef; +} +$label = 'Modules needed for rest of perlivp exist'; +if ($needed_total == $needed_there) { + print "ok 4 $label\n"; + $pass__total++; +} +else { + print "not ok 4 $label\n"; + $error_total++; +} +$tests_total++; + + +print "## Checking installations of extensions built with perl.\n" if $opt{'p'}; + +use Config; + +my $extensions_total = 0; +my $extensions_there = 0; +if (defined($Config{'extensions'})) { + my @extensions = split(/\s+/,$Config{'extensions'}); + foreach (@extensions) { + next if ($_ eq ''); + if ( $useithreads !~ /define/i ) { + next if ($_ eq 'threads'); + next if ($_ eq 'threads/shared'); + } + # that's a distribution name, not a module name + next if $_ eq 'IO/Compress'; + next if $_ eq 'Devel/DProf'; + next if $_ eq 'libnet'; + next if $_ eq 'Locale/Codes'; + next if $_ eq 'podlators'; + next if $_ eq 'perlfaq'; + # test modules + next if $_ eq 'XS/APItest'; + next if $_ eq 'XS/Typemap'; + # VMS$ perl -e "eval ""require \""Devel/DProf.pm\"";"" print $@" + # \NT> perl -e "eval \"require './Devel/DProf.pm'\"; print $@" + # DProf: run perl with -d to use DProf. + # Compilation failed in require at (eval 1) line 1. + eval " require \"$_.pm\"; "; + if (!$@) { + print "## Module '$_' appears to be installed.\n" if $opt{'v'}; + $extensions_there++; + } + else { + print "# Required module '$_' does not appear to be properly installed.\n"; + $@ = undef; + } + $extensions_total++; + } + + # A silly name for a module (that hopefully won't ever exist). + # Note that this test serves more as a check of the validity of the + # actual required module tests above. + my $unnecessary = 'bLuRfle'; + + if (!grep(/$unnecessary/, @extensions)) { + $@ = undef; + eval " require \"$unnecessary.pm\"; "; + if ($@) { + print "## Unnecessary module '$unnecessary' does not appear to be installed.\n" if $opt{'v'}; + } + else { + print "# Unnecessary module '$unnecessary' appears to be installed.\n"; + $extensions_there++; + } + } + $@ = undef; +} +$label = 'All (and only) expected extensions installed'; +if ($extensions_total == $extensions_there) { + print "ok 5 $label\n"; + $pass__total++; +} +else { + print "not ok 5 $label\n"; + $error_total++; +} +$tests_total++; + + +print "## Checking installations of later additional extensions.\n" if $opt{'p'}; + +use ExtUtils::Installed; + +my $installed_total = 0; +my $installed_there = 0; +my $version_check = 0; +my $installed = ExtUtils::Installed -> new(); +my @modules = $installed -> modules(); +my @missing = (); +my $version = undef; +for (@modules) { + $installed_total++; + # Consider it there if it contains one or more files, + # and has zero missing files, + # and has a defined version + $version = undef; + $version = $installed -> version($_); + if ($version) { + print "## $_; $version\n" if $opt{'v'}; + $version_check++; + } + else { + print "# $_; NO VERSION\n" if $opt{'v'}; + } + $version = undef; + @missing = (); + @missing = $installed -> validate($_); + + # .bs files are optional + @missing = grep { ! /\.bs$/ } @missing; + # man files are often compressed + @missing = grep { ! ( -s "$_.gz" || -s "$_.bz2" ) } @missing; + + if ($#missing >= 0) { + print "# file",+($#missing == 0) ? '' : 's'," missing from installation:\n"; + print '# ',join(' ',@missing),"\n"; + } + elsif ($#missing == -1) { + $installed_there++; + } + @missing = (); +} +$label = 'Module files correctly installed'; +if (($installed_total == $installed_there) && + ($installed_total == $version_check)) { + print "ok 6 $label\n"; + $pass__total++; +} +else { + print "not ok 6 $label\n"; + $error_total++; +} +$tests_total++; + +# Final report (rather than feed ousrselves to Test::Harness::runtests() +# we simply format some output on our own to keep things simple and +# easier to "fix" - at least for now. + +if ($error_total == 0 && $tests_total) { + print "All tests successful.\n"; +} elsif ($tests_total==0){ + die "FAILED--no tests were run for some reason.\n"; +} else { + my $rate = 0.0; + if ($tests_total > 0) { $rate = sprintf "%.2f", 100.0 * ($pass__total / $tests_total); } + printf " %d/%d subtests failed, %.2f%% okay.\n", + $error_total, $tests_total, $rate; +} + +=head1 NAME + +perlivp - Perl Installation Verification Procedure + +=head1 SYNOPSIS + +B [B<-p>] [B<-v>] [B<-h>] + +=head1 DESCRIPTION + +The B program is set up at Perl source code build time to test the +Perl version it was built under. It can be used after running: + + make install + +(or your platform's equivalent procedure) to verify that B and its +libraries have been installed correctly. A correct installation is verified +by output that looks like: + + ok 1 + ok 2 + +etc. + +=head1 OPTIONS + +=over 5 + +=item B<-h> help + +Prints out a brief help message. + +=item B<-p> print preface + +Gives a description of each test prior to performing it. + +=item B<-v> verbose + +Gives more detailed information about each test, after it has been performed. +Note that any failed tests ought to print out some extra information whether +or not -v is thrown. + +=back + +=head1 DIAGNOSTICS + +=over 4 + +=item * print "# Perl binary '$perlpath' does not appear executable.\n"; + +Likely to occur for a perl binary that was not properly installed. +Correct by conducting a proper installation. + +=item * print "# Perl version '$]' installed, expected $ivp_VERSION.\n"; + +Likely to occur for a perl that was not properly installed. +Correct by conducting a proper installation. + +=item * print "# Perl \@INC directory '$_' does not appear to exist.\n"; + +Likely to occur for a perl library tree that was not properly installed. +Correct by conducting a proper installation. + +=item * print "# Needed module '$_' does not appear to be properly installed.\n"; + +One of the two modules that is used by perlivp was not present in the +installation. This is a serious error since it adversely affects perlivp's +ability to function. You may be able to correct this by performing a +proper perl installation. + +=item * print "# Required module '$_' does not appear to be properly installed.\n"; + +An attempt to C failed, even though the list of +extensions indicated that it should succeed. Correct by conducting a proper +installation. + +=item * print "# Unnecessary module 'bLuRfle' appears to be installed.\n"; + +This test not coming out ok could indicate that you have in fact installed +a bLuRfle.pm module or that the C +test may give misleading results with your installation of perl. If yours +is the latter case then please let the author know. + +=item * print "# file",+($#missing == 0) ? '' : 's'," missing from installation:\n"; + +One or more files turned up missing according to a run of +C validate()> over your installation. +Correct by conducting a proper installation. + +=back + +For further information on how to conduct a proper installation consult the +INSTALL file that comes with the perl source and the README file for your +platform. + +=head1 AUTHOR + +Peter Prymmer + +=cut + diff --git a/git/usr/bin/core_perl/perlthanks b/git/usr/bin/core_perl/perlthanks new file mode 100644 index 0000000000000000000000000000000000000000..95bcf62c20b6fd50df5e0ef5ea65446f2527d116 --- /dev/null +++ b/git/usr/bin/core_perl/perlthanks @@ -0,0 +1,1537 @@ +#!/usr/bin/perl + eval 'exec /usr/bin/perl -S $0 ${1+"$@"}' + if 0; # ^ Run only under a shell + +my $config_tag1 = '5.42.2 - Thu Apr 2 19:54:57 UTC 2026'; + +my $patchlevel_date = 1774202317; +my @patches = Config::local_patches(); +my $patch_tags = join "", map /(\S+)/ ? "+$1 " : (), @patches; + +BEGIN { pop @INC if $INC[-1] eq '.' } +use warnings; +use strict; +use Config; +use File::Spec; # keep perlbug Perl 5.005 compatible +use Getopt::Std; +use File::Basename 'basename'; + +$Getopt::Std::STANDARD_HELP_VERSION = 1; + +sub paraprint; + +BEGIN { + eval { require Mail::Send;}; + $::HaveSend = ($@ eq ""); + eval { require Mail::Util; } ; + $::HaveUtil = (!$ENV{PERL_BUILD_PACKAGING} and $@ eq ""); + # use secure tempfiles wherever possible + eval { require File::Temp; }; + $::HaveTemp = ($@ eq ""); + eval { require Module::CoreList; }; + $::HaveCoreList = ($@ eq ""); + eval { require Text::Wrap; }; + $::HaveWrap = ($@ eq ""); +}; + +our $VERSION = "1.43"; + +#TODO: +# make sure failure (transmission-wise) of Mail::Send is accounted for. +# (This may work now. Unsure of the original author's issue -JESSE 2008-06-08) +# - Test -b option + +my( $file, $usefile, $cc, $address, $thanksaddress, + $filename, $messageid, $domain, $subject, $from, $verbose, $ed, $outfile, + $fh, $me, $body, $andcc, %REP, $ok, $thanks, $progname, + $Is_MSWin32, $Is_Linux, $Is_VMS, $Is_OpenBSD, + $report_about_module, $category, $severity, + %opt, $have_attachment, $attachments, $has_patch, $mime_boundary +); + +my $running_noninteractively = !-t STDIN; + +my $perl_version = $^V ? sprintf("%vd", $^V) : $]; + +my $config_tag2 = "$perl_version - $Config{cf_time}"; + +Init(); + +if ($opt{h}) { Help(); exit; } +if ($opt{d}) { Dump(*STDOUT); exit; } +if ($running_noninteractively && !$opt{t} && !($ok and not $opt{n})) { + paraprint <<"EOF"; +Please use $progname interactively. If you want to +include a file, you can use the -f switch. +EOF + die "\n"; +} + +Query(); +Edit() unless $usefile || ($ok and not $opt{n}); +NowWhat(); +if ($address) { + Send(); + if ($thanks) { + print "\nThank you for taking the time to send a thank-you message!\n\n"; + + paraprint < { + 'default' => 'core', + 'ok' => 'install', + # Inevitably some of these will end up in RT whatever we do: + 'thanks' => 'thanks', + 'opts' => [qw(core docs install library utilities)], # patch, notabug + }, + 'severity' => { + 'default' => 'low', + 'ok' => 'none', + 'thanks' => 'none', + 'opts' => [qw(critical high medium low wishlist none)], # zero + }, + ); + die "Invalid alternative ($name) requested\n" unless grep(/^$name$/, keys %alts); + my $alt = ""; + my $what = $ok || $thanks; + if ($what) { + $alt = $alts{$name}{$what}; + } else { + my @alts = @{$alts{$name}{'opts'}}; + print "\n\n"; + paraprint < 5) { + die "Invalid $name: aborting.\n"; + } + $alt = _prompt('', "\u$name", $alts{$name}{'default'}); + $alt ||= $alts{$name}{'default'}; + } while !((($alt) = grep(/^$alt/i, @alts))); + } + lc $alt; +} + +sub HELP_MESSAGE { Help(); exit; } +sub VERSION_MESSAGE { print "perlbug version $VERSION\n"; } + +sub Init { + # -------- Setup -------- + + $Is_MSWin32 = $^O eq 'MSWin32'; + $Is_VMS = $^O eq 'VMS'; + $Is_Linux = lc($^O) eq 'linux'; + $Is_OpenBSD = lc($^O) eq 'openbsd'; + + # Thanks address + $thanksaddress = 'perl-thanks@perl.org'; + + # Defaults if getopts fails. + $outfile = (basename($0) =~ /^perlthanks/i) ? "perlthanks.rep" : "perlbug.rep"; + $cc = $::Config{'perladmin'} || $::Config{'cf_email'} || $::Config{'cf_by'} || ''; + + HELP_MESSAGE() unless getopts("Adhva:s:b:f:F:r:e:SCc:to:n:T:p:", \%opt); + + # This comment is needed to notify metaconfig that we are + # using the $perladmin, $cf_by, and $cf_time definitions. + # -------- Configuration --------- + + if (basename ($0) =~ /^perlthanks/i) { + # invoked as perlthanks + $opt{T} = 1; + $opt{C} = 1; # don't send a copy to the local admin + } + + if ($opt{T}) { + $thanks = 'thanks'; + } + + $progname = $thanks ? 'perlthanks' : 'perlbug'; + # Target address + $address = $opt{a} || ($thanks ? $thanksaddress : ""); + + # Users address, used in message and in From and Reply-To headers + $from = $opt{r} || ""; + + # Include verbose configuration information + $verbose = $opt{v} || 0; + + # Subject of bug-report message + $subject = $opt{s} || ""; + + # Send a file + $usefile = ($opt{f} || 0); + + # File to send as report + $file = $opt{f} || ""; + + # We have one or more attachments + $have_attachment = ($opt{p} || 0); + $mime_boundary = ('-' x 12) . "$VERSION.perlbug" if $have_attachment; + + # Comma-separated list of attachments + $attachments = $opt{p} || ""; + $has_patch = 0; # TBD based on file type + + for my $attachment (split /\s*,\s*/, $attachments) { + unless (-f $attachment && -r $attachment) { + die "The attachment $attachment is not a readable file: $!\n"; + } + $has_patch = 1 if $attachment =~ m/\.(patch|diff)$/; + } + + # File to output to + $outfile = $opt{F} || "$progname.rep"; + + # Body of report + $body = $opt{b} || ""; + + # Editor + $ed = $opt{e} || $ENV{VISUAL} || $ENV{EDITOR} || $ENV{EDIT} + || ($Is_VMS && "edit/tpu") + || ($Is_MSWin32 && "notepad") + || "vi"; + + # Not OK - provide build failure template by finessing OK report + if ($opt{n}) { + if (substr($opt{n}, 0, 2) eq 'ok' ) { + $opt{o} = substr($opt{n}, 1); + } else { + Help(); + exit(); + } + } + + # OK - send "OK" report for build on this system + $ok = ''; + if ($opt{o}) { + if ($opt{o} eq 'k' or $opt{o} eq 'kay') { + my $age = time - $patchlevel_date; + if ($opt{o} eq 'k' and $age > 60 * 24 * 60 * 60 ) { + my $date = localtime $patchlevel_date; + print <<"EOF"; +"perlbug -ok" and "perlbug -nok" do not report on Perl versions which +are more than 60 days old. This Perl version was constructed on +$date. If you really want to report this, use +"perlbug -okay" or "perlbug -nokay". +EOF + exit(); + } + # force these options + unless ($opt{n}) { + $opt{S} = 1; # don't prompt for send + $opt{b} = 1; # we have a body + $body = "Perl reported to build OK on this system.\n"; + } + $opt{C} = 1; # don't send a copy to the local admin + $opt{s} = 1; # we have a subject line + $subject = ($opt{n} ? 'Not ' : '') + . "OK: perl $perl_version ${patch_tags}on" + ." $::Config{'archname'} $::Config{'osvers'} $subject"; + $ok = 'ok'; + } else { + Help(); + exit(); + } + } + + # Possible administrator addresses, in order of confidence + # (Note that cf_email is not mentioned to metaconfig, since + # we don't really want it. We'll just take it if we have to.) + # + # This has to be after the $ok stuff above because of the way + # that $opt{C} is forced. + $cc = $opt{C} ? "" : ( + $opt{c} || $::Config{'perladmin'} + || $::Config{'cf_email'} || $::Config{'cf_by'} + ); + + if ($::HaveUtil) { + $domain = Mail::Util::maildomain(); + } elsif ($Is_MSWin32) { + $domain = $ENV{'USERDOMAIN'}; + } else { + require Sys::Hostname; + $domain = Sys::Hostname::hostname(); + } + + # Message-Id - rjsf + $messageid = "<$::Config{'version'}_${$}_".time."\@$domain>"; + + # My username + $me = $Is_MSWin32 ? $ENV{'USERNAME'} + : $^O eq 'os2' ? $ENV{'USER'} || $ENV{'LOGNAME'} + : eval { getpwuid($<) }; # May be missing + + $from = $::Config{'cf_email'} + if !$from && $::Config{'cf_email'} && $::Config{'cf_by'} && $me && + ($me eq $::Config{'cf_by'}); +} # sub Init + +sub Query { + # Explain what perlbug is + unless ($ok) { + if ($thanks) { + paraprint <<'EOF'; +This program provides an easy way to send a thank-you message back to the +authors and maintainers of perl. + +If you wish to generate a bug report, please run it without the -T flag +(or run the program perlbug rather than perlthanks) +EOF + } else { + paraprint <<"EOF"; +This program provides an easy way to generate a bug report for the core +perl distribution (along with tests or patches). To send a thank-you +note to $thanksaddress instead of a bug report, please run 'perlthanks'. + +The GitHub issue tracker at https://github.com/Perl/perl5/issues is the +best place to submit your report so it can be tracked and resolved. + +Please do not use $0 to report bugs in perl modules from CPAN. + +Suggestions for how to find help using Perl can be found at +https://perldoc.perl.org/perlcommunity.html +EOF + } + } + + # Prompt for subject of message, if needed + + if ($subject && TrivialSubject($subject)) { + $subject = ''; + } + + unless ($subject) { + print +"First of all, please provide a subject for the report.\n"; + if ( not $thanks) { + paraprint <first_release($entry); + if ($entry and not $first_release) { + paraprint <:raw', $filename) or die "Unable to create report file '$filename': $!\n"; + binmode(REP, ':raw :crlf') if $Is_MSWin32; + + my $reptype = !$ok ? ($thanks ? 'thank-you' : 'bug') + : $opt{n} ? "build failure" : "success"; + + print REP <) { + print REP $_ + } + close(F) or die "Error closing '$file': $!"; + } else { + if ($thanks) { + print REP <<'EOF'; + +----------------------------------------------------------------- +[Please enter your thank-you message here] + + + +[You're welcome to delete anything below this line] +----------------------------------------------------------------- +EOF + } else { + print REP <<'EOF'; + +----------------------------------------------------------------- + + +**Description** + + + + +**Steps to Reproduce** + + + + +**Expected behavior** + + + + + + +EOF + } + } + Dump(*REP); + close(REP) or die "Error closing report file: $!"; + + # Set up an initial report fingerprint so we can compare it later + _fingerprint_lines_in_report(); + +} # sub Query + +sub Dump { + local(*OUT) = @_; + + # these won't have been set if run with -d + $category ||= 'core'; + $severity ||= 'low'; + + print OUT <etry dit + next; + } elsif ( $action =~ /^[cq]/i ) { # ancel, uit + Cancel(); # cancel exits + } + } + # Ok. the user did what they needed to; + return; + + } +} + + +sub Cancel { + 1 while unlink($filename); # remove all versions under VMS + print "\nQuitting without generating a report.\n"; + exit(0); +} + +sub NowWhat { + # Report is done, prompt for further action + if( !$opt{S} ) { + while(1) { + my $send_to = $address || 'the Perl developers'; + my $menu = <ile/ve + if ( SaveMessage() ) { exit } + } elsif ($action =~ /^(d|l|sh)/i ) { # isplay, ist, ow + # Display the message + print _read_report($filename); + if ($have_attachment) { + print "\n\n---\nAttachment(s):\n"; + for my $att (split /\s*,\s*/, $attachments) { print " $att\n"; } + } + } elsif ($action =~ /^su/i) { # bject + my $reply = _prompt( "Subject: $subject", "If the above subject is fine, press Enter. Otherwise, type a replacement now\nSubject"); + if ($reply ne '') { + unless (TrivialSubject($reply)) { + $subject = $reply; + print "Subject: $subject\n"; + } + } + } elsif ($action =~ /^se/i) { # end + # Send the message + if (not $thanks) { + print <dit, e-edit + # edit the message + Edit(); + } elsif ($action =~ /^[qc]/i) { # ancel, uit + Cancel(); + } elsif ($action =~ /^s/i) { + paraprint < 1); + close($fh); + return $filename; + } else { + # Bah. Fall back to doing things less securely. + my $dir = File::Spec->tmpdir(); + $filename = "bugrep0$$"; + $filename++ while -e File::Spec->catfile($dir, $filename); + $filename = File::Spec->catfile($dir, $filename); + } +} + +sub paraprint { + my @paragraphs = split /\n{2,}/, "@_"; + for (@paragraphs) { # implicit local $_ + s/(\S)\s*\n/$1 /g; + write; + print "\n"; + } +} + +sub _prompt { + my ($explanation, $prompt, $default) = (@_); + if ($explanation) { + print "\n\n"; + paraprint $explanation; + } + print $prompt. ($default ? " [$default]" :''). ": "; + my $result = scalar(<>); + return $default if !defined $result; # got eof + chomp($result); + $result =~ s/^\s*(.*?)\s*$/$1/s; + if ($default && $result eq '') { + return $default; + } else { + return $result; + } +} + +sub _build_header { + my %attr = (@_); + + my $head = ''; + for my $header (keys %attr) { + $head .= "$header: ".$attr{$header}."\n"; + } + return $head; +} + +sub _message_headers { + my %headers = ( To => $address || 'perl5-porters@perl.org', Subject => $subject ); + $headers{'Cc'} = $cc if ($cc); + $headers{'Message-Id'} = $messageid if ($messageid); + $headers{'Reply-To'} = $from if ($from); + $headers{'From'} = $from if ($from); + if ($have_attachment) { + $headers{'MIME-Version'} = '1.0'; + $headers{'Content-Type'} = qq{multipart/mixed; boundary=\"$mime_boundary\"}; + } + return \%headers; +} + +sub _add_body_start { + my $body_start = <<"BODY_START"; +This is a multi-part message in MIME format. +--$mime_boundary +Content-Type: text/plain; format=fixed +Content-Transfer-Encoding: 8bit + +BODY_START + return $body_start; +} + +sub _add_attachments { + my $attach = ''; + for my $attachment (split /\s*,\s*/, $attachments) { + my $attach_file = basename($attachment); + $attach .= <<"ATTACHMENT"; + +--$mime_boundary +Content-Type: text/x-patch; name="$attach_file" +Content-Transfer-Encoding: 8bit +Content-Disposition: attachment; filename="$attach_file" + +ATTACHMENT + + open my $attach_fh, '<:raw', $attachment + or die "Couldn't open attachment '$attachment': $!\n"; + while (<$attach_fh>) { $attach .= $_; } + close($attach_fh) or die "Error closing attachment '$attachment': $!"; + } + + $attach .= "\n--$mime_boundary--\n"; + return $attach; +} + +sub _read_report { + my $fname = shift; + my $content; + open( REP, "<:raw", $fname ) or die "Couldn't open file '$fname': $!\n"; + binmode(REP, ':raw :crlf') if $Is_MSWin32; + # wrap long lines to make sure the report gets delivered + local $Text::Wrap::columns = 900; + local $Text::Wrap::huge = 'overflow'; + while () { + if ($::HaveWrap && /\S/) { # wrap() would remove empty lines + $content .= Text::Wrap::wrap(undef, undef, $_); + } else { + $content .= $_; + } + } + close(REP) or die "Error closing report file '$fname': $!"; + return $content; +} + +sub build_complete_message { + my $content = _build_header(%{_message_headers()}) . "\n\n"; + $content .= _add_body_start() if $have_attachment; + $content .= _read_report($filename); + $content .= _add_attachments() if $have_attachment; + return $content; +} + +sub save_message_to_disk { + my $file = shift; + + if (-e $file) { + my $response = _prompt( '', "Overwrite existing '$file'", 'n' ); + return undef unless $response =~ / yes | y /xi; + } + open OUTFILE, '>:raw', $file or do { warn "Couldn't open '$file': $!\n"; return undef}; + binmode(OUTFILE, ':raw :crlf') if $Is_MSWin32; + + print OUTFILE build_complete_message(); + close(OUTFILE) or do { warn "Error closing $file: $!"; return undef }; + print "\nReport saved to '$file'. Please submit it to https://github.com/Perl/perl5/issues\n"; + return 1; +} + +sub _send_message_vms { + + my $mail_from = $from; + my $rcpt_to_to = $address; + my $rcpt_to_cc = $cc; + + map { $_ =~ s/^[^<]*[^>]*//; } ($mail_from, $rcpt_to_to, $rcpt_to_cc); + + if ( open my $sff_fh, '|-:raw', 'MCR TCPIP$SYSTEM:TCPIP$SMTP_SFF.EXE SYS$INPUT:' ) { + print $sff_fh "MAIL FROM:<$mail_from>\n"; + print $sff_fh "RCPT TO:<$rcpt_to_to>\n"; + print $sff_fh "RCPT TO:<$rcpt_to_cc>\n" if $rcpt_to_cc; + print $sff_fh "DATA\n"; + print $sff_fh build_complete_message(); + my $success = close $sff_fh; + if ($success ) { + print "\nMessage sent\n"; + return; + } + } + die "Mail transport failed (leaving bug report in $filename): $^E\n"; +} + +sub _send_message_mailsend { + my $msg = Mail::Send->new(); + my %headers = %{_message_headers()}; + for my $key ( keys %headers) { + $msg->add($key => $headers{$key}); + } + + $fh = $msg->open; + binmode($fh, ':raw'); + print $fh _add_body_start() if $have_attachment; + print $fh _read_report($filename); + print $fh _add_attachments() if $have_attachment; + $fh->close or die "Error sending mail: $!"; + + print "\nMessage sent.\n"; +} + +sub _probe_for_sendmail { + my $sendmail = ""; + for (qw(/usr/lib/sendmail /usr/sbin/sendmail /usr/ucblib/sendmail)) { + $sendmail = $_, last if -e $_; + } + if ( $^O eq 'os2' and $sendmail eq "" ) { + my $path = $ENV{PATH}; + $path =~ s:\\:/:; + my @path = split /$Config{'path_sep'}/, $path; + for (@path) { + $sendmail = "$_/sendmail", last if -e "$_/sendmail"; + $sendmail = "$_/sendmail.exe", last if -e "$_/sendmail.exe"; + } + } + return $sendmail; +} + +sub _send_message_sendmail { + my $sendmail = _probe_for_sendmail(); + unless ($sendmail) { + my $message_start = !$Is_Linux && !$Is_OpenBSD ? <<'EOT' : <<'EOT'; +It appears that there is no program which looks like "sendmail" on +your system and that the Mail::Send library from CPAN isn't available. +EOT +It appears that there is no program which looks like "sendmail" on +your system. +EOT + paraprint(<<"EOF"), die "\n"; +$message_start +Because of this, there's no easy way to automatically send your +report. + +A copy of your report has been saved in '$filename' for you to +send to '$address' with your normal mail client. +EOF + } + + open( SENDMAIL, "|-:raw", $sendmail, "-t", "-oi", "-f", $from ) + || die "'|$sendmail -t -oi -f $from' failed: $!"; + print SENDMAIL build_complete_message(); + if ( close(SENDMAIL) ) { + print "\nMessage sent\n"; + } else { + warn "\nSendmail returned status '", $? >> 8, "'\n"; + } +} + + + +# a strange way to check whether any significant editing +# has been done: check whether any new non-empty lines +# have been added. + +sub _fingerprint_lines_in_report { + my $new_lines = 0; + # read in the report template once so that + # we can track whether the user does any editing. + # yes, *all* whitespace is ignored. + + open(REP, '<:raw', $filename) or die "Unable to open report file '$filename': $!\n"; + binmode(REP, ':raw :crlf') if $Is_MSWin32; + while (my $line = ) { + $line =~ s/\s+//g; + $new_lines++ if (!$REP{$line}); + + } + close(REP) or die "Error closing report file '$filename': $!"; + # returns the number of lines with content that wasn't there when last we looked + return $new_lines; +} + + + +format STDOUT = +^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~~ +$_ +. + +__END__ + +=head1 NAME + +perlbug - how to submit bug reports on Perl + +=head1 SYNOPSIS + +B + +B S<[ B<-v> ]> S<[ B<-a> I
]> S<[ B<-s> I ]> +S<[ B<-b> I | B<-f> I ]> S<[ B<-F> I ]> +S<[ B<-r> I ]> +S<[ B<-e> I ]> S<[ B<-c> I | B<-C> ]> +S<[ B<-S> ]> S<[ B<-t> ]> S<[ B<-d> ]> S<[ B<-h> ]> S<[ B<-T> ]> + +B S<[ B<-v> ]> S<[ B<-r> I ]> + S<[ B<-ok> | B<-okay> | B<-nok> | B<-nokay> ]> + +B + +=head1 DESCRIPTION + + +This program is designed to help you generate bug reports +(and thank-you notes) about perl5 and the modules which ship with it. + +In most cases, you can just run it interactively from a command +line without any special arguments and follow the prompts. + +If you have found a bug with a non-standard port (one that was not +part of the I), a binary distribution, or a +non-core module (such as Tk, DBI, etc), then please see the +documentation that came with that distribution to determine the +correct place to report bugs. + +Bug reports should be submitted to the GitHub issue tracker at +L. The B +address no longer automatically opens tickets. You can use this tool +to compose your report and save it to a file which you can then submit +to the issue tracker. + +In extreme cases, B may not work well enough on your system +to guide you through composing a bug report. In those cases, you +may be able to use B or B to get system +configuration information to include in your issue report. + + +When reporting a bug, please run through this checklist: + +=over 4 + +=item What version of Perl you are running? + +Type C at the command line to find out. + +=item Are you running the latest released version of perl? + +Look at L to find out. If you are not using the +latest released version, please try to replicate your bug on the +latest stable release. + +Note that reports about bugs in old versions of Perl, especially +those which indicate you haven't also tested the current stable +release of Perl, are likely to receive less attention from the +volunteers who build and maintain Perl than reports about bugs in +the current release. + +=item Are you sure what you have is a bug? + +A significant number of the bug reports we get turn out to be +documented features in Perl. Make sure the issue you've run into +isn't intentional by glancing through the documentation that comes +with the Perl distribution. + +Given the sheer volume of Perl documentation, this isn't a trivial +undertaking, but if you can point to documentation that suggests +the behaviour you're seeing is I, your issue is likely to +receive more attention. You may want to start with B +L for pointers to common traps that new (and experienced) +Perl programmers run into. + +If you're unsure of the meaning of an error message you've run +across, B L for an explanation. If the message +isn't in perldiag, it probably isn't generated by Perl. You may +have luck consulting your operating system documentation instead. + +If you are on a non-UNIX platform B L, as some +features may be unimplemented or work differently. + +You may be able to figure out what's going wrong using the Perl +debugger. For information about how to use the debugger B +L. + +=item Do you have a proper test case? + +The easier it is to reproduce your bug, the more likely it will be +fixed -- if nobody can duplicate your problem, it probably won't be +addressed. + +A good test case has most of these attributes: short, simple code; +few dependencies on external commands, modules, or libraries; no +platform-dependent code (unless it's a platform-specific bug); +clear, simple documentation. + +A good test case is almost always a good candidate to be included in +Perl's test suite. If you have the time, consider writing your test case so +that it can be easily included into the standard test suite. + +=item Have you included all relevant information? + +Be sure to include the B error messages, if any. +"Perl gave an error" is not an exact error message. + +If you get a core dump (or equivalent), you may use a debugger +(B, B, etc) to produce a stack trace to include in the bug +report. + +NOTE: unless your Perl has been compiled with debug info +(often B<-g>), the stack trace is likely to be somewhat hard to use +because it will most probably contain only the function names and not +their arguments. If possible, recompile your Perl with debug info and +reproduce the crash and the stack trace. + +=item Can you describe the bug in plain English? + +The easier it is to understand a reproducible bug, the more likely +it will be fixed. Any insight you can provide into the problem +will help a great deal. In other words, try to analyze the problem +(to the extent you can) and report your discoveries. + +=item Can you fix the bug yourself? + +If so, that's great news; bug reports with patches are likely to +receive significantly more attention and interest than those without +patches. Please submit your patch via the GitHub Pull Request workflow +as described in B L. You may also send patches to +B. When sending a patch, create it using +C if possible, though a unified diff created with +C will do nearly as well. + +Your patch may be returned with requests for changes, or requests for more +detailed explanations about your fix. + +Here are a few hints for creating high-quality patches: + +Make sure the patch is not reversed (the first argument to diff is +typically the original file, the second argument your changed file). +Make sure you test your patch by applying it with C or the +C program before you send it on its way. Try to follow the +same style as the code you are trying to patch. Make sure your patch +really does work (C, if the thing you're patching is covered +by Perl's test suite). + +=item Can you use C to submit a thank-you note? + +Yes, you can do this by either using the C<-T> option, or by invoking +the program as C. Thank-you notes are good. It makes people +smile. + +=back + +Please make your issue title informative. "a bug" is not informative. +Neither is "perl crashes" nor is "HELP!!!". These don't help. A compact +description of what's wrong is fine. + +Having done your bit, please be prepared to wait, to be told the +bug is in your code, or possibly to get no reply at all. The +volunteers who maintain Perl are busy folks, so if your problem is +an obvious bug in your own code, is difficult to understand or is +a duplicate of an existing report, you may not receive a personal +reply. + +If it is important to you that your bug be fixed, do monitor the +issue tracker (you will be subscribed to notifications for issues you +submit or comment on) and the commit logs to development +versions of Perl, and encourage the maintainers with kind words or +offers of frosty beverages. (Please do be kind to the maintainers. +Harassing or flaming them is likely to have the opposite effect of the +one you want.) + +Feel free to update the ticket about your bug on +L +if a new version of Perl is released and your bug is still present. + +=head1 OPTIONS + +=over 8 + +=item B<-a> + +Address to send the report to instead of saving to a file. + +=item B<-b> + +Body of the report. If not included on the command line, or +in a file with B<-f>, you will get a chance to edit the report. + +=item B<-C> + +Don't send copy to administrator when sending report by mail. + +=item B<-c> + +Address to send copy of report to when sending report by mail. +Defaults to the address of the +local perl administrator (recorded when perl was built). + +=item B<-d> + +Data mode (the default if you redirect or pipe output). This prints out +your configuration data, without saving or mailing anything. You can use +this with B<-v> to get more complete data. + +=item B<-e> + +Editor to use. + +=item B<-f> + +File containing the body of the report. Use this to quickly send a +prepared report. + +=item B<-F> + +File to output the results to. Defaults to B. + +=item B<-h> + +Prints a brief summary of the options. + +=item B<-ok> + +Report successful build on this system to perl porters. Forces B<-S> +and B<-C>. Forces and supplies values for B<-s> and B<-b>. Only +prompts for a return address if it cannot guess it (for use with +B). Honors return address specified with B<-r>. You can use this +with B<-v> to get more complete data. Only makes a report if this +system is less than 60 days old. + +=item B<-okay> + +As B<-ok> except it will report on older systems. + +=item B<-nok> + +Report unsuccessful build on this system. Forces B<-C>. Forces and +supplies a value for B<-s>, then requires you to edit the report +and say what went wrong. Alternatively, a prepared report may be +supplied using B<-f>. Only prompts for a return address if it +cannot guess it (for use with B). Honors return address +specified with B<-r>. You can use this with B<-v> to get more +complete data. Only makes a report if this system is less than 60 +days old. + +=item B<-nokay> + +As B<-nok> except it will report on older systems. + +=item B<-p> + +The names of one or more patch files or other text attachments to be +included with the report. Multiple files must be separated with commas. + +=item B<-r> + +Your return address. The program will ask you to confirm its default +if you don't use this option. + +=item B<-S> + +Save or send the report without asking for confirmation. + +=item B<-s> + +Subject to include with the report. You will be prompted if you don't +supply one on the command line. + +=item B<-t> + +Test mode. Makes it possible to command perlbug from a pipe or file, for +testing purposes. + +=item B<-T> + +Send a thank-you note instead of a bug report. + +=item B<-v> + +Include verbose configuration data in the report. + +=back + +=head1 AUTHORS + +Kenneth Albanowski (Ekjahds@kjahds.comE), subsequently +Itored by Gurusamy Sarathy (Egsar@activestate.comE), +Tom Christiansen (Etchrist@perl.comE), Nathan Torkington +(Egnat@frii.comE), Charles F. Randall (Ecfr@pobox.comE), +Mike Guy (Emjtg@cam.ac.ukE), Dominic Dunlop +(Edomo@computer.orgE), Hugo van der Sanden (Ehv@crypt.orgE), +Jarkko Hietaniemi (Ejhi@iki.fiE), Chris Nandor +(Epudge@pobox.comE), Jon Orwant (Eorwant@media.mit.eduE, +Richard Foley (Erichard.foley@rfi.netE), Jesse Vincent +(Ejesse@bestpractical.comE), and Craig A. Berry (Ecraigberry@mac.comE). + +=head1 SEE ALSO + +perl(1), perldebug(1), perldiag(1), perlport(1), perltrap(1), +diff(1), patch(1), dbx(1), gdb(1) + +=head1 BUGS + +None known (guess what must have been used to report them?) + +=cut + diff --git a/git/usr/bin/core_perl/piconv b/git/usr/bin/core_perl/piconv new file mode 100644 index 0000000000000000000000000000000000000000..6c58e3eb195a9fc650c194fb134b68cbf5d76665 --- /dev/null +++ b/git/usr/bin/core_perl/piconv @@ -0,0 +1,322 @@ +#!/usr/bin/perl + eval 'exec /usr/bin/perl -S $0 ${1+"$@"}' + if 0; # ^ Run only under a shell +#!./perl +# $Id: piconv,v 2.8 2016/08/04 03:15:58 dankogai Exp $ +# +BEGIN { pop @INC if $INC[-1] eq '.' } +use 5.8.0; +use strict; +use Encode ; +use Encode::Alias; +my %Scheme = map {$_ => 1} qw(from_to decode_encode perlio); + +use File::Basename; +my $name = basename($0); + +use Getopt::Long qw(:config no_ignore_case); + +my %Opt; + +help() + unless + GetOptions(\%Opt, + 'from|f=s', + 'to|t=s', + 'list|l', + 'string|s=s', + 'check|C=i', + 'c', + 'perlqq|p', + 'htmlcref', + 'xmlcref', + 'debug|D', + 'scheme|S=s', + 'resolve|r=s', + 'help', + ); + +$Opt{help} and help(); +$Opt{list} and list_encodings(); +my $locale = $ENV{LC_CTYPE} || $ENV{LC_ALL} || $ENV{LANG}; +defined $Opt{resolve} and resolve_encoding($Opt{resolve}); +$Opt{from} || $Opt{to} || help(); +my $from = $Opt{from} || $locale or help("from_encoding unspecified"); +my $to = $Opt{to} || $locale or help("to_encoding unspecified"); +$Opt{string} and Encode::from_to($Opt{string}, $from, $to) and print $Opt{string} and exit; +my $scheme = do { + if (defined $Opt{scheme}) { + if (!exists $Scheme{$Opt{scheme}}) { + warn "Unknown scheme '$Opt{scheme}', fallback to 'from_to'.\n"; + 'from_to'; + } else { + $Opt{scheme}; + } + } else { + 'from_to'; + } +}; + +$Opt{check} ||= $Opt{c}; +$Opt{perlqq} and $Opt{check} = Encode::PERLQQ; +$Opt{htmlcref} and $Opt{check} = Encode::HTMLCREF; +$Opt{xmlcref} and $Opt{check} = Encode::XMLCREF; + +my $efrom = Encode->getEncoding($from) || die "Unknown encoding '$from'"; +my $eto = Encode->getEncoding($to) || die "Unknown encoding '$to'"; + +my $cfrom = $efrom->name; +my $cto = $eto->name; + +if ($Opt{debug}){ + print <<"EOT"; +Scheme: $scheme +From: $from => $cfrom +To: $to => $cto +EOT +} + +my %use_bom = + map { $_ => 1 } qw/UTF-16 UTF-16BE UTF-16LE UTF-32 UTF-32BE UTF-32LE/; + +# we do not use <> (or ARGV) for the sake of binmode() +@ARGV or push @ARGV, \*STDIN; + +unless ( $scheme eq 'perlio' ) { + binmode STDOUT; + my $need2slurp = $use_bom{ $eto } || $use_bom{ $efrom }; + for my $argv (@ARGV) { + my $ifh = ref $argv ? $argv : undef; + $ifh or open $ifh, "<", $argv or warn "Can't open $argv: $!" and next; + $ifh or open $ifh, "<", $argv or next; + binmode $ifh; + if ( $scheme eq 'from_to' ) { # default + if ($need2slurp){ + local $/; + $_ = <$ifh>; + Encode::from_to( $_, $from, $to, $Opt{check} ); + print; + }else{ + while (<$ifh>) { + Encode::from_to( $_, $from, $to, $Opt{check} ); + print; + } + } + } + elsif ( $scheme eq 'decode_encode' ) { # step-by-step + if ($need2slurp){ + local $/; + $_ = <$ifh>; + my $decoded = decode( $from, $_, $Opt{check} ); + my $encoded = encode( $to, $decoded ); + print $encoded; + }else{ + while (<$ifh>) { + my $decoded = decode( $from, $_, $Opt{check} ); + my $encoded = encode( $to, $decoded ); + print $encoded; + } + } + } + else { # won't reach + die "$name: unknown scheme: $scheme"; + } + } +} +else { + + # NI-S favorite + binmode STDOUT => "raw:encoding($to)"; + for my $argv (@ARGV) { + my $ifh = ref $argv ? $argv : undef; + $ifh or open $ifh, "<", $argv or warn "Can't open $argv: $!" and next; + $ifh or open $ifh, "<", $argv or next; + binmode $ifh => "raw:encoding($from)"; + print while (<$ifh>); + } +} + +sub list_encodings { + print join( "\n", Encode->encodings(":all") ), "\n"; + exit 0; +} + +sub resolve_encoding { + if ( my $alias = Encode::resolve_alias( $_[0] ) ) { + print $alias, "\n"; + exit 0; + } + else { + warn "$name: $_[0] is not known to Encode\n"; + exit 1; + } +} + +sub help { + my $message = shift; + $message and print STDERR "$name error: $message\n"; + print STDERR <<"EOT"; +$name [-f from_encoding] [-t to_encoding] + [-p|--perlqq|--htmlcref|--xmlcref] [-C N|-c] [-D] [-S scheme] + [-s string|file...] +$name -l +$name -r encoding_alias +$name -h +Common options: + -l,--list + lists all available encodings + -r,--resolve encoding_alias + resolve encoding to its (Encode) canonical name + -f,--from from_encoding + when omitted, the current locale will be used + -t,--to to_encoding + when omitted, the current locale will be used + -s,--string string + "string" will be the input instead of STDIN or files +The following are mainly of interest to Encode hackers: + -C N | -c check the validity of the input + -D,--debug show debug information + -S,--scheme scheme use the scheme for conversion +Those are handy when you can only see ASCII characters: + -p,--perlqq transliterate characters missing in encoding to \\x{HHHH} + where HHHH is the hexadecimal Unicode code point + --htmlcref transliterate characters missing in encoding to &#NNN; + where NNN is the decimal Unicode code point + --xmlcref transliterate characters missing in encoding to &#xHHHH; + where HHHH is the hexadecimal Unicode code point + +EOT + exit; +} + +__END__ + +=head1 NAME + +piconv -- iconv(1), reinvented in perl + +=head1 SYNOPSIS + + piconv [-f from_encoding] [-t to_encoding] + [-p|--perlqq|--htmlcref|--xmlcref] [-C N|-c] [-D] [-S scheme] + [-s string|file...] + piconv -l + piconv -r encoding_alias + piconv -h + +=head1 DESCRIPTION + +B is perl version of B, a character encoding converter +widely available for various Unixen today. This script was primarily +a technology demonstrator for Perl 5.8.0, but you can use piconv in the +place of iconv for virtually any case. + +piconv converts the character encoding of either STDIN or files +specified in the argument and prints out to STDOUT. + +Here is the list of options. Some options can be in short format (-f) +or long (--from) one. + +=over 4 + +=item -f,--from I + +Specifies the encoding you are converting from. Unlike B, +this option can be omitted. In such cases, the current locale is used. + +=item -t,--to I + +Specifies the encoding you are converting to. Unlike B, +this option can be omitted. In such cases, the current locale is used. + +Therefore, when both -f and -t are omitted, B just acts +like B. + +=item -s,--string I + +uses I instead of file for the source of text. + +=item -l,--list + +Lists all available encodings, one per line, in case-insensitive +order. Note that only the canonical names are listed; many aliases +exist. For example, the names are case-insensitive, and many standard +and common aliases work, such as "latin1" for "ISO-8859-1", or "ibm850" +instead of "cp850", or "winlatin1" for "cp1252". See L +for a full discussion. + +=item -r,--resolve I + +Resolve I to Encode canonical encoding name. + +=item -C,--check I + +Check the validity of the stream if I = 1. When I = -1, something +interesting happens when it encounters an invalid character. + +=item -c + +Same as C<-C 1>. + +=item -p,--perlqq + +Transliterate characters missing in encoding to \x{HHHH} where HHHH is the +hexadecimal Unicode code point. + +=item --htmlcref + +Transliterate characters missing in encoding to &#NNN; where NNN is the +decimal Unicode code point. + +=item --xmlcref + +Transliterate characters missing in encoding to &#xHHHH; where HHHH is the +hexadecimal Unicode code point. + +=item -h,--help + +Show usage. + +=item -D,--debug + +Invokes debugging mode. Primarily for Encode hackers. + +=item -S,--scheme I + +Selects which scheme is to be used for conversion. Available schemes +are as follows: + +=over 4 + +=item from_to + +Uses Encode::from_to for conversion. This is the default. + +=item decode_encode + +Input strings are decode()d then encode()d. A straight two-step +implementation. + +=item perlio + +The new perlIO layer is used. NI-S' favorite. + +You should use this option if you are using UTF-16 and others which +linefeed is not $/. + +=back + +Like the I<-D> option, this is also for Encode hackers. + +=back + +=head1 SEE ALSO + +L +L +L +L +L +L + +=cut diff --git a/git/usr/bin/core_perl/pl2pm b/git/usr/bin/core_perl/pl2pm new file mode 100644 index 0000000000000000000000000000000000000000..599b5d966bfbdd7d0d508007e3c8193112957a3d --- /dev/null +++ b/git/usr/bin/core_perl/pl2pm @@ -0,0 +1,378 @@ +#!/usr/bin/perl + eval 'exec /usr/bin/perl -S $0 ${1+"$@"}' + if 0; # ^ Run only under a shell + +=head1 NAME + +pl2pm - Rough tool to translate Perl4 .pl files to Perl5 .pm modules. + +=head1 SYNOPSIS + +B F + +=head1 DESCRIPTION + +B is a tool to aid in the conversion of Perl4-style .pl +library files to Perl5-style library modules. Usually, your old .pl +file will still work fine and you should only use this tool if you +plan to update your library to use some of the newer Perl 5 features, +such as AutoLoading. + +=head1 LIMITATIONS + +It's just a first step, but it's usually a good first step. + +=head1 AUTHOR + +Larry Wall + +=cut + +use strict; +use warnings; + +my %keyword = (); + +while () { + chomp; + $keyword{$_} = 1; +} + +local $/; + +while (<>) { + my $newname = $ARGV; + $newname =~ s/\.pl$/.pm/ || next; + $newname =~ s#(.*/)?(\w+)#$1\u$2#; + if (-f $newname) { + warn "Won't overwrite existing $newname\n"; + next; + } + my $oldpack = $2; + my $newpack = "\u$2"; + my @export = (); + + s/\bstd(in|out|err)\b/\U$&/g; + s/(sub\s+)(\w+)(\s*\{[ \t]*\n)\s*package\s+$oldpack\s*;[ \t]*\n+/${1}main'$2$3/ig; + if (/sub\s+\w+'/) { + @export = m/sub\s+\w+'(\w+)/g; + s/(sub\s+)main'(\w+)/$1$2/g; + } + else { + @export = m/sub\s+([A-Za-z]\w*)/g; + } + my @export_ok = grep($keyword{$_}, @export); + @export = grep(!$keyword{$_}, @export); + + my %export = (); + @export{@export} = (1) x @export; + + s/(^\s*);#/$1#/g; + s/(#.*)require ['"]$oldpack\.pl['"]/$1use $newpack/; + s/(package\s*)($oldpack)\s*;[ \t]*\n+//ig; + s/([\$\@%&*])'(\w+)/&xlate($1,"",$2,$newpack,$oldpack,\%export)/eg; + s/([\$\@%&*]?)(\w+)'(\w+)/&xlate($1,$2,$3,$newpack,$oldpack,\%export)/eg; + if (!/\$\[\s*\)?\s*=\s*[^0\s]/) { + s/^\s*(local\s*\()?\s*\$\[\s*\)?\s*=\s*0\s*;[ \t]*\n//g; + s/\$\[\s*\+\s*//g; + s/\s*\+\s*\$\[//g; + s/\$\[/0/g; + } + s/open\s+(\w+)/open($1)/g; + + my $export_ok = ''; + my $carp =''; + + + if (s/\bdie\b/croak/g) { + $carp = "use Carp;\n"; + s/croak "([^"]*)\\n"/croak "$1"/g; + } + + if (@export_ok) { + $export_ok = "\@EXPORT_OK = qw(@export_ok);\n"; + } + + if ( open(PM, ">", $newname) ) { + print PM <<"END"; +package $newpack; +use 5.006; +require Exporter; +$carp +\@ISA = qw(Exporter); +\@EXPORT = qw(@export); +$export_ok +$_ +END + } + else { + warn "Can't create $newname: $!\n"; + } +} + +sub xlate { + my ($prefix, $pack, $ident,$newpack,$oldpack,$export) = @_; + + my $xlated ; + if ($prefix eq '' && $ident =~ /^(t|s|m|d|ing|ll|ed|ve|re)$/) { + $xlated = "${pack}'$ident"; + } + elsif ($pack eq '' || $pack eq 'main') { + if ($export->{$ident}) { + $xlated = "$prefix$ident"; + } + else { + $xlated = "$prefix${pack}::$ident"; + } + } + elsif ($pack eq $oldpack) { + $xlated = "$prefix${newpack}::$ident"; + } + else { + $xlated = "$prefix${pack}::$ident"; + } + + return $xlated; +} +__END__ +AUTOLOAD +BEGIN +CHECK +CORE +DESTROY +END +INIT +UNITCHECK +abs +accept +alarm +and +atan2 +bind +binmode +bless +caller +chdir +chmod +chomp +chop +chown +chr +chroot +close +closedir +cmp +connect +continue +cos +crypt +dbmclose +dbmopen +defined +delete +die +do +dump +each +else +elsif +endgrent +endhostent +endnetent +endprotoent +endpwent +endservent +eof +eq +eval +exec +exists +exit +exp +fcntl +fileno +flock +for +foreach +fork +format +formline +ge +getc +getgrent +getgrgid +getgrnam +gethostbyaddr +gethostbyname +gethostent +getlogin +getnetbyaddr +getnetbyname +getnetent +getpeername +getpgrp +getppid +getpriority +getprotobyname +getprotobynumber +getprotoent +getpwent +getpwnam +getpwuid +getservbyname +getservbyport +getservent +getsockname +getsockopt +glob +gmtime +goto +grep +gt +hex +if +index +int +ioctl +join +keys +kill +last +lc +lcfirst +le +length +link +listen +local +localtime +lock +log +lstat +lt +m +map +mkdir +msgctl +msgget +msgrcv +msgsnd +my +ne +next +no +not +oct +open +opendir +or +ord +our +pack +package +pipe +pop +pos +print +printf +prototype +push +q +qq +qr +quotemeta +qw +qx +rand +read +readdir +readline +readlink +readpipe +recv +redo +ref +rename +require +reset +return +reverse +rewinddir +rindex +rmdir +s +scalar +seek +seekdir +select +semctl +semget +semop +send +setgrent +sethostent +setnetent +setpgrp +setpriority +setprotoent +setpwent +setservent +setsockopt +shift +shmctl +shmget +shmread +shmwrite +shutdown +sin +sleep +socket +socketpair +sort +splice +split +sprintf +sqrt +srand +stat +study +sub +substr +symlink +syscall +sysopen +sysread +sysseek +system +syswrite +tell +telldir +tie +tied +time +times +tr +truncate +uc +ucfirst +umask +undef +unless +unlink +unpack +unshift +untie +until +use +utime +values +vec +wait +waitpid +wantarray +warn +while +write +x +xor +y diff --git a/git/usr/bin/core_perl/pod2html b/git/usr/bin/core_perl/pod2html new file mode 100644 index 0000000000000000000000000000000000000000..ef21ec2bdb92457a08be63552ecde3e7e49e4d5b --- /dev/null +++ b/git/usr/bin/core_perl/pod2html @@ -0,0 +1,202 @@ +#!/usr/bin/perl + eval 'exec /usr/bin/perl -S $0 ${1+"$@"}' + if 0; # ^ Run only under a shell +=pod + +=head1 NAME + +pod2html - convert .pod files to .html files + +=head1 SYNOPSIS + + pod2html --help --htmldir= --htmlroot= + --infile= --outfile= + --podpath=:...: --podroot= + --cachedir= --flush --recurse --norecurse + --quiet --noquiet --verbose --noverbose + --index --noindex --backlink --nobacklink + --header --noheader --poderrors --nopoderrors + --css= --title= + +=head1 DESCRIPTION + +Converts files from pod format (see L) to HTML format. + +=head1 ARGUMENTS + +pod2html takes the following arguments: + +=over 4 + +=item backlink + + --backlink + --nobacklink + +Turn =head1 directives into links pointing to the top of the HTML file. +--nobacklink (which is the default behavior) does not create these backlinks. + +=item cachedir + + --cachedir=name + +Specify which directory is used for storing cache. Default directory is the +current working directory. + +=item css + + --css=URL + +Specify the URL of cascading style sheet to link from resulting HTML file. +Default is none style sheet. + +=item flush + + --flush + +Flush the cache. + +=item header + + --header + --noheader + +Create header and footer blocks containing the text of the "NAME" section. +--noheader -- which is the default behavior -- does not create header or footer +blocks. + +=item help + + --help + +Displays the usage message. + +=item htmldir + + --htmldir=name + +Sets the directory to which all cross references in the resulting HTML file +will be relative. Not passing this causes all links to be absolute since this +is the value that tells Pod::Html the root of the documentation tree. + +Do not use this and --htmlroot in the same call to pod2html; they are mutually +exclusive. + +=item htmlroot + + --htmlroot=URL + +Sets the base URL for the HTML files. When cross-references are made, the +HTML root is prepended to the URL. + +Do not use this if relative links are desired: use --htmldir instead. + +Do not pass both this and --htmldir to pod2html; they are mutually exclusive. + +=item index + + --index + +Generate an index at the top of the HTML file (default behaviour). + +=over 4 + +=item noindex + + --noindex + +Do not generate an index at the top of the HTML file. + +=back + +=item infile + + --infile=name + +Specify the pod file to convert. Input is taken from STDIN if no +infile is specified. + +=item outfile + + --outfile=name + +Specify the HTML file to create. Output goes to STDOUT if no outfile +is specified. + +=item poderrors + + --poderrors + --nopoderrors + +Include a "POD ERRORS" section in the outfile if there were any POD errors in +the infile (default behaviour). --nopoderrors does not create this "POD +ERRORS" section. + +=item podpath + + --podpath=name:...:name + +Specify which subdirectories of the podroot contain pod files whose +HTML converted forms can be linked-to in cross-references. + +=item podroot + + --podroot=name + +Specify the base directory for finding library pods. + +=item quiet + + --quiet + --noquiet + +Don't display mostly harmless warning messages. --noquiet -- which is the +default behavior -- I display these mostly harmless warning messages (but +this is not the same as "verbose" mode). + +=item recurse + + --recurse + --norecurse + +Recurse into subdirectories specified in podpath (default behaviour). +--norecurse does not recurse into these subdirectories. + +=item title + + --title=title + +Specify the title of the resulting HTML file. + +=item verbose + + --verbose + --noverbose + +Display progress messages. --noverbose -- which is the default behavior -- +does not display these progress messages. + +=back + +=head1 AUTHOR + +Tom Christiansen, Etchrist@perl.comE. + +=head1 BUGS + +See L for a list of known bugs in the translator. + +=head1 SEE ALSO + +L, L + +=head1 COPYRIGHT + +This program is distributed under the Artistic License. + +=cut + +BEGIN { pop @INC if $INC[-1] eq '.' } +use Pod::Html; + +pod2html @ARGV; diff --git a/git/usr/bin/core_perl/pod2man b/git/usr/bin/core_perl/pod2man new file mode 100644 index 0000000000000000000000000000000000000000..cf93f4f683c30191c81040e2bd12d1afde418b6c --- /dev/null +++ b/git/usr/bin/core_perl/pod2man @@ -0,0 +1,519 @@ +#!/usr/bin/perl +eval 'exec /usr/bin/perl -S $0 ${1+"$@"}' + if 0; # ^ Run only under a shell + +# Convert POD data to formatted *roff input. +# +# The driver script for Pod::Man. +# +# SPDX-License-Identifier: GPL-1.0-or-later OR Artistic-1.0-Perl + +use 5.012; +use warnings; + +use Getopt::Long qw(GetOptions); +use Pod::Man (); +use Pod::Usage qw(pod2usage); + +# Format a single POD file. +# +# $parser - Pod::Man object to use +# $input - Input file, - or undef for standard input +# $output - Output file, - or undef for standard output +# $verbose - Whether to print each file to standard output when converted +# +# Returns: 0 on no errors, 1 if there was an error +sub format_file { + my ($parser, $input, $output, $verbose) = @_; + my $to_stdout = !defined($output) || $output eq q{-}; + if ($verbose && !$to_stdout) { + print " $output\n" or warn "$0: cannot write to stdout: $!\n"; + } + $parser->parse_from_file($input, $output); + if ($parser->{CONTENTLESS}) { + if (defined($input) && $input ne q{-}) { + warn "$0: unable to format $input\n"; + } else { + warn "$0: unable to format standard input\n"; + } + if (!$to_stdout && !-s $output) { + unlink($output); + } + return 1; + } + return 0; +} + +# Clean up $0 for error reporting. +$0 =~ s{ .*/ }{}xms; + +# Insert -- into @ARGV before any single dash argument to hide it from +# Getopt::Long; we want to interpret it as meaning stdin. +my $stdin; +local @ARGV = map { $_ eq q{-} && !$stdin++ ? (q{--}, $_) : $_ } @ARGV; + +# Parse our options, trying to retain backward compatibility with pod2man but +# allowing short forms as well. --lax is currently ignored. +my %options; +Getopt::Long::config('bundling_override'); +GetOptions( + \%options, + 'center|c=s', + 'date|d=s', + 'encoding|e=s', + 'errors=s', + 'fixed=s', + 'fixedbold=s', + 'fixeditalic=s', + 'fixedbolditalic=s', + 'guesswork=s', + 'help|h', + 'lax|l', + 'language=s', + 'lquote=s', + 'name|n=s', + 'nourls', + 'official|o', + 'quotes|q=s', + 'release|r=s', + 'rquote=s', + 'section|s=s', + 'stderr', + 'verbose|v', + 'utf8|u', +) or exit 1; +if ($options{help}) { + pod2usage(0); +} + +# Official sets --center, but don't override things explicitly set. +if ($options{official} && !defined($options{center})) { + $options{center} = 'Perl Programmers Reference Guide'; +} + +# Delete flags that are only used in pod2man, not in Pod::Man. lax is accepted +# only for backward compatibility and does nothing. +my $verbose = $options{verbose}; +delete @options{qw(verbose lax official)}; + +# If neither stderr nor errors is set, default to errors = die rather than the +# Pod::Man default of pod. +if (!defined($options{stderr}) && !defined($options{errors})) { + $options{errors} = 'die'; +} + +# If given no arguments, read from stdin and write to stdout. +if (!@ARGV) { + push(@ARGV, q{-}); +} + +# Initialize and run the formatter, pulling a pair of input and output off at +# a time. For each file, we check whether the document was completely empty +# and, if so, will remove the created file and exit with a non-zero exit +# status. +my $parser = Pod::Man->new(%options); +my $status = 0; +while (@ARGV) { + my ($input, $output) = splice(@ARGV, 0, 2); + my $result = format_file($parser, $input, $output, $verbose); + $status ||= $result; +} +exit($status); + +__END__ + +=for stopwords +en em --stderr stderr --utf8 UTF-8 overdo markup MT-LEVEL Allbery Solaris URL +troff troff-specific formatters uppercased Christiansen --nourls UTC prepend +lquote rquote unrepresentable mandoc manref EBCDIC + +=head1 NAME + +pod2man - Convert POD data to formatted *roff input + +=head1 SYNOPSIS + +pod2man [B<--center>=I] [B<--date>=I] + [B<--encoding>=I] [B<--errors>=I