PageRenderTime 167ms CodeModel.GetById 20ms RepoModel.GetById 4ms app.codeStats 1ms

/lib/mkmf.rb

https://github.com/thepelkus/ruby
Ruby | 2441 lines | 1989 code | 124 blank | 328 comment | 145 complexity | 5e57a5ede84d035f016173f27c375b74 MD5 | raw file
Possible License(s): 0BSD, Unlicense, GPL-2.0, BSD-3-Clause, AGPL-3.0

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

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

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