-
Notifications
You must be signed in to change notification settings - Fork 3
/
TinyCC.pm
614 lines (426 loc) · 12.6 KB
/
TinyCC.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
package FFI::TinyCC;
use strict;
use warnings;
use 5.008001;
use Config;
use FFI::Platypus;
use FFI::Platypus::Memory qw( malloc free );
use Carp qw( croak carp );
use File::Spec;
use File::ShareDir::Dist qw( dist_share );
# ABSTRACT: Tiny C Compiler for FFI
# VERSION
=head1 SYNOPSIS
use FFI::TinyCC;
use FFI::Platypus;
my $tcc = FFI::TinyCC->new;
$tcc->compile_string(q{
int
find_square(int value)
{
return value*value;
}
});
my $address = $tcc->get_symbol('find_square');
my $ffi = FFI::Platypus->new;
$ffi->attach([$address => 'find_square'] => ['int'] => 'int');
print find_square(4), "\n"; # prints 16
For code that requires system headers:
use FFI::TinyCC;
use FFI::Platypus;
my $tcc = FFI::TinyCC->new;
# this will throw an exception if the system
# include paths cannot be detected.
$tcc->detect_sysinclude_path;
$tcc->compile_string(q{
#include <stdio.h>
void print_hello()
{
puts("hello world");
}
});
my $address = $tcc->get_symbol('print_hello');
my $ffi = FFI::Platypus->new;
$ffi->attach([$address => 'print_hello'] => [] => 'void');
print_hello();
=head1 DESCRIPTION
This module provides an interface to a very small C compiler known as
TinyCC. It does almost no optimizations, so C<gcc> or C<clang> will
probably generate faster code, but it is very small and is very fast and
thus may be useful for some Just In Time (JIT) or Foreign Function
Interface (FFI) situations.
For a simpler, but less powerful interface see L<FFI::TinyCC::Inline>.
=cut
sub _dlext ()
{
$^O eq 'MSWin32' ? 'dll' : $Config{dlext};
}
our $ffi = FFI::Platypus->new;
$ffi->lib(
File::Spec->catfile(dist_share( 'FFI-TinyCC' ), 'libtcc.' . _dlext)
);
$ffi->custom_type( tcc_t => {
perl_to_native => sub {
$_[0]->{handle},
},
native_to_perl => sub {
{
handle => $_[0],
relocate => 0,
error => [],
};
},
});
do {
my %output_type = qw(
memory 0
exe 1
dll 2
obj 3
);
$ffi->custom_type( output_t => {
native_type => 'int',
perl_to_native => sub { $output_type{$_[0]} },
});
};
$ffi->type('int' => 'error_t');
$ffi->type('(opaque,string)->void' => 'error_handler_t');
$ffi->attach([tcc_new => '_new'] => [] => 'tcc_t');
$ffi->attach([tcc_delete => '_delete'] => ['tcc_t'] => 'void');
$ffi->attach([tcc_set_error_func => '_set_error_func'] => ['tcc_t', 'opaque', 'error_handler_t'] => 'void');
$ffi->attach([tcc_add_symbol => '_add_symbol'] => ['tcc_t', 'string', 'opaque'] => 'int');
$ffi->attach([tcc_get_symbol => '_get_symbol'] => ['tcc_t', 'string'] => 'opaque');
$ffi->attach([tcc_relocate => '_relocate'] => ['tcc_t', 'opaque'] => 'int');
$ffi->attach([tcc_run => '_run'] => ['tcc_t', 'int', 'opaque'] => 'int');
sub _method ($;@)
{
my($name, @args) = @_;
$ffi->attach(["tcc_$name" => "_$name"] => ['tcc_t', @args] => 'error_t');
eval '# line '. __LINE__ . ' "' . __FILE__ . qq("\n) .qq{
sub $name
{
my \$r = _$name (\@_);
die FFI::TinyCC::Exception->new(\$_[0]) if \$r == -1;
\$_[0];
}
};
die $@ if $@;
}
=head1 CONSTRUCTOR
=head2 new
my $tcc = FFI::TinyCC->new;
Create a new TinyCC instance.
=cut
sub new
{
my($class, %opt) = @_;
my $self = bless _new(), $class;
$self->{error_cb} = $ffi->closure(sub {
push @{ $self->{error} }, $_[1];
});
_set_error_func($self, undef, $self->{error_cb});
if($^O eq 'MSWin32')
{
require File::Basename;
require File::Spec;
my $path = File::Spec->catdir(File::Basename::dirname($ffi->lib), 'lib');
$self->add_library_path($path);
}
$self->{no_free_store} = 1 if $opt{_no_free_store};
$self;
}
sub _error
{
my($self, $msg) = @_;
push @{ $self->{error} }, $msg;
$self;
}
if(defined ${^GLOBAL_PHASE})
{
*DESTROY = sub
{
my($self) = @_;
return if ${^GLOBAL_PHASE} eq 'DESTRUCT';
_delete($self);
# TODO: should we do this?
free($self->{store});
}
}
else
{
require Devel::GlobalDestruction;
*DESTROY = sub
{
my($self) = @_;
return if Devel::GlobalDestruction::in_global_destruction();
_delete($self);
# TODO: should we do this?
free($self->{store});
}
}
=head1 METHODS
Methods will generally throw an exception on failure.
=head2 Compile
=head3 set_options
$tcc->set_options($options);
Set compiler and linker options, as you would on the command line, for
example:
$tcc->set_options('-I/foo/include -L/foo/lib -DFOO=22');
=cut
_method set_options => qw( string );
=head3 add_file
$tcc->add_file('foo.c');
$tcc->add_file('foo.o');
$tcc->add_file('foo.so'); # or dll on windows
Add a file, DLL, shared object or object file.
On windows adding a DLL is not supported via this interface.
=cut
_method add_file => qw( string );
=head3 compile_string
$tcc->compile_string($c_code);
Compile a string containing C source code.
=cut
_method compile_string => qw( string );
=head3 add_symbol
$tcc->add_symbol($name, $callback);
$tcc->add_symbol($name, $pointer);
Add the given given symbol name / callback or pointer combination. See
example below for how to use this to call Perl from Tiny C code.
If you are using L<FFI::Platypus> you can use L<FFI::Platypus#cast>
to get a pointer to a closure:
use FFI::Platypus;
my $ffi = FFI::Platypus;
my $closure = $ffi->closure(sub { return $_[0]+1 });
my $pointer = $ffi->cast('(int)->int' => 'opaque', $closure);
$tcc->add_symbol('foo' => $pointer);
=cut
sub add_symbol
{
my($self, $name, $ptr) = @_;
my $r;
$r = _add_symbol($self, $name, $ptr);
die FFI::TinyCC::Exception->new($self) if $r == -1;
$self;
}
=head2 Preprocessor options
=head3 detect_sysinclude_path
[version 0.18]
$tcc->detect_sysinclude_path;
Attempt to find and configure the appropriate system include directories. If
the platform that you are on does not (yet?) support this functionality
then this method will throw an exception.
[version 0.19]
Returns the list of directories added to the system include directories.
=cut
sub detect_sysinclude_path
{
my($self) = @_;
my @path_list;
if($^O eq 'MSWin32')
{
require File::Spec;
push @path_list, File::Spec->catdir(dist_share('Alien-TinyCC'), 'include');
}
elsif($Config{incpth})
{
require Alien::TinyCC;
require File::Spec;
push @path_list, File::Spec->catdir(Alien::TinyCC->libtcc_library_path, qw( tcc include ));
push @path_list, split /\s+/, $Config{incpth};
}
elsif($Config{ccname} eq 'gcc')
{
require File::Temp;
my($fh, $filename) = File::Temp::tempfile( "tryXXXX", SUFFIX => '.c', UNLINK => 1 );
close $fh;
my @lines = `$Config{cpp} -v $filename 2>&1`;
shift @lines while defined $lines[0] && $lines[0] !~ /^#include </;
shift @lines;
pop @lines while defined $lines[-1] && $lines[-1] !~ /^End of search /;
pop @lines;
croak "Cannot detect sysinclude path" unless @lines;
require Alien::TinyCC;
require File::Spec;
push @path_list, File::Spec->catdir(Alien::TinyCC->libtcc_library_path, qw( tcc include ));
push @path_list, map { chomp; s/^ //; $_ } @lines;
}
else
{
croak "Cannot detect sysinclude path";
}
croak "Cannot detect sysinclude path" unless grep { -d $_ } @path_list;
$self->add_sysinclude_path($_) for @path_list;
@path_list;
}
=head3 add_include_path
$tcc->add_include_path($path);
Add the given path to the list of paths used to search for include files.
=cut
_method add_include_path => qw( string );
=head3 add_sysinclude_path
$tcc->add_sysinclude_path($path);
Add the given path to the list of paths used to search for system
include files.
=cut
_method add_sysinclude_path => qw( string );
=head3 set_lib_path
$tcc->set_lib_path($path);
Set the lib path
=cut
_method set_lib_path => qw( string );
=head3 define_symbol
$tcc->define_symbol($name => $value);
$tcc->define_symbol($name);
Define the given symbol, optionally with the specified value.
=cut
$ffi->attach([tcc_define_symbol=>'define_symbol'] => ['tcc_t', 'string', 'string'] => 'void');
=head3 undefine_symbol
$tcc->undefine_symbol($name);
Undefine the given symbol.
=cut
$ffi->attach([tcc_undefine_symbol=>'undefine_symbol'] => ['tcc_t', 'string', 'string'] => 'void');
=head2 Link / run
=head3 set_output_type
$tcc->set_output_type('memory');
$tcc->set_output_type('exe');
$tcc->set_output_type('dll');
$tcc->set_output_type('obj');
Set the output type. This must be called before any compilation.
Output formats may not be supported on your platform. C<exe> is
NOT supported on *BSD or OS X. It may NOT be supported on Linux.
As a basic baseline at least C<memory> should be supported.
=cut
_method set_output_type => qw( output_t );
=head3 add_library
$tcc->add_library($libname);
Add the given library when linking. Example:
$tcc->add_library('m'); # equivalent to -lm (math library)
=cut
_method add_library => qw( string );
=head3 add_library_path
$tcc->add_library_path($pathname);
Add the given directory to the search path used to find libraries.
=cut
_method add_library_path => qw( string );
=head3 run
my $exit_value = $tcc->run(@arguments);
=cut
sub run
{
my($self, @args) = @_;
croak "unable to use run method after get_symbol" if $self->{relocate};
my $argc = scalar @args;
my @c_strings = map { "$_\0" } @args;
my $ptrs = pack 'P' x $argc, @c_strings;
my $argv = unpack('L!', pack('P', $ptrs));
my $r = _run($self, $argc, $argv);
die FFI::TinyCC::Exception->new($self) if $r == -1;
$r;
}
=head3 get_symbol
my $pointer = $tcc->get_symbol($symbol_name);
Return symbol address or undef if not found. This can be passed into
the L<FFI::Platypus#function> method, L<FFI::Platypus#attach> method,
or similar interface that takes a pointer to a C function.
=cut
sub get_symbol
{
my($self, $symbol_name) = @_;
unless($self->{relocate})
{
my $size = _relocate($self, undef);
$self->{store} = malloc($size);
my $r = _relocate($self, $self->{store});
die FFI::TinyCC::Exception->new($self) if $r == -1;
$self->{relocate} = 1;
}
_get_symbol($self, $symbol_name);
}
=head3 output_file
$tcc->output_file($filename);
Output the generated code (either executable, object or DLL) to the
given filename. The type of output is specified by the
L<set_output_type|/set_output_type> method.
=cut
_method output_file => qw( string );
package
FFI::TinyCC::Exception;
use overload '""' => sub {
my $self = shift;
if(@{ $self->{fault} } == 2)
{
join(' ', $self->as_string,
at => $self->{fault}->[0],
line => $self->{fault}->[1],
);
}
else
{
$self->as_string . "\n";
}
};
use overload fallback => 1;
sub new
{
my($class, $tcc) = @_;
my @errors = @{ $tcc->{error} };
$tcc->{errors} = [];
my @stack;
my @fault;
my $i=2;
while(my @frame = caller($i++))
{
push @stack, \@frame;
if(@fault == 0 && $frame[0] !~ /^FFI::TinyCC/)
{
@fault = ($frame[1], $frame[2]);
}
}
my $self = bless {
errors => \@errors,
stack => \@stack,
fault => \@fault,
}, $class;
$self;
}
sub errors { shift->{errors} }
sub as_string
{
my($self) = @_;
join "\n", @{ $self->{errors} };
}
1;
=head1 EXAMPLES
=head2 Calling Tiny C code from Perl
# EXAMPLE: example/hello.pl
=head2 Calling Perl from Tiny C code
# EXAMPLE: example/callback.pl
=head2 Attaching as a FFI::Platypus function from a Tiny C function
# EXAMPLE: example/ffi_platypus.pl
=head1 CAVEATS
Tiny C is only supported on platforms with ARM or Intel processors. All
features may not be fully supported on all operating systems.
Tiny C is no longer supported by its original author, though various
forks seem to have varying levels of support. We use the fork that comes
with L<Alien::TinyCC>.
=head1 SEE ALSO
=over 4
=item L<FFI::TinyCC::Inline>
=item L<Tiny C|http://bellard.org/tcc/>
=item L<Tiny C Compiler Reference Documentation|http://bellard.org/tcc/tcc-doc.html>
=item L<FFI::Platypus>
=item L<C::Blocks>
=item L<Alien::TinyCC>
=item L<C::TinyCompiler>
=back
=head1 BUNDLED SOFTWARE
This package also comes with a parser that was shamelessly stolen from
L<XS::TCC>, which I strongly suspect was itself shamelessly "borrowed"
from L<Inline::C::Parser::RegExp>
The license details for the parser are:
Copyright 2002 Brian Ingerson
Copyright 2008, 2010-2012 Sisyphus
Copyright 2013 Steffen Muellero
This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.
=cut