File Coverage

lib/App/PP/Autolink.pm
Criterion Covered Total %
statement 47 334 14.0
branch 0 114 0.0
condition 0 20 0.0
subroutine 16 31 51.6
pod 0 10 0.0
total 63 509 12.3


line stmt bran cond sub pod time code
1             # logic initially based on pp_simple.pl
2             # Should cache the Module::Scandeps result
3             # and then clean it up after using it.
4            
5             package App::PP::Autolink;
6            
7 1     1   379676 use strict;
  1         3  
  1         47  
8 1     1   6 use warnings;
  1         2  
  1         77  
9 1     1   22 use 5.014;
  1         3  
10            
11 1     1   7 use Carp;
  1         2  
  1         171  
12 1     1   779 use English qw / -no_match_vars /;
  1         1094  
  1         9  
13            
14 1     1   474 use File::Which qw( which );
  1         2  
  1         90  
15 1     1   787 use Capture::Tiny qw/ capture /;
  1         33476  
  1         93  
16 1     1   10 use List::Util 1.45 qw( uniq any first );
  1         27  
  1         111  
17 1     1   835 use File::Find::Rule qw/ rule find /;
  1         12629  
  1         9  
18 1     1   1169 use Path::Tiny qw/ path /;
  1         18925  
  1         100  
19             #use File::Temp qw/ tempfile /;
20 1     1   1326 use Module::ScanDeps;
  1         35173  
  1         118  
21 1     1   1746 use Env qw /@PATH/;
  1         5022  
  1         7  
22            
23 1     1   226 use Config;
  1         3  
  1         47  
24 1     1   1158 use Getopt::ArgvFile default=>1;
  1         5991  
  1         8  
25 1     1   10638 use Getopt::Long qw / GetOptionsFromArray :config pass_through /;
  1         28917  
  1         18  
26            
27             our $VERSION = '2.14';
28            
29 1     1   564 use constant CASE_INSENSITIVE_OS => ($^O eq 'MSWin32');
  1         3  
  1         6972  
