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