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