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