ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/App-Staticperl/bin/staticperl
Revision: 1.54
Committed: Fri Mar 11 17:06:40 2011 UTC (15 years, 6 months ago) by root
Branch: MAIN
Changes since 1.53: +1 -1 lines
Log Message:
*** empty log message ***

File Contents

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