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