ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/App-Staticperl/bin/staticperl
Revision: 1.61
Committed: Sun May 1 10:03:29 2011 UTC (15 years, 4 months ago) by root
Branch: MAIN
CVS Tags: rel-1_22
Changes since 1.60: +3 -0 lines
Log Message:
1.22

File Contents

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