ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/cvsroot/App-Staticperl/bin/staticperl
Revision: 1.41
Committed: Thu Feb 10 11:46:02 2011 UTC (15 years, 8 months ago) by root
Branch: MAIN
Changes since 1.40: +3 -1 lines
Log Message:
*** empty log message ***

File Contents

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