ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/cvsroot/App-Staticperl/bin/staticperl
Revision: 1.64
Committed: Sun Jun 26 17:26:52 2011 UTC (15 years, 4 months ago) by root
Branch: MAIN
Changes since 1.63: +25 -14 lines
Log Message:
*** empty log message ***

File Contents

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