ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/cvsroot/App-Staticperl/bin/staticperl
Revision: 1.18
Committed: Fri Dec 10 02:35:54 2010 UTC (15 years, 10 months ago) by root
Branch: MAIN
Changes since 1.17: +630 -206 lines
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 root 1.1 #!/bin/sh
2    
3     #############################################################################
4     # configuration to fill in
5    
6     STATICPERL=~/.staticperl
7     CPAN=http://mirror.netcologne.de/cpan/ # which mirror to use
8     EMAIL="read the documentation <rtfm@example.org>"
9    
10     MKBUNDLE="$STATICPERL/mkbundle"
11    
12     # perl build variables
13 root 1.10 PERL_PREFIX="$STATICPERL/perl" # where the perl gets installed
14     PERL_VERSION=5.12.2 # 5.8.9 is also a good choice
15 root 1.8 PERL_CONFIGURE="" # additional Configure arguments
16 root 1.1 PERL_CPPFLAGS="-DPERL_DISABLE_PMC -DPERL_ARENA_SIZE=65536 -D_GNU_SOURCE -DNDEBUG -USITELIB_EXP -USITEARCHEXP -UARCHLIB_EXP"
17     PERL_OPTIMIZE="-Os -ffunction-sections -fdata-sections -finline-limit=8 -ffast-math"
18    
19     ARCH="$(uname -m)"
20    
21     case "$ARCH" in
22     i*86 | x86_64 | amd64 )
23     PERL_OPTIMIZE="$PERL_OPTIMIZE -mpush-args -mno-inline-stringops-dynamically -mno-align-stringops -mno-ieee-fp" # x86/amd64
24     case "$ARCH" in
25     i*86 )
26     PERL_OPTIMIZE="$PERL_OPTIMIZE -fomit-frame-pointer -march=pentium3 -mtune=i386" # x86 only
27     ;;
28     esac
29     ;;
30     esac
31    
32     # -Wl,--gc-sections makes it impossible to check for undefined references
33     # for some reason so we need to patch away the "-no" after Configure and before make :/
34     # -z muldefs is to work around uclibc's pthread static linking bug
35     PERL_LDFLAGS="-Wl,--no-gc-sections -z muldefs"
36     PERL_LIBS="-lm -lcrypt" # perl loves to add lotsa crap itself
37    
38     # some configuration options for modules
39     export PERL_MM_USE_DEFAULT=1
40     #export CORO_INTERFACE=p # needed without nptl on x86, due to bugs in linuxthreads - very slow
41     export EV_EXTRA_DEFS='-DEV_FEATURES=4+8+16+64 -DEV_USE_SELECT=0 -DEV_USE_POLL=1 -DEV_USE_EPOLL=1 -DEV_NO_LOOPS -DEV_COMPAT3=0'
42    
43     # which extra modules to install by default from CPAN that are
44     # required by mkbundle
45 root 1.2 STATICPERL_MODULES="common::sense Pod::Strip PPI::XS Pod::Usage"
46    
47     # which extra modules you might want to install
48     EXTRA_MODULES=""
49 root 1.1
50     # overridable functions
51 root 1.11 preconfigure() { : ; }
52 root 1.1 postconfigure() { : ; }
53     postbuild() { : ; }
54     postinstall() { : ; }
55    
56     # now source user config, if any
57     [ -r /etc/staticperlrc ] && . /etc/staticperlrc
58     [ -r ~/.staticperlrc ] && . ~/.staticperlrc
59     [ -r "$STATICPERL/rc" ] && . "$STATICPERL/rc"
60    
61     #############################################################################
62     # support
63    
64 root 1.18 unset PERL5OPT PERL5LIB PERLLIB PERL_UNICODE PERLIO_DEBUG
65     export LC_ALL=C # just to be on the safe side
66    
67 root 1.1 # set version in a way that Makefile.PL can extract
68     VERSION=VERSION; eval \
69 root 1.17 $VERSION=0.9
70 root 1.1
71     BZ2=bz2
72     BZIP2=bzip2
73    
74     fatal() {
75     printf -- "\nFATAL: %s\n\n" "$*" >&2
76     exit 1
77     }
78    
79     verbose() {
80     printf -- "%s\n" "$*"
81     }
82    
83     verblock() {
84     verbose
85     verbose "***"
86     while read line; do
87     verbose "*** $line"
88     done
89     verbose "***"
90     verbose
91     }
92    
93     rcd() {
94     cd "$1" || fatal "$1: cannot enter"
95     }
96    
97     trace() {
98     prefix="$1"; shift
99     # "$@" 2>&1 | while read line; do
100     # echo "$prefix: $line"
101     # done
102     "$@"
103     }
104    
105     trap wait 0
106    
107     #############################################################################
108     # clean
109    
110     distclean() {
111     verblock <<EOF
112     deleting everything installed by this script
113     EOF
114    
115     rm -rf "$STATICPERL"
116     }
117    
118     #############################################################################
119     # download/configure/compile/install perl
120    
121     clean() {
122 root 1.11 rm -rf "$STATICPERL/src/perl-$PERL_VERSION"
123 root 1.1 }
124    
125     fetch() {
126     rcd "$STATICPERL"
127    
128     mkdir -p src
129     rcd src
130    
131 root 1.10 if ! [ -d "perl-$PERL_VERSION" ]; then
132     if ! [ -e "perl-$PERL_VERSION.tar.$BZ2" ]; then
133 root 1.1
134 root 1.10 URL="$CPAN/src/5.0/perl-$PERL_VERSION.tar.$BZ2"
135 root 1.1
136     verblock <<EOF
137     downloading perl
138     to manually download perl yourself, place
139 root 1.10 perl-$PERL_VERSION.tar.$BZ2 in $STATICPERL
140 root 1.1 trying $URL
141     EOF
142    
143 root 1.10 rm -f perl-$PERL_VERSION.tar.$BZ2~ # just to be on the safe side
144     wget -O perl-$PERL_VERSION.tar.$BZ2~ "$URL" \
145     || curl >perl-$PERL_VERSION.tar.$BZ2~ "$URL" \
146     || fatal "$URL: unable to download"
147     mv perl-$PERL_VERSION.tar.$BZ2~ perl-$PERL_VERSION.tar.$BZ2
148 root 1.1 fi
149    
150     verblock <<EOF
151     unpacking perl
152     EOF
153    
154     mkdir -p unpack
155 root 1.12 $BZIP2 -d <perl-$PERL_VERSION.tar.bz2 | tar xC unpack \
156 root 1.10 || fatal "perl-$PERL_VERSION.tar.bz2: error during unpacking"
157 root 1.12 chmod -R u+w unpack/perl-$PERL_VERSION
158 root 1.10 mv unpack/perl-$PERL_VERSION perl-$PERL_VERSION
159 root 1.1 rmdir -p unpack
160     fi
161     }
162    
163     # similar to GNU-sed -i or perl -pi
164     sedreplace() {
165     sed -e "$1" <"$2" > "$2~" || fatal "error while running sed"
166     mv "$2~" "$2"
167     }
168    
169     configure() {
170     fetch
171    
172 root 1.10 rcd "$STATICPERL/src/perl-$PERL_VERSION"
173 root 1.1
174     [ -e staticstamp.configure ] && return
175    
176     verblock <<EOF
177 root 1.10 configuring $STATICPERL/src/perl-$PERL_VERSION
178 root 1.1 EOF
179    
180 root 1.12 rm -f "$PERL_PREFIX/staticstamp.install"
181 root 1.1
182 root 1.12 make distclean >/dev/null 2>&1
183 root 1.1
184     # I hate them
185     grep -q -- -fstack-protector Configure && \
186     sedreplace 's/-fstack-protector/-fno-stack-protector/g' Configure
187    
188 root 1.11 preconfigure
189    
190 root 1.1 # trace configure \
191     sh Configure -Duselargefiles \
192     -Uuse64bitint \
193     -Dusemymalloc=n \
194     -Uusedl \
195     -Uusethreads \
196     -Uuseithreads \
197     -Uusemultiplicity \
198     -Duseperlio \
199     -Uusesfio \
200     -Uuseshrplib \
201     -Dcppflags="$PERL_CPPFLAGS" \
202     -Dccflags="-g2 -fno-strict-aliasing" \
203     -Doptimize="$PERL_OPTIMIZE" \
204     -Dldflags="$PERL_LDFLAGS" \
205     -Dlibs="$PERL_LIBS" \
206 root 1.10 -Dprefix="$PERL_PREFIX" \
207     -Dbin="$PERL_PREFIX/bin" \
208     -Dprivlib="$PERL_PREFIX/lib" \
209     -Darchlib="$PERL_PREFIX/lib" \
210 root 1.1 -Uusevendorprefix \
211 root 1.10 -Dsitelib="$PERL_PREFIX/lib" \
212     -Dsitearch="$PERL_PREFIX/lib" \
213 root 1.1 -Usitelibexp \
214     -Uman1dir \
215     -Uman3dir \
216     -Usiteman1dir \
217     -Usiteman3dir \
218     -Dpager=/usr/bin/less \
219     -Demail="$EMAIL" \
220     -Dcf_email="$EMAIL" \
221     -Dcf_by="$EMAIL" \
222 root 1.8 $PERL_CONFIGURE \
223 root 1.1 -dE || fatal "Configure failed"
224    
225     sedreplace '
226     s/-Wl,--no-gc-sections/-Wl,--gc-sections/g
227     s/ *-fno-stack-protector */ /g
228     ' config.sh
229    
230     sh Configure -S || fatal "Configure -S failed"
231    
232     postconfigure || fatal "postconfigure hook failed"
233    
234     touch staticstamp.configure
235     }
236    
237     build() {
238     configure
239    
240 root 1.10 rcd "$STATICPERL/src/perl-$PERL_VERSION"
241 root 1.1
242     verblock <<EOF
243 root 1.10 building $STATICPERL/src/perl-$PERL_VERSION
244 root 1.1 EOF
245    
246 root 1.10 rm -f "$PERL_PREFIX/staticstamp.install"
247 root 1.1
248     make || fatal "make: error while building perl"
249    
250     postbuild || fatal "postbuild hook failed"
251     }
252    
253     install() {
254 root 1.13 if ! [ -e "$PERL_PREFIX/staticstamp.install" ]; then
255     build
256 root 1.1
257 root 1.13 verblock <<EOF
258 root 1.10 installing $STATICPERL/src/perl-$PERL_VERSION
259     to $PERL_PREFIX
260 root 1.1 EOF
261    
262 root 1.13 rm -rf "$PERL_PREFIX"
263    
264     make install || fatal "make install: error while installing"
265 root 1.1
266 root 1.13 rcd "$PERL_PREFIX"
267 root 1.2
268 root 1.13 # create a "make install" replacement for CPAN
269     cat >"$PERL_PREFIX"/bin/cpan-make-install <<EOF
270 root 1.14 make || exit
271    
272 root 1.1 if find blib/arch/auto -type f | grep -q -v .exists; then
273     echo Probably an XS module, rebuilding perl
274 root 1.14 if make perl; then
275     mv perl "$PERL_PREFIX"/bin/perl
276     make -f Makefile.aperl map_clean
277     else
278     make -f Makefile.aperl map_clean
279     exit 1
280     fi
281 root 1.1 fi
282 root 1.14
283     make install UNINST=1
284 root 1.1 EOF
285 root 1.13 chmod 755 "$PERL_PREFIX"/bin/cpan-make-install
286    
287     # trick CPAN into avoiding ~/.cpan completely
288     echo 1 >"$PERL_PREFIX/lib/CPAN/MyConfig.pm"
289 root 1.1
290 root 1.13 "$PERL_PREFIX"/bin/perl -MCPAN -e '
291     CPAN::Shell->o (conf => urllist => push => "'"$CPAN"'");
292     CPAN::Shell->o (conf => q<cpan_home>, "'"$STATICPERL"'/cpan");
293     CPAN::Shell->o (conf => q<init>);
294     CPAN::Shell->o (conf => q<cpan_home>, "'"$STATICPERL"'/cpan");
295     CPAN::Shell->o (conf => q<build_dir>, "'"$STATICPERL"'/cpan/build");
296     CPAN::Shell->o (conf => q<prefs_dir>, "'"$STATICPERL"'/cpan/prefs");
297     CPAN::Shell->o (conf => q<histfile> , "'"$STATICPERL"'/cpan/histfile");
298     CPAN::Shell->o (conf => q<keep_source_where>, "'"$STATICPERL"'/cpan/sources");
299     CPAN::Shell->o (conf => q<make_install_make_command>, "'"$PERL_PREFIX"'/bin/cpan-make-install");
300     CPAN::Shell->o (conf => q<prerequisites_policy>, q<follow>);
301     CPAN::Shell->o (conf => q<build_requires_install_policy>, q<no>);
302     CPAN::Shell->o (conf => q<commit>);
303     ' || fatal "error while initialising CPAN"
304 root 1.2
305 root 1.13 touch "$PERL_PREFIX/staticstamp.install"
306     fi
307    
308 root 1.14 if ! [ -e "$PERL_PREFIX/staticstamp.postinstall" ]; then
309 root 1.13 NOCHECK_INSTALL=+
310     instcpan $STATICPERL_MODULES
311     [ $EXTRA_MODULES ] && instcpan $EXTRA_MODULES
312 root 1.1
313 root 1.13 postinstall || fatal "postinstall hook failed"
314 root 1.1
315 root 1.13 touch "$PERL_PREFIX/staticstamp.postinstall"
316     fi
317 root 1.1 }
318    
319     #############################################################################
320     # install a module from CPAN
321    
322     instcpan() {
323     [ $NOCHECK_INSTALL ] || install
324    
325     verblock <<EOF
326     installing modules from CPAN
327     $@
328     EOF
329    
330     for mod in "$@"; do
331 root 1.10 "$PERL_PREFIX"/bin/perl -MCPAN -e 'notest install => "'"$mod"'"' \
332 root 1.1 || fatal "$mod: unable to install from CPAN"
333     done
334     rm -rf "$STATICPERL/build"
335     }
336    
337     #############################################################################
338     # install a module from unpacked sources
339    
340     instsrc() {
341     [ $NOCHECK_INSTALL ] || install
342    
343     verblock <<EOF
344     installing modules from source
345     $@
346     EOF
347    
348     for mod in "$@"; do
349     echo
350     echo $mod
351     (
352     rcd $mod
353     make -f Makefile.aperl map_clean >/dev/null 2>&1
354     make distclean >/dev/null 2>&1
355 root 1.10 "$PERL_PREFIX"/bin/perl Makefile.PL || fatal "$mod: error running Makefile.PL"
356 root 1.1 make || fatal "$mod: error building module"
357 root 1.10 "$PERL_PREFIX"/bin/cpan-make-install || fatal "$mod: error installing module"
358 root 1.1 make distclean >/dev/null 2>&1
359     exit 0
360     ) || exit $?
361     done
362     }
363    
364     #############################################################################
365     # main
366    
367     podusage() {
368     echo
369 root 1.10 if [ -e "$PERL_PREFIX/bin/perl" ]; then
370     "$PERL_PREFIX/bin/perl" -MPod::Usage -e \
371 root 1.1 'pod2usage -input => *STDIN, -output => *STDOUT, -verbose => '$1', -exitval => 0, -noperldoc => 1' <"$0" \
372     2>/dev/null && exit
373     fi
374     # try whatever perl we can find
375     perl -MPod::Usage -e \
376     'pod2usage -input => *STDIN, -output => *STDOUT, -verbose => '$1', -exitval => 0, -noperldoc => 1' <"$0" \
377     2>/dev/null && exit
378    
379     fatal "displaying documentation requires a working perl - try '$0 install' first"
380     }
381    
382     usage() {
383     podusage 0
384     }
385    
386     catmkbundle() {
387     {
388     read dummy
389 root 1.10 echo "#!$PERL_PREFIX/bin/perl"
390 root 1.1 cat
391     } <<'MKBUNDLE'
392     #!/opt/bin/perl
393    
394     #############################################################################
395     # cannot load modules till after the tracer BEGIN block
396    
397     our $VERBOSE = 1;
398     our $STRIP = "pod"; # none, pod or ppi
399 root 1.18 our $UNISTRIP = 1; # always on, try to strip unicore swash data
400 root 1.1 our $PERL = 0;
401 root 1.17 our $APP;
402 root 1.1 our $VERIFY = 0;
403     our $STATIC = 0;
404    
405 root 1.18 our $OPTIMISE_SIZE = 0; # optimise for raw file size instead of for compression?
406    
407     our $CACHE;
408     our $CACHEVER = 1; # do not change unless you know what you are doing
409    
410 root 1.1 my $PREFIX = "bundle";
411     my $PACKAGE = "static";
412    
413     my %pm;
414 root 1.8 my %pmbin;
415 root 1.1 my @libs;
416     my @static_ext;
417     my $extralibs;
418 root 1.18 my @staticlibs;
419     my @incext;
420 root 1.1
421     @ARGV
422     or die "$0: use 'staticperl help' (or read the sources of staticperl)\n";
423    
424 root 1.18 # remove "." from @INC - staticperl.sh does it for us, but be on the safe side
425     BEGIN { @INC = grep !/^\.$/, @INC }
426    
427 root 1.1 $|=1;
428    
429     our ($TRACER_W, $TRACER_R);
430    
431     sub find_inc($) {
432     for (@INC) {
433     next if ref;
434     return $_ if -e "$_/$_[0]";
435     }
436    
437     undef
438     }
439    
440     BEGIN {
441     # create a loader process to detect @INC requests before we load any modules
442     my ($W_TRACER, $R_TRACER); # used by tracer
443    
444     pipe $R_TRACER, $TRACER_W or die "pipe: $!";
445     pipe $TRACER_R, $W_TRACER or die "pipe: $!";
446    
447     unless (fork) {
448     close $TRACER_R;
449     close $TRACER_W;
450    
451     unshift @INC, sub {
452     my $dir = find_inc $_[1]
453     or return;
454    
455     syswrite $W_TRACER, "-\n$dir\n$_[1]\n";
456    
457     open my $fh, "<:perlio", "$dir/$_[1]"
458     or warn "ERROR: $dir/$_[1]: $!\n";
459    
460     $fh
461     };
462    
463     while (<$R_TRACER>) {
464     if (/use (.*)$/) {
465     my $mod = $1;
466     eval "require $mod";
467     warn "ERROR: $@ (while loading '$mod')\n"
468     if $@;
469     syswrite $W_TRACER, "\n";
470     } elsif (/eval (.*)$/) {
471     my $eval = $1;
472     eval $eval;
473     warn "ERROR: $@ (in '$eval')\n"
474     if $@;
475     }
476     }
477    
478     exit 0;
479     }
480     }
481    
482     # module loading is now safe
483 root 1.7
484 root 1.1 sub trace_module {
485     syswrite $TRACER_W, "use $_[0]\n";
486    
487     for (;;) {
488     <$TRACER_R> =~ /^-$/ or last;
489     my $dir = <$TRACER_R>; chomp $dir;
490     my $name = <$TRACER_R>; chomp $name;
491    
492     $pm{$name} = "$dir/$name";
493     }
494     }
495    
496     sub trace_eval {
497     syswrite $TRACER_W, "eval $_[0]\n";
498     }
499    
500     sub trace_finish {
501     close $TRACER_W;
502     close $TRACER_R;
503     }
504    
505     #############################################################################
506     # now we can use modules
507    
508     use common::sense;
509 root 1.18 use Config;
510 root 1.1 use Digest::MD5;
511    
512 root 1.18 sub cache($$$) {
513     my ($variant, $src, $filter) = @_;
514    
515     if (length $CACHE and 2048 <= length $src) {
516     my $file = "$CACHE/" . Digest::MD5::md5_hex "$CACHEVER\x00$variant\x00$src";
517    
518     if (open my $fh, "<:perlio", $file) {
519     local $/;
520     return <$fh>;
521     }
522    
523     $src = $filter->($src);
524    
525     if (open my $fh, ">:perlio", "$file~") {
526     if ((syswrite $fh, $src) == length $src) {
527     close $fh;
528     rename "$file~", $file;
529     }
530     }
531    
532     return $src;
533     }
534    
535     $filter->($src)
536     }
537    
538 root 1.1 sub dump_string {
539     my ($fh, $data) = @_;
540    
541     if (length $data) {
542     for (
543     my $ofs = 0;
544     length (my $substr = substr $data, $ofs, 80);
545     $ofs += 80
546     ) {
547     $substr =~ s/([^\x20-\x21\x23-\x5b\x5d-\x7e])/sprintf "\\%03o", ord $1/ge;
548     $substr =~ s/\?/\\?/g; # trigraphs...
549     print $fh " \"$substr\"\n";
550     }
551     } else {
552     print $fh " \"\"\n";
553     }
554     }
555    
556 root 1.18 #############################################################################
557    
558     sub glob2re {
559     for (quotemeta $_[0]) {
560     s/\\\*/\x00/g;
561     s/\x00\x00/.*/g;
562     s/\x00/[^\/]*/g;
563     s/\\\?/[^\/]/g;
564    
565     $_ = s/^\\\/// ? "^$_\$" : "(?:^|/)$_\$";
566    
567     s/(?: \[\^\/\] | \. ) \*\$$//x;
568    
569     return qr<$_>s
570     }
571     }
572    
573     our %INCSKIP = (
574     "unicore/TestProp.pl" => undef, # 3.5MB of insanity, apparently just some testcase
575     );
576    
577     sub get_dirtree {
578     my $root = shift;
579    
580     my @tree;
581     my $skip;
582    
583     my $scan; $scan = sub {
584     for (sort do {
585     opendir my $fh, $_[0]
586     or return;
587     readdir $fh
588     }) {
589     next if /^\./;
590    
591     my $path = "$_[0]/$_";
592    
593     if (-d "$path/.") {
594     $scan->($path);
595     } else {
596     next unless /\.(?:pm|pl)$/;
597    
598     $path = substr $path, $skip;
599     push @tree, $path
600     unless exists $INCSKIP{$path};
601     }
602     }
603     };
604    
605     $root =~ s/\/$//;
606     $skip = 1 + length $root;
607     $scan->($root);
608    
609     \@tree
610     }
611    
612     my $inctrees;
613    
614     sub get_inctrees {
615     unless ($inctrees) {
616     my %inctree;
617     $inctree{$_} ||= [$_, get_dirtree $_] # entries in @INC are often duplicates
618     for @INC;
619     $inctrees = [values %inctree];
620     }
621    
622     @$inctrees
623     }
624 root 1.1
625 root 1.18 #############################################################################
626 root 1.1
627     sub cmd_boot {
628     $pm{"//boot"} = $_[0];
629     }
630    
631     sub cmd_add {
632 root 1.3 $_[0] =~ /^(.*)(?:\s+(\S+))$/
633 root 1.1 or die "$_[0]: cannot parse";
634    
635     my $file = $1;
636     my $as = defined $2 ? $2 : "/$1";
637    
638     $pm{$as} = $file;
639 root 1.8 $pmbin{$as} = 1 if $_[1];
640 root 1.1 }
641    
642 root 1.18 sub cmd_staticlib {
643     push @staticlibs, $_
644     for split /\s+/, $_[0];
645     }
646    
647     sub cmd_include {
648     push @incext, [$_[1], glob2re $_[0]];
649     }
650    
651     sub cmd_incglob {
652     my ($pattern) = @_;
653    
654     $pattern = glob2re $pattern;
655    
656     for (get_inctrees) {
657     my ($dir, $files) = @$_;
658    
659     $pm{$_} = "$dir/$_"
660     for grep /$pattern/, @$files;
661     }
662     }
663    
664 root 1.1 sub cmd_file {
665     open my $fh, "<", $_[0]
666     or die "$_[0]: $!\n";
667    
668     while (<$fh>) {
669     chomp;
670     my ($cmd, $args) = split / /, $_, 2;
671 root 1.2 $cmd =~ s/^-+//;
672 root 1.1
673     if ($cmd eq "strip") {
674     $STRIP = $args;
675 root 1.17 } elsif ($cmd eq "perl") {
676     $PERL = 1;
677     } elsif ($cmd eq "app") {
678     $APP = $args;
679 root 1.1 } elsif ($cmd eq "eval") {
680     trace_eval $_;
681     } elsif ($cmd eq "use") {
682     trace_module $_
683     for split / /, $args;
684 root 1.18 } elsif ($cmd eq "staticlib") {
685     cmd_staticlib $args;
686 root 1.1 } elsif ($cmd eq "boot") {
687     cmd_boot $args;
688     } elsif ($cmd eq "static") {
689     $STATIC = 1;
690     } elsif ($cmd eq "add") {
691 root 1.8 cmd_add $args, 0;
692     } elsif ($cmd eq "addbin") {
693     cmd_add $args, 1;
694 root 1.18 } elsif ($cmd eq "incglob") {
695     cmd_incglob $args;
696     } elsif ($cmd eq "include") {
697     cmd_include $args, 1;
698     } elsif ($cmd eq "exclude") {
699     cmd_include $args, 0;
700 root 1.1 } elsif (/^\s*#/) {
701     # comment
702     } elsif (/\S/) {
703     die "$_: unsupported directive\n";
704     }
705     }
706     }
707    
708     use Getopt::Long;
709    
710     Getopt::Long::Configure ("bundling", "no_auto_abbrev", "no_ignore_case");
711    
712     GetOptions
713 root 1.18 "strip=s" => \$STRIP,
714     "cache=s" => \$CACHE, # internal option
715     "verbose|v" => sub { ++$VERBOSE },
716     "quiet|q" => sub { --$VERBOSE },
717     "perl" => \$PERL,
718     "app=s" => \$APP,
719     "eval|e=s" => sub { trace_eval $_[1] },
720     "use|M=s" => sub { trace_module $_[1] },
721     "boot=s" => sub { cmd_boot $_[1] },
722     "add=s" => sub { cmd_add $_[1], 0 },
723     "addbin=s" => sub { cmd_add $_[1], 1 },
724     "incglob=s" => sub { cmd_incglob $_[1] },
725     "include|i=s" => sub { cmd_include $_[1], 1 },
726     "exclude|x=s" => sub { cmd_include $_[1], 0 },
727     "static" => sub { $STATIC = 1 },
728     "staticlib=s" => sub { cmd_staticlib $_[1] },
729     "<>" => sub { cmd_file $_[0] },
730 root 1.1 or exit 1;
731    
732 root 1.17 die "cannot specify both --app and --perl\n"
733     if $PERL and defined $APP;
734    
735 root 1.18 # required for @INC loading, unfortunately
736     trace_module "PerlIO::scalar";
737    
738     #############################################################################
739     # include/exclude apply
740    
741     {
742     my %pmi;
743    
744     for (@incext) {
745     my ($inc, $glob) = @$_;
746    
747     my @match = grep /$glob/, keys %pm;
748    
749     if ($inc) {
750     # include
751     @pmi{@match} = delete @pm{@match};
752     } else {
753     # exclude
754     delete @pm{@match};
755     }
756     }
757    
758     my @pmi = keys %pmi;
759     @pm{@pmi} = delete @pmi{@pmi};
760     }
761    
762     #############################################################################
763     # scan for AutoLoader and static archives
764    
765     sub scan_al {
766     my ($auto, $autodir) = @_;
767    
768     my $ix = "$autodir/autosplit.ix";
769    
770     $pm{"$auto/autosplit.ix"} = $ix;
771    
772     open my $fh, "<:perlio", $ix
773     or die "$ix: $!";
774    
775     my $package;
776    
777     while (<$fh>) {
778     if (/^\s*sub\s+ ([^[:space:];]+) \s* (?:\([^)]*\))? \s*;?\s*$/x) {
779     my $al = "auto/$package/$1.al";
780     my $inc = find_inc $al;
781    
782     defined $inc or die "$al: autoload file not found, but should be there.\n";
783    
784     $pm{$al} = "$inc/$al";
785    
786     } elsif (/^\s*package\s+([^[:space:];]+)\s*;?\s*$/) {
787     ($package = $1) =~ s/::/\//g;
788     } elsif (/^\s*(?:#|1?\s*;?\s*$)/) {
789     # nop
790     } else {
791     warn "$ix: unparsable line, please report: $_";
792     }
793     }
794     }
795    
796     for my $pm (keys %pm) {
797     if ($pm =~ /^(.*)\.pm$/) {
798     my $auto = "auto/$1";
799     my $autodir = find_inc $auto;
800    
801     if (defined $autodir && -d "$autodir/$auto") {
802     $autodir = "$autodir/$auto";
803    
804     # AutoLoader
805     scan_al $auto, $autodir
806     if -f "$autodir/autosplit.ix";
807    
808     # extralibs.ld
809     if (open my $fh, "<:perlio", "$autodir/extralibs.ld") {
810     local $/;
811     $extralibs .= " " . <$fh>;
812     }
813    
814     $pm =~ /([^\/]+).pm$/ or die "$pm: unable to match last component";
815    
816     my $base = $1;
817    
818     # static ext
819     if (-f "$autodir/$base$Config{_a}") {
820     push @libs, "$autodir/$base$Config{_a}";
821     push @static_ext, $pm;
822     }
823    
824     # dynamic object
825     die "ERROR: found shared object - can't link statically ($_)\n"
826     if -f "$autodir/$base.$Config{dlext}";
827     }
828     }
829     }
830    
831     #############################################################################
832    
833 root 1.1 my $data;
834     my @index;
835     my @order = sort {
836     length $a <=> length $b
837     or $a cmp $b
838     } keys %pm;
839    
840     # sorting by name - better compression, but needs more metadata
841     # sorting by length - faster lookup
842     # usually, the metadata overhead beats the loss through compression
843    
844     for my $pm (@order) {
845     my $path = $pm{$pm};
846    
847     128 > length $pm
848 root 1.18 or die "ERROR: $pm: path too long (only 128 octets supported)\n";
849 root 1.1
850     my $src = ref $path
851     ? $$path
852     : do {
853 root 1.7 open my $pm, "<", $path
854 root 1.1 or die "$path: $!";
855    
856     local $/;
857    
858     <$pm>
859     };
860    
861 root 1.18 my $size = length $src;
862    
863 root 1.8 unless ($pmbin{$pm}) { # only do this unless the file is binary
864     if ($pm =~ /^auto\/POSIX\/[^\/]+\.al$/) {
865     if ($src =~ /^ unimpl \"/m) {
866     warn "$pm: skipping (not implemented anyways).\n"
867     if $VERBOSE >= 2;
868     next;
869     }
870 root 1.1 }
871    
872 root 1.18 $src = cache "$UNISTRIP,$OPTIMISE_SIZE,$STRIP", $src, sub {
873     if ($UNISTRIP && $pm =~ /^unicore\/.*\.pl$/) {
874     # special stripping for unicore swashes and properties
875     # much more could be done by going binary
876     $src =~ s{
877     (^return\ <<'END';\n) (.*?\n) (END(?:\n|\Z))
878     }{
879     my ($pre, $data, $post) = ($1, $2, $3);
880    
881     for ($data) {
882     s/^([0-9a-fA-F]+)\t([0-9a-fA-F]+)\t/sprintf "%X\t%X", hex $1, hex $2/gem
883     if $OPTIMISE_SIZE;
884    
885     # s{
886     # ^([0-9a-fA-F]+)\t([0-9a-fA-F]*)\t
887     # }{
888     # # ww - smaller filesize, UU - compress better
889     # pack "C0UU",
890     # hex $1,
891     # length $2 ? (hex $2) - (hex $1) : 0
892     # }gemx;
893 root 1.1
894 root 1.18 s/#.*\n/\n/mg;
895     s/\s+\n/\n/mg;
896     }
897 root 1.8
898 root 1.18 "$pre$data$post"
899     }smex;
900 root 1.1 }
901    
902 root 1.18 if ($STRIP =~ /ppi/i) {
903     require PPI;
904    
905     if (my $ppi = PPI::Document->new (\$src)) {
906     $ppi->prune ("PPI::Token::Comment");
907     $ppi->prune ("PPI::Token::Pod");
908    
909     # prune END stuff
910     for (my $last = $ppi->last_element; $last; ) {
911     my $prev = $last->previous_token;
912    
913     if ($last->isa (PPI::Token::Whitespace::)) {
914     $last->delete;
915     } elsif ($last->isa (PPI::Statement::End::)) {
916     $last->delete;
917     last;
918     } elsif ($last->isa (PPI::Token::Pod::)) {
919     $last->delete;
920     } else {
921     last;
922     }
923    
924     $last = $prev;
925     }
926    
927     # prune some but not all insignificant whitespace
928     for my $ws (@{ $ppi->find (PPI::Token::Whitespace::) }) {
929     my $prev = $ws->previous_token;
930     my $next = $ws->next_token;
931    
932     if (!$prev || !$next) {
933     $ws->delete;
934     } else {
935     if (
936     $next->isa (PPI::Token::Operator::) && $next->{content} =~ /^(?:,|=|!|!=|==|=>)$/ # no ., because of digits. == float
937     or $prev->isa (PPI::Token::Operator::) && $prev->{content} =~ /^(?:,|=|\.|!|!=|==|=>)$/
938     or $prev->isa (PPI::Token::Structure::)
939     or ($OPTIMISE_SIZE &&
940     ($prev->isa (PPI::Token::Word::)
941     && (PPI::Token::Symbol:: eq ref $next
942     || $next->isa (PPI::Structure::Block::)
943     || $next->isa (PPI::Structure::List::)
944     || $next->isa (PPI::Structure::Condition::)))
945     )
946     ) {
947     $ws->delete;
948     } elsif ($prev->isa (PPI::Token::Whitespace::)) {
949     $ws->{content} = ' ';
950     $prev->delete;
951     } else {
952     $ws->{content} = ' ';
953     }
954     }
955     }
956 root 1.1
957 root 1.18 # prune whitespace around blocks
958     if ($OPTIMISE_SIZE) {
959     # these usually decrease size, but decrease compressability more
960     for my $struct (PPI::Structure::Block::, PPI::Structure::Condition::) {
961     for my $node (@{ $ppi->find ($struct) }) {
962     my $n1 = $node->first_token;
963     my $n2 = $n1->previous_token;
964     $n1->delete if $n1->isa (PPI::Token::Whitespace::);
965     $n2->delete if $n2 && $n2->isa (PPI::Token::Whitespace::);
966     my $n1 = $node->last_token;
967     my $n2 = $n1->next_token;
968     $n1->delete if $n1->isa (PPI::Token::Whitespace::);
969     $n2->delete if $n2 && $n2->isa (PPI::Token::Whitespace::);
970     }
971     }
972    
973     for my $node (@{ $ppi->find (PPI::Structure::List::) }) {
974     my $n1 = $node->first_token;
975     $n1->delete if $n1->isa (PPI::Token::Whitespace::);
976     my $n1 = $node->last_token;
977     $n1->delete if $n1->isa (PPI::Token::Whitespace::);
978     }
979 root 1.8 }
980 root 1.1
981 root 1.18 # reformat qw() lists which often have lots of whitespace
982     for my $node (@{ $ppi->find (PPI::Token::QuoteLike::Words::) }) {
983     if ($node->{content} =~ /^qw(.)(.*)(.)$/s) {
984     my ($a, $qw, $b) = ($1, $2, $3);
985     $qw =~ s/^\s+//;
986     $qw =~ s/\s+$//;
987     $qw =~ s/\s+/ /g;
988     $node->{content} = "qw$a$qw$b";
989     }
990 root 1.8 }
991 root 1.18
992     $src = $ppi->serialize;
993     } else {
994     warn "WARNING: $pm{$pm}: PPI failed to parse this file\n";
995 root 1.8 }
996 root 1.18 } elsif ($STRIP =~ /pod/i && $pm ne "Opcode.pm") { # opcode parses it's own pod
997     require Pod::Strip;
998 root 1.8
999 root 1.18 my $stripper = Pod::Strip->new;
1000    
1001     my $out;
1002     $stripper->output_string (\$out);
1003     $stripper->parse_string_document ($src)
1004     or die;
1005     $src = $out;
1006 root 1.1 }
1007    
1008 root 1.18 if ($VERIFY && $pm =~ /\.pm$/ && $pm ne "Opcode.pm") {
1009     if (open my $fh, "-|") {
1010     <$fh>;
1011     } else {
1012     eval "#line 1 \"$pm\"\n$src" or warn "\n\n\n$pm\n\n$src\n$@\n\n\n";
1013     exit 0;
1014 root 1.8 }
1015 root 1.1 }
1016 root 1.8
1017 root 1.18 $src
1018     };
1019 root 1.1
1020 root 1.8 # if ($pm eq "Opcode.pm") {
1021     # open my $fh, ">x" or die; print $fh $src;#d#
1022     # exit 1;
1023     # }
1024 root 1.1 }
1025    
1026 root 1.18 print "adding $pm{$pm} (original size $size, stored size ", length $src, ")\n"
1027 root 1.1 if $VERBOSE >= 2;
1028    
1029     push @index, ((length $pm) << 25) | length $data;
1030     $data .= $pm . $src;
1031     }
1032    
1033     length $data < 2**25
1034     or die "bundle too large (only 32MB supported)\n";
1035    
1036     my $varpfx = "bundle_" . substr +(Digest::MD5::md5_hex $data), 0, 16;
1037    
1038     #############################################################################
1039     # output
1040    
1041     print "generating $PREFIX.h... ";
1042    
1043     {
1044     open my $fh, ">", "$PREFIX.h"
1045     or die "$PREFIX.h: $!\n";
1046    
1047     print $fh <<EOF;
1048     /* do not edit, automatically created by mkstaticbundle */
1049 root 1.8
1050 root 1.1 #include <EXTERN.h>
1051     #include <perl.h>
1052     #include <XSUB.h>
1053    
1054     /* public API */
1055     EXTERN_C PerlInterpreter *staticperl;
1056 root 1.7 EXTERN_C void staticperl_xs_init (pTHX);
1057 root 1.1 EXTERN_C void staticperl_init (void);
1058     EXTERN_C void staticperl_cleanup (void);
1059 root 1.8
1060 root 1.1 EOF
1061     }
1062    
1063     print "\n";
1064    
1065     #############################################################################
1066     # output
1067    
1068     print "generating $PREFIX.c... ";
1069    
1070     open my $fh, ">", "$PREFIX.c"
1071     or die "$PREFIX.c: $!\n";
1072    
1073     print $fh <<EOF;
1074     /* do not edit, automatically created by mkstaticbundle */
1075    
1076     #include "bundle.h"
1077    
1078     /* public API */
1079     PerlInterpreter *staticperl;
1080    
1081     EOF
1082    
1083     #############################################################################
1084     # bundle data
1085    
1086     my $count = @index;
1087    
1088     print $fh <<EOF;
1089     #include "bundle.h"
1090    
1091     /* bundle data */
1092    
1093     static const U32 $varpfx\_count = $count;
1094     static const U32 $varpfx\_index [$count + 1] = {
1095     EOF
1096    
1097     my $col;
1098     for (@index) {
1099     printf $fh "0x%08x,", $_;
1100     print $fh "\n" unless ++$col % 10;
1101    
1102     }
1103     printf $fh "0x%08x\n};\n", (length $data);
1104    
1105     print $fh "static const char $varpfx\_data [] =\n";
1106     dump_string $fh, $data;
1107    
1108     print $fh ";\n\n";;
1109    
1110     #############################################################################
1111     # bootstrap
1112    
1113     # boot file for staticperl
1114     # this file will be eval'ed at initialisation time
1115    
1116     my $bootstrap = '
1117     BEGIN {
1118     package ' . $PACKAGE . ';
1119    
1120     PerlIO::scalar->bootstrap;
1121    
1122     @INC = sub {
1123     my $data = find "$_[1]"
1124     or return;
1125    
1126     $INC{$_[1]} = $_[1];
1127    
1128     open my $fh, "<", \$data;
1129     $fh
1130     };
1131     }
1132     ';
1133    
1134     $bootstrap .= "require '//boot';"
1135     if exists $pm{"//boot"};
1136    
1137     $bootstrap =~ s/\s+/ /g;
1138     $bootstrap =~ s/(\W) /$1/g;
1139     $bootstrap =~ s/ (\W)/$1/g;
1140    
1141     print $fh "const char bootstrap [] = ";
1142     dump_string $fh, $bootstrap;
1143     print $fh ";\n\n";
1144    
1145     print $fh <<EOF;
1146     /* search all bundles for the given file, using binary search */
1147     XS(find)
1148     {
1149     dXSARGS;
1150    
1151     if (items != 1)
1152     Perl_croak (aTHX_ "Usage: $PACKAGE\::find (\$path)");
1153    
1154     {
1155     STRLEN namelen;
1156     char *name = SvPV (ST (0), namelen);
1157     SV *res = 0;
1158    
1159     int l = 0, r = $varpfx\_count;
1160    
1161     while (l <= r)
1162     {
1163     int m = (l + r) >> 1;
1164     U32 idx = $varpfx\_index [m];
1165     int comp = namelen - (idx >> 25);
1166    
1167     if (!comp)
1168     {
1169     int ofs = idx & 0x1FFFFFFU;
1170     comp = memcmp (name, $varpfx\_data + ofs, namelen);
1171    
1172     if (!comp)
1173     {
1174     /* found */
1175     int ofs2 = $varpfx\_index [m + 1] & 0x1FFFFFFU;
1176    
1177     ofs += namelen;
1178     res = newSVpvn ($varpfx\_data + ofs, ofs2 - ofs);
1179     goto found;
1180     }
1181     }
1182    
1183     if (comp < 0)
1184     r = m - 1;
1185     else
1186     l = m + 1;
1187     }
1188    
1189     XSRETURN (0);
1190    
1191     found:
1192     ST (0) = res;
1193     sv_2mortal (ST (0));
1194     }
1195    
1196     XSRETURN (1);
1197     }
1198    
1199     /* list all files in the bundle */
1200     XS(list)
1201     {
1202     dXSARGS;
1203    
1204     if (items != 0)
1205     Perl_croak (aTHX_ "Usage: $PACKAGE\::list");
1206    
1207     {
1208     int i;
1209    
1210     EXTEND (SP, $varpfx\_count);
1211    
1212     for (i = 0; i < $varpfx\_count; ++i)
1213     {
1214     U32 idx = $varpfx\_index [i];
1215    
1216     PUSHs (newSVpvn ($varpfx\_data + (idx & 0x1FFFFFFU), idx >> 25));
1217     }
1218     }
1219    
1220     XSRETURN ($varpfx\_count);
1221     }
1222    
1223     EOF
1224    
1225     #############################################################################
1226     # xs_init
1227    
1228     print $fh <<EOF;
1229 root 1.7 void
1230     staticperl_xs_init (pTHX)
1231 root 1.1 {
1232     EOF
1233    
1234     @static_ext = ("DynaLoader", sort @static_ext);
1235    
1236     # prototypes
1237     for (@static_ext) {
1238     s/\.pm$//;
1239     (my $cname = $_) =~ s/\//__/g;
1240     print $fh " EXTERN_C void boot_$cname (pTHX_ CV* cv);\n";
1241     }
1242    
1243     print $fh <<EOF;
1244     char *file = __FILE__;
1245     dXSUB_SYS;
1246    
1247     newXSproto ("$PACKAGE\::find", find, file, "\$");
1248     newXSproto ("$PACKAGE\::list", list, file, "");
1249     EOF
1250    
1251     # calls
1252     for (@static_ext) {
1253     s/\.pm$//;
1254    
1255     (my $cname = $_) =~ s/\//__/g;
1256     (my $pname = $_) =~ s/\//::/g;
1257    
1258     my $bootstrap = $pname eq "DynaLoader" ? "boot" : "bootstrap";
1259    
1260     print $fh " newXS (\"$pname\::$bootstrap\", boot_$cname, file);\n";
1261     }
1262    
1263     print $fh <<EOF;
1264     Perl_av_create_and_unshift_one (&PL_preambleav, newSVpv (bootstrap, sizeof (bootstrap) - 1));
1265     }
1266     EOF
1267    
1268     #############################################################################
1269     # optional perl_init/perl_destroy
1270    
1271 root 1.17 if ($APP) {
1272     print $fh <<EOF;
1273    
1274     int
1275     main (int argc, char *argv [])
1276     {
1277     extern char **environ;
1278     int exitstatus;
1279    
1280     static char *args[] = {
1281     "staticperl",
1282     "-e",
1283     "0"
1284     };
1285    
1286     PERL_SYS_INIT3 (&argc, &argv, &environ);
1287     staticperl = perl_alloc ();
1288     perl_construct (staticperl);
1289    
1290     PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
1291    
1292     exitstatus = perl_parse (staticperl, staticperl_xs_init, sizeof (args) / sizeof (*args), args, environ);
1293     if (!exitstatus)
1294     perl_run (staticperl);
1295    
1296     exitstatus = perl_destruct (staticperl);
1297     perl_free (staticperl);
1298     PERL_SYS_TERM ();
1299    
1300     return exitstatus;
1301     }
1302     EOF
1303     } elsif ($PERL) {
1304 root 1.1 print $fh <<EOF;
1305    
1306     int
1307     main (int argc, char *argv [])
1308     {
1309     extern char **environ;
1310     int exitstatus;
1311    
1312     PERL_SYS_INIT3 (&argc, &argv, &environ);
1313     staticperl = perl_alloc ();
1314     perl_construct (staticperl);
1315    
1316     PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
1317    
1318 root 1.7 exitstatus = perl_parse (staticperl, staticperl_xs_init, argc, argv, environ);
1319 root 1.1 if (!exitstatus)
1320     perl_run (staticperl);
1321    
1322     exitstatus = perl_destruct (staticperl);
1323     perl_free (staticperl);
1324     PERL_SYS_TERM ();
1325    
1326     return exitstatus;
1327     }
1328     EOF
1329     } else {
1330     print $fh <<EOF;
1331    
1332     EXTERN_C void
1333     staticperl_init (void)
1334     {
1335     extern char **environ;
1336     int argc = sizeof (args) / sizeof (args [0]);
1337     char **argv = args;
1338    
1339 root 1.17 static char *args[] = {
1340     "staticperl",
1341     "-e",
1342     "0"
1343     };
1344    
1345 root 1.1 PERL_SYS_INIT3 (&argc, &argv, &environ);
1346     staticperl = perl_alloc ();
1347     perl_construct (staticperl);
1348     PL_origalen = 1;
1349     PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
1350 root 1.7 perl_parse (staticperl, staticperl_xs_init, argc, argv, environ);
1351 root 1.1
1352     perl_run (staticperl);
1353     }
1354    
1355     EXTERN_C void
1356     staticperl_cleanup (void)
1357     {
1358     perl_destruct (staticperl);
1359     perl_free (staticperl);
1360     staticperl = 0;
1361     PERL_SYS_TERM ();
1362     }
1363     EOF
1364     }
1365    
1366     print -s "$PREFIX.c", " octets (", (length $data) , " data octets).\n\n";
1367    
1368     #############################################################################
1369     # libs, cflags
1370    
1371     {
1372     print "generating $PREFIX.ccopts... ";
1373    
1374     my $str = "$Config{ccflags} $Config{optimize} $Config{cppflags} -I$Config{archlibexp}/CORE";
1375     $str =~ s/([\(\)])/\\$1/g;
1376    
1377     print "$str\n\n";
1378    
1379     open my $fh, ">$PREFIX.ccopts"
1380     or die "$PREFIX.ccopts: $!";
1381     print $fh $str;
1382     }
1383    
1384     {
1385     print "generating $PREFIX.ldopts... ";
1386    
1387 root 1.18 my $str = $STATIC ? "-static " : "";
1388 root 1.1
1389     $str .= "$Config{ccdlflags} $Config{ldflags} @libs $Config{archlibexp}/CORE/$Config{libperl} $Config{perllibs}";
1390    
1391     my %seen;
1392     $str .= " $_" for grep !$seen{$_}++, ($extralibs =~ /(\S+)/g);
1393    
1394 root 1.18 for (@staticlibs) {
1395     $str =~ s/(^|\s) (-l\Q$_\E) ($|\s)/$1-Wl,-Bstatic $2 -Wl,-Bdynamic$3/gx;
1396     }
1397    
1398 root 1.1 $str =~ s/([\(\)])/\\$1/g;
1399    
1400     print "$str\n\n";
1401    
1402     open my $fh, ">$PREFIX.ldopts"
1403     or die "$PREFIX.ldopts: $!";
1404     print $fh $str;
1405     }
1406    
1407 root 1.17 if ($PERL or defined $APP) {
1408     $APP = "perl" unless defined $APP;
1409    
1410     print "generating $APP...\n";
1411    
1412     system "$Config{cc} \$(cat bundle.ccopts\) -o \Q$APP\E bundle.c \$(cat bundle.ldopts\)";
1413 root 1.1
1414 root 1.18 # unlink "$PREFIX.$_"
1415     # for qw(ccopts ldopts c h);
1416    
1417     print "\n";
1418 root 1.1 }
1419    
1420     MKBUNDLE
1421     }
1422    
1423     bundle() {
1424     catmkbundle >"$MKBUNDLE~" || fatal "$MKBUNDLE~: cannot create"
1425     chmod 755 "$MKBUNDLE~" && mv "$MKBUNDLE~" "$MKBUNDLE"
1426 root 1.18 CACHE="$STATICPERL/cache"
1427     mkdir -p "$CACHE"
1428     "$PERL_PREFIX/bin/perl" -- "$MKBUNDLE" --cache "$CACHE" "$@"
1429 root 1.1 }
1430    
1431     if [ $# -gt 0 ]; then
1432     while [ $# -gt 0 ]; do
1433     mkdir -p "$STATICPERL" || fatal "$STATICPERL: cannot create"
1434 root 1.10 mkdir -p "$PERL_PREFIX" || fatal "$PERL_PREFIX: cannot create"
1435 root 1.1
1436     command="${1#--}"; shift
1437     case "$command" in
1438     fetch | configure | build | install | clean | distclean)
1439     verblock <<EOF
1440     $command
1441     EOF
1442 root 1.10 ( "$command" )
1443 root 1.1 ;;
1444     instsrc )
1445 root 1.10 ( instsrc "$@" )
1446 root 1.1 exit
1447     ;;
1448     instcpan )
1449 root 1.10 ( instcpan "$@" )
1450 root 1.1 exit
1451     ;;
1452     cpan )
1453 root 1.10 ( install )
1454     "$PERL_PREFIX/bin/cpan" "$@"
1455 root 1.1 exit
1456     ;;
1457     mkbundle )
1458 root 1.10 ( install )
1459 root 1.1 bundle "$@"
1460     exit
1461     ;;
1462     mkperl )
1463 root 1.10 ( install )
1464 root 1.1 bundle --perl "$@"
1465     exit
1466     ;;
1467 root 1.17 mkapp )
1468     ( install )
1469     bundle --app "$@"
1470     exit
1471     ;;
1472 root 1.1 help )
1473     podusage 2
1474     ;;
1475     * )
1476     exec 1>&2
1477     echo
1478     echo "Unknown command: $command"
1479     podusage 0
1480     ;;
1481     esac
1482     done
1483     else
1484     usage
1485     fi
1486    
1487     exit 0
1488    
1489     =head1 NAME
1490    
1491 root 1.7 staticperl - perl, libc, 100 modules, all in one 500kb file
1492 root 1.1
1493     =head1 SYNOPSIS
1494    
1495     staticperl help # print the embedded documentation
1496     staticperl fetch # fetch and unpack perl sources
1497     staticperl configure # fetch and then configure perl
1498     staticperl build # configure and then build perl
1499     staticperl install # build and then install perl
1500     staticperl clean # clean most intermediate files (restart at configure)
1501     staticperl distclean # delete everything installed by this script
1502     staticperl cpan # invoke CPAN shell
1503     staticperl instmod path... # install unpacked modules
1504     staticperl instcpan modulename... # install modules from CPAN
1505     staticperl mkbundle <bundle-args...> # see documentation
1506     staticperl mkperl <bundle-args...> # see documentation
1507 root 1.17 staticperl mkapp appname <bundle-args...> # see documentation
1508 root 1.1
1509     Typical Examples:
1510    
1511     staticperl install # fetch, configure, build and install perl
1512     staticperl cpan # run interactive cpan shell
1513     staticperl mkperl -M '"Config_heavy.pl"' # build a perl that supports -V
1514     staticperl mkperl -MAnyEvent::Impl::Perl -MAnyEvent::HTTPD -MURI -MURI::http
1515     # build a perl with the above modules linked in
1516 root 1.17 staticperl mkapp myapp --boot mainprog mymodules
1517     # build a binary "myapp" from mainprog and mymodules
1518 root 1.1
1519     =head1 DESCRIPTION
1520    
1521 root 1.18 This script helps you to create single-file perl interpreters
1522     or applications, or embedding a perl interpreter in your
1523     applications. Single-file means that it is fully self-contained - no
1524     separate shared objects, no autoload fragments, no .pm or .pl files are
1525     needed. And when linking statically, you can create (or embed) a single
1526     file that contains perl interpreter, libc, all the modules you need, all
1527     the libraries you need and of course your actual program.
1528 root 1.1
1529 root 1.7 With F<uClibc> and F<upx> on x86, you can create a single 500kb binary
1530     that contains perl and 100 modules such as POSIX, AnyEvent, EV, IO::AIO,
1531     Coro and so on. Or any other choice of modules.
1532 root 1.1
1533 root 1.4 The created files do not need write access to the file system (like PAR
1534 root 1.1 does). In fact, since this script is in many ways similar to PAR::Packer,
1535     here are the differences:
1536    
1537     =over 4
1538    
1539     =item * The generated executables are much smaller than PAR created ones.
1540    
1541     Shared objects and the perl binary contain a lot of extra info, while
1542     the static nature of F<staticperl> allows the linker to remove all
1543     functionality and meta-info not required by the final executable. Even
1544     extensions statically compiled into perl at build time will only be
1545     present in the final executable when needed.
1546    
1547     In addition, F<staticperl> can strip perl sources much more effectively
1548     than PAR.
1549    
1550     =item * The generated executables start much faster.
1551    
1552     There is no need to unpack files, or even to parse Zip archives (which is
1553     slow and memory-consuming business).
1554    
1555     =item * The generated executables don't need a writable filesystem.
1556    
1557     F<staticperl> loads all required files directly from memory. There is no
1558     need to unpack files into a temporary directory.
1559    
1560 root 1.18 =item * More control over included files, more burden.
1561 root 1.1
1562 root 1.4 PAR tries to be maintenance and hassle-free - it tries to include more
1563 root 1.18 files than necessary to make sure everything works out of the box. It
1564     mostly succeeds at this, but he extra files (such as the unicode database)
1565     can take substantial amounts of memory and file size.
1566 root 1.1
1567     With F<staticperl>, the burden is mostly with the developer - only direct
1568     compile-time dependencies and L<AutoLoader> are handled automatically.
1569     This means the modules to include often need to be tweaked manually.
1570    
1571 root 1.18 All this does not preclude more permissive modes to be implemented in
1572     the future, but right now, you have to resolve state hidden dependencies
1573     manually.
1574    
1575 root 1.1 =item * PAR works out of the box, F<staticperl> does not.
1576    
1577     Maintaining your own custom perl build can be a pain in the ass, and while
1578     F<staticperl> tries to make this easy, it still requires a custom perl
1579     build and possibly fiddling with some modules. PAR is likely to produce
1580     results faster.
1581    
1582 root 1.13 Ok, PAR never has worked for me out of the box, and for some people,
1583     F<staticperl> does work out of the box, as they don't count "fiddling with
1584     module use lists" against it, but nevertheless, F<staticperl> is certainly
1585     a bit more difficult to use.
1586    
1587 root 1.1 =back
1588    
1589     =head1 HOW DOES IT WORK?
1590    
1591     Simple: F<staticperl> downloads, compile and installs a perl version of
1592     your choice in F<~/.staticperl>. You can add extra modules either by
1593     letting F<staticperl> install them for you automatically, or by using CPAN
1594     and doing it interactively. This usually takes 5-10 minutes, depending on
1595 root 1.4 the speed of your computer and your internet connection.
1596 root 1.1
1597     It is possible to do program development at this stage, too.
1598    
1599     Afterwards, you create a list of files and modules you want to include,
1600 root 1.4 and then either build a new perl binary (that acts just like a normal perl
1601 root 1.1 except everything is compiled in), or you create bundle files (basically C
1602     sources you can use to embed all files into your project).
1603    
1604 root 1.18 This step is very fast (a few seconds if PPI is not used for stripping, or
1605     the stripped files are in the cache), and can be tweaked and repeated as
1606     often as necessary.
1607 root 1.1
1608     =head1 THE F<STATICPERL> SCRIPT
1609    
1610     This module installs a script called F<staticperl> into your perl
1611     binary directory. The script is fully self-contained, and can be used
1612     without perl (for example, in an uClibc chroot environment). In fact,
1613     it can be extracted from the C<App::Staticperl> distribution tarball as
1614     F<bin/staticperl>, without any installation.
1615    
1616     F<staticperl> interprets the first argument as a command to execute,
1617     optionally followed by any parameters.
1618    
1619     There are two command categories: the "phase 1" commands which deal with
1620     installing perl and perl modules, and the "phase 2" commands, which deal
1621     with creating binaries and bundle files.
1622    
1623     =head2 PHASE 1 COMMANDS: INSTALLING PERL
1624    
1625     The most important command is F<install>, which does basically
1626     everything. The default is to download and install perl 5.12.2 and a few
1627     modules required by F<staticperl> itself, but all this can (and should) be
1628     changed - see L<CONFIGURATION>, below.
1629    
1630     The command
1631    
1632     staticperl install
1633    
1634     Is normally all you need: It installs the perl interpreter in
1635     F<~/.staticperl/perl>. It downloads, configures, builds and installs the
1636     perl interpreter if required.
1637    
1638     Most of the following commands simply run one or more steps of this
1639     sequence.
1640    
1641 root 1.4 To force recompilation or reinstallation, you need to run F<staticperl
1642 root 1.1 distclean> first.
1643    
1644     =over 4
1645    
1646     =item F<staticperl fetch>
1647    
1648     Runs only the download and unpack phase, unless this has already happened.
1649    
1650     =item F<staticperl configure>
1651    
1652     Configures the unpacked perl sources, potentially after downloading them first.
1653    
1654     =item F<staticperl build>
1655    
1656     Builds the configured perl sources, potentially after automatically
1657     configuring them.
1658    
1659     =item F<staticperl install>
1660    
1661 root 1.4 Wipes the perl installation directory (usually F<~/.staticperl/perl>) and
1662     installs the perl distribution, potentially after building it first.
1663 root 1.1
1664     =item F<staticperl cpan> [args...]
1665    
1666 root 1.4 Starts an interactive CPAN shell that you can use to install further
1667     modules. Installs the perl first if necessary, but apart from that,
1668 root 1.1 no magic is involved: you could just as well run it manually via
1669     F<~/.staticperl/perl/bin/cpan>.
1670    
1671     Any additional arguments are simply passed to the F<cpan> command.
1672    
1673     =item F<staticperl instcpan> module...
1674    
1675     Tries to install all the modules given and their dependencies, using CPAN.
1676    
1677     Example:
1678    
1679     staticperl instcpan EV AnyEvent::HTTPD Coro
1680    
1681     =item F<staticperl instsrc> directory...
1682    
1683     In the unlikely case that you have unpacked perl modules around and want
1684 root 1.4 to install from these instead of from CPAN, you can do this using this
1685 root 1.1 command by specifying all the directories with modules in them that you
1686     want to have built.
1687    
1688     =item F<staticperl clean>
1689    
1690 root 1.11 Deletes the perl source directory (and potentially cleans up other
1691     intermediate files). This can be used to clean up files only needed for
1692     building perl, without removing the installed perl interpreter, or to
1693     force a re-build from scratch.
1694    
1695     At the moment, it doesn't delete downloaded tarballs.
1696 root 1.1
1697     =item F<staticperl distclean>
1698    
1699     This wipes your complete F<~/.staticperl> directory. Be careful with this,
1700     it nukes your perl download, perl sources, perl distribution and any
1701     installed modules. It is useful if you wish to start over "from scratch"
1702     or when you want to uninstall F<staticperl>.
1703    
1704     =back
1705    
1706     =head2 PHASE 2 COMMANDS: BUILDING PERL BUNDLES
1707    
1708     Building (linking) a new F<perl> binary is handled by a separate
1709     script. To make it easy to use F<staticperl> from a F<chroot>, the script
1710     is embedded into F<staticperl>, which will write it out and call for you
1711     with any arguments you pass:
1712    
1713     staticperl mkbundle mkbundle-args...
1714    
1715     In the oh so unlikely case of something not working here, you
1716 root 1.2 can run the script manually as well (by default it is written to
1717 root 1.1 F<~/.staticperl/mkbundle>).
1718    
1719     F<mkbundle> is a more conventional command and expect the argument
1720 root 1.4 syntax commonly used on UNIX clones. For example, this command builds
1721 root 1.1 a new F<perl> binary and includes F<Config.pm> (for F<perl -V>),
1722     F<AnyEvent::HTTPD>, F<URI> and a custom F<httpd> script (from F<eg/httpd>
1723     in this distribution):
1724    
1725     # first make sure we have perl and the required modules
1726     staticperl instcpan AnyEvent::HTTPD
1727    
1728     # now build the perl
1729     staticperl mkperl -M'"Config_heavy.pl"' -MAnyEvent::Impl::Perl \
1730     -MAnyEvent::HTTPD -MURI::http \
1731     --add 'eg/httpd httpd.pm'
1732    
1733     # finally, invoke it
1734     ./perl -Mhttpd
1735    
1736 root 1.2 As you can see, things are not quite as trivial: the L<Config> module has
1737     a hidden dependency which is not even a perl module (F<Config_heavy.pl>),
1738     L<AnyEvent> needs at least one event loop backend that we have to
1739 root 1.4 specify manually (here L<AnyEvent::Impl::Perl>), and the F<URI> module
1740 root 1.2 (required by L<AnyEvent::HTTPD>) implements various URI schemes as extra
1741     modules - since L<AnyEvent::HTTPD> only needs C<http> URIs, we only need
1742 root 1.4 to include that module. I found out about these dependencies by carefully
1743     watching any error messages about missing modules...
1744 root 1.2
1745 root 1.17 Instead of building a new perl binary, you can also build a standalone
1746     application:
1747    
1748     # build the app
1749     staticperl mkapp app --boot eg/httpd \
1750     -MAnyEvent::Impl::Perl -MAnyEvent::HTTPD -MURI::http
1751    
1752     # run it
1753     ./app
1754    
1755 root 1.2 =head3 OPTION PROCESSING
1756    
1757 root 1.4 All options can be given as arguments on the command line (typically
1758     using long (e.g. C<--verbose>) or short option (e.g. C<-v>) style). Since
1759     specifying a lot of modules can make the command line very cumbersome,
1760 root 1.2 you can put all long options into a "bundle specification file" (with or
1761     without C<--> prefix) and specify this bundle file instead.
1762    
1763     For example, the command given earlier could also look like this:
1764    
1765     staticperl mkperl httpd.bundle
1766    
1767     And all options could be in F<httpd.bundle>:
1768 root 1.1
1769 root 1.2 use "Config_heavy.pl"
1770     use AnyEvent::Impl::Perl
1771     use AnyEvent::HTTPD
1772     use URI::http
1773     add eg/httpd httpd.pm
1774    
1775     All options that specify modules or files to be added are processed in the
1776 root 1.4 order given on the command line (that affects the C<--use> and C<--eval>
1777 root 1.2 options at the moment).
1778    
1779     =head3 MKBUNDLE OPTIONS
1780    
1781     =over 4
1782    
1783     =item --verbose | -v
1784    
1785     Increases the verbosity level by one (the default is C<1>).
1786    
1787     =item --quiet | -q
1788    
1789     Decreases the verbosity level by one.
1790    
1791     =item --strip none|pod|ppi
1792    
1793     Specify the stripping method applied to reduce the file of the perl
1794     sources included.
1795    
1796     The default is C<pod>, which uses the L<Pod::Strip> module to remove all
1797 root 1.4 pod documentation, which is very fast and reduces file size a lot.
1798 root 1.2
1799     The C<ppi> method uses L<PPI> to parse and condense the perl sources. This
1800 root 1.18 saves a lot more than just L<Pod::Strip>, and is generally safer,
1801     but is also a lot slower (some files take almost a minute to strip -
1802     F<staticperl> maintains a cache of stripped files to speed up subsequent
1803     runs for this reason). Note that this method doesn't optimise for raw file
1804     size, but for best compression (that means that the uncompressed file size
1805     is a bit larger, but the files compress better, e.g. with F<upx>).
1806 root 1.2
1807 root 1.7 Last not least, if you need accurate line numbers in error messages,
1808     or in the unlikely case where C<pod> is too slow, or some module gets
1809     mistreated, you can specify C<none> to not mangle included perl sources in
1810     any way.
1811 root 1.2
1812     =item --perl
1813    
1814     After writing out the bundle files, try to link a new perl interpreter. It
1815     will be called F<perl> and will be left in the current working
1816     directory. The bundle files will be removed.
1817    
1818 root 1.4 This switch is automatically used when F<staticperl> is invoked with the
1819 root 1.2 C<mkperl> command (instead of C<mkbundle>):
1820    
1821     # build a new ./perl with only common::sense in it - very small :)
1822     staticperl mkperl -Mcommon::sense
1823    
1824 root 1.17 =item --app name
1825    
1826     After writing out the bundle files, try to link a new standalone
1827     program. It will be called C<name>, and the bundle files get removed after
1828     linking it.
1829    
1830     The difference to the (mutually exclusive) C<--perl> option is that the
1831     binary created by this option will not try to act as a perl interpreter -
1832     instead it will simply initialise the perl interpreter, clean it up and
1833     exit.
1834    
1835     This switch is automatically used when F<staticperl> is invoked with the
1836     C<mkapp> command (instead of C<mkbundle>):
1837    
1838     To let it do something useful you I<must> add some boot code, e.g. with
1839     the C<--boot> option.
1840    
1841     Example: create a standalone perl binary that will execute F<appfile> when
1842     it is started.
1843    
1844     staticperl mkbundle --app myexe --boot appfile
1845    
1846 root 1.2 =item --use module | -Mmodule
1847    
1848     Include the named module and all direct dependencies. This is done by
1849     C<require>'ing the module in a subprocess and tracing which other modules
1850     and files it actually loads. If the module uses L<AutoLoader>, then all
1851     splitfiles will be included as well.
1852    
1853     Example: include AnyEvent and AnyEvent::Impl::Perl.
1854    
1855     staticperl mkbundle --use AnyEvent --use AnyEvent::Impl::Perl
1856    
1857     Sometimes you want to load old-style "perl libraries" (F<.pl> files), or
1858     maybe other weirdly named files. To do that, you need to quote the name in
1859 root 1.4 single or double quotes. When given on the command line, you probably need
1860 root 1.2 to quote once more to avoid your shell interpreting it. Common cases that
1861     need this are F<Config_heavy.pl> and F<utf8_heavy.pl>.
1862    
1863     Example: include the required files for F<perl -V> to work in all its
1864     glory (F<Config.pm> is included automatically by this).
1865    
1866     # bourne shell
1867     staticperl mkbundle --use '"Config_heavy.pl"'
1868    
1869     # bundle specification file
1870     use "Config_heavy.pl"
1871    
1872     The C<-Mmodule> syntax is included as an alias that might be easier to
1873     remember than C<use>. Or maybe it confuses people. Time will tell. Or
1874     maybe not. Argh.
1875    
1876     =item --eval "perl code" | -e "perl code"
1877    
1878     Sometimes it is easier (or necessary) to specify dependencies using perl
1879     code, or maybe one of the modules you use need a special use statement. In
1880     that case, you can use C<eval> to execute some perl snippet or set some
1881     variables or whatever you need. All files C<require>'d or C<use>'d in the
1882     script are included in the final bundle.
1883    
1884     Keep in mind that F<mkbundle> will only C<require> the modules named
1885     by the C<--use> option, so do not expect the symbols from modules you
1886 root 1.4 C<--use>'d earlier on the command line to be available.
1887 root 1.2
1888     Example: force L<AnyEvent> to detect a backend and therefore include it
1889     in the final bundle.
1890    
1891     staticperl mkbundle --eval 'use AnyEvent; AnyEvent::detect'
1892    
1893     # or like this
1894     staticperl mkbundle -MAnyEvent --eval 'use AnyEvent; AnyEvent::detect'
1895    
1896     Example: use a separate "bootstrap" script that C<use>'s lots of modules
1897     and include this in the final bundle, to be executed automatically.
1898    
1899     staticperl mkbundle --eval 'do "bootstrap"' --boot bootstrap
1900    
1901     =item --boot filename
1902    
1903     Include the given file in the bundle and arrange for it to be executed
1904     (using a C<require>) before anything else when the new perl is
1905     initialised. This can be used to modify C<@INC> or anything else before
1906 root 1.4 the perl interpreter executes scripts given on the command line (or via
1907 root 1.2 C<-e>). This works even in an embedded interpreter.
1908    
1909 root 1.18 =item --incglob pattern
1910    
1911     This goes through all library directories and tries to match any F<.pm>
1912     and F<.pl> files against the extended glob pattern (see below). If a file
1913     matches, it is added. This switch will automatically detect L<AutoLoader>
1914     files and the required link libraries for XS modules, but it will I<not>
1915     scan the file for dependencies (at the moment).
1916    
1917     This is mainly useful to include "everything":
1918    
1919     --incglob '*'
1920    
1921     Or to include perl libraries, or trees of those, such as the unicode
1922     database files needed by many other modules:
1923    
1924     --incglob '/unicore/**.pl'
1925    
1926     =item --add file | --add "file alias"
1927 root 1.2
1928     Adds the given (perl) file into the bundle (and optionally call it
1929     "alias"). This is useful to include any custom files into the bundle.
1930    
1931     Example: embed the file F<httpd> as F<httpd.pm> when creating the bundle.
1932    
1933     staticperl mkperl --add "httpd httpd.pm"
1934    
1935     It is also a great way to add any custom modules:
1936    
1937     # specification file
1938     add file1 myfiles/file1
1939     add file2 myfiles/file2
1940     add file3 myfiles/file3
1941    
1942 root 1.18 =item --binadd file | --add "file alias"
1943 root 1.8
1944     Just like C<--add>, except that it treats the file as binary and adds it
1945     without any processing.
1946    
1947     You should probably add a C</> prefix to avoid clashing with embedded
1948     perl files (whose paths do not start with C</>), and/or use a special
1949     directory, such as C</res/name>.
1950    
1951     You can later get a copy of these files by calling C<staticperl::find
1952     "alias">.
1953    
1954 root 1.18 =item --include pattern | -i pattern | --exclude pattern | -x pattern
1955    
1956     These two options define an include/exclude filter that is used after all
1957     files selected by the other options have been found. Each include/exclude
1958     is applied to all files found so far - an include makes sure that the
1959     given files will be part of the resulting file set, an exclude will
1960     exclude files. The patterns are "extended glob patterns" (see below).
1961    
1962     For example, to include everything, except C<Devel> modules, but still
1963     include F<Devel::PPPort>, you could use this:
1964    
1965     --incglob '*' -i '/Devel/PPPort.pm' -x '/Devel/**'
1966    
1967 root 1.2 =item --static
1968    
1969     When C<--perl> is also given, link statically instead of dynamically. The
1970     default is to link the new perl interpreter fully dynamic (that means all
1971     perl modules are linked statically, but all external libraries are still
1972     referenced dynamically).
1973    
1974     Keep in mind that Solaris doesn't support static linking at all, and
1975     systems based on GNU libc don't really support it in a usable fashion
1976     either. Try uClibc if you want to create fully statically linked
1977     executables, or try the C<--staticlibs> option to link only some libraries
1978     statically.
1979    
1980 root 1.18 =item --staticlib libname
1981    
1982     When not linking fully statically, this option allows you to link specific
1983     libraries statically. What it does is simply replace all occurances of
1984     C<-llibname> with the GCC-specific C<-Wl,-Bstatic -llibname -Wl,-Bdynamic>
1985     option.
1986    
1987     This will have no effect unless the library is actually linked against,
1988     specifically, C<--staticlib> will not link against the named library
1989     unless it would be linked against anyway.
1990    
1991     Example: link libcrypt statically into the binary.
1992    
1993     staticperl mkperl -MIO::AIO --staticlib crypt
1994    
1995     # ldopts might nwo contain:
1996     # -lm -Wl,-Bstatic -lcrypt -Wl,-Bdynamic -lpthread
1997    
1998 root 1.2 =item any other argument
1999    
2000     Any other argument is interpreted as a bundle specification file, which
2001     supports most long options (without extra quoting), one option per line.
2002    
2003     =back
2004    
2005 root 1.18 =head3 EXTENDED GLOB PATTERNS
2006    
2007     Some options of F<staticperl mkbundle> expect an I<extended glob
2008     pattern>. This is neither a normal shell glob nor a regex, but something
2009     in between. The idea has been copied from rsync, and there are the current
2010     matching rules:
2011    
2012     =over 4
2013    
2014     =item Patterns starting with F</> will be a anchored at the root of the library tree.
2015    
2016     That is, F</unicore> will match the F<unicore> directory in C<@INC>, but
2017     nothing inside, and neither any other file or directory called F<unicore>
2018     anywhere else in the hierarchy.
2019    
2020     =item Patterns not starting with F</> will be anchored at the end of the path.
2021    
2022     That is, F<idna.pl> will match any file called F<idna.pl> anywhere in the
2023     hierarchy, but not any directories of the same name.
2024    
2025     =item A F<*> matches any single component.
2026    
2027     That is, F</unicore/*.pl> would match all F<.pl> files directly inside
2028     C</unicore>, not any deeper level F<.pl> files. Or in other words, F<*>
2029     will not match slashes.
2030    
2031     =item A F<**> matches anything.
2032    
2033     That is, F</unicore/**.pl> would match all F<.pl> files under F</unicore>,
2034     no matter how deeply nested they are inside subdirectories.
2035    
2036     =item A F<?> matches a single character within a component.
2037    
2038     That is, F</Encode/??.pm> matches F</Encode/JP.pm>, but not the
2039     hypothetical F</Encode/J/.pm>, as F<?> does not match F</>.
2040    
2041     =back
2042    
2043     =head2 F<STATICPERL> CONFIGURATION AND HOOKS
2044 root 1.2
2045     During (each) startup, F<staticperl> tries to source the following shell
2046     files in order:
2047    
2048     /etc/staticperlrc
2049     ~/.staticperlrc
2050     $STATICPERL/rc
2051    
2052     They can be used to override shell variables, or define functions to be
2053     called at specific phases.
2054    
2055     Note that the last file is erased during F<staticperl distclean>, so
2056     generally should not be used.
2057    
2058     =head3 CONFIGURATION VARIABLES
2059    
2060     =head4 Variables you I<should> override
2061    
2062     =over 4
2063    
2064     =item C<EMAIL>
2065    
2066     The e-mail address of the person who built this binary. Has no good
2067     default, so should be specified by you.
2068    
2069     =item C<CPAN>
2070    
2071     The URL of the CPAN mirror to use (e.g. L<http://mirror.netcologne.de/cpan/>).
2072    
2073 root 1.6 =item C<EXTRA_MODULES>
2074 root 1.2
2075 root 1.6 Additional modules installed during F<staticperl install>. Here you can
2076     set which modules you want have to installed from CPAN.
2077 root 1.2
2078 root 1.10 Example: I really really need EV, AnyEvent, Coro and AnyEvent::AIO.
2079 root 1.2
2080 root 1.10 EXTRA_MODULES="EV AnyEvent Coro AnyEvent::AIO"
2081 root 1.2
2082 root 1.6 Note that you can also use a C<postinstall> hook to achieve this, and
2083     more.
2084 root 1.2
2085 root 1.10 =back
2086    
2087     =head4 Variables you might I<want> to override
2088    
2089     =over 4
2090    
2091     =item C<STATICPERL>
2092    
2093     The directory where staticperl stores all its files
2094     (default: F<~/.staticperl>).
2095    
2096 root 1.6 =item C<PERL_MM_USE_DEFAULT>, C<EV_EXTRA_DEFS>, ...
2097 root 1.2
2098     Usually set to C<1> to make modules "less inquisitive" during their
2099     installation, you can set any environment variable you want - some modules
2100     (such as L<Coro> or L<EV>) use environment variables for further tweaking.
2101    
2102 root 1.10 =item C<PERL_VERSION>
2103 root 1.6
2104 root 1.10 The perl version to install - default is currently C<5.12.2>, but C<5.8.9>
2105     is also a good choice (5.8.9 is much smaller than 5.12.2, while 5.10.1 is
2106     about as big as 5.12.2).
2107 root 1.2
2108 root 1.10 =item C<PERL_PREFIX>
2109 root 1.2
2110 root 1.6 The prefix where perl gets installed (default: F<$STATICPERL/perl>),
2111     i.e. where the F<bin> and F<lib> subdirectories will end up.
2112 root 1.2
2113 root 1.8 =item C<PERL_CONFIGURE>
2114    
2115     Additional Configure options - these are simply passed to the perl
2116     Configure script. For example, if you wanted to enable dynamic loading,
2117     you could pass C<-Dusedl>. To enable ithreads (Why would you want that
2118     insanity? Don't! Use L<forks> instead!) you would pass C<-Duseithreads>
2119     and so on.
2120    
2121     More commonly, you would either activate 64 bit integer support
2122     (C<-Duse64bitint>), or disable large files support (-Uuselargefiles), to
2123     reduce filesize further.
2124    
2125 root 1.6 =item C<PERL_CPPFLAGS>, C<PERL_OPTIMIZE>, C<PERL_LDFLAGS>, C<PERL_LIBS>
2126 root 1.2
2127 root 1.6 These flags are passed to perl's F<Configure> script, and are generally
2128     optimised for small size (at the cost of performance). Since they also
2129     contain subtle workarounds around various build issues, changing these
2130     usually requires understanding their default values - best look at the top
2131     of the F<staticperl> script for more info on these.
2132 root 1.2
2133     =back
2134    
2135 root 1.5 =head4 Variables you probably I<do not want> to override
2136 root 1.2
2137     =over 4
2138    
2139     =item C<MKBUNDLE>
2140    
2141     Where F<staticperl> writes the C<mkbundle> command to
2142     (default: F<$STATICPERL/mkbundle>).
2143 root 1.1
2144 root 1.2 =item C<STATICPERL_MODULES>
2145 root 1.1
2146 root 1.2 Additional modules needed by C<mkbundle> - should therefore not be changed
2147     unless you know what you are doing.
2148    
2149     =back
2150    
2151     =head3 OVERRIDABLE HOOKS
2152    
2153     In addition to environment variables, it is possible to provide some
2154     shell functions that are called at specific times. To provide your own
2155 root 1.4 commands, just define the corresponding function.
2156 root 1.2
2157     Example: install extra modules from CPAN and from some directories
2158     at F<staticperl install> time.
2159    
2160     postinstall() {
2161 root 1.5 rm -rf lib/threads* # weg mit Schaden
2162 root 1.2 instcpan IO::AIO EV
2163     instsrc ~/src/AnyEvent
2164     instsrc ~/src/XML-Sablotron-1.0100001
2165 root 1.5 instcpan Anyevent::AIO AnyEvent::HTTPD
2166 root 1.2 }
2167    
2168     =over 4
2169    
2170 root 1.11 =item preconfigure
2171    
2172     Called just before running F<./Configur> in the perl source
2173     directory. Current working directory is the perl source directory.
2174    
2175     This can be used to set any C<PERL_xxx> variables, which might be costly
2176     to compute.
2177    
2178 root 1.2 =item postconfigure
2179    
2180     Called after configuring, but before building perl. Current working
2181     directory is the perl source directory.
2182    
2183 root 1.11 Could be used to tailor/patch config.sh (followed by F<sh Configure -S>)
2184     or do any other modifications.
2185 root 1.2
2186     =item postbuild
2187    
2188     Called after building, but before installing perl. Current working
2189     directory is the perl source directory.
2190    
2191     I have no clue what this could be used for - tell me.
2192    
2193     =item postinstall
2194    
2195     Called after perl and any extra modules have been installed in C<$PREFIX>,
2196     but before setting the "installation O.K." flag.
2197    
2198     The current working directory is C<$PREFIX>, but maybe you should not rely
2199     on that.
2200    
2201     This hook is most useful to customise the installation, by deleting files,
2202     or installing extra modules using the C<instcpan> or C<instsrc> functions.
2203    
2204     The script must return with a zero exit status, or the installation will
2205     fail.
2206 root 1.1
2207 root 1.2 =back
2208 root 1.1
2209 root 1.7 =head1 ANATOMY OF A BUNDLE
2210    
2211     When not building a new perl binary, C<mkbundle> will leave a number of
2212     files in the current working directory, which can be used to embed a perl
2213     interpreter in your program.
2214    
2215     Intimate knowledge of L<perlembed> and preferably some experience with
2216     embedding perl is highly recommended.
2217    
2218     C<mkperl> (or the C<--perl> option) basically does this to link the new
2219     interpreter (it also adds a main program to F<bundle.>):
2220    
2221     $Config{cc} $(cat bundle.ccopts) -o perl bundle.c $(cat bundle.ldopts)
2222    
2223     =over 4
2224    
2225     =item bundle.h
2226    
2227     A header file that contains the prototypes of the few symbols "exported"
2228     by bundle.c, and also exposes the perl headers to the application.
2229    
2230     =over 4
2231    
2232     =item staticperl_init ()
2233    
2234     Initialises the perl interpreter. You can use the normal perl functions
2235     after calling this function, for example, to define extra functions or
2236     to load a .pm file that contains some initialisation code, or the main
2237     program function:
2238    
2239     XS (xsfunction)
2240     {
2241     dXSARGS;
2242    
2243     // now we have items, ST(i) etc.
2244     }
2245    
2246     static void
2247     run_myapp(void)
2248     {
2249     staticperl_init ();
2250     newXSproto ("myapp::xsfunction", xsfunction, __FILE__, "$$;$");
2251     eval_pv ("require myapp::main", 1); // executes "myapp/main.pm"
2252     }
2253    
2254     =item staticperl_xs_init (pTHX)
2255    
2256     Sometimes you need direct control over C<perl_parse> and C<perl_run>, in
2257     which case you do not want to use C<staticperl_init> but call them on your
2258     own.
2259    
2260     Then you need this function - either pass it directly as the C<xs_init>
2261     function to C<perl_parse>, or call it from your own C<xs_init> function.
2262    
2263     =item staticperl_cleanup ()
2264    
2265     In the unlikely case that you want to destroy the perl interpreter, here
2266     is the corresponding function.
2267    
2268     =item PerlInterpreter *staticperl
2269    
2270     The perl interpreter pointer used by staticperl. Not normally so useful,
2271     but there it is.
2272    
2273     =back
2274    
2275     =item bundle.ccopts
2276    
2277     Contains the compiler options required to compile at least F<bundle.c> and
2278     any file that includes F<bundle.h> - you should probably use it in your
2279     C<CFLAGS>.
2280    
2281     =item bundle.ldopts
2282    
2283     The linker options needed to link the final program.
2284    
2285     =back
2286    
2287     =head1 RUNTIME FUNCTIONALITY
2288    
2289     Binaries created with C<mkbundle>/C<mkperl> contain extra functions, which
2290     are required to access the bundled perl sources, but might be useful for
2291     other purposes.
2292    
2293     In addition, for the embedded loading of perl files to work, F<staticperl>
2294     overrides the C<@INC> array.
2295    
2296     =over 4
2297    
2298     =item $file = staticperl::find $path
2299    
2300     Returns the data associated with the given C<$path>
2301     (e.g. C<Digest/MD5.pm>, C<auto/POSIX/autosplit.ix>), which is basically
2302     the UNIX path relative to the perl library directory.
2303    
2304     Returns C<undef> if the file isn't embedded.
2305    
2306 root 1.8 =item @paths = staticperl::list
2307 root 1.7
2308     Returns the list of all paths embedded in this binary.
2309    
2310     =back
2311    
2312 root 1.8 =head1 FULLY STATIC BINARIES - BUILDROOT
2313    
2314     To make truly static (Linux-) libraries, you might want to have a look at
2315     buildroot (L<http://buildroot.uclibc.org/>).
2316    
2317     Buildroot is primarily meant to set up a cross-compile environment (which
2318     is not so useful as perl doesn't quite like cross compiles), but it can also compile
2319     a chroot environment where you can use F<staticperl>.
2320    
2321     To do so, download buildroot, and enable "Build options => development
2322     files in target filesystem" and optionally "Build options => gcc
2323     optimization level (optimize for size)". At the time of writing, I had
2324     good experiences with GCC 4.4.x but not GCC 4.5.
2325    
2326     To minimise code size, I used C<-pipe -ffunction-sections -fdata-sections
2327     -finline-limit=8 -fno-builtin-strlen -mtune=i386>. The C<-mtune=i386>
2328     doesn't decrease codesize much, but it makes the file much more
2329     compressible.
2330    
2331     If you don't need Coro or threads, you can go with "linuxthreads.old" (or
2332     no thread support). For Coro, it is highly recommended to switch to a
2333     uClibc newer than 0.9.31 (at the time of this writing, I used the 20101201
2334     snapshot) and enable NPTL, otherwise Coro needs to be configured with the
2335     ultra-slow pthreads backend to work around linuxthreads bugs (it also uses
2336     twice the address space needed for stacks).
2337    
2338     If you use C<linuxthreads.old>, then you should also be aware that
2339     uClibc shares C<errno> between all threads when statically linking. See
2340     L<http://lists.uclibc.org/pipermail/uclibc/2010-June/044157.html> for a
2341     workaround (And L<https://bugs.uclibc.org/2089> for discussion).
2342    
2343 root 1.10 C<ccache> support is also recommended, especially if you want
2344     to play around with buildroot options. Enabling the C<miniperl>
2345     package will probably enable all options required for a successful
2346     perl build. F<staticperl> itself additionally needs either C<wget>
2347     (recommended, for CPAN) or C<curl>.
2348 root 1.8
2349     As for shells, busybox should provide all that is needed, but the default
2350     busybox configuration doesn't include F<comm> which is needed by perl -
2351     either make a custom busybox config, or compile coreutils.
2352    
2353     For the latter route, you might find that bash has some bugs that keep
2354     it from working properly in a chroot - either use dash (and link it to
2355     F</bin/sh> inside the chroot) or link busybox to F</bin/sh>, using it's
2356     built-in ash shell.
2357    
2358     Finally, you need F</dev/null> inside the chroot for many scripts to work
2359     - F<cp /dev/null output/target/dev> or bind-mounting your F</dev> will
2360     both provide this.
2361    
2362     After you have compiled and set up your buildroot target, you can copy
2363     F<staticperl> from the C<App::Staticperl> distribution or from your
2364     perl f<bin> directory (if you installed it) into the F<output/target>
2365     filesystem, chroot inside and run it.
2366    
2367 root 1.18 =head1 RECIPES / SPECIFIC MODULES
2368    
2369     This section contains some common(?) recipes and information about
2370     problems with some common modules or perl constructs that require extra
2371     files to be included.
2372    
2373     =head2 MODULES
2374    
2375     =over 4
2376    
2377     =item utf8
2378    
2379     Some functionality in the utf8 module, such as swash handling (used
2380     for unicode character ranges in regexes) is implemented in the
2381     C<"utf8_heavy.pl"> library:
2382    
2383     -M'"utf8_heavy.pl"'
2384    
2385     Many Unicode properties in turn are defined in separate modules,
2386     such as C<"unicore/Heavy.pl"> and more specific data tables such as
2387     C<"unicore/To/Digit.pl"> or C<"unicore/lib/Perl/Word.pl">. These tables
2388     are big (7MB uncompressed, although F<staticperl> contains special
2389     handling for those files), so including them on demand by your application
2390     only might pay off.
2391    
2392     To simply include the whole unicode database, use:
2393    
2394     --incglob '/unicore/*.pl'
2395    
2396     =item AnyEvent
2397    
2398     AnyEvent needs a backend implementation that it will load in a delayed
2399     fashion. The L<AnyEvent::Impl::Perl> backend is the default choice
2400     for AnyEvent if it can't find anything else, and is usually a safe
2401     fallback. If you plan to use e.g. L<EV> (L<POE>...), then you need to
2402     include the L<AnyEvent::Impl::EV> (L<AnyEvent::Impl::POE>...) backend as
2403     well.
2404    
2405     If you want to handle IRIs or IDNs (L<AnyEvent::Util> punycode and idn
2406     functions), you also need to include C<"AnyEvent/Util/idna.pl"> and
2407     C<"AnyEvent/Util/uts46data.pl">.
2408    
2409     =item Carp
2410    
2411     Carp had (in older versions of perl) a dependency on L<Carp::Heavy>. As of
2412     perl 5.12.2 (maybe earlier), this dependency no longer exists.
2413    
2414     =item Config
2415    
2416     The F<perl -V> switch (as well as many modules) needs L<Config>, which in
2417     turn might need L<"Config_heavy.pl">. Including the latter gives you
2418     both.
2419    
2420     =item Term::ReadLine::Perl
2421    
2422     Also needs L<Term::ReadLine::readline>.
2423    
2424     =item URI
2425    
2426     URI implements schemes as separate modules - the generic URL scheme is
2427     implemented in L<URI::_generic>, HTTP is implemented in L<URI::http>. If
2428     you need to use any of these schemes, you should include these manually.
2429    
2430     =back
2431    
2432     =head2 RECIPES
2433    
2434     =over 4
2435    
2436     =item Linking everything in
2437    
2438     To link just about everything installed in the perl library into a new
2439     perl, try this:
2440    
2441     staticperl mkperl --strip ppi --incglob '*'
2442    
2443     =item Getting rid of netdb function
2444    
2445     The perl core has lots of netdb functions (C<getnetbyname>, C<getgrent>
2446     and so on) that few applications use. You can avoid compiling them in by
2447     putting the following fragment into a C<preconfigure> hook:
2448    
2449     preconfigure() {
2450     for sym in \
2451     d_getgrnam_r d_endgrent d_endgrent_r d_endhent \
2452     d_endhostent_r d_endnent d_endnetent_r d_endpent \
2453     d_endprotoent_r d_endpwent d_endpwent_r d_endsent \
2454     d_endservent_r d_getgrent d_getgrent_r d_getgrgid_r \
2455     d_getgrnam_r d_gethbyaddr d_gethent d_getsbyport \
2456     d_gethostbyaddr_r d_gethostbyname_r d_gethostent_r \
2457     d_getlogin_r d_getnbyaddr d_getnbyname d_getnent \
2458     d_getnetbyaddr_r d_getnetbyname_r d_getnetent_r \
2459     d_getpent d_getpbyname d_getpbynumber d_getprotobyname_r \
2460     d_getprotobynumber_r d_getprotoent_r d_getpwent \
2461     d_getpwent_r d_getpwnam_r d_getpwuid_r d_getsent \
2462     d_getservbyname_r d_getservbyport_r d_getservent_r \
2463     d_getspnam_r d_getsbyname
2464     # d_gethbyname
2465     do
2466     PERL_CONFIGURE="$PERL_CONFIGURE -U$sym"
2467     done
2468     }
2469    
2470     This mostly gains space when linking staticaly, as the functions will
2471     liekly not be linked in. The gain for dynamically-linked binaries is
2472     smaller.
2473    
2474     Also, this leaves C<gethostbyname> in - not only is it actually used
2475     often, the L<Socket> module also exposes it, so leaving it out usually
2476     gains little. Why Socket exposes a C function that is in the core already
2477     is anybody's guess.
2478    
2479     =back
2480    
2481 root 1.1 =head1 AUTHOR
2482    
2483     Marc Lehmann <schmorp@schmorp.de>
2484     http://software.schmorp.de/pkg/staticperl.html
2485