probe.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. # Replacement for autoconf.
  2. # Performs some test compiles, to check for headers and functions.
  3. # It does not execute anything it builds, making it friendly for cross compiles.
  4. from compilers import CompileCommand, LinkCommand
  5. from components import iterComponents, requiredLibrariesFor
  6. from configurations import getConfiguration
  7. from executils import captureStdout, shjoin
  8. from itertools import chain
  9. from libraries import librariesByName
  10. from makeutils import extractMakeVariables, parseBool
  11. from outpututils import rewriteIfChanged
  12. from packages import getPackage
  13. from systemfuncs import systemFunctions
  14. from systemfuncs2code import iterSystemFuncsHeader
  15. from os import environ, makedirs, remove
  16. from os.path import isdir, isfile, pathsep
  17. from shlex import split as shsplit
  18. import sys
  19. def resolve(log, expr):
  20. if expr is None:
  21. return ''
  22. # TODO: Since for example "sdl-config" is used in more than one
  23. # CFLAGS definition, it will be executed multiple times.
  24. try:
  25. return normalizeWhitespace(evaluateBackticks(log, expr))
  26. except IOError:
  27. # Executing a lib-config script is expected to fail if the
  28. # script is not installed.
  29. # TODO: Report this explicitly in the probe results table.
  30. return ''
  31. def writeFile(path, lines):
  32. out = open(path, 'w')
  33. try:
  34. for line in lines:
  35. print >> out, line
  36. finally:
  37. out.close()
  38. def tryCompile(log, compileCommand, sourcePath, lines):
  39. '''Write the program defined by "lines" to a text file specified
  40. by "path" and try to compile it.
  41. Returns True iff compilation succeeded.
  42. '''
  43. assert sourcePath.endswith('.cc')
  44. objectPath = sourcePath[ : -3] + '.o'
  45. writeFile(sourcePath, lines)
  46. try:
  47. return compileCommand.compile(log, sourcePath, objectPath)
  48. finally:
  49. remove(sourcePath)
  50. if isfile(objectPath):
  51. remove(objectPath)
  52. def checkCompiler(log, compileCommand, outDir):
  53. '''Checks whether compiler can compile anything at all.
  54. Returns True iff the compiler works.
  55. '''
  56. def hello():
  57. # The most famous program.
  58. yield '#include <iostream>'
  59. yield 'int main(int argc, char** argv) {'
  60. yield ' std::cout << "Hello World!" << std::endl;'
  61. yield ' return 0;'
  62. yield '}'
  63. return tryCompile(log, compileCommand, outDir + '/hello.cc', hello())
  64. def checkFunc(log, compileCommand, outDir, checkName, funcName, headers):
  65. '''Checks whether the given function is declared by the given headers.
  66. Returns True iff the function is declared.
  67. '''
  68. def takeFuncAddr():
  69. # Try to include the necessary headers and get the function address.
  70. for header in headers:
  71. yield '#include %s' % header
  72. yield 'void (*f)() = reinterpret_cast<void (*)()>(%s);' % funcName
  73. return tryCompile(
  74. log, compileCommand, outDir + '/' + checkName + '.cc', takeFuncAddr()
  75. )
  76. def evaluateBackticks(log, expression):
  77. parts = []
  78. index = 0
  79. while True:
  80. start = expression.find('`', index)
  81. if start == -1:
  82. parts.append(expression[index : ])
  83. break
  84. end = expression.find('`', start + 1)
  85. if end == -1:
  86. raise ValueError('Unmatched backtick: %s' % expression)
  87. parts.append(expression[index : start])
  88. command = expression[start + 1 : end].strip()
  89. result = captureStdout(log, command)
  90. if result is None:
  91. raise IOError('Backtick evaluation failed; see log')
  92. parts.append(result)
  93. index = end + 1
  94. return ''.join(parts)
  95. def normalizeWhitespace(expression):
  96. return shjoin(shsplit(expression))
  97. class TargetSystem(object):
  98. def __init__(
  99. self, log, logPath, compileCommandStr, outDir, platform, distroRoot,
  100. configuration
  101. ):
  102. '''Create empty log and result files.
  103. '''
  104. self.log = log
  105. self.logPath = logPath
  106. self.compileCommandStr = compileCommandStr
  107. self.outDir = outDir
  108. self.platform = platform
  109. self.distroRoot = distroRoot
  110. self.configuration = configuration
  111. self.outMakePath = outDir + '/probed_defs.mk'
  112. self.outHeaderPath = outDir + '/systemfuncs.hh'
  113. self.outVars = {}
  114. self.functionResults = {}
  115. self.typeTraitsResult = None
  116. self.libraries = sorted(requiredLibrariesFor(
  117. configuration.iterDesiredComponents()
  118. ))
  119. def checkAll(self):
  120. '''Run all probes.
  121. '''
  122. self.hello()
  123. for func in systemFunctions:
  124. self.checkFunc(func)
  125. for library in self.libraries:
  126. self.checkLibrary(library)
  127. def writeAll(self):
  128. def iterVars():
  129. yield '# Automatically generated by build system.'
  130. yield '# Non-empty value means found, empty means not found.'
  131. for library in self.libraries:
  132. for name in (
  133. 'HAVE_%s_H' % library,
  134. 'HAVE_%s_LIB' % library,
  135. '%s_CFLAGS' % library,
  136. '%s_LDFLAGS' % library,
  137. ):
  138. yield '%s:=%s' % (name, self.outVars[name])
  139. rewriteIfChanged(self.outMakePath, iterVars())
  140. rewriteIfChanged(
  141. self.outHeaderPath,
  142. iterSystemFuncsHeader(self.functionResults),
  143. )
  144. def printResults(self):
  145. for line in iterProbeResults(
  146. self.outVars, self.configuration, self.logPath
  147. ):
  148. print line
  149. def everything(self):
  150. self.checkAll()
  151. self.writeAll()
  152. self.printResults()
  153. def hello(self):
  154. '''Check compiler with the most famous program.
  155. '''
  156. compileCommand = CompileCommand.fromLine(self.compileCommandStr, '')
  157. ok = checkCompiler(self.log, compileCommand, self.outDir)
  158. print >> self.log, 'Compiler %s: %s' % (
  159. 'works' if ok else 'broken',
  160. compileCommand
  161. )
  162. self.outVars['COMPILER'] = str(ok).lower()
  163. def checkFunc(self, func):
  164. '''Probe for function.
  165. '''
  166. compileCommand = CompileCommand.fromLine(self.compileCommandStr, '')
  167. ok = checkFunc(
  168. self.log, compileCommand, self.outDir,
  169. func.name, func.getFunctionName(), func.iterHeaders(self.platform)
  170. )
  171. print >> self.log, '%s function: %s' % (
  172. 'Found' if ok else 'Missing',
  173. func.getFunctionName()
  174. )
  175. self.functionResults[func.getMakeName()] = ok
  176. def checkLibrary(self, makeName):
  177. library = librariesByName[makeName]
  178. cflags = resolve(
  179. self.log,
  180. library.getCompileFlags(
  181. self.platform, self.configuration.linkStatic(), self.distroRoot
  182. )
  183. )
  184. ldflags = resolve(
  185. self.log,
  186. library.getLinkFlags(
  187. self.platform, self.configuration.linkStatic(), self.distroRoot
  188. )
  189. )
  190. if self.platform == 'android':
  191. # This works around SDL 1.2's trickery with main().
  192. # If also weakens the probe considerably, since missing symbols
  193. # are no longer considered errors.
  194. # Remove this when we migrate to SDL2.
  195. ldflags += ' -shared'
  196. compileCommand = CompileCommand.fromLine(self.compileCommandStr, cflags)
  197. linkCommand = LinkCommand.fromLine(self.compileCommandStr, ldflags)
  198. self.outVars['%s_CFLAGS' % makeName] = cflags
  199. self.outVars['%s_LDFLAGS' % makeName] = ldflags
  200. sourcePath = self.outDir + '/' + makeName + '.cc'
  201. objectPath = self.outDir + '/' + makeName + '.o'
  202. binaryPath = self.outDir + '/' + makeName + '.bin'
  203. if self.platform == 'android':
  204. binaryPath = self.outDir + '/' + makeName + '.so'
  205. funcName = library.function
  206. headers = library.getHeaders(self.platform)
  207. def takeFuncAddr():
  208. # Try to include the necessary headers and get the function address.
  209. for header in headers:
  210. yield '#include %s' % header
  211. yield 'void (*f)() = reinterpret_cast<void (*)()>(%s);' % funcName
  212. yield 'int main(int argc, char** argv) {'
  213. yield ' return 0;'
  214. yield '}'
  215. writeFile(sourcePath, takeFuncAddr())
  216. try:
  217. compileOK = compileCommand.compile(self.log, sourcePath, objectPath)
  218. print >> self.log, '%s: %s header' % (
  219. makeName,
  220. 'Found' if compileOK else 'Missing'
  221. )
  222. if compileOK:
  223. linkOK = linkCommand.link(self.log, [ objectPath ], binaryPath)
  224. print >> self.log, '%s: %s lib' % (
  225. makeName,
  226. 'Found' if linkOK else 'Missing'
  227. )
  228. else:
  229. linkOK = False
  230. print >> self.log, (
  231. '%s: Cannot test linking because compile failed'
  232. % makeName
  233. )
  234. finally:
  235. remove(sourcePath)
  236. if isfile(objectPath):
  237. remove(objectPath)
  238. if isfile(binaryPath):
  239. remove(binaryPath)
  240. self.outVars['HAVE_%s_H' % makeName] = 'true' if compileOK else ''
  241. self.outVars['HAVE_%s_LIB' % makeName] = 'true' if linkOK else ''
  242. if linkOK:
  243. versionGet = library.getVersion(
  244. self.platform, self.configuration.linkStatic(), self.distroRoot
  245. )
  246. if callable(versionGet):
  247. version = versionGet(compileCommand, self.log)
  248. else:
  249. version = resolve(self.log, versionGet)
  250. if version is None:
  251. version = 'error'
  252. self.outVars['VERSION_%s' % makeName] = version
  253. def iterProbeResults(probeVars, configuration, logPath):
  254. '''Present probe results, so user can decide whether to start the build,
  255. or to change system configuration and rerun "configure".
  256. '''
  257. desiredComponents = set(configuration.iterDesiredComponents())
  258. requiredComponents = set(configuration.iterRequiredComponents())
  259. buildableComponents = set(configuration.iterBuildableComponents(probeVars))
  260. packages = sorted(
  261. ( getPackage(makeName)
  262. for makeName in requiredLibrariesFor(desiredComponents)
  263. ),
  264. key = lambda package: package.niceName.lower()
  265. )
  266. customVars = extractMakeVariables('build/custom.mk')
  267. yield ''
  268. if not parseBool(probeVars['COMPILER']):
  269. yield 'No working C++ compiler was found.'
  270. yield "Please install a C++ compiler, such as GCC's g++."
  271. yield 'If you have a C++ compiler installed and openMSX did not ' \
  272. 'detect it, please set the environment variable CXX to the name ' \
  273. 'of your C++ compiler.'
  274. yield 'After you have corrected the situation, rerun "configure".'
  275. yield ''
  276. else:
  277. # Compute how wide the first column should be.
  278. def iterNiceNames():
  279. for package in packages:
  280. yield package.niceName
  281. for component in iterComponents():
  282. yield component.niceName
  283. maxLen = max(len(niceName) for niceName in iterNiceNames())
  284. formatStr = ' %-' + str(maxLen + 3) + 's %s'
  285. yield 'Found libraries:'
  286. for package in packages:
  287. makeName = package.getMakeName()
  288. if probeVars['HAVE_%s_LIB' % makeName]:
  289. found = 'version %s' % probeVars['VERSION_%s' % makeName]
  290. elif probeVars['HAVE_%s_H' % makeName]:
  291. # Dependency resolution of a typical distro will not allow
  292. # this situation. Most likely we got the link flags wrong.
  293. found = 'headers found, link test failed'
  294. else:
  295. found = 'no'
  296. yield formatStr % (package.niceName + ':', found)
  297. yield ''
  298. yield 'Components overview:'
  299. for component in iterComponents():
  300. if component in desiredComponents:
  301. status = 'yes' if component in buildableComponents else 'no'
  302. else:
  303. status = 'disabled'
  304. yield formatStr % (component.niceName + ':', status)
  305. yield ''
  306. yield 'Customisable options:'
  307. yield formatStr % ('Install to', customVars['INSTALL_BASE'])
  308. yield ' (you can edit these in build/custom.mk)'
  309. yield ''
  310. if buildableComponents == desiredComponents:
  311. yield 'All required and optional components can be built.'
  312. elif requiredComponents.issubset(buildableComponents):
  313. yield 'If you are satisfied with the probe results, ' \
  314. 'run "make" to start the build.'
  315. yield 'Otherwise, install some libraries and headers ' \
  316. 'and rerun "configure".'
  317. else:
  318. yield 'Please install missing libraries and headers ' \
  319. 'and rerun "configure".'
  320. yield ''
  321. yield 'If the detected libraries differ from what you think ' \
  322. 'is installed on this system, please check the log file: %s' \
  323. % logPath
  324. yield ''
  325. def main(compileCommandStr, outDir, platform, linkMode, thirdPartyInstall):
  326. if not isdir(outDir):
  327. makedirs(outDir)
  328. logPath = outDir + '/probe.log'
  329. log = open(logPath, 'w')
  330. print 'Probing target system...'
  331. print >> log, 'Probing system:'
  332. try:
  333. distroRoot = thirdPartyInstall or None
  334. if distroRoot is None:
  335. if platform == 'darwin':
  336. for searchPath in environ.get('PATH', '').split(pathsep):
  337. if searchPath == '/opt/local/bin':
  338. print 'Using libraries from MacPorts.'
  339. distroRoot = '/opt/local'
  340. break
  341. elif searchPath == '/sw/bin':
  342. print 'Using libraries from Fink.'
  343. distroRoot = '/sw'
  344. break
  345. else:
  346. distroRoot = '/usr/local'
  347. elif platform.endswith('bsd') or platform == 'dragonfly':
  348. distroRoot = environ.get('LOCALBASE', '/usr/local')
  349. print 'Using libraries from ports directory %s.' % distroRoot
  350. elif platform == 'pandora':
  351. distroRoot = environ.get('LIBTOOL_SYSROOT_PATH')
  352. if distroRoot is not None:
  353. distroRoot += '/usr'
  354. print 'Using libraries from sysroot directory %s.' \
  355. % distroRoot
  356. configuration = getConfiguration(linkMode)
  357. TargetSystem(
  358. log, logPath, compileCommandStr, outDir, platform, distroRoot,
  359. configuration
  360. ).everything()
  361. finally:
  362. log.close()
  363. if __name__ == '__main__':
  364. if len(sys.argv) == 6:
  365. try:
  366. main(*sys.argv[1 : ])
  367. except ValueError, ve:
  368. print >> sys.stderr, ve
  369. sys.exit(2)
  370. else:
  371. print >> sys.stderr, (
  372. 'Usage: python probe.py '
  373. 'COMPILE OUTDIR OPENMSX_TARGET_OS LINK_MODE 3RDPARTY_INSTALL_DIR'
  374. )
  375. sys.exit(2)