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