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

/lib/ruby/1.9/mkmf.rb

https://bitbucket.org/nicksieger/jruby
Ruby | 1886 lines | 1491 code | 101 blank | 294 comment | 121 complexity | 776b2677184b731e988099bf3cdb4437 MD5 | raw file
Possible License(s): GPL-3.0, JSON

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

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

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