perlcc.PL 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147
  1. #! perl
  2. use Config;
  3. use File::Basename qw(&basename &dirname);
  4. use File::Spec;
  5. use Cwd;
  6. # List explicitly here the variables you want Configure to
  7. # generate. Metaconfig only looks for shell variables, so you
  8. # have to mention them as if they were shell variables, not
  9. # %Config entries. Thus you write
  10. # $startperl
  11. # to ensure Configure will look for $Config{startperl}.
  12. # Wanted: $archlibexp
  13. # This forces PL files to create target in same directory as PL file.
  14. # This is so that make depend always knows where to find PL derivatives.
  15. $origdir = cwd;
  16. chdir dirname($0);
  17. $file = basename($0, '.PL');
  18. $file .= '.com' if $^O eq 'VMS';
  19. open OUT,">$file" or die "Can't create $file: $!";
  20. print "Extracting $file (with variable substitutions)\n";
  21. # In this section, perl variables will be expanded during extraction.
  22. # You can use $Config{...} to use Configure variables.
  23. print OUT <<"!GROK!THIS!";
  24. $Config{startperl}
  25. eval 'exec $Config{perlpath} -S \$0 \${1+"\$@"}'
  26. if \$running_under_some_shell;
  27. --\$running_under_some_shell;
  28. !GROK!THIS!
  29. # In the following, perl variables are not expanded during extraction.
  30. print OUT <<'!NO!SUBS!';
  31. # Version 2.0, Simon Cozens, Thu Mar 30 17:52:45 JST 2000
  32. # Version 2.01, Tom Christiansen, Thu Mar 30 08:25:14 MST 2000
  33. # Version 2.02, Simon Cozens, Sun Apr 16 01:53:36 JST 2000
  34. # Version 2.03, Edward Peschko, Mon Feb 26 12:04:17 PST 2001
  35. # Version 2.04, Enache Adrian, Fri, 18 Jul 2003 23:15:37 +0300
  36. # Version 2.05, Reini Urban, 2009-12-01 00:00:13
  37. # Version 2.06, Reini Urban, 2009-12-28 21:56:15
  38. # Version 2.07, Reini Urban, 2010-06-30 22:32:20
  39. # Version 2.08, Reini Urban, 2010-07-30 21:30:33
  40. # Version 2.09, Reini Urban, 2010-10-11 13:54:52
  41. # Version 2.10, Reini Urban, 2011-02-11 22:58:37
  42. # Version 2.11, Reini Urban, 2011-04-11 20:16:00
  43. # Version 2.12, Reini Urban, 2011-10-02 05:19:00
  44. # Version 2.13, Reini Urban, 2012-01-10 13:03:00
  45. # Version 2.14, Reini Urban, 2012-02-28 09:04:07
  46. # Version 2.15, Reini Urban, 2013-02-01 10:41:54
  47. use strict;
  48. use warnings;
  49. use 5.006_000;
  50. use FileHandle;
  51. use Config;
  52. use Fcntl qw(:DEFAULT :flock);
  53. use File::Temp qw(tempfile);
  54. use File::Basename qw(basename dirname);
  55. # use Cwd;
  56. use Pod::Usage;
  57. # Time::HiRes does not work with 5.6
  58. # use Time::HiRes qw(gettimeofday tv_interval);
  59. our $VERSION = 2.15;
  60. $| = 1;
  61. eval { require B::C::Flags; };
  62. $SIG{INT} = sub { exit(); } if exists $SIG{INT}; # exit gracefully and clean up after ourselves.
  63. use subs qw{
  64. cc_harness check_read check_write checkopts_byte choose_backend
  65. compile_byte compile_cstyle compile_module generate_code
  66. grab_stash parse_argv sanity_check vprint yclept spawnit
  67. gettimeofday tv_interval vsystem
  68. };
  69. sub opt(*); # imal quoting
  70. sub is_win32();
  71. sub is_msvc();
  72. our ($Options, $BinPerl, $Backend);
  73. our ($Input => $Output);
  74. our ($logfh);
  75. our ($cfile);
  76. our (@begin_output); # output from BEGIN {}, for testsuite
  77. our ($extra_libs);
  78. # eval { main(); 1 } or die;
  79. main();
  80. sub main {
  81. parse_argv();
  82. check_write($Output);
  83. choose_backend();
  84. generate_code();
  85. run_code();
  86. _die("Not reached?");
  87. }
  88. #######################################################################
  89. sub choose_backend {
  90. # Choose the backend.
  91. $Backend = 'C';
  92. if (opt('B')) {
  93. checkopts_byte();
  94. $Backend = 'Bytecode';
  95. }
  96. if (opt('S') && opt('c')) {
  97. # die "$0: Do you want me to compile this or not?\n";
  98. delete $Options->{S};
  99. }
  100. $Backend = 'CC' if opt('O');
  101. }
  102. sub generate_code {
  103. vprint 4, "Compiling $Input";
  104. $BinPerl = yclept(); # Calling convention for perl.
  105. if (exists $Options->{m}) {
  106. compile_module();
  107. } else {
  108. if ($Backend eq 'Bytecode') {
  109. compile_byte();
  110. } else {
  111. compile_cstyle();
  112. }
  113. }
  114. exit(0) if (!opt('r'));
  115. }
  116. sub run_code {
  117. if ($Backend eq 'Bytecode') {
  118. if ($] < 5.007) {
  119. $Output = "$BinPerl -MByteLoader $Output";
  120. } else {
  121. $Output = "$BinPerl $Output";
  122. }
  123. }
  124. if (opt('staticxs') and $extra_libs) {
  125. my $path = '';
  126. my $PATHSEP = $^O eq 'MSWin32' ? ';' : ':';
  127. for (split / /, $extra_libs) {
  128. s{/[^/]+$}{};
  129. # XXX qx quote?
  130. $path .= $PATHSEP.$_ if $_;
  131. }
  132. if ($^O =~ /^MSWin32|msys|cygwin$/) {
  133. $ENV{PATH} .= $path;
  134. vprint 0, "PATH=\$PATH$path";
  135. } elsif ($^O ne 'darwin') {
  136. $ENV{LD_LIBRARY_PATH} .= $path;
  137. vprint 0, "LD_LIBRARY_PATH=\$LD_LIBRARY_PATH$path";
  138. }
  139. }
  140. vprint 0, "Running code $Output @ARGV";
  141. run("$Output @ARGV");
  142. exit(0);
  143. }
  144. # usage: vprint [level] msg args
  145. sub vprint {
  146. my $level;
  147. if (@_ == 1) {
  148. $level = 1;
  149. } elsif ($_[0] =~ /^-?\d$/) {
  150. $level = shift;
  151. } else {
  152. # well, they forgot to use a number; means >0
  153. $level = 0;
  154. }
  155. my $msg = "@_";
  156. $msg .= "\n" unless substr($msg, -1) eq "\n";
  157. if (opt('v') > $level)
  158. {
  159. if (opt('log')) {
  160. print $logfh "$0: $msg" ;
  161. } else {
  162. print "$0: $msg";
  163. }
  164. }
  165. }
  166. sub vsystem {
  167. if (opt('dryrun')) {
  168. print "@_\n";
  169. } else {
  170. system(@_);
  171. }
  172. }
  173. sub parse_argv {
  174. use Getopt::Long;
  175. # disallows using long arguments
  176. Getopt::Long::Configure("bundling");
  177. Getopt::Long::Configure("no_ignore_case");
  178. # no difference in exists and defined for %ENV; also, a "0"
  179. # argument or a "" would not help cc, so skip
  180. unshift @ARGV, split ' ', $ENV{PERLCC_OPTS} if $ENV{PERLCC_OPTS};
  181. $Options = {};
  182. # support single dash -Wb. GetOptions requires --Wb with bundling enabled.
  183. if (my ($wb) = grep /^-Wb=(.+)/, @ARGV) {
  184. $Options->{Wb} = substr($wb,4);
  185. @ARGV = grep !/^-Wb=(.+)/, @ARGV;
  186. }
  187. # -O2 i.e. -Wb=-O1 (new since 2.13)
  188. if (my ($o1) = grep /^-O(\d)$/, @ARGV) {
  189. $Options->{Wb} = $Options->{Wb} ? $Options->{Wb}.",$o1" : $o1;
  190. @ARGV = grep !/^-O\d$/, @ARGV;
  191. }
  192. if (my ($v) = grep /^-v\d$/, @ARGV) {
  193. $Options->{v} = 0+substr($v,2);
  194. @ARGV = grep !/^-v\d$/, @ARGV;
  195. }
  196. if (grep /^-stash$/, @ARGV) {
  197. $Options->{stash}++;
  198. @ARGV = grep !/^-stash$/, @ARGV;
  199. }
  200. $Options->{spawn} = 1 unless $^O eq 'MSWin32';
  201. Getopt::Long::GetOptions( $Options,
  202. 'L=s', # lib directory
  203. 'I=s', # include directories (FOR C, NOT FOR PERL)
  204. 'o=s', # Output executable
  205. 'v:i', # Verbosity level
  206. 'e=s', # One-liner
  207. 'm|sharedlib:s',# as Module [name] (new since 2.11, not yet tested)
  208. 'r', # run resulting executable
  209. 'B', # Byte compiler backend
  210. 'O', # Optimised C backend B::CC
  211. #'O1-4' # alias for -Wb=-O1 (new since 2.13)
  212. 'dryrun|n', # only print commands, do not execute
  213. 'c', # Compile only
  214. 'help|h', # Help me
  215. 'S', # Dump C files
  216. 'T', # run the backend using perl -T
  217. 't', # run the backend using perl -t
  218. 'u=s@', # use packages (new since 2.13)
  219. 'U=s@', # skip packages (new since 2.13)
  220. 'static', # Link to static libperl (default, new since 2.11)
  221. 'shared', # Link to shared libperl (new since 2.07)
  222. 'staticxs', # Link static XSUBs (new since 2.07)
  223. 'sharedxs', # Link shared XSUBs (default, new since 2.07))
  224. 'stash', # Detect external packages via B::Stash
  225. 'log:s', # where to log compilation process information
  226. 'Wb=s', # pass (comma-seperated) options to backend
  227. 'f=s@', # pass compiler option(s) to backend (new since 2.14)
  228. 'Wc=s', # pass (comma-seperated) options to cc (new since 2.13)
  229. 'Wl=s', # pass (comma-seperated) options to ld (new since 2.13)
  230. 'testsuite', # try to be nice to testsuite modules (STDOUT, STDERR handles)
  231. 'spawn!', # --no-spawn (new since 2.12)
  232. 'time', # print benchmark timings (new since 2.08)
  233. 'version', # (new since 2.13)
  234. );
  235. $Options->{v} += 0;
  236. if( opt('t') && opt('T') ) {
  237. warn "Can't specify both -T and -t, -t ignored";
  238. $Options->{t} = 0;
  239. }
  240. helpme() if opt('help'); # And exit
  241. if (opt('version')) {
  242. die version();
  243. }
  244. $Options->{Wb} .= ",-O1" if opt('O1');
  245. $Options->{Wb} .= ",-O2" if opt('O2');
  246. $Options->{Wb} .= ",-O3" if opt('O3');
  247. $Options->{Wb} .= ",-O4" if opt('O4');
  248. if( $Options->{time} or $Options->{spawn} ) {
  249. eval { require Time::HiRes; }; # 5.6 has no Time::HiRes
  250. if ($@) {
  251. warn "--time ignored. No Time::HiRes\n" if $Options->{time};
  252. $Options->{time} = 0;
  253. } else {
  254. sub main::gettimeofday () {};
  255. Time::HiRes->import('gettimeofday','tv_interval','sleep');
  256. }
  257. }
  258. $logfh = new FileHandle(">> " . opt('log')) if (opt('log'));
  259. if (opt('e')) {
  260. warn "$0: using -e 'code' as input file, ignoring @ARGV\n" if @ARGV;
  261. # We don't use a temporary file here; why bother?
  262. # XXX: this is not bullet proof -- spaces or quotes in name!
  263. $Input = is_win32() ? # Quotes eaten by shell
  264. '-e "'.opt('e').'"' :
  265. "-e '".opt('e')."'";
  266. } else {
  267. $Input = shift @ARGV; # XXX: more files?
  268. _usage_and_die("No input file specified\n") unless $Input;
  269. # DWIM modules. This is bad but necessary.
  270. $Options->{m} = '' if $Input =~ /\.pm\z/ and !opt('m');
  271. vprint 1, "$0: using $Input as input file, ignoring @ARGV\n" if @ARGV;
  272. check_read($Input);
  273. check_perl($Input);
  274. }
  275. if (opt('o')) {
  276. $Output = opt('o');
  277. } elsif (opt('B')) {
  278. if (opt('e')) {
  279. my $suffix = '.plc';
  280. $suffix = '.pmc' if exists $Options->{m};
  281. (undef, $Output) = tempfile("plcXXXXX", SUFFIX => $suffix);
  282. } else {
  283. $Output = basename($Input) . "c";
  284. }
  285. } else {
  286. $Output = ( is_win32() or $^O eq 'cygwin' ) ? 'a.exe' : 'a.out';
  287. }
  288. $Output = relativize($Output) unless is_win32();
  289. sanity_check();
  290. }
  291. sub opt(*) {
  292. my $opt = shift;
  293. return exists($Options->{$opt}) && ($Options->{$opt} || 0);
  294. }
  295. sub compile_module {
  296. if ($Backend eq 'Bytecode') {
  297. compile_byte('-m'.$Options->{m});
  298. } else {
  299. compile_cstyle("-m".$Options->{m});
  300. }
  301. }
  302. sub compile_byte {
  303. vprint 3, "Writing B on $Output";
  304. my $opts = $] < 5.007 ? "" : "-H,-s,";
  305. if ($] >= 5.007 and $Input =~ /^-e/) {
  306. $opts = "-H,";
  307. }
  308. if (@_ == 1) {
  309. $opts .= $_[0].",";
  310. }
  311. my $addoptions = opt('Wb');
  312. if( $addoptions ) {
  313. $opts .= '-v,' if opt('v') > 4;
  314. $opts .= '-DM,-DG,-DA,-DComment,' if opt('v') > 5;
  315. $opts .= "$addoptions,";
  316. } elsif (opt('v') > 4) {
  317. $opts .= '-v,';
  318. $opts .= '-DM,-DG,-DA,-DComment,' if opt('v') > 5;
  319. }
  320. my $command = "$BinPerl -MO=Bytecode,$opts-o$Output $Input";
  321. $Input =~ s/^-e.*$/-e/;
  322. vprint 5, "Compiling...";
  323. vprint 0, "Calling $command";
  324. my $t0 = [gettimeofday] if opt('time');
  325. my ($output_r, $error_r, $errcode) = spawnit($command);
  326. my $elapsed = tv_interval ( $t0 ) if opt('time');
  327. vprint -1, "c time: $elapsed" if opt('time');
  328. if (@$error_r && $errcode != 0) {
  329. _die("$Input did not compile $errcode:\n@$error_r\n");
  330. } else {
  331. my @error = grep { !/^$Input syntax OK$/o } @$error_r;
  332. warn "$0: Unexpected compiler output\n@error" if @error and opt('v')<5;
  333. warn "@error" if @error and opt('v')>4;
  334. }
  335. unless (opt('dryrun')) {
  336. chmod 0777 & ~umask, $Output or _die("can't chmod $Output: $!\n");
  337. }
  338. }
  339. sub compile_cstyle {
  340. my $stash = opt('stash') ? grab_stash() : "";
  341. $stash .= "," if $stash; #stash can be empty
  342. $stash .= "-u$_," for @{$Options->{u}};
  343. $stash .= "-U$_," for @{$Options->{U}};
  344. my $taint = opt('T') ? ' -T' :
  345. opt('t') ? ' -t' : '';
  346. # What are we going to call our output C file?
  347. my $lose = 0;
  348. my ($cfh);
  349. my $testsuite = '';
  350. my $addoptions = '';
  351. if (@_ == 1) {
  352. $addoptions .= $_[0].",";
  353. }
  354. $addoptions .= opt('Wb');
  355. if( $addoptions ) {
  356. $addoptions .= ',-Dfull' if opt('v') >= 6;
  357. $addoptions .= ',-Dsp,-v' if opt('v') == 5;
  358. $addoptions .= ',';
  359. } elsif (opt('v') > 4) {
  360. $addoptions = '-Dsp,-v,';
  361. $addoptions = '-Dfull,-v,' if opt('v') >= 6;
  362. }
  363. if (opt('f')) {
  364. $addoptions .= "-f$_," for @{$Options->{f}};
  365. }
  366. my $staticxs = opt('staticxs') ? "-staticxs," : '';
  367. warn "--staticxs on darwin does not work yet\n"
  368. if $staticxs and $^O eq 'darwin';
  369. if (opt('testsuite')) {
  370. my $bo = join '', @begin_output;
  371. $bo =~ s/\\/\\\\\\\\/gs;
  372. $bo =~ s/\n/\\n/gs;
  373. $bo =~ s/,/\\054/gs;
  374. # don't look at that: it hurts
  375. $testsuite = q{-fuse-script-name,-fsave-data,-fsave-sig-hash,}.
  376. qq[-e"print q{$bo}",] .
  377. q{-e"open(Test::Builder::TESTOUT\054 '>&STDOUT') or die $!",} .
  378. q{-e"open(Test::Builder::TESTERR\054 '>&STDERR') or die $!",};
  379. }
  380. if (opt('o')) {
  381. $cfile = opt('o').".c";
  382. } elsif (opt('S') || opt('c')) { # We need to keep it
  383. if (opt('e')) {
  384. $cfile = opt('o') ? opt('o').".c" : "a.out.c";
  385. } else {
  386. $cfile = basename($Input);
  387. # File off extension if present
  388. # hold on: plx is executable; also, careful of ordering!
  389. $cfile =~ s/\.(?:p(?:lx|l|h)|m)\z//i;
  390. $cfile .= ".c";
  391. $cfile = $Output if opt('c') && $Output =~ /\.c\z/i;
  392. }
  393. check_write($cfile);
  394. } else { # Do not keep tempfiles (no -S nor -c nor -o)
  395. $lose = 1;
  396. ($cfh, $cfile) = tempfile("pccXXXXX", SUFFIX => ".c");
  397. close $cfh; # See comment just below
  398. }
  399. vprint 3, "Writing C on $cfile";
  400. my $max_line_len = '';
  401. if ($^O eq 'MSWin32' && $Config{cc} =~ /^cl/i) {
  402. $max_line_len = '-l2000,';
  403. }
  404. my $options = "$addoptions$testsuite$max_line_len$staticxs$stash";
  405. # This has to do the write itself, so we can't keep a lock. Life
  406. # sucks.
  407. my $command = "$BinPerl$taint -MO=$Backend,$options"."-o$cfile $Input";
  408. vprint 5, "Compiling...";
  409. vprint 0, "Calling $command";
  410. my $t0 = [gettimeofday] if opt('time');
  411. my ($output_r, $error_r, $errcode) = spawnit($command);
  412. my $elapsed = tv_interval ( $t0 ) if opt('time');
  413. my @output = @$output_r;
  414. my @error = @$error_r;
  415. if (@error && $errcode != 0) {
  416. _die("$Input did not compile, which can't happen $errcode:\n@error\n");
  417. } else {
  418. my $i = substr($Input,0,2) eq '-e' ? '-e' : $Input;
  419. @error = grep { !/^$i syntax OK$/o } @error;
  420. warn "$0: Unexpected compiler output\n@error" if @error and opt('v')<5;
  421. warn "@error" if @error and opt('v')>4;
  422. }
  423. vprint -1, "c time: $elapsed" if opt('time');
  424. $extra_libs = '';
  425. my %rpath;
  426. if ($staticxs and open(XS, "<", $cfile.".lst")) {
  427. while (<XS>) {
  428. my ($s, $l) = m/^([^\t]+)(.*)$/;
  429. next if grep { $s eq $_ } @{$Options->{U}};
  430. $stash .= ",-u$s";
  431. if ($l) {
  432. $l = substr($l,1);
  433. if ($^O eq 'darwin' and $l =~/\.bundle$/) {
  434. my $ofile = $l;
  435. $ofile =~ s/\.bundle$/.o/;
  436. $ofile =~ s{^.*/auto/}{};
  437. $ofile =~ s{(.*)/[^/]+\.o}{$1.o};
  438. $ofile =~ s{/}{_}g;
  439. $ofile = 'pcc'.$ofile;
  440. if (-e $ofile) {
  441. vprint 3, "Using ".$ofile;
  442. } else {
  443. vprint 3, "Creating ".$ofile;
  444. # This fails sometimes
  445. my $cmd = "otool -tv $l | \"$^X\" -pe "
  446. . q{'s{^/}{# .file /};s/^00[0-9a-f]+\s/\t/;s/^\(__(\w+)(,__.*?)?\) section/q(.).lc($1)/e'}
  447. . " | as -o \"$ofile\"";
  448. vprint 3, $cmd;
  449. vsystem($cmd);
  450. }
  451. $extra_libs .= " ".$l if -e $ofile;
  452. } else {
  453. $extra_libs .= " ".$l;
  454. $rpath{dirname($l)}++;
  455. }
  456. }
  457. }
  458. close XS;
  459. my ($rpath) = $Config{ccdlflags} =~ /^(.+rpath,)/;
  460. ($rpath) = $Config{ccdlflags} =~ m{^(.+-R,)/} unless $rpath;
  461. if (!$rpath and $Config{gccversion}) {
  462. $rpath = '-Wl,-rpath,';
  463. }
  464. $rpath =~ s/^-Wl,-E// if $rpath; # already done via ccdlflags
  465. # $extra_libs .= " $rpath".join(" ".$rpath,keys %rpath) if $rpath and %rpath;
  466. vprint 4, "staticxs: $stash $extra_libs";
  467. }
  468. $t0 = [gettimeofday] if opt('time');
  469. is_msvc ?
  470. cc_harness_msvc($cfile, $stash, $extra_libs) :
  471. cc_harness($cfile, $stash, $extra_libs) unless opt('c');
  472. $elapsed = tv_interval ( $t0 ) if opt('time');
  473. vprint -1, "cc time: $elapsed" if opt('time');
  474. if ($lose and -s $Output) {
  475. vprint 3, "Unlinking $cfile";
  476. unlink $cfile or _die("can't unlink $cfile: $!\n");
  477. }
  478. }
  479. sub cc_harness_msvc {
  480. my ($cfile, $stash, $extra_libs) = @_;
  481. use ExtUtils::Embed ();
  482. my $obj = "${Output}.obj";
  483. my $compile = ExtUtils::Embed::ccopts." -c -Fo$obj $cfile ";
  484. my $link = "-out:$Output $obj";
  485. $compile .= " -DHAVE_INDEPENDENT_COMALLOC" if $B::C::Flags::have_independent_comalloc;
  486. $compile .= $B::C::Flags::extra_cflags;
  487. $compile .= " -I".$_ for split /\s+/, opt('I');
  488. $compile .= " -DNO_DYNAMIC_LOADING" if opt('staticxs');
  489. $compile .= " ".opt('Wc') if opt('Wc');
  490. $link .= " -libpath:".$_ for split /\s+/, opt('L');
  491. # TODO: -shared,-static,-sharedxs
  492. if ($stash) {
  493. my @mods = split /,?-?u/, $stash; # XXX -U stashes
  494. $link .= " ".ExtUtils::Embed::ldopts("-std", \@mods);
  495. # XXX staticxs need to check if the last mods for staticxs found a static lib.
  496. # XXX only if not use the extra_libs
  497. } else {
  498. $link .= " ".ExtUtils::Embed::ldopts("-std");
  499. }
  500. if ($Config{ccversion} eq '12.0.8804') {
  501. $link =~ s/ -opt:ref,icf//;
  502. }
  503. $link .= " ".opt('Wl') if opt('Wl');
  504. $link .= $extra_libs;
  505. $link .= " perl5$Config{PERL_VERSION}.lib kernel32.lib msvcrt.lib";
  506. $link .= $B::C::Flags::extra_libs;
  507. vprint 3, "Calling $Config{cc} $compile";
  508. vsystem("$Config{cc} $compile");
  509. vprint 3, "Calling $Config{ld} $link";
  510. vsystem("$Config{ld} $link");
  511. }
  512. sub cc_harness {
  513. my ($cfile, $stash, $extra_libs) = @_;
  514. use ExtUtils::Embed ();
  515. my $command = ExtUtils::Embed::ccopts." -o $Output $cfile ";
  516. $command .= " -DHAVE_INDEPENDENT_COMALLOC" if $B::C::Flags::have_independent_comalloc;
  517. $command .= $B::C::Flags::extra_cflags if $B::C::Flags::extra_cflags;
  518. $command .= " -I".$_ for split /\s+/, opt('I');
  519. $command .= " -L".$_ for split /\s+/, opt('L');
  520. $command .= " -DNO_DYNAMIC_LOADING" if opt('staticxs');
  521. $command .= " ".opt('Wc') if opt('Wc');
  522. my $ccflags = $command;
  523. my $useshrplib = $Config{useshrplib};
  524. _die("--sharedxs with useshrplib=false\n") if !$useshrplib and opt('sharedxs');
  525. my $ldopts;
  526. if ($stash) {
  527. my @mods = split /,?-?u/, $stash; # XXX -U stashes
  528. $ldopts = ExtUtils::Embed::ldopts("-std", \@mods);
  529. } else {
  530. $ldopts = ExtUtils::Embed::ldopts("-std");
  531. }
  532. $ldopts .= " ".opt('Wl') if opt('Wl');
  533. # gcc crashes with this duplicate -fstack-protector arg
  534. my $ldflags = $Config{ldflags};
  535. if ($^O eq 'cygwin' and $ccflags =~ /-fstack-protector\b/ and $ldopts =~ /-fstack-protector\b/) {
  536. $ldopts =~ s/-fstack-protector\b//;
  537. $ldflags =~ s/-fstack-protector\b// if $extra_libs;
  538. }
  539. my $libperl = $Config{libperl};
  540. my $libdir = $Config{prefix} . "/lib";
  541. my $coredir = $ENV{PERL_SRC} || $Config{archlib}."/CORE";
  542. if ($extra_libs) {
  543. # splice extra_libs after $Config{ldopts} before @archives
  544. my $i_ldopts = index($ldopts, $ldflags);
  545. if ($ldflags and $i_ldopts >= 0) {
  546. my $l = $i_ldopts + length($ldflags);
  547. $ldopts = substr($ldopts,0,$l).$extra_libs." ".substr($ldopts,$l);
  548. } else {
  549. $ldopts = $extra_libs." ".$ldopts;
  550. }
  551. }
  552. if (opt('shared')) {
  553. warn "--shared with useshrplib=false might not work\n" unless $useshrplib;
  554. my @plibs = ($libperl, "$coredir/$libperl", "$libdir/$libperl");
  555. if ($libperl !~ /$Config{dlext}$/) {
  556. $libperl = "libperl.".$Config{dlext};
  557. @plibs = ($libperl, "$coredir/$libperl", "$libdir/$libperl");
  558. push @plibs, glob "$coredir/*perl5*".$Config{dlext};
  559. push @plibs, glob "$coredir/*perl.".$Config{dlext};
  560. push @plibs, glob $libdir."/*perl5*.".$Config{dlext};
  561. push @plibs, glob $libdir."/*perl.".$Config{dlext};
  562. push @plibs, glob $Config{bin}."/perl*.".$Config{dlext};
  563. }
  564. for my $lib (@plibs) {
  565. if (-e $lib) {
  566. $ldopts =~ s|-lperl |$lib |;
  567. $ldopts =~ s|\s+\S+libperl\w+\.a | $lib |;
  568. $ldopts = "$coredir/DynaLoader.o $ldopts" if -e "$coredir/DynaLoader.o";
  569. last;
  570. }
  571. }
  572. } elsif (opt('static')) {
  573. for my $lib ($libperl, "$coredir/$libperl", "$coredir/$libperl",
  574. "$coredir/libperl.a", "$libdir/libperl.a") {
  575. if (-e $lib) {
  576. $ldopts =~ s|-lperl |$lib |;
  577. $ldopts = "$coredir/DynaLoader.o $ldopts" if -e "$coredir/DynaLoader.o";
  578. last;
  579. }
  580. }
  581. } else {
  582. if ( $useshrplib and -e $libdir."/".$Config{libperl}) {
  583. # debian: only /usr/lib/libperl.so.5.10.1 and broken ExtUtils::Embed::ldopts
  584. $ldopts =~ s|-lperl |$libdir/$Config{libperl} |;
  585. }
  586. if ( $useshrplib and -e $coredir."/".$Config{libperl}) {
  587. # help cygwin debugging
  588. $ldopts =~ s|-lperl |$coredir/$Config{libperl} |;
  589. }
  590. }
  591. $ldopts .= " -lperl" unless $command =~ /perl/;
  592. $command .= " ".$ldopts;
  593. $command .= $B::C::Flags::extra_libs if $B::C::Flags::extra_libs;
  594. vprint 3, "Calling $Config{cc} $command";
  595. vsystem("$Config{cc} $command");
  596. }
  597. # Where Perl is, and which include path to give it.
  598. sub yclept {
  599. my $command = $^X =~ m/\s/ ? qq{"$^X"} : $^X;
  600. # DWIM the -I to be Perl, not C, include directories.
  601. if (opt('I') && $Backend eq "Bytecode") {
  602. for (split /\s+/, opt('I')) {
  603. if (-d $_) {
  604. push @INC, $_;
  605. } else {
  606. warn "$0: Include directory $_ not found, skipping\n";
  607. }
  608. }
  609. }
  610. my %OINC;
  611. $OINC{$Config{$_}}++ for (qw(privlib archlib sitelib sitearch vendorlib vendorarch));
  612. $OINC{'.'}++ unless ${^TAINT};
  613. $OINC{$_}++ for split ':', $Config{otherlibdirs};
  614. if (my $incver = $Config{inc_version_list}) {
  615. my $incpre = dirname($Config{sitelib});
  616. $OINC{$_}++ for map { File::Spec->catdir($incpre,$_) } split(' ',$incver);
  617. }
  618. for my $i (@INC) {
  619. my $inc = $i =~ m/\s/ ? qq{"$i"} : $i;
  620. $command .= " -I$inc" unless $OINC{$i}; # omit internal @INC dirs
  621. }
  622. return $command;
  623. }
  624. # Use B::Stash to find additional modules and stuff.
  625. {
  626. my $_stash;
  627. sub grab_stash {
  628. warn "already called grab_stash once" if $_stash;
  629. my $taint = opt('T') ? ' -T' :
  630. opt('t') ? ' -t' : '';
  631. my $command = "$BinPerl$taint -MB::Stash -c $Input";
  632. # Filename here is perfectly sanitised.
  633. vprint 3, "Calling $command\n";
  634. my ($stash_r, $error_r, $errcode) = spawnit($command);
  635. my @stash = @$stash_r;
  636. my @error = @$error_r;
  637. if (@error && $errcode != 0) {
  638. _die("$Input did not compile $errcode:\n@error\n");
  639. }
  640. # band-aid for modules with noisy BEGIN {}
  641. foreach my $i ( @stash ) {
  642. $i =~ m/-[ux](?:[\w:]+|\<none\>)$/ and $stash[0] = $i and next;
  643. push @begin_output, $i;
  644. }
  645. chomp $stash[0];
  646. $stash[0] =~ s/,-[ux]\<none\>//;
  647. $stash[0] =~ s/^.*?-([ux])/-$1/s;
  648. vprint 2, "Stash: ", join " ", split /,?-[ux]/, $stash[0];
  649. chomp $stash[0];
  650. return $_stash = $stash[0];
  651. }
  652. }
  653. # Check the consistency of options if -B is selected.
  654. # To wit, (-B|-O) ==> no -shared, no -S, no -c
  655. sub checkopts_byte {
  656. _die("Please choose one of either -B and -O.\n") if opt('O');
  657. for my $o ( qw[shared sharedxs static staticxs] ) {
  658. if (exists($Options->{$o}) && $Options->{$o}) {
  659. warn "$0: --$o incompatible with -B\n";
  660. delete $Options->{$o};
  661. }
  662. }
  663. # TODO make -S produce an .asm also?
  664. for my $o ( qw[c S] ) {
  665. if (exists($Options->{$o}) && $Options->{$o}) {
  666. warn "$0: Compiling to bytecode is a one-pass process. ",
  667. "-$o ignored\n";
  668. delete $Options->{$o};
  669. }
  670. }
  671. }
  672. # Check the input and output files make sense, are read/writeable.
  673. sub sanity_check {
  674. if ($Input eq $Output) {
  675. if ($Input eq 'a.out') {
  676. _die("Compiling a.out is probably not what you want to do.\n");
  677. # You fully deserve what you get now. No you *don't*. typos happen.
  678. } else {
  679. warn "$0: Will not write output on top of input file, ",
  680. "compiling to a.out instead\n";
  681. $Output = (is_win32 or $^O eq 'cygwin') ? 'a.exe' : 'a.out';
  682. }
  683. }
  684. }
  685. sub check_read {
  686. my $file = shift;
  687. unless (-r $file) {
  688. _die("Input file $file is a directory, not a file\n") if -d _;
  689. unless (-e _) {
  690. _die("Input file $file was not found\n");
  691. } else {
  692. _die("Cannot read input file $file: $!\n");
  693. }
  694. }
  695. unless (-f _) {
  696. # XXX: die? don't try this on /dev/tty
  697. warn "$0: WARNING: input $file is not a plain file\n";
  698. }
  699. }
  700. sub check_write {
  701. my $file = shift;
  702. if (-d $file) {
  703. _die("Cannot write on $file, is a directory\n");
  704. }
  705. if (-e _) {
  706. _die("Cannot write on $file: $!\n") unless -w _;
  707. }
  708. unless (-w '.') {
  709. _die("Cannot write in this directory: $!\n");
  710. }
  711. }
  712. sub check_perl {
  713. my $file = shift;
  714. unless (-T $file) {
  715. warn "$0: Binary `$file' sure doesn't smell like perl source!\n";
  716. print "Checking file type... ";
  717. vsystem("file", $file);
  718. _die("Please try a perlier file!\n");
  719. }
  720. open(my $handle, "<", $file) or _die("Can't open $file: $!\n");
  721. local $_ = <$handle>;
  722. if (/^#!/ && !/perl/) {
  723. _die("$file is a ", /^#!\s*(\S+)/, " script, not perl\n");
  724. }
  725. }
  726. # File spawning and error collecting
  727. sub spawnit {
  728. my $command = shift;
  729. my (@error,@output,$errname,$errcode);
  730. if (opt('dryrun')) {
  731. print "$command\n";;
  732. }
  733. elsif ($Options->{spawn}) {
  734. (undef, $errname) = tempfile("pccXXXXX");
  735. {
  736. my $pid = open (S_OUT, "$command 2>$errname |")
  737. or _die("Couldn't spawn the compiler.\n");
  738. $errcode = $?;
  739. my $kid;
  740. do {
  741. $kid = waitpid($pid, 0);
  742. } while $kid > 0;
  743. @output = <S_OUT>;
  744. }
  745. open (S_ERROR, $errname) or _die("Couldn't read the error file.\n");
  746. @error = <S_ERROR>;
  747. close S_ERROR;
  748. close S_OUT;
  749. unlink $errname or _die("Can't unlink error file $errname\n");
  750. } else {
  751. @output = split /\n/, `$command`;
  752. }
  753. return (\@output, \@error, $errcode);
  754. }
  755. sub version {
  756. require B::C::Flags;
  757. no warnings 'once';
  758. my $BC_VERSION = $B::C::Flags::VERSION . $B::C::REVISION;
  759. return "perlcc $VERSION, B-C-${BC_VERSION} built for $Config{perlpath} $Config{archname}\n";
  760. }
  761. sub helpme {
  762. print version(),"\n";
  763. if (opt('v')) {
  764. pod2usage( -verbose => opt('v') );
  765. } else {
  766. pod2usage( -verbose => 0 );
  767. }
  768. }
  769. sub relativize {
  770. my ($args) = @_;
  771. return() if ($args =~ m"^[/\\]");
  772. return("./$args");
  773. }
  774. sub _die {
  775. my @args = ("$0: ", @_);
  776. $logfh->print(@args) if opt('log');
  777. print STDERR @args;
  778. exit(); # should die eventually. However, needed so that a 'make compile'
  779. # can compile all the way through to the end for standard dist.
  780. }
  781. sub _usage_and_die {
  782. _die(<<EOU);
  783. Usage:
  784. $0 [-o executable] [-h][-r] [-O|-B|-c|-S] [-I /foo] [-L /foo] [--log log] [source[.pl] | -e code]
  785. More options (see perldoc perlcc)
  786. -v[1-4]
  787. --stash --staticxs --shared --static
  788. --testsuite --time
  789. EOU
  790. }
  791. sub run {
  792. my (@commands) = @_;
  793. my $t0 = [gettimeofday] if opt('time');
  794. print interruptrun(@commands) if (!opt('log'));
  795. $logfh->print(interruptrun(@commands)) if (opt('log'));
  796. my $elapsed = tv_interval ( $t0 ) if opt('time');
  797. vprint -1, "r time: $elapsed" if opt('time');
  798. }
  799. sub interruptrun {
  800. my (@commands) = @_;
  801. my $command = join('', @commands);
  802. local(*FD);
  803. my $pid = open(FD, "$command |");
  804. my $text;
  805. local($SIG{HUP}, $SIG{INT}) if exists $SIG{HUP};
  806. $SIG{HUP} = $SIG{INT} = sub { kill 9, $pid; exit } if exists $SIG{HUP};
  807. my $needalarm =
  808. ($ENV{PERLCC_TIMEOUT} &&
  809. exists $SIG{ALRM} &&
  810. $Config{'osname'} ne 'MSWin32' &&
  811. $command =~ m"(^|\s)perlcc\s");
  812. eval {
  813. local($SIG{ALRM}) = sub { die "INFINITE LOOP"; } if exists $SIG{ALRM};
  814. alarm($ENV{PERLCC_TIMEOUT}) if $needalarm;
  815. $text = join('', <FD>);
  816. alarm(0) if $needalarm;
  817. };
  818. if ($@) {
  819. eval { kill 'HUP', $pid };
  820. vprint 0, "SYSTEM TIMEOUT (infinite loop?)\n";
  821. }
  822. close(FD);
  823. return($text);
  824. }
  825. sub is_win32() { $^O =~ m/^MSWin/ }
  826. sub is_msvc() { is_win32 && $Config{cc} =~ m/^cl/i }
  827. END {
  828. if ($cfile && !opt('S') && !opt('c') && -e $cfile) {
  829. vprint 4, "Unlinking $cfile";
  830. unlink $cfile;
  831. }
  832. if (opt('staticxs') and !opt('S')) {
  833. vprint 4, "Unlinking $cfile.lst";
  834. unlink "$cfile.lst";
  835. }
  836. }
  837. __END__
  838. =head1 NAME
  839. perlcc - generate executables from Perl programs
  840. =head1 SYNOPSIS
  841. perlcc hello.pl # Compiles into executable 'a.out'
  842. perlcc -o hello hello.pl # Compiles into executable 'hello'
  843. perlcc -O file.pl # Compiles using the optimised CC backend
  844. perlcc -O3 file.pl # Compiles with C, using -O3 optimizations
  845. perlcc -B file.pl # Compiles using the bytecode backend
  846. perlcc -B -m file.pm # Compiles a module to file.pmc
  847. perlcc -c file.pl # Creates a C file, 'file.c'
  848. perlcc -S -o hello file.pl # Keep C file
  849. perlcc -c out.c file.pl # Creates a C file, 'out.c' from 'file'
  850. perlcc --staticxs -r -o hello hello.pl # Compiles,links and runs with
  851. # XS modules static/dynaloaded
  852. perlcc -e 'print q//' # Compiles a one-liner into 'a.out'
  853. perlcc -c -e 'print q//' # Creates a C file 'a.out.c'
  854. perlcc -I /foo hello # extra headers for C
  855. perlcc -L /foo hello # extra libraries for C
  856. perlcc --Wb=-Dsp # extra perl compiler options
  857. perlcc -fno-delete-pkg # extra perl compiler options
  858. perlcc --Wc=-fno-openmp # extra C compiler options
  859. perlcc --Wl=-s # extra C linker options
  860. perlcc -uIO::Socket # force saving IO::Socket
  861. perlcc -UB # "unuse" B, compile without any B symbols
  862. perlcc -r hello # compiles 'hello' into 'a.out', runs 'a.out'
  863. perlcc -r hello a b c # compiles 'hello' into 'a.out', runs 'a.out'
  864. # with arguments 'a b c'
  865. perlcc hello -log c.log # compiles 'hello' into 'a.out', log into 'c.log'
  866. perlcc -h # help, only SYNOPSIS
  867. perlcc -v2 -h # verbose help, also DESCRIPTION and OPTIONS
  868. perlcc --version # prints internal perlcc and the B-C release version
  869. =head1 DESCRIPTION
  870. F<perlcc> creates standalone executables from Perl programs, using the
  871. code generators provided by the L<B> module. At present, you may
  872. either create executable Perl bytecode, using the C<-B> option, or
  873. generate and compile C files using the standard and 'optimised' C
  874. backends.
  875. The code generated in this way is not guaranteed to work. The whole
  876. codegen suite (C<perlcc> included) should be considered B<very>
  877. experimental. Use for production purposes is strongly discouraged.
  878. =head1 OPTIONS
  879. =over 4
  880. =item -LI<C library directories>
  881. Adds the given directories to the library search path when C code is
  882. passed to your C compiler.
  883. =item -II<C include directories>
  884. Adds the given directories to the include file search path when C code is
  885. passed to your C compiler; when using the Perl bytecode option, adds the
  886. given directories to Perl's include path.
  887. =item -o I<output file name>
  888. Specifies the file name for the final compiled executable.
  889. =item -c I<C file name>
  890. Create C code only; do not compile to a standalone binary.
  891. =item -e I<perl code>
  892. Compile a one-liner, much the same as C<perl -e '...'>
  893. =item -S
  894. "Keep source".
  895. Do not delete generated C code after compilation.
  896. =item -B
  897. Use the Perl bytecode code generator.
  898. =item -O
  899. Use the 'optimised' C code generator B::CC. This is more experimental than
  900. everything else put together, and the code created is not guaranteed to
  901. compile in finite time and memory, or indeed, at all.
  902. =item -OI<1-4>
  903. Pass the numeric optimisation option to the compiler backend.
  904. Shortcut for C<-Wb=-On>.
  905. This does not enforce B::CC.
  906. =item -v I<0-6>
  907. Set verbosity of output from 0 to max. 6.
  908. =item -r
  909. Run the resulting compiled script after compiling it.
  910. =item --log I<logfile>
  911. Log the output of compiling to a file rather than to stdout.
  912. =item -f<option> or --f=<option>
  913. Pass the options to the compiler backend, such as
  914. C<-fstash> or C<-fno-delete-pkg>.
  915. =item --Wb=I<options>
  916. Pass the options to the compiler backend, such as C<--Wb=-O2,-v>
  917. =item --Wc=I<options>
  918. Pass comma-seperated options to cc.
  919. =item --Wl=I<options>
  920. Pass comma-seperated options to ld.
  921. =item -T or -t
  922. run the backend using perl -T or -t
  923. =item -u package
  924. Add package(s) to compiler and force linking to it.
  925. =item -U package
  926. Skip package(s). Do not compile and link.
  927. =item --stash
  928. Detect external packages automatically via B::Stash
  929. =item --static
  930. Link to static libperl.a
  931. =item --staticxs
  932. Link to static XS if available.
  933. If the XS libs are only available as shared libs link to those ("prelink").
  934. Systems without rpath (windows, cygwin) must be extend LD_LIBRARY_PATH/PATH at run-time.
  935. Together with -static, purely static modules and no run-time eval or
  936. require this will gain no external dependencies.
  937. =item --shared
  938. Link to shared libperl
  939. =item --sharedxs
  940. Link shared XSUBs if the linker supports it. No DynaLoader needed.
  941. This will still require the shared XSUB libraries to be installed
  942. at the client, modification of @INC in the source is probably required.
  943. (Not yet implemented)
  944. =item -m|--sharedlib [Modulename]
  945. Create a module, resp. a shared library.
  946. Currently only enabled for Bytecode and CC. I<(not yet tested)>
  947. =item --testsuite
  948. Tries be nice to Test:: modules, like preallocating the file
  949. handles 4 and 5, and munge the output of BEGIN.
  950. perlcc -r --testsuite t/harness
  951. =item --time
  952. Benchmark the different phases B<c> I<(B::* compilation)>,
  953. B<cc> I<(cc compile + link)>, and B<r> (runtime).
  954. =item --no-spawn
  955. Do not spawn subprocesses for compilation, because broken
  956. shells might not be able to kill its children.
  957. =back
  958. =cut
  959. # Local Variables:
  960. # mode: cperl
  961. # cperl-indent-level: 4
  962. # fill-column: 100
  963. # End:
  964. # vim: expandtab shiftwidth=4:
  965. !NO!SUBS!
  966. close OUT or die "Can't close $file: $!";
  967. chmod 0755, $file or die "Can't reset permissions for $file: $!\n";
  968. exec("$Config{'eunicefix'} $file") if $Config{'eunicefix'} ne ':';
  969. chdir $origdir;