ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/App-Staticperl/mkbundle
Revision: 1.41
Committed: Fri Aug 4 03:14:33 2023 UTC (3 years, 1 month ago) by root
Branch: MAIN
Changes since 1.40: +126 -2 lines
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 root 1.1 #!/opt/bin/perl
2    
3     #############################################################################
4     # cannot load modules till after the tracer BEGIN block
5    
6 root 1.29 our $VERBOSE = 1;
7     our $STRIP = "pod"; # none, pod or ppi
8 root 1.41 our $COMPRESS = "lzf";
9 root 1.29 our $UNISTRIP = 1; # always on, try to strip unicore swash data
10     our $PERL = 0;
11 root 1.9 our $APP;
12 root 1.29 our $VERIFY = 0;
13     our $STATIC = 0;
14     our $PACKLIST = 0;
15     our $IGNORE_ENV = 0;
16     our $ALLOW_DYNAMIC = 0;
17     our $HAVE_DYNAMIC; # maybe useful?
18 root 1.37 our $EXTRA_CFLAGS = "";
19     our $EXTRA_LDFLAGS = "";
20     our $EXTRA_LIBS = "";
21 root 1.1
22 root 1.11 our $OPTIMISE_SIZE = 0; # optimise for raw file size instead of for compression?
23    
24     our $CACHE;
25 root 1.39 our $CACHEVER = 2; # do not change unless you know what you are doing
26 root 1.11
27 root 1.1 my $PREFIX = "bundle";
28     my $PACKAGE = "static";
29    
30     my %pm;
31 root 1.6 my %pmbin;
32 root 1.1 my @libs;
33     my @static_ext;
34     my $extralibs;
35 root 1.10 my @staticlibs;
36     my @incext;
37 root 1.1
38     @ARGV
39     or die "$0: use 'staticperl help' (or read the sources of staticperl)\n";
40    
41 root 1.11 # remove "." from @INC - staticperl.sh does it for us, but be on the safe side
42     BEGIN { @INC = grep !/^\.$/, @INC }
43    
44 root 1.1 $|=1;
45    
46     our ($TRACER_W, $TRACER_R);
47    
48 root 1.12 sub find_incdir($) {
49 root 1.1 for (@INC) {
50     next if ref;
51     return $_ if -e "$_/$_[0]";
52     }
53    
54     undef
55     }
56    
57 root 1.12 sub find_inc($) {
58     my $dir = find_incdir $_[0];
59    
60     return "$dir/$_[0]"
61     if defined $dir;
62    
63     undef
64     }
65    
66 root 1.1 BEGIN {
67     # create a loader process to detect @INC requests before we load any modules
68     my ($W_TRACER, $R_TRACER); # used by tracer
69    
70     pipe $R_TRACER, $TRACER_W or die "pipe: $!";
71     pipe $TRACER_R, $W_TRACER or die "pipe: $!";
72    
73     unless (fork) {
74     close $TRACER_R;
75     close $TRACER_W;
76    
77 root 1.16 my $pkg = "pkg000000";
78    
79 root 1.1 unshift @INC, sub {
80 root 1.12 my $dir = find_incdir $_[1]
81 root 1.1 or return;
82    
83     syswrite $W_TRACER, "-\n$dir\n$_[1]\n";
84    
85 root 1.34 open my $fh, "<:raw:perlio", "$dir/$_[1]"
86 root 1.1 or warn "ERROR: $dir/$_[1]: $!\n";
87    
88     $fh
89     };
90    
91     while (<$R_TRACER>) {
92     if (/use (.*)$/) {
93     my $mod = $1;
94 root 1.25 my $eval;
95    
96     if ($mod =~ /^'.*'$/ or $mod =~ /^".*"$/) {
97     $eval = "require $mod";
98     } elsif ($mod =~ y%/.%%) {
99     $eval = "require q\x00$mod\x00";
100     } else {
101     my $pkg = ++$pkg;
102     $eval = "{ package $pkg; use $mod; }";
103     }
104    
105 root 1.17 eval $eval;
106 root 1.1 warn "ERROR: $@ (while loading '$mod')\n"
107     if $@;
108     } elsif (/eval (.*)$/) {
109     my $eval = $1;
110     eval $eval;
111     warn "ERROR: $@ (in '$eval')\n"
112     if $@;
113     }
114 root 1.12
115     syswrite $W_TRACER, "\n";
116 root 1.1 }
117    
118     exit 0;
119     }
120     }
121    
122     # module loading is now safe
123 root 1.5
124 root 1.12 sub trace_parse {
125 root 1.1 for (;;) {
126     <$TRACER_R> =~ /^-$/ or last;
127     my $dir = <$TRACER_R>; chomp $dir;
128     my $name = <$TRACER_R>; chomp $name;
129    
130     $pm{$name} = "$dir/$name";
131 root 1.12
132     print "+ found potential dependency $name\n"
133     if $VERBOSE >= 3;
134 root 1.1 }
135     }
136    
137 root 1.12 sub trace_module {
138     print "tracing module $_[0]\n"
139     if $VERBOSE >= 2;
140    
141     syswrite $TRACER_W, "use $_[0]\n";
142     trace_parse;
143     }
144    
145 root 1.1 sub trace_eval {
146 root 1.12 print "tracing eval $_[0]\n"
147     if $VERBOSE >= 2;
148    
149 root 1.1 syswrite $TRACER_W, "eval $_[0]\n";
150 root 1.12 trace_parse;
151 root 1.1 }
152    
153     sub trace_finish {
154     close $TRACER_W;
155     close $TRACER_R;
156     }
157    
158     #############################################################################
159     # now we can use modules
160    
161     use common::sense;
162 root 1.11 use Config;
163 root 1.1 use Digest::MD5;
164    
165 root 1.11 sub cache($$$) {
166     my ($variant, $src, $filter) = @_;
167    
168 root 1.12 if (length $CACHE and 2048 <= length $src and defined $variant) {
169 root 1.11 my $file = "$CACHE/" . Digest::MD5::md5_hex "$CACHEVER\x00$variant\x00$src";
170    
171 root 1.34 if (open my $fh, "<:raw:perlio", $file) {
172 root 1.12 print "using cache for $file\n"
173     if $VERBOSE >= 7;
174    
175 root 1.11 local $/;
176     return <$fh>;
177     }
178    
179     $src = $filter->($src);
180    
181 root 1.12 print "creating cache entry $file\n"
182     if $VERBOSE >= 8;
183    
184 root 1.34 if (open my $fh, ">:raw:perlio", "$file~") {
185 root 1.11 if ((syswrite $fh, $src) == length $src) {
186     close $fh;
187     rename "$file~", $file;
188     }
189     }
190    
191     return $src;
192     }
193    
194     $filter->($src)
195     }
196    
197 root 1.1 sub dump_string {
198     my ($fh, $data) = @_;
199    
200     if (length $data) {
201 root 1.29 if ($^O eq "MSWin32") {
202     # 16 bit system, strings can't be longer than 64k. seriously.
203     print $fh "{\n";
204     for (
205     my $ofs = 0;
206     length (my $substr = substr $data, $ofs, 20);
207     $ofs += 20
208     ) {
209     $substr = join ",", map ord, split //, $substr;
210     print $fh " $substr,\n";
211     }
212     print $fh " 0 }\n";
213     } else {
214     for (
215     my $ofs = 0;
216     length (my $substr = substr $data, $ofs, 80);
217     $ofs += 80
218     ) {
219     $substr =~ s/([^\x20-\x21\x23-\x5b\x5d-\x7e])/sprintf "\\%03o", ord $1/ge;
220     $substr =~ s/\?/\\?/g; # trigraphs...
221     print $fh " \"$substr\"\n";
222     }
223 root 1.1 }
224     } else {
225     print $fh " \"\"\n";
226     }
227     }
228    
229 root 1.11 #############################################################################
230    
231     sub glob2re {
232     for (quotemeta $_[0]) {
233     s/\\\*/\x00/g;
234     s/\x00\x00/.*/g;
235     s/\x00/[^\/]*/g;
236     s/\\\?/[^\/]/g;
237    
238     $_ = s/^\\\/// ? "^$_\$" : "(?:^|/)$_\$";
239    
240     s/(?: \[\^\/\] | \. ) \*\$$//x;
241    
242     return qr<$_>s
243     }
244     }
245    
246     our %INCSKIP = (
247     "unicore/TestProp.pl" => undef, # 3.5MB of insanity, apparently just some testcase
248     );
249    
250     sub get_dirtree {
251     my $root = shift;
252    
253     my @tree;
254     my $skip;
255    
256     my $scan; $scan = sub {
257     for (sort do {
258     opendir my $fh, $_[0]
259     or return;
260     readdir $fh
261     }) {
262     next if /^\./;
263    
264     my $path = "$_[0]/$_";
265    
266     if (-d "$path/.") {
267     $scan->($path);
268     } else {
269     $path = substr $path, $skip;
270     push @tree, $path
271     unless exists $INCSKIP{$path};
272     }
273     }
274     };
275    
276     $root =~ s/\/$//;
277     $skip = 1 + length $root;
278     $scan->($root);
279    
280     \@tree
281     }
282    
283     my $inctrees;
284    
285     sub get_inctrees {
286     unless ($inctrees) {
287     my %inctree;
288     $inctree{$_} ||= [$_, get_dirtree $_] # entries in @INC are often duplicates
289     for @INC;
290     $inctrees = [values %inctree];
291     }
292    
293     @$inctrees
294     }
295 root 1.1
296 root 1.11 #############################################################################
297 root 1.1
298     sub cmd_boot {
299 root 1.29 $pm{"!boot"} = $_[0];
300 root 1.1 }
301    
302     sub cmd_add {
303 root 1.21 $_[0] =~ /^(.*?)(?:\s+(\S+))?$/
304 root 1.1 or die "$_[0]: cannot parse";
305    
306     my $file = $1;
307 root 1.24 my $as = defined $2 ? $2 : $1;
308 root 1.1
309     $pm{$as} = $file;
310 root 1.6 $pmbin{$as} = 1 if $_[1];
311 root 1.1 }
312    
313 root 1.10 sub cmd_staticlib {
314     push @staticlibs, $_
315     for split /\s+/, $_[0];
316     }
317    
318 root 1.11 sub cmd_include {
319     push @incext, [$_[1], glob2re $_[0]];
320     }
321    
322     sub cmd_incglob {
323     my ($pattern) = @_;
324    
325     $pattern = glob2re $pattern;
326    
327     for (get_inctrees) {
328     my ($dir, $files) = @$_;
329    
330     $pm{$_} = "$dir/$_"
331 root 1.14 for grep /$pattern/ && /\.(pl|pm)$/, @$files;
332 root 1.11 }
333     }
334    
335 root 1.12 sub parse_argv;
336    
337 root 1.1 sub cmd_file {
338     open my $fh, "<", $_[0]
339     or die "$_[0]: $!\n";
340    
341 root 1.12 local @ARGV;
342    
343 root 1.1 while (<$fh>) {
344     chomp;
345 root 1.12 next unless /\S/;
346     next if /^\s*#/;
347    
348     s/^\s*-*/--/;
349 root 1.1 my ($cmd, $args) = split / /, $_, 2;
350    
351 root 1.12 push @ARGV, $cmd;
352     push @ARGV, $args if defined $args;
353 root 1.1 }
354 root 1.12
355     parse_argv;
356 root 1.1 }
357    
358     use Getopt::Long;
359    
360 root 1.12 sub parse_argv {
361     GetOptions
362 root 1.37 "perl" => \$PERL,
363     "app=s" => \$APP,
364 root 1.25
365 root 1.37 "verbose|v" => sub { ++$VERBOSE },
366     "quiet|q" => sub { --$VERBOSE },
367 root 1.25
368 root 1.37 "strip=s" => \$STRIP,
369 root 1.41 "compress=s" => \$COMPRESS,
370 root 1.37 "cache=s" => \$CACHE, # internal option
371     "eval|e=s" => sub { trace_eval $_[1] },
372     "use|M=s" => sub { trace_module $_[1] },
373     "boot=s" => sub { cmd_boot $_[1] },
374     "add=s" => sub { cmd_add $_[1], 0 },
375     "addbin=s" => sub { cmd_add $_[1], 1 },
376     "incglob=s" => sub { cmd_incglob $_[1] },
377     "include|i=s" => sub { cmd_include $_[1], 1 },
378     "exclude|x=s" => sub { cmd_include $_[1], 0 },
379     "usepacklists!" => \$PACKLIST,
380    
381     "static!" => \$STATIC,
382     "staticlib=s" => sub { cmd_staticlib $_[1] },
383     "allow-dynamic!" => \$ALLOW_DYNAMIC,
384     "ignore-env" => \$IGNORE_ENV,
385    
386     "extra-cflags=s" => \$EXTRA_CFLAGS,
387     "extra-ldflags=s" => \$EXTRA_LDFLAGS,
388     "extra-libs=s" => \$EXTRA_LIBS,
389 root 1.25
390 root 1.37 "<>" => sub { cmd_file $_[0] },
391 root 1.12 or exit 1;
392     }
393    
394 root 1.1 Getopt::Long::Configure ("bundling", "no_auto_abbrev", "no_ignore_case");
395    
396 root 1.12 parse_argv;
397 root 1.1
398 root 1.9 die "cannot specify both --app and --perl\n"
399     if $PERL and defined $APP;
400    
401 root 1.41 die "--compress must be either none or lzf\n"
402     unless $COMPRESS =~ /^(?:none|lzf)\z/;
403    
404 root 1.11 # required for @INC loading, unfortunately
405     trace_module "PerlIO::scalar";
406    
407     #############################################################################
408 root 1.14 # apply include/exclude
409 root 1.11
410     {
411     my %pmi;
412    
413     for (@incext) {
414     my ($inc, $glob) = @$_;
415    
416     my @match = grep /$glob/, keys %pm;
417    
418     if ($inc) {
419     # include
420     @pmi{@match} = delete @pm{@match};
421 root 1.12
422     print "applying include $glob - protected ", (scalar @match), " files.\n"
423     if $VERBOSE >= 5;
424 root 1.11 } else {
425     # exclude
426     delete @pm{@match};
427 root 1.12
428 root 1.14 print "applying exclude $glob - removed ", (scalar @match), " files.\n"
429 root 1.12 if $VERBOSE >= 5;
430 root 1.11 }
431     }
432    
433     my @pmi = keys %pmi;
434     @pm{@pmi} = delete @pmi{@pmi};
435     }
436    
437     #############################################################################
438 root 1.14 # scan for AutoLoader, static archives and other dependencies
439 root 1.11
440     sub scan_al {
441     my ($auto, $autodir) = @_;
442    
443     my $ix = "$autodir/autosplit.ix";
444    
445 root 1.12 print "processing autoload index for '$auto'\n"
446     if $VERBOSE >= 6;
447    
448 root 1.11 $pm{"$auto/autosplit.ix"} = $ix;
449    
450     open my $fh, "<:perlio", $ix
451     or die "$ix: $!";
452    
453     my $package;
454    
455     while (<$fh>) {
456     if (/^\s*sub\s+ ([^[:space:];]+) \s* (?:\([^)]*\))? \s*;?\s*$/x) {
457     my $al = "auto/$package/$1.al";
458     my $inc = find_inc $al;
459    
460     defined $inc or die "$al: autoload file not found, but should be there.\n";
461    
462 root 1.12 $pm{$al} = $inc;
463     print "found autoload function '$al'\n"
464     if $VERBOSE >= 6;
465 root 1.11
466     } elsif (/^\s*package\s+([^[:space:];]+)\s*;?\s*$/) {
467     ($package = $1) =~ s/::/\//g;
468     } elsif (/^\s*(?:#|1?\s*;?\s*$)/) {
469     # nop
470     } else {
471 root 1.12 warn "WARNING: $ix: unparsable line, please report: $_";
472 root 1.11 }
473     }
474     }
475    
476     for my $pm (keys %pm) {
477     if ($pm =~ /^(.*)\.pm$/) {
478     my $auto = "auto/$1";
479     my $autodir = find_inc $auto;
480    
481 root 1.12 if (defined $autodir && -d $autodir) {
482 root 1.11 # AutoLoader
483     scan_al $auto, $autodir
484     if -f "$autodir/autosplit.ix";
485    
486     # extralibs.ld
487     if (open my $fh, "<:perlio", "$autodir/extralibs.ld") {
488 root 1.12 print "found extralibs for $pm\n"
489     if $VERBOSE >= 6;
490    
491 root 1.11 local $/;
492     $extralibs .= " " . <$fh>;
493     }
494    
495     $pm =~ /([^\/]+).pm$/ or die "$pm: unable to match last component";
496    
497     my $base = $1;
498    
499     # static ext
500     if (-f "$autodir/$base$Config{_a}") {
501 root 1.12 print "found static archive for $pm\n"
502     if $VERBOSE >= 3;
503    
504 root 1.11 push @libs, "$autodir/$base$Config{_a}";
505     push @static_ext, $pm;
506     }
507    
508     # dynamic object
509 root 1.28 if (-f "$autodir/$base.$Config{dlext}") {
510 root 1.29 if ($ALLOW_DYNAMIC) {
511     my $as = "!$auto/$base.$Config{dlext}";
512 root 1.28 $pm{$as} = "$autodir/$base.$Config{dlext}";
513     $pmbin{$as} = 1;
514    
515 root 1.29 $HAVE_DYNAMIC = 1;
516 root 1.28
517 root 1.29 print "+ added dynamic object $as\n"
518 root 1.28 if $VERBOSE >= 3;
519     } else {
520 root 1.29 die "ERROR: found shared object '$autodir/$base.$Config{dlext}' but --allow-dynamic not given, aborting.\n"
521 root 1.28 }
522     }
523 root 1.12
524     if ($PACKLIST && open my $fh, "<:perlio", "$autodir/.packlist") {
525     print "found .packlist for $pm\n"
526     if $VERBOSE >= 3;
527    
528     while (<$fh>) {
529     chomp;
530 root 1.14 s/ .*$//; # newer-style .packlists might contain key=value pairs
531 root 1.12
532     # only include certain files (.al, .ix, .pm, .pl)
533     if (/\.(pm|pl|al|ix)$/) {
534     for my $inc (@INC) {
535     # in addition, we only add files that are below some @INC path
536     $inc =~ s/\/*$/\//;
537    
538     if ($inc eq substr $_, 0, length $inc) {
539     my $base = substr $_, length $inc;
540     $pm{$base} = $_;
541    
542     print "+ added .packlist dependency $base\n"
543     if $VERBOSE >= 3;
544     }
545    
546     last;
547     }
548     }
549     }
550     }
551 root 1.11 }
552     }
553     }
554    
555     #############################################################################
556    
557 root 1.12 print "processing bundle files (try more -v power if you get bored waiting here)...\n"
558     if $VERBOSE >= 1;
559    
560 root 1.41 my $compress = sub { shift };
561    
562     if ($COMPRESS eq "lzf") {
563     require Compress::LZF;
564     $compress = sub { Compress::LZF::compress_best (shift) };
565     }
566    
567 root 1.1 my $data;
568     my @index;
569     my @order = sort {
570     length $a <=> length $b
571     or $a cmp $b
572     } keys %pm;
573    
574     # sorting by name - better compression, but needs more metadata
575     # sorting by length - faster lookup
576     # usually, the metadata overhead beats the loss through compression
577    
578     for my $pm (@order) {
579     my $path = $pm{$pm};
580    
581     128 > length $pm
582 root 1.11 or die "ERROR: $pm: path too long (only 128 octets supported)\n";
583 root 1.1
584     my $src = ref $path
585     ? $$path
586     : do {
587 root 1.34 open my $pm, "<:raw:perlio", $path
588 root 1.1 or die "$path: $!";
589    
590     local $/;
591    
592     <$pm>
593     };
594    
595 root 1.11 my $size = length $src;
596    
597 root 1.6 unless ($pmbin{$pm}) { # only do this unless the file is binary
598     if ($pm =~ /^auto\/POSIX\/[^\/]+\.al$/) {
599     if ($src =~ /^ unimpl \"/m) {
600 root 1.13 print "$pm: skipping (raises runtime error only).\n"
601 root 1.12 if $VERBOSE >= 3;
602 root 1.6 next;
603     }
604 root 1.1 }
605    
606 root 1.41 $src = cache "$STRIP,$UNISTRIP,$OPTIMISE_SIZE,$COMPRESS", $src, sub {
607 root 1.11 if ($UNISTRIP && $pm =~ /^unicore\/.*\.pl$/) {
608 root 1.12 print "applying unicore stripping $pm\n"
609     if $VERBOSE >= 6;
610    
611 root 1.11 # special stripping for unicore swashes and properties
612     # much more could be done by going binary
613     $src =~ s{
614     (^return\ <<'END';\n) (.*?\n) (END(?:\n|\Z))
615     }{
616     my ($pre, $data, $post) = ($1, $2, $3);
617    
618     for ($data) {
619     s/^([0-9a-fA-F]+)\t([0-9a-fA-F]+)\t/sprintf "%X\t%X", hex $1, hex $2/gem
620     if $OPTIMISE_SIZE;
621    
622     # s{
623     # ^([0-9a-fA-F]+)\t([0-9a-fA-F]*)\t
624     # }{
625     # # ww - smaller filesize, UU - compress better
626     # pack "C0UU",
627     # hex $1,
628     # length $2 ? (hex $2) - (hex $1) : 0
629     # }gemx;
630 root 1.6
631 root 1.11 s/#.*\n/\n/mg;
632     s/\s+\n/\n/mg;
633     }
634 root 1.1
635 root 1.11 "$pre$data$post"
636     }smex;
637 root 1.1 }
638    
639 root 1.11 if ($STRIP =~ /ppi/i) {
640     require PPI;
641    
642     if (my $ppi = PPI::Document->new (\$src)) {
643     $ppi->prune ("PPI::Token::Comment");
644     $ppi->prune ("PPI::Token::Pod");
645    
646     # prune END stuff
647     for (my $last = $ppi->last_element; $last; ) {
648     my $prev = $last->previous_token;
649    
650     if ($last->isa (PPI::Token::Whitespace::)) {
651     $last->delete;
652     } elsif ($last->isa (PPI::Statement::End::)) {
653     $last->delete;
654     last;
655     } elsif ($last->isa (PPI::Token::Pod::)) {
656     $last->delete;
657     } else {
658     last;
659     }
660    
661     $last = $prev;
662     }
663    
664     # prune some but not all insignificant whitespace
665     for my $ws (@{ $ppi->find (PPI::Token::Whitespace::) }) {
666     my $prev = $ws->previous_token;
667     my $next = $ws->next_token;
668    
669     if (!$prev || !$next) {
670     $ws->delete;
671     } else {
672 root 1.40 if ($next->isa (PPI::Token::Whitespace::)) {
673     $ws->delete;
674     } elsif (
675 root 1.11 $next->isa (PPI::Token::Operator::) && $next->{content} =~ /^(?:,|=|!|!=|==|=>)$/ # no ., because of digits. == float
676     or $prev->isa (PPI::Token::Operator::) && $prev->{content} =~ /^(?:,|=|\.|!|!=|==|=>)$/
677     or $prev->isa (PPI::Token::Structure::)
678     or ($OPTIMISE_SIZE &&
679     ($prev->isa (PPI::Token::Word::)
680     && (PPI::Token::Symbol:: eq ref $next
681     || $next->isa (PPI::Structure::Block::)
682     || $next->isa (PPI::Structure::List::)
683     || $next->isa (PPI::Structure::Condition::)))
684     )
685     ) {
686 root 1.39 # perl has some idiotic warnigns about nonexisting operators
687     if ($prev->isa (PPI::Token::Operator::) && $prev->{content} eq "="
688     && $next->isa (PPI::Token::Operator::) && $next->{content} =~ /[+\-]/
689     ) {
690     # avoid "Reverse %s operator" diagnostic
691     } else {
692     $ws->delete;
693     }
694 root 1.11 } else {
695     $ws->{content} = ' ';
696     }
697     }
698     }
699 root 1.1
700 root 1.11 # prune whitespace around blocks
701     if ($OPTIMISE_SIZE) {
702     # these usually decrease size, but decrease compressability more
703     for my $struct (PPI::Structure::Block::, PPI::Structure::Condition::) {
704     for my $node (@{ $ppi->find ($struct) }) {
705     my $n1 = $node->first_token;
706     my $n2 = $n1->previous_token;
707     $n1->delete if $n1->isa (PPI::Token::Whitespace::);
708     $n2->delete if $n2 && $n2->isa (PPI::Token::Whitespace::);
709     my $n1 = $node->last_token;
710     my $n2 = $n1->next_token;
711     $n1->delete if $n1->isa (PPI::Token::Whitespace::);
712     $n2->delete if $n2 && $n2->isa (PPI::Token::Whitespace::);
713     }
714     }
715    
716     for my $node (@{ $ppi->find (PPI::Structure::List::) }) {
717     my $n1 = $node->first_token;
718     $n1->delete if $n1->isa (PPI::Token::Whitespace::);
719     my $n1 = $node->last_token;
720     $n1->delete if $n1->isa (PPI::Token::Whitespace::);
721     }
722 root 1.6 }
723 root 1.1
724 root 1.11 # reformat qw() lists which often have lots of whitespace
725     for my $node (@{ $ppi->find (PPI::Token::QuoteLike::Words::) }) {
726     if ($node->{content} =~ /^qw(.)(.*)(.)$/s) {
727     my ($a, $qw, $b) = ($1, $2, $3);
728     $qw =~ s/^\s+//;
729     $qw =~ s/\s+$//;
730     $qw =~ s/\s+/ /g;
731     $node->{content} = "qw$a$qw$b";
732     }
733 root 1.6 }
734 root 1.11
735     $src = $ppi->serialize;
736     } else {
737     warn "WARNING: $pm{$pm}: PPI failed to parse this file\n";
738 root 1.6 }
739 root 1.15 } elsif ($STRIP =~ /pod/i && $pm ne "Opcode.pm") { # opcode parses its own pod
740 root 1.11 require Pod::Strip;
741    
742     my $stripper = Pod::Strip->new;
743 root 1.6
744 root 1.11 my $out;
745     $stripper->output_string (\$out);
746     $stripper->parse_string_document ($src)
747     or die;
748     $src = $out;
749 root 1.1 }
750    
751 root 1.11 if ($VERIFY && $pm =~ /\.pm$/ && $pm ne "Opcode.pm") {
752     if (open my $fh, "-|") {
753     <$fh>;
754     } else {
755     eval "#line 1 \"$pm\"\n$src" or warn "\n\n\n$pm\n\n$src\n$@\n\n\n";
756     exit 0;
757 root 1.6 }
758 root 1.1 }
759    
760 root 1.41 $src = $compress->($src);
761    
762 root 1.11 $src
763     };
764 root 1.1
765 root 1.6 # if ($pm eq "Opcode.pm") {
766     # open my $fh, ">x" or die; print $fh $src;#d#
767     # exit 1;
768     # }
769 root 1.1 }
770    
771 root 1.12 print "adding $pm (original size $size, stored size ", length $src, ")\n"
772 root 1.1 if $VERBOSE >= 2;
773    
774     push @index, ((length $pm) << 25) | length $data;
775     $data .= $pm . $src;
776     }
777    
778     length $data < 2**25
779 root 1.12 or die "ERROR: bundle too large (only 32MB supported)\n";
780 root 1.1
781 root 1.26 my $varpfx = "bundle";
782 root 1.1
783     #############################################################################
784     # output
785    
786 root 1.12 print "generating $PREFIX.h... "
787     if $VERBOSE >= 1;
788 root 1.1
789     {
790     open my $fh, ">", "$PREFIX.h"
791     or die "$PREFIX.h: $!\n";
792    
793     print $fh <<EOF;
794 root 1.27 /* do not edit, automatically created by staticperl */
795 root 1.5
796 root 1.1 #include <EXTERN.h>
797     #include <perl.h>
798     #include <XSUB.h>
799    
800     /* public API */
801     EXTERN_C PerlInterpreter *staticperl;
802 root 1.5 EXTERN_C void staticperl_xs_init (pTHX);
803 root 1.18 EXTERN_C void staticperl_init (XSINIT_t xs_init); /* argument can be 0 */
804 root 1.1 EXTERN_C void staticperl_cleanup (void);
805 root 1.5
806 root 1.1 EOF
807     }
808    
809 root 1.12 print "\n"
810     if $VERBOSE >= 1;
811 root 1.1
812     #############################################################################
813     # output
814    
815 root 1.12 print "generating $PREFIX.c... "
816     if $VERBOSE >= 1;
817 root 1.1
818     open my $fh, ">", "$PREFIX.c"
819     or die "$PREFIX.c: $!\n";
820    
821     print $fh <<EOF;
822 root 1.27 /* do not edit, automatically created by staticperl */
823 root 1.1
824     #include "bundle.h"
825    
826     /* public API */
827     PerlInterpreter *staticperl;
828    
829     EOF
830    
831     #############################################################################
832 root 1.41 # lzf decompressor
833    
834     if ($COMPRESS eq "lzf") {
835     print $fh <<'EOF';
836     /* stripped down/perlified version of lzf_d.c from liblzf-3.7 */
837    
838     #if (__i386 || __amd64) && __GNUC__ >= 3
839     # define lzf_movsb(dst, src, len) \
840     asm ("rep movsb" \
841     : "=D" (dst), "=S" (src), "=c" (len) \
842     : "0" (dst), "1" (src), "2" (len));
843     #endif
844    
845     static unsigned int
846     lzf_decompress (const void *const in_data, unsigned int in_len,
847     void *out_data, unsigned int out_len)
848     {
849     U8 const *ip = (const U8 *)in_data;
850     U8 *op = (U8 *)out_data;
851     U8 const *const in_end = ip + in_len;
852     U8 *const out_end = op + out_len;
853    
854     do
855     {
856     unsigned int ctrl = *ip++;
857    
858     if (ctrl < (1 << 5)) /* literal run */
859     {
860     ctrl++;
861    
862     if (op + ctrl > out_end)
863     return 0;
864    
865     #ifdef lzf_movsb
866     lzf_movsb (op, ip, ctrl);
867     #else
868     while (ctrl--)
869     *op++ = *ip++;
870     #endif
871     }
872     else /* back reference */
873     {
874     unsigned int len = ctrl >> 5;
875    
876     U8 *ref = op - ((ctrl & 0x1f) << 8) - 1;
877    
878     if (len == 7)
879     len += *ip++;
880    
881     ref -= *ip++;
882    
883     if (op + len + 2 > out_end)
884     return 0;
885    
886     if (ref < (U8 *)out_data)
887     return 0;
888    
889     len += 2;
890     #ifdef lzf_movsb
891     lzf_movsb (op, ref, len);
892     #else
893     do
894     *op++ = *ref++;
895     while (--len);
896     #endif
897     }
898     }
899     while (ip < in_end);
900    
901     return op - (U8 *)out_data;
902     }
903    
904     static SV *
905     static_to_sv (const char *ptr, STRLEN len)
906     {
907     SV *res;
908     const U8 *p = (const U8 *)ptr;
909    
910     if (len == 0) /* empty */
911     res = newSVpvn ("", 0);
912     else if (*p == 0) /* not compressed */
913     res = newSVpvn (p + 1, len - 1);
914     else /* lzf compressed, with UTF-8-encoded original size in front */
915     {
916     STRLEN ulenlen;
917     UV ulen = utf8n_to_uvchr (p, len, &ulenlen, 0);
918    
919     p += ulenlen;
920     len -= ulenlen;
921    
922     res = NEWSV (0, ulen);
923     sv_upgrade (res, SVt_PV);
924     SvPOK_only (res);
925     lzf_decompress (p, len, SvPVX (res), ulen);
926     SvCUR_set (res, ulen);
927     }
928    
929     return res;
930     }
931    
932     EOF
933     } else {
934     print $fh <<EOF;
935    
936     #define static_to_sv(ptr,len) newSVpvn (ptr, len)
937    
938     EOF
939     }
940    
941     #############################################################################
942 root 1.1 # bundle data
943    
944     my $count = @index;
945    
946     print $fh <<EOF;
947     #include "bundle.h"
948    
949     /* bundle data */
950    
951     static const U32 $varpfx\_count = $count;
952     static const U32 $varpfx\_index [$count + 1] = {
953     EOF
954    
955     my $col;
956     for (@index) {
957     printf $fh "0x%08x,", $_;
958     print $fh "\n" unless ++$col % 10;
959    
960     }
961     printf $fh "0x%08x\n};\n", (length $data);
962    
963     print $fh "static const char $varpfx\_data [] =\n";
964     dump_string $fh, $data;
965    
966 root 1.12 print $fh ";\n\n";
967 root 1.1
968     #############################################################################
969     # bootstrap
970    
971     # boot file for staticperl
972     # this file will be eval'ed at initialisation time
973    
974 root 1.29 # lines marked with "^D" are only used when $HAVE_DYNAMIC
975 root 1.1 my $bootstrap = '
976     BEGIN {
977     package ' . $PACKAGE . ';
978    
979 root 1.28 # the path prefix to use when putting files into %INC
980     our $inc_prefix;
981 root 1.1
982 root 1.28 # the @INC hook to use when we have PerlIO::scalar available
983     my $perlio_inc = sub {
984 root 1.1 my $data = find "$_[1]"
985     or return;
986    
987 root 1.28 $INC{$_[1]} = "$inc_prefix$_[1]";
988 root 1.1
989     open my $fh, "<", \$data;
990     $fh
991     };
992 root 1.28
993     D if (defined &PerlIO::scalar::bootstrap) {
994     # PerlIO::scalar statically compiled in
995     PerlIO::scalar->bootstrap;
996     @INC = $perlio_inc;
997     D } else {
998     D # PerlIO::scalar not available, use slower method
999     D @INC = sub {
1000     D # always check if PerlIO::scalar might now be available
1001     D if (defined &PerlIO::scalar::bootstrap) {
1002     D # switch to the faster perlio_inc hook
1003     D @INC = map { $_ == $_[0] ? $perlio_inc : $_ } @INC;
1004     D goto &$perlio_inc;
1005     D }
1006     D
1007     D my $data = find "$_[1]"
1008     D or return;
1009     D
1010     D $INC{$_[1]} = "$inc_prefix$_[1]";
1011     D
1012     D sub {
1013     D $data =~ /\G([^\n]*\n?)/g
1014     D or return;
1015     D
1016     D $_ = $1;
1017     D 1
1018     D }
1019     D };
1020     D }
1021 root 1.1 }
1022     ';
1023    
1024 root 1.29 $bootstrap .= "require '!boot';"
1025     if exists $pm{"!boot"};
1026 root 1.1
1027 root 1.29 if ($HAVE_DYNAMIC) {
1028 root 1.28 $bootstrap =~ s/^D/ /mg;
1029     } else {
1030     $bootstrap =~ s/^D.*$//mg;
1031     }
1032    
1033     $bootstrap =~ s/#.*$//mg;
1034 root 1.1 $bootstrap =~ s/\s+/ /g;
1035     $bootstrap =~ s/(\W) /$1/g;
1036     $bootstrap =~ s/ (\W)/$1/g;
1037    
1038     print $fh "const char bootstrap [] = ";
1039     dump_string $fh, $bootstrap;
1040     print $fh ";\n\n";
1041    
1042     print $fh <<EOF;
1043     /* search all bundles for the given file, using binary search */
1044     XS(find)
1045     {
1046     dXSARGS;
1047    
1048     if (items != 1)
1049     Perl_croak (aTHX_ "Usage: $PACKAGE\::find (\$path)");
1050    
1051     {
1052     STRLEN namelen;
1053     char *name = SvPV (ST (0), namelen);
1054     SV *res = 0;
1055    
1056     int l = 0, r = $varpfx\_count;
1057    
1058     while (l <= r)
1059     {
1060     int m = (l + r) >> 1;
1061     U32 idx = $varpfx\_index [m];
1062     int comp = namelen - (idx >> 25);
1063    
1064     if (!comp)
1065     {
1066     int ofs = idx & 0x1FFFFFFU;
1067     comp = memcmp (name, $varpfx\_data + ofs, namelen);
1068    
1069     if (!comp)
1070     {
1071     /* found */
1072     int ofs2 = $varpfx\_index [m + 1] & 0x1FFFFFFU;
1073    
1074     ofs += namelen;
1075 root 1.41 res = static_to_sv ($varpfx\_data + ofs, ofs2 - ofs);
1076 root 1.1 goto found;
1077     }
1078     }
1079    
1080     if (comp < 0)
1081     r = m - 1;
1082     else
1083     l = m + 1;
1084     }
1085    
1086     XSRETURN (0);
1087    
1088     found:
1089 root 1.28 ST (0) = sv_2mortal (res);
1090 root 1.1 }
1091    
1092     XSRETURN (1);
1093     }
1094    
1095     /* list all files in the bundle */
1096     XS(list)
1097     {
1098     dXSARGS;
1099    
1100     if (items != 0)
1101     Perl_croak (aTHX_ "Usage: $PACKAGE\::list");
1102    
1103     {
1104     int i;
1105    
1106     EXTEND (SP, $varpfx\_count);
1107    
1108     for (i = 0; i < $varpfx\_count; ++i)
1109     {
1110     U32 idx = $varpfx\_index [i];
1111    
1112 root 1.28 PUSHs (sv_2mortal (newSVpvn ($varpfx\_data + (idx & 0x1FFFFFFU), idx >> 25)));
1113 root 1.1 }
1114     }
1115    
1116     XSRETURN ($varpfx\_count);
1117     }
1118    
1119 root 1.35 #ifdef STATICPERL_BUNDLE_INCLUDE
1120     #include STATICPERL_BUNDLE_INCLUDE
1121     #endif
1122    
1123 root 1.1 EOF
1124    
1125     #############################################################################
1126     # xs_init
1127    
1128     print $fh <<EOF;
1129 root 1.5 void
1130     staticperl_xs_init (pTHX)
1131 root 1.1 {
1132     EOF
1133    
1134 root 1.28 @static_ext = sort @static_ext;
1135 root 1.1
1136     # prototypes
1137     for (@static_ext) {
1138     s/\.pm$//;
1139     (my $cname = $_) =~ s/\//__/g;
1140     print $fh " EXTERN_C void boot_$cname (pTHX_ CV* cv);\n";
1141     }
1142    
1143     print $fh <<EOF;
1144     char *file = __FILE__;
1145     dXSUB_SYS;
1146    
1147     newXSproto ("$PACKAGE\::find", find, file, "\$");
1148     newXSproto ("$PACKAGE\::list", list, file, "");
1149 root 1.35
1150     #ifdef STATICPERL_BUNDLE_XS_INIT
1151     STATICPERL_BUNDLE_XS_INIT;
1152     #endif
1153 root 1.1 EOF
1154    
1155     # calls
1156     for (@static_ext) {
1157     s/\.pm$//;
1158    
1159     (my $cname = $_) =~ s/\//__/g;
1160     (my $pname = $_) =~ s/\//::/g;
1161    
1162 root 1.28 my $bootstrap = $pname eq "DynaLoader" ? "boot_DynaLoader" : "bootstrap";
1163 root 1.1
1164     print $fh " newXS (\"$pname\::$bootstrap\", boot_$cname, file);\n";
1165     }
1166    
1167     print $fh <<EOF;
1168 root 1.36 Safefree (PL_origfilename);
1169     PL_origfilename = savepv (PL_origargv [0]);
1170     sv_setpv (GvSV (gv_fetchpvs ("0", GV_ADD|GV_NOTQUAL, SVt_PV)), PL_origfilename);
1171    
1172 root 1.29 #ifdef _WIN32
1173     /* windows perls usually trail behind unix perls 8-10 years in exporting symbols */
1174    
1175     if (!PL_preambleav)
1176     PL_preambleav = newAV ();
1177    
1178     av_unshift (PL_preambleav, 1);
1179     av_store (PL_preambleav, 0, newSVpv (bootstrap, sizeof (bootstrap) - 1));
1180     #else
1181 root 1.30 Perl_av_create_and_unshift_one (&PL_preambleav, newSVpv (bootstrap, sizeof (bootstrap) - 1));
1182 root 1.29 #endif
1183 root 1.18
1184     if (PL_oldname)
1185     ((XSINIT_t)PL_oldname)(aTHX);
1186 root 1.1 }
1187     EOF
1188    
1189     #############################################################################
1190     # optional perl_init/perl_destroy
1191    
1192 root 1.25 if ($IGNORE_ENV) {
1193     $IGNORE_ENV = <<EOF;
1194     unsetenv ("PERL_UNICODE");
1195     unsetenv ("PERL_HASH_SEED_DEBUG");
1196     unsetenv ("PERL_DESTRUCT_LEVEL");
1197     unsetenv ("PERL_SIGNALS");
1198     unsetenv ("PERL_DEBUG_MSTATS");
1199     unsetenv ("PERL5OPT");
1200     unsetenv ("PERLIO_DEBUG");
1201     unsetenv ("PERLIO");
1202     unsetenv ("PERL_HASH_SEED");
1203     EOF
1204     } else {
1205     $IGNORE_ENV = "";
1206     }
1207    
1208 root 1.9 if ($APP) {
1209     print $fh <<EOF;
1210    
1211     int
1212     main (int argc, char *argv [])
1213     {
1214     extern char **environ;
1215 root 1.17 int i, exitstatus;
1216     char **args = malloc ((argc + 3) * sizeof (const char *));
1217    
1218     args [0] = argv [0];
1219     args [1] = "-e";
1220     args [2] = "0";
1221     args [3] = "--";
1222 root 1.9
1223 root 1.17 for (i = 1; i < argc; ++i)
1224     args [i + 3] = argv [i];
1225 root 1.9
1226 root 1.25 $IGNORE_ENV
1227 root 1.9 PERL_SYS_INIT3 (&argc, &argv, &environ);
1228     staticperl = perl_alloc ();
1229     perl_construct (staticperl);
1230    
1231     PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
1232    
1233 root 1.17 exitstatus = perl_parse (staticperl, staticperl_xs_init, argc + 3, args, environ);
1234 root 1.9 if (!exitstatus)
1235     perl_run (staticperl);
1236    
1237     exitstatus = perl_destruct (staticperl);
1238     perl_free (staticperl);
1239     PERL_SYS_TERM ();
1240 root 1.38 /*free (args); no point doing it this late */
1241 root 1.9
1242     return exitstatus;
1243     }
1244     EOF
1245     } elsif ($PERL) {
1246 root 1.1 print $fh <<EOF;
1247    
1248     int
1249     main (int argc, char *argv [])
1250     {
1251     extern char **environ;
1252     int exitstatus;
1253    
1254 root 1.25 $IGNORE_ENV
1255 root 1.1 PERL_SYS_INIT3 (&argc, &argv, &environ);
1256     staticperl = perl_alloc ();
1257     perl_construct (staticperl);
1258    
1259     PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
1260    
1261 root 1.5 exitstatus = perl_parse (staticperl, staticperl_xs_init, argc, argv, environ);
1262 root 1.1 if (!exitstatus)
1263     perl_run (staticperl);
1264    
1265     exitstatus = perl_destruct (staticperl);
1266     perl_free (staticperl);
1267     PERL_SYS_TERM ();
1268    
1269     return exitstatus;
1270     }
1271     EOF
1272     } else {
1273     print $fh <<EOF;
1274    
1275     EXTERN_C void
1276 root 1.18 staticperl_init (XSINIT_t xs_init)
1277 root 1.1 {
1278 root 1.9 static char *args[] = {
1279     "staticperl",
1280     "-e",
1281     "0"
1282     };
1283    
1284 root 1.17 extern char **environ;
1285     int argc = sizeof (args) / sizeof (args [0]);
1286     char **argv = args;
1287    
1288 root 1.25 $IGNORE_ENV
1289 root 1.1 PERL_SYS_INIT3 (&argc, &argv, &environ);
1290     staticperl = perl_alloc ();
1291     perl_construct (staticperl);
1292     PL_origalen = 1;
1293     PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
1294 root 1.18 PL_oldname = (char *)xs_init;
1295 root 1.5 perl_parse (staticperl, staticperl_xs_init, argc, argv, environ);
1296 root 1.1
1297     perl_run (staticperl);
1298     }
1299    
1300     EXTERN_C void
1301     staticperl_cleanup (void)
1302     {
1303     perl_destruct (staticperl);
1304     perl_free (staticperl);
1305     staticperl = 0;
1306     PERL_SYS_TERM ();
1307     }
1308     EOF
1309     }
1310    
1311 root 1.29 close $fh;
1312    
1313 root 1.12 print -s "$PREFIX.c", " octets (", (length $data) , " data octets).\n\n"
1314     if $VERBOSE >= 1;
1315 root 1.1
1316     #############################################################################
1317     # libs, cflags
1318    
1319 root 1.29 my $ccopts;
1320    
1321 root 1.1 {
1322 root 1.12 print "generating $PREFIX.ccopts... "
1323     if $VERBOSE >= 1;
1324 root 1.1
1325 root 1.37 $ccopts = "$Config{ccflags} $Config{optimize} $Config{cppflags} -I$Config{archlibexp}/CORE $EXTRA_CFLAGS";
1326 root 1.29 $ccopts =~ s/([\(\)])/\\$1/g;
1327 root 1.1
1328     open my $fh, ">$PREFIX.ccopts"
1329     or die "$PREFIX.ccopts: $!";
1330 root 1.29 print $fh $ccopts;
1331 root 1.12
1332 root 1.29 print "$ccopts\n\n"
1333 root 1.12 if $VERBOSE >= 1;
1334 root 1.1 }
1335    
1336 root 1.29 my $ldopts;
1337    
1338 root 1.1 {
1339     print "generating $PREFIX.ldopts... ";
1340    
1341 root 1.29 $ldopts = $STATIC ? "-static " : "";
1342 root 1.1
1343 root 1.37 $ldopts .= "$Config{ccdlflags} $Config{ldflags} $EXTRA_LDFLAGS @libs $Config{archlibexp}/CORE/$Config{libperl} $Config{perllibs} $EXTRA_LIBS";
1344 root 1.1
1345     my %seen;
1346 root 1.32 $ldopts .= " $_" for reverse grep !$seen{$_}++, reverse +($extralibs =~ /(\S+)/g);
1347 root 1.1
1348 root 1.10 for (@staticlibs) {
1349 root 1.29 $ldopts =~ s/(^|\s) (-l\Q$_\E) ($|\s)/$1-Wl,-Bstatic $2 -Wl,-Bdynamic$3/gx;
1350 root 1.10 }
1351    
1352 root 1.29 $ldopts =~ s/([\(\)])/\\$1/g;
1353 root 1.1
1354     open my $fh, ">$PREFIX.ldopts"
1355     or die "$PREFIX.ldopts: $!";
1356 root 1.29 print $fh $ldopts;
1357 root 1.12
1358 root 1.29 print "$ldopts\n\n"
1359 root 1.12 if $VERBOSE >= 1;
1360 root 1.1 }
1361    
1362 root 1.9 if ($PERL or defined $APP) {
1363     $APP = "perl" unless defined $APP;
1364    
1365 root 1.29 my $build = "$Config{cc} $ccopts -o \Q$APP\E$Config{_exe} bundle.c $ldopts";
1366    
1367     print "build $APP...\n"
1368 root 1.12 if $VERBOSE >= 1;
1369 root 1.9
1370 root 1.29 print "$build\n"
1371     if $VERBOSE >= 2;
1372    
1373     system $build;
1374 root 1.1
1375 root 1.33 unlink "$PREFIX.$_"
1376     for qw(ccopts ldopts c h);
1377 root 1.11
1378 root 1.12 print "\n"
1379     if $VERBOSE >= 1;
1380 root 1.1 }
1381