probe.py 12 KB

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