ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/App-Staticperl/bin/staticperl
Revision: 1.57
Committed: Fri Apr 1 05:58:22 2011 UTC (15 years, 5 months ago) by root
Branch: MAIN
Changes since 1.56: +6 -1 lines
Log Message:
*** empty log message ***

File Contents

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