PageRenderTime 64ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/mkmf.rb

https://github.com/ahwuyeah/ruby
Ruby | 2646 lines | 2085 code | 158 blank | 403 comment | 156 complexity | 6dec4b913c4267d6ed09b6503255ce44 MD5 | raw file
Possible License(s): BSD-3-Clause, AGPL-3.0, Unlicense, GPL-2.0

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

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

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