ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/App-Staticperl/bin/staticperl
Revision: 1.12
Committed: Tue Dec 7 19:55:56 2010 UTC (15 years, 9 months ago) by root
Branch: MAIN
Changes since 1.11: +4 -3 lines
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 root 1.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     MKBUNDLE="$STATICPERL/mkbundle"
11    
12     # perl build variables
13 root 1.10 PERL_PREFIX="$STATICPERL/perl" # where the perl gets installed
14     PERL_VERSION=5.12.2 # 5.8.9 is also a good choice
15 root 1.8 PERL_CONFIGURE="" # additional Configure arguments
16 root 1.1 PERL_CPPFLAGS="-DPERL_DISABLE_PMC -DPERL_ARENA_SIZE=65536 -D_GNU_SOURCE -DNDEBUG -USITELIB_EXP -USITEARCHEXP -UARCHLIB_EXP"
17     PERL_OPTIMIZE="-Os -ffunction-sections -fdata-sections -finline-limit=8 -ffast-math"
18    
19     ARCH="$(uname -m)"
20    
21     case "$ARCH" in
22     i*86 | x86_64 | amd64 )
23     PERL_OPTIMIZE="$PERL_OPTIMIZE -mpush-args -mno-inline-stringops-dynamically -mno-align-stringops -mno-ieee-fp" # x86/amd64
24     case "$ARCH" in
25     i*86 )
26     PERL_OPTIMIZE="$PERL_OPTIMIZE -fomit-frame-pointer -march=pentium3 -mtune=i386" # x86 only
27     ;;
28     esac
29     ;;
30     esac
31    
32     # -Wl,--gc-sections makes it impossible to check for undefined references
33     # for some reason so we need to patch away the "-no" after Configure and before make :/
34     # -z muldefs is to work around uclibc's pthread static linking bug
35     PERL_LDFLAGS="-Wl,--no-gc-sections -z muldefs"
36     PERL_LIBS="-lm -lcrypt" # perl loves to add lotsa crap itself
37    
38     # some configuration options for modules
39     export PERL_MM_USE_DEFAULT=1
40     #export CORO_INTERFACE=p # needed without nptl on x86, due to bugs in linuxthreads - very slow
41     export 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'
42    
43     # which extra modules to install by default from CPAN that are
44     # required by mkbundle
45 root 1.2 STATICPERL_MODULES="common::sense Pod::Strip PPI::XS Pod::Usage"
46    
47     # which extra modules you might want to install
48     EXTRA_MODULES=""
49 root 1.1
50     # overridable functions
51 root 1.11 preconfigure() { : ; }
52 root 1.1 postconfigure() { : ; }
53     postbuild() { : ; }
54     postinstall() { : ; }
55    
56     # now source user config, if any
57     [ -r /etc/staticperlrc ] && . /etc/staticperlrc
58     [ -r ~/.staticperlrc ] && . ~/.staticperlrc
59     [ -r "$STATICPERL/rc" ] && . "$STATICPERL/rc"
60    
61     #############################################################################
62     # support
63    
64     # set version in a way that Makefile.PL can extract
65     VERSION=VERSION; eval \
66     $VERSION=0.1
67    
68     BZ2=bz2
69     BZIP2=bzip2
70    
71     fatal() {
72     printf -- "\nFATAL: %s\n\n" "$*" >&2
73     exit 1
74     }
75    
76     verbose() {
77     printf -- "%s\n" "$*"
78     }
79    
80     verblock() {
81     verbose
82     verbose "***"
83     while read line; do
84     verbose "*** $line"
85     done
86     verbose "***"
87     verbose
88     }
89    
90     rcd() {
91     cd "$1" || fatal "$1: cannot enter"
92     }
93    
94     trace() {
95     prefix="$1"; shift
96     # "$@" 2>&1 | while read line; do
97     # echo "$prefix: $line"
98     # done
99     "$@"
100     }
101    
102     trap wait 0
103    
104     #############################################################################
105     # clean
106    
107     distclean() {
108     verblock <<EOF
109     deleting everything installed by this script
110     EOF
111    
112     rm -rf "$STATICPERL"
113     }
114    
115     #############################################################################
116     # download/configure/compile/install perl
117    
118     clean() {
119 root 1.11 rm -rf "$STATICPERL/src/perl-$PERL_VERSION"
120 root 1.1 }
121    
122     fetch() {
123     rcd "$STATICPERL"
124    
125     mkdir -p src
126     rcd src
127    
128 root 1.10 if ! [ -d "perl-$PERL_VERSION" ]; then
129     if ! [ -e "perl-$PERL_VERSION.tar.$BZ2" ]; then
130 root 1.1
131 root 1.10 URL="$CPAN/src/5.0/perl-$PERL_VERSION.tar.$BZ2"
132 root 1.1
133     verblock <<EOF
134     downloading perl
135     to manually download perl yourself, place
136 root 1.10 perl-$PERL_VERSION.tar.$BZ2 in $STATICPERL
137 root 1.1 trying $URL
138     EOF
139    
140 root 1.10 rm -f perl-$PERL_VERSION.tar.$BZ2~ # just to be on the safe side
141     wget -O perl-$PERL_VERSION.tar.$BZ2~ "$URL" \
142     || curl >perl-$PERL_VERSION.tar.$BZ2~ "$URL" \
143     || fatal "$URL: unable to download"
144     mv perl-$PERL_VERSION.tar.$BZ2~ perl-$PERL_VERSION.tar.$BZ2
145 root 1.1 fi
146    
147     verblock <<EOF
148     unpacking perl
149     EOF
150    
151     mkdir -p unpack
152 root 1.12 $BZIP2 -d <perl-$PERL_VERSION.tar.bz2 | tar xC unpack \
153 root 1.10 || fatal "perl-$PERL_VERSION.tar.bz2: error during unpacking"
154 root 1.12 chmod -R u+w unpack/perl-$PERL_VERSION
155 root 1.10 mv unpack/perl-$PERL_VERSION perl-$PERL_VERSION
156 root 1.1 rmdir -p unpack
157     fi
158     }
159    
160     # similar to GNU-sed -i or perl -pi
161     sedreplace() {
162     sed -e "$1" <"$2" > "$2~" || fatal "error while running sed"
163     mv "$2~" "$2"
164     }
165    
166     configure() {
167     fetch
168    
169 root 1.10 rcd "$STATICPERL/src/perl-$PERL_VERSION"
170 root 1.1
171     [ -e staticstamp.configure ] && return
172    
173     verblock <<EOF
174 root 1.10 configuring $STATICPERL/src/perl-$PERL_VERSION
175 root 1.1 EOF
176    
177 root 1.12 rm -f "$PERL_PREFIX/staticstamp.install"
178 root 1.1
179 root 1.12 make distclean >/dev/null 2>&1
180 root 1.1
181     # I hate them
182     grep -q -- -fstack-protector Configure && \
183     sedreplace 's/-fstack-protector/-fno-stack-protector/g' Configure
184    
185 root 1.11 preconfigure
186    
187 root 1.1 # trace configure \
188     sh Configure -Duselargefiles \
189     -Uuse64bitint \
190     -Dusemymalloc=n \
191     -Uusedl \
192     -Uusethreads \
193     -Uuseithreads \
194     -Uusemultiplicity \
195     -Duseperlio \
196     -Uusesfio \
197     -Uuseshrplib \
198     -Dcppflags="$PERL_CPPFLAGS" \
199     -Dccflags="-g2 -fno-strict-aliasing" \
200     -Doptimize="$PERL_OPTIMIZE" \
201     -Dldflags="$PERL_LDFLAGS" \
202     -Dlibs="$PERL_LIBS" \
203 root 1.10 -Dprefix="$PERL_PREFIX" \
204     -Dbin="$PERL_PREFIX/bin" \
205     -Dprivlib="$PERL_PREFIX/lib" \
206     -Darchlib="$PERL_PREFIX/lib" \
207 root 1.1 -Uusevendorprefix \
208 root 1.10 -Dsitelib="$PERL_PREFIX/lib" \
209     -Dsitearch="$PERL_PREFIX/lib" \
210 root 1.1 -Usitelibexp \
211     -Uman1dir \
212     -Uman3dir \
213     -Usiteman1dir \
214     -Usiteman3dir \
215     -Dpager=/usr/bin/less \
216     -Demail="$EMAIL" \
217     -Dcf_email="$EMAIL" \
218     -Dcf_by="$EMAIL" \
219 root 1.8 $PERL_CONFIGURE \
220 root 1.1 -dE || fatal "Configure failed"
221    
222     sedreplace '
223     s/-Wl,--no-gc-sections/-Wl,--gc-sections/g
224     s/ *-fno-stack-protector */ /g
225     ' config.sh
226    
227     sh Configure -S || fatal "Configure -S failed"
228    
229     postconfigure || fatal "postconfigure hook failed"
230    
231     touch staticstamp.configure
232     }
233    
234     build() {
235     configure
236    
237 root 1.10 rcd "$STATICPERL/src/perl-$PERL_VERSION"
238 root 1.1
239     verblock <<EOF
240 root 1.10 building $STATICPERL/src/perl-$PERL_VERSION
241 root 1.1 EOF
242    
243 root 1.10 rm -f "$PERL_PREFIX/staticstamp.install"
244 root 1.1
245     make || fatal "make: error while building perl"
246    
247     postbuild || fatal "postbuild hook failed"
248     }
249    
250     install() {
251 root 1.10 [ -e "$PERL_PREFIX/staticstamp.install" ] && return
252 root 1.1
253     build
254    
255     verblock <<EOF
256 root 1.10 installing $STATICPERL/src/perl-$PERL_VERSION
257     to $PERL_PREFIX
258 root 1.1 EOF
259    
260 root 1.10 rm -rf "$PERL_PREFIX"
261 root 1.1
262     make install || fatal "make install: error while installing"
263    
264 root 1.10 rcd "$PERL_PREFIX"
265 root 1.2
266 root 1.1 # create a "make install" replacement for CPAN
267 root 1.10 cat >"$PERL_PREFIX"/bin/cpan-make-install <<EOF
268 root 1.1 make install UNINST=1
269     if find blib/arch/auto -type f | grep -q -v .exists; then
270     echo Probably an XS module, rebuilding perl
271     make perl
272 root 1.10 rm -f "$PERL_PREFIX"/bin/perl
273 root 1.1 make -f Makefile.aperl inst_perl
274     make -f Makefile.aperl map_clean
275     fi
276     EOF
277 root 1.10 chmod 755 "$PERL_PREFIX"/bin/cpan-make-install
278 root 1.1
279 root 1.4 # trick CPAN into avoiding ~/.cpan completely
280 root 1.10 echo 1 >"$PERL_PREFIX/lib/CPAN/MyConfig.pm"
281 root 1.2
282 root 1.10 "$PERL_PREFIX"/bin/perl -MCPAN -e '
283 root 1.1 CPAN::Shell->o (conf => urllist => push => "'"$CPAN"'");
284 root 1.2 CPAN::Shell->o (conf => q<cpan_home>, "'"$STATICPERL"'/cpan");
285 root 1.1 CPAN::Shell->o (conf => q<init>);
286     CPAN::Shell->o (conf => q<cpan_home>, "'"$STATICPERL"'/cpan");
287     CPAN::Shell->o (conf => q<build_dir>, "'"$STATICPERL"'/cpan/build");
288     CPAN::Shell->o (conf => q<prefs_dir>, "'"$STATICPERL"'/cpan/prefs");
289     CPAN::Shell->o (conf => q<histfile> , "'"$STATICPERL"'/cpan/histfile");
290     CPAN::Shell->o (conf => q<keep_source_where>, "'"$STATICPERL"'/cpan/sources");
291 root 1.10 CPAN::Shell->o (conf => q<make_install_make_command>, "'"$PERL_PREFIX"'/bin/cpan-make-install");
292 root 1.1 CPAN::Shell->o (conf => q<prerequisites_policy>, q<follow>);
293     CPAN::Shell->o (conf => q<build_requires_install_policy>, q<no>);
294     CPAN::Shell->o (conf => q<commit>);
295     ' || fatal "error while initialising CPAN"
296    
297     NOCHECK_INSTALL=+
298 root 1.2 instcpan $STATICPERL_MODULES
299     [ $EXTRA_MODULES ] && instcpan $EXTRA_MODULES
300 root 1.1
301     postinstall || fatal "postinstall hook failed"
302    
303 root 1.10 touch "$PERL_PREFIX/staticstamp.install"
304 root 1.1 }
305    
306     #############################################################################
307     # install a module from CPAN
308    
309     instcpan() {
310     [ $NOCHECK_INSTALL ] || install
311    
312     verblock <<EOF
313     installing modules from CPAN
314     $@
315     EOF
316    
317     for mod in "$@"; do
318 root 1.10 "$PERL_PREFIX"/bin/perl -MCPAN -e 'notest install => "'"$mod"'"' \
319 root 1.1 || fatal "$mod: unable to install from CPAN"
320     done
321     rm -rf "$STATICPERL/build"
322     }
323    
324     #############################################################################
325     # install a module from unpacked sources
326    
327     instsrc() {
328     [ $NOCHECK_INSTALL ] || install
329    
330     verblock <<EOF
331     installing modules from source
332     $@
333     EOF
334    
335     for mod in "$@"; do
336     echo
337     echo $mod
338     (
339     rcd $mod
340     make -f Makefile.aperl map_clean >/dev/null 2>&1
341     make distclean >/dev/null 2>&1
342 root 1.10 "$PERL_PREFIX"/bin/perl Makefile.PL || fatal "$mod: error running Makefile.PL"
343 root 1.1 make || fatal "$mod: error building module"
344 root 1.10 "$PERL_PREFIX"/bin/cpan-make-install || fatal "$mod: error installing module"
345 root 1.1 make distclean >/dev/null 2>&1
346     exit 0
347     ) || exit $?
348     done
349     }
350    
351     #############################################################################
352     # main
353    
354     podusage() {
355     echo
356 root 1.10 if [ -e "$PERL_PREFIX/bin/perl" ]; then
357     "$PERL_PREFIX/bin/perl" -MPod::Usage -e \
358 root 1.1 'pod2usage -input => *STDIN, -output => *STDOUT, -verbose => '$1', -exitval => 0, -noperldoc => 1' <"$0" \
359     2>/dev/null && exit
360     fi
361     # try whatever perl we can find
362     perl -MPod::Usage -e \
363     'pod2usage -input => *STDIN, -output => *STDOUT, -verbose => '$1', -exitval => 0, -noperldoc => 1' <"$0" \
364     2>/dev/null && exit
365    
366     fatal "displaying documentation requires a working perl - try '$0 install' first"
367     }
368    
369     usage() {
370     podusage 0
371     }
372    
373     catmkbundle() {
374     {
375     read dummy
376 root 1.10 echo "#!$PERL_PREFIX/bin/perl"
377 root 1.1 cat
378     } <<'MKBUNDLE'
379     #!/opt/bin/perl
380    
381     #############################################################################
382     # cannot load modules till after the tracer BEGIN block
383    
384     our $VERBOSE = 1;
385     our $STRIP = "pod"; # none, pod or ppi
386     our $PERL = 0;
387     our $VERIFY = 0;
388     our $STATIC = 0;
389    
390     my $PREFIX = "bundle";
391     my $PACKAGE = "static";
392    
393     my %pm;
394 root 1.8 my %pmbin;
395 root 1.1 my @libs;
396     my @static_ext;
397     my $extralibs;
398    
399     @ARGV
400     or die "$0: use 'staticperl help' (or read the sources of staticperl)\n";
401    
402     $|=1;
403    
404     our ($TRACER_W, $TRACER_R);
405    
406     sub find_inc($) {
407     for (@INC) {
408     next if ref;
409     return $_ if -e "$_/$_[0]";
410     }
411    
412     undef
413     }
414    
415     BEGIN {
416     # create a loader process to detect @INC requests before we load any modules
417     my ($W_TRACER, $R_TRACER); # used by tracer
418    
419     pipe $R_TRACER, $TRACER_W or die "pipe: $!";
420     pipe $TRACER_R, $W_TRACER or die "pipe: $!";
421    
422     unless (fork) {
423     close $TRACER_R;
424     close $TRACER_W;
425    
426     unshift @INC, sub {
427     my $dir = find_inc $_[1]
428     or return;
429    
430     syswrite $W_TRACER, "-\n$dir\n$_[1]\n";
431    
432     open my $fh, "<:perlio", "$dir/$_[1]"
433     or warn "ERROR: $dir/$_[1]: $!\n";
434    
435     $fh
436     };
437    
438     while (<$R_TRACER>) {
439     if (/use (.*)$/) {
440     my $mod = $1;
441     eval "require $mod";
442     warn "ERROR: $@ (while loading '$mod')\n"
443     if $@;
444     syswrite $W_TRACER, "\n";
445     } elsif (/eval (.*)$/) {
446     my $eval = $1;
447     eval $eval;
448     warn "ERROR: $@ (in '$eval')\n"
449     if $@;
450     }
451     }
452    
453     exit 0;
454     }
455     }
456    
457     # module loading is now safe
458     use Config;
459    
460 root 1.7 sub scan_al {
461     my ($auto, $autodir, $ix) = @_;
462    
463     $pm{"$auto/$ix"} = "$autodir/$ix";
464    
465 root 1.8 open my $fh, "<:perlio", "$autodir/$ix"
466 root 1.7 or die "$autodir/$ix: $!";
467    
468     my $package;
469    
470     while (<$fh>) {
471     if (/^\s*sub\s+([^[:space:];]+)\s*;?\s*$/) {
472     my $al = "auto/$package/$1.al";
473     my $inc = find_inc $al;
474    
475     defined $inc or die "$al: autoload file not found, but should be there.\n";
476    
477     $pm{$al} = "$inc/$al";
478    
479     } elsif (/^\s*package\s+([^[:space:];]+)\s*;?\s*$/) {
480     ($package = $1) =~ s/::/\//g;
481     } elsif (/^\s*(?:#|1?\s*;?\s*$)/) {
482     # nop
483     } else {
484     warn "$autodir/$ix: unparsable line, please report: $_";
485     }
486     }
487     }
488    
489 root 1.1 sub trace_module {
490     syswrite $TRACER_W, "use $_[0]\n";
491    
492     for (;;) {
493     <$TRACER_R> =~ /^-$/ or last;
494     my $dir = <$TRACER_R>; chomp $dir;
495     my $name = <$TRACER_R>; chomp $name;
496    
497     $pm{$name} = "$dir/$name";
498    
499     if ($name =~ /^(.*)\.pm$/) {
500     my $auto = "auto/$1";
501     my $autodir = "$dir/$auto";
502    
503     if (-d $autodir) {
504     opendir my $dir, $autodir
505     or die "$autodir: $!\n";
506    
507     for (readdir $dir) {
508     # AutoLoader
509 root 1.7 scan_al $auto, $autodir, $_
510     if /\.ix$/;
511 root 1.1
512     # static ext
513     if (/\Q$Config{_a}\E$/o) {
514     push @libs, "$autodir/$_";
515     push @static_ext, $name;
516     }
517    
518     # extralibs.ld
519     if ($_ eq "extralibs.ld") {
520     open my $fh, "<:perlio", "$autodir/$_"
521     or die "$autodir/$_";
522    
523     local $/;
524     $extralibs .= " " . <$fh>;
525     }
526    
527     # dynamic object
528     warn "WARNING: found shared object - can't link statically ($_)\n"
529     if /\.\Q$Config{dlext}\E$/o;
530     }
531     }
532     }
533     }
534     }
535    
536     sub trace_eval {
537     syswrite $TRACER_W, "eval $_[0]\n";
538     }
539    
540     sub trace_finish {
541     close $TRACER_W;
542     close $TRACER_R;
543     }
544    
545     #############################################################################
546     # now we can use modules
547    
548     use common::sense;
549     use Digest::MD5;
550    
551     sub dump_string {
552     my ($fh, $data) = @_;
553    
554     if (length $data) {
555     for (
556     my $ofs = 0;
557     length (my $substr = substr $data, $ofs, 80);
558     $ofs += 80
559     ) {
560     $substr =~ s/([^\x20-\x21\x23-\x5b\x5d-\x7e])/sprintf "\\%03o", ord $1/ge;
561     $substr =~ s/\?/\\?/g; # trigraphs...
562     print $fh " \"$substr\"\n";
563     }
564     } else {
565     print $fh " \"\"\n";
566     }
567     }
568    
569     # required for @INC loading, unfortunately
570     trace_module "PerlIO::scalar";
571    
572     #trace_module "Term::ReadLine::readline"; # Term::ReadLine::Perl dependency
573     # URI is difficult
574     #trace_module "URI::http";
575     #trace_module "URI::_generic";
576    
577     sub cmd_boot {
578     $pm{"//boot"} = $_[0];
579     }
580    
581     sub cmd_add {
582 root 1.3 $_[0] =~ /^(.*)(?:\s+(\S+))$/
583 root 1.1 or die "$_[0]: cannot parse";
584    
585     my $file = $1;
586     my $as = defined $2 ? $2 : "/$1";
587    
588     $pm{$as} = $file;
589 root 1.8 $pmbin{$as} = 1 if $_[1];
590 root 1.1 }
591    
592     sub cmd_file {
593     open my $fh, "<", $_[0]
594     or die "$_[0]: $!\n";
595    
596     while (<$fh>) {
597     chomp;
598     my ($cmd, $args) = split / /, $_, 2;
599 root 1.2 $cmd =~ s/^-+//;
600 root 1.1
601     if ($cmd eq "strip") {
602     $STRIP = $args;
603     } elsif ($cmd eq "eval") {
604     trace_eval $_;
605     } elsif ($cmd eq "use") {
606     trace_module $_
607     for split / /, $args;
608     } elsif ($cmd eq "boot") {
609     cmd_boot $args;
610     } elsif ($cmd eq "static") {
611     $STATIC = 1;
612     } elsif ($cmd eq "add") {
613 root 1.8 cmd_add $args, 0;
614     } elsif ($cmd eq "addbin") {
615     cmd_add $args, 1;
616 root 1.1 } elsif (/^\s*#/) {
617     # comment
618     } elsif (/\S/) {
619     die "$_: unsupported directive\n";
620     }
621     }
622     }
623    
624     use Getopt::Long;
625    
626     Getopt::Long::Configure ("bundling", "no_auto_abbrev", "no_ignore_case");
627    
628     GetOptions
629     "strip=s" => \$STRIP,
630     "verbose|v" => sub { ++$VERBOSE },
631     "quiet|q" => sub { --$VERBOSE },
632     "perl" => \$PERL,
633 root 1.2 "eval|e=s" => sub { trace_eval $_[1] },
634 root 1.1 "use|M=s" => sub { trace_module $_[1] },
635     "boot=s" => sub { cmd_boot $_[1] },
636 root 1.8 "add=s" => sub { cmd_add $_[1], 0 },
637     "addbin=s" => sub { cmd_add $_[1], 1 },
638 root 1.1 "static" => sub { $STATIC = 1 },
639 root 1.4 "<>" => sub { cmd_file $_[0] },
640 root 1.1 or exit 1;
641    
642     my $data;
643     my @index;
644     my @order = sort {
645     length $a <=> length $b
646     or $a cmp $b
647     } keys %pm;
648    
649     # sorting by name - better compression, but needs more metadata
650     # sorting by length - faster lookup
651     # usually, the metadata overhead beats the loss through compression
652    
653     for my $pm (@order) {
654     my $path = $pm{$pm};
655    
656     128 > length $pm
657     or die "$pm: path too long (only 128 octets supported)\n";
658    
659     my $src = ref $path
660     ? $$path
661     : do {
662 root 1.7 open my $pm, "<", $path
663 root 1.1 or die "$path: $!";
664    
665     local $/;
666    
667     <$pm>
668     };
669    
670 root 1.8 unless ($pmbin{$pm}) { # only do this unless the file is binary
671    
672     if ($pm =~ /^auto\/POSIX\/[^\/]+\.al$/) {
673     if ($src =~ /^ unimpl \"/m) {
674     warn "$pm: skipping (not implemented anyways).\n"
675     if $VERBOSE >= 2;
676     next;
677     }
678 root 1.1 }
679    
680 root 1.8 if ($STRIP =~ /ppi/i) {
681     require PPI;
682 root 1.1
683 root 1.8 my $ppi = PPI::Document->new (\$src);
684     $ppi->prune ("PPI::Token::Comment");
685     $ppi->prune ("PPI::Token::Pod");
686    
687     # prune END stuff
688     for (my $last = $ppi->last_element; $last; ) {
689     my $prev = $last->previous_token;
690    
691     if ($last->isa (PPI::Token::Whitespace::)) {
692     $last->delete;
693     } elsif ($last->isa (PPI::Statement::End::)) {
694     $last->delete;
695     last;
696     } elsif ($last->isa (PPI::Token::Pod::)) {
697     $last->delete;
698     } else {
699     last;
700     }
701    
702     $last = $prev;
703 root 1.1 }
704    
705 root 1.8 # prune some but not all insignificant whitespace
706     for my $ws (@{ $ppi->find (PPI::Token::Whitespace::) }) {
707     my $prev = $ws->previous_token;
708     my $next = $ws->next_token;
709 root 1.1
710 root 1.8 if (!$prev || !$next) {
711 root 1.1 $ws->delete;
712     } else {
713 root 1.8 if (
714     $next->isa (PPI::Token::Operator::) && $next->{content} =~ /^(?:,|=|!|!=|==|=>)$/ # no ., because of digits. == float
715     or $prev->isa (PPI::Token::Operator::) && $prev->{content} =~ /^(?:,|=|\.|!|!=|==|=>)$/
716     or $prev->isa (PPI::Token::Structure::)
717     # decrease size, decrease compressability
718     #or ($prev->isa (PPI::Token::Word::)
719     # && (PPI::Token::Symbol:: eq ref $next
720     # || $next->isa (PPI::Structure::Block::)
721     # || $next->isa (PPI::Structure::List::)
722     # || $next->isa (PPI::Structure::Condition::)))
723     ) {
724     $ws->delete;
725     } elsif ($prev->isa (PPI::Token::Whitespace::)) {
726     $ws->{content} = ' ';
727     $prev->delete;
728     } else {
729     $ws->{content} = ' ';
730     }
731 root 1.1 }
732     }
733    
734 root 1.8 # prune whitespace around blocks
735     if (0) {
736     # these usually decrease size, but decrease compressability more
737     for my $struct (PPI::Structure::Block::, PPI::Structure::Condition::) {
738     for my $node (@{ $ppi->find ($struct) }) {
739     my $n1 = $node->first_token;
740     my $n2 = $n1->previous_token;
741     $n1->delete if $n1->isa (PPI::Token::Whitespace::);
742     $n2->delete if $n2 && $n2->isa (PPI::Token::Whitespace::);
743     my $n1 = $node->last_token;
744     my $n2 = $n1->next_token;
745     $n1->delete if $n1->isa (PPI::Token::Whitespace::);
746     $n2->delete if $n2 && $n2->isa (PPI::Token::Whitespace::);
747     }
748     }
749    
750     for my $node (@{ $ppi->find (PPI::Structure::List::) }) {
751 root 1.1 my $n1 = $node->first_token;
752     $n1->delete if $n1->isa (PPI::Token::Whitespace::);
753     my $n1 = $node->last_token;
754     $n1->delete if $n1->isa (PPI::Token::Whitespace::);
755     }
756     }
757    
758 root 1.8 # reformat qw() lists which often have lots of whitespace
759     for my $node (@{ $ppi->find (PPI::Token::QuoteLike::Words::) }) {
760     if ($node->{content} =~ /^qw(.)(.*)(.)$/s) {
761     my ($a, $qw, $b) = ($1, $2, $3);
762     $qw =~ s/^\s+//;
763     $qw =~ s/\s+$//;
764     $qw =~ s/\s+/ /g;
765     $node->{content} = "qw$a$qw$b";
766     }
767 root 1.1 }
768 root 1.8
769     $src = $ppi->serialize;
770     } elsif ($STRIP =~ /pod/i && $pm ne "Opcode.pm") { # opcode parses it's own pod
771     require Pod::Strip;
772    
773     my $stripper = Pod::Strip->new;
774    
775     my $out;
776     $stripper->output_string (\$out);
777     $stripper->parse_string_document ($src)
778     or die;
779     $src = $out;
780 root 1.1 }
781    
782 root 1.8 if ($VERIFY && $pm =~ /\.pm$/ && $pm ne "Opcode.pm") {
783     if (open my $fh, "-|") {
784     <$fh>;
785     } else {
786     eval "#line 1 \"$pm\"\n$src" or warn "\n\n\n$pm\n\n$src\n$@\n\n\n";
787     exit 0;
788 root 1.1 }
789     }
790    
791 root 1.8 # if ($pm eq "Opcode.pm") {
792     # open my $fh, ">x" or die; print $fh $src;#d#
793     # exit 1;
794     # }
795 root 1.1 }
796    
797     warn "adding $pm\n"
798     if $VERBOSE >= 2;
799    
800     push @index, ((length $pm) << 25) | length $data;
801     $data .= $pm . $src;
802     }
803    
804     length $data < 2**25
805     or die "bundle too large (only 32MB supported)\n";
806    
807     my $varpfx = "bundle_" . substr +(Digest::MD5::md5_hex $data), 0, 16;
808    
809     #############################################################################
810     # output
811    
812     print "generating $PREFIX.h... ";
813    
814     {
815     open my $fh, ">", "$PREFIX.h"
816     or die "$PREFIX.h: $!\n";
817    
818     print $fh <<EOF;
819     /* do not edit, automatically created by mkstaticbundle */
820 root 1.8
821 root 1.1 #include <EXTERN.h>
822     #include <perl.h>
823     #include <XSUB.h>
824    
825     /* public API */
826     EXTERN_C PerlInterpreter *staticperl;
827 root 1.7 EXTERN_C void staticperl_xs_init (pTHX);
828 root 1.1 EXTERN_C void staticperl_init (void);
829     EXTERN_C void staticperl_cleanup (void);
830 root 1.8
831 root 1.1 EOF
832     }
833    
834     print "\n";
835    
836     #############################################################################
837     # output
838    
839     print "generating $PREFIX.c... ";
840    
841     open my $fh, ">", "$PREFIX.c"
842     or die "$PREFIX.c: $!\n";
843    
844     print $fh <<EOF;
845     /* do not edit, automatically created by mkstaticbundle */
846    
847     #include "bundle.h"
848    
849     /* public API */
850     PerlInterpreter *staticperl;
851    
852     EOF
853    
854     #############################################################################
855     # bundle data
856    
857     my $count = @index;
858    
859     print $fh <<EOF;
860     #include "bundle.h"
861    
862     /* bundle data */
863    
864     static const U32 $varpfx\_count = $count;
865     static const U32 $varpfx\_index [$count + 1] = {
866     EOF
867    
868     my $col;
869     for (@index) {
870     printf $fh "0x%08x,", $_;
871     print $fh "\n" unless ++$col % 10;
872    
873     }
874     printf $fh "0x%08x\n};\n", (length $data);
875    
876     print $fh "static const char $varpfx\_data [] =\n";
877     dump_string $fh, $data;
878    
879     print $fh ";\n\n";;
880    
881     #############################################################################
882     # bootstrap
883    
884     # boot file for staticperl
885     # this file will be eval'ed at initialisation time
886    
887     my $bootstrap = '
888     BEGIN {
889     package ' . $PACKAGE . ';
890    
891     PerlIO::scalar->bootstrap;
892    
893     @INC = sub {
894     my $data = find "$_[1]"
895     or return;
896    
897     $INC{$_[1]} = $_[1];
898    
899     open my $fh, "<", \$data;
900     $fh
901     };
902     }
903     ';
904    
905     $bootstrap .= "require '//boot';"
906     if exists $pm{"//boot"};
907    
908     $bootstrap =~ s/\s+/ /g;
909     $bootstrap =~ s/(\W) /$1/g;
910     $bootstrap =~ s/ (\W)/$1/g;
911    
912     print $fh "const char bootstrap [] = ";
913     dump_string $fh, $bootstrap;
914     print $fh ";\n\n";
915    
916     print $fh <<EOF;
917     /* search all bundles for the given file, using binary search */
918     XS(find)
919     {
920     dXSARGS;
921    
922     if (items != 1)
923     Perl_croak (aTHX_ "Usage: $PACKAGE\::find (\$path)");
924    
925     {
926     STRLEN namelen;
927     char *name = SvPV (ST (0), namelen);
928     SV *res = 0;
929    
930     int l = 0, r = $varpfx\_count;
931    
932     while (l <= r)
933     {
934     int m = (l + r) >> 1;
935     U32 idx = $varpfx\_index [m];
936     int comp = namelen - (idx >> 25);
937    
938     if (!comp)
939     {
940     int ofs = idx & 0x1FFFFFFU;
941     comp = memcmp (name, $varpfx\_data + ofs, namelen);
942    
943     if (!comp)
944     {
945     /* found */
946     int ofs2 = $varpfx\_index [m + 1] & 0x1FFFFFFU;
947    
948     ofs += namelen;
949     res = newSVpvn ($varpfx\_data + ofs, ofs2 - ofs);
950     goto found;
951     }
952     }
953    
954     if (comp < 0)
955     r = m - 1;
956     else
957     l = m + 1;
958     }
959    
960     XSRETURN (0);
961    
962     found:
963     ST (0) = res;
964     sv_2mortal (ST (0));
965     }
966    
967     XSRETURN (1);
968     }
969    
970     /* list all files in the bundle */
971     XS(list)
972     {
973     dXSARGS;
974    
975     if (items != 0)
976     Perl_croak (aTHX_ "Usage: $PACKAGE\::list");
977    
978     {
979     int i;
980    
981     EXTEND (SP, $varpfx\_count);
982    
983     for (i = 0; i < $varpfx\_count; ++i)
984     {
985     U32 idx = $varpfx\_index [i];
986    
987     PUSHs (newSVpvn ($varpfx\_data + (idx & 0x1FFFFFFU), idx >> 25));
988     }
989     }
990    
991     XSRETURN ($varpfx\_count);
992     }
993    
994     static char *args[] = {
995     "staticperl",
996     "-e",
997     "0"
998     };
999    
1000     EOF
1001    
1002     #############################################################################
1003     # xs_init
1004    
1005     print $fh <<EOF;
1006 root 1.7 void
1007     staticperl_xs_init (pTHX)
1008 root 1.1 {
1009     EOF
1010    
1011     @static_ext = ("DynaLoader", sort @static_ext);
1012    
1013     # prototypes
1014     for (@static_ext) {
1015     s/\.pm$//;
1016     (my $cname = $_) =~ s/\//__/g;
1017     print $fh " EXTERN_C void boot_$cname (pTHX_ CV* cv);\n";
1018     }
1019    
1020     print $fh <<EOF;
1021     char *file = __FILE__;
1022     dXSUB_SYS;
1023    
1024     newXSproto ("$PACKAGE\::find", find, file, "\$");
1025     newXSproto ("$PACKAGE\::list", list, file, "");
1026     EOF
1027    
1028     # calls
1029     for (@static_ext) {
1030     s/\.pm$//;
1031    
1032     (my $cname = $_) =~ s/\//__/g;
1033     (my $pname = $_) =~ s/\//::/g;
1034    
1035     my $bootstrap = $pname eq "DynaLoader" ? "boot" : "bootstrap";
1036    
1037     print $fh " newXS (\"$pname\::$bootstrap\", boot_$cname, file);\n";
1038     }
1039    
1040     print $fh <<EOF;
1041     Perl_av_create_and_unshift_one (&PL_preambleav, newSVpv (bootstrap, sizeof (bootstrap) - 1));
1042     }
1043     EOF
1044    
1045     #############################################################################
1046     # optional perl_init/perl_destroy
1047    
1048     if ($PERL) {
1049     print $fh <<EOF;
1050    
1051     int
1052     main (int argc, char *argv [])
1053     {
1054     extern char **environ;
1055     int exitstatus;
1056    
1057     PERL_SYS_INIT3 (&argc, &argv, &environ);
1058     staticperl = perl_alloc ();
1059     perl_construct (staticperl);
1060    
1061     PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
1062    
1063 root 1.7 exitstatus = perl_parse (staticperl, staticperl_xs_init, argc, argv, environ);
1064 root 1.1 if (!exitstatus)
1065     perl_run (staticperl);
1066    
1067     exitstatus = perl_destruct (staticperl);
1068     perl_free (staticperl);
1069     PERL_SYS_TERM ();
1070    
1071     return exitstatus;
1072     }
1073     EOF
1074     } else {
1075     print $fh <<EOF;
1076    
1077     EXTERN_C void
1078     staticperl_init (void)
1079     {
1080     extern char **environ;
1081     int argc = sizeof (args) / sizeof (args [0]);
1082     char **argv = args;
1083    
1084     PERL_SYS_INIT3 (&argc, &argv, &environ);
1085     staticperl = perl_alloc ();
1086     perl_construct (staticperl);
1087     PL_origalen = 1;
1088     PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
1089 root 1.7 perl_parse (staticperl, staticperl_xs_init, argc, argv, environ);
1090 root 1.1
1091     perl_run (staticperl);
1092     }
1093    
1094     EXTERN_C void
1095     staticperl_cleanup (void)
1096     {
1097     perl_destruct (staticperl);
1098     perl_free (staticperl);
1099     staticperl = 0;
1100     PERL_SYS_TERM ();
1101     }
1102     EOF
1103     }
1104    
1105     print -s "$PREFIX.c", " octets (", (length $data) , " data octets).\n\n";
1106    
1107     #############################################################################
1108     # libs, cflags
1109    
1110     {
1111     print "generating $PREFIX.ccopts... ";
1112    
1113     my $str = "$Config{ccflags} $Config{optimize} $Config{cppflags} -I$Config{archlibexp}/CORE";
1114     $str =~ s/([\(\)])/\\$1/g;
1115    
1116     print "$str\n\n";
1117    
1118     open my $fh, ">$PREFIX.ccopts"
1119     or die "$PREFIX.ccopts: $!";
1120     print $fh $str;
1121     }
1122    
1123     {
1124     print "generating $PREFIX.ldopts... ";
1125    
1126     my $str = $STATIC ? "--static " : "";
1127    
1128     $str .= "$Config{ccdlflags} $Config{ldflags} @libs $Config{archlibexp}/CORE/$Config{libperl} $Config{perllibs}";
1129    
1130     my %seen;
1131     $str .= " $_" for grep !$seen{$_}++, ($extralibs =~ /(\S+)/g);
1132    
1133     $str =~ s/([\(\)])/\\$1/g;
1134    
1135     print "$str\n\n";
1136    
1137     open my $fh, ">$PREFIX.ldopts"
1138     or die "$PREFIX.ldopts: $!";
1139     print $fh $str;
1140     }
1141    
1142     if ($PERL) {
1143     system "$Config{cc} \$(cat bundle.ccopts\) -o perl bundle.c \$(cat bundle.ldopts\)";
1144    
1145     unlink "$PREFIX.$_"
1146     for qw(ccopts ldopts c h);
1147     }
1148    
1149     MKBUNDLE
1150     }
1151    
1152     bundle() {
1153     catmkbundle >"$MKBUNDLE~" || fatal "$MKBUNDLE~: cannot create"
1154     chmod 755 "$MKBUNDLE~" && mv "$MKBUNDLE~" "$MKBUNDLE"
1155 root 1.10 "$PERL_PREFIX/bin/perl" -- "$MKBUNDLE" "$@"
1156 root 1.1 }
1157    
1158     if [ $# -gt 0 ]; then
1159     while [ $# -gt 0 ]; do
1160     mkdir -p "$STATICPERL" || fatal "$STATICPERL: cannot create"
1161 root 1.10 mkdir -p "$PERL_PREFIX" || fatal "$PERL_PREFIX: cannot create"
1162 root 1.1
1163     command="${1#--}"; shift
1164     case "$command" in
1165     fetch | configure | build | install | clean | distclean)
1166     verblock <<EOF
1167     $command
1168     EOF
1169 root 1.10 ( "$command" )
1170 root 1.1 ;;
1171     instsrc )
1172 root 1.10 ( instsrc "$@" )
1173 root 1.1 exit
1174     ;;
1175     instcpan )
1176 root 1.10 ( instcpan "$@" )
1177 root 1.1 exit
1178     ;;
1179     cpan )
1180 root 1.10 ( install )
1181     "$PERL_PREFIX/bin/cpan" "$@"
1182 root 1.1 exit
1183     ;;
1184     mkbundle )
1185 root 1.10 ( install )
1186 root 1.1 bundle "$@"
1187     exit
1188     ;;
1189     mkperl )
1190 root 1.10 ( install )
1191 root 1.1 bundle --perl "$@"
1192     exit
1193     ;;
1194     help )
1195     podusage 2
1196     ;;
1197     * )
1198     exec 1>&2
1199     echo
1200     echo "Unknown command: $command"
1201     podusage 0
1202     ;;
1203     esac
1204     done
1205     else
1206     usage
1207     fi
1208    
1209     exit 0
1210    
1211     =head1 NAME
1212    
1213 root 1.7 staticperl - perl, libc, 100 modules, all in one 500kb file
1214 root 1.1
1215     =head1 SYNOPSIS
1216    
1217     staticperl help # print the embedded documentation
1218     staticperl fetch # fetch and unpack perl sources
1219     staticperl configure # fetch and then configure perl
1220     staticperl build # configure and then build perl
1221     staticperl install # build and then install perl
1222     staticperl clean # clean most intermediate files (restart at configure)
1223     staticperl distclean # delete everything installed by this script
1224     staticperl cpan # invoke CPAN shell
1225     staticperl instmod path... # install unpacked modules
1226     staticperl instcpan modulename... # install modules from CPAN
1227     staticperl mkbundle <bundle-args...> # see documentation
1228     staticperl mkperl <bundle-args...> # see documentation
1229    
1230     Typical Examples:
1231    
1232     staticperl install # fetch, configure, build and install perl
1233     staticperl cpan # run interactive cpan shell
1234     staticperl mkperl -M '"Config_heavy.pl"' # build a perl that supports -V
1235     staticperl mkperl -MAnyEvent::Impl::Perl -MAnyEvent::HTTPD -MURI -MURI::http
1236     # build a perl with the above modules linked in
1237    
1238     =head1 DESCRIPTION
1239    
1240     This script helps you creating single-file perl interpreters, or embedding
1241 root 1.4 a perl interpreter in your applications. Single-file means that it is
1242     fully self-contained - no separate shared objects, no autoload fragments,
1243     no .pm or .pl files are needed. And when linking statically, you can
1244     create (or embed) a single file that contains perl interpreter, libc, all
1245     the modules you need and all the libraries you need.
1246 root 1.1
1247 root 1.7 With F<uClibc> and F<upx> on x86, you can create a single 500kb binary
1248     that contains perl and 100 modules such as POSIX, AnyEvent, EV, IO::AIO,
1249     Coro and so on. Or any other choice of modules.
1250 root 1.1
1251 root 1.4 The created files do not need write access to the file system (like PAR
1252 root 1.1 does). In fact, since this script is in many ways similar to PAR::Packer,
1253     here are the differences:
1254    
1255     =over 4
1256    
1257     =item * The generated executables are much smaller than PAR created ones.
1258    
1259     Shared objects and the perl binary contain a lot of extra info, while
1260     the static nature of F<staticperl> allows the linker to remove all
1261     functionality and meta-info not required by the final executable. Even
1262     extensions statically compiled into perl at build time will only be
1263     present in the final executable when needed.
1264    
1265     In addition, F<staticperl> can strip perl sources much more effectively
1266     than PAR.
1267    
1268     =item * The generated executables start much faster.
1269    
1270     There is no need to unpack files, or even to parse Zip archives (which is
1271     slow and memory-consuming business).
1272    
1273     =item * The generated executables don't need a writable filesystem.
1274    
1275     F<staticperl> loads all required files directly from memory. There is no
1276     need to unpack files into a temporary directory.
1277    
1278     =item * More control over included files.
1279    
1280 root 1.4 PAR tries to be maintenance and hassle-free - it tries to include more
1281     files than necessary to make sure everything works out of the box. The
1282     extra files (such as the unicode database) can take substantial amounts of
1283     memory and file size.
1284 root 1.1
1285     With F<staticperl>, the burden is mostly with the developer - only direct
1286     compile-time dependencies and L<AutoLoader> are handled automatically.
1287     This means the modules to include often need to be tweaked manually.
1288    
1289     =item * PAR works out of the box, F<staticperl> does not.
1290    
1291     Maintaining your own custom perl build can be a pain in the ass, and while
1292     F<staticperl> tries to make this easy, it still requires a custom perl
1293     build and possibly fiddling with some modules. PAR is likely to produce
1294     results faster.
1295    
1296     =back
1297    
1298     =head1 HOW DOES IT WORK?
1299    
1300     Simple: F<staticperl> downloads, compile and installs a perl version of
1301     your choice in F<~/.staticperl>. You can add extra modules either by
1302     letting F<staticperl> install them for you automatically, or by using CPAN
1303     and doing it interactively. This usually takes 5-10 minutes, depending on
1304 root 1.4 the speed of your computer and your internet connection.
1305 root 1.1
1306     It is possible to do program development at this stage, too.
1307    
1308     Afterwards, you create a list of files and modules you want to include,
1309 root 1.4 and then either build a new perl binary (that acts just like a normal perl
1310 root 1.1 except everything is compiled in), or you create bundle files (basically C
1311     sources you can use to embed all files into your project).
1312    
1313     This step is very fast (a few seconds if PPI is not used for stripping,
1314     more seconds otherwise, as PPI is very slow), and can be tweaked and
1315     repeated as often as necessary.
1316    
1317     =head1 THE F<STATICPERL> SCRIPT
1318    
1319     This module installs a script called F<staticperl> into your perl
1320     binary directory. The script is fully self-contained, and can be used
1321     without perl (for example, in an uClibc chroot environment). In fact,
1322     it can be extracted from the C<App::Staticperl> distribution tarball as
1323     F<bin/staticperl>, without any installation.
1324    
1325     F<staticperl> interprets the first argument as a command to execute,
1326     optionally followed by any parameters.
1327    
1328     There are two command categories: the "phase 1" commands which deal with
1329     installing perl and perl modules, and the "phase 2" commands, which deal
1330     with creating binaries and bundle files.
1331    
1332     =head2 PHASE 1 COMMANDS: INSTALLING PERL
1333    
1334     The most important command is F<install>, which does basically
1335     everything. The default is to download and install perl 5.12.2 and a few
1336     modules required by F<staticperl> itself, but all this can (and should) be
1337     changed - see L<CONFIGURATION>, below.
1338    
1339     The command
1340    
1341     staticperl install
1342    
1343     Is normally all you need: It installs the perl interpreter in
1344     F<~/.staticperl/perl>. It downloads, configures, builds and installs the
1345     perl interpreter if required.
1346    
1347     Most of the following commands simply run one or more steps of this
1348     sequence.
1349    
1350 root 1.4 To force recompilation or reinstallation, you need to run F<staticperl
1351 root 1.1 distclean> first.
1352    
1353     =over 4
1354    
1355     =item F<staticperl fetch>
1356    
1357     Runs only the download and unpack phase, unless this has already happened.
1358    
1359     =item F<staticperl configure>
1360    
1361     Configures the unpacked perl sources, potentially after downloading them first.
1362    
1363     =item F<staticperl build>
1364    
1365     Builds the configured perl sources, potentially after automatically
1366     configuring them.
1367    
1368     =item F<staticperl install>
1369    
1370 root 1.4 Wipes the perl installation directory (usually F<~/.staticperl/perl>) and
1371     installs the perl distribution, potentially after building it first.
1372 root 1.1
1373     =item F<staticperl cpan> [args...]
1374    
1375 root 1.4 Starts an interactive CPAN shell that you can use to install further
1376     modules. Installs the perl first if necessary, but apart from that,
1377 root 1.1 no magic is involved: you could just as well run it manually via
1378     F<~/.staticperl/perl/bin/cpan>.
1379    
1380     Any additional arguments are simply passed to the F<cpan> command.
1381    
1382     =item F<staticperl instcpan> module...
1383    
1384     Tries to install all the modules given and their dependencies, using CPAN.
1385    
1386     Example:
1387    
1388     staticperl instcpan EV AnyEvent::HTTPD Coro
1389    
1390     =item F<staticperl instsrc> directory...
1391    
1392     In the unlikely case that you have unpacked perl modules around and want
1393 root 1.4 to install from these instead of from CPAN, you can do this using this
1394 root 1.1 command by specifying all the directories with modules in them that you
1395     want to have built.
1396    
1397     =item F<staticperl clean>
1398    
1399 root 1.11 Deletes the perl source directory (and potentially cleans up other
1400     intermediate files). This can be used to clean up files only needed for
1401     building perl, without removing the installed perl interpreter, or to
1402     force a re-build from scratch.
1403    
1404     At the moment, it doesn't delete downloaded tarballs.
1405 root 1.1
1406     =item F<staticperl distclean>
1407    
1408     This wipes your complete F<~/.staticperl> directory. Be careful with this,
1409     it nukes your perl download, perl sources, perl distribution and any
1410     installed modules. It is useful if you wish to start over "from scratch"
1411     or when you want to uninstall F<staticperl>.
1412    
1413     =back
1414    
1415     =head2 PHASE 2 COMMANDS: BUILDING PERL BUNDLES
1416    
1417     Building (linking) a new F<perl> binary is handled by a separate
1418     script. To make it easy to use F<staticperl> from a F<chroot>, the script
1419     is embedded into F<staticperl>, which will write it out and call for you
1420     with any arguments you pass:
1421    
1422     staticperl mkbundle mkbundle-args...
1423    
1424     In the oh so unlikely case of something not working here, you
1425 root 1.2 can run the script manually as well (by default it is written to
1426 root 1.1 F<~/.staticperl/mkbundle>).
1427    
1428     F<mkbundle> is a more conventional command and expect the argument
1429 root 1.4 syntax commonly used on UNIX clones. For example, this command builds
1430 root 1.1 a new F<perl> binary and includes F<Config.pm> (for F<perl -V>),
1431     F<AnyEvent::HTTPD>, F<URI> and a custom F<httpd> script (from F<eg/httpd>
1432     in this distribution):
1433    
1434     # first make sure we have perl and the required modules
1435     staticperl instcpan AnyEvent::HTTPD
1436    
1437     # now build the perl
1438     staticperl mkperl -M'"Config_heavy.pl"' -MAnyEvent::Impl::Perl \
1439     -MAnyEvent::HTTPD -MURI::http \
1440     --add 'eg/httpd httpd.pm'
1441    
1442     # finally, invoke it
1443     ./perl -Mhttpd
1444    
1445 root 1.2 As you can see, things are not quite as trivial: the L<Config> module has
1446     a hidden dependency which is not even a perl module (F<Config_heavy.pl>),
1447     L<AnyEvent> needs at least one event loop backend that we have to
1448 root 1.4 specify manually (here L<AnyEvent::Impl::Perl>), and the F<URI> module
1449 root 1.2 (required by L<AnyEvent::HTTPD>) implements various URI schemes as extra
1450     modules - since L<AnyEvent::HTTPD> only needs C<http> URIs, we only need
1451 root 1.4 to include that module. I found out about these dependencies by carefully
1452     watching any error messages about missing modules...
1453 root 1.2
1454     =head3 OPTION PROCESSING
1455    
1456 root 1.4 All options can be given as arguments on the command line (typically
1457     using long (e.g. C<--verbose>) or short option (e.g. C<-v>) style). Since
1458     specifying a lot of modules can make the command line very cumbersome,
1459 root 1.2 you can put all long options into a "bundle specification file" (with or
1460     without C<--> prefix) and specify this bundle file instead.
1461    
1462     For example, the command given earlier could also look like this:
1463    
1464     staticperl mkperl httpd.bundle
1465    
1466     And all options could be in F<httpd.bundle>:
1467 root 1.1
1468 root 1.2 use "Config_heavy.pl"
1469     use AnyEvent::Impl::Perl
1470     use AnyEvent::HTTPD
1471     use URI::http
1472     add eg/httpd httpd.pm
1473    
1474     All options that specify modules or files to be added are processed in the
1475 root 1.4 order given on the command line (that affects the C<--use> and C<--eval>
1476 root 1.2 options at the moment).
1477    
1478     =head3 MKBUNDLE OPTIONS
1479    
1480     =over 4
1481    
1482     =item --verbose | -v
1483    
1484     Increases the verbosity level by one (the default is C<1>).
1485    
1486     =item --quiet | -q
1487    
1488     Decreases the verbosity level by one.
1489    
1490     =item --strip none|pod|ppi
1491    
1492     Specify the stripping method applied to reduce the file of the perl
1493     sources included.
1494    
1495     The default is C<pod>, which uses the L<Pod::Strip> module to remove all
1496 root 1.4 pod documentation, which is very fast and reduces file size a lot.
1497 root 1.2
1498     The C<ppi> method uses L<PPI> to parse and condense the perl sources. This
1499 root 1.4 saves a lot more than just L<Pod::Strip>, and is generally safer, but
1500     is also a lot slower, so is best used for production builds. Note that
1501     this method doesn't optimise for raw file size, but for best compression
1502     (that means that the uncompressed file size is a bit larger, but the files
1503     compress better, e.g. with F<upx>).
1504 root 1.2
1505 root 1.7 Last not least, if you need accurate line numbers in error messages,
1506     or in the unlikely case where C<pod> is too slow, or some module gets
1507     mistreated, you can specify C<none> to not mangle included perl sources in
1508     any way.
1509 root 1.2
1510     =item --perl
1511    
1512     After writing out the bundle files, try to link a new perl interpreter. It
1513     will be called F<perl> and will be left in the current working
1514     directory. The bundle files will be removed.
1515    
1516 root 1.4 This switch is automatically used when F<staticperl> is invoked with the
1517 root 1.2 C<mkperl> command (instead of C<mkbundle>):
1518    
1519     # build a new ./perl with only common::sense in it - very small :)
1520     staticperl mkperl -Mcommon::sense
1521    
1522     =item --use module | -Mmodule
1523    
1524     Include the named module and all direct dependencies. This is done by
1525     C<require>'ing the module in a subprocess and tracing which other modules
1526     and files it actually loads. If the module uses L<AutoLoader>, then all
1527     splitfiles will be included as well.
1528    
1529     Example: include AnyEvent and AnyEvent::Impl::Perl.
1530    
1531     staticperl mkbundle --use AnyEvent --use AnyEvent::Impl::Perl
1532    
1533     Sometimes you want to load old-style "perl libraries" (F<.pl> files), or
1534     maybe other weirdly named files. To do that, you need to quote the name in
1535 root 1.4 single or double quotes. When given on the command line, you probably need
1536 root 1.2 to quote once more to avoid your shell interpreting it. Common cases that
1537     need this are F<Config_heavy.pl> and F<utf8_heavy.pl>.
1538    
1539     Example: include the required files for F<perl -V> to work in all its
1540     glory (F<Config.pm> is included automatically by this).
1541    
1542     # bourne shell
1543     staticperl mkbundle --use '"Config_heavy.pl"'
1544    
1545     # bundle specification file
1546     use "Config_heavy.pl"
1547    
1548     The C<-Mmodule> syntax is included as an alias that might be easier to
1549     remember than C<use>. Or maybe it confuses people. Time will tell. Or
1550     maybe not. Argh.
1551    
1552     =item --eval "perl code" | -e "perl code"
1553    
1554     Sometimes it is easier (or necessary) to specify dependencies using perl
1555     code, or maybe one of the modules you use need a special use statement. In
1556     that case, you can use C<eval> to execute some perl snippet or set some
1557     variables or whatever you need. All files C<require>'d or C<use>'d in the
1558     script are included in the final bundle.
1559    
1560     Keep in mind that F<mkbundle> will only C<require> the modules named
1561     by the C<--use> option, so do not expect the symbols from modules you
1562 root 1.4 C<--use>'d earlier on the command line to be available.
1563 root 1.2
1564     Example: force L<AnyEvent> to detect a backend and therefore include it
1565     in the final bundle.
1566    
1567     staticperl mkbundle --eval 'use AnyEvent; AnyEvent::detect'
1568    
1569     # or like this
1570     staticperl mkbundle -MAnyEvent --eval 'use AnyEvent; AnyEvent::detect'
1571    
1572     Example: use a separate "bootstrap" script that C<use>'s lots of modules
1573     and include this in the final bundle, to be executed automatically.
1574    
1575     staticperl mkbundle --eval 'do "bootstrap"' --boot bootstrap
1576    
1577     =item --boot filename
1578    
1579     Include the given file in the bundle and arrange for it to be executed
1580     (using a C<require>) before anything else when the new perl is
1581     initialised. This can be used to modify C<@INC> or anything else before
1582 root 1.4 the perl interpreter executes scripts given on the command line (or via
1583 root 1.2 C<-e>). This works even in an embedded interpreter.
1584    
1585     =item --add "file" | --add "file alias"
1586    
1587     Adds the given (perl) file into the bundle (and optionally call it
1588     "alias"). This is useful to include any custom files into the bundle.
1589    
1590     Example: embed the file F<httpd> as F<httpd.pm> when creating the bundle.
1591    
1592     staticperl mkperl --add "httpd httpd.pm"
1593    
1594     It is also a great way to add any custom modules:
1595    
1596     # specification file
1597     add file1 myfiles/file1
1598     add file2 myfiles/file2
1599     add file3 myfiles/file3
1600    
1601 root 1.8 =item --binadd "file" | --add "file alias"
1602    
1603     Just like C<--add>, except that it treats the file as binary and adds it
1604     without any processing.
1605    
1606     You should probably add a C</> prefix to avoid clashing with embedded
1607     perl files (whose paths do not start with C</>), and/or use a special
1608     directory, such as C</res/name>.
1609    
1610     You can later get a copy of these files by calling C<staticperl::find
1611     "alias">.
1612    
1613 root 1.2 =item --static
1614    
1615     When C<--perl> is also given, link statically instead of dynamically. The
1616     default is to link the new perl interpreter fully dynamic (that means all
1617     perl modules are linked statically, but all external libraries are still
1618     referenced dynamically).
1619    
1620     Keep in mind that Solaris doesn't support static linking at all, and
1621     systems based on GNU libc don't really support it in a usable fashion
1622     either. Try uClibc if you want to create fully statically linked
1623     executables, or try the C<--staticlibs> option to link only some libraries
1624     statically.
1625    
1626     =item any other argument
1627    
1628     Any other argument is interpreted as a bundle specification file, which
1629     supports most long options (without extra quoting), one option per line.
1630    
1631     =back
1632    
1633     =head2 F<STATCPERL> CONFIGURATION AND HOOKS
1634    
1635     During (each) startup, F<staticperl> tries to source the following shell
1636     files in order:
1637    
1638     /etc/staticperlrc
1639     ~/.staticperlrc
1640     $STATICPERL/rc
1641    
1642     They can be used to override shell variables, or define functions to be
1643     called at specific phases.
1644    
1645     Note that the last file is erased during F<staticperl distclean>, so
1646     generally should not be used.
1647    
1648     =head3 CONFIGURATION VARIABLES
1649    
1650     =head4 Variables you I<should> override
1651    
1652     =over 4
1653    
1654     =item C<EMAIL>
1655    
1656     The e-mail address of the person who built this binary. Has no good
1657     default, so should be specified by you.
1658    
1659     =item C<CPAN>
1660    
1661     The URL of the CPAN mirror to use (e.g. L<http://mirror.netcologne.de/cpan/>).
1662    
1663 root 1.6 =item C<EXTRA_MODULES>
1664 root 1.2
1665 root 1.6 Additional modules installed during F<staticperl install>. Here you can
1666     set which modules you want have to installed from CPAN.
1667 root 1.2
1668 root 1.10 Example: I really really need EV, AnyEvent, Coro and AnyEvent::AIO.
1669 root 1.2
1670 root 1.10 EXTRA_MODULES="EV AnyEvent Coro AnyEvent::AIO"
1671 root 1.2
1672 root 1.6 Note that you can also use a C<postinstall> hook to achieve this, and
1673     more.
1674 root 1.2
1675 root 1.10 =back
1676    
1677     =head4 Variables you might I<want> to override
1678    
1679     =over 4
1680    
1681     =item C<STATICPERL>
1682    
1683     The directory where staticperl stores all its files
1684     (default: F<~/.staticperl>).
1685    
1686 root 1.6 =item C<PERL_MM_USE_DEFAULT>, C<EV_EXTRA_DEFS>, ...
1687 root 1.2
1688     Usually set to C<1> to make modules "less inquisitive" during their
1689     installation, you can set any environment variable you want - some modules
1690     (such as L<Coro> or L<EV>) use environment variables for further tweaking.
1691    
1692 root 1.10 =item C<PERL_VERSION>
1693 root 1.6
1694 root 1.10 The perl version to install - default is currently C<5.12.2>, but C<5.8.9>
1695     is also a good choice (5.8.9 is much smaller than 5.12.2, while 5.10.1 is
1696     about as big as 5.12.2).
1697 root 1.2
1698 root 1.10 =item C<PERL_PREFIX>
1699 root 1.2
1700 root 1.6 The prefix where perl gets installed (default: F<$STATICPERL/perl>),
1701     i.e. where the F<bin> and F<lib> subdirectories will end up.
1702 root 1.2
1703 root 1.8 =item C<PERL_CONFIGURE>
1704    
1705     Additional Configure options - these are simply passed to the perl
1706     Configure script. For example, if you wanted to enable dynamic loading,
1707     you could pass C<-Dusedl>. To enable ithreads (Why would you want that
1708     insanity? Don't! Use L<forks> instead!) you would pass C<-Duseithreads>
1709     and so on.
1710    
1711     More commonly, you would either activate 64 bit integer support
1712     (C<-Duse64bitint>), or disable large files support (-Uuselargefiles), to
1713     reduce filesize further.
1714    
1715 root 1.6 =item C<PERL_CPPFLAGS>, C<PERL_OPTIMIZE>, C<PERL_LDFLAGS>, C<PERL_LIBS>
1716 root 1.2
1717 root 1.6 These flags are passed to perl's F<Configure> script, and are generally
1718     optimised for small size (at the cost of performance). Since they also
1719     contain subtle workarounds around various build issues, changing these
1720     usually requires understanding their default values - best look at the top
1721     of the F<staticperl> script for more info on these.
1722 root 1.2
1723     =back
1724    
1725 root 1.5 =head4 Variables you probably I<do not want> to override
1726 root 1.2
1727     =over 4
1728    
1729     =item C<MKBUNDLE>
1730    
1731     Where F<staticperl> writes the C<mkbundle> command to
1732     (default: F<$STATICPERL/mkbundle>).
1733 root 1.1
1734 root 1.2 =item C<STATICPERL_MODULES>
1735 root 1.1
1736 root 1.2 Additional modules needed by C<mkbundle> - should therefore not be changed
1737     unless you know what you are doing.
1738    
1739     =back
1740    
1741     =head3 OVERRIDABLE HOOKS
1742    
1743     In addition to environment variables, it is possible to provide some
1744     shell functions that are called at specific times. To provide your own
1745 root 1.4 commands, just define the corresponding function.
1746 root 1.2
1747     Example: install extra modules from CPAN and from some directories
1748     at F<staticperl install> time.
1749    
1750     postinstall() {
1751 root 1.5 rm -rf lib/threads* # weg mit Schaden
1752 root 1.2 instcpan IO::AIO EV
1753     instsrc ~/src/AnyEvent
1754     instsrc ~/src/XML-Sablotron-1.0100001
1755 root 1.5 instcpan Anyevent::AIO AnyEvent::HTTPD
1756 root 1.2 }
1757    
1758     =over 4
1759    
1760 root 1.11 =item preconfigure
1761    
1762     Called just before running F<./Configur> in the perl source
1763     directory. Current working directory is the perl source directory.
1764    
1765     This can be used to set any C<PERL_xxx> variables, which might be costly
1766     to compute.
1767    
1768 root 1.2 =item postconfigure
1769    
1770     Called after configuring, but before building perl. Current working
1771     directory is the perl source directory.
1772    
1773 root 1.11 Could be used to tailor/patch config.sh (followed by F<sh Configure -S>)
1774     or do any other modifications.
1775 root 1.2
1776     =item postbuild
1777    
1778     Called after building, but before installing perl. Current working
1779     directory is the perl source directory.
1780    
1781     I have no clue what this could be used for - tell me.
1782    
1783     =item postinstall
1784    
1785     Called after perl and any extra modules have been installed in C<$PREFIX>,
1786     but before setting the "installation O.K." flag.
1787    
1788     The current working directory is C<$PREFIX>, but maybe you should not rely
1789     on that.
1790    
1791     This hook is most useful to customise the installation, by deleting files,
1792     or installing extra modules using the C<instcpan> or C<instsrc> functions.
1793    
1794     The script must return with a zero exit status, or the installation will
1795     fail.
1796 root 1.1
1797 root 1.2 =back
1798 root 1.1
1799 root 1.7 =head1 ANATOMY OF A BUNDLE
1800    
1801     When not building a new perl binary, C<mkbundle> will leave a number of
1802     files in the current working directory, which can be used to embed a perl
1803     interpreter in your program.
1804    
1805     Intimate knowledge of L<perlembed> and preferably some experience with
1806     embedding perl is highly recommended.
1807    
1808     C<mkperl> (or the C<--perl> option) basically does this to link the new
1809     interpreter (it also adds a main program to F<bundle.>):
1810    
1811     $Config{cc} $(cat bundle.ccopts) -o perl bundle.c $(cat bundle.ldopts)
1812    
1813     =over 4
1814    
1815     =item bundle.h
1816    
1817     A header file that contains the prototypes of the few symbols "exported"
1818     by bundle.c, and also exposes the perl headers to the application.
1819    
1820     =over 4
1821    
1822     =item staticperl_init ()
1823    
1824     Initialises the perl interpreter. You can use the normal perl functions
1825     after calling this function, for example, to define extra functions or
1826     to load a .pm file that contains some initialisation code, or the main
1827     program function:
1828    
1829     XS (xsfunction)
1830     {
1831     dXSARGS;
1832    
1833     // now we have items, ST(i) etc.
1834     }
1835    
1836     static void
1837     run_myapp(void)
1838     {
1839     staticperl_init ();
1840     newXSproto ("myapp::xsfunction", xsfunction, __FILE__, "$$;$");
1841     eval_pv ("require myapp::main", 1); // executes "myapp/main.pm"
1842     }
1843    
1844     =item staticperl_xs_init (pTHX)
1845    
1846     Sometimes you need direct control over C<perl_parse> and C<perl_run>, in
1847     which case you do not want to use C<staticperl_init> but call them on your
1848     own.
1849    
1850     Then you need this function - either pass it directly as the C<xs_init>
1851     function to C<perl_parse>, or call it from your own C<xs_init> function.
1852    
1853     =item staticperl_cleanup ()
1854    
1855     In the unlikely case that you want to destroy the perl interpreter, here
1856     is the corresponding function.
1857    
1858     =item PerlInterpreter *staticperl
1859    
1860     The perl interpreter pointer used by staticperl. Not normally so useful,
1861     but there it is.
1862    
1863     =back
1864    
1865     =item bundle.ccopts
1866    
1867     Contains the compiler options required to compile at least F<bundle.c> and
1868     any file that includes F<bundle.h> - you should probably use it in your
1869     C<CFLAGS>.
1870    
1871     =item bundle.ldopts
1872    
1873     The linker options needed to link the final program.
1874    
1875     =back
1876    
1877     =head1 RUNTIME FUNCTIONALITY
1878    
1879     Binaries created with C<mkbundle>/C<mkperl> contain extra functions, which
1880     are required to access the bundled perl sources, but might be useful for
1881     other purposes.
1882    
1883     In addition, for the embedded loading of perl files to work, F<staticperl>
1884     overrides the C<@INC> array.
1885    
1886     =over 4
1887    
1888     =item $file = staticperl::find $path
1889    
1890     Returns the data associated with the given C<$path>
1891     (e.g. C<Digest/MD5.pm>, C<auto/POSIX/autosplit.ix>), which is basically
1892     the UNIX path relative to the perl library directory.
1893    
1894     Returns C<undef> if the file isn't embedded.
1895    
1896 root 1.8 =item @paths = staticperl::list
1897 root 1.7
1898     Returns the list of all paths embedded in this binary.
1899    
1900     =back
1901    
1902 root 1.8 =head1 FULLY STATIC BINARIES - BUILDROOT
1903    
1904     To make truly static (Linux-) libraries, you might want to have a look at
1905     buildroot (L<http://buildroot.uclibc.org/>).
1906    
1907     Buildroot is primarily meant to set up a cross-compile environment (which
1908     is not so useful as perl doesn't quite like cross compiles), but it can also compile
1909     a chroot environment where you can use F<staticperl>.
1910    
1911     To do so, download buildroot, and enable "Build options => development
1912     files in target filesystem" and optionally "Build options => gcc
1913     optimization level (optimize for size)". At the time of writing, I had
1914     good experiences with GCC 4.4.x but not GCC 4.5.
1915    
1916     To minimise code size, I used C<-pipe -ffunction-sections -fdata-sections
1917     -finline-limit=8 -fno-builtin-strlen -mtune=i386>. The C<-mtune=i386>
1918     doesn't decrease codesize much, but it makes the file much more
1919     compressible.
1920    
1921     If you don't need Coro or threads, you can go with "linuxthreads.old" (or
1922     no thread support). For Coro, it is highly recommended to switch to a
1923     uClibc newer than 0.9.31 (at the time of this writing, I used the 20101201
1924     snapshot) and enable NPTL, otherwise Coro needs to be configured with the
1925     ultra-slow pthreads backend to work around linuxthreads bugs (it also uses
1926     twice the address space needed for stacks).
1927    
1928     If you use C<linuxthreads.old>, then you should also be aware that
1929     uClibc shares C<errno> between all threads when statically linking. See
1930     L<http://lists.uclibc.org/pipermail/uclibc/2010-June/044157.html> for a
1931     workaround (And L<https://bugs.uclibc.org/2089> for discussion).
1932    
1933 root 1.10 C<ccache> support is also recommended, especially if you want
1934     to play around with buildroot options. Enabling the C<miniperl>
1935     package will probably enable all options required for a successful
1936     perl build. F<staticperl> itself additionally needs either C<wget>
1937     (recommended, for CPAN) or C<curl>.
1938 root 1.8
1939     As for shells, busybox should provide all that is needed, but the default
1940     busybox configuration doesn't include F<comm> which is needed by perl -
1941     either make a custom busybox config, or compile coreutils.
1942    
1943     For the latter route, you might find that bash has some bugs that keep
1944     it from working properly in a chroot - either use dash (and link it to
1945     F</bin/sh> inside the chroot) or link busybox to F</bin/sh>, using it's
1946     built-in ash shell.
1947    
1948     Finally, you need F</dev/null> inside the chroot for many scripts to work
1949     - F<cp /dev/null output/target/dev> or bind-mounting your F</dev> will
1950     both provide this.
1951    
1952     After you have compiled and set up your buildroot target, you can copy
1953     F<staticperl> from the C<App::Staticperl> distribution or from your
1954     perl f<bin> directory (if you installed it) into the F<output/target>
1955     filesystem, chroot inside and run it.
1956    
1957 root 1.1 =head1 AUTHOR
1958    
1959     Marc Lehmann <schmorp@schmorp.de>
1960     http://software.schmorp.de/pkg/staticperl.html
1961