ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/App-Staticperl/bin/staticperl
Revision: 1.55
Committed: Sun Mar 13 23:20:21 2011 UTC (15 years, 6 months ago) by root
Branch: MAIN
CVS Tags: rel-1_2
Changes since 1.54: +24 -3 lines
Log Message:
1.2

File Contents

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