PageRenderTime 34ms CodeModel.GetById 8ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/ruby/1.8/mkmf.rb

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

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