ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/App-Staticperl/bin/staticperl
Revision: 1.56
Committed: Fri Mar 18 19:49:04 2011 UTC (15 years, 6 months ago) by root
Branch: MAIN
CVS Tags: rel-1_21
Changes since 1.55: +25 -8 lines
Log Message:
1.21

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