perlcc.PL 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  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;
  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 (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. Time::HiRes->import('gettimeofday','tv_interval','sleep');
  255. }
  256. }
  257. $logfh = new FileHandle(">> " . opt('log')) if (opt('log'));
  258. if (opt('e')) {
  259. warn "$0: using -e 'code' as input file, ignoring @ARGV\n" if @ARGV;
  260. # We don't use a temporary file here; why bother?
  261. # XXX: this is not bullet proof -- spaces or quotes in name!
  262. $Input = is_win32() ? # Quotes eaten by shell
  263. '-e "'.opt('e').'"' :
  264. "-e '".opt('e')."'";
  265. } else {
  266. $Input = shift @ARGV; # XXX: more files?
  267. _usage_and_die("No input file specified\n") unless $Input;
  268. # DWIM modules. This is bad but necessary.
  269. $Options->{m} = '' if $Input =~ /\.pm\z/ and !opt('m');
  270. vprint 1, "$0: using $Input as input file, ignoring @ARGV\n" if @ARGV;
  271. check_read($Input);
  272. check_perl($Input);
  273. }
  274. if (opt('o')) {
  275. $Output = opt('o');
  276. } elsif (opt('B')) {
  277. if (opt('e')) {
  278. my $suffix = '.plc';
  279. $suffix = '.pmc' if exists $Options->{m};
  280. (undef, $Output) = tempfile("plcXXXXX", SUFFIX => $suffix);
  281. } else {
  282. $Output = basename($Input) . "c";
  283. }
  284. } else {
  285. $Output = ( is_win32() or $^O eq 'cygwin' ) ? 'a.exe' : 'a.out';
  286. }
  287. $Output = relativize($Output) unless is_win32();
  288. sanity_check();
  289. }
  290. sub opt(*) {
  291. my $opt = shift;
  292. return exists($Options->{$opt}) && ($Options->{$opt} || 0);
  293. }
  294. sub compile_module {
  295. if ($Backend eq 'Bytecode') {
  296. compile_byte('-m'.$Options->{m});
  297. } else {
  298. compile_cstyle("-m".$Options->{m});
  299. }
  300. }
  301. sub compile_byte {
  302. vprint 3, "Writing B on $Output";
  303. my $opts = $] < 5.007 ? "" : "-H,-s,";
  304. if ($] >= 5.007 and $Input =~ /^-e/) {
  305. $opts = "-H,";
  306. }
  307. if (@_ == 1) {
  308. $opts .= $_[0].",";
  309. }
  310. my $addoptions = opt('Wb');
  311. if( $addoptions ) {
  312. $opts .= '-v,' if opt('v') > 4;
  313. $opts .= '-DM,-DG,-DA,-DComment,' if opt('v') > 5;
  314. $opts .= "$addoptions,";
  315. } elsif (opt('v') > 4) {
  316. $opts .= '-v,';
  317. $opts .= '-DM,-DG,-DA,-DComment,' if opt('v') > 5;
  318. }
  319. my $command = "$BinPerl -MO=Bytecode,$opts-o$Output $Input";
  320. $Input =~ s/^-e.*$/-e/;
  321. vprint 5, "Compiling...";
  322. vprint 0, "Calling $command";
  323. my $t0 = [gettimeofday] if opt('time');
  324. my ($output_r, $error_r, $errcode) = spawnit($command);
  325. my $elapsed = tv_interval ( $t0 ) if opt('time');
  326. vprint -1, "c time: $elapsed" if opt('time');
  327. if (@$error_r && $errcode != 0) {
  328. _die("$Input did not compile $errcode:\n@$error_r\n");
  329. } else {
  330. my @error = grep { !/^$Input syntax OK$/o } @$error_r;
  331. warn "$0: Unexpected compiler output\n@error" if @error and opt('v')<5;
  332. warn "@error" if @error and opt('v')>4;
  333. }
  334. unless (opt('dryrun')) {
  335. chmod 0777 & ~umask, $Output or _die("can't chmod $Output: $!\n");
  336. }
  337. }
  338. sub compile_cstyle {
  339. my $stash = opt('stash') ? grab_stash() : "";
  340. $stash .= "," if $stash; #stash can be empty
  341. $stash .= "-u$_," for @{$Options->{u}};
  342. $stash .= "-U$_," for @{$Options->{U}};
  343. my $taint = opt('T') ? ' -T' :
  344. opt('t') ? ' -t' : '';
  345. # What are we going to call our output C file?
  346. my $lose = 0;
  347. my ($cfh);
  348. my $testsuite = '';
  349. my $addoptions = '';
  350. if (@_ == 1) {
  351. $addoptions .= $_[0].",";
  352. }
  353. $addoptions .= opt('Wb');
  354. if( $addoptions ) {
  355. $addoptions .= ',-Dfull' if opt('v') >= 6;
  356. $addoptions .= ',-Dsp,-v' if opt('v') == 5;
  357. $addoptions .= ',';
  358. } elsif (opt('v') > 4) {
  359. $addoptions = '-Dsp,-v,';
  360. $addoptions = '-Dfull,-v,' if opt('v') >= 6;
  361. }
  362. if (opt('f')) {
  363. $addoptions .= "-f$_," for @{$Options->{f}};
  364. }
  365. my $staticxs = opt('staticxs') ? "-staticxs," : '';
  366. warn "--staticxs on darwin does not work yet\n"
  367. if $staticxs and $^O eq 'darwin';
  368. if (opt('testsuite')) {
  369. my $bo = join '', @begin_output;
  370. $bo =~ s/\\/\\\\\\\\/gs;
  371. $bo =~ s/\n/\\n/gs;
  372. $bo =~ s/,/\\054/gs;
  373. # don't look at that: it hurts
  374. $testsuite = q{-fuse-script-name,-fsave-data,-fsave-sig-hash,}.
  375. qq[-e"print q{$bo}",] .
  376. q{-e"open(Test::Builder::TESTOUT\054 '>&STDOUT') or die $!",} .
  377. q{-e"open(Test::Builder::TESTERR\054 '>&STDERR') or die $!",};
  378. }
  379. if (opt('o')) {
  380. $cfile = opt('o').".c";
  381. } elsif (opt('S') || opt('c')) { # We need to keep it
  382. if (opt('e')) {
  383. $cfile = opt('o') ? opt('o').".c" : "a.out.c";
  384. } else {
  385. $cfile = basename($Input);
  386. # File off extension if present
  387. # hold on: plx is executable; also, careful of ordering!
  388. $cfile =~ s/\.(?:p(?:lx|l|h)|m)\z//i;
  389. $cfile .= ".c";
  390. $cfile = $Output if opt('c') && $Output =~ /\.c\z/i;
  391. }
  392. check_write($cfile);
  393. } else { # Do not keep tempfiles (no -S nor -c nor -o)
  394. $lose = 1;
  395. ($cfh, $cfile) = tempfile("pccXXXXX", SUFFIX => ".c");
  396. close $cfh; # See comment just below
  397. }
  398. vprint 3, "Writing C on $cfile";
  399. my $max_line_len = '';
  400. if ($^O eq 'MSWin32' && $Config{cc} =~ /^cl/i) {
  401. $max_line_len = '-l2000,';
  402. }
  403. my $options = "$addoptions$testsuite$max_line_len$staticxs$stash";
  404. # This has to do the write itself, so we can't keep a lock. Life
  405. # sucks.
  406. my $command = "$BinPerl$taint -MO=$Backend,$options"."-o$cfile $Input";
  407. vprint 5, "Compiling...";
  408. vprint 0, "Calling $command";
  409. my $t0 = [gettimeofday] if opt('time');
  410. my ($output_r, $error_r, $errcode) = spawnit($command);
  411. my $elapsed = tv_interval ( $t0 ) if opt('time');
  412. my @output = @$output_r;
  413. my @error = @$error_r;
  414. if (@error && $errcode != 0) {
  415. _die("$Input did not compile, which can't happen $errcode:\n@error\n");
  416. } else {
  417. my $i = substr($Input,0,2) eq '-e' ? '-e' : $Input;
  418. @error = grep { !/^$i syntax OK$/o } @error;
  419. warn "$0: Unexpected compiler output\n@error" if @error and opt('v')<5;
  420. warn "@error" if @error and opt('v')>4;
  421. }
  422. vprint -1, "c time: $elapsed" if opt('time');
  423. $extra_libs = '';
  424. my %rpath;
  425. if ($staticxs and open(XS, "<", $cfile.".lst")) {
  426. while (<XS>) {
  427. my ($s, $l) = m/^([^\t]+)(.*)$/;
  428. next if grep { $s eq $_ } @{$Options->{U}};
  429. $stash .= ",-u$s";
  430. if ($l) {
  431. $l = substr($l,1);
  432. if ($^O eq 'darwin' and $l =~/\.bundle$/) {
  433. my $ofile = $l;
  434. $ofile =~ s/\.bundle$/.o/;
  435. $ofile =~ s{^.*/auto/}{};
  436. $ofile =~ s{(.*)/[^/]+\.o}{$1.o};
  437. $ofile =~ s{/}{_}g;
  438. $ofile = 'pcc'.$ofile;
  439. if (-e $ofile) {
  440. vprint 3, "Using ".$ofile;
  441. } else {
  442. vprint 3, "Creating ".$ofile;
  443. # This fails sometimes
  444. my $cmd = "otool -tv $l | \"$^X\" -pe "
  445. . q{'s{^/}{# .file /};s/^00[0-9a-f]+\s/\t/;s/^\(__(\w+)(,__.*?)?\) section/q(.).lc($1)/e'}
  446. . " | as -o \"$ofile\"";
  447. vprint 3, $cmd;
  448. vsystem($cmd);
  449. }
  450. $extra_libs .= " ".$l if -e $ofile;
  451. } else {
  452. $extra_libs .= " ".$l;
  453. $rpath{dirname($l)}++;
  454. }
  455. }
  456. }
  457. close XS;
  458. my ($rpath) = $Config{ccdlflags} =~ /^(.+rpath,)/;
  459. ($rpath) = $Config{ccdlflags} =~ m{^(.+-R,)/} unless $rpath;
  460. if (!$rpath and $Config{gccversion}) {
  461. $rpath = '-Wl,-rpath,';
  462. }
  463. $rpath =~ s/^-Wl,-E// if $rpath; # already done via ccdlflags
  464. # $extra_libs .= " $rpath".join(" ".$rpath,keys %rpath) if $rpath and %rpath;
  465. vprint 4, "staticxs: $stash $extra_libs";
  466. }
  467. $t0 = [gettimeofday] if opt('time');
  468. is_msvc ?
  469. cc_harness_msvc($cfile, $stash, $extra_libs) :
  470. cc_harness($cfile, $stash, $extra_libs) unless opt('c');
  471. $elapsed = tv_interval ( $t0 ) if opt('time');
  472. vprint -1, "cc time: $elapsed" if opt('time');
  473. if ($lose and -s $Output) {
  474. vprint 3, "Unlinking $cfile";
  475. unlink $cfile or _die("can't unlink $cfile: $!\n");
  476. }
  477. }
  478. sub cc_harness_msvc {
  479. my ($cfile, $stash, $extra_libs) = @_;
  480. use ExtUtils::Embed ();
  481. my $obj = "${Output}.obj";
  482. my $compile = ExtUtils::Embed::ccopts." -c -Fo$obj $cfile ";
  483. my $link = "-out:$Output $obj";
  484. $compile .= " -DHAVE_INDEPENDENT_COMALLOC" if $B::C::Flags::have_independent_comalloc;
  485. $compile .= $B::C::Flags::extra_cflags;
  486. $compile .= " -I".$_ for split /\s+/, opt('I');
  487. $compile .= " -DNO_DYNAMIC_LOADING" if opt('staticxs');
  488. $compile .= " ".opt('Wc') if opt('Wc');
  489. $link .= " -libpath:".$_ for split /\s+/, opt('L');
  490. # TODO: -shared,-static,-sharedxs
  491. if ($stash) {
  492. my @mods = split /,?-?u/, $stash; # XXX -U stashes
  493. $link .= " ".ExtUtils::Embed::ldopts("-std", \@mods);
  494. # XXX staticxs need to check if the last mods for staticxs found a static lib.
  495. # XXX only if not use the extra_libs
  496. } else {
  497. $link .= " ".ExtUtils::Embed::ldopts("-std");
  498. }
  499. if ($Config{ccversion} eq '12.0.8804') {
  500. $link =~ s/ -opt:ref,icf//;
  501. }
  502. $link .= " ".opt('Wl') if opt('Wl');
  503. $link .= $extra_libs;
  504. $link .= " perl5$Config{PERL_VERSION}.lib kernel32.lib msvcrt.lib";
  505. $link .= $B::C::Flags::extra_libs;
  506. vprint 3, "Calling $Config{cc} $compile";
  507. vsystem("$Config{cc} $compile");
  508. vprint 3, "Calling $Config{ld} $link";
  509. vsystem("$Config{ld} $link");
  510. }
  511. sub cc_harness {
  512. my ($cfile, $stash, $extra_libs) = @_;
  513. use ExtUtils::Embed ();
  514. my $command = ExtUtils::Embed::ccopts." -o $Output $cfile ";
  515. $command .= " -DHAVE_INDEPENDENT_COMALLOC" if $B::C::Flags::have_independent_comalloc;
  516. $command .= $B::C::Flags::extra_cflags if $B::C::Flags::extra_cflags;
  517. $command .= " -I".$_ for split /\s+/, opt('I');
  518. $command .= " -L".$_ for split /\s+/, opt('L');
  519. $command .= " -DNO_DYNAMIC_LOADING" if opt('staticxs');
  520. $command .= " ".opt('Wc') if opt('Wc');
  521. my $ccflags = $command;
  522. my $useshrplib = $Config{useshrplib};
  523. _die("--sharedxs with useshrplib=false\n") if !$useshrplib and opt('sharedxs');
  524. my $ldopts;
  525. if ($stash) {
  526. my @mods = split /,?-?u/, $stash; # XXX -U stashes
  527. $ldopts = ExtUtils::Embed::ldopts("-std", \@mods);
  528. } else {
  529. $ldopts = ExtUtils::Embed::ldopts("-std");
  530. }
  531. $ldopts .= " ".opt('Wl') if opt('Wl');
  532. # gcc crashes with this duplicate -fstack-protector arg
  533. my $ldflags = $Config{ldflags};
  534. if ($ccflags =~ /-fstack-protector/ and $ldopts =~ /-fstack-protector/) {
  535. $ldopts =~ s/-fstack-protector//;
  536. $ldflags =~ s/-fstack-protector// if $extra_libs;
  537. }
  538. my $libperl = $Config{libperl};
  539. my $libdir = $Config{prefix} . "/lib";
  540. my $coredir = $ENV{PERL_SRC} || $Config{archlib}."/CORE";
  541. if ($extra_libs) {
  542. # splice extra_libs after $Config{ldopts} before @archives
  543. my $i_ldopts = index($ldopts, $ldflags);
  544. if ($ldflags and $i_ldopts >= 0) {
  545. my $l = $i_ldopts + length($ldflags);
  546. $ldopts = substr($ldopts,0,$l).$extra_libs." ".substr($ldopts,$l);
  547. } else {
  548. $ldopts = $extra_libs." ".$ldopts;
  549. }
  550. }
  551. if (opt('shared')) {
  552. warn "--shared with useshrplib=false might not work\n" unless $useshrplib;
  553. my @plibs = ($libperl, "$coredir/$libperl", "$libdir/$libperl");
  554. if ($libperl !~ /$Config{dlext}$/) {
  555. $libperl = "libperl.".$Config{dlext};
  556. @plibs = ($libperl, "$coredir/$libperl", "$libdir/$libperl");
  557. push @plibs, glob "$coredir/*perl5*".$Config{dlext};
  558. push @plibs, glob "$coredir/*perl.".$Config{dlext};
  559. push @plibs, glob $libdir."/*perl5*.".$Config{dlext};
  560. push @plibs, glob $libdir."/*perl.".$Config{dlext};
  561. push @plibs, glob $Config{bin}."/perl*.".$Config{dlext};
  562. }
  563. for my $lib (@plibs) {
  564. if (-e $lib) {
  565. $ldopts =~ s|-lperl |$lib |;
  566. $ldopts =~ s|\s+\S+libperl\w+\.a | $lib |;
  567. $ldopts = "$coredir/DynaLoader.o $ldopts" if -e "$coredir/DynaLoader.o";
  568. last;
  569. }
  570. }
  571. } elsif (opt('static')) {
  572. for my $lib ($libperl, "$coredir/$libperl", "$coredir/$libperl",
  573. "$coredir/libperl.a", "$libdir/libperl.a") {
  574. if (-e $lib) {
  575. $ldopts =~ s|-lperl |$lib |;
  576. $ldopts = "$coredir/DynaLoader.o $ldopts" if -e "$coredir/DynaLoader.o";
  577. last;
  578. }
  579. }
  580. } else {
  581. if ( $useshrplib and -e $libdir."/".$Config{libperl}) {
  582. # debian: only /usr/lib/libperl.so.5.10.1 and broken ExtUtils::Embed::ldopts
  583. $ldopts =~ s|-lperl |$libdir/$Config{libperl} |;
  584. }
  585. if ( $useshrplib and -e $coredir."/".$Config{libperl}) {
  586. # help cygwin debugging
  587. $ldopts =~ s|-lperl |$coredir/$Config{libperl} |;
  588. }
  589. }
  590. $ldopts .= " -lperl" unless $command =~ /perl/;
  591. $command .= " ".$ldopts;
  592. $command .= $B::C::Flags::extra_libs if $B::C::Flags::extra_libs;
  593. vprint 3, "Calling $Config{cc} $command";
  594. vsystem("$Config{cc} $command");
  595. }
  596. # Where Perl is, and which include path to give it.
  597. sub yclept {
  598. my $command = $^X =~ m/\s/ ? qq{"$^X"} : $^X;
  599. # DWIM the -I to be Perl, not C, include directories.
  600. if (opt('I') && $Backend eq "Bytecode") {
  601. for (split /\s+/, opt('I')) {
  602. if (-d $_) {
  603. push @INC, $_;
  604. } else {
  605. warn "$0: Include directory $_ not found, skipping\n";
  606. }
  607. }
  608. }
  609. my %OINC;
  610. $OINC{$Config{$_}}++ for (qw(privlib archlib sitelib sitearch vendorlib vendorarch));
  611. $OINC{'.'}++ unless ${^TAINT};
  612. $OINC{$_}++ for split ':', $Config{otherlibdirs};
  613. if (my $incver = $Config{inc_version_list}) {
  614. my $incpre = dirname($Config{sitelib});
  615. $OINC{$_}++ for map { File::Spec->catdir($incpre,$_) } split(' ',$incver);
  616. }
  617. for my $i (@INC) {
  618. my $inc = $i =~ m/\s/ ? qq{"$i"} : $i;
  619. $command .= " -I$inc" unless $OINC{$i}; # omit internal @INC dirs
  620. }
  621. return $command;
  622. }
  623. # Use B::Stash to find additional modules and stuff.
  624. {
  625. my $_stash;
  626. sub grab_stash {
  627. warn "already called grab_stash once" if $_stash;
  628. my $taint = opt('T') ? ' -T' :
  629. opt('t') ? ' -t' : '';
  630. my $command = "$BinPerl$taint -MB::Stash -c $Input";
  631. # Filename here is perfectly sanitised.
  632. vprint 3, "Calling $command\n";
  633. my ($stash_r, $error_r, $errcode) = spawnit($command);
  634. my @stash = @$stash_r;
  635. my @error = @$error_r;
  636. if (@error && $errcode != 0) {
  637. _die("$Input did not compile $errcode:\n@error\n");
  638. }
  639. # band-aid for modules with noisy BEGIN {}
  640. foreach my $i ( @stash ) {
  641. $i =~ m/-[ux](?:[\w:]+|\<none\>)$/ and $stash[0] = $i and next;
  642. push @begin_output, $i;
  643. }
  644. chomp $stash[0];
  645. $stash[0] =~ s/,-[ux]\<none\>//;
  646. $stash[0] =~ s/^.*?-([ux])/-$1/s;
  647. vprint 2, "Stash: ", join " ", split /,?-[ux]/, $stash[0];
  648. chomp $stash[0];
  649. return $_stash = $stash[0];
  650. }
  651. }
  652. # Check the consistency of options if -B is selected.
  653. # To wit, (-B|-O) ==> no -shared, no -S, no -c
  654. sub checkopts_byte {
  655. _die("Please choose one of either -B and -O.\n") if opt('O');
  656. for my $o ( qw[shared sharedxs static staticxs] ) {
  657. if (exists($Options->{$o}) && $Options->{$o}) {
  658. warn "$0: --$o incompatible with -B\n";
  659. delete $Options->{$o};
  660. }
  661. }
  662. # TODO make -S produce an .asm also?
  663. for my $o ( qw[c S] ) {
  664. if (exists($Options->{$o}) && $Options->{$o}) {
  665. warn "$0: Compiling to bytecode is a one-pass process. ",
  666. "-$o ignored\n";
  667. delete $Options->{$o};
  668. }
  669. }
  670. }
  671. # Check the input and output files make sense, are read/writeable.
  672. sub sanity_check {
  673. if ($Input eq $Output) {
  674. if ($Input eq 'a.out') {
  675. _die("Compiling a.out is probably not what you want to do.\n");
  676. # You fully deserve what you get now. No you *don't*. typos happen.
  677. } else {
  678. warn "$0: Will not write output on top of input file, ",
  679. "compiling to a.out instead\n";
  680. $Output = (is_win32 or $^O eq 'cygwin') ? 'a.exe' : 'a.out';
  681. }
  682. }
  683. }
  684. sub check_read {
  685. my $file = shift;
  686. unless (-r $file) {
  687. _die("Input file $file is a directory, not a file\n") if -d _;
  688. unless (-e _) {
  689. _die("Input file $file was not found\n");
  690. } else {
  691. _die("Cannot read input file $file: $!\n");
  692. }
  693. }
  694. unless (-f _) {
  695. # XXX: die? don't try this on /dev/tty
  696. warn "$0: WARNING: input $file is not a plain file\n";
  697. }
  698. }
  699. sub check_write {
  700. my $file = shift;
  701. if (-d $file) {
  702. _die("Cannot write on $file, is a directory\n");
  703. }
  704. if (-e _) {
  705. _die("Cannot write on $file: $!\n") unless -w _;
  706. }
  707. unless (-w '.') {
  708. _die("Cannot write in this directory: $!\n");
  709. }
  710. }
  711. sub check_perl {
  712. my $file = shift;
  713. unless (-T $file) {
  714. warn "$0: Binary `$file' sure doesn't smell like perl source!\n";
  715. print "Checking file type... ";
  716. vsystem("file", $file);
  717. _die("Please try a perlier file!\n");
  718. }
  719. open(my $handle, "<", $file) or _die("Can't open $file: $!\n");
  720. local $_ = <$handle>;
  721. if (/^#!/ && !/perl/) {
  722. _die("$file is a ", /^#!\s*(\S+)/, " script, not perl\n");
  723. }
  724. }
  725. # File spawning and error collecting
  726. sub spawnit {
  727. my $command = shift;
  728. my (@error,@output,$errname,$errcode);
  729. if (opt('dryrun')) {
  730. print "$command\n";;
  731. }
  732. elsif ($Options->{spawn}) {
  733. (undef, $errname) = tempfile("pccXXXXX");
  734. {
  735. my $pid = open (S_OUT, "$command 2>$errname |")
  736. or _die("Couldn't spawn the compiler.\n");
  737. $errcode = $?;
  738. my $kid;
  739. do {
  740. $kid = waitpid($pid, 0);
  741. } while $kid > 0;
  742. @output = <S_OUT>;
  743. }
  744. open (S_ERROR, $errname) or _die("Couldn't read the error file.\n");
  745. @error = <S_ERROR>;
  746. close S_ERROR;
  747. close S_OUT;
  748. unlink $errname or _die("Can't unlink error file $errname\n");
  749. } else {
  750. @output = split /\n/, `$command`;
  751. }
  752. return (\@output, \@error, $errcode);
  753. }
  754. sub version {
  755. require B::C::Flags;
  756. no warnings 'once';
  757. my $BC_VERSION = $B::C::Flags::VERSION . $B::C::REVISION;
  758. return "perlcc $VERSION, B-C-${BC_VERSION} built for $Config{perlpath} $Config{archname}\n";
  759. }
  760. sub helpme {
  761. print version(),"\n";
  762. if (opt('v')) {
  763. pod2usage( -verbose => opt('v') );
  764. } else {
  765. pod2usage( -verbose => 0 );
  766. }
  767. }
  768. sub relativize {
  769. my ($args) = @_;
  770. return() if ($args =~ m"^[/\\]");
  771. return("./$args");
  772. }
  773. sub _die {
  774. my @args = ("$0: ", @_);
  775. $logfh->print(@args) if opt('log');
  776. print STDERR @args;
  777. exit(); # should die eventually. However, needed so that a 'make compile'
  778. # can compile all the way through to the end for standard dist.
  779. }
  780. sub _usage_and_die {
  781. _die(<<EOU);
  782. Usage:
  783. $0 [-o executable] [-h][-r] [-O|-B|-c|-S] [-I /foo] [-L /foo] [--log log] [source[.pl] | -e code]
  784. More options (see perldoc perlcc)
  785. -v[1-4]
  786. --stash --staticxs --shared --static
  787. --testsuite --time
  788. EOU
  789. }
  790. sub run {
  791. my (@commands) = @_;
  792. my $t0 = [gettimeofday] if opt('time');
  793. print interruptrun(@commands) if (!opt('log'));
  794. $logfh->print(interruptrun(@commands)) if (opt('log'));
  795. my $elapsed = tv_interval ( $t0 ) if opt('time');
  796. vprint -1, "r time: $elapsed" if opt('time');
  797. }
  798. sub interruptrun {
  799. my (@commands) = @_;
  800. my $command = join('', @commands);
  801. local(*FD);
  802. my $pid = open(FD, "$command |");
  803. my $text;
  804. local($SIG{HUP}, $SIG{INT}) if exists $SIG{HUP};
  805. $SIG{HUP} = $SIG{INT} = sub { kill 9, $pid; exit } if exists $SIG{HUP};
  806. my $needalarm =
  807. ($ENV{PERLCC_TIMEOUT} &&
  808. exists $SIG{ALRM} &&
  809. $Config{'osname'} ne 'MSWin32' &&
  810. $command =~ m"(^|\s)perlcc\s");
  811. eval {
  812. local($SIG{ALRM}) = sub { die "INFINITE LOOP"; } if exists $SIG{ALRM};
  813. alarm($ENV{PERLCC_TIMEOUT}) if $needalarm;
  814. $text = join('', <FD>);
  815. alarm(0) if $needalarm;
  816. };
  817. if ($@) {
  818. eval { kill 'HUP', $pid };
  819. vprint 0, "SYSTEM TIMEOUT (infinite loop?)\n";
  820. }
  821. close(FD);
  822. return($text);
  823. }
  824. sub is_win32() { $^O =~ m/^MSWin/ }
  825. sub is_msvc() { is_win32 && $Config{cc} =~ m/^cl/i }
  826. END {
  827. if ($cfile && !opt('S') && !opt('c') && -e $cfile) {
  828. vprint 4, "Unlinking $cfile";
  829. unlink $cfile;
  830. }
  831. if (opt('staticxs') and !opt('S')) {
  832. vprint 4, "Unlinking $cfile.lst";
  833. unlink "$cfile.lst";
  834. }
  835. }
  836. __END__
  837. =head1 NAME
  838. perlcc - generate executables from Perl programs
  839. =head1 SYNOPSIS
  840. perlcc hello.pl # Compiles into executable 'a.out'
  841. perlcc -o hello hello.pl # Compiles into executable 'hello'
  842. perlcc -O file.pl # Compiles using the optimised CC backend
  843. perlcc -O3 file.pl # Compiles with C, using -O3 optimizations
  844. perlcc -B file.pl # Compiles using the bytecode backend
  845. perlcc -B -m file.pm # Compiles a module to file.pmc
  846. perlcc -c file.pl # Creates a C file, 'file.c'
  847. perlcc -S -o hello file.pl # Keep C file
  848. perlcc -c out.c file.pl # Creates a C file, 'out.c' from 'file'
  849. perlcc --staticxs -r -o hello hello.pl # Compiles,links and runs with
  850. # XS modules static/dynaloaded
  851. perlcc -e 'print q//' # Compiles a one-liner into 'a.out'
  852. perlcc -c -e 'print q//' # Creates a C file 'a.out.c'
  853. perlcc -I /foo hello # extra headers for C
  854. perlcc -L /foo hello # extra libraries for C
  855. perlcc --Wb=-Dsp # extra perl compiler options
  856. perlcc -fno-delete-pkg # extra perl compiler options
  857. perlcc --Wc=-fno-openmp # extra C compiler options
  858. perlcc --Wl=-s # extra C linker options
  859. perlcc -uIO::Socket # force saving IO::Socket
  860. perlcc -UB # "unuse" B, compile without any B symbols
  861. perlcc -r hello # compiles 'hello' into 'a.out', runs 'a.out'
  862. perlcc -r hello a b c # compiles 'hello' into 'a.out', runs 'a.out'
  863. # with arguments 'a b c'
  864. perlcc hello -log c.log # compiles 'hello' into 'a.out', log into 'c.log'
  865. perlcc -h # help, only SYNOPSIS
  866. perlcc -v2 -h # verbose help, also DESCRIPTION and OPTIONS
  867. perlcc --version # prints internal perlcc and the B-C release version
  868. =head1 DESCRIPTION
  869. F<perlcc> creates standalone executables from Perl programs, using the
  870. code generators provided by the L<B> module. At present, you may
  871. either create executable Perl bytecode, using the C<-B> option, or
  872. generate and compile C files using the standard and 'optimised' C
  873. backends.
  874. The code generated in this way is not guaranteed to work. The whole
  875. codegen suite (C<perlcc> included) should be considered B<very>
  876. experimental. Use for production purposes is strongly discouraged.
  877. =head1 OPTIONS
  878. =over 4
  879. =item -LI<C library directories>
  880. Adds the given directories to the library search path when C code is
  881. passed to your C compiler.
  882. =item -II<C include directories>
  883. Adds the given directories to the include file search path when C code is
  884. passed to your C compiler; when using the Perl bytecode option, adds the
  885. given directories to Perl's include path.
  886. =item -o I<output file name>
  887. Specifies the file name for the final compiled executable.
  888. =item -c I<C file name>
  889. Create C code only; do not compile to a standalone binary.
  890. =item -e I<perl code>
  891. Compile a one-liner, much the same as C<perl -e '...'>
  892. =item -S
  893. "Keep source".
  894. Do not delete generated C code after compilation.
  895. =item -B
  896. Use the Perl bytecode code generator.
  897. =item -O
  898. Use the 'optimised' C code generator B::CC. This is more experimental than
  899. everything else put together, and the code created is not guaranteed to
  900. compile in finite time and memory, or indeed, at all.
  901. =item -OI<1-4>
  902. Pass the numeric optimisation option to the compiler backend.
  903. Shortcut for C<-Wb=-On>.
  904. This does not enforce B::CC.
  905. =item -v I<0-6>
  906. Set verbosity of output from 0 to max. 6.
  907. =item -r
  908. Run the resulting compiled script after compiling it.
  909. =item --log I<logfile>
  910. Log the output of compiling to a file rather than to stdout.
  911. =item -f<option> or --f=<option>
  912. Pass the options to the compiler backend, such as
  913. C<-fstash> or C<-fno-delete-pkg>.
  914. =item --Wb=I<options>
  915. Pass the options to the compiler backend, such as C<--Wb=-O2,-v>
  916. =item --Wc=I<options>
  917. Pass comma-seperated options to cc.
  918. =item --Wl=I<options>
  919. Pass comma-seperated options to ld.
  920. =item -T or -t
  921. run the backend using perl -T or -t
  922. =item -u package
  923. Add package(s) to compiler and force linking to it.
  924. =item -U package
  925. Skip package(s). Do not compile and link.
  926. =item --stash
  927. Detect external packages automatically via B::Stash
  928. =item --static
  929. Link to static libperl.a
  930. =item --staticxs
  931. Link to static XS if available.
  932. If the XS libs are only available as shared libs link to those ("prelink").
  933. Systems without rpath (windows, cygwin) must be extend LD_LIBRARY_PATH/PATH at run-time.
  934. Together with -static, purely static modules and no run-time eval or
  935. require this will gain no external dependencies.
  936. =item --shared
  937. Link to shared libperl
  938. =item --sharedxs
  939. Link shared XSUBs if the linker supports it. No DynaLoader needed.
  940. This will still require the shared XSUB libraries to be installed
  941. at the client, modification of @INC in the source is probably required.
  942. (Not yet implemented)
  943. =item -m|--sharedlib [Modulename]
  944. Create a module, resp. a shared library.
  945. Currently only enabled for Bytecode and CC. I<(not yet tested)>
  946. =item --testsuite
  947. perlcc -r --testsuite t/harness
  948. =item --time
  949. Benchmark the different phases B<c> I<(B::* compilation)>,
  950. B<cc> I<(cc compile + link)>, and B<r> (runtime).
  951. =item --no-spawn
  952. Do not spawn subprocesses for compilation, because broken
  953. shells might not be able to kill its children.
  954. =back
  955. =cut
  956. # Local Variables:
  957. # mode: cperl
  958. # cperl-indent-level: 4
  959. # fill-column: 100
  960. # End:
  961. # vim: expandtab shiftwidth=4:
  962. q
  963. !NO!SUBS!
  964. close OUT or die "Can't close $file: $!";
  965. chmod 0755, $file or die "Can't reset permissions for $file: $!\n";
  966. exec("$Config{'eunicefix'} $file") if $Config{'eunicefix'} ne ':';
  967. chdir $origdir;