coredata.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. # Copyright 2012-2017 The Meson development team
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. # Unless required by applicable law or agreed to in writing, software
  7. # distributed under the License is distributed on an "AS IS" BASIS,
  8. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. # See the License for the specific language governing permissions and
  10. # limitations under the License.
  11. import pickle, os, uuid
  12. from pathlib import PurePath
  13. from collections import OrderedDict
  14. from .mesonlib import MesonException, commonpath
  15. from .mesonlib import default_libdir, default_libexecdir, default_prefix
  16. import ast
  17. version = '0.42.0.dev1'
  18. backendlist = ['ninja', 'vs', 'vs2010', 'vs2015', 'vs2017', 'xcode']
  19. class UserOption:
  20. def __init__(self, name, description, choices):
  21. super().__init__()
  22. self.name = name
  23. self.choices = choices
  24. self.description = description
  25. def parse_string(self, valuestring):
  26. return valuestring
  27. # Check that the input is a valid value and return the
  28. # "cleaned" or "native" version. For example the Boolean
  29. # option could take the string "true" and return True.
  30. def validate_value(self, value):
  31. raise RuntimeError('Derived option class did not override validate_value.')
  32. class UserStringOption(UserOption):
  33. def __init__(self, name, description, value, choices=None):
  34. super().__init__(name, description, choices)
  35. self.set_value(value)
  36. def validate(self, value):
  37. if not isinstance(value, str):
  38. raise MesonException('Value "%s" for string option "%s" is not a string.' % (str(value), self.name))
  39. def set_value(self, newvalue):
  40. self.validate(newvalue)
  41. self.value = newvalue
  42. def validate_value(self, value):
  43. self.validate(value)
  44. return value
  45. class UserBooleanOption(UserOption):
  46. def __init__(self, name, description, value):
  47. super().__init__(name, description, [True, False])
  48. self.set_value(value)
  49. def tobool(self, thing):
  50. if isinstance(thing, bool):
  51. return thing
  52. if thing.lower() == 'true':
  53. return True
  54. if thing.lower() == 'false':
  55. return False
  56. raise MesonException('Value %s is not boolean (true or false).' % thing)
  57. def set_value(self, newvalue):
  58. self.value = self.tobool(newvalue)
  59. def parse_string(self, valuestring):
  60. if valuestring == 'false':
  61. return False
  62. if valuestring == 'true':
  63. return True
  64. raise MesonException('Value "%s" for boolean option "%s" is not a boolean.' % (valuestring, self.name))
  65. def __bool__(self):
  66. return self.value
  67. def validate_value(self, value):
  68. return self.tobool(value)
  69. class UserIntegerOption(UserOption):
  70. def __init__(self, name, description, min_value, max_value, value):
  71. super().__init__(name, description, [True, False])
  72. self.min_value = min_value
  73. self.max_value = max_value
  74. self.set_value(value)
  75. def set_value(self, newvalue):
  76. if isinstance(newvalue, str):
  77. newvalue = self.toint(newvalue)
  78. if not isinstance(newvalue, int):
  79. raise MesonException('New value for integer option is not an integer.')
  80. if self.min_value is not None and newvalue < self.min_value:
  81. raise MesonException('New value %d is less than minimum value %d.' % (newvalue, self.min_value))
  82. if self.max_value is not None and newvalue > self.max_value:
  83. raise MesonException('New value %d is more than maximum value %d.' % (newvalue, self.max_value))
  84. self.value = newvalue
  85. def toint(self, valuestring):
  86. try:
  87. return int(valuestring)
  88. except:
  89. raise MesonException('Value string "%s" is not convertable to an integer.' % valuestring)
  90. def parse_string(self, valuestring):
  91. return self.toint(valuestring)
  92. def validate_value(self, value):
  93. return self.toint(value)
  94. class UserComboOption(UserOption):
  95. def __init__(self, name, description, choices, value):
  96. super().__init__(name, description, choices)
  97. if not isinstance(self.choices, list):
  98. raise MesonException('Combo choices must be an array.')
  99. for i in self.choices:
  100. if not isinstance(i, str):
  101. raise MesonException('Combo choice elements must be strings.')
  102. self.set_value(value)
  103. def set_value(self, newvalue):
  104. if newvalue not in self.choices:
  105. optionsstring = ', '.join(['"%s"' % (item,) for item in self.choices])
  106. raise MesonException('Value "%s" for combo option "%s" is not one of the choices. Possible choices are: %s.' % (newvalue, self.name, optionsstring))
  107. self.value = newvalue
  108. def validate_value(self, value):
  109. if value not in self.choices:
  110. raise MesonException('Value %s not one of accepted values.' % value)
  111. return value
  112. class UserStringArrayOption(UserOption):
  113. def __init__(self, name, description, value, **kwargs):
  114. super().__init__(name, description, kwargs.get('choices', []))
  115. self.set_value(value)
  116. def validate(self, value):
  117. if isinstance(value, str):
  118. if not value.startswith('['):
  119. raise MesonException('Valuestring does not define an array: ' + value)
  120. newvalue = ast.literal_eval(value)
  121. else:
  122. newvalue = value
  123. if not isinstance(newvalue, list):
  124. raise MesonException('"{0}" should be a string array, but it is not'.format(str(newvalue)))
  125. for i in newvalue:
  126. if not isinstance(i, str):
  127. raise MesonException('String array element "{0}" is not a string.'.format(str(newvalue)))
  128. return newvalue
  129. def set_value(self, newvalue):
  130. self.value = self.validate(newvalue)
  131. def validate_value(self, value):
  132. self.validate(value)
  133. return value
  134. # This class contains all data that must persist over multiple
  135. # invocations of Meson. It is roughly the same thing as
  136. # cmakecache.
  137. class CoreData:
  138. def __init__(self, options):
  139. self.guid = str(uuid.uuid4()).upper()
  140. self.test_guid = str(uuid.uuid4()).upper()
  141. self.regen_guid = str(uuid.uuid4()).upper()
  142. self.target_guids = {}
  143. self.version = version
  144. self.init_builtins(options)
  145. self.init_backend_options(self.builtins['backend'].value)
  146. self.user_options = {}
  147. self.compiler_options = {}
  148. self.base_options = {}
  149. # These external_*args, are set via env vars CFLAGS, LDFLAGS, etc
  150. # but only when not cross-compiling.
  151. self.external_preprocess_args = {} # CPPFLAGS only
  152. self.external_args = {} # CPPFLAGS + CFLAGS
  153. self.external_link_args = {} # CFLAGS + LDFLAGS (with MSVC: only LDFLAGS)
  154. if options.cross_file is not None:
  155. self.cross_file = os.path.join(os.getcwd(), options.cross_file)
  156. else:
  157. self.cross_file = None
  158. self.wrap_mode = options.wrap_mode
  159. self.compilers = OrderedDict()
  160. self.cross_compilers = OrderedDict()
  161. self.deps = OrderedDict()
  162. self.modules = {}
  163. # Only to print a warning if it changes between Meson invocations.
  164. self.pkgconf_envvar = os.environ.get('PKG_CONFIG_PATH', '')
  165. def sanitize_prefix(self, prefix):
  166. if not os.path.isabs(prefix):
  167. raise MesonException('prefix value {!r} must be an absolute path'
  168. ''.format(prefix))
  169. if prefix.endswith('/') or prefix.endswith('\\'):
  170. # On Windows we need to preserve the trailing slash if the
  171. # string is of type 'C:\' because 'C:' is not an absolute path.
  172. if len(prefix) == 3 and prefix[1] == ':':
  173. pass
  174. else:
  175. prefix = prefix[:-1]
  176. return prefix
  177. def sanitize_dir_option_value(self, prefix, option, value):
  178. '''
  179. If the option is an installation directory option and the value is an
  180. absolute path, check that it resides within prefix and return the value
  181. as a path relative to the prefix.
  182. This way everyone can do f.ex, get_option('libdir') and be sure to get
  183. the library directory relative to prefix.
  184. '''
  185. if option.endswith('dir') and os.path.isabs(value) and \
  186. option not in builtin_dir_noprefix_options:
  187. # Value must be a subdir of the prefix
  188. # commonpath will always return a path in the native format, so we
  189. # must use pathlib.PurePath to do the same conversion before
  190. # comparing.
  191. if commonpath([value, prefix]) != str(PurePath(prefix)):
  192. m = 'The value of the {!r} option is {!r} which must be a ' \
  193. 'subdir of the prefix {!r}.\nNote that if you pass a ' \
  194. 'relative path, it is assumed to be a subdir of prefix.'
  195. raise MesonException(m.format(option, value, prefix))
  196. # Convert path to be relative to prefix
  197. skip = len(prefix) + 1
  198. value = value[skip:]
  199. return value
  200. def init_builtins(self, options):
  201. self.builtins = {}
  202. # Sanitize prefix
  203. options.prefix = self.sanitize_prefix(options.prefix)
  204. # Initialize other builtin options
  205. for key in get_builtin_options():
  206. if hasattr(options, key):
  207. value = getattr(options, key)
  208. value = self.sanitize_dir_option_value(options.prefix, key, value)
  209. setattr(options, key, value)
  210. else:
  211. value = get_builtin_option_default(key)
  212. args = [key] + builtin_options[key][1:-1] + [value]
  213. self.builtins[key] = builtin_options[key][0](*args)
  214. def init_backend_options(self, backend_name):
  215. self.backend_options = {}
  216. if backend_name == 'ninja':
  217. self.backend_options['backend_max_links'] = UserIntegerOption('backend_max_links',
  218. 'Maximum number of linker processes to run or 0 for no limit',
  219. 0, None, 0)
  220. def get_builtin_option(self, optname):
  221. if optname in self.builtins:
  222. return self.builtins[optname].value
  223. raise RuntimeError('Tried to get unknown builtin option %s.' % optname)
  224. def set_builtin_option(self, optname, value):
  225. if optname == 'prefix':
  226. value = self.sanitize_prefix(value)
  227. elif optname in self.builtins:
  228. prefix = self.builtins['prefix'].value
  229. value = self.sanitize_dir_option_value(prefix, optname, value)
  230. else:
  231. raise RuntimeError('Tried to set unknown builtin option %s.' % optname)
  232. self.builtins[optname].set_value(value)
  233. def validate_option_value(self, option_name, override_value):
  234. for opts in (self.builtins, self.base_options, self.compiler_options, self.user_options):
  235. if option_name in opts:
  236. opt = opts[option_name]
  237. return opt.validate_value(override_value)
  238. raise MesonException('Tried to validate unknown option %s.' % option_name)
  239. def load(filename):
  240. load_fail_msg = 'Coredata file {!r} is corrupted. Try with a fresh build tree.'.format(filename)
  241. try:
  242. with open(filename, 'rb') as f:
  243. obj = pickle.load(f)
  244. except pickle.UnpicklingError:
  245. raise MesonException(load_fail_msg)
  246. if not isinstance(obj, CoreData):
  247. raise MesonException(load_fail_msg)
  248. if obj.version != version:
  249. raise MesonException('Build directory has been generated with Meson version %s, which is incompatible with current version %s.\nPlease delete this build directory AND create a new one.' %
  250. (obj.version, version))
  251. return obj
  252. def save(obj, filename):
  253. if obj.version != version:
  254. raise MesonException('Fatal version mismatch corruption.')
  255. with open(filename, 'wb') as f:
  256. pickle.dump(obj, f)
  257. def get_builtin_options():
  258. return list(builtin_options.keys())
  259. def is_builtin_option(optname):
  260. return optname in get_builtin_options()
  261. def get_builtin_option_choices(optname):
  262. if is_builtin_option(optname):
  263. if builtin_options[optname][0] == UserStringOption:
  264. return None
  265. elif builtin_options[optname][0] == UserBooleanOption:
  266. return [True, False]
  267. else:
  268. return builtin_options[optname][2]
  269. else:
  270. raise RuntimeError('Tried to get the supported values for an unknown builtin option \'%s\'.' % optname)
  271. def get_builtin_option_description(optname):
  272. if is_builtin_option(optname):
  273. return builtin_options[optname][1]
  274. else:
  275. raise RuntimeError('Tried to get the description for an unknown builtin option \'%s\'.' % optname)
  276. def get_builtin_option_default(optname):
  277. if is_builtin_option(optname):
  278. o = builtin_options[optname]
  279. if o[0] == UserComboOption:
  280. return o[3]
  281. return o[2]
  282. else:
  283. raise RuntimeError('Tried to get the default value for an unknown builtin option \'%s\'.' % optname)
  284. builtin_options = {
  285. 'buildtype': [UserComboOption, 'Build type to use.', ['plain', 'debug', 'debugoptimized', 'release', 'minsize'], 'debug'],
  286. 'strip': [UserBooleanOption, 'Strip targets on install.', False],
  287. 'unity': [UserComboOption, 'Unity build.', ['on', 'off', 'subprojects'], 'off'],
  288. 'prefix': [UserStringOption, 'Installation prefix.', default_prefix()],
  289. 'libdir': [UserStringOption, 'Library directory.', default_libdir()],
  290. 'libexecdir': [UserStringOption, 'Library executable directory.', default_libexecdir()],
  291. 'bindir': [UserStringOption, 'Executable directory.', 'bin'],
  292. 'sbindir': [UserStringOption, 'System executable directory.', 'sbin'],
  293. 'includedir': [UserStringOption, 'Header file directory.', 'include'],
  294. 'datadir': [UserStringOption, 'Data file directory.', 'share'],
  295. 'mandir': [UserStringOption, 'Manual page directory.', 'share/man'],
  296. 'infodir': [UserStringOption, 'Info page directory.', 'share/info'],
  297. 'localedir': [UserStringOption, 'Locale data directory.', 'share/locale'],
  298. # sysconfdir, localstatedir and sharedstatedir are a bit special. These defaults to ${prefix}/etc,
  299. # ${prefix}/var and ${prefix}/com but nobody uses that. Instead they always set it
  300. # manually to /etc, /var and /var/lib. This default values is thus pointless and not really used
  301. # but we set it to this for consistency with other systems.
  302. #
  303. # Projects installing to sysconfdir, localstatedir or sharedstatedir probably want
  304. # to set the following in project():
  305. #
  306. # default_options : ['sysconfdir=/etc', 'localstatedir=/var', 'sharedstatedir=/var/lib']
  307. 'sysconfdir': [UserStringOption, 'Sysconf data directory.', 'etc'],
  308. 'localstatedir': [UserStringOption, 'Localstate data directory.', 'var'],
  309. 'sharedstatedir': [UserStringOption, 'Architecture-independent data directory.', 'com'],
  310. 'werror': [UserBooleanOption, 'Treat warnings as errors.', False],
  311. 'warning_level': [UserComboOption, 'Compiler warning level to use.', ['1', '2', '3'], '1'],
  312. 'layout': [UserComboOption, 'Build directory layout.', ['mirror', 'flat'], 'mirror'],
  313. 'default_library': [UserComboOption, 'Default library type.', ['shared', 'static'], 'shared'],
  314. 'backend': [UserComboOption, 'Backend to use.', backendlist, 'ninja'],
  315. 'stdsplit': [UserBooleanOption, 'Split stdout and stderr in test logs.', True],
  316. 'errorlogs': [UserBooleanOption, "Whether to print the logs from failing tests.", True],
  317. }
  318. # Installation directories that can reside in a path outside of the prefix
  319. builtin_dir_noprefix_options = {'sysconfdir', 'localstatedir', 'sharedstatedir'}
  320. forbidden_target_names = {'clean': None,
  321. 'clean-ctlist': None,
  322. 'clean-gcno': None,
  323. 'clean-gcda': None,
  324. 'coverage': None,
  325. 'coverage-text': None,
  326. 'coverage-xml': None,
  327. 'coverage-html': None,
  328. 'phony': None,
  329. 'PHONY': None,
  330. 'all': None,
  331. 'test': None,
  332. 'benchmark': None,
  333. 'install': None,
  334. 'uninstall': None,
  335. 'build.ninja': None,
  336. 'scan-build': None,
  337. 'reconfigure': None,
  338. 'dist': None,
  339. 'distcheck': None,
  340. }