Debian Codegraph @

lib/FFI/Build.pm

raw
1 package FFI::Build;
2
3 use strict;
4 use warnings;
5 use 5.008004;
6 use FFI::Build::Plugin;
7 use FFI::Build::PluginData qw( plugin_data );
8 use FFI::Build::File::Library;
9 use Carp ();
10 use File::Glob ();
11 use File::Basename ();
12 use List::Util 1.45 ();
13 use Capture::Tiny ();
14 use File::Path ();
15
16 # ABSTRACT: Build shared libraries for use with FFI
17 our $VERSION = '2.12'; # VERSION
18
19 # Platypus-Man,
20 # Platypus-Man,
21 # Friendly Neighborhood Platypus-Man
22 # Is He Strong?
23 # Listen Bud
24 # He's got Proportional Strength of a Platypus
25 # Hey Man!
26 # There Goes The Platypus-Man
27
28
29 {
30 my $plugins = FFI::Build::Plugin->new;
31 # PLUGIN: require
32 # ARGS: NONE
33 $plugins->call('build-require');
34 sub _plugins { $plugins ||= FFI::Build::Plugin->new };
35 }
36
37 sub import
38 {
39 my @caller = caller;
40 # PLUGIN: import
41 # ARGS: @caller, \@args
42 _plugins->call('build-import', \@caller, \@_);
43 }
44
45 sub _native_name
46 {
47 my($self, $name) = @_;
48 join '', $self->platform->library_prefix, $name, scalar $self->platform->library_suffix;
49 }
50
51 sub new
52 {
53 my($class, $name, %args) = @_;
54
55 Carp::croak "name is required" unless defined $name;
56
57 # PLUGIN: new-pre
58 # ARGS: $name, \%args
59 _plugins->call('build-new-pre', $name, \%args);
60
61 my $self = bless {
62 source => [],
63 cflags_I => [],
64 cflags => [],
65 libs_L => [],
66 libs => [],
67 alien => [],
68 }, $class;
69
70 my $platform = $self->{platform} = $args{platform} || FFI::Build::Platform->default;
71 my $file = $self->{file} = $args{file} || FFI::Build::File::Library->new([$args{dir} || '.', $self->_native_name($name)], platform => $self->platform);
72 my $buildname = $self->{buildname} = $args{buildname} || '_build';
73 my $verbose = $self->{verbose} = $args{verbose} || 0;
74 my $export = $self->{export} = $args{export} || [];
75
76 $self->{verbose} = $verbose = 2 if $ENV{V};
77
78 if(defined $args{cflags})
79 {
80 my @flags = ref $args{cflags} ? @{ $args{cflags} } : $self->platform->shellwords($args{cflags});
81 push @{ $self->{cflags} }, grep !/^-I/, @flags;
82 push @{ $self->{cflags_I} }, grep /^-I/, @flags;
83 }
84
85 if(defined $args{libs})
86 {
87 my @flags = ref $args{libs} ? @{ $args{libs} } : $self->platform->shellwords($args{libs});
88 push @{ $self->{libs} }, grep !/^-L/, @flags;
89 push @{ $self->{libs_L} }, grep /^-L/, @flags;
90 }
91
92 if(defined $args{alien})
93 {
94 my @aliens = ref $args{alien} ? @{ $args{alien} } : ($args{alien});
95 foreach my $alien (@aliens)
96 {
97 unless(eval { $alien->can('cflags') && $alien->can('libs') })
98 {
99 my $pm = "$alien.pm";
100 $pm =~ s/::/\//g;
101 require $pm;
102 }
103 push @{ $self->{alien} }, $alien;
104 push @{ $self->{cflags} }, grep !/^-I/, $self->platform->shellwords($alien->cflags);
105 push @{ $self->{cflags_I} }, grep /^-I/, $self->platform->shellwords($alien->cflags);
106 push @{ $self->{libs} }, grep !/^-L/, $self->platform->shellwords($alien->libs);
107 push @{ $self->{libs_L} }, grep /^-L/, $self->platform->shellwords($alien->libs);
108 }
109 }
110
111 $self->source(ref $args{source} ? @{ $args{source} } : ($args{source})) if $args{source};
112
113 # PLUGIN: new-post
114 # ARGS: $self
115 _plugins->call('build-new-post', $self);
116
117 $self;
118 }
119
120
121 sub buildname { shift->{buildname} }
122 sub export { shift->{export} }
123 sub file { shift->{file} }
124 sub platform { shift->{platform} }
125 sub verbose { shift->{verbose} }
126 sub cflags { shift->{cflags} }
127 sub cflags_I { shift->{cflags_I} }
128 sub libs { shift->{libs} }
129 sub libs_L { shift->{libs_L} }
130 sub alien { shift->{alien} }
131
132 my @file_classes;
133 sub _file_classes
134 {
135 unless(@file_classes)
136 {
137 if(defined $FFI::Build::VERSION)
138 {
139 foreach my $inc (@INC)
140 {
141 push @file_classes,
142 map { my $f = $_; $f =~ s/\.pm$//; "FFI::Build::File::$f" }
143 grep !/^Base\.pm$/,
144 map { File::Basename::basename($_) }
145 File::Glob::bsd_glob(
146 File::Spec->catfile($inc, 'FFI', 'Build', 'File', '*.pm')
147 );
148 }
149 }
150 else
151 {
152 # When building out of git without dzil, $VERSION will not
153 # usually be defined and any file plugins that require a
154 # specific version will break, so we only use core file
155 # classes for that.
156 push @file_classes, map { "FFI::Build::File::$_" } qw( C CXX Library Object );
157 }
158
159 # also anything already loaded, that might not be in the
160 # @INC path (for testing ususally)
161 push @file_classes,
162 map { my $f = $_; $f =~ s/::$//; "FFI::Build::File::$f" }
163 grep !/Base::/,
164 grep /::$/,
165 keys %{FFI::Build::File::};
166
167 @file_classes = List::Util::uniq(@file_classes);
168 foreach my $class (@file_classes)
169 {
170 next if(eval { $class->can('new') });
171 my $pm = $class . ".pm";
172 $pm =~ s/::/\//g;
173 require $pm;
174 }
175 }
176 @file_classes;
177 }
178
179
180 sub source
181 {
182 my($self, @file_spec) = @_;
183
184 foreach my $file_spec (@file_spec)
185 {
186 if(eval { $file_spec->isa('FFI::Build::File::Base') })
187 {
188 push @{ $self->{source} }, $file_spec;
189 next;
190 }
191 if(ref $file_spec eq 'ARRAY')
192 {
193 my($type, $content, @args) = @$file_spec;
194 my $class = "FFI::Build::File::$type";
195 unless($class->can('new'))
196 {
197 my $pm = "FFI/Build/File/$type.pm";
198 require $pm;
199 }
200 push @{ $self->{source} }, $class->new(
201 $content,
202 build => $self,
203 platform => $self->platform,
204 @args
205 );
206 next;
207 }
208 my @paths = File::Glob::bsd_glob($file_spec);
209 path:
210 foreach my $path (@paths)
211 {
212 foreach my $class (_file_classes)
213 {
214 foreach my $regex ($class->accept_suffix)
215 {
216 if($path =~ $regex)
217 {
218 push @{ $self->{source} }, $class->new($path, platform => $self->platform, build => $self);
219 next path;
220 }
221 }
222 }
223 Carp::croak("Unknown file type: $path");
224 }
225 }
226
227 @{ $self->{source} };
228 }
229
230
231 sub build
232 {
233 my($self) = @_;
234
235 # PLUGIN: build
236 # ARGS: $self
237 _plugins->call('build-build', $self);
238
239 my @objects;
240
241 my $ld = $self->platform->ld;
242
243 foreach my $source ($self->source)
244 {
245 # PLUGIN: build-item
246 # ARGS: $self, $source
247 _plugins->call('build-build-item', $self, $source);
248
249 if($source->can('build_all'))
250 {
251 my $count = scalar $self->source;
252 if($count == 1)
253 {
254 return $source->build_all($self->file);
255 }
256 else
257 {
258 die "@{[ ref $source ]} has build_all method, but there is not exactly one source";
259 }
260 }
261
262 $ld = $source->ld if $source->ld;
263 my $output;
264 while(my $next = $source->build_item)
265 {
266 $ld = $next->ld if $next->ld;
267 $output = $source = $next;
268 }
269 push @objects, $output;
270 }
271
272 my $needs_rebuild = sub {
273 my(@objects) = @_;
274 return 1 unless -f $self->file->path;
275 my $target_time = [stat $self->file->path]->[9];
276 foreach my $object (@objects)
277 {
278 my $object_time = [stat "$object"]->[9];
279 return 1 if $object_time > $target_time;
280 }
281 return 0;
282 };
283
284 return $self->file unless $needs_rebuild->(@objects);
285
286 File::Path::mkpath($self->file->dirname, 0, oct(755));
287
288 my @cmd = (
289 $ld,
290 $self->libs_L,
291 $self->platform->ldflags,
292 (map { "$_" } @objects),
293 $self->libs,
294 $self->platform->flag_export(@{ $self->export }),
295 $self->platform->flag_library_output($self->file->path),
296 );
297
298 # PLUGIN: build-link
299 # ARGS: $self, \@cmd
300 _plugins->call('build-build-link', $self, \@cmd);
301
302 my($out, $exit) = Capture::Tiny::capture_merged(sub {
303 $self->platform->run(@cmd);
304 });
305
306 if($exit || !-f $self->file->path)
307 {
308 print $out;
309 die "error building @{[ $self->file->path ]} from @objects";
310 }
311 elsif($self->verbose >= 2)
312 {
313 print $out;
314 }
315 elsif($self->verbose >= 1)
316 {
317 print "LD @{[ $self->file->path ]}\n";
318 }
319
320 # PLUGIN: link-postlink
321 # ARGS: $self, \@cmd
322 _plugins->call('build-build-postlink', $self);
323
324 $self->file;
325 }
326
327
328 sub clean
329 {
330 my($self) = @_;
331 my $dll = $self->file->path;
332 if(-f $dll)
333 {
334 # PLUGIN: clean
335 # ARGS: $self, $path
336 _plugins->call('build-clean', $self, $dll);
337 unlink $dll;
338 }
339 foreach my $source ($self->source)
340 {
341 my $dir = File::Spec->catdir($source->dirname, $self->buildname);
342 if(-d $dir)
343 {
344 foreach my $path (File::Glob::bsd_glob("$dir/*"))
345 {
346 _plugins->call('build-clean', $self, $path);
347 unlink $path;
348 }
349 _plugins->call('build-clean', $self, $dir);
350 rmdir $dir;
351 }
352 }
353 }
354
355 1;
356
357 __END__
358
359 =pod
360
361 =encoding UTF-8
362
363 =head1 NAME
364
365 FFI::Build - Build shared libraries for use with FFI
366
367 =head1 VERSION
368
369 version 2.12
370
371 =head1 SYNOPSIS
372
373 use FFI::Platypus 2.00;
374 use FFI::Build;
375
376 my $build = FFI::Build->new(
377 'frooble',
378 source => 'ffi/*.c',
379 );
380
381 # $lib is an instance of FFI::Build::File::Library
382 my $lib = $build->build;
383
384 my $ffi = FFI::Platypus->new( api => 2 );
385 # The filename will be platform dependant, but something like libfrooble.so or frooble.dll
386 $ffi->lib($lib->path);
387
388 ... # use $ffi to attach functions in ffi/*.c
389
390 =head1 DESCRIPTION
391
392 Using libffi based L<FFI::Platypus> is a great alternative to XS for writing library bindings for Perl.
393 Sometimes, however, you need to bundle a little C code with your FFI module, but this has never been
394 that easy to use. L<Module::Build::FFI> was an early attempt to address this use case, but it uses
395 the now out of fashion L<Module::Build>.
396
397 This module itself doesn't directly integrate with CPAN installers like L<ExtUtils::MakeMaker> or
398 L<Module::Build>, but there is a light weight layer L<FFI::Build::MM> that will allow you to easily
399 use this module with L<ExtUtils::MakeMaker>. If you are using L<Dist::Zilla> as your dist builder,
400 then there is also L<Dist::Zilla::Plugin::FFI::Build>, which will help with the connections.
401
402 There is some functional overlap with L<ExtUtils::CBuilder>, which was in fact used by L<Module::Build::FFI>.
403 For this iteration I have decided not to use that module because although it will generate dynamic libraries
404 that can sometimes be used by L<FFI::Platypus>, it is really designed for building XS modules, and trying
405 to coerce it into a more general solution has proved difficult in the past.
406
407 Supported languages out of the box are C, C++ and Fortran. Rust is supported via a language plugin,
408 see L<FFI::Platypus::Lang::Rust>.
409
410 =head1 CONSTRUCTOR
411
412 =head2 new
413
414 my $build = FFI::Build->new($name, %options);
415
416 Create an instance of this class. The C<$name> argument is used when computing the file name for
417 the library. The actual name will be something like C<lib$name.so> or C<$name.dll>. The following
418 options are supported:
419
420 =over 4
421
422 =item alien
423
424 List of Aliens to compile/link against. L<FFI::Build> will work with any L<Alien::Base> based
425 alien, or modules that provide a compatible API.
426
427 =item buildname
428
429 Directory name that will be used for building intermediate files, such as object files. This is
430 C<_build> by default.
431
432 =item cflags
433
434 Extra compiler flags to use. Things like C<-I/foo/include> or C<-DFOO=1>.
435
436 =item dir
437
438 The directory where the library will be written. This is C<.> by default.
439
440 =item export
441
442 Functions that should be exported (Windows + Visual C++ only)
443
444 =item file
445
446 An instance of L<FFI::Build::File::Library> to which the library will be written. Normally not needed.
447
448 =item libs
449
450 Extra library flags to use. Things like C<-L/foo/lib -lfoo>.
451
452 =item platform
453
454 An instance of L<FFI::Build::Platform>. Usually you want to omit this and use the default instance.
455
456 =item source
457
458 List of source files. You can use wildcards supported by C<bsd_glob> from L<File::Glob>.
459
460 =item verbose
461
462 By default this class does not print out the actual compiler and linker commands used in building
463 the library unless there is a failure. You can alter this behavior with this option. Set to
464 one of these values:
465
466 =over 4
467
468 =item zero (0)
469
470 Default, quiet unless there is a failure.
471
472 =item one (1)
473
474 Output the operation (compile, link, etc) and the file, but nothing else
475
476 =item two (2)
477
478 Output the complete commands run verbatim.
479
480 =back
481
482 If the environment variable C<V> is set to a true value then the verbosity will be set to C<2> regardless
483 of what is passed in.
484
485 =back
486
487 =head1 METHODS
488
489 =head2 dir
490
491 my $dir = $build->dir;
492
493 Returns the directory where the library will be written.
494
495 =head2 buildname
496
497 my $builddir = $build->builddir;
498
499 Returns the build name. This is used in computing a directory to save intermediate files like objects. For example,
500 if you specify a file like C<ffi/foo.c>, then the object file will be stored in C<ffi/_build/foo.o> by default.
501 C<_build> in this example (the default) is the build name.
502
503 =head2 export
504
505 my $exports = $build->export;
506
507 Returns a array reference of the exported functions (Windows + Visual C++ only)
508
509 =head2 file
510
511 my $file = $build->file;
512
513 Returns an instance of L<FFI::Build::File::Library> corresponding to the library being built. This is
514 also returned by the C<build> method below.
515
516 =head2 platform
517
518 my $platform = $build->platform;
519
520 An instance of L<FFI::Build::Platform>, which contains information about the platform on which you are building.
521 The default is usually reasonable.
522
523 =head2 verbose
524
525 my $verbose = $build->verbose;
526
527 Returns the verbose flag.
528
529 =head2 cflags
530
531 my @cflags = @{ $build->cflags };
532
533 Returns the compiler flags.
534
535 =head2 cflags_I
536
537 my @cflags_I = @{ $build->cflags_I };
538
539 Returns the C<-I> cflags.
540
541 =head2 libs
542
543 my @libs = @{ $build->libs };
544
545 Returns the library flags.
546
547 =head2 libs_L
548
549 my @libs = @{ $build->libs };
550
551 Returns the C<-L> library flags.
552
553 =head2 alien
554
555 my @aliens = @{ $build->alien };
556
557 Returns a the list of aliens being used.
558
559 =head2 source
560
561 $build->source(@files);
562
563 Add the C<@files> to the list of source files that will be used in building the library.
564 The format is the same as with the C<source> attribute above.
565
566 =head2 build
567
568 my $lib = $build->build;
569
570 This compiles the source files and links the library. Files that have already been compiled or linked
571 may be reused without recompiling/linking if the timestamps are newer than the source files. An instance
572 of L<FFI::Build::File::Library> is returned which can be used to get the path to the library, which can
573 be feed into L<FFI::Platypus> or similar.
574
575 =head2 clean
576
577 $build->clean;
578
579 Removes the library and intermediate files.
580
581 =head1 AUTHOR
582
583 Author: Graham Ollis E<lt>[email protected]<gt>
584
585 Contributors:
586
587 Bakkiaraj Murugesan (bakkiaraj)
588
589 Dylan Cali (calid)
590
591 pipcet
592
593 Zaki Mughal (zmughal)
594
595 Fitz Elliott (felliott)
596
597 Vickenty Fesunov (vyf)
598
599 Gregor Herrmann (gregoa)
600
601 Shlomi Fish (shlomif)
602
603 Damyan Ivanov
604
605 Ilya Pavlov (Ilya33)
606
607 Petr Písař (ppisar)
608
609 Mohammad S Anwar (MANWAR)
610
611 Håkon Hægland (hakonhagland, HAKONH)
612
613 Meredith (merrilymeredith, MHOWARD)
614
615 Diab Jerius (DJERIUS)
616
617 Eric Brine (IKEGAMI)
618
619 szTheory
620
621 José Joaquín Atria (JJATRIA)
622
623 Pete Houston (openstrike, HOUSTON)
624
625 Lukas Mai (MAUKE)
626
627 =head1 COPYRIGHT AND LICENSE
628
629 This software is copyright (c) 2015-2022 by Graham Ollis.
630
631 This is free software; you can redistribute it and/or modify it under
632 the same terms as the Perl 5 programming language system itself.
633
634 =cut