ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/cvsroot/App-Staticperl/bin/staticperl
Revision: 1.59
Committed: Sun May 1 07:56:26 2011 UTC (15 years, 5 months ago) by root
Branch: MAIN
Changes since 1.58: +5 -4 lines
Log Message:
*** empty log message ***

File Contents

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