30            
31             my $RE_DLL_EXT = qr/\.$Config::Config{so}$/i;
32             if ($^O eq 'darwin') {
33             $RE_DLL_EXT = qr/\.($Config::Config{so}|bundle)$/i;
34             }
35            
36             my $ldd_exe = which('ldd');
37            
38            
39             sub new {
40 0     0 0   my ($class, @args) = @_;
41            
42 0           my $self = bless {}, $class;
43            
44             $self->{autolink_list_method}
45 0 0         = $^O eq 'MSWin32' ? 'get_autolink_list'
    0          
    0          
46             : $^O eq 'darwin' ? 'get_autolink_list_macos'
47             : $ldd_exe ? 'get_autolink_list_ldd'
48             # objdump behaves differently on linux (centos at least)
49             : die 'Unable to generate autolink list';
50            
51             # slightly messy, but issues with pass_through and --no-x
52 0           $self->{no_execute_flag} = not grep {$_ eq '-x'} @args;
  0            
53            
54             # Should trap any scandeps args (if diff from pp).
55 0           my @args_array = @args;
56 0           my @argv_linkers;
57            
58 0           GetOptionsFromArray (
59             \@args_array,
60             "link|l=s" => \@argv_linkers,
61             );
62 0           $self->{argv_linkers} = \@argv_linkers;
63 0           $self->{args_to_pass_to_pp} = \@args_array;
64            
65             # pp allows multiple .pl files.
66 0 0         my $script_fullname = $args[-1] or die 'no input file specified';
67 0           $self->{script_fullname} = $script_fullname;
68            
69 0           $self->{alien_sys_installs} = [];
70 0           $self->{alien_deps} = [];
71            
72 0           return $self;
73             }
74            
75             sub build {
76 0     0 0   my ($self) = @_;
77            
78             # reassemble the arg list
79 0           my $argv_linkers = $self->{argv_linkers};
80 0           my $args_array = $self->{args_to_pass_to_pp};
81             my @args_for_pp = (
82 0           (map {("--link" => $_)} @$argv_linkers),
  0            
83             @$args_array,
84             );
85            
86 0           my $method = $self->{autolink_list_method};
87 0           say 'Scanning dependent dynamic libs';
88 0           my @dll_list = $self->$method;
89 0           my $alien_sys_installs = $self->{alien_sys_installs};
90            
91             # two-step process to get unique paths
92 0           my %tmp = map {($_ => '--link')} (@dll_list, @$alien_sys_installs);
  0            
93 0           my @links = reverse %tmp;
94            
95 0 0         if (@$alien_sys_installs) {
96 0           say 'Alien sys dlls added: ' . join ' ', @$alien_sys_installs;
97 0           say '';
98             }
99             else {
100 0           say "No alien system dlls detected\n";
101             }
102            
103 0           say 'Detected link list: ' . join ' ', grep {$_ ne '--link'} @links;
  0            
104 0           say '';
105            
106 0           my @aliens = uniq @{$self->{alien_deps}};
  0            
107 0           my @alien_deps = map {; '-M' => $_} @aliens;
  0            
108 0           say 'Detected aliens: ' . join ' ', sort @aliens;
109 0           say '';
110            
111 0           my @command = (
112             'pp',
113             @links,
114             #"--cachedeps=$cache_file",
115             @alien_deps,
116             @args_for_pp,
117             );
118            
119 0           say 'CMD: ' . join ' ', @command;
120 0 0         system (@command) == 0
121             or die "system @command failed: $?";
122            
123 0           return;
124             }
125            
126            
127            
128             sub get_autolink_list {
129 0     0 0   my ($self) = @_;
130            
131 0           my $argv_linkers = $self->{argv_linkers};
132            
133 0 0         my $OBJDUMP = which('objdump') or die "objdump not found";
134            
135 0           my @exe_path = @PATH;
136            
137 0           my @system_paths;
138            
139 0 0         if ($OSNAME =~ /MSWin32/i) {
140             # skip anything under the C:\Windows folder,
141             # blank entries
142             # and no longer extant folders
143 0   0       my $system_root = $ENV{SystemRoot} || $ENV{WINDIR};
144             @system_paths
145 0           = map {path($_)->stringify} # otherwise we hit issues on SP5.36
146 0 0         grep {$_ and $_ =~ m|^\Q$system_root\E|i}
  0            
147             @exe_path;
148             @exe_path
149 0           = map {path($_)->stringify}
150 0 0 0       grep {$_ and (-e $_) and $_ !~ m|^\Q$system_root\E|i}
  0            
151             @exe_path;
152             #say "PATHS: " . join ' ', @exe_path;
153             }
154             # what to skip for linux or mac?
155            
156             # get all the DLLs in the path - saves repeated searching lower down
157             my @dll_files
158 0           = map {$_->stringify}
159 0           map {path($_)->children ( qr /$Config::Config{so}$/)}
  0            
160             @exe_path;
161            
162 0           if (CASE_INSENSITIVE_OS) {
163             @dll_files = map {lc $_} @dll_files;
164             }
165            
166 0           my %dll_file_hash;
167 0           foreach my $file (@dll_files) {
168 0           my $basename = path($file)->basename;
169 0   0       $dll_file_hash{$basename} //= $file; # we only want the first in the path
170             }
171            
172            
173             # lc is dirty and underhanded
174             # - need to find a different approach to get
175             # canonical file name while handling case,
176             # poss Win32::GetLongPathName
177 0           say "Getting dependent DLLs";
178 0           my @dlls = @$argv_linkers;
179 0           push @dlls,
180             $self->get_dep_dlls;
181            
182 0           if (CASE_INSENSITIVE_OS) {
183             @dlls = map {path ($_)->stringify} map {lc $_} @dlls;
184             }
185             #say join "\n", @dlls;
186            
187 0           my $re_skippers = $self->get_dll_skipper_regexp();
188 0           my %full_list;
189             my %searched_for;
190 0           my $iter = 0;
191            
192 0           my @missing;
193            
194             DLL_CHECK:
195 0           while (1) {
196 0           $iter++;
197 0           say "DLL check iter: $iter";
198             #say join ' ', @dlls;
199             my ( $stdout, $stderr, $exit ) = capture {
200 0     0     system( $OBJDUMP, '-p', @dlls );
201 0           };
202 0 0         if( $exit ) {
203 0           $stderr =~ s{\s+$}{};
204 0           warn "(@dlls):$exit: $stderr ";
205 0           exit;
206             }
207 0           @dlls = $stdout =~ /DLL.Name:\s*(\S+)/gmi;
208            
209 0           if (CASE_INSENSITIVE_OS) {
210             @dlls = map {lc $_} @dlls;
211             }
212            
213             # extra grep appears wasteful but useful for debug
214             # since we can easily disable it
215             @dlls
216             = sort
217 0           grep {!exists $full_list{$_}}
218 0           grep {$_ !~ /$re_skippers/}
  0            
219             uniq
220             @dlls;
221            
222 0 0         if (!@dlls) {
223 0           say 'no more DLLs';
224 0           last DLL_CHECK;
225             }
226            
227 0           my @dll2;
228 0           foreach my $file (@dlls) {
229 0 0         next if $searched_for{$file};
230            
231 0 0         if (exists $dll_file_hash{$file}) {
232 0           push @dll2, $dll_file_hash{$file};
233             }
234             else {
235 0           push @missing, $file;
236             }
237            
238 0           $searched_for{$file}++;
239             }
240 0           @dlls = uniq @dll2;
241 0           my $key_count = keys %full_list;
242 0           @full_list{@dlls} = (1) x @dlls;
243            
244             # did we add anything new?
245 0 0         last DLL_CHECK if $key_count == scalar keys %full_list;
246             }
247            
248 0           my @l2 = sort keys %full_list;
249            
250 0 0         if (@missing) {
251 0           my @missing2;
252             MISSING:
253 0           foreach my $file (uniq @missing) {
254             next MISSING
255 0 0   0     if any {; -e "$_/$file"} @system_paths;
  0            
256 0           push @missing2, $file;
257             }
258            
259 0 0         if (@missing2) {
260             say STDERR "\nUnable to locate these DLLS, packed script might not work: "
261 0           . join ' ', sort {$a cmp $b} @missing2;
  0            
262 0           say '';
263             }
264             }
265            
266 0 0         return wantarray ? @l2 : \@l2;
267             }
268            
269             sub _resolve_rpath_mac {
270 0     0     my ($source, $target) = @_;
271            
272 0           say "Resolving rpath for $source wrt $target";
273            
274             # clean up the target
275 0           $target =~ s|\@rpath/||;
276            
277 0           my @results = qx /otool -l $source/;
278 0           while (my $line = shift @results) {
279 0 0         last if $line =~ /LC_RPATH/;
280             }
281 0           my @lc_rpath_chunk;
282 0           while (my $line = shift @results) {
283 0 0         last if $line =~ /LC_/; # any other command
284 0           push @lc_rpath_chunk, $line;
285             }
286             my @paths
287 0           = map {s/\s\(offset.+$//r}
288 0           map {s/^\s+path //r}
289 0           grep {/^\s+path/}
  0            
290             @lc_rpath_chunk;
291 0           my $loader_path = path ($source)->parent->stringify;
292 0           my @checked_paths;
293 0           foreach my $path (@paths) {
294 0           chomp $path; # should be done above
295 0           $path =~ s/\@loader_path/$loader_path/;
296 0           $path = path($path, $target);
297 0 0         if ($path->exists) {
298 0           $path = $path->realpath->stringify;
299 0           push @checked_paths, $path;
300             }
301             }
302            
303             # should handle multiple paths
304 0           return $checked_paths[0];
305             }
306            
307             sub _resolve_loader_path_mac {
308 0     0     my ($source, $target) = @_;
309 0           say "Resolving loader_path for $source wrt $target";
310 0           my $source_path = path($source)->parent->stringify;
311 0           $target =~ s/\@loader_path/$source_path/;
312 0           return $target;
313             }
314            
315            
316             sub get_autolink_list_macos {
317 0     0 0   my ($self) = @_;
318            
319 0           my $argv_linkers = $self->{argv_linkers};
320            
321 0 0         my $OTOOL = which('otool') or die "otool not found";
322            
323 0           my @bundle_list = $self->get_dep_dlls;
324 0           my @libs_to_pack;
325             my %seen;
326            
327 0           my @target_libs = (
328             @$argv_linkers,
329             @bundle_list,
330             #'/usr/local/opt/libffi/lib/libffi.6.dylib',
331             #($pixbuf_query_loader,
332             #find_so_files ($gdk_pixbuf_dir) ) if $pack_gdkpixbuf,
333             );
334 0           while (my $lib = shift @target_libs) {
335 0           say "otool -L $lib";
336 0           my @lib_arr = qx /otool -L $lib/;
337 0 0         warn qq["otool -L $lib" failed\n]
338             if not $? == 0;
339 0           shift @lib_arr; # first result is dylib we called otool on
340             DEP_LIB:
341 0           foreach my $line (@lib_arr) {
342 0           $line =~ /^\s+(.+?)\s/;
343 0           my $dylib = $1;
344 0 0         if ($dylib =~ /\@rpath/i) {
    0          
345 0           my $orig_name = $dylib;
346 0           $dylib = _resolve_rpath_mac($lib, $dylib);
347 0 0         if (!defined $dylib) {
348 0           say STDERR "Cannot resolve rpath for $orig_name, dependency of $lib";
349 0           next DEP_LIB;
350             }
351             }
352             elsif ($dylib =~ /\@loader_path/) {
353 0           my $orig_name = $dylib;
354 0           $dylib = _resolve_loader_path_mac($lib, $dylib);
355             }
356 0 0         next if $seen{$dylib};
357 0 0         next if $dylib =~ m{^/System}; # skip system libs
358             #next if $dylib =~ m{^/usr/lib/system};
359 0 0         next if $dylib =~ m{^/usr/lib/libSystem};
360 0 0         next if $dylib =~ m{^/usr/lib/};
361 0 0         next if $dylib =~ m{\Qdarwin-thread-multi-2level/auto/share/dist/Alien\E}; # another alien
362 0           say "adding $dylib for $lib";
363 0           push @libs_to_pack, $dylib;
364 0           $seen{$dylib}++;
365             # add this dylib to the search set
366 0           push @target_libs, $dylib;
367             }
368             }
369            
370 0           @libs_to_pack = sort @libs_to_pack;
371            
372 0 0         return wantarray ? @libs_to_pack : \@libs_to_pack;
373             }
374            
375             sub get_autolink_list_ldd {
376 0     0 0   my ($self) = @_;
377            
378 0           my $argv_linkers = $self->{argv_linkers};
379            
380 0           my @bundle_list = $self->get_dep_dlls;
381 0           my @libs_to_pack;
382             my %seen;
383            
384 0           my $RE_skip = $self->get_ldd_skipper_regexp;
385            
386 0           my @target_libs = (
387             @$argv_linkers,
388             @bundle_list,
389             );
390 0           while (my $lib = shift @target_libs) {
391 0 0         if ($lib =~ $RE_skip) {
392 0           say "skipping $lib";
393 0           next;
394             }
395            
396 0           say "ldd $lib";
397 0           my $out = qx /ldd $lib/;
398 0 0         warn qq["ldd $lib" failed\n]
399             if not $? == 0;
400            
401             # much of this logic is from PAR::Packer
402             # https://github.com/rschupp/PAR-Packer/blob/04a133b034448adeb5444af1941a5d7947d8cafb/myldr/find_files_to_embed/ldd.pl#L47
403 0           my %dlls = $out =~ /^ \s* (\S+) \s* => \s* ( \/ \S+ ) /gmx;
404            
405             DLL:
406 0           foreach my $name (keys %dlls) {
407             #say "$name, $dlls{$name}";
408 0 0 0       if ($seen{$name} or $name =~ $RE_skip) {
409 0           delete $dlls{$name};
410 0           next DLL;
411             }
412            
413 0           $seen{$name}++;
414            
415 0           my $path = path($dlls{$name})->realpath;
416            
417             #say "Checking $name => $path";
418            
419 0 0 0       if (not -r $path) {
    0 0        
420 0           warn qq[# ldd reported strange path: $path\n];
421 0           delete $dlls{$name};
422             }
423             elsif (
424             #$path =~ m{^(?:/usr)?/lib(?:32|64)?/} # system lib
425             $path =~ $RE_skip
426             or $path =~ m{\Qdarwin-thread-multi-2level/auto/share/dist/Alien\E} # alien in share
427             or $name =~ m{^lib(?:c|gcc_s|stdc\+\+)\.} # should already be packed?
428             ) {
429             #say "skipping $name => $path";
430             #warn "re1" if $path =~ m{^(?:/usr)?/lib(?:32|64)/};
431             #warn "re2" if $path =~ m{\Qdarwin-thread-multi-2level/auto/share/dist/Alien\E};
432             #warn "re3" if $name =~ m{^lib(?:gcc_s|stdc\+\+)\.};
433 0           delete $dlls{$name};
434             }
435             }
436 0           push @target_libs, sort values %dlls;
437 0           push @libs_to_pack, sort values %dlls;
438             }
439            
440 0           @libs_to_pack = sort @libs_to_pack;
441            
442 0 0         return wantarray ? @libs_to_pack : \@libs_to_pack;
443             }
444            
445            
446             # needed for gdkpixbuf, when we support it
447             sub find_so_files {
448 0     0 0   my ($self, $target_dir) = @_;
449 0 0         return if !defined $target_dir;
450            
451 0           my @files = File::Find::Rule->extras({ follow => 1, follow_skip=>2 })
452             ->file()
453             ->name( qr/\.so$/ )
454             ->in( $target_dir );
455 0 0         return wantarray ? @files : \@files;
456             }
457            
458             sub get_ldd_skipper_regexp {
459 0     0 0   my ($self) = @_;
460 0           my @skip = qw /libm libc libpthread libdl/;
461 0           my $sk = join '|', @skip;
462 0           my $qr_skip = qr {\b(?:$sk)\.$Config::Config{so}};
463            
464 0           return $qr_skip;
465             }
466            
467             sub get_dll_skipper_regexp {
468 0     0 0   my ($self) = @_;
469            
470             # PAR packs these automatically these days.
471 0           my @skip = qw /
472             perl5\d\d
473             libstdc\+\+\-6
474             libgcc_s_seh\-1
475             libwinpthread\-1
476             libgcc_s_sjlj\-1
477             /;
478 0           my $sk = join '|', @skip;
479 0           my $qr_skip = qr /^(?:$sk)$RE_DLL_EXT$/;
480 0           return $qr_skip;
481             }
482            
483             # find dependent dlls
484             # could also adapt some of Module::ScanDeps::_compile_or_execute
485             # as it handles more edge cases
486             sub get_dep_dlls {
487 0     0 0   my ($self) = @_;
488            
489 0           my $script = $self->{script_fullname};
490 0           my $no_execute_flag = $self->{no_execute_flag};
491 0           my $alien_sys_installs = $self->{alien_sys_installs};
492             # my $cache_file = $self->{cache_file};
493            
494 0           my $deps_hash = scan_deps(
495             files => [ $script ],
496             recurse => 1,
497             execute => !$no_execute_flag,
498             # cache_file => $cache_file,
499             );
500            
501             #my @lib_paths
502             # = map {path($_)->absolute}
503             # grep {defined} # needed?
504             # @Config{qw /installsitearch installvendorarch installarchlib/};
505             #say join ' ', @lib_paths;
506             my @lib_paths
507 0           = reverse sort {length $a <=> length $b}
508 0           map {path($_)->absolute}
  0            
509             @INC;
510            
511 0           my $paths = join '|', map {quotemeta} map {path($_)->stringify} @lib_paths;
  0            
  0            
512 0           my $inc_path_re = qr /^($paths)/i;
513             #say $inc_path_re;
514            
515             #say "DEPS HASH:" . join "\n", keys %$deps_hash;
516 0           my %dll_hash;
517             my @aliens;
518 0           foreach my $package (keys %$deps_hash) {
519 0           my $details = $deps_hash->{$package};
520 0   0       my @uses = @{$details->{uses} // []};
  0            
521 0 0         if ($details->{key} =~ m{^Alien/.+\.pm$}) {
    0          
522 0           push @aliens, $package;
523             }
524             elsif ($details->{key} =~ m{^Gtk}) {
525             # we need to check the pixbuf loaders
526 0           my @pixbuf_loaders = $self->process_gdk_pixbuf_loaders;
527 0           push @uses, @pixbuf_loaders;
528             }
529            
530             push @uses, $package
531 0 0         if $details->{file} =~ $RE_DLL_EXT;
532            
533 0 0         next if !@uses;
534            
535 0           foreach my $dll (grep {$_ =~ $RE_DLL_EXT} @uses) {
  0            
536 0           my $dll_path = $dll;
537 0 0         if (!path($dll_path)->is_absolute) {
538 0 0   0     if (my $pfx = List::Util::first {path($_, $dll)->exists} @INC) {
  0            
539 0           $dll_path = path($pfx, $dll);
540             }
541             }
542             # We were getting double paths under SP 5.36.
543             # It should be fixed now but leave here just in case.
544 0 0         if ($dll =~ /^\w:.+:/){
545 0           warn "Fixing double dir path: $dll_path}";
546 0           $dll_path =~ s/^.+(.):/$1:/;
547             }
548 0 0         croak "either cannot find or cannot read $dll "
549             . "for package $package"
550             if not -r $dll_path;
551 0           $dll_hash{$dll_path}++;
552             }
553             }
554             # handle aliens
555             ALIEN:
556 0           foreach my $package (@aliens) {
557 0 0         next if $package =~ m{^Alien/(Base|Build)};
558 0           my $package_inc_name = $package;
559 0           $package =~ s{/}{::}g;
560 0           $package =~ s/\.pm$//;
561 0 0         if (!$INC{$package_inc_name}) {
562             # if the execute flag was off then try to load the package
563 0           eval "require $package";
564 0 0         if ($@) {
565 0           say "Unable to require $package, skipping (error is $@)";
566 0           next ALIEN;
567             }
568             }
569             # some older aliens might do different things
570 0 0         next ALIEN if !$package->isa ('Alien::Base');
571 0           say "Finding dynamic libs for $package";
572 0           foreach my $path ($package->dynamic_libs) {
573             # warn $path;
574 0           $dll_hash{$path}++;
575             }
576 0 0         if ($package->install_type eq 'system') {
577 0           push @$alien_sys_installs, $package->dynamic_libs;
578             }
579 0           push @{$self->{alien_deps}}, $package;
  0            
580             }
581            
582 0           my @dll_list = sort keys %dll_hash;
583 0 0         return wantarray ? @dll_list : \@dll_list;
584             }
585            
586             sub process_gdk_pixbuf_loaders {
587 0     0 0   my ($self) = @_;
588            
589 0           say 'Scanning gdk-pixbuf-query-loaders result';
590            
591 0           my $ql = which 'gdk-pixbuf-query-loaders';
592            
593 0 0         return if !$ql;
594            
595 0           my $pixbuf_parent_path = path ($ql)->parent->parent;
596            
597             my @res =
598 0           map {path $_}
599 0           grep {$_ =~ /$RE_DLL_EXT$/}
600 0           grep {$_ !~ /#/}
601 0           map {s/"//gr}
602 0           map {s/\s*//gr}
  0            
603             qx /gdk-pixbuf-query-loaders/;
604            
605 0           foreach my $path (@res) {
606             # are we relative to pixbuf-loader?
607 0 0         if (!$path->is_absolute) {
608 0           $path = path ($pixbuf_parent_path, $path);
609             }
610             }
611 0           return @res;
612             }
613            
614             1;
615            
616             __END__