ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/App-Staticperl/bin/staticperl
Revision: 1.29
Committed: Tue Dec 21 19:14:56 2010 UTC (15 years, 8 months ago) by root
Branch: MAIN
Changes since 1.28: +277 -157 lines
Log Message:
*** empty log message ***

File Contents

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