ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/App-Staticperl/bin/staticperl
Revision: 1.111
Committed: Sat Apr 4 15:26:02 2026 UTC (5 months, 2 weeks ago) by root
Branch: MAIN
CVS Tags: rel-1_5, HEAD
Changes since 1.110: +96 -18 lines
Log Message:
1.5

File Contents

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