PageRenderTime 70ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/19/mkmf.rb

http://github.com/rubinius/rubinius
Ruby | 2203 lines | 1819 code | 103 blank | 281 comment | 129 complexity | c1b359850eacc62b7d13688219671717 MD5 | raw file
Possible License(s): BSD-3-Clause, MPL-2.0-no-copyleft-exception, 0BSD, GPL-2.0, LGPL-2.1

Large files files are truncated, but you can click here to view the full file

  1. # -*- indent-tabs-mode: t -*-
  2. # module to create Makefile for extension modules
  3. # invoke like: ruby -r mkmf extconf.rb
  4. require 'rbconfig'
  5. require 'fileutils'
  6. require 'shellwords'
  7. CONFIG = RbConfig::MAKEFILE_CONFIG
  8. ORIG_LIBPATH = ENV['LIB']
  9. C_EXT = %w[c m]
  10. CXX_EXT = %w[cc mm cxx cpp]
  11. if File::FNM_SYSCASE.zero?
  12. CXX_EXT.concat(%w[C])
  13. end
  14. SRC_EXT = C_EXT + CXX_EXT
  15. $static = nil
  16. $config_h = '$(arch_hdrdir)/ruby/config.h'
  17. $default_static = $static
  18. unless defined? $configure_args
  19. $configure_args = {}
  20. args = CONFIG["configure_args"]
  21. if ENV["CONFIGURE_ARGS"]
  22. args << " " << ENV["CONFIGURE_ARGS"]
  23. end
  24. for arg in Shellwords::shellwords(args)
  25. arg, val = arg.split('=', 2)
  26. next unless arg
  27. arg.tr!('_', '-')
  28. if arg.sub!(/^(?!--)/, '--')
  29. val or next
  30. arg.downcase!
  31. end
  32. next if /^--(?:top|topsrc|src|cur)dir$/ =~ arg
  33. $configure_args[arg] = val || true
  34. end
  35. for arg in ARGV
  36. arg, val = arg.split('=', 2)
  37. next unless arg
  38. arg.tr!('_', '-')
  39. if arg.sub!(/^(?!--)/, '--')
  40. val or next
  41. arg.downcase!
  42. end
  43. $configure_args[arg] = val || true
  44. end
  45. end
  46. $libdir = CONFIG["libdir"]
  47. $rubylibdir = CONFIG["rubylibdir"]
  48. $archdir = CONFIG["archdir"]
  49. $sitedir = CONFIG["sitedir"]
  50. $sitelibdir = CONFIG["sitelibdir"]
  51. $sitearchdir = CONFIG["sitearchdir"]
  52. $vendordir = CONFIG["vendordir"]
  53. $vendorlibdir = CONFIG["vendorlibdir"]
  54. $vendorarchdir = CONFIG["vendorarchdir"]
  55. $mswin = /mswin/ =~ RUBY_PLATFORM
  56. $bccwin = /bccwin/ =~ RUBY_PLATFORM
  57. $mingw = /mingw/ =~ RUBY_PLATFORM
  58. $cygwin = /cygwin/ =~ RUBY_PLATFORM
  59. $netbsd = /netbsd/ =~ RUBY_PLATFORM
  60. $os2 = /os2/ =~ RUBY_PLATFORM
  61. $beos = /beos/ =~ RUBY_PLATFORM
  62. $haiku = /haiku/ =~ RUBY_PLATFORM
  63. $solaris = /solaris/ =~ RUBY_PLATFORM
  64. $universal = /universal/ =~ RUBY_PLATFORM
  65. $dest_prefix_pattern = (File::PATH_SEPARATOR == ';' ? /\A([[:alpha:]]:)?/ : /\A/)
  66. # :stopdoc:
  67. def config_string(key, config = CONFIG)
  68. s = config[key] and !s.empty? and block_given? ? yield(s) : s
  69. end
  70. def dir_re(dir)
  71. Regexp.new('\$(?:\('+dir+'\)|\{'+dir+'\})(?:\$(?:\(target_prefix\)|\{target_prefix\}))?')
  72. end
  73. def relative_from(path, base)
  74. dir = File.join(path, "")
  75. if File.expand_path(dir) == File.expand_path(dir, base)
  76. path
  77. else
  78. File.join(base, path)
  79. end
  80. end
  81. INSTALL_DIRS = [
  82. [dir_re('commondir'), "$(RUBYCOMMONDIR)"],
  83. [dir_re('sitedir'), "$(RUBYCOMMONDIR)"],
  84. [dir_re('vendordir'), "$(RUBYCOMMONDIR)"],
  85. [dir_re('rubylibdir'), "$(RUBYLIBDIR)"],
  86. [dir_re('archdir'), "$(RUBYARCHDIR)"],
  87. [dir_re('sitelibdir'), "$(RUBYLIBDIR)"],
  88. [dir_re('vendorlibdir'), "$(RUBYLIBDIR)"],
  89. [dir_re('sitearchdir'), "$(RUBYARCHDIR)"],
  90. [dir_re('vendorarchdir'), "$(RUBYARCHDIR)"],
  91. [dir_re('rubyhdrdir'), "$(RUBYHDRDIR)"],
  92. [dir_re('sitehdrdir'), "$(SITEHDRDIR)"],
  93. [dir_re('vendorhdrdir'), "$(VENDORHDRDIR)"],
  94. [dir_re('bindir'), "$(BINDIR)"],
  95. ]
  96. def install_dirs(target_prefix = nil)
  97. if $extout
  98. dirs = [
  99. ['BINDIR', '$(extout)/bin'],
  100. ['RUBYCOMMONDIR', '$(extout)/common'],
  101. ['RUBYLIBDIR', '$(RUBYCOMMONDIR)$(target_prefix)'],
  102. ['RUBYARCHDIR', '$(extout)/$(arch)$(target_prefix)'],
  103. ['HDRDIR', '$(extout)/include/ruby$(target_prefix)'],
  104. ['ARCHHDRDIR', '$(extout)/include/$(arch)/ruby$(target_prefix)'],
  105. ['extout', "#$extout"],
  106. ['extout_prefix', "#$extout_prefix"],
  107. ]
  108. elsif $extmk
  109. dirs = [
  110. ['BINDIR', '$(bindir)'],
  111. ['RUBYCOMMONDIR', '$(rubylibdir)'],
  112. ['RUBYLIBDIR', '$(rubylibdir)$(target_prefix)'],
  113. ['RUBYARCHDIR', '$(archdir)$(target_prefix)'],
  114. ['HDRDIR', '$(rubyhdrdir)/ruby$(target_prefix)'],
  115. ['ARCHHDRDIR', '$(rubyhdrdir)/$(arch)/ruby$(target_prefix)'],
  116. ]
  117. elsif $configure_args.has_key?('--vendor')
  118. dirs = [
  119. ['BINDIR', '$(bindir)'],
  120. ['RUBYCOMMONDIR', '$(vendordir)$(target_prefix)'],
  121. ['RUBYLIBDIR', '$(vendorlibdir)$(target_prefix)'],
  122. ['RUBYARCHDIR', '$(vendorarchdir)$(target_prefix)'],
  123. ['HDRDIR', '$(rubyhdrdir)/ruby$(target_prefix)'],
  124. ['ARCHHDRDIR', '$(rubyhdrdir)/$(arch)/ruby$(target_prefix)'],
  125. ]
  126. else
  127. dirs = [
  128. ['BINDIR', '$(bindir)'],
  129. ['RUBYCOMMONDIR', '$(sitedir)$(target_prefix)'],
  130. ['RUBYLIBDIR', '$(sitelibdir)$(target_prefix)'],
  131. ['RUBYARCHDIR', '$(sitearchdir)$(target_prefix)'],
  132. ['HDRDIR', '$(rubyhdrdir)/ruby$(target_prefix)'],
  133. ['ARCHHDRDIR', '$(rubyhdrdir)/$(arch)/ruby$(target_prefix)'],
  134. ]
  135. end
  136. dirs << ['target_prefix', (target_prefix ? "/#{target_prefix}" : "")]
  137. dirs
  138. end
  139. def map_dir(dir, map = nil)
  140. map ||= INSTALL_DIRS
  141. map.inject(dir) {|d, (orig, new)| d.gsub(orig, new)}
  142. end
  143. # ---------------------- Changed for Rubinius --------------------------------
  144. if dir = ENV['RBX_CAPI_DIR']
  145. if Rubinius.ruby18?
  146. $topdir = "#{dir}/vm/capi/18/include"
  147. else
  148. $topdir = "#{dir}/vm/capi/19/include"
  149. end
  150. else
  151. $topdir = RbConfig::CONFIG["rubyhdrdir"]
  152. end
  153. $top_srcdir = $topdir
  154. $hdrdir = $topdir
  155. $arch_hdrdir = $hdrdir
  156. unless File.exists?($hdrdir + "/ruby.h")
  157. abort "mkmf.rb can't find header files for ruby at #{$hdrdir}/ruby.h"
  158. end
  159. # ----------------------------------------------------------------------------
  160. OUTFLAG = CONFIG['OUTFLAG']
  161. COUTFLAG = CONFIG['COUTFLAG']
  162. CPPOUTFILE = CONFIG['CPPOUTFILE']
  163. CONFTEST_C = "conftest.c".freeze
  164. class String
  165. # Wraps a string in escaped quotes if it contains whitespace.
  166. def quote
  167. /\s/ =~ self ? "\"#{self}\"" : "#{self}"
  168. end
  169. # Generates a string used as cpp macro name.
  170. def tr_cpp
  171. strip.upcase.tr_s("^A-Z0-9_*", "_").tr_s("*", "P")
  172. end
  173. end
  174. class Array
  175. # Wraps all strings in escaped quotes if they contain whitespace.
  176. def quote
  177. map {|s| s.quote}
  178. end
  179. end
  180. def rm_f(*files)
  181. opt = (Hash === files.last ? [files.pop] : [])
  182. FileUtils.rm_f(Dir[*files.flatten], *opt)
  183. end
  184. def rm_rf(*files)
  185. opt = (Hash === files.last ? [files.pop] : [])
  186. FileUtils.rm_rf(Dir[*files.flatten], *opt)
  187. end
  188. # Returns time stamp of the +target+ file if it exists and is newer
  189. # than or equal to all of +times+.
  190. def modified?(target, times)
  191. (t = File.mtime(target)) rescue return nil
  192. Array === times or times = [times]
  193. t if times.all? {|n| n <= t}
  194. end
  195. def merge_libs(*libs)
  196. libs.inject([]) do |x, y|
  197. xy = x & y
  198. xn = yn = 0
  199. y = y.inject([]) {|ary, e| ary.last == e ? ary : ary << e}
  200. y.each_with_index do |v, yi|
  201. if xy.include?(v)
  202. xi = [x.index(v), xn].max()
  203. x[xi, 1] = y[yn..yi]
  204. xn, yn = xi + (yi - yn + 1), yi + 1
  205. end
  206. end
  207. x.concat(y[yn..-1] || [])
  208. end
  209. end
  210. # This is a custom logging module. It generates an mkmf.log file when you
  211. # run your extconf.rb script. This can be useful for debugging unexpected
  212. # failures.
  213. #
  214. # This module and its associated methods are meant for internal use only.
  215. #
  216. module Logging
  217. @log = nil
  218. @logfile = 'mkmf.log'
  219. @orgerr = $stderr.dup
  220. @orgout = $stdout.dup
  221. @postpone = 0
  222. @quiet = $extmk
  223. def self::log_open
  224. @log ||= File::open(@logfile, 'wb')
  225. @log.sync = true
  226. end
  227. def self::open
  228. log_open
  229. $stderr.reopen(@log)
  230. $stdout.reopen(@log)
  231. yield
  232. ensure
  233. $stderr.reopen(@orgerr)
  234. $stdout.reopen(@orgout)
  235. end
  236. def self::message(*s)
  237. log_open
  238. @log.printf(*s)
  239. end
  240. def self::logfile file
  241. @logfile = file
  242. log_close
  243. end
  244. def self::log_close
  245. if @log and not @log.closed?
  246. @log.flush
  247. @log.close
  248. @log = nil
  249. end
  250. end
  251. def self::postpone
  252. tmplog = "mkmftmp#{@postpone += 1}.log"
  253. open do
  254. log, *save = @log, @logfile, @orgout, @orgerr
  255. @log, @logfile, @orgout, @orgerr = nil, tmplog, log, log
  256. begin
  257. log.print(open {yield @log})
  258. ensure
  259. @log.close if @log and not @log.closed?
  260. File::open(tmplog) {|t| FileUtils.copy_stream(t, log)} if File.exist?(tmplog)
  261. @log, @logfile, @orgout, @orgerr = log, *save
  262. @postpone -= 1
  263. rm_f tmplog
  264. end
  265. end
  266. end
  267. class << self
  268. attr_accessor :quiet
  269. end
  270. end
  271. def xsystem command, opts = nil
  272. varpat = /\$\((\w+)\)|\$\{(\w+)\}/
  273. if varpat =~ command
  274. vars = Hash.new {|h, k| h[k] = ''; ENV[k]}
  275. command = command.dup
  276. nil while command.gsub!(varpat) {vars[$1||$2]}
  277. end
  278. Logging::open do
  279. puts command.quote
  280. if opts and opts[:werror]
  281. result = nil
  282. Logging.postpone do |log|
  283. result = (system(command) and File.zero?(log.path))
  284. ""
  285. end
  286. result
  287. else
  288. system(command)
  289. end
  290. end
  291. end
  292. def xpopen command, *mode, &block
  293. Logging::open do
  294. case mode[0]
  295. when nil, /^r/
  296. puts "#{command} |"
  297. else
  298. puts "| #{command}"
  299. end
  300. IO.popen(command, *mode, &block)
  301. end
  302. end
  303. def log_src(src)
  304. src = src.split(/^/)
  305. fmt = "%#{src.size.to_s.size}d: %s"
  306. Logging::message <<"EOM"
  307. checked program was:
  308. /* begin */
  309. EOM
  310. src.each_with_index {|line, no| Logging::message fmt, no+1, line}
  311. Logging::message <<"EOM"
  312. /* end */
  313. EOM
  314. end
  315. def create_tmpsrc(src)
  316. src = "#{COMMON_HEADERS}\n#{src}"
  317. src = yield(src) if block_given?
  318. src.gsub!(/[ \t]+$/, '')
  319. src.gsub!(/\A\n+|^\n+$/, '')
  320. src.sub!(/[^\n]\z/, "\\&\n")
  321. count = 0
  322. begin
  323. open(CONFTEST_C, "wb") do |cfile|
  324. cfile.print src
  325. end
  326. rescue Errno::EACCES
  327. if (count += 1) < 5
  328. sleep 0.2
  329. retry
  330. end
  331. end
  332. src
  333. end
  334. def have_devel?
  335. unless defined? $have_devel
  336. $have_devel = true
  337. $have_devel = try_link(MAIN_DOES_NOTHING)
  338. end
  339. $have_devel
  340. end
  341. def try_do(src, command, *opts, &b)
  342. unless have_devel?
  343. raise <<MSG
  344. The compiler failed to generate an executable file.
  345. You have to install development tools first.
  346. MSG
  347. end
  348. begin
  349. src = create_tmpsrc(src, &b)
  350. xsystem(command, *opts)
  351. ensure
  352. log_src(src)
  353. rm_rf 'conftest.dSYM'
  354. end
  355. end
  356. def link_command(ldflags, opt="", libpath=$DEFLIBPATH|$LIBPATH)
  357. librubyarg = $extmk ? $LIBRUBYARG_STATIC : "$(LIBRUBYARG)"
  358. conf = RbConfig::CONFIG.merge('hdrdir' => $hdrdir.quote,
  359. 'src' => "#{CONFTEST_C}",
  360. 'arch_hdrdir' => $arch_hdrdir.quote,
  361. 'top_srcdir' => $top_srcdir.quote,
  362. 'INCFLAGS' => "#$INCFLAGS",
  363. 'CPPFLAGS' => "#$CPPFLAGS",
  364. 'CFLAGS' => "#$CFLAGS",
  365. 'ARCH_FLAG' => "#$ARCH_FLAG",
  366. 'LDFLAGS' => "#$LDFLAGS #{ldflags}",
  367. 'LOCAL_LIBS' => "#$LOCAL_LIBS #$libs",
  368. 'LIBS' => "#{librubyarg} #{opt} #$LIBS")
  369. conf['LIBPATH'] = libpathflag(libpath.map {|s| RbConfig::expand(s.dup, conf)})
  370. RbConfig::expand(TRY_LINK.dup, conf)
  371. end
  372. def cc_command(opt="")
  373. conf = RbConfig::CONFIG.merge('hdrdir' => $hdrdir.quote, 'srcdir' => $srcdir.quote,
  374. 'arch_hdrdir' => $arch_hdrdir.quote,
  375. 'top_srcdir' => $top_srcdir.quote)
  376. RbConfig::expand("$(CC) #$INCFLAGS #$CPPFLAGS #$CFLAGS #$ARCH_FLAG #{opt} -c #{CONFTEST_C}",
  377. conf)
  378. end
  379. def cpp_command(outfile, opt="")
  380. conf = RbConfig::CONFIG.merge('hdrdir' => $hdrdir.quote, 'srcdir' => $srcdir.quote,
  381. 'arch_hdrdir' => $arch_hdrdir.quote,
  382. 'top_srcdir' => $top_srcdir.quote)
  383. RbConfig::expand("$(CPP) #$INCFLAGS #$CPPFLAGS #$CFLAGS #{opt} #{CONFTEST_C} #{outfile}",
  384. conf)
  385. end
  386. def libpathflag(libpath=$DEFLIBPATH|$LIBPATH)
  387. libpath.map{|x|
  388. case x
  389. when "$(topdir)", /\A\./
  390. LIBPATHFLAG
  391. else
  392. LIBPATHFLAG+RPATHFLAG
  393. end % x.quote
  394. }.join
  395. end
  396. def with_werror(opt, opts = nil)
  397. if opts
  398. if opts[:werror] and config_string("WERRORFLAG") {|flag| opt = opt ? "#{opt} #{flag}" : flag}
  399. (opts = opts.dup).delete(:werror)
  400. end
  401. yield(opt, opts)
  402. else
  403. yield(opt)
  404. end
  405. end
  406. # :nodoc:
  407. def try_link0(src, opt="", *opts, &b)
  408. cmd = link_command("", opt)
  409. if $universal
  410. require 'tmpdir'
  411. Dir.mktmpdir("mkmf_", oldtmpdir = ENV["TMPDIR"]) do |tmpdir|
  412. begin
  413. ENV["TMPDIR"] = tmpdir
  414. try_do(src, cmd, *opts, &b)
  415. ensure
  416. ENV["TMPDIR"] = oldtmpdir
  417. end
  418. end
  419. else
  420. try_do(src, cmd, *opts, &b)
  421. end
  422. end
  423. # Returns whether or not the +src+ can be compiled as a C source and
  424. # linked with its depending libraries successfully.
  425. # +opt+ is passed to the linker as options. Note that +$CFLAGS+ and +$LDFLAGS+
  426. # are also passed to the linker.
  427. #
  428. # If a block given, it is called with the source before compilation. You can
  429. # modify the source in the block.
  430. #
  431. # [+src+] a String which contains a C source
  432. # [+opt+] a String which contains linker options
  433. def try_link(src, opt="", *opts, &b)
  434. try_link0(src, opt, *opts, &b)
  435. ensure
  436. rm_f "conftest*", "c0x32*"
  437. end
  438. # Returns whether or not the +src+ can be compiled as a C source.
  439. # +opt+ is passed to the C compiler as options. Note that +$CFLAGS+ is
  440. # also passed to the compiler.
  441. #
  442. # If a block given, it is called with the source before compilation. You can
  443. # modify the source in the block.
  444. #
  445. # [+src+] a String which contains a C source
  446. # [+opt+] a String which contains compiler options
  447. def try_compile(src, opt="", *opts, &b)
  448. with_werror(opt, *opts) {|_opt, *_opts| try_do(src, cc_command(_opt), *_opts, &b)}
  449. ensure
  450. rm_f "conftest*"
  451. end
  452. # Returns whether or not the +src+ can be preprocessed with the C preprocessor.
  453. # +opt+ is passed to the preprocessor as options. Note that +$CFLAGS+ is
  454. # also passed to the preprocessor.
  455. #
  456. # If a block given, it is called with the source before preprocessing. You can
  457. # modify the source in the block.
  458. #
  459. # [+src+] a String which contains a C source
  460. # [+opt+] a String which contains preprocessor options
  461. def try_cpp(src, opt="", *opts, &b)
  462. try_do(src, cpp_command(CPPOUTFILE, opt), *opts, &b)
  463. ensure
  464. rm_f "conftest*"
  465. end
  466. class Object
  467. alias_method :try_header, (config_string('try_header') || :try_cpp)
  468. end
  469. def cpp_include(header)
  470. if header
  471. header = [header] unless header.kind_of? Array
  472. header.map {|h| String === h ? "#include <#{h}>\n" : h}.join
  473. else
  474. ""
  475. end
  476. end
  477. def with_cppflags(flags)
  478. cppflags = $CPPFLAGS
  479. $CPPFLAGS = flags
  480. ret = yield
  481. ensure
  482. $CPPFLAGS = cppflags unless ret
  483. end
  484. def with_cflags(flags)
  485. cflags = $CFLAGS
  486. $CFLAGS = flags
  487. ret = yield
  488. ensure
  489. $CFLAGS = cflags unless ret
  490. end
  491. def with_ldflags(flags)
  492. ldflags = $LDFLAGS
  493. $LDFLAGS = flags
  494. ret = yield
  495. ensure
  496. $LDFLAGS = ldflags unless ret
  497. end
  498. def try_static_assert(expr, headers = nil, opt = "", &b)
  499. headers = cpp_include(headers)
  500. try_compile(<<SRC, opt, &b)
  501. #{headers}
  502. /*top*/
  503. int conftest_const[(#{expr}) ? 1 : -1];
  504. SRC
  505. end
  506. def try_constant(const, headers = nil, opt = "", &b)
  507. includes = cpp_include(headers)
  508. if CROSS_COMPILING
  509. if try_static_assert("#{const} > 0", headers, opt)
  510. # positive constant
  511. elsif try_static_assert("#{const} < 0", headers, opt)
  512. neg = true
  513. const = "-(#{const})"
  514. elsif try_static_assert("#{const} == 0", headers, opt)
  515. return 0
  516. else
  517. # not a constant
  518. return nil
  519. end
  520. upper = 1
  521. lower = 0
  522. until try_static_assert("#{const} <= #{upper}", headers, opt)
  523. lower = upper
  524. upper <<= 1
  525. end
  526. return nil unless lower
  527. while upper > lower + 1
  528. mid = (upper + lower) / 2
  529. if try_static_assert("#{const} > #{mid}", headers, opt)
  530. lower = mid
  531. else
  532. upper = mid
  533. end
  534. end
  535. upper = -upper if neg
  536. return upper
  537. else
  538. src = %{#{includes}
  539. #include <stdio.h>
  540. /*top*/
  541. int conftest_const = (int)(#{const});
  542. int main() {printf("%d\\n", conftest_const); return 0;}
  543. }
  544. if try_link0(src, opt, &b)
  545. xpopen("./conftest") do |f|
  546. return Integer(f.gets)
  547. end
  548. end
  549. end
  550. nil
  551. end
  552. # You should use +have_func+ rather than +try_func+.
  553. #
  554. # [+func+] a String which contains a symbol name
  555. # [+libs+] a String which contains library names.
  556. # [+headers+] a String or an Array of strings which contains
  557. # names of header files.
  558. def try_func(func, libs, headers = nil, &b)
  559. headers = cpp_include(headers)
  560. case func
  561. when /^&/
  562. decltype = proc {|x|"const volatile void *#{x}"}
  563. else
  564. call = true
  565. decltype = proc {|x| "void ((*#{x})())"}
  566. end
  567. try_link(<<"SRC", libs, &b) or
  568. #{headers}
  569. /*top*/
  570. #{MAIN_DOES_NOTHING}
  571. int t() { #{decltype["volatile p"]}; p = (#{decltype[]})#{func}; return 0; }
  572. SRC
  573. call && try_link(<<"SRC", libs, &b)
  574. #{headers}
  575. /*top*/
  576. #{MAIN_DOES_NOTHING}
  577. int t() { #{func}(); return 0; }
  578. SRC
  579. end
  580. # You should use +have_var+ rather than +try_var+.
  581. def try_var(var, headers = nil, &b)
  582. headers = cpp_include(headers)
  583. try_compile(<<"SRC", &b)
  584. #{headers}
  585. /*top*/
  586. #{MAIN_DOES_NOTHING}
  587. int t() { const volatile void *volatile p; p = &(&#{var})[0]; return 0; }
  588. SRC
  589. end
  590. # Returns whether or not the +src+ can be preprocessed with the C preprocessor and
  591. # matches with +pat+.
  592. #
  593. # If a block given, it is called with the source before compilation. You can
  594. # modify the source in the block.
  595. #
  596. # [+pat+] a Regexp or a String
  597. # [+src+] a String which contains a C source
  598. # [+opt+] a String which contains preprocessor options
  599. #
  600. # Note:
  601. # When pat is a Regexp the matching will be checked in process,
  602. # otherwise egrep(1) will be invoked to check it.
  603. def egrep_cpp(pat, src, opt = "", &b)
  604. src = create_tmpsrc(src, &b)
  605. xpopen(cpp_command('', opt)) do |f|
  606. if Regexp === pat
  607. puts(" ruby -ne 'print if #{pat.inspect}'")
  608. f.grep(pat) {|l|
  609. puts "#{f.lineno}: #{l}"
  610. return true
  611. }
  612. false
  613. else
  614. puts(" egrep '#{pat}'")
  615. begin
  616. stdin = $stdin.dup
  617. $stdin.reopen(f)
  618. system("egrep", pat)
  619. ensure
  620. $stdin.reopen(stdin)
  621. end
  622. end
  623. end
  624. ensure
  625. rm_f "conftest*"
  626. log_src(src)
  627. end
  628. # This is used internally by the have_macro? method.
  629. def macro_defined?(macro, src, opt = "", &b)
  630. src = src.sub(/[^\n]\z/, "\\&\n")
  631. try_compile(src + <<"SRC", opt, &b)
  632. /*top*/
  633. #ifndef #{macro}
  634. # error
  635. >>>>>> #{macro} undefined <<<<<<
  636. #endif
  637. SRC
  638. end
  639. # Returns whether or not
  640. # * the +src+ can be compiled as a C source,
  641. # * the result object can be linked with its depending libraries successfully,
  642. # * the linked file can be invoked as an executable
  643. # * and the executable exits successfully
  644. # +opt+ is passed to the linker as options. Note that +$CFLAGS+ and +$LDFLAGS+
  645. # are also passed to the linker.
  646. #
  647. # If a block given, it is called with the source before compilation. You can
  648. # modify the source in the block.
  649. #
  650. # [+src+] a String which contains a C source
  651. # [+opt+] a String which contains linker options
  652. #
  653. # @return true when the executable exits successfully, false when it fails, or
  654. # nil when preprocessing, compilation or link fails.
  655. def try_run(src, opt = "", &b)
  656. if try_link0(src, opt, &b)
  657. xsystem("./conftest")
  658. else
  659. nil
  660. end
  661. ensure
  662. rm_f "conftest*"
  663. end
  664. def install_files(mfile, ifiles, map = nil, srcprefix = nil)
  665. ifiles or return
  666. ifiles.empty? and return
  667. srcprefix ||= "$(srcdir)/#{srcprefix}".chomp('/')
  668. RbConfig::expand(srcdir = srcprefix.dup)
  669. dirs = []
  670. path = Hash.new {|h, i| h[i] = dirs.push([i])[-1]}
  671. ifiles.each do |files, dir, prefix|
  672. dir = map_dir(dir, map)
  673. prefix &&= %r|\A#{Regexp.quote(prefix)}/?|
  674. if /\A\.\// =~ files
  675. # install files which are in current working directory.
  676. files = files[2..-1]
  677. len = nil
  678. else
  679. # install files which are under the $(srcdir).
  680. files = File.join(srcdir, files)
  681. len = srcdir.size
  682. end
  683. f = nil
  684. Dir.glob(files) do |fx|
  685. f = fx
  686. f[0..len] = "" if len
  687. case File.basename(f)
  688. when *$NONINSTALLFILES
  689. next
  690. end
  691. d = File.dirname(f)
  692. d.sub!(prefix, "") if prefix
  693. d = (d.empty? || d == ".") ? dir : File.join(dir, d)
  694. f = File.join(srcprefix, f) if len
  695. path[d] << f
  696. end
  697. unless len or f
  698. d = File.dirname(files)
  699. d.sub!(prefix, "") if prefix
  700. d = (d.empty? || d == ".") ? dir : File.join(dir, d)
  701. path[d] << files
  702. end
  703. end
  704. dirs
  705. end
  706. def install_rb(mfile, dest, srcdir = nil)
  707. install_files(mfile, [["lib/**/*.rb", dest, "lib"]], nil, srcdir)
  708. end
  709. def append_library(libs, lib) # :no-doc:
  710. format(LIBARG, lib) + " " + libs
  711. end
  712. def message(*s)
  713. unless Logging.quiet and not $VERBOSE
  714. printf(*s)
  715. $stdout.flush
  716. end
  717. end
  718. # This emits a string to stdout that allows users to see the results of the
  719. # various have* and find* methods as they are tested.
  720. #
  721. # Internal use only.
  722. #
  723. def checking_for(m, fmt = nil)
  724. f = caller[0][/in `([^<].*)'$/, 1] and f << ": " #` for vim #'
  725. m = "checking #{/\Acheck/ =~ f ? '' : 'for '}#{m}... "
  726. message "%s", m
  727. a = r = nil
  728. Logging::postpone do
  729. r = yield
  730. a = (fmt ? fmt % r : r ? "yes" : "no") << "\n"
  731. "#{f}#{m}-------------------- #{a}\n"
  732. end
  733. message(a)
  734. Logging::message "--------------------\n\n"
  735. r
  736. end
  737. def checking_message(target, place = nil, opt = nil)
  738. [["in", place], ["with", opt]].inject("#{target}") do |msg, (pre, noun)|
  739. if noun
  740. [[:to_str], [:join, ","], [:to_s]].each do |meth, *args|
  741. if noun.respond_to?(meth)
  742. break noun = noun.send(meth, *args)
  743. end
  744. end
  745. msg << " #{pre} #{noun}" unless noun.empty?
  746. end
  747. msg
  748. end
  749. end
  750. # :startdoc:
  751. # Returns whether or not +macro+ is defined either in the common header
  752. # files or within any +headers+ you provide.
  753. #
  754. # Any options you pass to +opt+ are passed along to the compiler.
  755. #
  756. def have_macro(macro, headers = nil, opt = "", &b)
  757. checking_for checking_message(macro, headers, opt) do
  758. macro_defined?(macro, cpp_include(headers), opt, &b)
  759. end
  760. end
  761. # Returns whether or not the given entry point +func+ can be found within
  762. # +lib+. If +func+ is nil, the 'main()' entry point is used by default.
  763. # If found, it adds the library to list of libraries to be used when linking
  764. # your extension.
  765. #
  766. # If +headers+ are provided, it will include those header files as the
  767. # header files it looks in when searching for +func+.
  768. #
  769. # The real name of the library to be linked can be altered by
  770. # '--with-FOOlib' configuration option.
  771. #
  772. def have_library(lib, func = nil, headers = nil, &b)
  773. func = "main" if !func or func.empty?
  774. lib = with_config(lib+'lib', lib)
  775. checking_for checking_message("#{func}()", LIBARG%lib) do
  776. if COMMON_LIBS.include?(lib)
  777. true
  778. else
  779. libs = append_library($libs, lib)
  780. if try_func(func, libs, headers, &b)
  781. $libs = libs
  782. true
  783. else
  784. false
  785. end
  786. end
  787. end
  788. end
  789. # Returns whether or not the entry point +func+ can be found within the library
  790. # +lib+ in one of the +paths+ specified, where +paths+ is an array of strings.
  791. # If +func+ is nil , then the main() function is used as the entry point.
  792. #
  793. # If +lib+ is found, then the path it was found on is added to the list of
  794. # library paths searched and linked against.
  795. #
  796. def find_library(lib, func, *paths, &b)
  797. func = "main" if !func or func.empty?
  798. lib = with_config(lib+'lib', lib)
  799. paths = paths.collect {|path| path.split(File::PATH_SEPARATOR)}.flatten
  800. checking_for "#{func}() in #{LIBARG%lib}" do
  801. libpath = $LIBPATH
  802. libs = append_library($libs, lib)
  803. begin
  804. until r = try_func(func, libs, &b) or paths.empty?
  805. $LIBPATH = libpath | [paths.shift]
  806. end
  807. if r
  808. $libs = libs
  809. libpath = nil
  810. end
  811. ensure
  812. $LIBPATH = libpath if libpath
  813. end
  814. r
  815. end
  816. end
  817. # Returns whether or not the function +func+ can be found in the common
  818. # header files, or within any +headers+ that you provide. If found, a
  819. # macro is passed as a preprocessor constant to the compiler using the
  820. # function name, in uppercase, prepended with 'HAVE_'.
  821. #
  822. # For example, if have_func('foo') returned true, then the HAVE_FOO
  823. # preprocessor macro would be passed to the compiler.
  824. #
  825. def have_func(func, headers = nil, &b)
  826. checking_for checking_message("#{func}()", headers) do
  827. if try_func(func, $libs, headers, &b)
  828. $defs.push(format("-DHAVE_%s", func.tr_cpp))
  829. true
  830. else
  831. false
  832. end
  833. end
  834. end
  835. # Returns whether or not the variable +var+ can be found in the common
  836. # header files, or within any +headers+ that you provide. If found, a
  837. # macro is passed as a preprocessor constant to the compiler using the
  838. # variable name, in uppercase, prepended with 'HAVE_'.
  839. #
  840. # For example, if have_var('foo') returned true, then the HAVE_FOO
  841. # preprocessor macro would be passed to the compiler.
  842. #
  843. def have_var(var, headers = nil, &b)
  844. checking_for checking_message(var, headers) do
  845. if try_var(var, headers, &b)
  846. $defs.push(format("-DHAVE_%s", var.tr_cpp))
  847. true
  848. else
  849. false
  850. end
  851. end
  852. end
  853. # Returns whether or not the given +header+ file can be found on your system.
  854. # If found, a macro is passed as a preprocessor constant to the compiler using
  855. # the header file name, in uppercase, prepended with 'HAVE_'.
  856. #
  857. # For example, if have_header('foo.h') returned true, then the HAVE_FOO_H
  858. # preprocessor macro would be passed to the compiler.
  859. #
  860. def have_header(header, preheaders = nil, &b)
  861. checking_for header do
  862. if try_header(cpp_include(preheaders)+cpp_include(header), &b)
  863. $defs.push(format("-DHAVE_%s", header.tr_cpp))
  864. true
  865. else
  866. false
  867. end
  868. end
  869. end
  870. # Returns whether or not the given +framework+ can be found on your system.
  871. # If found, a macro is passed as a preprocessor constant to the compiler using
  872. # the framework name, in uppercase, prepended with 'HAVE_FRAMEWORK_'.
  873. #
  874. # For example, if have_framework('Ruby') returned true, then the HAVE_FRAMEWORK_RUBY
  875. # preprocessor macro would be passed to the compiler.
  876. #
  877. def have_framework(fw, &b)
  878. checking_for fw do
  879. src = cpp_include("#{fw}/#{fw}.h") << "\n" "int main(void){return 0;}"
  880. if try_link(src, opt = "-framework #{fw}", &b)
  881. $defs.push(format("-DHAVE_FRAMEWORK_%s", fw.tr_cpp))
  882. $LDFLAGS << " " << opt
  883. true
  884. else
  885. false
  886. end
  887. end
  888. end
  889. # Instructs mkmf to search for the given +header+ in any of the +paths+
  890. # provided, and returns whether or not it was found in those paths.
  891. #
  892. # If the header is found then the path it was found on is added to the list
  893. # of included directories that are sent to the compiler (via the -I switch).
  894. #
  895. def find_header(header, *paths)
  896. message = checking_message(header, paths)
  897. header = cpp_include(header)
  898. checking_for message do
  899. if try_header(header)
  900. true
  901. else
  902. found = false
  903. paths.each do |dir|
  904. opt = "-I#{dir}".quote
  905. if try_header(header, opt)
  906. $INCFLAGS << " " << opt
  907. found = true
  908. break
  909. end
  910. end
  911. found
  912. end
  913. end
  914. end
  915. # Returns whether or not the struct of type +type+ contains +member+. If
  916. # it does not, or the struct type can't be found, then false is returned. You
  917. # may optionally specify additional +headers+ in which to look for the struct
  918. # (in addition to the common header files).
  919. #
  920. # If found, a macro is passed as a preprocessor constant to the compiler using
  921. # the type name and the member name, in uppercase, prepended with 'HAVE_'.
  922. #
  923. # For example, if have_struct_member('struct foo', 'bar') returned true, then the
  924. # HAVE_STRUCT_FOO_BAR preprocessor macro would be passed to the compiler.
  925. #
  926. # HAVE_ST_BAR is also defined for backward compatibility.
  927. #
  928. def have_struct_member(type, member, headers = nil, &b)
  929. checking_for checking_message("#{type}.#{member}", headers) do
  930. if try_compile(<<"SRC", &b)
  931. #{cpp_include(headers)}
  932. /*top*/
  933. #{MAIN_DOES_NOTHING}
  934. int s = (char *)&((#{type}*)0)->#{member} - (char *)0;
  935. SRC
  936. $defs.push(format("-DHAVE_%s_%s", type.tr_cpp, member.tr_cpp))
  937. $defs.push(format("-DHAVE_ST_%s", member.tr_cpp)) # backward compatibility
  938. true
  939. else
  940. false
  941. end
  942. end
  943. end
  944. # Returns whether or not the static type +type+ is defined.
  945. #
  946. # See also +have_type+
  947. #
  948. def try_type(type, headers = nil, opt = "", &b)
  949. if try_compile(<<"SRC", opt, &b)
  950. #{cpp_include(headers)}
  951. /*top*/
  952. typedef #{type} conftest_type;
  953. int conftestval[sizeof(conftest_type)?1:-1];
  954. SRC
  955. $defs.push(format("-DHAVE_TYPE_%s", type.tr_cpp))
  956. true
  957. else
  958. false
  959. end
  960. end
  961. # Returns whether or not the static type +type+ is defined. You may
  962. # optionally pass additional +headers+ to check against in addition to the
  963. # common header files.
  964. #
  965. # You may also pass additional flags to +opt+ which are then passed along to
  966. # the compiler.
  967. #
  968. # If found, a macro is passed as a preprocessor constant to the compiler using
  969. # the type name, in uppercase, prepended with 'HAVE_TYPE_'.
  970. #
  971. # For example, if have_type('foo') returned true, then the HAVE_TYPE_FOO
  972. # preprocessor macro would be passed to the compiler.
  973. #
  974. def have_type(type, headers = nil, opt = "", &b)
  975. checking_for checking_message(type, headers, opt) do
  976. try_type(type, headers, opt, &b)
  977. end
  978. end
  979. # Returns where the static type +type+ is defined.
  980. #
  981. # You may also pass additional flags to +opt+ which are then passed along to
  982. # the compiler.
  983. #
  984. # See also +have_type+.
  985. #
  986. def find_type(type, opt, *headers, &b)
  987. opt ||= ""
  988. fmt = "not found"
  989. def fmt.%(x)
  990. x ? x.respond_to?(:join) ? x.join(",") : x : self
  991. end
  992. checking_for checking_message(type, nil, opt), fmt do
  993. headers.find do |h|
  994. try_type(type, h, opt, &b)
  995. end
  996. end
  997. end
  998. # Returns whether or not the Constant +const+ is defined.
  999. #
  1000. # See also +have_const+
  1001. #
  1002. def try_const(const, headers = nil, opt = "", &b)
  1003. const, type = *const
  1004. if try_compile(<<"SRC", opt, &b)
  1005. #{cpp_include(headers)}
  1006. /*top*/
  1007. typedef #{type || 'int'} conftest_type;
  1008. conftest_type conftestval = #{type ? '' : '(int)'}#{const};
  1009. SRC
  1010. $defs.push(format("-DHAVE_CONST_%s", const.tr_cpp))
  1011. true
  1012. else
  1013. false
  1014. end
  1015. end
  1016. # Returns whether or not the constant +const+ is defined. You may
  1017. # optionally pass the +type+ of +const+ as <code>[const, type]</code>,
  1018. # like as:
  1019. #
  1020. # have_const(%w[PTHREAD_MUTEX_INITIALIZER pthread_mutex_t], "pthread.h")
  1021. #
  1022. # You may also pass additional +headers+ to check against in addition
  1023. # to the common header files, and additional flags to +opt+ which are
  1024. # then passed along to the compiler.
  1025. #
  1026. # If found, a macro is passed as a preprocessor constant to the compiler using
  1027. # the type name, in uppercase, prepended with 'HAVE_CONST_'.
  1028. #
  1029. # For example, if have_const('foo') returned true, then the HAVE_CONST_FOO
  1030. # preprocessor macro would be passed to the compiler.
  1031. #
  1032. def have_const(const, headers = nil, opt = "", &b)
  1033. checking_for checking_message([*const].compact.join(' '), headers, opt) do
  1034. try_const(const, headers, opt, &b)
  1035. end
  1036. end
  1037. STRING_OR_FAILED_FORMAT = "%s"
  1038. # :stopdoc:
  1039. def STRING_OR_FAILED_FORMAT.%(x)
  1040. x ? super : "failed"
  1041. end
  1042. def typedef_expr(type, headers)
  1043. typename, member = type.split('.', 2)
  1044. prelude = cpp_include(headers).split(/$/)
  1045. prelude << "typedef #{typename} rbcv_typedef_;\n"
  1046. return "rbcv_typedef_", member, prelude
  1047. end
  1048. def try_signedness(type, member, headers = nil, opts = nil, &b)
  1049. raise ArgumentError, "don't know how to tell signedness of members" if member
  1050. if try_static_assert("(#{type})-1 < 0", headers, opts)
  1051. return -1
  1052. elsif try_static_assert("(#{type})-1 > 0", headers, opts)
  1053. return +1
  1054. end
  1055. end
  1056. # :startdoc:
  1057. # Returns the size of the given +type+. You may optionally specify additional
  1058. # +headers+ to search in for the +type+.
  1059. #
  1060. # If found, a macro is passed as a preprocessor constant to the compiler using
  1061. # the type name, in uppercase, prepended with 'SIZEOF_', followed by the type
  1062. # name, followed by '=X' where 'X' is the actual size.
  1063. #
  1064. # For example, if check_sizeof('mystruct') returned 12, then the
  1065. # SIZEOF_MYSTRUCT=12 preprocessor macro would be passed to the compiler.
  1066. #
  1067. def check_sizeof(type, headers = nil, opts = "", &b)
  1068. typedef, member, prelude = typedef_expr(type, headers)
  1069. prelude << "static #{typedef} *rbcv_ptr_;\n"
  1070. prelude = [prelude]
  1071. expr = "sizeof((*rbcv_ptr_)#{"." << member if member})"
  1072. fmt = STRING_OR_FAILED_FORMAT
  1073. checking_for checking_message("size of #{type}", headers), fmt do
  1074. if size = try_constant(expr, prelude, opts, &b)
  1075. $defs.push(format("-DSIZEOF_%s=%s", type.tr_cpp, size))
  1076. size
  1077. end
  1078. end
  1079. end
  1080. # Returns the signedness of the given +type+. You may optionally
  1081. # specify additional +headers+ to search in for the +type+.
  1082. #
  1083. # If the +type+ is found and is a numeric type, a macro is passed as a
  1084. # preprocessor constant to the compiler using the +type+ name, in
  1085. # uppercase, prepended with 'SIGNEDNESS_OF_', followed by the +type+
  1086. # name, followed by '=X' where 'X' is positive integer if the +type+ is
  1087. # unsigned, or negative integer if the +type+ is signed.
  1088. #
  1089. # For example, if size_t is defined as unsigned, then
  1090. # check_signedness('size_t') would returned +1 and the
  1091. # SIGNEDNESS_OF_SIZE_T=+1 preprocessor macro would be passed to the
  1092. # compiler, and SIGNEDNESS_OF_INT=-1 if check_signedness('int') is
  1093. # done.
  1094. #
  1095. def check_signedness(type, headers = nil, opts = nil, &b)
  1096. typedef, member, prelude = typedef_expr(type, headers)
  1097. signed = nil
  1098. checking_for("signedness of #{type}", STRING_OR_FAILED_FORMAT) do
  1099. signed = try_signedness(typedef, member, [prelude], opts, &b) or next nil
  1100. $defs.push("-DSIGNEDNESS_OF_%s=%+d" % [type.tr_cpp, signed])
  1101. signed < 0 ? "signed" : "unsigned"
  1102. end
  1103. signed
  1104. end
  1105. # Returns the convertible integer type of the given +type+. You may
  1106. # optionally specify additional +headers+ to search in for the +type+.
  1107. # _Convertible_ means actually same type, or typedefed from same type.
  1108. #
  1109. # If the +type+ is a integer type and _convertible_ type is found,
  1110. # following macros are passed as preprocessor constants to the
  1111. # compiler using the +type+ name, in uppercase.
  1112. #
  1113. # * 'TYPEOF_', followed by the +type+ name, followed by '=X' where 'X'
  1114. # is the found _convertible_ type name. * 'TYP2NUM' and 'NUM2TYP,
  1115. # where 'TYP' is the +type+ name in uppercase with replacing '_t'
  1116. # suffix with 'T', followed by '=X' where 'X' is the macro name to
  1117. # convert +type+ to +Integer+ object, and vice versa.
  1118. #
  1119. # For example, if foobar_t is defined as unsigned long, then
  1120. # convertible_int("foobar_t") would return "unsigned long", and define
  1121. # macros:
  1122. #
  1123. # #define TYPEOF_FOOBAR_T unsigned long
  1124. # #define FOOBART2NUM ULONG2NUM
  1125. # #define NUM2FOOBART NUM2ULONG
  1126. def convertible_int(type, headers = nil, opts = nil, &b)
  1127. type, macname = *type
  1128. checking_for("convertible type of #{type}", STRING_OR_FAILED_FORMAT) do
  1129. if UNIVERSAL_INTS.include?(type)
  1130. type
  1131. else
  1132. typedef, member, prelude = typedef_expr(type, headers, &b)
  1133. next unless signed = try_signedness(typedef, member, [prelude])
  1134. u = "unsigned " if signed > 0
  1135. prelude << "extern rbcv_typedef_ foo();"
  1136. compat = UNIVERSAL_INTS.find {|t|
  1137. try_compile([prelude, "extern #{u}#{t} foo();"].join("\n"), opts, :werror=>true, &b)
  1138. }
  1139. if compat
  1140. macname ||= type.sub(/_(?=t\z)/, '').tr_cpp
  1141. conv = (compat == "long long" ? "LL" : compat.upcase)
  1142. compat = "#{u}#{compat}"
  1143. $defs.push(format("-DTYPEOF_%s=%s", type.tr_cpp, compat.quote))
  1144. $defs.push(format("-DPRI_%s_PREFIX=PRI_%s_PREFIX", macname, conv))
  1145. conv = (u ? "U" : "") + conv
  1146. $defs.push(format("-D%s2NUM=%s2NUM", macname, conv))
  1147. $defs.push(format("-DNUM2%s=NUM2%s", macname, conv))
  1148. compat
  1149. end
  1150. end
  1151. end
  1152. end
  1153. # :stopdoc:
  1154. # Used internally by the what_type? method to determine if +type+ is a scalar
  1155. # pointer.
  1156. def scalar_ptr_type?(type, member = nil, headers = nil, &b)
  1157. try_compile(<<"SRC", &b) # pointer
  1158. #{cpp_include(headers)}
  1159. /*top*/
  1160. volatile #{type} conftestval;
  1161. #{MAIN_DOES_NOTHING}
  1162. int t() {return (int)(1-*(conftestval#{member ? ".#{member}" : ""}));}
  1163. SRC
  1164. end
  1165. # Used internally by the what_type? method to determine if +type+ is a scalar
  1166. # pointer.
  1167. def scalar_type?(type, member = nil, headers = nil, &b)
  1168. try_compile(<<"SRC", &b) # pointer
  1169. #{cpp_include(headers)}
  1170. /*top*/
  1171. volatile #{type} conftestval;
  1172. #{MAIN_DOES_NOTHING}
  1173. int t() {return (int)(1-(conftestval#{member ? ".#{member}" : ""}));}
  1174. SRC
  1175. end
  1176. # Used internally by the what_type? method to check if _typeof_ GCC
  1177. # extension is available.
  1178. def have_typeof?
  1179. return $typeof if defined?($typeof)
  1180. $typeof = %w[__typeof__ typeof].find do |t|
  1181. try_compile(<<SRC)
  1182. int rbcv_foo;
  1183. #{t}(rbcv_foo) rbcv_bar;
  1184. SRC
  1185. end
  1186. end
  1187. def what_type?(type, member = nil, headers = nil, &b)
  1188. m = "#{type}"
  1189. var = val = "*rbcv_var_"
  1190. func = "rbcv_func_(void)"
  1191. if member
  1192. m << "." << member
  1193. else
  1194. type, member = type.split('.', 2)
  1195. end
  1196. if member
  1197. val = "(#{var}).#{member}"
  1198. end
  1199. prelude = [cpp_include(headers).split(/^/)]
  1200. prelude << ["typedef #{type} rbcv_typedef_;\n",
  1201. "extern rbcv_typedef_ *#{func};\n",
  1202. "static rbcv_typedef_ #{var};\n",
  1203. ]
  1204. type = "rbcv_typedef_"
  1205. fmt = member && !(typeof = have_typeof?) ? "seems %s" : "%s"
  1206. if typeof
  1207. var = "*rbcv_member_"
  1208. func = "rbcv_mem_func_(void)"
  1209. member = nil
  1210. type = "rbcv_mem_typedef_"
  1211. prelude[-1] << "typedef #{typeof}(#{val}) #{type};\n"
  1212. prelude[-1] << "extern #{type} *#{func};\n"
  1213. prelude[-1] << "static #{type} #{var};\n"
  1214. val = var
  1215. end
  1216. def fmt.%(x)
  1217. x ? super : "unknown"
  1218. end
  1219. checking_for checking_message(m, headers), fmt do
  1220. if scalar_ptr_type?(type, member, prelude, &b)
  1221. if try_static_assert("sizeof(*#{var}) == 1", prelude)
  1222. return "string"
  1223. end
  1224. ptr = "*"
  1225. elsif scalar_type?(type, member, prelude, &b)
  1226. unless member and !typeof or try_static_assert("(#{type})-1 < 0", prelude)
  1227. unsigned = "unsigned"
  1228. end
  1229. ptr = ""
  1230. else
  1231. next
  1232. end
  1233. type = UNIVERSAL_INTS.find do |t|
  1234. pre = prelude
  1235. unless member
  1236. pre += [["static #{unsigned} #{t} #{ptr}#{var};\n",
  1237. "extern #{unsigned} #{t} #{ptr}*#{func};\n"]]
  1238. end
  1239. try_static_assert("sizeof(#{ptr}#{val}) == sizeof(#{unsigned} #{t})", pre)
  1240. end
  1241. type or next
  1242. [unsigned, type, ptr].join(" ").strip
  1243. end
  1244. end
  1245. # This method is used internally by the find_executable method.
  1246. #
  1247. # Internal use only.
  1248. #
  1249. def find_executable0(bin, path = nil)
  1250. executable_file = proc do |name|
  1251. begin
  1252. stat = File.stat(name)
  1253. rescue SystemCallError
  1254. else
  1255. next name if stat.file? and stat.executable?
  1256. end
  1257. end
  1258. exts = config_string('EXECUTABLE_EXTS') {|s| s.split} || config_string('EXEEXT') {|s| [s]}
  1259. if File.expand_path(bin) == bin
  1260. return bin if executable_file.call(bin)
  1261. if exts
  1262. exts.each {|ext| executable_file.call(file = bin + ext) and return file}
  1263. end
  1264. return nil
  1265. end
  1266. if path ||= ENV['PATH']
  1267. path = path.split(File::PATH_SEPARATOR)
  1268. else
  1269. path = %w[/usr/local/bin /usr/ucb /usr/bin /bin]
  1270. end
  1271. file = nil
  1272. path.each do |dir|
  1273. return file if executable_file.call(file = File.join(dir, bin))
  1274. if exts
  1275. exts.each {|ext| executable_file.call(ext = file + ext) and return ext}
  1276. end
  1277. end
  1278. nil
  1279. end
  1280. # :startdoc:
  1281. # Searches for the executable +bin+ on +path+. The default path is your
  1282. # PATH environment variable. If that isn't defined, it will resort to
  1283. # searching /usr/local/bin, /usr/ucb, /usr/bin and /bin.
  1284. #
  1285. # If found, it will return the full path, including the executable name,
  1286. # of where it was found.
  1287. #
  1288. # Note that this method does not actually affect the generated Makefile.
  1289. #
  1290. def find_executable(bin, path = nil)
  1291. checking_for checking_message(bin, path) do
  1292. find_executable0(bin, path)
  1293. end
  1294. end
  1295. # :stopdoc:
  1296. def arg_config(config, default=nil, &block)
  1297. $arg_config << [config, default]
  1298. defaults = []
  1299. if default
  1300. defaults << default
  1301. elsif !block
  1302. defaults << nil
  1303. end
  1304. $configure_args.fetch(config.tr('_', '-'), *defaults, &block)
  1305. end
  1306. # :startdoc:
  1307. # Tests for the presence of a --with-<tt>config</tt> or --without-<tt>config</tt>
  1308. # option. Returns true if the with option is given, false if the without
  1309. # option is given, and the default value otherwise.
  1310. #
  1311. # This can be useful for adding custom definitions, such as debug information.
  1312. #
  1313. # Example:
  1314. #
  1315. # if with_config("debug")
  1316. # $defs.push("-DOSSL_DEBUG") unless $defs.include? "-DOSSL_DEBUG"
  1317. # end
  1318. #
  1319. def with_config(config, default=nil)
  1320. config = config.sub(/^--with[-_]/, '')
  1321. val = arg_config("--with-"+config) do
  1322. if arg_config("--without-"+config)
  1323. false
  1324. elsif block_given?
  1325. yield(config, default)
  1326. else
  1327. break default
  1328. end
  1329. end
  1330. case val
  1331. when "yes"
  1332. true
  1333. when "no"
  1334. false
  1335. else
  1336. val
  1337. end
  1338. end
  1339. # Tests for the presence of an --enable-<tt>config</tt> or
  1340. # --disable-<tt>config</tt> option. Returns true if the enable option is given,
  1341. # false if the disable option is given, and the default value otherwise.
  1342. #
  1343. # This can be useful for adding custom definitions, such as debug information.
  1344. #
  1345. # Example:
  1346. #
  1347. # if enable_config("debug")
  1348. # $defs.push("-DOSSL_DEBUG") unless $defs.include? "-DOSSL_DEBUG"
  1349. # end
  1350. #
  1351. def enable_config(config, default=nil)
  1352. if arg_config("--enable-"+config)
  1353. true
  1354. elsif arg_config("--disable-"+config)
  1355. false
  1356. elsif block_given?
  1357. yield(config, default)
  1358. else
  1359. return default
  1360. end
  1361. end
  1362. # Generates a header file consisting of the various macro definitions generated
  1363. # by other methods such as have_func and have_header. These are then wrapped in
  1364. # a custom #ifndef based on the +header+ file name, which defaults to
  1365. # 'extconf.h'.
  1366. #
  1367. # For example:
  1368. #
  1369. # # extconf.rb
  1370. # require 'mkmf'
  1371. # have_func('realpath')
  1372. # have_header('sys/utime.h')
  1373. # create_header
  1374. # create_makefile('foo')
  1375. #
  1376. # The above script would generate the following extconf.h file:
  1377. #
  1378. # #ifndef EXTCONF_H
  1379. # #define EXTCONF_H
  1380. # #define HAVE_REALPATH 1
  1381. # #define HAVE_SYS_UTIME_H 1
  1382. # #endif
  1383. #
  1384. # Given that the create_header method generates a file based on definitions
  1385. # set earlier in your extconf.rb file, you will probably want to make this
  1386. # one of the last methods you call in your script.
  1387. #
  1388. def create_header(header = "extconf.h")
  1389. message "creating %s\n", header
  1390. sym = header.tr_cpp
  1391. hdr = ["#ifndef #{sym}\n#define #{sym}\n"]
  1392. for line in $defs
  1393. case line
  1394. when /^-D([^=]+)(?:=(.*))?/
  1395. hdr << "#define #$1 #{$2 ? Shellwords.shellwords($2)[0].gsub(/(?=\t+)/, "\\\n") : 1}\n"
  1396. when /^-U(.*)/
  1397. hdr << "#undef #$1\n"
  1398. end
  1399. end
  1400. hdr << "#endif\n"
  1401. hdr = hdr.join
  1402. unless (IO.read(header) == hdr rescue false)
  1403. open(header, "wb") do |hfile|
  1404. hfile.write(hdr)
  1405. end
  1406. end
  1407. $extconf_h = header
  1408. end
  1409. # Sets a +target+ name that the user can then use to configure various 'with'
  1410. # options with on the command line by using that name. For example, if the
  1411. # target is set to "foo", then the user could use the --with-foo-dir command
  1412. # line option.
  1413. #
  1414. # You may pass along additional 'include' or 'lib' defaults via the +idefault+
  1415. # and +ldefault+ parameters, respectively.
  1416. #
  1417. # Note that dir_config only adds to the list of places to search for libraries
  1418. # and include files. It does not link the libraries into your application.
  1419. #
  1420. def dir_config(target, idefault=nil, ldefault=nil)
  1421. if dir = with_config(target + "-dir", (idefault unless ldefault))
  1422. defaults = Array === dir ? dir : dir.split(File::PATH_SEPARATOR)
  1423. idefault = ldefault = nil
  1424. end
  1425. idir = with_config(target + "-include", idefault)
  1426. $arg_config.last[1] ||= "${#{target}-dir}/include"
  1427. ldir = with_config(target + "-lib", ldefault)
  1428. $arg_config.last[1] ||= "${#{target}-dir}/lib"
  1429. idirs = idir ? Array === idir ? idir.dup : idir.split(File::PATH_SEPARATOR) : []
  1430. if defaults
  1431. idirs.concat(defaults.collect {|d| d + "/include"})
  1432. idir = ([idir] + idirs).compact.join(File::PATH_SEPARATOR)
  1433. end
  1434. unless idirs.empty?
  1435. idirs.collect! {|d| "-I" + d}
  1436. idirs -= Shellwords.shellwords($CPPFLAGS)
  1437. unless idirs.empty?
  1438. $CPPFLAGS = (idirs.quote << $CPPFLAGS).join(" ")
  1439. end
  1440. end
  1441. ldirs = ldir ? Array === ldir ? ldir.dup : ldir.split(File::PATH_SEPARATOR) : []
  1442. if defaults
  1443. ldirs.concat(defaults.collect {|d| d + "/lib"})
  1444. ldir = ([ldir] + ldirs).compact.join(File::PATH_SEPARATOR)
  1445. end
  1446. $LIBPATH = ldirs | $LIBPATH
  1447. [idir, ldir]
  1448. end
  1449. # :stopdoc:
  1450. # Handles meta information about installed libraries. Uses your platform's
  1451. # pkg-config program if it has one.
  1452. def pkg_config(pkg)
  1453. if pkgconfig = with_config("#{pkg}-config") and find_executable0(pkgconfig)
  1454. # iff package specific config command is given
  1455. get = proc {|opt| `#{pkgconfig} --#{opt}`.chomp}
  1456. elsif ($PKGCONFIG ||=
  1457. (pkgconfig = with_config("pkg-config", ("pkg-config" unless CROSS_COMPILING))) &&
  1458. find_executable0(pkgconfig) && pkgconfig) and
  1459. system("#{$PKGCONFIG} --exists #{pkg}")
  1460. # default to pkg-config command
  1461. get = proc {|opt| `#{$PKGCONFIG} --#{opt} #{pkg}`.chomp}
  1462. elsif find_executable0(pkgconfig = "#{pkg}-config")
  1463. # default to package specific config command, as a last resort.
  1464. get = proc {|opt| `#{pkgconfig} --#{opt}`.chomp}
  1465. end
  1466. if get
  1467. cflags = get['cflags']
  1468. ldflags = get['libs']
  1469. libs = get['libs-only-l']
  1470. ldflags = (Shellwords.shellwords(ldflags) - Shellwords.shellwords(libs)).quote.join(" ")
  1471. $CFLAGS += " " << cflags
  1472. $LDFLAGS += " " << ldflags
  1473. $libs += " " << libs
  1474. Logging::message "package configuration for %s\n", pkg
  1475. Logging::message "cflags: %s\nldflags: %s\nlibs: %s\n\n",
  1476. cflags, ldflags, libs
  1477. [cflags, ldflags, libs]
  1478. else
  1479. Logging::message "package configuration for %s is not found\n", pkg
  1480. nil
  1481. end
  1482. end
  1483. def with_destdir(dir)
  1484. dir = dir.sub($dest_prefix_pattern, '')
  1485. /\A\$[\(\{]/ =~ dir ? dir : "$(DESTDIR)"+dir
  1486. end
  1487. # Converts forward slashes to backslashes. Aimed at MS Windows.
  1488. #
  1489. # Internal use only.
  1490. #
  1491. def winsep(s)
  1492. s.tr('/', '\\')
  1493. end
  1494. # Converts native path to format acceptable in Makefile
  1495. #
  1496. # Internal use only.
  1497. #
  1498. if !CROSS_COMPILING
  1499. case CONFIG['build_os']
  1500. when 'mingw32'
  1501. def mkintpath(path)
  1502. # mingw uses make from msys and it needs special care
  1503. # converts from C:\some\path to /C/some/path
  1504. path = path.dup
  1505. path.tr!('\\', '/')
  1506. path.sub!(/\A([A-Za-z]):(?=\/)/, '/\1')
  1507. path
  1508. end
  1509. end
  1510. end
  1511. unless defined?(mkintpath)
  1512. def mkintpath(path)
  1513. path
  1514. end
  1515. end
  1516. def configuration(srcdir)
  1517. mk = []
  1518. vpath = $VPATH.dup
  1519. if !CROSS_COMPILING
  1520. case CONFIG['build_os']
  1521. when 'cygwin'
  1522. if CONFIG['target_os'] != 'cygwin'
  1523. vpath = vpath.map {|p| p.sub(/.*/, '$(shell cygpath -u \&)')}
  1524. end
  1525. end
  1526. end
  1527. CONFIG["hdrdir"] ||= $hdrdir
  1528. mk << %{
  1529. SHELL = /bin/sh
  1530. # V=0 quiet, V=1 verbose. other values don't work.
  1531. V = 0
  1532. Q1 = $(V:1=)
  1533. Q = $(Q1:0=@)
  1534. n=$(NULLCMD)
  1535. ECHO1 = $(V:1=@$n)
  1536. ECHO = $(ECHO1:0=@echo)
  1537. #### Start of system configuration section. ####
  1538. #{"top_srcdir = " + $top_srcdir.sub(%r"\A#{Regexp.quote($topdir)}/", "$(topdir)/") if $extmk}
  1539. srcdir = #{srcdir.gsub(/\$\((srcdir)\)|\$\{(srcdir)\}/) {mkintpath(CONFIG[$1||$2])}.quote}
  1540. topdir = #{mkintpath($extmk ? CONFIG["topdir"] : $topdir).quote}
  1541. hdrdir = #{mkintpath(CONFIG["hdrdir"]).quote}
  1542. arch_hdrdir = #{$arch_hdrdir.quote}
  1543. VPATH = #{vpath.join(CONFIG['PATH_SEPARATOR'])}
  1544. }
  1545. if $extmk
  1546. mk << "RUBYLIB =\n""RUBYOPT = -\n"
  1547. end
  1548. if destdir = CONFIG["prefix"][$dest_prefix_pattern, 1]
  1549. mk << "\nDESTDIR = #{destdir}\n"
  1550. end
  1551. CONFIG.each do |key, var|
  1552. next unless /prefix$/ =~ key
  1553. mk << "#{key} = #{with_destdir(var)}\n"
  1554. end
  1555. CONFIG.each do |key, var|
  1556. next if /^abs_/ =~ key
  1557. next if /^(?:src|top|hdr)dir$/ =~ key
  1558. next unless /dir$/ =~ key
  1559. mk << "#{key} = #{with_destdir(var)}\n"
  1560. end
  1561. if !$extmk and !$configure_args.has_key?('--ruby') and
  1562. sep = config_string('BUILD_FILE_SEPARATOR')
  1563. sep = ":/=#{sep}"
  1564. else
  1565. sep = ""
  1566. end
  1567. possible_command = (proc {|s| s if /top_srcdir/ !~ s} unless $extmk)
  1568. extconf_h = $extconf_h ? "-DRUBY_EXTCONF_H=\\\"$(RUBY_EXTCONF_H)\\\" " : $defs.join(" ") << " "
  1569. mk << %{
  1570. NULLCMD = #{CONFIG['NULLCMD']}
  1571. CC = #{CONFIG['CC']}
  1572. CXX = #{CONFIG['CXX']}
  1573. LIBRUBY = #{CONFIG['LIBRUBY']}
  1574. LIBRUBY_A = #{CONFIG['LIBRUBY_A']}
  1575. LIBRUBYARG_SHARED = #$LIBRUBYARG_SHARED
  1576. LIBRUBYARG_STATIC = #$LIBRUBYARG_STATIC
  1577. OUTFLAG = #{OUTFLAG}
  1578. COUTFLAG = #{COUTFLAG}
  1579. RUBY_EXTCONF_H = #{$extconf_h}
  1580. cflags = #{CONFIG['cflags']}
  1581. optflags = #{CONFIG['optflags']}
  1582. debugflags = #{CONFIG['debugflags']}
  1583. warnflags = #{$warnflags}
  1584. CFLAGS = #{$static ? '' : CONFIG['CCDLFLAGS']} #$CFLAGS #$ARCH_FLAG
  1585. INCFLAGS = -I. #$INCFLAGS
  1586. DEFS = #{CONFIG['DEFS']}
  1587. CPPFLAGS = #{extconf_h}#{$CPPFLAGS}
  1588. CXXFLAGS = $(CFLAGS) #{CONFIG['CXXFLAGS']}
  1589. ldflags = #{$LDFLAGS}
  1590. dldflags = #{$DLDFLAGS}
  1591. ARCH_FLAG = #{$ARCH_FLAG}
  1592. DLDFLAGS = $(ldflags) $(dldflags)
  1593. LDSHARED = #{CONFIG['LDSHARED']}
  1594. LDSHAREDXX = #{config_string('LDSHAREDXX') || '$(LDSHARED)'}
  1595. AR = #{CONFIG['AR']}
  1596. EXEEXT = #{CONFIG['EXEEXT']}
  1597. RUBY_BASE_NAME = #{CONFIG['RUBY_BASE_NAME']}
  1598. RUBY_INSTALL_NAME = #{CONFIG['RUBY_INSTALL_NAME']}
  1599. RUBY_SO_NAME = #{CONFIG['RUBY_SO_NAME']}
  1600. arch = #{CONFIG['arch']}
  1601. sitearch = #{CONFIG['sitearch']}
  1602. ruby_version = #{RbConfig::CONFIG['ruby_version']}
  1603. ruby = #{$ruby}
  1604. RUBY = $(ruby#{sep})
  1605. RM = #{config_string('RM', &possible_command) || '$(RUBY) -run -e rm -- -f'}
  1606. RM_RF = #{'$(RUBY) -run -e rm -- -rf'}
  1607. RMDIRS = #{config_string('RMDIRS', &possible_command) || '$(RUBY) -run -e rmdir -- -p'}
  1608. MAKEDIRS = #{config_string('MAKEDIRS', &possible_command) || '@$(RUBY) -run -e mkdir -- -p'}
  1609. INSTALL = #{config_string('INSTALL', &possible_command) || '@$(RUBY) -run -e install -- -vp'}
  1610. INSTALL_PROG = #{config_string('INSTALL_PROG') || '$(INSTALL) -m 0755'}
  1611. INSTALL_DATA = #{config_string('INSTALL_DATA') || '$(INSTALL) -m 0644'}
  1612. COPY = #{config_string('CP', &possible_command) || '@$(RUBY) -run -e cp -- -v'}
  1613. #### End of system configuration section. ####
  1614. preload = #{defined?($preload) && $preload ? $preload.join(' ') : ''}
  1615. }
  1616. if $nmake == ?b

Large files files are truncated, but you can click here to view the full file