Debian Codegraph @

lib/FFI/Probe.pm

raw
1 package FFI::Probe;
2
3 use strict;
4 use warnings;
5 use 5.008004;
6 use File::Basename qw( dirname );
7 use Data::Dumper ();
8 use FFI::Probe::Runner;
9 use FFI::Build;
10 use FFI::Build::File::C;
11 use Capture::Tiny qw( capture_merged capture );
12 use FFI::Temp;
13
14 # ABSTRACT: System detection and probing for FFI extensions.
15 our $VERSION = '2.12'; # VERSION
16
17
18 sub new
19 {
20 my($class, %args) = @_;
21
22 $args{log} ||= "ffi-probe.log";
23 $args{data_filename} ||= "ffi-probe.pl";
24
25 unless(ref $args{log})
26 {
27 my $fn = $args{log};
28 my $fh;
29 open $fh, '>>', $fn;
30 $args{log} = $fh;
31 }
32
33 my $data;
34
35 if(-r $args{data_filename})
36 {
37 my $fn = $args{data_filename};
38 unless($data = do $fn)
39 {
40 die "couldn't parse configuration $fn $@" if $@;
41 die "couldn't do $fn $!" if $!;
42 die "bad or missing config file $fn";
43 }
44 }
45
46 $data ||= {};
47
48 my $self = bless {
49 headers => [],
50 log => $args{log},
51 data_filename => $args{data_filename},
52 data => $data,
53 dir => FFI::Temp->newdir( TEMPLATE => 'ffi-probe-XXXXXX' ),
54 counter => 0,
55 runner => $args{runner},
56 alien => $args{alien} || [],
57 cflags => $args{cflags},
58 libs => $args{libs},
59 }, $class;
60
61 $self;
62 }
63
64 sub _runner
65 {
66 my($self) = @_;
67 $self->{runner} ||= FFI::Probe::Runner->new;
68 }
69
70
71 sub check_header
72 {
73 my($self, $header) = @_;
74
75 return if defined $self->{data}->{header}->{$header};
76
77 my $code = '';
78 $code .= "#include <$_>\n" for @{ $self->{headers} }, $header;
79
80 my $build = FFI::Build->new("hcheck@{[ ++$self->{counter} ]}",
81 verbose => 2,
82 dir => $self->{dir},
83 alien => $self->{alien},
84 cflags => $self->{cflags},
85 libs => $self->{libs},
86 );
87 my $file = FFI::Build::File::C->new(
88 \$code,
89 dir => $self->{dir},
90 build => $build,
91 );
92 my($out, $o) = capture_merged {
93 eval { $file->build_item };
94 };
95 $self->log_code($code);
96 $self->log($out);
97 if($o)
98 {
99 $self->set('header', $header => 1);
100 push @{ $self->{headers} }, $header;
101 return 1;
102 }
103 else
104 {
105 $self->set('header', $header => 0);
106 return;
107 }
108 }
109
110
111 sub check_cpp
112 {
113 my($self, $code) = @_;
114
115 my $build = FFI::Build->new("hcheck@{[ ++$self->{counter} ]}",
116 verbose => 2,
117 dir => $self->{dir},
118 alien => $self->{alien},
119 cflags => $self->{cflags},
120 libs => $self->{libs},
121 );
122 my $file = FFI::Build::File::C->new(
123 \$code,
124 dir => $self->{dir},
125 build => $build,
126 );
127 my($out, $i) = capture_merged {
128 eval { $file->build_item_cpp };
129 };
130 $self->log_code($code);
131 $self->log($out);
132
133 if($i && -f $i->path)
134 {
135 return $i->slurp;
136 }
137 else
138 {
139 return;
140 }
141 }
142
143
144 sub check_eval
145 {
146 my($self, %args) = @_;
147
148 my $code = $args{_template} || $self->template;
149
150 my $headers = join "", map { "#include <$_>\n" } (@{ $self->{headers} }, @{ $args{headers} || [] });
151 my @decl = @{ $args{decl} || [] };
152 my @stmt = @{ $args{stmt} || [] };
153 my %eval = %{ $args{eval} || {} };
154
155 $code =~ s/##HEADERS##/$headers/;
156 $code =~ s/##DECL##/join "\n", @decl/e;
157 $code =~ s/##STMT##/join "\n", @stmt/e;
158
159 my $eval = '';
160 my $i=0;
161 my %map;
162 foreach my $key (sort keys %eval)
163 {
164 $i++;
165 $map{$key} = "eval$i";
166 my($format,$expression) = @{ $eval{$key} };
167 $eval .= " printf(\"eval$i=<<<$format>>>\\n\", $expression);\n";
168 }
169
170 $code =~ s/##EVAL##/$eval/;
171
172 my $build = FFI::Build->new("eval@{[ ++$self->{counter} ]}",
173 verbose => 2,
174 dir => $self->{dir},
175 alien => $self->{alien},
176 cflags => $self->{cflags},
177 libs => $self->{libs},
178 export => ['dlmain'],
179 );
180 $build->source(
181 FFI::Build::File::C->new(
182 \$code,
183 dir => $self->{dir},
184 build => $build,
185 ),
186 );
187
188 my $lib = do {
189 my($out, $lib, $error) = capture_merged {
190 my $lib = eval {
191 $build->build;
192 };
193 ($lib, $@);
194 };
195
196 $self->log_code($code);
197 $self->log("[build]");
198 $self->log($out);
199 if($error)
200 {
201 $self->log("exception: $error");
202 return;
203 }
204 elsif(!$lib)
205 {
206 $self->log("failed");
207 return;
208 }
209 $lib;
210 };
211
212 my $result = $self->_runner->run($lib->path);
213
214 $self->log("[stdout]");
215 $self->log($result->stdout);
216 $self->log("[stderr]");
217 $self->log($result->stderr);
218 $self->log("rv = @{[ $result->rv ]}");
219 $self->log("sig = @{[ $result->signal ]}") if $result->signal;
220
221 if($result->pass)
222 {
223 foreach my $key (sort keys %eval)
224 {
225 my $eval = $map{$key};
226 if($result->stdout =~ /$eval=<<<(.*?)>>>/)
227 {
228 my $value = $1;
229 my @key = split /\./, $key;
230 $self->set(@key, $value);
231 }
232 }
233 return 1;
234 }
235 else
236 {
237 return;
238 }
239 }
240
241
242 sub check
243 {
244 my($self, $name, $code) = @_;
245 if($self->check_eval(_template => $code))
246 {
247 $self->set('probe', $name, 1);
248 return 1;
249 }
250 else
251 {
252 $self->set('probe', $name, 0);
253 return;
254 }
255 }
256
257
258 sub check_type_int
259 {
260 my($self, $type) = @_;
261
262 $self->check_header('stddef.h');
263
264 my $ret = $self->check_eval(
265 decl => [
266 '#define signed(type) (((type)-1) < 0) ? "signed" : "unsigned"',
267 "struct align { char a; $type b; };",
268 ],
269 eval => {
270 "type.$type.size" => [ '%d' => "(int)sizeof($type)" ],
271 "type.$type.sign" => [ '%s' => "signed($type)" ],
272 "type.$type.align" => [ '%d' => '(int)offsetof(struct align, b)' ],
273 },
274 );
275
276 return unless $ret;
277
278 my $size = $self->data->{type}->{$type}->{size};
279 my $sign = $self->data->{type}->{$type}->{sign};
280
281 sprintf("%sint%d", $sign eq 'signed' ? 's' : 'u', $size*8);
282 }
283
284
285 sub check_type_enum
286 {
287 my($self) = @_;
288
289 $self->check_header('stddef.h');
290
291 my $ret = $self->check_eval(
292 decl => [
293 '#define signed(type) (((type)-1) < 0) ? "signed" : "unsigned"',
294 "typedef enum { ONE, TWO } myenum;",
295 "struct align { char a; myenum b; };",
296 ],
297 eval => {
298 "type.enum.size" => [ '%d' => '(int)sizeof(myenum)' ],
299 "type.enum.sign" => [ '%s' => 'signed(myenum)' ],
300 "type.enum.align" => [ '%d' => '(int)offsetof(struct align, b)' ],
301 },
302 );
303
304 return unless $ret;
305
306 my $size = $self->data->{type}->{enum}->{size};
307 my $sign = $self->data->{type}->{enum}->{sign};
308
309 sprintf("%sint%d", $sign eq 'signed' ? 's' : 'u', $size*8);
310 }
311
312
313 sub check_type_signed_enum
314 {
315 my($self) = @_;
316
317 $self->check_header('stddef.h');
318
319 my $ret = $self->check_eval(
320 decl => [
321 '#define signed(type) (((type)-1) < 0) ? "signed" : "unsigned"',
322 "typedef enum { NEG = -1, ONE = 1, TWO = 2 } myenum;",
323 "struct align { char a; myenum b; };",
324 ],
325 eval => {
326 "type.senum.size" => [ '%d' => '(int)sizeof(myenum)' ],
327 "type.senum.sign" => [ '%s' => 'signed(myenum)' ],
328 "type.senum.align" => [ '%d' => '(int)offsetof(struct align, b)' ],
329 },
330 );
331
332 return unless $ret;
333
334 my $size = $self->data->{type}->{senum}->{size};
335 my $sign = $self->data->{type}->{senum}->{sign};
336
337 sprintf("%sint%d", $sign eq 'signed' ? 's' : 'u', $size*8);
338 }
339
340
341 sub check_type_float
342 {
343 my($self, $type) = @_;
344
345 $self->check_header('stddef.h');
346
347 my $ret = $self->check_eval(
348 decl => [
349 "struct align { char a; $type b; };",
350 ],
351 eval => {
352 "type.$type.size" => [ '%d' => "(int)sizeof($type)" ],
353 "type.$type.align" => [ '%d' => '(int)offsetof(struct align, b)' ],
354 },
355 );
356
357 return unless $ret;
358
359 my $size = $self->data->{type}->{$type}->{size};
360 my $complex = !!($type =~ /complex/);
361
362 if($complex) {
363 $size /= 2;
364 }
365
366 my $t;
367 if($size == 4)
368 { $t = 'float' }
369 elsif($size == 8)
370 { $t = 'double' }
371 elsif($size > 9)
372 { $t = 'longdouble' }
373
374 $t = "complex_$t" if $complex;
375
376 $t;
377 }
378
379
380 sub check_type_pointer
381 {
382 my($self) = @_;
383
384 $self->check_header('stddef.h');
385
386 my $ret = $self->check_eval(
387 decl => [
388 "struct align { char a; void* b; };",
389 ],
390 eval => {
391 "type.pointer.size" => [ '%d' => '(int)sizeof(void *)' ],
392 "type.pointer.align" => [ '%d' => '(int)offsetof(struct align, b)' ],
393 },
394 );
395
396 return unless $ret;
397 'pointer';
398 }
399
400 sub _set
401 {
402 my($data, $value, @key) = @_;
403 my $key = shift @key;
404 if(@key > 0)
405 {
406 _set($data->{$key} ||= {}, $value, @key);
407 }
408 else
409 {
410 $data->{$key} = $value;
411 }
412 }
413
414
415 sub set
416 {
417 my $self = shift;
418 my $value = pop;
419 my @key = @_;
420
421 my $print_value = $value;
422 if(ref $print_value)
423 {
424 my $d = Data::Dumper->new([$value], [qw($value)]);
425 $d->Indent(0);
426 $d->Terse(1);
427 $print_value = $d->Dump;
428 }
429
430 my $key = join ".", map { /\./ ? "\"$_\"" : $_ } @key;
431 print "PR $key=$print_value\n";
432 $self->log("$key=$print_value");
433 _set($self->{data}, $value, @key);
434 }
435
436
437 sub save
438 {
439 my($self) = @_;
440
441 my $dir = dirname($self->{data_filename});
442
443 my $dd = Data::Dumper->new([$self->{data}],['x'])
444 ->Indent(1)
445 ->Terse(0)
446 ->Purity(1)
447 ->Sortkeys(1)
448 ->Dump;
449
450 mkpath( $dir, 0, oct(755) ) unless -d $dir;
451
452 my $fh;
453 open($fh, '>', $self->{data_filename}) || die "error writing @{[ $self->{data_filename} ]}";
454 print $fh 'do { my ';
455 print $fh $dd;
456 print $fh '$x;}';
457 close $fh;
458 }
459
460
461 sub data { shift->{data} }
462
463
464 sub log
465 {
466 my($self, $string) = @_;
467 my $fh = $self->{log};
468 chomp $string;
469 print $fh $string, "\n";
470 }
471
472
473 sub log_code
474 {
475 my($self, $code) = @_;
476 my @code = split /\n/, $code;
477 chomp for @code;
478 $self->log("code: $_") for @code;
479 }
480
481 sub DESTROY
482 {
483 my($self) = @_;
484 $self->save;
485 my $fh = $self->{log};
486 return unless defined $fh;
487 close $fh;
488 }
489
490 my $template;
491
492
493 sub template
494 {
495 unless(defined $template)
496 {
497 local $/;
498 $template = <DATA>;
499 }
500
501 $template;
502 }
503
504 1;
505
506 =pod
507
508 =encoding UTF-8
509
510 =head1 NAME
511
512 FFI::Probe - System detection and probing for FFI extensions.
513
514 =head1 VERSION
515
516 version 2.12
517
518 =head1 SYNOPSIS
519
520 use FFI::Probe;
521
522 my $probe = FFI::Probe->new;
523 $probe->check_header('foo.h');
524 ...
525
526 =head1 DESCRIPTION
527
528 This class provides an interface for probing for system
529 capabilities. It is used internally as part of the
530 L<FFI::Platypus> build process, but it may also be useful
531 for extensions that use Platypus as well.
532
533 =head1 CONSTRUCTOR
534
535 =head2 new
536
537 my $probe = FFI::Probe->new(%args);
538
539 Creates a new instance.
540
541 =over 4
542
543 =item log
544
545 Path to a log or file handle to write to.
546
547 =item data_filename
548
549 Path to a file which will be used to store/cache results.
550
551 =back
552
553 =head1 METHODS
554
555 =head2 check_header
556
557 my $bool = $probe->check_header($header);
558
559 Checks that the given C header file is available.
560 Stores the result, and returns a true/false value.
561
562 =head2 check_cpp
563
564 =head2 check_eval
565
566 my $bool = $probe>check_eval(%args);
567
568 =over 4
569
570 =item headers
571
572 Any additional headers.
573
574 =item decl
575
576 Any C declarations that need to be made before the C<dlmain> function.
577
578 =item stmt
579
580 Any C statements that should be made before the evaluation.
581
582 =item eval
583
584 Any evaluations that should be returned.
585
586 =back
587
588 =head2 check
589
590 =head2 check_type_int
591
592 my $type = $probe->check_type_int($type);
593
594 =head2 check_type_enum
595
596 my $type = $probe->check_type_enum;
597
598 =head2 check_type_enum
599
600 my $type = $probe->check_type_enum;
601
602 =head2 check_type_float
603
604 my $type = $probe->check_type_float($type);
605
606 =head2 check_type_pointer
607
608 my $type = $probe->check_type_pointer;
609
610 =head2 set
611
612 $probe->set(@key, $value);
613
614 Used internally to store a value.
615
616 =head2 save
617
618 $probe->save;
619
620 Saves the values already detected.
621
622 =head2 data
623
624 my $data = $probe->data;
625
626 Returns a hashref of the data already detected.
627
628 =head2 log
629
630 $probe->log($string);
631
632 Sends the given string to the log.
633
634 =head2 log_code
635
636 $prbe->log_code($string);
637
638 Sends the given multi-line code block to the log.
639
640 =head2 template
641
642 my $template = $probe->template;
643
644 Returns the C code template used for C<check_eval> and other
645 C<check_> methods.
646
647 =head1 AUTHOR
648
649 Author: Graham Ollis E<lt>[email protected]<gt>
650
651 Contributors:
652
653 Bakkiaraj Murugesan (bakkiaraj)
654
655 Dylan Cali (calid)
656
657 pipcet
658
659 Zaki Mughal (zmughal)
660
661 Fitz Elliott (felliott)
662
663 Vickenty Fesunov (vyf)
664
665 Gregor Herrmann (gregoa)
666
667 Shlomi Fish (shlomif)
668
669 Damyan Ivanov
670
671 Ilya Pavlov (Ilya33)
672
673 Petr Písař (ppisar)
674
675 Mohammad S Anwar (MANWAR)
676
677 Håkon Hægland (hakonhagland, HAKONH)
678
679 Meredith (merrilymeredith, MHOWARD)
680
681 Diab Jerius (DJERIUS)
682
683 Eric Brine (IKEGAMI)
684
685 szTheory
686
687 José Joaquín Atria (JJATRIA)
688
689 Pete Houston (openstrike, HOUSTON)
690
691 Lukas Mai (MAUKE)
692
693 =head1 COPYRIGHT AND LICENSE
694
695 This software is copyright (c) 2015-2022 by Graham Ollis.
696
697 This is free software; you can redistribute it and/or modify it under
698 the same terms as the Perl 5 programming language system itself.
699
700 =cut
701
702 __DATA__
703 #include <stdio.h>
704 ##HEADERS##
705 ##DECL##
706
707
708 int
709 dlmain(int argc, char *argv[])
710 {
711 ##STMT##
712
713 ##EVAL##
714 return 0;
715 }