PageRenderTime 60ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/jruby-1.1.6RC1/lib/ruby/1.8/mkmf.rb

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