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;
5
6 use 5.00405; #postfix foreach
7 use strict;
8 use vars qw($VERSION @ISA @EXPORT);
9 $VERSION = '0.98';
10 use Config qw(%Config);
11 use Text::ParseWords 'quotewords';
12
13 use File::Spec;
14 use File::Temp;
15
16 require Exporter;
17 @ISA = qw(Exporter);
18 @EXPORT = qw(assert_lib check_lib_or_exit check_lib);
19
20 # localising prevents the warningness leaking out of this module
21 local $^W = 1; # use warnings is a 5.6-ism
22
23 _findcc(); # bomb out early if there's no compiler
24
25 =head1 NAME
26
27 Devel::CheckLib - check that a library is available
28
29 =head1 DESCRIPTION
30
31 Devel::CheckLib is a perl module that checks whether a particular C
32 library and its headers are available.
33
34 =head1 SYNOPSIS
35
36 use Devel::CheckLib;
37
38 check_lib_or_exit( lib => 'jpeg', header => 'jpeglib.h' );
39 check_lib_or_exit( lib => [ 'iconv', 'jpeg' ] );
40
41 # or prompt for path to library and then do this:
42 check_lib_or_exit( lib => 'jpeg', libpath => $additional_path );
43
44 =head1 USING IT IN Makefile.PL or Build.PL
45
46 If you want to use this from Makefile.PL or Build.PL, do
47 not simply copy the module into your distribution as this may cause
48 problems when PAUSE and search.cpan.org index the distro. Instead, use
49 the use-devel-checklib script.
50
51 =head1 HOW IT WORKS
52
53 You pass named parameters to a function, describing to it how to build
54 and link to the libraries.
55
56 It works by trying to compile some code - which defaults to this:
57
58 int main(void) { return 0; }
59
60 and linking it to the specified libraries. If something pops out the end
61 which looks executable, it gets executed, and if main() returns 0 we know
62 that it worked. That tiny program is
63 built once for each library that you specify, and (without linking) once
64 for each header file.
65
66 If you want to check for the presence of particular functions in a
67 library, or even that those functions return particular results, then
68 you can pass your own function body for main() thus:
69
70 check_lib_or_exit(
71 function => 'foo();if(libversion() > 5) return 0; else return 1;'
72 incpath => ...
73 libpath => ...
74 lib => ...
75 header => ...
76 );
77
78 In that case, it will fail to build if either foo() or libversion() don't
79 exist, and main() will return the wrong value if libversion()'s return
80 value isn't what you want.
81
82 =head1 FUNCTIONS
83
84 All of these take the same named parameters and are exported by default.
85 To avoid exporting them, C<use Devel::CheckLib ()>.
86
87 =head2 assert_lib
88
89 This takes several named parameters, all of which are optional, and dies
90 with an error message if any of the libraries listed can
91 not be found. B<Note>: dying in a Makefile.PL or Build.PL may provoke
92 a 'FAIL' report from CPAN Testers' automated smoke testers. Use
93 C<check_lib_or_exit> instead.
94
95 The named parameters are:
96
97 =over
98
99 =item lib
100
101 Must be either a string with the name of a single
102 library or a reference to an array of strings of library names. Depending
103 on the compiler found, library names will be fed to the compiler either as
104 C<-l> arguments or as C<.lib> file names. (E.g. C<-ljpeg> or C<jpeg.lib>)
105
106 =item libpath
107
108 a string or an array of strings
109 representing additional paths to search for libraries.
110
111 =item LIBS
112
113 a C<ExtUtils::MakeMaker>-style space-seperated list of
114 libraries (each preceded by '-l') and directories (preceded by '-L').
115
116 This can also be supplied on the command-line.
117
118 =back
119
120 And libraries are no use without header files, so ...
121
122 =over
123
124 =item header
125
126 Must be either a string with the name of a single
127 header file or a reference to an array of strings of header file names.
128
129 =item incpath
130
131 a string or an array of strings
132 representing additional paths to search for headers.
133
134 =item INC
135
136 a C<ExtUtils::MakeMaker>-style space-seperated list of
137 incpaths, each preceded by '-I'.
138
139 This can also be supplied on the command-line.
140
141 =back
142
143 =head2 check_lib_or_exit
144
145 This behaves exactly the same as C<assert_lib()> except that instead of
146 dieing, it warns (with exactly the same error message) and exits.
147 This is intended for use in Makefile.PL / Build.PL
148 when you might want to prompt the user for various paths and
149 things before checking that what they've told you is sane.
150
151 If any library or header is missing, it exits with an exit value of 0 to avoid
152 causing a CPAN Testers 'FAIL' report. CPAN Testers should ignore this
153 result -- which is what you want if an external library dependency is not
154 available.
155
156 =head2 check_lib
157
158 This behaves exactly the same as C<assert_lib()> except that it is silent,
159 returning false instead of dieing, or true otherwise.
160
161 =cut
162
163 sub check_lib_or_exit {
164 eval 'assert_lib(@_)';
165 if($@) {
166 warn $@;
167 exit;
168 }
169 }
170
171 sub check_lib {
172 eval 'assert_lib(@_)';
173 return $@ ? 0 : 1;
174 }
175
176 sub assert_lib {
177 my %args = @_;
178 my (@libs, @libpaths, @headers, @incpaths);
179
180 # FIXME: these four just SCREAM "refactor" at me
181 @libs = (ref($args{lib}) ? @{$args{lib}} : $args{lib})
182 if $args{lib};
183 @libpaths = (ref($args{libpath}) ? @{$args{libpath}} : $args{libpath})
184 if $args{libpath};
185 @headers = (ref($args{header}) ? @{$args{header}} : $args{header})
186 if $args{header};
187 @incpaths = (ref($args{incpath}) ? @{$args{incpath}} : $args{incpath})
188 if $args{incpath};
189
190 # work-a-like for Makefile.PL's LIBS and INC arguments
191 # if given as command-line argument, append to %args
192 for my $arg (@ARGV) {
193 for my $mm_attr_key (qw(LIBS INC)) {
194 if (my ($mm_attr_value) = $arg =~ /\A $mm_attr_key = (.*)/x) {
195 # it is tempting to put some \s* into the expression, but the
196 # MM command-line parser only accepts LIBS etc. followed by =,
197 # so we should not be any more lenient with whitespace than that
198 $args{$mm_attr_key} .= " $mm_attr_value";
199 }
200 }
201 }
202
203 # using special form of split to trim whitespace
204 if(defined($args{LIBS})) {
205 foreach my $arg (split(' ', $args{LIBS})) {
206 die("LIBS argument badly-formed: $arg\n") unless($arg =~ /^-l/i);
207 push @{$arg =~ /^-l/ ? \@libs : \@libpaths}, substr($arg, 2);
208 }
209 }
210 if(defined($args{INC})) {
211 foreach my $arg (split(' ', $args{INC})) {
212 die("INC argument badly-formed: $arg\n") unless($arg =~ /^-I/);
213 push @incpaths, substr($arg, 2);
214 }
215 }
216
217 my ($cc, $ld) = _findcc();
218 my @missing;
219 my @wrongresult;
220 my @use_headers;
221
222 # first figure out which headers we can't find ...
223 for my $header (@headers) {
224 push @use_headers, $header;
225 my($ch, $cfile) = File::Temp::tempfile(
226 'assertlibXXXXXXXX', SUFFIX => '.c'
227 );
228 my $ofile = $cfile;
229 $ofile =~ s/\.c$/$Config{_o}/;
230 print $ch qq{#include <$_>\n} for @use_headers;
231 print $ch qq{int main(void) { return 0; }\n};
232 close($ch);
233 my $exefile = File::Temp::mktemp( 'assertlibXXXXXXXX' ) . $Config{_exe};
234 my @sys_cmd;
235 # FIXME: re-factor - almost identical code later when linking
236 if ( $Config{cc} eq 'cl' ) { # Microsoft compiler
237 require Win32;
238 @sys_cmd = (
239 @$cc,
240 $cfile,
241 "/Fe$exefile",
242 (map { '/I'.Win32::GetShortPathName($_) } @incpaths),
243 "/link",
244 @$ld
245 );
246 } elsif($Config{cc} =~ /bcc32(\.exe)?/) { # Borland
247 @sys_cmd = (
248 @$cc,
249 @$ld,
250 (map { "-I$_" } @incpaths),
251 "-o$exefile",
252 $cfile
253 );
254 } else { # Unix-ish: gcc, Sun, AIX (gcc, cc), ...
255 @sys_cmd = (
256 @$cc,
257 @$ld,
258 $cfile,
259 (map { "-I$_" } @incpaths),
260 "-o", "$exefile"
261 );
262 }
263 warn "# @sys_cmd\n" if $args{debug};
264 my $rv = $args{debug} ? system(@sys_cmd) : _quiet_system(@sys_cmd);
265 push @missing, $header if $rv != 0 || ! -x $exefile;
266 _cleanup_exe($exefile);
267 unlink $ofile if -e $ofile;
268 unlink $cfile;
269 }
270
271 # now do each library in turn with headers
272 my($ch, $cfile) = File::Temp::tempfile(
273 'assertlibXXXXXXXX', SUFFIX => '.c'
274 );
275 my $ofile = $cfile;
276 $ofile =~ s/\.c$/$Config{_o}/;
277 print $ch qq{#include <$_>\n} foreach (@headers);
278 print $ch "int main(void) { ".($args{function} || 'return 0;')." }\n";
279 close($ch);
280
281 my $exefile = File::Temp::mktemp( 'assertlibXXXXXXXX' ) . $Config{_exe};
282 my @sys_cmd;
283 if ( $Config{cc} eq 'cl' ) { # Microsoft compiler
284 require Win32;
285 my @libpath = map {
286 q{/libpath:} . Win32::GetShortPathName($_)
287 } @libpaths;
288 # this is horribly sensitive to the order of arguments
289 @sys_cmd = (
290 @$cc,
291 $cfile,
292 (map { "$_.lib" } @libs),
293 "/Fe$exefile",
294 (map { '/I'.Win32::GetShortPathName($_) } @incpaths),
295 "/link",
296 @$ld,
297 (map {'/libpath:'.Win32::GetShortPathName($_)} @libpaths),
298 );
299 } elsif($Config{cc} eq 'CC/DECC') { # VMS
300 } elsif($Config{cc} =~ /bcc32(\.exe)?/) { # Borland
301 @sys_cmd = (
302 @$cc,
303 @$ld,
304 "-o$exefile",
305 (map { "-I$_" } @incpaths),
306 (map { "-L$_" } @libpaths),
307 (map { "-l$_" } @libs),
308 $cfile);
309 } else { # Unix-ish
310 # gcc, Sun, AIX (gcc, cc)
311 @sys_cmd = (
312 @$cc,
313 @$ld,
314 $cfile,
315 "-o", "$exefile",
316 (map { "-I$_" } @incpaths),
317 (map { "-L$_" } @libpaths),
318 (map { "-l$_" } @libs),
319 );
320 }
321 warn "# @sys_cmd\n" if $args{debug};
322 my $rv = $args{debug} ? system(@sys_cmd) : _quiet_system(@sys_cmd);
323 push @missing, @libs if $rv != 0 || ! -x $exefile;
324 my $absexefile = File::Spec->rel2abs($exefile);
325 $absexefile = '"'.$absexefile.'"' if $absexefile =~ m/\s/;
326 push @wrongresult, @libs if $rv == 0 && -x $exefile && system($absexefile) != 0;
327 unlink $ofile if -e $ofile;
328 _cleanup_exe($exefile);
329
330 unlink $cfile;
331
332 my $miss_string = join( q{, }, map { qq{'$_'} } @missing );
333 die("Can't link/include C library $miss_string, aborting.\n") if @missing;
334 my $wrong_string = join( q{, }, map { qq{'$_'} } @wrongresult);
335 die("wrong result: $wrong_string\n") if @wrongresult;
336 }
337
338 sub _cleanup_exe {
339 my ($exefile) = @_;
340 my $ofile = $exefile;
341 $ofile =~ s/$Config{_exe}$/$Config{_o}/;
342 unlink $exefile if -f $exefile;
343 unlink $ofile if -f $ofile;
344 unlink "$exefile\.manifest" if -f "$exefile\.manifest";
345 if ( $Config{cc} eq 'cl' ) {
346 # MSVC also creates foo.ilk and foo.pdb
347 my $ilkfile = $exefile;
348 $ilkfile =~ s/$Config{_exe}$/.ilk/;
349 my $pdbfile = $exefile;
350 $pdbfile =~ s/$Config{_exe}$/.pdb/;
351 unlink $ilkfile if -f $ilkfile;
352 unlink $pdbfile if -f $pdbfile;
353 }
354 return
355 }
356
357 # return ($cc, $ld)
358 # where $cc is an array ref of compiler name, compiler flags
359 # where $ld is an array ref of linker flags
360 sub _findcc {
361 # Need to use $keep=1 to work with MSWin32 backslashes and quotes
362 my $Config_ccflags = $Config{ccflags}; # use copy so ASPerl will compile
363 my @Config_ldflags = ();
364 for my $config_val ( @Config{qw(ldflags perllibs)} ){
365 push @Config_ldflags, $config_val if ( $config_val =~ /\S/ );
366 }
367 my @ccflags = grep { length } quotewords('\s+', 1, $Config_ccflags||'');
368 my @ldflags = grep { length } quotewords('\s+', 1, @Config_ldflags);
369 my @paths = split(/$Config{path_sep}/, $ENV{PATH});
370 my @cc = split(/\s+/, $Config{cc});
371 return ( [ @cc, @ccflags ], \@ldflags ) if -x $cc[0];
372 foreach my $path (@paths) {
373 my $compiler = File::Spec->catfile($path, $cc[0]) . $Config{_exe};
374 return ([ $compiler, @cc[1 .. $#cc], @ccflags ], \@ldflags)
375 if -x $compiler;
376 }
377 die("Couldn't find your C compiler\n");
378 }
379
380 # code substantially borrowed from IPC::Run3
381 sub _quiet_system {
382 my (@cmd) = @_;
383
384 # save handles
385 local *STDOUT_SAVE;
386 local *STDERR_SAVE;
387 open STDOUT_SAVE, ">&STDOUT" or die "CheckLib: $! saving STDOUT";
388 open STDERR_SAVE, ">&STDERR" or die "CheckLib: $! saving STDERR";
389
390 # redirect to nowhere
391 local *DEV_NULL;
392 open DEV_NULL, ">" . File::Spec->devnull
393 or die "CheckLib: $! opening handle to null device";
394 open STDOUT, ">&" . fileno DEV_NULL
395 or die "CheckLib: $! redirecting STDOUT to null handle";
396 open STDERR, ">&" . fileno DEV_NULL
397 or die "CheckLib: $! redirecting STDERR to null handle";
398
399 # run system command
400 my $rv = system(@cmd);
401
402 # restore handles
403 open STDOUT, ">&" . fileno STDOUT_SAVE
404 or die "CheckLib: $! restoring STDOUT handle";
405 open STDERR, ">&" . fileno STDERR_SAVE
406 or die "CheckLib: $! restoring STDERR handle";
407
408 return $rv;
409 }
410
411 =head1 PLATFORMS SUPPORTED
412
413 You must have a C compiler installed. We check for C<$Config{cc}>,
414 both literally as it is in Config.pm and also in the $PATH.
415
416 It has been tested with varying degrees on rigourousness on:
417
418 =over
419
420 =item gcc (on Linux, *BSD, Mac OS X, Solaris, Cygwin)
421
422 =item Sun's compiler tools on Solaris
423
424 =item IBM's tools on AIX
425
426 =item SGI's tools on Irix 6.5
427
428 =item Microsoft's tools on Windows
429
430 =item MinGW on Windows (with Strawberry Perl)
431
432 =item Borland's tools on Windows
433
434 =item QNX
435
436 =back
437
438 =head1 WARNINGS, BUGS and FEEDBACK
439
440 This is a very early release intended primarily for feedback from
441 people who have discussed it. The interface may change and it has
442 not been adequately tested.
443
444 Feedback is most welcome, including constructive criticism.
445 Bug reports should be made using L<http://rt.cpan.org/> or by email.
446
447 When submitting a bug report, please include the output from running:
448
449 perl -V
450 perl -MDevel::CheckLib -e0
451
452 =head1 SEE ALSO
453
454 L<Devel::CheckOS>
455
456 L<Probe::Perl>
457
458 =head1 AUTHORS
459
460 David Cantrell E<lt>[email protected]<gt>
461
462 David Golden E<lt>[email protected]<gt>
463
464 Yasuhiro Matsumoto E<lt>[email protected]<gt>
465
466 Thanks to the cpan-testers-discuss mailing list for prompting us to write it
467 in the first place;
468
469 to Chris Williams for help with Borland support;
470
471 to Tony Cook for help with Microsoft compiler command-line options
472
473 =head1 COPYRIGHT and LICENCE
474
475 Copyright 2007 David Cantrell. Portions copyright 2007 David Golden.
476
477 This module is free-as-in-speech software, and may be used, distributed,
478 and modified under the same conditions as perl itself.
479
480 =head1 CONSPIRACY
481
482 This module is also free-as-in-mason software.
483
484 =cut
485
486 1;