PageRenderTime 41ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/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
  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}\n"]
  1542. for line in $defs
  1543. case line
  1544. when /^-D([^=]+)(?:=(.*))?/
  1545. hdr << "#define #$1 #{$2 ? Shellwords.shellwords($2)[0].gsub(/(?=\t+)/, "\\\n") : 1}\n"
  1546. when /^-U(.*)/
  1547. hdr << "#undef #$1\n"
  1548. end
  1549. end
  1550. hdr << "#endif\n"
  1551. hdr = hdr.join("")
  1552. log_src(hdr, "#{header} is")
  1553. unless (IO.read(header) == hdr rescue false)
  1554. open(header, "wb") do |hfile|
  1555. hfile.write(hdr)
  1556. end
  1557. end
  1558. $extconf_h = header
  1559. end
  1560. # call-seq:
  1561. # dir_config(target)
  1562. # dir_config(target, prefix)
  1563. # dir_config(target, idefault, ldefault)
  1564. #
  1565. # Sets a +target+ name that the user can then use to configure
  1566. # various "with" options with on the command line by using that
  1567. # name. For example, if the target is set to "foo", then the user
  1568. # could use the <code>--with-foo-dir=prefix</code>,
  1569. # <code>--with-foo-include=dir</code> and
  1570. # <code>--with-foo-lib=dir</code> command line options to tell where
  1571. # to search for header/library files.
  1572. #
  1573. # You may pass along additional parameters to specify default
  1574. # values. If one is given it is taken as default +prefix+, and if
  1575. # two are given they are taken as "include" and "lib" defaults in
  1576. # that order.
  1577. #
  1578. # In any case, the return value will be an array of determined
  1579. # "include" and "lib" directories, either of which can be nil if no
  1580. # corresponding command line option is given when no default value
  1581. # is specified.
  1582. #
  1583. # Note that dir_config only adds to the list of places to search for
  1584. # libraries and include files. It does not link the libraries into your
  1585. # application.
  1586. #
  1587. def dir_config(target, idefault=nil, ldefault=nil)
  1588. if dir = with_config(target + "-dir", (idefault unless ldefault))
  1589. defaults = Array === dir ? dir : dir.split(File::PATH_SEPARATOR)
  1590. idefault = ldefault = nil
  1591. end
  1592. idir = with_config(target + "-include", idefault)
  1593. $arg_config.last[1] ||= "${#{target}-dir}/include"
  1594. ldir = with_config(target + "-lib", ldefault)
  1595. $arg_config.last[1] ||= "${#{target}-dir}/#{_libdir_basename}"
  1596. idirs = idir ? Array === idir ? idir.dup : idir.split(File::PATH_SEPARATOR) : []
  1597. if defaults
  1598. idirs.concat(defaults.collect {|d| d + "/include"})
  1599. idir = ([idir] + idirs).compact.join(File::PATH_SEPARATOR)
  1600. end
  1601. unless idirs.empty?
  1602. idirs.collect! {|d| "-I" + d}
  1603. idirs -= Shellwords.shellwords($CPPFLAGS)
  1604. unless idirs.empty?
  1605. $CPPFLAGS = (idirs.quote << $CPPFLAGS).join(" ")
  1606. end
  1607. end
  1608. ldirs = ldir ? Array === ldir ? ldir.dup : ldir.split(File::PATH_SEPARATOR) : []
  1609. if defaults
  1610. ldirs.concat(defaults.collect {|d| "#{d}/#{_libdir_basename}"})
  1611. ldir = ([ldir] + ldirs).compact.join(File::PATH_SEPARATOR)
  1612. end
  1613. $LIBPATH = ldirs | $LIBPATH
  1614. [idir, ldir]
  1615. end
  1616. # Returns compile/link information about an installed library in a
  1617. # tuple of <code>[cflags, ldflags, libs]</code>, by using the
  1618. # command found first in the following commands:
  1619. #
  1620. # 1. If <code>--with-{pkg}-config={command}</code> is given via
  1621. # command line option: <code>{command} {option}</code>
  1622. #
  1623. # 2. <code>{pkg}-config {option}</code>
  1624. #
  1625. # 3. <code>pkg-config {option} {pkg}</code>
  1626. #
  1627. # Where {option} is, for instance, <code>--cflags</code>.
  1628. #
  1629. # The values obtained are appended to +$CFLAGS+, +$LDFLAGS+ and
  1630. # +$libs+.
  1631. #
  1632. # If an <code>option</code> argument is given, the config command is
  1633. # invoked with the option and a stripped output string is returned
  1634. # without modifying any of the global values mentioned above.
  1635. def pkg_config(pkg, option=nil)
  1636. if pkgconfig = with_config("#{pkg}-config") and find_executable0(pkgconfig)
  1637. # iff package specific config command is given
  1638. get = proc {|opt| `#{pkgconfig} --#{opt}`.strip}
  1639. elsif ($PKGCONFIG ||=
  1640. (pkgconfig = with_config("pkg-config", ("pkg-config" unless CROSS_COMPILING))) &&
  1641. find_executable0(pkgconfig) && pkgconfig) and
  1642. system("#{$PKGCONFIG} --exists #{pkg}")
  1643. # default to pkg-config command
  1644. get = proc {|opt| `#{$PKGCONFIG} --#{opt} #{pkg}`.strip}
  1645. elsif find_executable0(pkgconfig = "#{pkg}-config")
  1646. # default to package specific config command, as a last resort.
  1647. get = proc {|opt| `#{pkgconfig} --#{opt}`.strip}
  1648. end
  1649. orig_ldflags = $LDFLAGS
  1650. if get and option
  1651. get[option]
  1652. elsif get and try_ldflags(ldflags = get['libs'])
  1653. cflags = get['cflags']
  1654. libs = get['libs-only-l']
  1655. ldflags = (Shellwords.shellwords(ldflags) - Shellwords.shellwords(libs)).quote.join(" ")
  1656. $CFLAGS += " " << cflags
  1657. $LDFLAGS = [orig_ldflags, ldflags].join(' ')
  1658. $libs += " " << libs
  1659. Logging::message "package configuration for %s\n", pkg
  1660. Logging::message "cflags: %s\nldflags: %s\nlibs: %s\n\n",
  1661. cflags, ldflags, libs
  1662. [cflags, ldflags, libs]
  1663. else
  1664. Logging::message "package configuration for %s is not found\n", pkg
  1665. nil
  1666. end
  1667. end
  1668. # :stopdoc:
  1669. def with_destdir(dir)
  1670. dir = dir.sub($dest_prefix_pattern, '')
  1671. /\A\$[\(\{]/ =~ dir ? dir : "$(DESTDIR)"+dir
  1672. end
  1673. # Converts forward slashes to backslashes. Aimed at MS Windows.
  1674. #
  1675. # Internal use only.
  1676. #
  1677. def winsep(s)
  1678. s.tr('/', '\\')
  1679. end
  1680. # Converts native path to format acceptable in Makefile
  1681. #
  1682. # Internal use only.
  1683. #
  1684. if !CROSS_COMPILING
  1685. case CONFIG['build_os']
  1686. when 'mingw32'
  1687. def mkintpath(path)
  1688. # mingw uses make from msys and it needs special care
  1689. # converts from C:\some\path to /C/some/path
  1690. path = path.dup
  1691. path.tr!('\\', '/')
  1692. path.sub!(/\A([A-Za-z]):(?=\/)/, '/\1')
  1693. path
  1694. end
  1695. when 'cygwin'
  1696. if CONFIG['target_os'] != 'cygwin'
  1697. def mkintpath(path)
  1698. IO.popen(["cygpath", "-u", path], &:read).chomp
  1699. end
  1700. end
  1701. end
  1702. end
  1703. unless method_defined?(:mkintpath)
  1704. def mkintpath(path)
  1705. path
  1706. end
  1707. end
  1708. def configuration(srcdir)
  1709. mk = []
  1710. vpath = $VPATH.dup
  1711. CONFIG["hdrdir"] ||= $hdrdir
  1712. mk << %{
  1713. SHELL = /bin/sh
  1714. # V=0 quiet, V=1 verbose. other values don't work.
  1715. V = 0
  1716. Q1 = $(V:1=)
  1717. Q = $(Q1:0=@)
  1718. ECHO1 = $(V:1=@#{CONFIG['NULLCMD']})
  1719. ECHO = $(ECHO1:0=@echo)
  1720. NULLCMD = #{CONFIG['NULLCMD']}
  1721. #### Start of system configuration section. ####
  1722. #{"top_srcdir = " + $top_srcdir.sub(%r"\A#{Regexp.quote($topdir)}/", "$(topdir)/") if $extmk}
  1723. srcdir = #{srcdir.gsub(/\$\((srcdir)\)|\$\{(srcdir)\}/) {mkintpath(CONFIG[$1||$2]).unspace}}
  1724. topdir = #{mkintpath(topdir = $extmk ? CONFIG["topdir"] : $topdir).unspace}
  1725. hdrdir = #{(hdrdir = CONFIG["hdrdir"]) == topdir ? "$(topdir)" : mkintpath(hdrdir).unspace}
  1726. arch_hdrdir = #{$arch_hdrdir.quote}
  1727. PATH_SEPARATOR = #{CONFIG['PATH_SEPARATOR']}
  1728. VPATH = #{vpath.join(CONFIG['PATH_SEPARATOR'])}
  1729. }
  1730. if $extmk
  1731. mk << "RUBYLIB =\n""RUBYOPT = -\n"
  1732. end
  1733. prefix = mkintpath(CONFIG["prefix"])
  1734. if destdir = prefix[$dest_prefix_pattern, 1]
  1735. mk << "\nDESTDIR = #{destdir}\n"
  1736. prefix = prefix[destdir.size..-1]
  1737. end
  1738. mk << "prefix = #{with_destdir(prefix).unspace}\n"
  1739. CONFIG.each do |key, var|
  1740. mk << "#{key} = #{with_destdir(mkintpath(var)).unspace}\n" if /.prefix$/ =~ key
  1741. end
  1742. CONFIG.each do |key, var|
  1743. next if /^abs_/ =~ key
  1744. next if /^(?:src|top|hdr)dir$/ =~ key
  1745. next unless /dir$/ =~ key
  1746. mk << "#{key} = #{with_destdir(var)}\n"
  1747. end
  1748. if !$extmk and !$configure_args.has_key?('--ruby') and
  1749. sep = config_string('BUILD_FILE_SEPARATOR')
  1750. sep = ":/=#{sep}"
  1751. else
  1752. sep = ""
  1753. end
  1754. possible_command = (proc {|s| s if /top_srcdir/ !~ s} unless $extmk)
  1755. extconf_h = $extconf_h ? "-DRUBY_EXTCONF_H=\\\"$(RUBY_EXTCONF_H)\\\" " : $defs.join(" ") << " "
  1756. headers = %w[
  1757. $(hdrdir)/ruby.h
  1758. $(hdrdir)/ruby/ruby.h
  1759. $(hdrdir)/ruby/defines.h
  1760. $(hdrdir)/ruby/missing.h
  1761. $(hdrdir)/ruby/intern.h
  1762. $(hdrdir)/ruby/st.h
  1763. $(hdrdir)/ruby/subst.h
  1764. ]
  1765. if RULE_SUBST
  1766. headers.each {|h| h.sub!(/.*/, &RULE_SUBST.method(:%))}
  1767. end
  1768. headers << $config_h
  1769. headers << '$(RUBY_EXTCONF_H)' if $extconf_h
  1770. mk << %{
  1771. CC = #{CONFIG['CC']}
  1772. CXX = #{CONFIG['CXX']}
  1773. LIBRUBY = #{CONFIG['LIBRUBY']}
  1774. LIBRUBY_A = #{CONFIG['LIBRUBY_A']}
  1775. LIBRUBYARG_SHARED = #$LIBRUBYARG_SHARED
  1776. LIBRUBYARG_STATIC = #$LIBRUBYARG_STATIC
  1777. empty =
  1778. OUTFLAG = #{OUTFLAG}$(empty)
  1779. COUTFLAG = #{COUTFLAG}$(empty)
  1780. RUBY_EXTCONF_H = #{$extconf_h}
  1781. cflags = #{CONFIG['cflags']}
  1782. optflags = #{CONFIG['optflags']}
  1783. debugflags = #{CONFIG['debugflags']}
  1784. warnflags = #{$warnflags}
  1785. CCDLFLAGS = #{$static ? '' : CONFIG['CCDLFLAGS']}
  1786. CFLAGS = $(CCDLFLAGS) #$CFLAGS $(ARCH_FLAG)
  1787. INCFLAGS = -I. #$INCFLAGS
  1788. DEFS = #{CONFIG['DEFS']}
  1789. CPPFLAGS = #{extconf_h}#{$CPPFLAGS}
  1790. CXXFLAGS = $(CCDLFLAGS) #$CXXFLAGS $(ARCH_FLAG)
  1791. ldflags = #{$LDFLAGS}
  1792. dldflags = #{$DLDFLAGS} #{CONFIG['EXTDLDFLAGS']}
  1793. ARCH_FLAG = #{$ARCH_FLAG}
  1794. DLDFLAGS = $(ldflags) $(dldflags) $(ARCH_FLAG)
  1795. LDSHARED = #{CONFIG['LDSHARED']}
  1796. LDSHAREDXX = #{config_string('LDSHAREDXX') || '$(LDSHARED)'}
  1797. AR = #{CONFIG['AR']}
  1798. EXEEXT = #{CONFIG['EXEEXT']}
  1799. }
  1800. CONFIG.each do |key, val|
  1801. mk << "#{key} = #{val}\n" if /^RUBY.*NAME/ =~ key
  1802. end
  1803. mk << %{
  1804. arch = #{CONFIG['arch']}
  1805. sitearch = #{CONFIG['sitearch']}
  1806. ruby_version = #{RbConfig::CONFIG['ruby_version']}
  1807. ruby = #{$ruby.sub(%r[\A#{Regexp.quote(RbConfig::CONFIG['bindir'])}(?=/|\z)]) {'$(bindir)'}}
  1808. RUBY = $(ruby#{sep})
  1809. ruby_headers = #{headers.join(' ')}
  1810. RM = #{config_string('RM', &possible_command) || '$(RUBY) -run -e rm -- -f'}
  1811. RM_RF = #{'$(RUBY) -run -e rm -- -rf'}
  1812. RMDIRS = #{config_string('RMDIRS', &possible_command) || '$(RUBY) -run -e rmdir -- -p'}
  1813. MAKEDIRS = #{config_string('MAKEDIRS', &possible_command) || '@$(RUBY) -run -e mkdir -- -p'}
  1814. INSTALL = #{config_string('INSTALL', &possible_command) || '@$(RUBY) -run -e install -- -vp'}
  1815. INSTALL_PROG = #{config_string('INSTALL_PROG') || '$(INSTALL) -m 0755'}
  1816. INSTALL_DATA = #{config_string('INSTALL_DATA') || '$(INSTALL) -m 0644'}
  1817. COPY = #{config_string('CP', &possible_command) || '@$(RUBY) -run -e cp -- -v'}
  1818. TOUCH = exit >
  1819. #### End of system configuration section. ####
  1820. preload = #{defined?($preload) && $preload ? $preload.join(' ') : ''}
  1821. }
  1822. if $nmake == ?b
  1823. mk.each do |x|
  1824. x.gsub!(/^(MAKEDIRS|INSTALL_(?:PROG|DATA))+\s*=.*\n/) do
  1825. "!ifndef " + $1 + "\n" +
  1826. $& +
  1827. "!endif\n"
  1828. end
  1829. end
  1830. end
  1831. mk
  1832. end
  1833. def timestamp_file(name, target_prefix = nil)
  1834. if target_prefix
  1835. pat = []
  1836. install_dirs.each do |n, d|
  1837. pat << n if /\$\(target_prefix\)\z/ =~ d
  1838. end
  1839. name = name.gsub(/\$\((#{pat.join("|")})\)/) {$&+target_prefix}
  1840. end
  1841. name = name.gsub(/(\$[({]|[})])|(\/+)|[^-.\w]+/) {$1 ? "" : $2 ? ".-." : "_"}
  1842. "$(TIMESTAMP_DIR)/.#{name}.time"
  1843. end
  1844. # :startdoc:
  1845. # creates a stub Makefile.
  1846. #
  1847. def dummy_makefile(srcdir)
  1848. configuration(srcdir) << <<RULES << CLEANINGS
  1849. CLEANFILES = #{$cleanfiles.join(' ')}
  1850. DISTCLEANFILES = #{$distcleanfiles.join(' ')}
  1851. all install static install-so install-rb: Makefile
  1852. .PHONY: all install static install-so install-rb
  1853. .PHONY: clean clean-so clean-static clean-rb
  1854. RULES
  1855. end
  1856. def each_compile_rules # :nodoc:
  1857. vpath_splat = /\$\(\*VPATH\*\)/
  1858. COMPILE_RULES.each do |rule|
  1859. if vpath_splat =~ rule
  1860. $VPATH.each do |path|
  1861. yield rule.sub(vpath_splat) {path}
  1862. end
  1863. else
  1864. yield rule
  1865. end
  1866. end
  1867. end
  1868. # Processes the data contents of the "depend" file. Each line of this file
  1869. # is expected to be a file name.
  1870. #
  1871. # Returns the output of findings, in Makefile format.
  1872. #
  1873. def depend_rules(depend)
  1874. suffixes = []
  1875. depout = []
  1876. cont = implicit = nil
  1877. impconv = proc do
  1878. each_compile_rules {|rule| depout << (rule % implicit[0]) << implicit[1]}
  1879. implicit = nil
  1880. end
  1881. ruleconv = proc do |line|
  1882. if implicit
  1883. if /\A\t/ =~ line
  1884. implicit[1] << line
  1885. next
  1886. else
  1887. impconv[]
  1888. end
  1889. end
  1890. if m = /\A\.(\w+)\.(\w+)(?:\s*:)/.match(line)
  1891. suffixes << m[1] << m[2]
  1892. implicit = [[m[1], m[2]], [m.post_match]]
  1893. next
  1894. elsif RULE_SUBST and /\A(?!\s*\w+\s*=)[$\w][^#]*:/ =~ line
  1895. line.gsub!(%r"(\s)(?!\.)([^$(){}+=:\s\/\\,]+)(?=\s|\z)") {$1 + RULE_SUBST % $2}
  1896. end
  1897. depout << line
  1898. end
  1899. depend.each_line do |line|
  1900. line.gsub!(/\.o\b/, ".#{$OBJEXT}")
  1901. line.gsub!(/\{\$\(VPATH\)\}/, "") unless $nmake
  1902. line.gsub!(/\$\((?:hdr|top)dir\)\/config.h/, $config_h)
  1903. line.gsub!(%r"\$\(hdrdir\)/(?!ruby(?![^:;/\s]))(?=[-\w]+\.h)", '\&ruby/')
  1904. if $nmake && /\A\s*\$\(RM|COPY\)/ =~ line
  1905. line.gsub!(%r"[-\w\./]{2,}"){$&.tr("/", "\\")}
  1906. line.gsub!(/(\$\((?!RM|COPY)[^:)]+)(?=\))/, '\1:/=\\')
  1907. end
  1908. if /(?:^|[^\\])(?:\\\\)*\\$/ =~ line
  1909. (cont ||= []) << line
  1910. next
  1911. elsif cont
  1912. line = (cont << line).join
  1913. cont = nil
  1914. end
  1915. ruleconv.call(line)
  1916. end
  1917. if cont
  1918. ruleconv.call(cont.join)
  1919. elsif implicit
  1920. impconv.call
  1921. end
  1922. unless suffixes.empty?
  1923. depout.unshift(".SUFFIXES: ." + suffixes.uniq.join(" .") + "\n\n")
  1924. end
  1925. depout.unshift("$(OBJS): $(RUBY_EXTCONF_H)\n\n") if $extconf_h
  1926. depout.flatten!
  1927. depout
  1928. end
  1929. # Generates the Makefile for your extension, passing along any options and
  1930. # preprocessor constants that you may have generated through other methods.
  1931. #
  1932. # The +target+ name should correspond the name of the global function name
  1933. # defined within your C extension, minus the +Init_+. For example, if your
  1934. # C extension is defined as +Init_foo+, then your target would simply be
  1935. # "foo".
  1936. #
  1937. # If any "/" characters are present in the target name, only the last name
  1938. # is interpreted as the target name, and the rest are considered toplevel
  1939. # directory names, and the generated Makefile will be altered accordingly to
  1940. # follow that directory structure.
  1941. #
  1942. # For example, if you pass "test/foo" as a target name, your extension will
  1943. # be installed under the "test" directory. This means that in order to
  1944. # load the file within a Ruby program later, that directory structure will
  1945. # have to be followed, e.g. <code>require 'test/foo'</code>.
  1946. #
  1947. # The +srcprefix+ should be used when your source files are not in the same
  1948. # directory as your build script. This will not only eliminate the need for
  1949. # you to manually copy the source files into the same directory as your
  1950. # build script, but it also sets the proper +target_prefix+ in the generated
  1951. # Makefile.
  1952. #
  1953. # Setting the +target_prefix+ will, in turn, install the generated binary in
  1954. # a directory under your <code>RbConfig::CONFIG['sitearchdir']</code> that
  1955. # mimics your local filesystem when you run <code>make install</code>.
  1956. #
  1957. # For example, given the following file tree:
  1958. #
  1959. # ext/
  1960. # extconf.rb
  1961. # test/
  1962. # foo.c
  1963. #
  1964. # And given the following code:
  1965. #
  1966. # create_makefile('test/foo', 'test')
  1967. #
  1968. # That will set the +target_prefix+ in the generated Makefile to "test".
  1969. # That, in turn, will create the following file tree when installed via the
  1970. # <code>make install</code> command:
  1971. #
  1972. # /path/to/ruby/sitearchdir/test/foo.so
  1973. #
  1974. # It is recommended that you use this approach to generate your makefiles,
  1975. # instead of copying files around manually, because some third party
  1976. # libraries may depend on the +target_prefix+ being set properly.
  1977. #
  1978. # The +srcprefix+ argument can be used to override the default source
  1979. # directory, i.e. the current directory. It is included as part of the
  1980. # +VPATH+ and added to the list of +INCFLAGS+.
  1981. #
  1982. def create_makefile(target, srcprefix = nil)
  1983. $target = target
  1984. libpath = $LIBPATH|$DEFLIBPATH
  1985. message "creating Makefile\n"
  1986. MakeMakefile.rm_f "#{CONFTEST}*"
  1987. if CONFIG["DLEXT"] == $OBJEXT
  1988. for lib in libs = $libs.split
  1989. lib.sub!(/-l(.*)/, %%"lib\\1.#{$LIBEXT}"%)
  1990. end
  1991. $defs.push(format("-DEXTLIB='%s'", libs.join(",")))
  1992. end
  1993. if target.include?('/')
  1994. target_prefix, target = File.split(target)
  1995. target_prefix[0,0] = '/'
  1996. else
  1997. target_prefix = ""
  1998. end
  1999. srcprefix ||= "$(srcdir)/#{srcprefix}".chomp('/')
  2000. RbConfig.expand(srcdir = srcprefix.dup)
  2001. ext = ".#{$OBJEXT}"
  2002. orig_srcs = Dir[File.join(srcdir, "*.{#{SRC_EXT.join(%q{,})}}")]
  2003. if not $objs
  2004. srcs = $srcs || orig_srcs
  2005. objs = srcs.inject(Hash.new {[]}) {|h, f| h[File.basename(f, ".*") << ext] <<= f; h}
  2006. $objs = objs.keys
  2007. unless objs.delete_if {|b, f| f.size == 1}.empty?
  2008. dups = objs.sort.map {|b, f|
  2009. "#{b[/.*\./]}{#{f.collect {|n| n[/([^.]+)\z/]}.join(',')}}"
  2010. }
  2011. abort "source files duplication - #{dups.join(", ")}"
  2012. end
  2013. else
  2014. $objs.collect! {|o| File.basename(o, ".*") << ext} unless $OBJEXT == "o"
  2015. srcs = $srcs || $objs.collect {|o| o.chomp(ext) << ".c"}
  2016. end
  2017. $srcs = srcs
  2018. hdrs = Dir[File.join(srcdir, "*.{#{HDR_EXT.join(%q{,})}}")]
  2019. target = nil if $objs.empty?
  2020. if target and EXPORT_PREFIX
  2021. if File.exist?(File.join(srcdir, target + '.def'))
  2022. deffile = "$(srcdir)/$(TARGET).def"
  2023. unless EXPORT_PREFIX.empty?
  2024. makedef = %{-pe "$_.sub!(/^(?=\\w)/,'#{EXPORT_PREFIX}') unless 1../^EXPORTS$/i"}
  2025. end
  2026. else
  2027. makedef = %{-e "puts 'EXPORTS', '$(TARGET_ENTRY)'"}
  2028. end
  2029. if makedef
  2030. $cleanfiles << '$(DEFFILE)'
  2031. origdef = deffile
  2032. deffile = "$(TARGET)-$(arch).def"
  2033. end
  2034. end
  2035. origdef ||= ''
  2036. if $extout and $INSTALLFILES
  2037. $cleanfiles.concat($INSTALLFILES.collect {|files, dir|File.join(dir, files.sub(/\A\.\//, ''))})
  2038. $distcleandirs.concat($INSTALLFILES.collect {|files, dir| dir})
  2039. end
  2040. if $extmk and $static
  2041. $defs << "-DRUBY_EXPORT=1"
  2042. end
  2043. if $extmk and not $extconf_h
  2044. create_header
  2045. end
  2046. libpath = libpathflag(libpath)
  2047. dllib = target ? "$(TARGET).#{CONFIG['DLEXT']}" : ""
  2048. staticlib = target ? "$(TARGET).#$LIBEXT" : ""
  2049. mfile = open("Makefile", "wb")
  2050. conf = configuration(srcprefix)
  2051. conf = yield(conf) if block_given?
  2052. mfile.puts(conf)
  2053. mfile.print "
  2054. libpath = #{($LIBPATH|$DEFLIBPATH).join(" ")}
  2055. LIBPATH = #{libpath}
  2056. DEFFILE = #{deffile}
  2057. CLEANFILES = #{$cleanfiles.join(' ')}
  2058. DISTCLEANFILES = #{$distcleanfiles.join(' ')}
  2059. DISTCLEANDIRS = #{$distcleandirs.join(' ')}
  2060. extout = #{$extout && $extout.quote}
  2061. extout_prefix = #{$extout_prefix}
  2062. target_prefix = #{target_prefix}
  2063. LOCAL_LIBS = #{$LOCAL_LIBS}
  2064. LIBS = #{$LIBRUBYARG} #{$libs} #{$LIBS}
  2065. ORIG_SRCS = #{orig_srcs.collect(&File.method(:basename)).join(' ')}
  2066. SRCS = $(ORIG_SRCS) #{(srcs - orig_srcs).collect(&File.method(:basename)).join(' ')}
  2067. OBJS = #{$objs.join(" ")}
  2068. HDRS = #{hdrs.map{|h| '$(srcdir)/' + File.basename(h)}.join(' ')}
  2069. TARGET = #{target}
  2070. TARGET_NAME = #{target && target[/\A\w+/]}
  2071. TARGET_ENTRY = #{EXPORT_PREFIX || ''}Init_$(TARGET_NAME)
  2072. DLLIB = #{dllib}
  2073. EXTSTATIC = #{$static || ""}
  2074. STATIC_LIB = #{staticlib unless $static.nil?}
  2075. #{!$extout && defined?($installed_list) ? "INSTALLED_LIST = #{$installed_list}\n" : ""}
  2076. TIMESTAMP_DIR = #{$extout ? '$(extout)/.timestamp' : '.'}
  2077. " #"
  2078. # TODO: fixme
  2079. install_dirs.each {|d| mfile.print("%-14s= %s\n" % d) if /^[[:upper:]]/ =~ d[0]}
  2080. n = ($extout ? '$(RUBYARCHDIR)/' : '') + '$(TARGET)'
  2081. mfile.print "
  2082. TARGET_SO = #{($extout ? '$(RUBYARCHDIR)/' : '')}$(DLLIB)
  2083. CLEANLIBS = #{n}.#{CONFIG['DLEXT']} #{config_string('cleanlibs') {|t| t.gsub(/\$\*/) {n}}}
  2084. CLEANOBJS = *.#{$OBJEXT} #{config_string('cleanobjs') {|t| t.gsub(/\$\*/, "$(TARGET)#{deffile ? '-$(arch)': ''}")} if target} *.bak
  2085. all: #{$extout ? "install" : target ? "$(DLLIB)" : "Makefile"}
  2086. static: $(STATIC_LIB)#{$extout ? " install-rb" : ""}
  2087. .PHONY: all install static install-so install-rb
  2088. .PHONY: clean clean-so clean-static clean-rb
  2089. "
  2090. mfile.print CLEANINGS
  2091. fsep = config_string('BUILD_FILE_SEPARATOR') {|s| s unless s == "/"}
  2092. if fsep
  2093. sep = ":/=#{fsep}"
  2094. fseprepl = proc {|s|
  2095. s = s.gsub("/", fsep)
  2096. s = s.gsub(/(\$\(\w+)(\))/) {$1+sep+$2}
  2097. s = s.gsub(/(\$\{\w+)(\})/) {$1+sep+$2}
  2098. }
  2099. rsep = ":#{fsep}=/"
  2100. else
  2101. fseprepl = proc {|s| s}
  2102. sep = ""
  2103. rsep = ""
  2104. end
  2105. dirs = []
  2106. mfile.print "install: install-so install-rb\n\n"
  2107. sodir = (dir = "$(RUBYARCHDIR)").dup
  2108. mfile.print("install-so: ")
  2109. if target
  2110. f = "$(DLLIB)"
  2111. dest = "#{dir}/#{f}"
  2112. if $extout
  2113. mfile.puts dest
  2114. mfile.print "clean-so::\n"
  2115. mfile.print "\t-$(Q)$(RM) #{fseprepl[dest]}\n"
  2116. mfile.print "\t-$(Q)$(RMDIRS) #{fseprepl[dir]}#{$ignore_error}\n"
  2117. else
  2118. mfile.print "#{f} #{timestamp_file(dir, target_prefix)}\n"
  2119. mfile.print "\t$(INSTALL_PROG) #{fseprepl[f]} #{dir}\n"
  2120. if defined?($installed_list)
  2121. mfile.print "\t@echo #{dir}/#{File.basename(f)}>>$(INSTALLED_LIST)\n"
  2122. end
  2123. end
  2124. mfile.print "clean-static::\n"
  2125. mfile.print "\t-$(Q)$(RM) $(STATIC_LIB)\n"
  2126. else
  2127. mfile.puts "Makefile"
  2128. end
  2129. mfile.print("install-rb: pre-install-rb install-rb-default\n")
  2130. mfile.print("install-rb-default: pre-install-rb-default\n")
  2131. mfile.print("pre-install-rb: Makefile\n")
  2132. mfile.print("pre-install-rb-default: Makefile\n")
  2133. for sfx, i in [["-default", [["lib/**/*.rb", "$(RUBYLIBDIR)", "lib"]]], ["", $INSTALLFILES]]
  2134. files = install_files(mfile, i, nil, srcprefix) or next
  2135. for dir, *files in files
  2136. unless dirs.include?(dir)
  2137. dirs << dir
  2138. mfile.print "pre-install-rb#{sfx}: #{timestamp_file(dir, target_prefix)}\n"
  2139. end
  2140. for f in files
  2141. dest = "#{dir}/#{File.basename(f)}"
  2142. mfile.print("install-rb#{sfx}: #{dest}\n")
  2143. mfile.print("#{dest}: #{f} #{timestamp_file(dir, target_prefix)}\n")
  2144. mfile.print("\t$(Q) $(#{$extout ? 'COPY' : 'INSTALL_DATA'}) #{f} $(@D#{sep})\n")
  2145. if defined?($installed_list) and !$extout
  2146. mfile.print("\t@echo #{dest}>>$(INSTALLED_LIST)\n")
  2147. end
  2148. if $extout
  2149. mfile.print("clean-rb#{sfx}::\n")
  2150. mfile.print("\t-$(Q)$(RM) #{fseprepl[dest]}\n")
  2151. end
  2152. end
  2153. end
  2154. mfile.print "pre-install-rb#{sfx}:\n"
  2155. if files.empty?
  2156. mfile.print("\t@$(NULLCMD)\n")
  2157. else
  2158. mfile.print("\t$(ECHO) installing#{sfx.sub(/^-/, " ")} #{target} libraries\n")
  2159. end
  2160. if $extout
  2161. dirs.uniq!
  2162. unless dirs.empty?
  2163. mfile.print("clean-rb#{sfx}::\n")
  2164. for dir in dirs.sort_by {|d| -d.count('/')}
  2165. mfile.print("\t-$(Q)$(RMDIRS) #{fseprepl[dir]}#{$ignore_error}\n")
  2166. end
  2167. end
  2168. end
  2169. end
  2170. dirs.unshift(sodir) if target and !dirs.include?(sodir)
  2171. dirs.each do |d|
  2172. t = timestamp_file(d, target_prefix)
  2173. mfile.print "#{t}:\n\t$(Q) $(MAKEDIRS) $(@D) #{d}\n\t$(Q) $(TOUCH) $@\n"
  2174. end
  2175. mfile.print <<-SITEINSTALL
  2176. site-install: site-install-so site-install-rb
  2177. site-install-so: install-so
  2178. site-install-rb: install-rb
  2179. SITEINSTALL
  2180. return unless target
  2181. mfile.puts SRC_EXT.collect {|e| ".path.#{e} = $(VPATH)"} if $nmake == ?b
  2182. mfile.print ".SUFFIXES: .#{SRC_EXT.join(' .')} .#{$OBJEXT}\n"
  2183. mfile.print "\n"
  2184. compile_command = "\n\t$(ECHO) compiling $(<#{rsep})\n\t$(Q) %s\n\n"
  2185. CXX_EXT.each do |e|
  2186. each_compile_rules do |rule|
  2187. mfile.printf(rule, e, $OBJEXT)
  2188. mfile.printf(compile_command, COMPILE_CXX)
  2189. end
  2190. end
  2191. C_EXT.each do |e|
  2192. each_compile_rules do |rule|
  2193. mfile.printf(rule, e, $OBJEXT)
  2194. mfile.printf(compile_command, COMPILE_C)
  2195. end
  2196. end
  2197. mfile.print "$(RUBYARCHDIR)/" if $extout
  2198. mfile.print "$(DLLIB): "
  2199. mfile.print "$(DEFFILE) " if makedef
  2200. mfile.print "$(OBJS) Makefile"
  2201. mfile.print " #{timestamp_file('$(RUBYARCHDIR)', target_prefix)}" if $extout
  2202. mfile.print "\n"
  2203. mfile.print "\t$(ECHO) linking shared-object #{target_prefix.sub(/\A\/(.*)/, '\1/')}$(DLLIB)\n"
  2204. mfile.print "\t-$(Q)$(RM) $(@#{sep})\n"
  2205. link_so = LINK_SO.gsub(/^/, "\t$(Q) ")
  2206. if srcs.any?(&%r"\.(?:#{CXX_EXT.join('|')})\z".method(:===))
  2207. link_so = link_so.sub(/\bLDSHARED\b/, '\&XX')
  2208. end
  2209. mfile.print link_so, "\n\n"
  2210. unless $static.nil?
  2211. mfile.print "$(STATIC_LIB): $(OBJS)\n\t-$(Q)$(RM) $(@#{sep})\n\t"
  2212. mfile.print "$(ECHO) linking static-library $(@#{rsep})\n\t$(Q) "
  2213. mfile.print "$(AR) #{config_string('ARFLAGS') || 'cru '}$@ $(OBJS)"
  2214. config_string('RANLIB') do |ranlib|
  2215. mfile.print "\n\t-$(Q)#{ranlib} $(@) 2> /dev/null || true"
  2216. end
  2217. end
  2218. mfile.print "\n\n"
  2219. if makedef
  2220. mfile.print "$(DEFFILE): #{origdef}\n"
  2221. mfile.print "\t$(ECHO) generating $(@#{rsep})\n"
  2222. mfile.print "\t$(Q) $(RUBY) #{makedef} #{origdef} > $@\n\n"
  2223. end
  2224. depend = File.join(srcdir, "depend")
  2225. if File.exist?(depend)
  2226. mfile.print("###\n", *depend_rules(File.read(depend)))
  2227. else
  2228. mfile.print "$(OBJS): $(HDRS) $(ruby_headers)\n"
  2229. end
  2230. $makefile_created = true
  2231. ensure
  2232. mfile.close if mfile
  2233. end
  2234. # :stopdoc:
  2235. def init_mkmf(config = CONFIG, rbconfig = RbConfig::CONFIG)
  2236. $makefile_created = false
  2237. $arg_config = []
  2238. $enable_shared = config['ENABLE_SHARED'] == 'yes'
  2239. $defs = []
  2240. $extconf_h = nil
  2241. if $warnflags = CONFIG['warnflags'] and CONFIG['GCC'] == 'yes'
  2242. # turn warnings into errors only for bundled extensions.
  2243. config['warnflags'] = $warnflags.gsub(/(\A|\s)-Werror[-=]/, '\1-W')
  2244. RbConfig.expand(rbconfig['warnflags'] = config['warnflags'].dup)
  2245. config.each do |key, val|
  2246. RbConfig.expand(rbconfig[key] = val.dup) if /warnflags/ =~ val
  2247. end
  2248. $warnflags = config['warnflags'] unless $extmk
  2249. end
  2250. $CFLAGS = with_config("cflags", arg_config("CFLAGS", config["CFLAGS"])).dup
  2251. $CXXFLAGS = (with_config("cxxflags", arg_config("CXXFLAGS", config["CXXFLAGS"]))||'').dup
  2252. $ARCH_FLAG = with_config("arch_flag", arg_config("ARCH_FLAG", config["ARCH_FLAG"])).dup
  2253. $CPPFLAGS = with_config("cppflags", arg_config("CPPFLAGS", config["CPPFLAGS"])).dup
  2254. $LDFLAGS = with_config("ldflags", arg_config("LDFLAGS", config["LDFLAGS"])).dup
  2255. $INCFLAGS = "-I$(arch_hdrdir)"
  2256. $INCFLAGS << " -I$(hdrdir)/ruby/backward" unless $extmk
  2257. $INCFLAGS << " -I$(hdrdir) -I$(srcdir)"
  2258. $DLDFLAGS = with_config("dldflags", arg_config("DLDFLAGS", config["DLDFLAGS"])).dup
  2259. $LIBEXT = config['LIBEXT'].dup
  2260. $OBJEXT = config["OBJEXT"].dup
  2261. $EXEEXT = config["EXEEXT"].dup
  2262. $LIBS = "#{config['LIBS']} #{config['DLDLIBS']}"
  2263. $LIBRUBYARG = ""
  2264. $LIBRUBYARG_STATIC = config['LIBRUBYARG_STATIC']
  2265. $LIBRUBYARG_SHARED = config['LIBRUBYARG_SHARED']
  2266. $DEFLIBPATH = [$extmk ? "$(topdir)" : "$(#{config["libdirname"] || "libdir"})"]
  2267. $DEFLIBPATH.unshift(".")
  2268. $LIBPATH = []
  2269. $INSTALLFILES = []
  2270. $NONINSTALLFILES = [/~\z/, /\A#.*#\z/, /\A\.#/, /\.bak\z/i, /\.orig\z/, /\.rej\z/, /\.l[ao]\z/, /\.o\z/]
  2271. $VPATH = %w[$(srcdir) $(arch_hdrdir)/ruby $(hdrdir)/ruby]
  2272. $objs = nil
  2273. $srcs = nil
  2274. $libs = ""
  2275. if $enable_shared or RbConfig.expand(config["LIBRUBY"].dup) != RbConfig.expand(config["LIBRUBY_A"].dup)
  2276. $LIBRUBYARG = config['LIBRUBYARG']
  2277. end
  2278. $LOCAL_LIBS = ""
  2279. $cleanfiles = config_string('CLEANFILES') {|s| Shellwords.shellwords(s)} || []
  2280. $cleanfiles << "mkmf.log"
  2281. $distcleanfiles = config_string('DISTCLEANFILES') {|s| Shellwords.shellwords(s)} || []
  2282. $distcleandirs = config_string('DISTCLEANDIRS') {|s| Shellwords.shellwords(s)} || []
  2283. $extout ||= nil
  2284. $extout_prefix ||= nil
  2285. $arg_config.clear
  2286. dir_config("opt")
  2287. end
  2288. FailedMessage = <<MESSAGE
  2289. Could not create Makefile due to some reason, probably lack of necessary
  2290. libraries and/or headers. Check the mkmf.log file for more details. You may
  2291. need configuration options.
  2292. Provided configuration options:
  2293. MESSAGE
  2294. # Returns whether or not the Makefile was successfully generated. If not,
  2295. # the script will abort with an error message.
  2296. #
  2297. # Internal use only.
  2298. #
  2299. def mkmf_failed(path)
  2300. unless $makefile_created or File.exist?("Makefile")
  2301. opts = $arg_config.collect {|t, n| "\t#{t}#{n ? "=#{n}" : ""}\n"}
  2302. abort "*** #{path} failed ***\n" + FailedMessage + opts.join
  2303. end
  2304. end
  2305. private
  2306. def _libdir_basename
  2307. @libdir_basename ||= config_string("libdir") {|name| name[/\A\$\(exec_prefix\)\/(.*)/, 1]} || "lib"
  2308. end
  2309. def MAIN_DOES_NOTHING(*refs)
  2310. src = MAIN_DOES_NOTHING
  2311. unless refs.empty?
  2312. src = src.sub(/\{/) do
  2313. $& +
  2314. "\n if (argc > 1000000) {\n" +
  2315. refs.map {|n|" printf(\"%p\", &#{n});\n"}.join("") +
  2316. " }\n"
  2317. end
  2318. end
  2319. src
  2320. end
  2321. extend self
  2322. init_mkmf
  2323. $make = with_config("make-prog", ENV["MAKE"] || "make")
  2324. make, = Shellwords.shellwords($make)
  2325. $nmake = nil
  2326. case
  2327. when $mswin
  2328. $nmake = ?m if /nmake/i =~ make
  2329. when $bccwin
  2330. $nmake = ?b if /Borland/i =~ `#{make} -h`
  2331. end
  2332. $ignore_error = $nmake ? '' : ' 2> /dev/null || true'
  2333. RbConfig::CONFIG["srcdir"] = CONFIG["srcdir"] =
  2334. $srcdir = arg_config("--srcdir", File.dirname($0))
  2335. $configure_args["--topsrcdir"] ||= $srcdir
  2336. if $curdir = arg_config("--curdir")
  2337. RbConfig.expand(curdir = $curdir.dup)
  2338. else
  2339. curdir = $curdir = "."
  2340. end
  2341. unless File.expand_path(RbConfig::CONFIG["topdir"]) == File.expand_path(curdir)
  2342. CONFIG["topdir"] = $curdir
  2343. RbConfig::CONFIG["topdir"] = curdir
  2344. end
  2345. $configure_args["--topdir"] ||= $curdir
  2346. $ruby = arg_config("--ruby", File.join(RbConfig::CONFIG["bindir"], CONFIG["ruby_install_name"]))
  2347. RbConfig.expand(CONFIG["RUBY_SO_NAME"])
  2348. # :startdoc:
  2349. split = Shellwords.method(:shellwords).to_proc
  2350. EXPORT_PREFIX = config_string('EXPORT_PREFIX') {|s| s.strip}
  2351. hdr = ['#include "ruby.h"' "\n"]
  2352. config_string('COMMON_MACROS') do |s|
  2353. Shellwords.shellwords(s).each do |w|
  2354. w, v = w.split(/=/, 2)
  2355. hdr << "#ifndef #{w}"
  2356. hdr << "#define #{[w, v].compact.join(" ")}"
  2357. hdr << "#endif /* #{w} */"
  2358. end
  2359. end
  2360. config_string('COMMON_HEADERS') do |s|
  2361. Shellwords.shellwords(s).each {|w| hdr << "#include <#{w}>"}
  2362. end
  2363. ##
  2364. # Common headers for Ruby C extensions
  2365. COMMON_HEADERS = hdr.join("\n")
  2366. ##
  2367. # Common libraries for Ruby C extensions
  2368. COMMON_LIBS = config_string('COMMON_LIBS', &split) || []
  2369. ##
  2370. # make compile rules
  2371. COMPILE_RULES = config_string('COMPILE_RULES', &split) || %w[.%s.%s:]
  2372. RULE_SUBST = config_string('RULE_SUBST')
  2373. ##
  2374. # Command which will compile C files in the generated Makefile
  2375. COMPILE_C = config_string('COMPILE_C') || '$(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -c $<'
  2376. ##
  2377. # Command which will compile C++ files in the generated Makefile
  2378. COMPILE_CXX = config_string('COMPILE_CXX') || '$(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $<'
  2379. ##
  2380. # Command which will compile a program in order to test linking a library
  2381. TRY_LINK = config_string('TRY_LINK') ||
  2382. "$(CC) #{OUTFLAG}#{CONFTEST}#{$EXEEXT} $(INCFLAGS) $(CPPFLAGS) " \
  2383. "$(CFLAGS) $(src) $(LIBPATH) $(LDFLAGS) $(ARCH_FLAG) $(LOCAL_LIBS) $(LIBS)"
  2384. ##
  2385. # Command which will link a shared library
  2386. LINK_SO = (config_string('LINK_SO') || "").sub(/^$/) do
  2387. if CONFIG["DLEXT"] == $OBJEXT
  2388. "ld $(DLDFLAGS) -r -o $@ $(OBJS)\n"
  2389. else
  2390. "$(LDSHARED) #{OUTFLAG}$@ $(OBJS) " \
  2391. "$(LIBPATH) $(DLDFLAGS) $(LOCAL_LIBS) $(LIBS)"
  2392. end
  2393. end
  2394. ##
  2395. # Argument which will add a library path to the linker
  2396. LIBPATHFLAG = config_string('LIBPATHFLAG') || ' -L%s'
  2397. RPATHFLAG = config_string('RPATHFLAG') || ''
  2398. ##
  2399. # Argument which will add a library to the linker
  2400. LIBARG = config_string('LIBARG') || '-l%s'
  2401. ##
  2402. # A C main function which does no work
  2403. MAIN_DOES_NOTHING = config_string('MAIN_DOES_NOTHING') || "int main(int argc, char **argv)\n{\n return 0;\n}"
  2404. UNIVERSAL_INTS = config_string('UNIVERSAL_INTS') {|s| Shellwords.shellwords(s)} ||
  2405. %w[int short long long\ long]
  2406. sep = config_string('BUILD_FILE_SEPARATOR') {|s| ":/=#{s}" if s != "/"} || ""
  2407. ##
  2408. # Makefile rules that will clean the extension build directory
  2409. CLEANINGS = "
  2410. clean-static::
  2411. clean-rb-default::
  2412. clean-rb::
  2413. clean-so::
  2414. clean: clean-so clean-static clean-rb-default clean-rb
  2415. \t\t-$(Q)$(RM) $(CLEANLIBS#{sep}) $(CLEANOBJS#{sep}) $(CLEANFILES#{sep}) .*.time
  2416. distclean-rb-default::
  2417. distclean-rb::
  2418. distclean-so::
  2419. distclean-static::
  2420. distclean: clean distclean-so distclean-static distclean-rb-default distclean-rb
  2421. \t\t-$(Q)$(RM) Makefile $(RUBY_EXTCONF_H) #{CONFTEST}.* mkmf.log
  2422. \t\t-$(Q)$(RM) core ruby$(EXEEXT) *~ $(DISTCLEANFILES#{sep})
  2423. \t\t-$(Q)$(RMDIRS) $(DISTCLEANDIRS#{sep})#{$ignore_error}
  2424. realclean: distclean
  2425. "
  2426. end
  2427. include MakeMakefile
  2428. if not $extmk and /\A(extconf|makefile).rb\z/ =~ File.basename($0)
  2429. END {mkmf_failed($0)}
  2430. end