script/par.pl untested

filter: Statementstmt 0.0% 0 / 553 Branchbran 0.0% 0 / 202 Conditioncond 0.0% 0 / 131 Subroutinesub 0.0% 0 / 70 Podpod 0.0% 0 / 13 totaltotal 0.0% 0 / 969 CC 129 SCAR 83.9
CC
129
Cov
0%
BEGIN
9120.0
_set_par_temp
132.0
_set_progname
110.0
CRAP 4390.9
1 #!/usr/local/bin/perl
2 eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
3 if 0; # not running under some shell
4  
5 package __par_pl;
6  
7 # --- This script must not use any modules at compile time ---
8 # use strict;
9  
10 =head1 NAME
11  
12 par.pl - Make and run Perl Archives
13  
14 =head1 SYNOPSIS
15  
16 (Please see L<pp> for convenient ways to make self-contained
17 executables, scripts or PAR archives from perl programs.)
18  
19 To make a I<PAR distribution> from a CPAN module distribution:
20  
21 % par.pl -p # make a PAR dist under the current path
22 % par.pl -p Foo-0.01 # assume unpacked CPAN dist in Foo-0.01/
23  
24 To manipulate a I<PAR distribution>:
25  
26 % par.pl -i Foo-0.01-i386-freebsd-5.8.0.par # install
27 % par.pl -i http://foo.com/Foo-0.01 # auto-appends archname + perlver
28 % par.pl -i cpan://AUTRIJUS/PAR-0.74 # uses CPAN author directory
29 % par.pl -u Foo-0.01-i386-freebsd-5.8.0.par # uninstall
30 % par.pl -s Foo-0.01-i386-freebsd-5.8.0.par # sign
31 % par.pl -v Foo-0.01-i386-freebsd-5.8.0.par # verify
32  
33 To use F<Hello.pm> from F<./foo.par>:
34  
35 % par.pl -A./foo.par -MHello
36 % par.pl -A./foo -MHello # the .par part is optional
37  
38 Same thing, but search F<foo.par> in the F<@INC>;
39  
40 % par.pl -Ifoo.par -MHello
41 % par.pl -Ifoo -MHello # ditto
42  
43 Run F<test.pl> or F<script/test.pl> from F<foo.par>:
44  
45 % par.pl foo.par test.pl # looks for 'main.pl' by default,
46 # otherwise run 'test.pl'
47  
48 To make a self-containing script containing a PAR file :
49  
50 % par.pl -O./foo.pl foo.par
51 % ./foo.pl test.pl # same as above
52  
53 To embed the necessary non-core modules and shared objects for PAR's
54 execution (like C<Zlib>, C<IO>, C<Cwd>, etc), use the B<-b> flag:
55  
56 % par.pl -b -O./foo.pl foo.par
57 % ./foo.pl test.pl # runs anywhere with core modules installed
58  
59 If you also wish to embed I<core> modules along, use the B<-B> flag
60 instead:
61  
62 % par.pl -B -O./foo.pl foo.par
63 % ./foo.pl test.pl # runs anywhere with the perl interpreter
64  
65 This is particularly useful when making stand-alone binary
66 executables; see L<pp> for details.
67  
68 =head1 DESCRIPTION
69  
70 This stand-alone command offers roughly the same feature as C<perl
71 -MPAR>, except that it takes the pre-loaded F<.par> files via
72 C<-Afoo.par> instead of C<-MPAR=foo.par>.
73  
74 Additionally, it lets you convert a CPAN distribution to a PAR
75 distribution, as well as manipulate such distributions. For more
76 information about PAR distributions, see L<PAR::Dist>.
77  
78 =head2 Binary PAR loader (L<parl>)
79  
80 If you have a C compiler, or a pre-built binary package of B<PAR> is
81 available for your platform, a binary version of B<par.pl> will also be
82 automatically installed as B<parl>. You can use it to run F<.par> files:
83  
84 # runs script/run.pl in archive, uses its lib/* as libraries
85 % parl myapp.par run.pl # runs run.pl or script/run.pl in myapp.par
86 % parl otherapp.pl # also runs normal perl scripts
87  
88 However, if the F<.par> archive contains either F<main.pl> or
89 F<script/main.pl>, it is used instead:
90  
91 % parl myapp.par run.pl # runs main.pl, with 'run.pl' as @ARGV
92  
93 Finally, the C<-O> option makes a stand-alone binary executable from a
94 PAR file:
95  
96 % parl -B -Omyapp myapp.par
97 % ./myapp # run it anywhere without perl binaries
98  
99 With the C<--par-options> flag, generated binaries can act as C<parl>
100 to pack new binaries:
101  
102 % ./myapp --par-options -Omyap2 myapp.par # identical to ./myapp
103 % ./myapp --par-options -Omyap3 myap3.par # now with different PAR
104  
105 =head2 Stand-alone executable format
106  
107 The format for the stand-alone executable is simply concatenating the
108 following elements:
109  
110 =over 4
111  
112 =item * The executable itself
113  
114 Either in plain-text (F<par.pl>) or native executable format (F<parl>
115 or F<parl.exe>).
116  
117 =item * Any number of embedded files
118  
119 These are typically used for bootstrapping PAR's various XS dependencies.
120 Each section contains:
121  
122 =over 4
123  
124 =item The magic string "C<FILE>"
125  
126 =item Length of file name in C<pack('N')> format plus 9
127  
128 =item 8 bytes of hex-encoded CRC32 of file content
129  
130 =item A single slash ("C</>")
131  
132 =item The file name (without path)
133  
134 =item File length in C<pack('N')> format
135  
136 =item The file's content (not compressed)
137  
138 =back
139  
140 =item * One PAR file
141  
142 This is just a zip file beginning with the magic string "C<PK\003\004>".
143  
144 =item * Ending section
145  
146 The pre-computed cache name. A pack('Z40') string of the value of -T
147 (--tempcache) or the hash of the file, followed by C<\0CACHE>. The hash
148 of the file is calculated with L<Digest::SHA>.
149  
150 A pack('N') number of the total length of FILE and PAR sections,
151 followed by a 8-bytes magic string: "C<\012PAR.pm\012>".
152  
153 =back
154  
155 =cut
156  
157 my ($PAR_MAGIC, $FILE_offset_size, $cache_name_size);
158 # NOTE: must initialize them in BEGIN as they are used in BEGIN below
159 BEGIN {
160 $PAR_MAGIC = "\nPAR.pm\n";
161 $FILE_offset_size = 4; # pack("N")
162 $cache_name_size = 40;
163 $PKZIP_MAGIC = "PK\003\004";
164 }
165  
166  
167 # Search $fh for the "\nPAR.pm\n signature backward from the end of the file
168 sub find_par_magic
169 {
170 my ($fh) = @_;
171  
172 my $chunk_size = 64 * 1024;
173 my $buf;
174 my $size = -s $fh;
175  
176 my $pos = ($size-1) - ($size-1) % $chunk_size; # NOTE: $pos is a multiple of $chunk_size
177 while ($pos >= 0) {
178 seek $fh, $pos, 0;
179 read $fh, $buf, $chunk_size + length($PAR_MAGIC);
180 if ((my $i = rindex($buf, $PAR_MAGIC)) >= 0) {
181 return $pos + $i;
182 }
183 $pos -= $chunk_size;
184 }
185 return -1;
186 }
187  
188 my ($par_temp, $progname, @tmpfile, %ModuleCache);
189 END { if ($ENV{PAR_CLEAN}) {
190 require File::Temp;
191 require File::Basename;
192 require File::Spec;
193 my $topdir = File::Basename::dirname($par_temp);
194 outs(qq[Removing files in "$par_temp"]);
195 File::Find::finddepth(sub { ( -d ) ? rmdir : unlink }, $par_temp);
196 rmdir $par_temp;
197 # Don't remove topdir because this causes a race with other apps
198 # that are trying to start.
199  
200 if (-d $par_temp && $^O ne 'MSWin32') {
201 # Something went wrong unlinking the temporary directory. This
202 # typically happens on platforms that disallow unlinking shared
203 # libraries and executables that are in use. Unlink with a background
204 # shell command so the files are no longer in use by this process.
205 # Don't do anything on Windows because our parent process will
206 # take care of cleaning things up.
207  
208 my $tmp = new File::Temp(
209 TEMPLATE => 'tmpXXXXX',
210 DIR => File::Basename::dirname($topdir),
211 SUFFIX => '.cmd',
212 UNLINK => 0,
213 );
214 my $filename = $tmp->filename;
215  
216 print $tmp <<"...";
217 #!/bin/sh
218 x=1; while [ \$x -lt 10 ]; do
219 rm -rf '$par_temp'
220 if [ \! -d '$par_temp' ]; then
221 break
222 fi
223 sleep 1
224 x=`expr \$x + 1`
225 done
226 rm '$filename'
227 ...
228 close $tmp;
229  
230 chmod 0700, $filename;
231 my $cmd = "$filename >/dev/null 2>&1 &";
232 system($cmd);
233 outs(qq[Spawned background process to perform cleanup: $filename]);
234 }
235 } }
236  
237  
238 BEGIN {
239 Internals::PAR::BOOT() if defined &Internals::PAR::BOOT;
240  
241 eval {
242  
243 _par_init_env();
244  
245 my $quiet = !$ENV{PAR_DEBUG};
246  
247 # fix $progname if invoked from PATH
248 my %sys = (
249 path_sep => ($^O =~ /^MSWin/ ? ';' : ':'),
250 _exe => ($^O =~ /^(?:MSWin|OS2|cygwin)/ ? '.exe' : ''),
251 _delim => ($^O =~ /^MSWin|OS2/ ? '\\' : '/'),
252 );
253  
254 _set_progname();
255 outs(qq[\$progname = "$progname"]);
256  
257 _set_par_temp();
258 outs(qq[\$ENV{PAR_TEMP} = "$ENV{PAR_TEMP}"]);
259  
260 # Magic string checking and extracting bundled modules {{{
261 my ($start_pos, $start_of_FILE_section);
262 MAGIC: {
263 local $SIG{__WARN__} = sub {};
264  
265 # Check file type, get start of data section {{{
266 unless (open _FH, '<:raw', $progname) {
267 outs(qq[Can't read from file "$progname"]); # don't use $! here as it requires Errno.pm
268 last MAGIC;
269 }
270  
271 # Search for the "\nPAR.pm\n signature backward from the end of the file
272 my $magic_pos = find_par_magic(*_FH);
273 if ($magic_pos < 0) {
274 outs(qq[Can't find magic string "$PAR_MAGIC" in file "$progname"]);
275 last MAGIC;
276 }
277 outs("Found PAR magic at position $magic_pos");
278  
279 # Check for "\0CACHE" 4 bytes below the signature
280 seek _FH, $magic_pos - $FILE_offset_size - length("\0CACHE"), 0;
281 read _FH, $buf, length("\0CACHE");
282 if ($buf ne "\0CACHE" && $buf ne "\0CLEAN") {
283 outs("No cache marker found");
284 last MAGIC;
285 }
286 outs(qq[Cache marker "$buf" found]);
287  
288 # Seek 4 bytes backward from the signature to get the offset of the
289 # first embedded FILE, then seek to it
290 seek _FH, $magic_pos - $FILE_offset_size, 0;
291 read _FH, $buf, $FILE_offset_size;
292 my $offset = unpack("N", $buf);
293 outs("Offset from start of FILEs is $offset");
294 seek _FH, $magic_pos - $FILE_offset_size - $offset, 0;
295 $start_of_FILE_section = tell _FH;
296  
297 # }}}
298  
299 # Extracting each file into memory {{{
300 my %require_list;
301 read _FH, $buf, 4; # read the first "FILE"
302 while ($buf eq "FILE") {
303 read _FH, $buf, 4;
304 read _FH, $buf, unpack("N", $buf);
305  
306 my $fullname = $buf;
307 outs(qq[Unpacking FILE "$fullname"...]);
308 my $crc = ( $fullname =~ s|^([a-f\d]{8})/|| ) ? $1 : undef;
309 my ($basename, $ext) = ($buf =~ m|(?:.*/)?(.*)(\..*)|);
310  
311 read _FH, $buf, 4;
312 read _FH, $buf, unpack("N", $buf);
313  
314 if (defined($ext) and $ext !~ /\.(?:pm|pl|ix|al)$/i) {
315 my $filename = _save_as("$crc$ext", $buf, 0755);
316 $PAR::Heavy::FullCache{$fullname} = $filename;
317 $PAR::Heavy::FullCache{$filename} = $fullname;
318 }
319 elsif ( $fullname =~ m|^/?shlib/| and defined $ENV{PAR_TEMP} ) {
320 my $filename = _save_as("$basename$ext", $buf, 0755);
321 outs("SHLIB: $filename\n");
322 }
323 else {
324 $ModuleCache{$fullname} = {
325 buf => $buf,
326 crc => $crc,
327 name => $fullname,
328 };
329 $require_list{$fullname}++;
330 }
331 read _FH, $buf, 4;
332 }
333 # }}}
334  
335 local @INC = (sub {
336 my ($self, $module) = @_;
337  
338 return if ref $module or !$module;
339  
340 my $info = $ModuleCache{$module};
341 return unless $info;
342  
343 delete $require_list{$module};
344  
345 $INC{$module} = "/loader/$info/$module";
346  
347 if ($ENV{PAR_CLEAN} and defined(&IO::File::new)) {
348 my $fh = IO::File->new_tmpfile or die "Can't create temp file: $!";
349 $fh->binmode();
350 $fh->print($info->{buf});
351 $fh->seek(0, 0);
352 return $fh;
353 }
354 else {
355 my $filename = _save_as("$info->{crc}.pm", $info->{buf});
356 $info->{file} = $filename;
357  
358 open my $fh, '<:raw', $filename or die qq[Can't read "$filename": $!];
359 return $fh;
360 }
361  
362 die "Bootstrapping failed: can't find module $module!";
363 }, @INC);
364  
365 # Now load all bundled files {{{
366  
367 # initialize shared object processing
368 require XSLoader;
369 require PAR::Heavy;
370 require Carp::Heavy;
371 require Exporter::Heavy;
372 PAR::Heavy::_init_dynaloader();
373  
374 # now let's try getting helper modules from within
375 require IO::File;
376  
377 # load rest of the group in
378 while (my $filename = (sort keys %require_list)[0]) {
379 #local $INC{'Cwd.pm'} = __FILE__ if $^O ne 'MSWin32';
380 unless ($INC{$filename} or $filename =~ /BSDPAN/) {
381 # require modules, do other executable files
382 if ($filename =~ /\.pmc?$/i) {
383 require $filename;
384 }
385 else {
386 # Skip ActiveState's sitecustomize.pl file:
387 do $filename unless $filename =~ /sitecustomize\.pl$/;
388 }
389 }
390 delete $require_list{$filename};
391 }
392  
393 # }}}
394  
395 if ($buf ne $PKZIP_MAGIC) {
396 outs(qq[No zip found after FILE section in file "$progname"]);
397 last MAGIC ;
398 }
399  
400 $start_pos = (tell _FH) - 4; # start of zip
401 }
402 # }}}
403  
404 # Argument processing {{{
405 my @par_args;
406 my ($out, $bundle, $logfh, $cache_name);
407  
408 delete $ENV{PAR_APP_REUSE}; # sanitize (REUSE may be a security problem)
409  
410 # Don't swallow arguments for compiled executables without --par-options
411 if (!$start_pos or ($ARGV[0] eq '--par-options' && shift)) {
412 my %dist_cmd = qw(
413 p blib_to_par
414 i install_par
415 u uninstall_par
416 s sign_par
417 v verify_par
418 );
419  
420 # if the app is invoked as "appname --par-options --reuse PROGRAM @PROG_ARGV",
421 # use the app to run the given perl code instead of anything from the
422 # app itself (but still set up the normal app environment and @INC)
423 if (@ARGV and $ARGV[0] eq '--reuse') {
424 shift @ARGV;
425 $ENV{PAR_APP_REUSE} = shift @ARGV;
426 }
427 else { # normal parl behaviour
428  
429 my @add_to_inc;
430 while (@ARGV) {
431 $ARGV[0] =~ /^-([AIMOBLbqpiusTv])(.*)/ or last;
432  
433 if ($1 eq 'I') {
434 push @add_to_inc, $2;
435 }
436 elsif ($1 eq 'M') {
437 eval "use $2";
438 }
439 elsif ($1 eq 'A') {
440 unshift @par_args, $2;
441 }
442 elsif ($1 eq 'O') {
443 $out = $2;
444 }
445 elsif ($1 eq 'b') {
446 $bundle = 'site';
447 }
448 elsif ($1 eq 'B') {
449 $bundle = 'all';
450 }
451 elsif ($1 eq 'q') {
452 $quiet = 1;
453 }
454 elsif ($1 eq 'L') {
455 open $logfh, ">>", $2 or die qq[Can't open log file "$2": $!];
456 }
457 elsif ($1 eq 'T') {
458 $cache_name = $2;
459 }
460  
461 shift(@ARGV);
462  
463 if (my $cmd = $dist_cmd{$1}) {
464 delete $ENV{'PAR_TEMP'};
465 init_inc();
466 require PAR::Dist;
467 &{"PAR::Dist::$cmd"}() unless @ARGV;
468 &{"PAR::Dist::$cmd"}($_) for @ARGV;
469 exit;
470 }
471 }
472  
473 unshift @INC, @add_to_inc;
474 }
475 }
476  
477 # XXX -- add --par-debug support!
478  
479 # }}}
480  
481 # Output mode (-O) handling {{{
482 if ($out) {
483 {
484 #local $INC{'Cwd.pm'} = __FILE__ if $^O ne 'MSWin32';
485 require IO::File;
486 require Archive::Zip;
487 require Digest::SHA;
488 }
489  
490 my $par = shift(@ARGV);
491 my $zip;
492  
493  
494 if (defined $par) {
495 open my $fh, '<:raw', $par or die qq[Can't find par file "$par": $!];
496 bless($fh, 'IO::File');
497  
498 $zip = Archive::Zip->new;
499 ( $zip->readFromFileHandle($fh, $par) == Archive::Zip::AZ_OK() )
500 or die qq[Error reading zip archive "$par"];
501 }
502  
503  
504 # Extract the "par" dictionary from META.yml in $zip
505 my %meta_par = do {
506 if ($zip and my $meta = $zip->contents('META.yml')) {
507 $meta =~ s/.*^par:$//ms;
508 $meta =~ s/^\S.*//ms;
509 $meta =~ /^ ([^:]+): (.+)$/mg;
510 }
511 };
512  
513 # Open input and output files {{{
514  
515 if (defined $par) {
516 open my $ph, '<:raw', $par or die qq[Can't read par file "$par": $!];
517 my $buf;
518 read $ph, $buf, 4;
519 die qq["$par" is not a par file] unless $buf eq $PKZIP_MAGIC;
520 close $ph;
521 }
522  
523 CreatePath($out) ;
524  
525 my $fh = IO::File->new(
526 $out,
527 IO::File::O_CREAT() | IO::File::O_RDWR() | IO::File::O_TRUNC(),
528 0777,
529 ) or die qq[Can't create file "$out": $!];
530 $fh->binmode();
531  
532 seek _FH, 0, 0;
533  
534 my $loader;
535 if (defined $start_of_FILE_section) {
536 read _FH, $loader, $start_of_FILE_section;
537 } else {
538 local $/ = undef;
539 $loader = <_FH>;
540 }
541  
542 if (!$ENV{PAR_VERBATIM} and $loader =~ /^(?:#!|\@rem)/) {
543 require PAR::Filter::PodStrip;
544 PAR::Filter::PodStrip->apply(\$loader, $0);
545 }
546  
547 $fh->print($loader)
548 or die qq[Error writing loader to "$out": $!];
549 # }}}
550  
551 # Write bundled modules {{{
552 if ($bundle) {
553 require PAR::Heavy;
554 PAR::Heavy::_init_dynaloader();
555  
556 init_inc();
557  
558 require_modules();
559  
560 # NOTE: use $Config::Config{...} since we only "require" (*not* "use") it - no import
561 my @inc = grep { !/BSDPAN/ }
562 grep {
563 ($bundle ne 'site') or
564 ($_ ne $Config::Config{archlibexp} and
565 $_ ne $Config::Config{privlibexp});
566 } @INC;
567  
568 # normalize paths (remove trailing or multiple consecutive slashes)
569 s|/+|/|g, s|/$|| foreach @inc;
570  
571 # Now determine the files loaded above by require_modules():
572 # Perl source files are found in values %INC and DLLs are
573 # found in @DynaLoader::dl_shared_objects.
574 my %files;
575 $files{$_}++ for @DynaLoader::dl_shared_objects, values %INC;
576  
577 my $lib_ext = $Config::Config{lib_ext}; # XXX lib_ext vs dlext ?
578 my %written;
579  
580 foreach my $key (sort keys %files) {
581 my ($file, $name);
582  
583 if (defined(my $fc = $PAR::Heavy::FullCache{$key})) {
584 ($file, $name) = ($key, $fc);
585 }
586 else {
587 foreach my $dir (@inc) {
588 if ($key =~ m|^\Q$dir\E/(.*)$|i) {
589 ($file, $name) = ($key, $1);
590 last;
591 }
592 if ($key =~ m|^/loader/[^/]+/(.*)$|) {
593 if (my $ref = $ModuleCache{$1}) {
594 ($file, $name) = ($ref, $1);
595 last;
596 }
597 if (-f "$dir/$1") {
598 ($file, $name) = ("$dir/$1", $1);
599 last;
600 }
601 }
602 }
603 }
604 # There are legitimate reasons why we couldn't find $name and $file for a $key:
605 # - cperl has e.g. $INC{"XSLoader.pm"} = "XSLoader.c",
606 # $INC{"DynaLoader.pm"}' = "dlboot_c.PL"
607 next unless defined $name;
608  
609 next if $written{$name}++;
610 next if !ref($file) and $file =~ /\.\Q$lib_ext\E$/i;
611  
612 outs(sprintf(qq[Packing FILE "%s"...], ref $file ? $file->{name} : $file));
613 my $content;
614 if (ref($file)) {
615 $content = $file->{buf};
616 }
617 else {
618 local $/ = undef;
619 open my $th, '<:raw', $file or die qq[Can't read "$file": $!];
620 $content = <$th>;
621 close $th;
622  
623 PAR::Filter::PodStrip->apply(\$content, "<embedded>/$name")
624 if !$ENV{PAR_VERBATIM} and $name =~ /\.(?:pm|ix|al)$/i;
625  
626 PAR::Filter::PatchContent->new->apply(\$content, $file, $name);
627 }
628  
629 $fh->print("FILE",
630 pack('N', length($name) + 9),
631 sprintf("%08x/%s", Archive::Zip::computeCRC32($content), $name),
632 pack('N', length($content)),
633 $content)
634 or die qq[Error writing embedded FILE to "$out": $!];
635  
636 outs(qq[Written as "$name"]);
637 }
638 }
639 # }}}
640  
641 # Now write out the PAR and magic strings {{{
642 if ($zip) {
643 $zip->writeToFileHandle($fh) == Archive::Zip::AZ_OK
644 or die qq[Error writing zip part of "$out"];
645 }
646  
647 if ($meta_par{clean}) {
648 $fh->print("\0CLEAN");
649 }
650 else {
651 if (!defined $cache_name) {
652 my $ctx = Digest::SHA->new(1);
653 seek $fh, 0, 0;
654 $ctx->addfile($fh);
655 seek $fh, 0, 2;
656 $cache_name = $ctx->hexdigest;
657 }
658 # truncate $cache_name to 40 byes and fill with NULs if necessary
659 $cache_name = substr $cache_name, 0, $cache_name_size;
660 $cache_name .= "\0" x ($cache_name_size - length $cache_name);
661 $fh->print($cache_name,
662 "\0CACHE");
663 }
664  
665 # compute the offset from the end of $loader to end of "...\0CACHE" or "\0CLEAN"
666 my $offset = $fh->tell - length($loader);
667 $fh->print(pack('N', $offset),
668 $PAR_MAGIC);
669  
670 $fh->close or die qq[Error writing trailer of "$out": $!];
671 chmod 0755, $out;
672 # }}}
673  
674 exit;
675 }
676 # }}}
677  
678 # Prepare $progname into PAR file cache {{{
679 {
680 last unless defined $start_pos;
681  
682 _fix_progname();
683  
684 # Now load the PAR file and put it into PAR::LibCache {{{
685 require PAR;
686 PAR::Heavy::_init_dynaloader();
687  
688  
689 {
690 #local $INC{'Cwd.pm'} = __FILE__ if $^O ne 'MSWin32';
691 require File::Find;
692 require Archive::Zip;
693 }
694  
695 my $fh = IO::File->new; # Archive::Zip operates on an IO::Handle
696 $fh->fdopen(fileno(_FH), 'r') or die qq[fdopen() failed: $!];
697  
698 # Temporarily increase the chunk size for Archive::Zip so that it will find the EOCD
699 # even if lots of stuff has been appended to the pp'ed exe (e.g. by OSX codesign).
700 Archive::Zip::setChunkSize(-s _FH);
701 my $zip = Archive::Zip->new;
702 ($zip->readFromFileHandle($fh, $progname) == Archive::Zip::AZ_OK())
703 or die qq[Error reading zip archive "$progname"];
704 Archive::Zip::setChunkSize(64 * 1024);
705  
706 push @PAR::LibCache, $zip;
707 $PAR::LibCache{$progname} = $zip;
708  
709  
710 outs("Extracting zip...");
711 if (defined $ENV{PAR_TEMP}) { # should be set at this point!
712 foreach my $member ( $zip->members ) {
713 next if $member->isDirectory;
714 my $member_name = $member->fileName;
715 next unless $member_name =~ m{
716 ^
717 /?shlib/
718 (?:$Config::Config{version}/)?
719 (?:$Config::Config{archname}/)?
720 ([^/]+)
721 $
722 }x;
723 my $extract_name = $1;
724 my $dest_name = File::Spec->catfile($ENV{PAR_TEMP}, $extract_name);
725 if (-f $dest_name && -s _ == $member->uncompressedSize()) {
726 outs(qq[Skipping "$member_name" since it already exists at "$dest_name"]);
727 } else {
728 outs(qq[Extracting "$member_name" to "$dest_name"...]);
729 ($member->extractToFileNamed($dest_name) == Archive::Zip::AZ_OK())
730 or die qq[Error extracting zip member to "$dest_name"];
731 chmod(0555, $dest_name) if $^O eq "hpux";
732 }
733 }
734 }
735 # }}}
736 }
737 # }}}
738  
739 # If there's no main.pl to run, show usage {{{
740 unless ($PAR::LibCache{$progname}) {
741 die << "." unless @ARGV;
742 Usage: $0 [ -Alib.par ] [ -Idir ] [ -Mmodule ] [ src.par ] [ program.pl ]
743 $0 [ -B|-b ] [-Ooutfile] src.par
744 .
745 $ENV{PAR_PROGNAME} = $progname = $0 = shift(@ARGV);
746 }
747 # }}}
748  
749 sub CreatePath {
750 my ($name) = @_;
751  
752 require File::Basename;
753 my ($basename, $path, $ext) = File::Basename::fileparse($name, ('\..*'));
754  
755 require File::Path;
756  
757 File::Path::mkpath($path) unless(-e $path); # mkpath dies with error
758 }
759  
760 sub require_modules {
761  
762 require lib;
763 require DynaLoader;
764 require integer;
765 require strict;
766 require warnings;
767 require vars;
768 require Carp;
769 require Carp::Heavy;
770 require Errno;
771 require Exporter::Heavy;
772 require Exporter;
773 require Fcntl;
774 require File::Temp;
775 require File::Spec;
776 require XSLoader;
777 require Config;
778 require IO::Handle;
779 require IO::File;
780 require Compress::Zlib;
781 require Archive::Zip;
782 require Digest::SHA;
783 require PAR;
784 require PAR::Heavy;
785 require PAR::Dist;
786 require PAR::Filter::PodStrip;
787 require PAR::Filter::PatchContent;
788 require attributes;
789 eval { require Cwd };
790 eval { require Win32 };
791 eval { require Scalar::Util };
792 eval { require Archive::Unzip::Burst };
793 eval { require Tie::Hash::NamedCapture };
794 eval { require PerlIO; require PerlIO::scalar };
795 eval { require utf8 };
796 }
797  
798 # The C version of this code appears in myldr/mktmpdir.c
799 # This code also lives in PAR::SetupTemp as set_par_temp_env!
800 sub _set_par_temp {
801 if (defined $ENV{PAR_TEMP} and $ENV{PAR_TEMP} =~ /(.+)/) {
802 $par_temp = $1;
803 return;
804 }
805  
806 foreach my $path (
807 (map $ENV{$_}, qw( PAR_TMPDIR TMPDIR TEMPDIR TEMP TMP )),
808 qw( C:\\TEMP /tmp . )
809 ) {
810 next unless defined $path and -d $path and -w $path;
811 my $username;
812 my $pwuid;
813 # does not work everywhere:
814 eval {($pwuid) = getpwuid($>) if defined $>;};
815  
816 if ( defined(&Win32::LoginName) ) {
817 $username = &Win32::LoginName;
818 }
819 elsif (defined $pwuid) {
820 $username = $pwuid;
821 }
822 else {
823 $username = $ENV{USERNAME} || $ENV{USER} || 'SYSTEM';
824 }
825  
826 my $stmpdir = "$path$sys{_delim}par-".unpack("H*", $username);
827 mkdir $stmpdir, 0755;
828  
829 my $cache_dir;
830 if ($ENV{PAR_CLEAN}) {
831 $cache_dir = "temp-$$";
832 }
833 else {
834 open my $fh, "<:raw", $progname or die qq[Can't read "$progname": $!];
835 if ((my $magic_pos = find_par_magic($fh)) >= 0) {
836 seek $fh, $magic_pos
837 - $FILE_offset_size
838 - length("\0CACHE"), 0;
839 my $buf;
840 read $fh, $buf, length("\0CACHE");
841 if ($buf eq "\0CACHE") {
842 seek $fh, $magic_pos
843 - $FILE_offset_size
844 - length("\0CACHE")
845 - $cache_name_size, 0;
846 read $fh, $buf, $cache_name_size;
847 $buf =~ s/\0//g;
848 $cache_dir = "cache-$buf";
849 }
850 }
851 close $fh;
852 }
853 if (!$cache_dir) {
854 $cache_dir = "temp-$$";
855 $ENV{PAR_CLEAN} = 1;
856 }
857 $stmpdir .= "$sys{_delim}$cache_dir";
858  
859 mkdir $stmpdir, 0755;
860 $ENV{PAR_TEMP} = $stmpdir;
861 last;
862 }
863  
864 $par_temp = $1 if $ENV{PAR_TEMP} and $ENV{PAR_TEMP} =~ /(.+)/;
865 }
866  
867  
868 # check if $name (relative to $par_temp) already exists;
869 # if not, create a file with a unique temporary name,
870 # fill it with $contents, set its file mode to $mode if present;
871 # finaly rename it to $name;
872 # in any case return the absolute filename
873 sub _save_as {
874 my ($name, $contents, $mode) = @_;
875  
876 my $fullname = "$par_temp/$name";
877 unless (-e $fullname) {
878 my $tempname = "$fullname.$$";
879  
880 my $fh;
881 (open $fh, '>:raw', $tempname)
882 && (print $fh $contents)
883 && (close $fh)
884 or die qq[Error writing "$tempname": $!];
885 chmod $mode, $tempname if defined $mode;
886  
887 rename($tempname, $fullname) or unlink($tempname);
888 # NOTE: The rename() error presumably is something like ETXTBSY
889 # (scenario: another process was faster at extraction $fullname
890 # than us and is already using it in some way); anyway,
891 # let's assume $fullname is "good" and clean up our copy.
892 }
893  
894 return $fullname;
895 }
896  
897 # same code lives in PAR::SetupProgname::set_progname
898 sub _set_progname {
899 if (defined $ENV{PAR_PROGNAME} and $ENV{PAR_PROGNAME} =~ /(.+)/) {
900 $progname = $1;
901 }
902  
903 $progname ||= $0;
904  
905 if ($ENV{PAR_TEMP} and index($progname, $ENV{PAR_TEMP}) >= 0) {
906 $progname = substr($progname, rindex($progname, $sys{_delim}) + 1);
907 }
908  
909 if (!$ENV{PAR_PROGNAME} or index($progname, $sys{_delim}) >= 0) {
910 if (open my $fh, '<', $progname) {
911 return if -s $fh;
912 }
913 if (-s "$progname$sys{_exe}") {
914 $progname .= $sys{_exe};
915 return;
916 }
917 }
918  
919 foreach my $dir (split /\Q$sys{path_sep}\E/, $ENV{PATH}) {
920 next if exists $ENV{PAR_TEMP} and $dir eq $ENV{PAR_TEMP};
921 $dir =~ s/\Q$sys{_delim}\E$//;
922 (($progname = "$dir$sys{_delim}$progname$sys{_exe}"), last)
923 if -s "$dir$sys{_delim}$progname$sys{_exe}";
924 (($progname = "$dir$sys{_delim}$progname"), last)
925 if -s "$dir$sys{_delim}$progname";
926 }
927 }
928  
929 sub _fix_progname {
930 $0 = $progname ||= $ENV{PAR_PROGNAME};
931 if (index($progname, $sys{_delim}) < 0) {
932 $progname = ".$sys{_delim}$progname";
933 }
934  
935 # XXX - hack to make PWD work
936 my $pwd = (defined &Cwd::getcwd) ? Cwd::getcwd()
937 : ((defined &Win32::GetCwd) ? Win32::GetCwd() : `pwd`);
938 chomp($pwd);
939 $progname =~ s/^(?=\.\.?\Q$sys{_delim}\E)/$pwd$sys{_delim}/;
940  
941 $ENV{PAR_PROGNAME} = $progname;
942 }
943  
944 sub _par_init_env {
945 if ( $ENV{PAR_INITIALIZED}++ == 1 ) {
946 return;
947 } else {
948 $ENV{PAR_INITIALIZED} = 2;
949 }
950  
951 for (qw( SPAWNED TEMP CLEAN DEBUG CACHE PROGNAME ) ) {
952 delete $ENV{"PAR_$_"};
953 }
954  
955 for (qw/ TMPDIR TEMP CLEAN DEBUG /) {
956 $ENV{"PAR_$_"} = $ENV{"PAR_GLOBAL_$_"} if exists $ENV{"PAR_GLOBAL_$_"};
957 }
958  
959 if ($ENV{PAR_TEMP}) {
960 delete $ENV{PAR_CLEAN};
961 }
962 }
963  
964 sub outs {
965 return if $quiet;
966 if ($logfh) {
967 print $logfh "@_\n";
968 }
969 else {
970 print "@_\n";
971 }
972 }
973  
974 sub init_inc {
975 require Config;
976 # NOTE: use $Config::Config{...} since we only "require" (*not* "use") it - no import
977 push @INC, grep defined, map $Config::Config{$_}, qw(
978 archlibexp privlibexp sitearchexp sitelibexp
979 vendorarchexp vendorlibexp
980 );
981 }
982  
983 ########################################################################
984 # The main package for script execution
985  
986 package main;
987  
988 require PAR;
989 unshift @INC, \&PAR::find_par;
990 PAR->import(@par_args);
991  
992 die qq[par.pl: Can't open perl script "$progname": No such file or directory\n]
993 unless -e $progname;
994  
995 do $progname;
996 CORE::exit($1) if ($@ =~/^_TK_EXIT_\((\d+)\)/);
997 die $@ if $@;
998  
999 };
1000  
1001 $::__ERROR = $@ if $@;
1002 }
1003  
1004 CORE::exit($1) if ($::__ERROR =~/^_TK_EXIT_\((\d+)\)/);
1005 die $::__ERROR if $::__ERROR;
1006  
1007 1;
1008  
1009 =head1 SEE ALSO
1010  
1011 L<PAR>, L<PAR::Dist>, L<parl>, L<pp>
1012  
1013 =head1 AUTHORS
1014  
1015 Audrey Tang E<lt>cpan@audreyt.orgE<gt>,
1016 Steffen Mueller E<lt>smueller@cpan.orgE<gt>
1017  
1018 You can write
1019 to the mailing list at E<lt>par@perl.orgE<gt>, or send an empty mail to
1020 E<lt>par-subscribe@perl.orgE<gt> to participate in the discussion.
1021  
1022 Please submit bug reports to E<lt>bug-par-packer@rt.cpan.orgE<gt>.
1023  
1024 =head1 COPYRIGHT
1025  
1026 Copyright 2002-2009 by Audrey Tang E<lt>cpan@audreyt.orgE<gt>.
1027  
1028 Neither this program nor the associated L<parl> program impose any
1029 licensing restrictions on files generated by their execution, in
1030 accordance with the 8th article of the Artistic License:
1031  
1032 "Aggregation of this Package with a commercial distribution is
1033 always permitted provided that the use of this Package is embedded;
1034 that is, when no overt attempt is made to make this Package's
1035 interfaces visible to the end user of the commercial distribution.
1036 Such use shall not be construed as a distribution of this Package."
1037  
1038 Therefore, you are absolutely free to place any license on the resulting
1039 executable, as long as the packed 3rd-party libraries are also available
1040 under the Artistic License.
1041  
1042 This program is free software; you can redistribute it and/or modify it
1043 under the same terms as Perl itself.
1044  
1045 See F<LICENSE>.
1046  
1047 =cut
1048  
1049 __END__