Debian Codegraph @

inc/Devel/CheckLib.pm

raw
1 # $Id: CheckLib.pm,v 1.25 2008/10/27 12:16:23 drhyde Exp $
2
3 package #
4 Devel::CheckLib; # don't index
5
6 use 5.00405; #postfix foreach
7 use strict;
8 use vars qw($VERSION @ISA @EXPORT);
9 $VERSION = '1.16_03';
10 use Config qw(%Config);
11 use Text::ParseWords qw(quotewords shellwords);
12
13 use File::Spec;
14 use File::Temp;
15 use File::Path qw(rmtree);
16
17 require Exporter;
18 @ISA = qw(Exporter);
19 @EXPORT = qw(assert_lib check_lib_or_exit check_lib);
20
21 # localising prevents the warningness leaking out of this module
22 local $^W = 1; # use warnings is a 5.6-ism
23
24 _findcc(); # bomb out early if there's no compiler
25
26 =head1 NAME
27
28 Devel::CheckLib - check that a library is available
29
30 =head1 DESCRIPTION
31
32 Devel::CheckLib is a perl module that checks whether a particular C
33 library and its headers are available.
34
35 =head1 SYNOPSIS
36
37 use Devel::CheckLib;
38
39 check_lib_or_exit( lib => 'jpeg', header => 'jpeglib.h' );
40 check_lib_or_exit( lib => [ 'iconv', 'jpeg' ] );
41
42 # or prompt for path to library and then do this:
43 check_lib_or_exit( lib => 'jpeg', libpath => $additional_path );
44
45 =head1 USING IT IN Makefile.PL or Build.PL
46
47 If you want to use this from Makefile.PL or Build.PL, do
48 not simply copy the module into your distribution as this may cause
49 problems when PAUSE and search.cpan.org index the distro. Instead, use
50 the use-devel-checklib script.
51
52 =head1 HOW IT WORKS
53
54 You pass named parameters to a function, describing to it how to build
55 and link to the libraries.
56
57 It works by trying to compile some code - which defaults to this:
58
59 int main(int argc, char *argv[]) { return 0; }
60
61 and linking it to the specified libraries. If something pops out the end
62 which looks executable, it gets executed, and if main() returns 0 we know
63 that it worked. That tiny program is
64 built once for each library that you specify, and (without linking) once
65 for each header file.
66
67 If you want to check for the presence of particular functions in a
68 library, or even that those functions return particular results, then
69 you can pass your own function body for main() thus:
70
71 check_lib_or_exit(
72 function => 'foo();if(libversion() > 5) return 0; else return 1;'
73 incpath => ...
74 libpath => ...
75 lib => ...
76 header => ...
77 );
78
79 In that case, it will fail to build if either foo() or libversion() don't
80 exist, and main() will return the wrong value if libversion()'s return
81 value isn't what you want.
82
83 You can also use the C<prologue> parameter to add extra supporting
84 code between the headers and the definition of C<main>.
85
86 =head1 FUNCTIONS
87
88 All of these take the same named parameters and are exported by default.
89 To avoid exporting them, C<use Devel::CheckLib ()>.
90
91 =head2 assert_lib
92
93 This takes several named parameters, all of which are optional, and dies
94 with an error message if any of the libraries listed can
95 not be found. B<Note>: dying in a Makefile.PL or Build.PL may provoke
96 a 'FAIL' report from CPAN Testers' automated smoke testers. Use
97 C<check_lib_or_exit> instead.
98
99 The named parameters are:
100
101 =over
102
103 =item lib
104
105 Must be either a string with the name of a single
106 library or a reference to an array of strings of library names. Depending
107 on the compiler found, library names will be fed to the compiler either as
108 C<-l> arguments or as C<.lib> file names. (E.g. C<-ljpeg> or C<jpeg.lib>)
109
110 =item libpath
111
112 a string or an array of strings
113 representing additional paths to search for libraries.
114
115 =item LIBS
116
117 a C<ExtUtils::MakeMaker>-style space-separated list of
118 libraries (each preceded by '-l') and directories (preceded by '-L').
119
120 This can also be supplied on the command-line.
121
122 =item debug
123
124 If true - emit information during processing that can be used for
125 debugging.
126
127 =back
128
129 And libraries are no use without header files, so ...
130
131 =over
132
133 =item header
134
135 Must be either a string with the name of a single
136 header file or a reference to an array of strings of header file names.
137
138 =item incpath
139
140 a string or an array of strings
141 representing additional paths to search for headers.
142
143 =item INC
144
145 a C<ExtUtils::MakeMaker>-style space-separated list of
146 incpaths, each preceded by '-I'.
147
148 This can also be supplied on the command-line.
149
150 =item ccflags
151
152 Extra flags to pass to the compiler.
153
154 =item ldflags
155
156 Extra flags to pass to the linker.
157
158 =item analyze_binary
159
160 a callback function that will be invoked in order to perform custom
161 analysis of the generated binary. The callback arguments are the
162 library name and the path to the binary just compiled.
163
164 It is possible to use this callback, for instance, to inspect the
165 binary for further dependencies.
166
167 =item not_execute
168
169 Do not try to execute generated binary. Only check that compilation has not failed.
170
171 =back
172
173 =head2 check_lib_or_exit
174
175 This behaves exactly the same as C<assert_lib()> except that instead of
176 dieing, it warns (with exactly the same error message) and exits.
177 This is intended for use in Makefile.PL / Build.PL
178 when you might want to prompt the user for various paths and
179 things before checking that what they've told you is sane.
180
181 If any library or header is missing, it exits with an exit value of 0 to avoid
182 causing a CPAN Testers 'FAIL' report. CPAN Testers should ignore this
183 result -- which is what you want if an external library dependency is not
184 available.
185
186 =head2 check_lib
187
188 This behaves exactly the same as C<assert_lib()> except that it is silent,
189 returning false instead of dieing, or true otherwise.
190
191 =cut
192
193 sub check_lib_or_exit {
194 eval 'assert_lib(@_)';
195 if($@) {
196 warn $@;
197 exit;
198 }
199 }
200
201 sub check_lib {
202 eval 'assert_lib(@_)';
203 return $@ ? 0 : 1;
204 }
205
206 # borrowed from Text::ParseWords
207 sub _parse_line {
208 my($delimiter, $keep, $line) = @_;
209 my($word, @pieces);
210
211 no warnings 'uninitialized'; # we will be testing undef strings
212
213 while (length($line)) {
214 # This pattern is optimised to be stack conservative on older perls.
215 # Do not refactor without being careful and testing it on very long strings.
216 # See Perl bug #42980 for an example of a stack busting input.
217 $line =~ s/^
218 (?:
219 # double quoted string
220 (") # $quote
221 ((?>[^\\"]*(?:\\.[^\\"]*)*))" # $quoted
222 | # --OR--
223 # singe quoted string
224 (') # $quote
225 ((?>[^\\']*(?:\\.[^\\']*)*))' # $quoted
226 | # --OR--
227 # unquoted string
228 ( # $unquoted
229 (?:\\.|[^\\"'])*?
230 )
231 # followed by
232 ( # $delim
233 \Z(?!\n) # EOL
234 | # --OR--
235 (?-x:$delimiter) # delimiter
236 | # --OR--
237 (?!^)(?=["']) # a quote
238 )
239 )//xs or return; # extended layout
240 my ($quote, $quoted, $unquoted, $delim) = (($1 ? ($1,$2) : ($3,$4)), $5, $6);
241
242 return() unless( defined($quote) || length($unquoted) || length($delim));
243
244 if ($keep) {
245 $quoted = "$quote$quoted$quote";
246 }
247 else {
248 $unquoted =~ s/\\(.)/$1/sg;
249 if (defined $quote) {
250 $quoted =~ s/\\(.)/$1/sg if ($quote eq '"');
251 }
252 }
253 $word .= substr($line, 0, 0); # leave results tainted
254 $word .= defined $quote ? $quoted : $unquoted;
255
256 if (length($delim)) {
257 push(@pieces, $word);
258 push(@pieces, $delim) if ($keep eq 'delimiters');
259 undef $word;
260 }
261 if (!length($line)) {
262 push(@pieces, $word);
263 }
264 }
265 return(@pieces);
266 }
267
268 sub _parsewords {
269 return shellwords @_ if $^O ne 'MSWin32';
270 # for Win32, take off "" but leave \
271 map { my $s=$_; $s =~ s/^"(.*)"$/$1/; $s } grep defined && length, quotewords '\s+', 1, @_;
272 }
273
274 sub _compile_cmd {
275 my ($Config_cc, $cc, $cfile, $exefile, $incpaths, $ld, $Config_libs, $libs, $libpaths) = @_;
276 my @sys_cmd = @$cc;
277 if ( $Config_cc eq 'cl' ) { # Microsoft compiler
278 # this is horribly sensitive to the order of arguments
279 push @sys_cmd,
280 $cfile,
281 (defined $libs ? ( map "$_.lib", @$libs ) : ()),
282 "/Fe$exefile",
283 (map '/I'.$_, @$incpaths),
284 "/link",
285 @$ld,
286 _parsewords($Config_libs),
287 (defined $libs ? map '/libpath:'.$_, @$libpaths : ()),
288 ;
289 } elsif($Config_cc =~ /bcc32(\.exe)?/) { # Borland
290 push @sys_cmd,
291 @$ld,
292 (map "-I$_", @$incpaths),
293 "-o$exefile",
294 (defined $libs ? ((map "-L$_", @$libpaths), map "-l$_", @$libs) : ()),
295 $cfile,
296 ;
297 } else { # Unix-ish: gcc, Sun, AIX (gcc, cc), ...
298 push @sys_cmd,
299 (map "-I$_", @$incpaths),
300 $cfile,
301 (!defined $libs ? () : (
302 (map "-L$_", @$libpaths),
303 ($^O eq 'darwin' ? (map { "-Wl,-rpath,$_" } @$libpaths) : ()),
304 map "-l$_", @$libs
305 )),
306 @$ld,
307 "-o", $exefile,
308 ;
309 }
310 @sys_cmd;
311 }
312
313 sub _make_cfile {
314 my ($use_headers, $function, $debug, $prologue) = @_;
315 my $code = '';
316 $code .= qq{#include <$_>\n} for @$use_headers;
317 $code .= "$prologue\n" if defined $prologue;
318 $code .= "int main(int argc, char *argv[]) { ".($function || 'return 0;')." }\n";
319 if ($debug) {
320 (my $c = $code) =~ s:^:# :gm;
321 warn "# Code:\n$c\n";
322 }
323 my ($ch, $cfile) = File::Temp::tempfile(
324 'assertlibXXXXXXXX', SUFFIX => '.c'
325 );
326 print $ch $code;
327 close $ch;
328 (my $ofile = $cfile) =~ s/\.c$/$Config{_o}/;
329 ($cfile, $ofile);
330 }
331
332 sub assert_lib {
333 my %args = @_;
334 $args{$_} = [$args{$_}]
335 for grep $args{$_} && !ref($args{$_}), qw(lib libpath header incpath);
336 my @libs = @{$args{lib} || []};
337 my @libpaths = @{$args{libpath} || []};
338 my @headers = @{$args{header} || []};
339 my @incpaths = @{$args{incpath} || []};
340 my $analyze_binary = $args{analyze_binary};
341 my $execute = !$args{not_execute};
342
343 my @argv = @ARGV;
344 push @argv, _parse_line('\s+', 0, $ENV{PERL_MM_OPT}||'');
345
346 # work-a-like for Makefile.PL's LIBS and INC arguments
347 # if given as command-line argument, append to %args
348 for my $arg (@argv) {
349 for my $mm_attr_key (qw(LIBS INC)) {
350 if (my ($mm_attr_value) = $arg =~ /\A $mm_attr_key = (.*)/x) {
351 # it is tempting to put some \s* into the expression, but the
352 # MM command-line parser only accepts LIBS etc. followed by =,
353 # so we should not be any more lenient with whitespace than that
354 $args{$mm_attr_key} .= " $mm_attr_value";
355 }
356 }
357 }
358
359 my @link_cfgs = map [ \@libpaths, [ $_ ] ], @libs;
360 if(defined($args{LIBS})) {
361 if (ref $args{LIBS}) {
362 foreach my $arg (@{$args{LIBS}}) {
363 my @sep = _parsewords($arg);
364 my @libs = map { /^-l(.+)$/ ? $1 : () } @sep;
365 my @paths = map { /^-L(.+)$/ ? $1 : () } @sep;
366 push @link_cfgs, [ \@paths, \@libs ];
367 }
368 }
369 else {
370 my @libs;
371 my @paths;
372 foreach my $arg (split(' ', $args{LIBS})) {
373 die("LIBS argument badly-formed: $arg\n") unless($arg =~ /^-l/i);
374 push @{$arg =~ /^-l/ ? \@libs : \@paths}, substr($arg, 2);
375 }
376 push @link_cfgs, map [ \@paths, [ $_ ] ], @libs;
377 }
378 }
379 if(defined($args{INC})) {
380 foreach my $arg (_parsewords($args{INC})) {
381 die("INC argument badly-formed: $arg\n") unless($arg =~ /^-I/);
382 push @incpaths, substr($arg, 2);
383 }
384 }
385
386 my ($cc, $ld) = _findcc($args{debug}, $args{ccflags}, $args{ldflags});
387 my @missing;
388 my @wrongresult;
389 my @wronganalysis;
390 my @use_headers;
391
392 # first figure out which headers we can't find ...
393 for my $header (@headers) {
394 push @use_headers, $header;
395 my ($cfile, $ofile) = _make_cfile(\@use_headers, '', $args{debug});
396 my $exefile = File::Temp::mktemp( 'assertlibXXXXXXXX' ) . $Config{_exe};
397 my @sys_cmd = _compile_cmd($Config{cc}, $cc, $cfile, $exefile, \@incpaths, $ld, $Config{libs});
398 warn "# @sys_cmd\n" if $args{debug};
399 my $rv = $args{debug} ? system(@sys_cmd) : _quiet_system(@sys_cmd);
400 push @missing, $header if $rv != 0 || ! -f $exefile;
401 _cleanup_exe($exefile);
402 unlink $cfile;
403 }
404
405 # now do each library in turn with headers
406 my ($cfile, $ofile) = _make_cfile(\@use_headers, @args{qw(function debug prologue)});
407 for my $link_cfg ( @link_cfgs ) {
408 my ($paths, $libs) = @$link_cfg;
409 last if $Config{cc} eq 'CC/DECC'; # VMS
410 my $exefile = File::Temp::mktemp( 'assertlibXXXXXXXX' ) . $Config{_exe};
411 my @sys_cmd = _compile_cmd($Config{cc}, $cc, $cfile, $exefile, \@incpaths, $ld, $Config{libs}, $libs, $paths);
412 warn "# @sys_cmd\n" if $args{debug};
413 local $ENV{LD_RUN_PATH} = join(":", grep $_, @libpaths, $ENV{LD_RUN_PATH}) unless $^O eq 'MSWin32' or $^O eq 'darwin';
414 local $ENV{PATH} = join(";", @libpaths).";".$ENV{PATH} if $^O eq 'MSWin32';
415 my $rv = $args{debug} ? system(@sys_cmd) : _quiet_system(@sys_cmd);
416 if ($rv != 0 || ! -f $exefile) {
417 push @missing, "@$libs";
418 }
419 else {
420 chmod 0755, $exefile;
421 my $absexefile = File::Spec->rel2abs($exefile);
422 $absexefile = '"'.$absexefile.'"' if $absexefile =~ m/\s/;
423 warn "# Execute($execute): $absexefile\n" if $args{debug};
424 if ($execute) {
425 my $retval = system($absexefile);
426 warn "# return value: $retval\n" if $args{debug};
427 push @wrongresult, "@$libs" if $retval != 0;
428 }
429 push @wronganalysis, "@$libs"
430 if $analyze_binary and !$analyze_binary->($libs ? $libs->[0] : undef, $exefile);
431 }
432 _cleanup_exe($exefile);
433 }
434 unlink $cfile;
435
436 my $miss_string = join( q{, }, map qq{'$_'}, @missing );
437 die("Can't link/include C library $miss_string, aborting.\n") if @missing;
438 my $wrong_string = join( q{, }, map qq{'$_'}, @wrongresult);
439 die("wrong result: $wrong_string\n") if @wrongresult;
440 my $analysis_string = join(q{, }, map qq{'$_'}, @wronganalysis );
441 die("wrong analysis: $analysis_string") if @wronganalysis;
442 }
443
444 sub _cleanup_exe {
445 my ($exefile) = @_;
446 my $ofile = $exefile;
447 $ofile =~ s/$Config{_exe}$/$Config{_o}/;
448 # List of files to remove
449 my @rmfiles;
450 push @rmfiles, $exefile, $ofile, "$exefile\.manifest";
451 if ( $Config{cc} eq 'cl' ) {
452 # MSVC also creates foo.ilk and foo.pdb
453 my $ilkfile = $exefile;
454 $ilkfile =~ s/$Config{_exe}$/.ilk/;
455 my $pdbfile = $exefile;
456 $pdbfile =~ s/$Config{_exe}$/.pdb/;
457 push @rmfiles, $ilkfile, $pdbfile;
458 }
459 foreach (grep -f, @rmfiles) {
460 unlink $_ or warn "Could not remove $_: $!";
461 }
462 if ($^O eq "darwin") {
463 # created by clang on darwin
464 my $dsym_dir = $exefile;
465 $dsym_dir =~ s/\Q$Config{_exe}\E$/.dSYM/;
466 rmtree $dsym_dir if -d $dsym_dir;
467 }
468 return
469 }
470
471 # return ($cc, $ld)
472 # where $cc is an array ref of compiler name, compiler flags
473 # where $ld is an array ref of linker flags
474 sub _findcc {
475 my ($debug, $user_ccflags, $user_ldflags) = @_;
476 # Need to use $keep=1 to work with MSWin32 backslashes and quotes
477 my $Config_ccflags = $Config{ccflags}; # use copy so ASPerl will compile
478 $Config_ccflags =~ s:-O\S*::; # stop GCC optimising away test code
479 my @Config_ldflags = ();
480 for my $config_val ( @Config{qw(ldflags)} ){
481 push @Config_ldflags, $config_val if ( $config_val =~ /\S/ );
482 }
483 my @ccflags = grep { length } _parsewords($Config_ccflags||'', $user_ccflags||'');
484 my @ldflags = grep { length && $_ !~ m/^-Wl/ } _parsewords(@Config_ldflags, $user_ldflags||'');
485 my @paths = split(/$Config{path_sep}/, $ENV{PATH});
486 my @cc = _parsewords($Config{cc});
487 if (check_compiler ($cc[0], $debug)) {
488 return ( [ @cc, @ccflags ], \@ldflags );
489 }
490 # Find the extension for executables.
491 my $exe = $Config{_exe};
492 if ($^O eq 'cygwin') {
493 $exe = '';
494 }
495 foreach my $path (@paths) {
496 # Look for "$path/$cc[0].exe"
497 my $compiler = File::Spec->catfile($path, $cc[0]) . $exe;
498 if (check_compiler ($compiler, $debug)) {
499 return ([ $compiler, @cc[1 .. $#cc], @ccflags ], \@ldflags)
500 }
501 next if ! $exe;
502 # Look for "$path/$cc[0]" without the .exe, if necessary.
503 $compiler = File::Spec->catfile($path, $cc[0]);
504 if (check_compiler ($compiler, $debug)) {
505 return ([ $compiler, @cc[1 .. $#cc], @ccflags ], \@ldflags)
506 }
507 }
508 die("Couldn't find your C compiler.\n");
509 }
510
511 sub check_compiler
512 {
513 my ($compiler, $debug) = @_;
514 if (-f $compiler && -x $compiler) {
515 warn "# Compiler seems to be $compiler\n" if $debug;
516 return 1;
517 }
518 warn "# Compiler was not $compiler\n" if $debug;
519 return '';
520 }
521
522
523 # code substantially borrowed from IPC::Run3
524 sub _quiet_system {
525 my (@cmd) = @_;
526
527 # save handles
528 local *STDOUT_SAVE;
529 local *STDERR_SAVE;
530 open STDOUT_SAVE, ">&STDOUT" or die "CheckLib: $! saving STDOUT";
531 open STDERR_SAVE, ">&STDERR" or die "CheckLib: $! saving STDERR";
532
533 # redirect to nowhere
534 local *DEV_NULL;
535 open DEV_NULL, ">" . File::Spec->devnull
536 or die "CheckLib: $! opening handle to null device";
537 open STDOUT, ">&" . fileno DEV_NULL
538 or die "CheckLib: $! redirecting STDOUT to null handle";
539 open STDERR, ">&" . fileno DEV_NULL
540 or die "CheckLib: $! redirecting STDERR to null handle";
541
542 # run system command
543 my $rv = system(@cmd);
544
545 # restore handles
546 open STDOUT, ">&" . fileno STDOUT_SAVE
547 or die "CheckLib: $! restoring STDOUT handle";
548 open STDERR, ">&" . fileno STDERR_SAVE
549 or die "CheckLib: $! restoring STDERR handle";
550
551 return $rv;
552 }
553
554 =head1 PLATFORMS SUPPORTED
555
556 You must have a C compiler installed. We check for C<$Config{cc}>,
557 both literally as it is in Config.pm and also in the $PATH.
558
559 It has been tested with varying degrees of rigorousness on:
560
561 =over
562
563 =item gcc (on Linux, *BSD, Mac OS X, Solaris, Cygwin)
564
565 =item Sun's compiler tools on Solaris
566
567 =item IBM's tools on AIX
568
569 =item SGI's tools on Irix 6.5
570
571 =item Microsoft's tools on Windows
572
573 =item MinGW on Windows (with Strawberry Perl)
574
575 =item Borland's tools on Windows
576
577 =item QNX
578
579 =back
580
581 =head1 WARNINGS, BUGS and FEEDBACK
582
583 This is a very early release intended primarily for feedback from
584 people who have discussed it. The interface may change and it has
585 not been adequately tested.
586
587 Feedback is most welcome, including constructive criticism.
588 Bug reports should be made using L<http://rt.cpan.org/> or by email.
589
590 When submitting a bug report, please include the output from running:
591
592 perl -V
593 perl -MDevel::CheckLib -e0
594
595 =head1 SEE ALSO
596
597 L<Devel::CheckOS>
598
599 L<Probe::Perl>
600
601 =head1 AUTHORS
602
603 David Cantrell E<lt>[email protected]<gt>
604
605 David Golden E<lt>[email protected]<gt>
606
607 Yasuhiro Matsumoto E<lt>[email protected]<gt>
608
609 Thanks to the cpan-testers-discuss mailing list for prompting us to write it
610 in the first place;
611
612 to Chris Williams for help with Borland support;
613
614 to Tony Cook for help with Microsoft compiler command-line options
615
616 =head1 COPYRIGHT and LICENCE
617
618 Copyright 2007 David Cantrell. Portions copyright 2007 David Golden.
619
620 This module is free-as-in-speech software, and may be used, distributed,
621 and modified under the same conditions as perl itself.
622
623 =head1 CONSPIRACY
624
625 This module is also free-as-in-mason software.
626
627 =cut
628
629 1;