perlcc.PL 33 KB

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