PageRenderTime 82ms CodeModel.GetById 21ms RepoModel.GetById 20ms app.codeStats 0ms

/Languages/Ruby/StdLib/ruby/1.9.1/mkmf.rb

http://github.com/IronLanguages/main
Ruby | 2079 lines | 1709 code | 110 blank | 260 comment | 138 complexity | 4983656e0cc2fb1351311348a6f352df MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception

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

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

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