blib/script/pkg-config.pl untested

filter: Statementstmt 0.0% 0 / 583 Branchbran 0.0% 0 / 256 Conditioncond 0.0% 0 / 110 MC/DCmcdc 0.0% 0 / 61 Subroutinesub 0.0% 0 / 43 Podpod 0.0% 0 / 26 totaltotal 0.0% 0 / 1079 CC 55 SCAR 34.7
CC
55
Cov
0%
find
132.0
parse_pcfile
72.0
get_requires
42.0
CRAP 32.1
1 #!/usr/local/bin/perl
2  
3 # lightweight no-dependency version of pkg-config. This will work on any machine
4 # with Perl installed.
5  
6 # Copyright (C) 2012 M. Nunberg.
7 # You may use and distribute this software under the same terms and conditions
8 # as Perl itself.
9  
10 package PkgConfig;
11  
12 #First two digits are Perl version, second two are pkg-config version
13 our $VERSION = '0.26026';
14  
15 $VERSION =~ /([0-9]{2})$/;
16 my $compat_version = $1;
17  
18 use strict;
19 use warnings;
20 use 5.006;
21 use Config;
22 use File::Spec;
23 use File::Glob 'bsd_glob';
24 use Class::Struct; #in core since 5.004
25 use File::Basename qw( dirname );
26 use Text::ParseWords qw( shellwords );
27  
28 our $UseDebugging;
29  
30 ################################################################################
31 ### Check for Log::Fu ###
32 ################################################################################
33 BEGIN {
34 my $ret = eval q{
35 use Log::Fu 0.25 { level => "warn" };
36 1;
37 };
38  
39 if(!$ret) {
40 my $log_base = sub {
41 my (@args) = @_;
42 print STDERR "[DEBUG] ", join(' ', @args);
43 print STDERR "\n";
44 };
45 *log_debug = *log_debugf = sub { return unless $UseDebugging; goto &$log_base };
46 *log_err = *log_errf = *log_warn = *log_warnf = *log_info = *log_infof =
47 $log_base;
48  
49 }
50 }
51  
52 ################################################################################
53 ### Sane Defaults ###
54 ################################################################################
55 our @DEFAULT_SEARCH_PATH = qw(
56 /usr/local/lib/pkgconfig /usr/local/share/pkgconfig
57 /usr/lib/pkgconfig /usr/share/pkgconfig
58  
59 );
60  
61 our @DEFAULT_EXCLUDE_CFLAGS = qw(-I/usr/include -I/usr/local/include);
62 # don't include default link/search paths!
63 our @DEFAULT_EXCLUDE_LFLAGS = map { ( "-L$_", "-R$_" ) } qw( /lib /lib32 /lib64 /usr/lib /usr/lib32 /usr/lib/64 /usr/local/lib /usr/local/lib32 /usr/local/lib64 );
64  
65 if($ENV{PKG_CONFIG_NO_OS_CUSTOMIZATION}) {
66  
67 # use the defaults regardless of detected platform
68  
69 } elsif($ENV{PKG_CONFIG_LIBDIR}) {
70  
71 @DEFAULT_SEARCH_PATH = split $Config{path_sep}, $ENV{PKG_CONFIG_LIBDIR};
72  
73 } elsif($^O eq 'msys') {
74  
75 # MSYS2 seems to actually set PKG_CONFIG_PATH in its /etc/profile
76 # god bless it. But. The defaults if you unset the environment
77 # variable are different
78 @DEFAULT_SEARCH_PATH = qw(
79 /usr/lib/pkgconfig
80 /usr/share/pkgconfig
81 );
82  
83 } elsif($^O eq 'solaris' && $Config{ptrsize} == 8) {
84  
85 @DEFAULT_SEARCH_PATH = qw(
86 /usr/local/lib/64/pkgconfig /usr/local/share/pkgconfig
87 /usr/lib/64/pkgconfig /usr/share/pkgconfig
88 );
89  
90 } elsif($^O eq 'linux' and -f '/etc/gentoo-release') {
91 # OK, we're running on Gentoo
92  
93 # Fetch ptrsize value
94 my $ptrsize = $Config{ptrsize};
95  
96 # Are we running on 64 bit system?
97 if ($ptrsize eq 8) {
98 # We do
99 @DEFAULT_SEARCH_PATH = qw!
100 /usr/lib64/pkgconfig/ /usr/share/pkgconfig/
101 !;
102 } else {
103 # We're running on a 32 bit system (hopefully)
104 @DEFAULT_SEARCH_PATH = qw!
105 /usr/lib/pkgconfig/ /usr/share/pkgconfig/
106 !;
107 }
108  
109 } elsif($^O =~ /^(gnukfreebsd|linux)$/ && -r "/etc/debian_version") {
110  
111 my $arch;
112 if(-x "/usr/bin/dpkg-architecture") {
113 # works if dpkg-dev is installed
114 # rt96694
115 ($arch) = map { chomp; (split /=/)[1] }
116 grep /^DEB_HOST_MULTIARCH=/,
117 `/usr/bin/dpkg-architecture`;
118 } elsif(-x "/usr/bin/gcc") {
119 # works if gcc is installed
120 $arch = `/usr/bin/gcc -dumpmachine`;
121 chomp $arch;
122 } else {
123 my $deb_arch = `dpkg --print-architecture`;
124 if($deb_arch =~ /^amd64/) {
125 if($^O eq 'linux') {
126 $arch = 'x86_64-linux-gnu';
127 } elsif($^O eq 'gnukfreebsd') {
128 $arch = 'x86_64-kfreebsd-gnu';
129 }
130 } elsif($deb_arch =~ /^i386/) {
131 if($^O eq 'linux') {
132 $arch = 'i386-linux-gnu';
133 } elsif($^O eq 'gnukfreebsd') {
134 $arch = 'i386-kfreebsd-gnu';
135 }
136 }
137 }
138  
139 if($arch) {
140 if(scalar grep /--print-foreign-architectures/, `dpkg --help`)
141 {
142 # multi arch support / Debian 7+
143 @DEFAULT_SEARCH_PATH = (
144 "/usr/local/lib/$arch/pkgconfig",
145 "/usr/local/lib/pkgconfig",
146 "/usr/local/share/pkgconfig",
147 "/usr/lib/$arch/pkgconfig",
148 "/usr/lib/pkgconfig",
149 "/usr/share/pkgconfig",
150 );
151  
152 push @DEFAULT_EXCLUDE_LFLAGS, map { ("-L$_", "-R$_") }
153 "/usr/local/lib/$arch",
154 "/usr/lib/$arch";
155  
156 } else {
157  
158 @DEFAULT_SEARCH_PATH = (
159 "/usr/local/lib/pkgconfig",
160 "/usr/local/lib/pkgconfig/$arch",
161 "/usr/local/share/pkgconfig",
162 "/usr/lib/pkgconfig",
163 "/usr/lib/pkgconfig/$arch",
164 "/usr/share/pkgconfig",
165 );
166 }
167  
168 } else {
169  
170 @DEFAULT_SEARCH_PATH = (
171 "/usr/local/lib/pkgconfig",
172 "/usr/local/share/pkgconfig",
173 "/usr/lib/pkgconfig",
174 "/usr/share/pkgconfig",
175 );
176  
177 }
178  
179 } elsif($^O eq 'linux' && -r "/etc/redhat-release") {
180  
181 if(-d "/usr/lib64/pkgconfig") {
182 @DEFAULT_SEARCH_PATH = qw(
183 /usr/lib64/pkgconfig
184 /usr/share/pkgconfig
185 );
186 } else {
187 @DEFAULT_SEARCH_PATH = qw(
188 /usr/lib/pkgconfig
189 /usr/share/pkgconfig
190 );
191 }
192  
193 } elsif($^O eq 'linux' && -r "/etc/slackware-version") {
194  
195 # Fetch ptrsize value
196 my $ptrsize = $Config{ptrsize};
197  
198 # Are we running on 64 bit system?
199 if ($ptrsize == 8) {
200 # We do
201 @DEFAULT_SEARCH_PATH = qw!
202 /usr/lib64/pkgconfig/ /usr/share/pkgconfig/
203 !;
204 } else {
205 # We're running on a 32 bit system (hopefully)
206 @DEFAULT_SEARCH_PATH = qw!
207 /usr/lib/pkgconfig/ /usr/share/pkgconfig/
208 !;
209 }
210  
211  
212 } elsif($^O eq 'freebsd') {
213  
214 # TODO: FreeBSD 10-12's version of pkg-config does not
215 # support PKG_CONFIG_DEBUG_SPEW so I can't verify
216 # the path there.
217 @DEFAULT_SEARCH_PATH = qw(
218 /usr/local/libdata/pkgconfig
219 /usr/libdata/pkgconfig
220 );
221  
222 } elsif($^O eq 'netbsd') {
223  
224 @DEFAULT_SEARCH_PATH = qw(
225 /usr/pkg/lib/pkgconfig
226 /usr/pkg/share/pkgconfig
227 /usr/X11R7/lib/pkgconfig
228 /usr/lib/pkgconfig
229 );
230 } elsif($^O eq 'openbsd') {
231  
232 @DEFAULT_SEARCH_PATH = qw(
233 /usr/lib/pkgconfig
234 /usr/local/lib/pkgconfig
235 /usr/local/share/pkgconfig
236 /usr/X11R6/lib/pkgconfig
237 /usr/X11R6/share/pkgconfig
238 );
239  
240 } elsif($^O eq 'MSWin32') {
241  
242 # Caveats:
243 # 1. This pulls in Config,
244 # which we don't load on non MSWin32
245 # but it is in the core.
246 # 2. Slight semantic difference in that we are treating
247 # Strawberry as the "system" rather than Windows, but
248 # since pkg-config is rarely used in MSWin32, it is
249 # better to have something that is useful rather than
250 # worry about if it is exactly the same as other
251 # platforms.
252 # 3. It is a little brittle in that Strawberry might
253 # one day change its layouts. If it has and you are
254 # reading this, please send a pull request or simply
255 # let me know -plicease
256 require Config;
257 if($Config::Config{myuname} =~ /strawberry-perl/)
258 {
259 # handle PAR::Packer executables which have $^X eq "perl.exe"
260 if ($ENV{PAR_0})
261 {
262 my $path = $ENV{PAR_TEMP};
263 $path =~ s{\\}{/}g;
264 @DEFAULT_SEARCH_PATH = ($path);
265 }
266 else {
267 my($vol, $dir, $file) = File::Spec->splitpath($^X);
268 my @dirs = File::Spec->splitdir($dir);
269 splice @dirs, -3;
270 my $path = (File::Spec->catdir($vol, @dirs, qw( c lib pkgconfig )));
271 $path =~ s{\\}{/}g;
272 @DEFAULT_SEARCH_PATH = $path;
273 }
274 }
275  
276 my @reg_paths;
277  
278 eval q{
279 package
280 PkgConfig::WinReg;
281  
282 use Win32API::Registry 0.21 qw( :ALL );
283  
284 foreach my $top (HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER) {
285 my $key;
286 RegOpenKeyEx( $top, "Software\\\\pkgconfig\\\\PKG_CONFIG_PATH", 0, KEY_READ, $key) || next;
287 my $nlen = 1024;
288 my $pos = 0;
289 my $name = '';
290  
291 while(RegEnumValue($key, $pos++, $name, $nlen, [], [], [], [])) {
292 my $type;
293 my $data;
294 RegQueryValueEx($key, $name, [], $type, $data, []);
295 push @reg_paths, $data;
296 }
297  
298 RegCloseKey( $key );
299 }
300 };
301  
302 unless($@) {
303 unshift @DEFAULT_SEARCH_PATH, @reg_paths;
304 }
305  
306 if($Config::Config{cc} =~ /cl(\.exe)?$/i)
307 {
308 @DEFAULT_EXCLUDE_LFLAGS = ();
309 @DEFAULT_EXCLUDE_CFLAGS = ();
310 }
311 else
312 {
313 @DEFAULT_EXCLUDE_LFLAGS = (
314 "-L/mingw/lib",
315 "-R/mingw/lib",
316 "-L/mingw/lib/pkgconfig/../../lib",
317 "-R/mingw/lib/pkgconfig/../../lib",
318 );
319 @DEFAULT_EXCLUDE_CFLAGS = (
320 "-I/mingw/include",
321 "-I/mingw/lib/pkgconfig/../../include",
322 );
323 }
324  
325 # See caveats above for Strawberry and PAR::Packer
326 require Config;
327 if(not $ENV{PAR_0} and $Config::Config{myuname} =~ /strawberry-perl/)
328 {
329 my($vol, $dir, $file) = File::Spec->splitpath($^X);
330 my @dirs = File::Spec->splitdir($dir);
331 splice @dirs, -3;
332 my $path = (File::Spec->catdir($vol, @dirs, qw( c )));
333 $path =~ s{\\}{/}g;
334 push @DEFAULT_EXCLUDE_LFLAGS, (
335 "-L$path/lib",
336 "-L$path/lib/pkgconfig/../../lib",
337 "-R$path/lib",
338 "-R$path/lib/pkgconfig/../../lib",
339 );
340 push @DEFAULT_EXCLUDE_CFLAGS, (
341 "-I$path/include",
342 "-I$path/lib/pkgconfig/../../include",
343 );
344 }
345 } elsif($^O eq 'darwin') {
346  
347 if(-x '/usr/local/Homebrew/bin/brew') {
348 # Mac OS X with homebrew installed
349 push @DEFAULT_SEARCH_PATH,
350 bsd_glob '/usr/local/opt/*/lib/pkgconfig'
351 ;
352 }
353  
354 }
355  
356 my @ENV_SEARCH_PATH = split($Config{path_sep}, $ENV{PKG_CONFIG_PATH} || "");
357  
358 unshift @DEFAULT_SEARCH_PATH, @ENV_SEARCH_PATH;
359  
360 if($^O eq 'MSWin32') {
361 @DEFAULT_SEARCH_PATH = map { s{\\}{/}g; $_ } map { /\s/ ? Win32::GetShortPathName($_) : $_ } @DEFAULT_SEARCH_PATH;
362 }
363  
364 if($ENV{PKG_CONFIG_ALLOW_SYSTEM_CFLAGS}) {
365 @DEFAULT_EXCLUDE_CFLAGS = ();
366 }
367  
368 if($ENV{PKG_CONFIG_ALLOW_SYSTEM_LIBS}) {
369 @DEFAULT_EXCLUDE_LFLAGS = ();
370 }
371  
372 my $LD_OUTPUT_RE = qr/
373 SEARCH_DIR\("
374 ([^"]+)
375 "\)
376 /x;
377  
378 sub GuessPaths {
379 my $pkg = shift;
380 local $ENV{LD_LIBRARY_PATH} = "";
381 local $ENV{C_INCLUDE_PATH} = "";
382 local $ENV{LD_RUN_PATH} = "";
383  
384 my $ld = $ENV{LD} || 'ld';
385 my $ld_output = qx(ld -verbose);
386 my @defl_search_dirs = ($ld_output =~ m/$LD_OUTPUT_RE/g);
387  
388 @DEFAULT_EXCLUDE_LFLAGS = ();
389 foreach my $path (@defl_search_dirs) {
390 push @DEFAULT_EXCLUDE_LFLAGS, (map { "$_".$path }
391 (qw(-R -L -rpath= -rpath-link= -rpath -rpath-link)));
392 }
393 log_debug("Determined exclude LDFLAGS", @DEFAULT_EXCLUDE_LFLAGS);
394  
395 #now get the include paths:
396 my @cpp_output = qx(cpp --verbose 2>&1 < /dev/null);
397 @cpp_output = map { chomp $_; $_ } @cpp_output;
398 #log_info(join("!", @cpp_output));
399 while (my $cpp_line = shift @cpp_output) {
400 chomp($cpp_line);
401 if($cpp_line =~ /\s*#include\s*<.+search starts here/) {
402 last;
403 }
404 }
405 #log_info(@cpp_output);
406 my @include_paths;
407 while (my $path = shift @cpp_output) {
408 if($path =~ /\s*End of search list/) {
409 last;
410 }
411 push @include_paths, $path;
412 }
413 @DEFAULT_EXCLUDE_CFLAGS = map { "-I$_" } @include_paths;
414 log_debug("Determine exclude CFLAGS", @DEFAULT_EXCLUDE_CFLAGS);
415 }
416  
417  
418 ################################################################################
419 ### Define our fields ###
420 ################################################################################
421 struct(
422 __PACKAGE__,
423 [
424 # .pc search paths, defaults to PKG_CONFIG_PATH in environment
425 'search_path' => '@',
426  
427 # whether to also spit out static dependencies
428 'static' => '$',
429  
430 # whether we replace references to -L and friends with -Wl,-rpath, etc.
431 'rpath' => '$',
432  
433 # build rpath-search,
434  
435 # no recursion. set if we just want a version, or to see if the
436 # package exists.
437 'no_recurse' => '$',
438  
439 #list of cflags and ldflags to exclude
440 'exclude_ldflags' => '@',
441 'exclude_cflags' => '@',
442  
443 # what level of recursion we're at
444 'recursion' => '$',
445  
446 # hash of libraries, keyed by recursion levels. Lower recursion numbers
447 # will be listed first
448 'libs_deplist' => '*%',
449  
450 # cumulative cflags and ldflags
451 'ldflags' => '*@',
452 'cflags' => '*@',
453  
454 # whether we print the c/ldflags
455 'print_cflags' => '$',
456 'print_ldflags' => '$',
457  
458 # information about our top-level package
459 'pkg' => '$',
460 'pkg_exists' => '$',
461 'pkg_version' => '$',
462 'pkg_url', => '$',
463 'pkg_description' => '$',
464 'errmsg' => '$',
465  
466 'filevars' => '*%',
467 'uservars' => '*%',
468  
469 # options for printing variables
470 'print_variables' => '$',
471 'print_variable' => '$',
472 'print_values' => '$',
473 'defined_variables' => '*%',
474  
475 # for creating PkgConfig objects with identical
476 # settings
477 'original' => '$',
478 ]
479 );
480  
481 ################################################################################
482 ################################################################################
483 ### Variable Storage ###
484 ################################################################################
485 ################################################################################
486  
487 sub assign_var {
488 my ($self,$field,$value,$force) = @_;
489 # if the user has provided a definition, use that.
490 if (!$force && exists $self->uservars->{$field}) {
491 log_debug("Prefix already defined by user");
492 return;
493 }
494 my $filevars = $self->filevars;
495 if ($field =~ /(dir|prefix)$/ && $value !~ /\$/) {
496 # heuristic - it's a directory
497 $filevars->{$field} = [grep length, $value];
498 return;
499 }
500 my (@inwords, @outwords) = shellwords $value; # FIRST split it
501 for my $inword (@inwords) { # THEN sub
502 my ($word, $outword) = ($inword, '');
503 while ($word =~ s/(^|.*?[^\$])\$\{([a-z_.]+)\}//s) {
504 my ($start, $var) = ($1, $2);
505 $outword .= $start;
506 my $val = $filevars->{$var};
507 next if !defined($val) or !grep length, @$val;
508 $outword .= "@$val";
509 }
510 $outword .= $word; # what's left
511 next if !length $outword;
512 $outword =~ s/\$\$/\$/g; # pkg-config escapes a '$' with a '$$'
513 push @outwords, $outword;
514 }
515 $filevars->{$field} = \@outwords;
516 }
517  
518 sub prepare_vars {
519 my $self = shift;
520 my $uv = $self->uservars;
521 $self->assign_var($_, $uv->{$_}, 1) for keys %$uv;
522 }
523  
524 ################################################################################
525 ################################################################################
526 ### Initializer ###
527 ################################################################################
528 ################################################################################
529 sub find {
530 my ($cls,$library,%options) = @_;
531 my @uspecs = (
532 ['search_path', \@DEFAULT_SEARCH_PATH],
533 ['exclude_ldflags', \@DEFAULT_EXCLUDE_LFLAGS],
534 ['exclude_cflags', \@DEFAULT_EXCLUDE_CFLAGS]
535 );
536  
537 my %original = %options;
538  
539 foreach (@uspecs) {
540 my ($basekey,$default) = @$_;
541 my $list = [ @{$options{$basekey} ||= [] } ];
542 if($options{$basekey . "_override"}) {
543 @$list = @{ delete $options{$basekey."_override"} };
544 } else {
545 push @$list, @$default;
546 }
547  
548 $options{$basekey} = $list;
549 #print "$basekey: " . Dumper($list);
550 }
551  
552 $options{filevars} = {};
553 $options{uservars} = {$options{VARS} ? %{ delete $options{VARS} } : ()};
554 $options{original} = \%original;
555  
556 my $o = $cls->new(%options);
557  
558 my @libraries;
559 if(ref $library eq 'ARRAY') {
560 @libraries = @$library;
561 } else {
562 @libraries = ($library);
563 }
564  
565 if($options{file_path}) {
566  
567 if(-r $options{file_path}) {
568 $o->recursion(1);
569 $o->parse_pcfile($options{file_path});
570 $o->recursion(0);
571 } else {
572 $o->errmsg("No such file $options{file_path}\n");
573 }
574  
575 } else {
576  
577 foreach my $lib (@libraries) {
578 $o->recursion(0);
579 my($op,$ver);
580 ($lib,$op,$ver) = ($1,$2,PkgConfig::Version->new($3))
581 if $lib =~ /^(.*)\s+(!=|=|>=|<=|>|<)\s+(.*)$/;
582 $o->find_pcfile($lib);
583  
584 if(!$o->errmsg && defined $op) {
585 $op = '==' if $op eq '=';
586 unless(eval qq{ PkgConfig::Version->new(\$o->pkg_version) $op \$ver })
587 {
588 $o->errmsg("Requested '$lib $op $ver' but version of $lib is " .
589 ($o->pkg_version ? $o->pkg_version : '') . "\n");
590 }
591 }
592 }
593 }
594  
595 $o;
596 }
597  
598 ################################################################################
599 ################################################################################
600 ### Modify our flags stack ###
601 ################################################################################
602 ################################################################################
603 sub append_ldflags {
604 my ($self,@ld_flags) = @_;
605  
606 foreach my $ldflag (@ld_flags) {
607 next unless $ldflag =~ /^-Wl/;
608  
609 my (@wlflags) = split(/,/, $ldflag);
610 shift @wlflags; #first is -Wl,
611 filter_omit(\@wlflags, $self->exclude_ldflags);
612  
613 if(!@wlflags) {
614 $ldflag = "";
615 next;
616 }
617  
618 $ldflag = join(",", '-Wl', @wlflags);
619 }
620  
621 @ld_flags = grep $_, @ld_flags;
622 return unless @ld_flags;
623  
624 push @{($self->libs_deplist->{$self->recursion} ||=[])},
625 @ld_flags;
626 }
627  
628 # notify us about extra compiler flags
629 sub append_cflags {
630 my ($self,@flags) = @_;
631 push @{$self->cflags}, @flags;
632 }
633  
634  
635 ################################################################################
636 ################################################################################
637 ### All sorts of parsing is here ###
638 ################################################################################
639 ################################################################################
640 sub get_requires {
641 my ($self,$requires) = @_;
642 return () unless $requires;
643  
644 my @reqlist = split(/[\s,]+/, $requires);
645 my @ret;
646 while (defined (my $req = shift @reqlist) ) {
647 my $reqlet = [ $req ];
648 push @ret, $reqlet;
649 last unless @reqlist;
650 #check if we need some version scanning:
651  
652 my $cmp_op;
653 my $want;
654  
655 GT_PARSE_REQ:
656 {
657 #all in one word:
658 ($cmp_op) = ($req =~ /([<>=]+)/);
659 if($cmp_op) {
660 if($req =~ /[<>=]+$/) {
661 log_debug("comparison operator spaced ($cmp_op)");
662 ($want) = ($req =~ /([^<>=]+$)/);
663 $want ||= shift @reqlist;
664 } else {
665 $want = shift @reqlist;
666 }
667 push @$reqlet, ($cmp_op, $want);
668 } elsif ($reqlist[0] =~ /[<>=]+/) {
669 $req = shift @reqlist;
670 goto GT_PARSE_REQ;
671 }
672 }
673 }
674 #log_debug(@ret);
675 @ret;
676 }
677  
678 sub parse_line {
679 my ($self,$line) = @_;
680  
681 $line =~ s/#[^#]+$//g; # strip comments
682 return unless $line;
683  
684 my ($tok) = ($line =~ /([=:])/);
685  
686 my ($field,$value) = split(/[=:]/, $line, 2);
687 return unless defined $value;
688  
689 if($tok eq '=') {
690 $self->defined_variables->{$field} = $value;
691 }
692  
693 #strip trailing/leading whitespace:
694 $field =~ s/(^\s+)|(\s+)$//msg;
695  
696 #remove trailing/leading whitespace from value
697 $value =~ s/(^\s+)|(\s+$)//msg;
698  
699 log_debugf("Field %s, Value %s", $field, $value);
700  
701 $field = lc($field);
702  
703 my $filevars = $self->filevars;
704 if ($tok eq ':' and $field !~ /^(cflags|libs)/) {
705 $value =~ s/(^|[^\$])\$\{([a-z_.]+)\}/$1$filevars->{$2}[0]/g;
706 $filevars->{$field} = [grep length, $value]; # no need quoting
707 return;
708 }
709  
710 #remove quotes from field names
711 $field =~ s/['"]//g;
712  
713 $value =~ s/(\$\{[^}]+\})/lc($1)/ge;
714  
715 #get existent variables from our hash:
716 $self->assign_var($field, $value);
717 }
718  
719 sub parse_pcfile {
720 my ($self,$pcfile,$wantversion) = @_;
721 #log_warn("Requesting $pcfile");
722 open my $fh, "<", $pcfile or die "$pcfile: $!";
723  
724 $self->prepare_vars();
725  
726 my @lines = (<$fh>);
727 close($fh);
728  
729 my $text = join("", @lines);
730 $text =~ s,\\[\r\n],,g;
731 @lines = split(/[\r\n]/, $text);
732  
733 #Fold lines:
734  
735 my $pcfiledir = dirname $pcfile;
736 $pcfiledir =~ s{\\}{/}g;
737  
738 foreach my $line ("pcfiledir=$pcfiledir", @lines) {
739 $self->parse_line($line);
740 }
741  
742 #now that we have eval strings, evaluate them all within the same
743 #lexical scope:
744  
745  
746 $self->append_cflags( $self->get_var('cflags') );
747 if($self->static) {
748 $self->append_cflags( $self->get_var('cflags.private') );
749 }
750 $self->append_ldflags( $self->get_var('libs') );
751 if($self->static) {
752 $self->append_ldflags( $self->get_var('libs.private') );
753 }
754  
755 my @deps;
756 my @deps_dynamic = $self->get_requires( $self->get_var('requires'));
757 my @deps_static = $self->get_requires( $self->get_var('requires.private') );
758 @deps = @deps_dynamic;
759  
760  
761 if($self->static) {
762 push @deps, @deps_static;
763 }
764  
765 if($self->recursion == 1 && (!$self->pkg_exists())) {
766 $self->pkg_version( $self->get_var('version') );
767 $self->pkg_url( $self->get_var('url') );
768 $self->pkg_description( $self->get_var('description') );
769 $self->pkg_exists(1);
770 }
771  
772 unless ($self->no_recurse) {
773 foreach (@deps) {
774 my ($dep,$cmp_op,$version) = @$_;
775 $dep = "$dep $cmp_op $version" if defined $cmp_op;
776 my $other = PkgConfig->find($dep, %{ $self->original });
777 if($other->errmsg) {
778 $self->errmsg($other->errmsg);
779 last;
780 }
781 $self->append_cflags( $other->get_cflags );
782 $self->append_ldflags( $other->get_ldflags );
783 }
784 }
785 }
786  
787  
788 ################################################################################
789 ################################################################################
790 ### Locate and process a .pc file ###
791 ################################################################################
792 ################################################################################
793 sub find_pcfile {
794 my ($self,$libname,$version) = @_;
795  
796 $self->recursion($self->recursion + 1);
797  
798 my $pcfile = "$libname.pc";
799 my $found = 0;
800 my @found_paths = (grep {
801 -e File::Spec->catfile($_, $pcfile)
802 } @{$self->search_path});
803  
804 if(!@found_paths) {
805 my @search_paths = @{$self->search_path};
806 $self->errmsg(
807 join("\n",
808 "Can't find $pcfile in any of @search_paths",
809 "use the PKG_CONFIG_PATH environment variable, or",
810 "specify extra search paths via 'search_paths'",
811 ""
812 )
813 ) unless $self->errmsg();
814 return;
815 }
816  
817 $pcfile = File::Spec->catfile($found_paths[0], $pcfile);
818  
819 $self->parse_pcfile($pcfile);
820  
821 $self->recursion($self->recursion - 1);
822 }
823  
824 ################################################################################
825 ################################################################################
826 ### Public Getters ###
827 ################################################################################
828 ################################################################################
829  
830 sub _quote_protect {
831 my ($v) = @_;
832 return qq{""} if !length($v); # empty strings get preserved
833 return $v if $v !~ /['"\s\\]/;
834 $v =~ s/["\\]/\\$&/g; # the "" will already protect from ' and space
835 $v =~ /['\s]/ ? qq{"$v"} : $v;
836 }
837 sub _return_context {
838 wantarray ? @_ : join ' ', map _quote_protect($_), @_;
839 }
840  
841 sub get_cflags {
842 my $self = shift;
843 my @cflags = @{$self->cflags};
844  
845 filter_omit(\@cflags, $self->exclude_cflags);
846 filter_dups(\@cflags);
847 _return_context @cflags;
848 }
849  
850 sub get_ldflags {
851 my $self = shift;
852 my @ordered_libs;
853 my @lib_levels = sort keys %{$self->libs_deplist};
854 my @ret;
855  
856 @ordered_libs = @{$self->libs_deplist}{@lib_levels};
857 foreach my $liblist (@ordered_libs) {
858 my $lcopy = [ @$liblist ];
859 filter_dups($lcopy);
860 filter_omit($lcopy, $self->exclude_ldflags);
861 push @ret, @$lcopy;
862 }
863  
864 @ret = reverse @ret;
865 filter_dups(\@ret);
866 @ret = reverse(@ret);
867 _return_context @ret;
868 }
869  
870 sub get_var {
871 my($self, $name) = @_;
872 _return_context @{ $self->filevars->{$name} };
873 }
874  
875 sub get_list {
876 my $self = shift;
877 my @search_paths = @{$self->search_path};
878 my @rv = ();
879 $self->recursion(0);
880 for my $d (@search_paths) {
881 next unless -d $d;
882 for my $pc (bsd_glob("$d/*.pc")) {
883 if ($pc =~ m|/([^\\\/]+)\.pc$|) {
884 $self->parse_pcfile($pc);
885 push @rv, [$1, $self->get_var('name') . ' - ' . $self->get_var('description')];
886 }
887 }
888 }
889 @rv;
890 }
891  
892  
893 ################################################################################
894 ################################################################################
895 ### Utility functions ###
896 ################################################################################
897 ################################################################################
898  
899 #split a list of tokens by spaces
900 sub _split_flags {
901 my @flags = @_;
902 if(!@flags) {
903 return @flags;
904 }
905 if(@flags == 1) {
906 my $str = shift @flags;
907 return () if !$str;
908 @flags = shellwords $str;
909 }
910 @flags = grep $_, @flags;
911 @flags;
912 }
913  
914  
915  
916 sub filter_dups {
917 my $array = shift;
918 my @ret;
919 my %seen_hash;
920 foreach my $elem (@$array) {
921 if(exists $seen_hash{$elem}) {
922 next;
923 }
924 $seen_hash{$elem} = 1;
925 push @ret, $elem;
926 }
927 #print Dumper(\%seen_hash);
928 @$array = @ret;
929 }
930  
931 sub filter_omit {
932 my ($have,$exclude) = @_;
933 my @ret;
934 #print Dumper($have);
935 foreach my $elem (@$have) {
936 #log_warn("Checking '$elem'");
937 if(grep { $_ eq $elem } @$exclude) {
938 #log_warn("Found illegal flag '$elem'");
939 next;
940 }
941 push @ret, $elem;
942 }
943 @$have = @ret;
944 }
945  
946 sub version_2_array {
947 my $string = shift;
948 my @chunks = split(/\./, $string);
949 my @ret;
950 my $chunk;
951 while( ($chunk = pop @chunks)
952 && $chunk =~ /^\d+$/) {
953 push @ret, $chunk;
954 }
955 @ret;
956 }
957  
958  
959 sub version_check {
960 my ($want,$have) = @_;
961 my @a_want = version_2_array($want);
962 my @a_have = version_2_array($have);
963  
964 my $max_elem = scalar @a_want > scalar @a_have
965 ? scalar @a_have
966 : scalar @a_want;
967  
968 for(my $i = 0; $i < $max_elem; $i++) {
969 if($a_want[$i] > $a_have[$i]) {
970 return 0;
971 }
972 }
973 1;
974 }
975  
976  
977 if(caller) {
978 return 1;
979 }
980  
981 package
982 PkgConfig::Version;
983  
984 use overload
985 '<=>' => sub { $_[0]->cmp($_[1]) },
986 '""' => sub { $_[0]->as_string },
987 fallback => 1;
988  
989 sub new {
990 my($class, $value) = @_;
991 bless [split /\./, defined $value ? $value : ''], $class;
992 }
993  
994 sub clone {
995 __PACKAGE__->new(shift->as_string);
996 }
997  
998 sub as_string {
999 my($self) = @_;
1000 join '.', @{ $self };
1001 }
1002  
1003 sub cmp {
1004 my($self, $other) = @_;
1005 no warnings 'uninitialized';
1006 defined($self->[0]) || defined($other->[0]) ? ($self->[0] <=> $other->[0]) || &cmp([@{$self}[1..$#$self]], [@{$other}[1..$#$other]]) : 0;
1007 }
1008  
1009 ################################################################################
1010 ################################################################################
1011 ################################################################################
1012 ################################################################################
1013 ### Script-Only stuff ###
1014 ################################################################################
1015 ################################################################################
1016 ################################################################################
1017 ################################################################################
1018 package PkgConfig::Script;
1019 use strict;
1020 use warnings;
1021 use Getopt::Long qw(:config no_ignore_case);
1022 use Pod::Usage;
1023  
1024 my $print_errors = 0;
1025 my @ARGV_PRESERVE = @ARGV;
1026  
1027 my @POD_USAGE_SECTIONS = (
1028 "NAME",
1029 'DESCRIPTION/SCRIPT OPTIONS/USAGE',
1030 "DESCRIPTION/SCRIPT OPTIONS/ARGUMENTS|ENVIRONMENT",
1031 "AUTHOR & COPYRIGHT"
1032 );
1033  
1034 my @POD_USAGE_OPTIONS = (
1035 -verbose => 99,
1036 -sections => \@POD_USAGE_SECTIONS
1037 );
1038  
1039 GetOptions(
1040 'libs' => \my $PrintLibs,
1041 'libs-only-L' => \my $PrintLibsOnlyL,
1042 'libs-only-l' => \my $PrintLibsOnlyl,
1043 'libs-only-other' => \my $PrintLibsOnlyOther,
1044 'list-all' => \my $ListAll,
1045 'static' => \my $UseStatic,
1046 'cflags' => \my $PrintCflags,
1047 'cflags-only-I' => \my $PrintCflagsOnlyI,
1048 'cflags-only-other' => \my $PrintCflagsOnlyOther,
1049 'exists' => \my $PrintExists,
1050 'atleast-version=s' => \my $AtLeastVersion,
1051 'atleast-pkgconfig-version=s' => \my $AtLeastPkgConfigVersion,
1052 'exact-version=s' => \my $ExactVersion,
1053 'max-version=s' => \my $MaxVersion,
1054  
1055 'silence-errors' => \my $SilenceErrors,
1056 'print-errors' => \my $PrintErrors,
1057 'errors-to-stdout' => \my $ErrToStdOut,
1058 'short-errors' => \my $ShortErrors,
1059  
1060 'define-variable=s', => \my %UserVariables,
1061  
1062 'print-variables' => \my $PrintVariables,
1063 'print-values' => \my $PrintValues,
1064 'variable=s', => \my $OutputVariableValue,
1065  
1066 'modversion' => \my $PrintVersion,
1067 'version', => \my $PrintAPIversion,
1068 'real-version' => \my $PrintRealVersion,
1069  
1070 'debug' => \my $Debug,
1071 'with-path=s', => \my @ExtraPaths,
1072 'env-only', => \my $EnvOnly,
1073 'guess-paths', => \my $GuessPaths,
1074  
1075 'h|help|?' => \my $WantHelp
1076 ) or pod2usage(@POD_USAGE_OPTIONS);
1077  
1078 if($^O eq 'msys' && !$ENV{PKG_CONFIG_NO_OS_CUSTOMIZATION}) {
1079 $UseStatic = 1;
1080 }
1081  
1082 if($WantHelp) {
1083 pod2usage(@POD_USAGE_OPTIONS, -exitval => 0);
1084 }
1085  
1086 if($Debug) {
1087 eval {
1088 Log::Fu::set_log_level('PkgConfig', 'DEBUG');
1089 };
1090 $PkgConfig::UseDebugging = 1;
1091 }
1092  
1093 if($GuessPaths) {
1094 PkgConfig->GuessPaths();
1095 }
1096  
1097 if($PrintAPIversion) {
1098 print '0.', $compat_version, "\n";
1099 exit(0);
1100 }
1101  
1102 if($AtLeastPkgConfigVersion) {
1103 my($major,$minor,$patch) = split /\./, $AtLeastPkgConfigVersion;
1104 exit 1 if $major > 0;
1105 exit 1 if $minor > $compat_version;
1106 exit 1 if $minor == $compat_version && $patch > 0;
1107 exit 0;
1108 }
1109  
1110 if($PrintRealVersion) {
1111  
1112 printf STDOUT ("ppkg-config - cruftless pkg-config\n" .
1113 "Version: %s\n", $PkgConfig::VERSION);
1114 exit(0);
1115 }
1116  
1117 if($PrintErrors) {
1118 $print_errors = 1;
1119 }
1120  
1121 if($SilenceErrors) {
1122 $print_errors = 0;
1123 }
1124  
1125 # This option takes precedence over all other options
1126 # be it:
1127 # --silence-errors
1128 # or
1129 # --print-errors
1130 if ($ErrToStdOut) {
1131 $print_errors = 2;
1132 }
1133  
1134 my $WantFlags = ($PrintCflags || $PrintLibs || $PrintLibsOnlyL || $PrintCflagsOnlyI || $PrintCflagsOnlyOther || $PrintLibsOnlyOther || $PrintLibsOnlyl || $PrintVersion);
1135  
1136 if($WantFlags) {
1137 $print_errors = 1 unless $SilenceErrors;
1138 }
1139  
1140 my %pc_options;
1141 if($PrintExists || $AtLeastVersion || $ExactVersion || $MaxVersion || $PrintVersion) {
1142 $pc_options{no_recurse} = 1;
1143 }
1144  
1145  
1146 $pc_options{static} = $UseStatic;
1147 $pc_options{search_path} = \@ExtraPaths;
1148  
1149 if($EnvOnly) {
1150 delete $pc_options{search_path};
1151 $pc_options{search_path_override} = [ @ExtraPaths, @ENV_SEARCH_PATH];
1152 }
1153  
1154 $pc_options{print_variables} = $PrintVariables;
1155 $pc_options{print_values} = $PrintValues;
1156 $pc_options{VARS} = \%UserVariables;
1157  
1158 if($ListAll) {
1159 my $o = PkgConfig->find([], %pc_options);
1160 my @list = $o->get_list();
1161  
1162 # can't use List::Util::max as it wasn't core until Perl 5.8
1163 my $max_length = 0;
1164 foreach my $length (map { length $_->[0] } @list) {
1165 $max_length = $length if $length > $max_length;
1166 }
1167  
1168 printf "%-${max_length}s %s\n", $_->[0], $_->[1] for @list;
1169 exit(0);
1170 }
1171  
1172 my @FINDLIBS = @ARGV or die "Must specify at least one library";
1173  
1174 if($AtLeastVersion) {
1175 @FINDLIBS = map { "$_ >= $AtLeastVersion" } @FINDLIBS;
1176 } elsif($MaxVersion) {
1177 @FINDLIBS = map { "$_ <= $MaxVersion" } @FINDLIBS;
1178 } elsif($ExactVersion) {
1179 @FINDLIBS = map { "$_ = $ExactVersion" } @FINDLIBS;
1180 }
1181  
1182 my $o = PkgConfig->find(\@FINDLIBS, %pc_options);
1183  
1184 if($o->errmsg) {
1185 # --errors-to-stdout
1186 if ($print_errors == 2) {
1187 print STDOUT $o->errmsg;
1188 # --print-errors
1189 } elsif ($print_errors == 1) {
1190 print STDERR $o->errmsg;
1191 }
1192 # --silence-errors
1193 exit(1);
1194 }
1195  
1196 if($o->print_variables) {
1197 while (my ($k,$v) = each %{$o->defined_variables}) {
1198 print $k;
1199 if($o->print_values) {
1200 print "=$v";
1201 } else {
1202 print "\n";
1203 }
1204 }
1205 }
1206  
1207 if($OutputVariableValue) {
1208 my $val = $o->get_var($OutputVariableValue) || "";
1209 print $val . "\n";
1210 }
1211  
1212 if(!$WantFlags) {
1213 exit(0);
1214 }
1215  
1216 if($PrintVersion) {
1217 print $o->pkg_version . "\n";
1218 exit(0);
1219 }
1220  
1221 my @print_flags;
1222  
1223 if($PrintCflags) {
1224 @print_flags = $o->get_cflags;
1225 }
1226  
1227 if($PrintCflagsOnlyI) {
1228 @print_flags = grep /^-I/, $o->get_cflags;
1229 }
1230  
1231 if($PrintCflagsOnlyOther) {
1232 @print_flags = grep /^-[^I]/, $o->get_cflags;
1233 }
1234  
1235 if($PrintLibs) {
1236 @print_flags = $o->get_ldflags;
1237 }
1238  
1239 if ($PrintLibsOnlyOther) {
1240 @print_flags = grep /^-[^LRl]/, $o->get_ldflags;
1241 }
1242  
1243 # handle --libs-only-L and --libs-only-l but watch the case when
1244 # we got 'ppkg-config --libs-only-L --libs-only-l foo' which must behave just like
1245 # 'ppkg-config --libs-only-l foo'
1246  
1247 if($PrintLibsOnlyl or ($PrintLibsOnlyl and $PrintLibsOnlyL)) {
1248 @print_flags = grep /^-l/, $o->get_ldflags;
1249 } elsif ($PrintLibsOnlyL) {
1250 @print_flags = grep /^-[LR]/, $o->get_ldflags;
1251 }
1252  
1253 print scalar PkgConfig::_return_context(@print_flags);
1254 print "\n";
1255 exit(0);
1256  
1257 __END__