build.py 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317
  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 copy, os, re
  12. from collections import OrderedDict
  13. import itertools, pathlib
  14. import hashlib
  15. import pickle
  16. from functools import lru_cache
  17. from . import environment
  18. from . import dependencies
  19. from . import mlog
  20. from .mesonlib import (
  21. File, MesonException, listify, extract_as_list, OrderedSet,
  22. typeslistify, stringlistify, classify_unity_sources,
  23. get_filenames_templates_dict, substitute_values,
  24. for_windows, for_darwin, for_cygwin, for_android, has_path_sep
  25. )
  26. from .compilers import is_object, clink_langs, sort_clink, lang_suffixes, get_macos_dylib_install_name
  27. from .interpreterbase import FeatureNew
  28. pch_kwargs = set(['c_pch', 'cpp_pch'])
  29. lang_arg_kwargs = set([
  30. 'c_args',
  31. 'cpp_args',
  32. 'cuda_args',
  33. 'd_args',
  34. 'd_import_dirs',
  35. 'd_unittest',
  36. 'd_module_versions',
  37. 'd_debug',
  38. 'fortran_args',
  39. 'java_args',
  40. 'objc_args',
  41. 'objcpp_args',
  42. 'rust_args',
  43. 'vala_args',
  44. 'cs_args',
  45. ])
  46. vala_kwargs = set(['vala_header', 'vala_gir', 'vala_vapi'])
  47. rust_kwargs = set(['rust_crate_type'])
  48. cs_kwargs = set(['resources', 'cs_args'])
  49. buildtarget_kwargs = set([
  50. 'build_by_default',
  51. 'build_rpath',
  52. 'dependencies',
  53. 'extra_files',
  54. 'gui_app',
  55. 'link_with',
  56. 'link_whole',
  57. 'link_args',
  58. 'link_depends',
  59. 'implicit_include_directories',
  60. 'include_directories',
  61. 'install',
  62. 'install_rpath',
  63. 'install_dir',
  64. 'install_mode',
  65. 'name_prefix',
  66. 'name_suffix',
  67. 'native',
  68. 'objects',
  69. 'override_options',
  70. 'sources',
  71. 'gnu_symbol_visibility',
  72. ])
  73. known_build_target_kwargs = (
  74. buildtarget_kwargs |
  75. lang_arg_kwargs |
  76. pch_kwargs |
  77. vala_kwargs |
  78. rust_kwargs |
  79. cs_kwargs)
  80. known_exe_kwargs = known_build_target_kwargs | {'implib', 'export_dynamic', 'pie'}
  81. known_shlib_kwargs = known_build_target_kwargs | {'version', 'soversion', 'vs_module_defs', 'darwin_versions'}
  82. known_shmod_kwargs = known_build_target_kwargs
  83. known_stlib_kwargs = known_build_target_kwargs | {'pic'}
  84. known_jar_kwargs = known_exe_kwargs | {'main_class'}
  85. @lru_cache(maxsize=None)
  86. def get_target_macos_dylib_install_name(ld):
  87. return get_macos_dylib_install_name(ld.prefix, ld.name, ld.suffix, ld.soversion)
  88. class InvalidArguments(MesonException):
  89. pass
  90. class Build:
  91. """A class that holds the status of one build including
  92. all dependencies and so on.
  93. """
  94. def __init__(self, environment):
  95. self.project_name = 'name of master project'
  96. self.project_version = None
  97. self.environment = environment
  98. self.projects = {}
  99. self.targets = OrderedDict()
  100. # Coredata holds the state. This is just here for convenience.
  101. self.compilers = environment.coredata.compilers
  102. self.cross_compilers = environment.coredata.cross_compilers
  103. self.global_args = {}
  104. self.projects_args = {}
  105. self.global_link_args = {}
  106. self.projects_link_args = {}
  107. self.cross_global_args = {}
  108. self.cross_projects_args = {}
  109. self.cross_global_link_args = {}
  110. self.cross_projects_link_args = {}
  111. self.tests = []
  112. self.benchmarks = []
  113. self.headers = []
  114. self.man = []
  115. self.data = []
  116. self.static_linker = None
  117. self.static_cross_linker = None
  118. self.subprojects = {}
  119. self.subproject_dir = ''
  120. self.install_scripts = []
  121. self.postconf_scripts = []
  122. self.dist_scripts = []
  123. self.install_dirs = []
  124. self.dep_manifest_name = None
  125. self.dep_manifest = {}
  126. self.cross_stdlibs = {}
  127. self.test_setups = {}
  128. self.test_setup_default_name = None
  129. self.find_overrides = {}
  130. self.searched_programs = set() # The list of all programs that have been searched for.
  131. def copy(self):
  132. other = Build(self.environment)
  133. for k, v in self.__dict__.items():
  134. if k in ['compilers', 'cross_compilers']:
  135. # These alias coredata's fields of the same name, and must not
  136. # become copies.
  137. continue
  138. if isinstance(v, (list, dict, set, OrderedDict)):
  139. other.__dict__[k] = v.copy()
  140. else:
  141. other.__dict__[k] = v
  142. return other
  143. def merge(self, other):
  144. for k, v in other.__dict__.items():
  145. self.__dict__[k] = v
  146. def ensure_static_linker(self, compiler):
  147. if self.static_linker is None and compiler.needs_static_linker():
  148. self.static_linker = self.environment.detect_static_linker(compiler)
  149. def ensure_static_cross_linker(self, compiler):
  150. if self.static_cross_linker is None and compiler.needs_static_linker():
  151. self.static_cross_linker = self.environment.detect_static_linker(compiler)
  152. def get_project(self):
  153. return self.projects['']
  154. def get_subproject_dir(self):
  155. return self.subproject_dir
  156. def get_targets(self):
  157. return self.targets
  158. def get_tests(self):
  159. return self.tests
  160. def get_benchmarks(self):
  161. return self.benchmarks
  162. def get_headers(self):
  163. return self.headers
  164. def get_man(self):
  165. return self.man
  166. def get_data(self):
  167. return self.data
  168. def get_install_subdirs(self):
  169. return self.install_dirs
  170. def get_global_args(self, compiler, for_cross):
  171. d = self.cross_global_args if for_cross else self.global_args
  172. return d.get(compiler.get_language(), [])
  173. def get_project_args(self, compiler, project, for_cross):
  174. d = self.cross_projects_args if for_cross else self.projects_args
  175. args = d.get(project)
  176. if not args:
  177. return []
  178. return args.get(compiler.get_language(), [])
  179. def get_global_link_args(self, compiler, for_cross):
  180. d = self.cross_global_link_args if for_cross else self.global_link_args
  181. return d.get(compiler.get_language(), [])
  182. def get_project_link_args(self, compiler, project, for_cross):
  183. d = self.cross_projects_link_args if for_cross else self.projects_link_args
  184. link_args = d.get(project)
  185. if not link_args:
  186. return []
  187. return link_args.get(compiler.get_language(), [])
  188. class IncludeDirs:
  189. def __init__(self, curdir, dirs, is_system, extra_build_dirs=None):
  190. self.curdir = curdir
  191. self.incdirs = dirs
  192. self.is_system = is_system
  193. # Interpreter has validated that all given directories
  194. # actually exist.
  195. if extra_build_dirs is None:
  196. self.extra_build_dirs = []
  197. else:
  198. self.extra_build_dirs = extra_build_dirs
  199. def __repr__(self):
  200. r = '<{} {}/{}>'
  201. return r.format(self.__class__.__name__, self.curdir, self.incdirs)
  202. def get_curdir(self):
  203. return self.curdir
  204. def get_incdirs(self):
  205. return self.incdirs
  206. def get_extra_build_dirs(self):
  207. return self.extra_build_dirs
  208. class ExtractedObjects:
  209. '''
  210. Holds a list of sources for which the objects must be extracted
  211. '''
  212. def __init__(self, target, srclist=[], genlist=[], objlist=[], recursive=True):
  213. self.target = target
  214. self.recursive = recursive
  215. self.srclist = srclist
  216. self.genlist = genlist
  217. self.objlist = objlist
  218. if self.target.is_unity:
  219. self.check_unity_compatible()
  220. def __repr__(self):
  221. r = '<{0} {1!r}: {2}>'
  222. return r.format(self.__class__.__name__, self.target.name, self.srclist)
  223. def classify_all_sources(self, sources, generated_sources):
  224. # Merge sources and generated sources
  225. sources = list(sources)
  226. for gensrc in generated_sources:
  227. for s in gensrc.get_outputs():
  228. # We cannot know the path where this source will be generated,
  229. # but all we need here is the file extension to determine the
  230. # compiler.
  231. sources.append(s)
  232. # Filter out headers and all non-source files
  233. sources = [s for s in sources if environment.is_source(s) and not environment.is_header(s)]
  234. return classify_unity_sources(self.target.compilers.values(), sources)
  235. def check_unity_compatible(self):
  236. # Figure out if the extracted object list is compatible with a Unity
  237. # build. When we're doing a Unified build, we go through the sources,
  238. # and create a single source file from each subset of the sources that
  239. # can be compiled with a specific compiler. Then we create one object
  240. # from each unified source file. So for each compiler we can either
  241. # extra all its sources or none.
  242. cmpsrcs = self.classify_all_sources(self.target.sources, self.target.generated)
  243. extracted_cmpsrcs = self.classify_all_sources(self.srclist, self.genlist)
  244. for comp, srcs in extracted_cmpsrcs.items():
  245. if set(srcs) != set(cmpsrcs[comp]):
  246. raise MesonException('Single object files can not be extracted '
  247. 'in Unity builds. You can only extract all '
  248. 'the object files for each compiler at once.')
  249. class EnvironmentVariables:
  250. def __init__(self):
  251. self.envvars = []
  252. def __repr__(self):
  253. repr_str = "<{0}: {1}>"
  254. return repr_str.format(self.__class__.__name__, self.envvars)
  255. def get_value(self, values, kwargs):
  256. separator = kwargs.get('separator', os.pathsep)
  257. value = ''
  258. for var in values:
  259. value += separator + var
  260. return separator, value.strip(separator)
  261. def set(self, env, name, values, kwargs):
  262. return self.get_value(values, kwargs)[1]
  263. def append(self, env, name, values, kwargs):
  264. sep, value = self.get_value(values, kwargs)
  265. if name in env:
  266. return env[name] + sep + value
  267. return value
  268. def prepend(self, env, name, values, kwargs):
  269. sep, value = self.get_value(values, kwargs)
  270. if name in env:
  271. return value + sep + env[name]
  272. return value
  273. def get_env(self, full_env):
  274. env = full_env.copy()
  275. for method, name, values, kwargs in self.envvars:
  276. env[name] = method(full_env, name, values, kwargs)
  277. return env
  278. class Target:
  279. def __init__(self, name, subdir, subproject, build_by_default):
  280. if has_path_sep(name):
  281. # Fix failing test 53 when this becomes an error.
  282. mlog.warning('''Target "%s" has a path separator in its name.
  283. This is not supported, it can cause unexpected failures and will become
  284. a hard error in the future.''' % name)
  285. self.name = name
  286. self.subdir = subdir
  287. self.subproject = subproject
  288. self.build_by_default = build_by_default
  289. self.install = False
  290. self.build_always_stale = False
  291. self.option_overrides = {}
  292. if not hasattr(self, 'typename'):
  293. raise RuntimeError('Target type is not set for target class "{}". This is a bug'.format(type(self).__name__))
  294. def get_install_dir(self, environment):
  295. # Find the installation directory.
  296. default_install_dir = self.get_default_install_dir(environment)
  297. outdirs = self.get_custom_install_dir()
  298. if outdirs[0] is not None and outdirs[0] != default_install_dir and outdirs[0] is not True:
  299. # Either the value is set to a non-default value, or is set to
  300. # False (which means we want this specific output out of many
  301. # outputs to not be installed).
  302. custom_install_dir = True
  303. else:
  304. custom_install_dir = False
  305. outdirs[0] = default_install_dir
  306. return outdirs, custom_install_dir
  307. def get_basename(self):
  308. return self.name
  309. def get_subdir(self):
  310. return self.subdir
  311. def get_typename(self):
  312. return self.typename
  313. @staticmethod
  314. def _get_id_hash(target_id):
  315. # We don't really need cryptographic security here.
  316. # Small-digest hash function with unlikely collision is good enough.
  317. h = hashlib.sha256()
  318. h.update(target_id.encode(encoding='utf-8', errors='replace'))
  319. # This ID should be case-insensitive and should work in Visual Studio,
  320. # e.g. it should not start with leading '-'.
  321. return h.hexdigest()[:7]
  322. @staticmethod
  323. def construct_id_from_path(subdir, name, type_suffix):
  324. """Construct target ID from subdir, name and type suffix.
  325. This helper function is made public mostly for tests."""
  326. # This ID must also be a valid file name on all OSs.
  327. # It should also avoid shell metacharacters for obvious
  328. # reasons. '@' is not used as often as '_' in source code names.
  329. # In case of collisions consider using checksums.
  330. # FIXME replace with assert when slash in names is prohibited
  331. name_part = name.replace('/', '@').replace('\\', '@')
  332. assert not has_path_sep(type_suffix)
  333. my_id = name_part + type_suffix
  334. if subdir:
  335. subdir_part = Target._get_id_hash(subdir)
  336. # preserve myid for better debuggability
  337. return subdir_part + '@@' + my_id
  338. return my_id
  339. def get_id(self):
  340. return self.construct_id_from_path(
  341. self.subdir, self.name, self.type_suffix())
  342. def process_kwargs(self, kwargs):
  343. if 'build_by_default' in kwargs:
  344. self.build_by_default = kwargs['build_by_default']
  345. if not isinstance(self.build_by_default, bool):
  346. raise InvalidArguments('build_by_default must be a boolean value.')
  347. elif kwargs.get('install', False):
  348. # For backward compatibility, if build_by_default is not explicitly
  349. # set, use the value of 'install' if it's enabled.
  350. self.build_by_default = True
  351. self.option_overrides = self.parse_overrides(kwargs)
  352. def parse_overrides(self, kwargs):
  353. result = {}
  354. overrides = stringlistify(kwargs.get('override_options', []))
  355. for o in overrides:
  356. if '=' not in o:
  357. raise InvalidArguments('Overrides must be of form "key=value"')
  358. k, v = o.split('=', 1)
  359. k = k.strip()
  360. v = v.strip()
  361. result[k] = v
  362. return result
  363. def is_linkable_target(self):
  364. return False
  365. class BuildTarget(Target):
  366. known_kwargs = known_build_target_kwargs
  367. def __init__(self, name, subdir, subproject, is_cross, sources, objects, environment, kwargs):
  368. super().__init__(name, subdir, subproject, True)
  369. self.is_cross = is_cross
  370. unity_opt = environment.coredata.get_builtin_option('unity')
  371. self.is_unity = unity_opt == 'on' or (unity_opt == 'subprojects' and subproject != '')
  372. self.environment = environment
  373. self.sources = []
  374. self.compilers = OrderedDict()
  375. self.objects = []
  376. self.external_deps = []
  377. self.include_dirs = []
  378. self.link_targets = []
  379. self.link_whole_targets = []
  380. self.link_depends = []
  381. self.name_prefix_set = False
  382. self.name_suffix_set = False
  383. self.filename = 'no_name'
  384. # The list of all files outputted by this target. Useful in cases such
  385. # as Vala which generates .vapi and .h besides the compiled output.
  386. self.outputs = [self.filename]
  387. self.need_install = False
  388. self.pch = {}
  389. self.extra_args = {}
  390. self.generated = []
  391. self.extra_files = []
  392. self.d_features = {}
  393. self.pic = False
  394. self.pie = False
  395. # Sources can be:
  396. # 1. Pre-existing source files in the source tree
  397. # 2. Pre-existing sources generated by configure_file in the build tree
  398. # 3. Sources files generated by another target or a Generator
  399. self.process_sourcelist(sources)
  400. # Objects can be:
  401. # 1. Pre-existing objects provided by the user with the `objects:` kwarg
  402. # 2. Compiled objects created by and extracted from another target
  403. self.process_objectlist(objects)
  404. self.process_kwargs(kwargs, environment)
  405. self.check_unknown_kwargs(kwargs)
  406. self.process_compilers()
  407. if not any([self.sources, self.generated, self.objects, self.link_whole]):
  408. raise InvalidArguments('Build target %s has no sources.' % name)
  409. self.process_compilers_late()
  410. self.validate_sources()
  411. self.validate_cross_install(environment)
  412. self.check_module_linking()
  413. def __lt__(self, other):
  414. return self.get_id() < other.get_id()
  415. def __repr__(self):
  416. repr_str = "<{0} {1}: {2}>"
  417. return repr_str.format(self.__class__.__name__, self.get_id(), self.filename)
  418. def validate_cross_install(self, environment):
  419. if environment.is_cross_build() and not self.is_cross and self.need_install:
  420. raise InvalidArguments('Tried to install a natively built target in a cross build.')
  421. def check_unknown_kwargs(self, kwargs):
  422. # Override this method in derived classes that have more
  423. # keywords.
  424. self.check_unknown_kwargs_int(kwargs, self.known_kwargs)
  425. def check_unknown_kwargs_int(self, kwargs, known_kwargs):
  426. unknowns = []
  427. for k in kwargs:
  428. if k not in known_kwargs:
  429. unknowns.append(k)
  430. if len(unknowns) > 0:
  431. mlog.warning('Unknown keyword argument(s) in target %s: %s.' %
  432. (self.name, ', '.join(unknowns)))
  433. def process_objectlist(self, objects):
  434. assert(isinstance(objects, list))
  435. for s in objects:
  436. if hasattr(s, 'held_object'):
  437. s = s.held_object
  438. if isinstance(s, (str, File, ExtractedObjects)):
  439. self.objects.append(s)
  440. elif isinstance(s, (GeneratedList, CustomTarget)):
  441. msg = 'Generated files are not allowed in the \'objects\' kwarg ' + \
  442. 'for target {!r}.\nIt is meant only for '.format(self.name) + \
  443. 'pre-built object files that are shipped with the\nsource ' + \
  444. 'tree. Try adding it in the list of sources.'
  445. raise InvalidArguments(msg)
  446. else:
  447. msg = 'Bad object of type {!r} in target {!r}.'.format(type(s).__name__, self.name)
  448. raise InvalidArguments(msg)
  449. def process_sourcelist(self, sources):
  450. sources = listify(sources)
  451. added_sources = {} # If the same source is defined multiple times, use it only once.
  452. for s in sources:
  453. # Holder unpacking. Ugly.
  454. if hasattr(s, 'held_object'):
  455. s = s.held_object
  456. if isinstance(s, File):
  457. if s not in added_sources:
  458. self.sources.append(s)
  459. added_sources[s] = True
  460. elif isinstance(s, (GeneratedList, CustomTarget, CustomTargetIndex)):
  461. self.generated.append(s)
  462. else:
  463. msg = 'Bad source of type {!r} in target {!r}.'.format(type(s).__name__, self.name)
  464. raise InvalidArguments(msg)
  465. @staticmethod
  466. def can_compile_remove_sources(compiler, sources):
  467. removed = False
  468. for s in sources[:]:
  469. if compiler.can_compile(s):
  470. sources.remove(s)
  471. removed = True
  472. return removed
  473. def process_compilers_late(self):
  474. """Processes additional compilers after kwargs have been evaluated.
  475. This can add extra compilers that might be required by keyword
  476. arguments, such as link_with or dependencies. It will also try to guess
  477. which compiler to use if one hasn't been selected already.
  478. """
  479. # Populate list of compilers
  480. if self.is_cross:
  481. compilers = self.environment.coredata.cross_compilers
  482. else:
  483. compilers = self.environment.coredata.compilers
  484. # If this library is linked against another library we need to consider
  485. # the languages of those libraries as well.
  486. if self.link_targets or self.link_whole_targets:
  487. extra = set()
  488. for t in itertools.chain(self.link_targets, self.link_whole_targets):
  489. for name, compiler in t.compilers.items():
  490. if name in clink_langs:
  491. extra.add((name, compiler))
  492. for name, compiler in sorted(extra, key=lambda p: sort_clink(p[0])):
  493. self.compilers[name] = compiler
  494. if not self.compilers:
  495. # No source files or parent targets, target consists of only object
  496. # files of unknown origin. Just add the first clink compiler
  497. # that we have and hope that it can link these objects
  498. for lang in clink_langs:
  499. if lang in compilers:
  500. self.compilers[lang] = compilers[lang]
  501. break
  502. def process_compilers(self):
  503. '''
  504. Populate self.compilers, which is the list of compilers that this
  505. target will use for compiling all its sources.
  506. We also add compilers that were used by extracted objects to simplify
  507. dynamic linker determination.
  508. '''
  509. if not self.sources and not self.generated and not self.objects:
  510. return
  511. # Populate list of compilers
  512. if self.is_cross:
  513. compilers = self.environment.coredata.cross_compilers
  514. else:
  515. compilers = self.environment.coredata.compilers
  516. # Pre-existing sources
  517. sources = list(self.sources)
  518. # All generated sources
  519. for gensrc in self.generated:
  520. for s in gensrc.get_outputs():
  521. # Generated objects can't be compiled, so don't use them for
  522. # compiler detection. If our target only has generated objects,
  523. # we will fall back to using the first c-like compiler we find,
  524. # which is what we need.
  525. if not is_object(s):
  526. sources.append(s)
  527. for d in self.external_deps:
  528. if hasattr(d, 'held_object'):
  529. d = d.held_object
  530. for s in d.sources:
  531. if isinstance(s, (str, File)):
  532. sources.append(s)
  533. # Sources that were used to create our extracted objects
  534. for o in self.objects:
  535. if not isinstance(o, ExtractedObjects):
  536. continue
  537. for s in o.srclist:
  538. # Don't add Vala sources since that will pull in the Vala
  539. # compiler even though we will never use it since we are
  540. # dealing with compiled C code.
  541. if not s.endswith(lang_suffixes['vala']):
  542. sources.append(s)
  543. if sources:
  544. # For each source, try to add one compiler that can compile it.
  545. # It's ok if no compilers can do so, because users are expected to
  546. # be able to add arbitrary non-source files to the sources list.
  547. for s in sources:
  548. for lang, compiler in compilers.items():
  549. if compiler.can_compile(s):
  550. if lang not in self.compilers:
  551. self.compilers[lang] = compiler
  552. break
  553. # Re-sort according to clink_langs
  554. self.compilers = OrderedDict(sorted(self.compilers.items(),
  555. key=lambda t: sort_clink(t[0])))
  556. # If all our sources are Vala, our target also needs the C compiler but
  557. # it won't get added above.
  558. if 'vala' in self.compilers and 'c' not in self.compilers:
  559. self.compilers['c'] = compilers['c']
  560. def validate_sources(self):
  561. if not self.sources:
  562. return
  563. for lang in ('cs', 'java'):
  564. if lang in self.compilers:
  565. check_sources = list(self.sources)
  566. compiler = self.compilers[lang]
  567. if not self.can_compile_remove_sources(compiler, check_sources):
  568. m = 'No {} sources found in target {!r}'.format(lang, self.name)
  569. raise InvalidArguments(m)
  570. if check_sources:
  571. m = '{0} targets can only contain {0} files:\n'.format(lang.capitalize())
  572. m += '\n'.join([repr(c) for c in check_sources])
  573. raise InvalidArguments(m)
  574. # CSharp and Java targets can't contain any other file types
  575. assert(len(self.compilers) == 1)
  576. return
  577. def process_link_depends(self, sources, environment):
  578. """Process the link_depends keyword argument.
  579. This is designed to handle strings, Files, and the output of Custom
  580. Targets. Notably it doesn't handle generator() returned objects, since
  581. adding them as a link depends would inherently cause them to be
  582. generated twice, since the output needs to be passed to the ld_args and
  583. link_depends.
  584. """
  585. sources = listify(sources)
  586. for s in sources:
  587. if hasattr(s, 'held_object'):
  588. s = s.held_object
  589. if isinstance(s, File):
  590. self.link_depends.append(s)
  591. elif isinstance(s, str):
  592. self.link_depends.append(
  593. File.from_source_file(environment.source_dir, self.subdir, s))
  594. elif hasattr(s, 'get_outputs'):
  595. self.link_depends.extend(
  596. [File.from_built_file(s.subdir, p) for p in s.get_outputs()])
  597. else:
  598. raise InvalidArguments(
  599. 'Link_depends arguments must be strings, Files, '
  600. 'or a Custom Target, or lists thereof.')
  601. def get_original_kwargs(self):
  602. return self.kwargs
  603. def unpack_holder(self, d):
  604. d = listify(d)
  605. newd = []
  606. for i in d:
  607. if isinstance(i, list):
  608. i = self.unpack_holder(i)
  609. elif hasattr(i, 'held_object'):
  610. i = i.held_object
  611. for t in ['dependencies', 'link_with', 'include_directories', 'sources']:
  612. if hasattr(i, t):
  613. setattr(i, t, self.unpack_holder(getattr(i, t)))
  614. newd.append(i)
  615. return newd
  616. def copy_kwargs(self, kwargs):
  617. self.kwargs = copy.copy(kwargs)
  618. # This sucks quite badly. Arguments
  619. # are holders but they can't be pickled
  620. # so unpack those known.
  621. for k, v in self.kwargs.items():
  622. if isinstance(v, list):
  623. self.kwargs[k] = self.unpack_holder(v)
  624. if hasattr(v, 'held_object'):
  625. self.kwargs[k] = v.held_object
  626. for t in ['dependencies', 'link_with', 'include_directories', 'sources']:
  627. if t in self.kwargs:
  628. self.kwargs[t] = self.unpack_holder(self.kwargs[t])
  629. def extract_objects(self, srclist):
  630. obj_src = []
  631. for src in srclist:
  632. if not isinstance(src, str):
  633. raise MesonException('Object extraction arguments must be strings.')
  634. src = File(False, self.subdir, src)
  635. # FIXME: It could be a generated source
  636. if src not in self.sources:
  637. raise MesonException('Tried to extract unknown source %s.' % src)
  638. obj_src.append(src)
  639. return ExtractedObjects(self, obj_src)
  640. def extract_all_objects(self, recursive=True):
  641. return ExtractedObjects(self, self.sources, self.generated, self.objects,
  642. recursive)
  643. def get_all_link_deps(self):
  644. return self.get_transitive_link_deps()
  645. @lru_cache(maxsize=None)
  646. def get_transitive_link_deps(self):
  647. result = []
  648. for i in self.link_targets:
  649. result += i.get_all_link_deps()
  650. return result
  651. def get_link_deps_mapping(self, prefix, environment):
  652. return self.get_transitive_link_deps_mapping(prefix, environment)
  653. @lru_cache(maxsize=None)
  654. def get_transitive_link_deps_mapping(self, prefix, environment):
  655. result = {}
  656. for i in self.link_targets:
  657. mapping = i.get_link_deps_mapping(prefix, environment)
  658. #we are merging two dictionaries, while keeping the earlier one dominant
  659. result_tmp = mapping.copy()
  660. result_tmp.update(result)
  661. result = result_tmp
  662. return result
  663. @lru_cache(maxsize=None)
  664. def get_link_dep_subdirs(self):
  665. result = OrderedSet()
  666. for i in self.link_targets:
  667. result.add(i.get_subdir())
  668. result.update(i.get_link_dep_subdirs())
  669. return result
  670. def get_default_install_dir(self, environment):
  671. return environment.get_libdir()
  672. def get_custom_install_dir(self):
  673. return self.install_dir
  674. def get_custom_install_mode(self):
  675. return self.install_mode
  676. def process_kwargs(self, kwargs, environment):
  677. super().process_kwargs(kwargs)
  678. self.copy_kwargs(kwargs)
  679. kwargs.get('modules', [])
  680. self.need_install = kwargs.get('install', self.need_install)
  681. llist = extract_as_list(kwargs, 'link_with')
  682. for linktarget in llist:
  683. # Sorry for this hack. Keyword targets are kept in holders
  684. # in kwargs. Unpack here without looking at the exact type.
  685. if hasattr(linktarget, "held_object"):
  686. linktarget = linktarget.held_object
  687. if isinstance(linktarget, dependencies.ExternalLibrary):
  688. raise MesonException('''An external library was used in link_with keyword argument, which
  689. is reserved for libraries built as part of this project. External
  690. libraries must be passed using the dependencies keyword argument
  691. instead, because they are conceptually "external dependencies",
  692. just like those detected with the dependency() function.''')
  693. self.link(linktarget)
  694. lwhole = extract_as_list(kwargs, 'link_whole')
  695. for linktarget in lwhole:
  696. self.link_whole(linktarget)
  697. c_pchlist, cpp_pchlist, clist, cpplist, cudalist, cslist, valalist, objclist, objcpplist, fortranlist, rustlist \
  698. = extract_as_list(kwargs, 'c_pch', 'cpp_pch', 'c_args', 'cpp_args', 'cuda_args', 'cs_args', 'vala_args', 'objc_args',
  699. 'objcpp_args', 'fortran_args', 'rust_args')
  700. self.add_pch('c', c_pchlist)
  701. self.add_pch('cpp', cpp_pchlist)
  702. compiler_args = {'c': clist, 'cpp': cpplist, 'cuda': cudalist, 'cs': cslist, 'vala': valalist, 'objc': objclist, 'objcpp': objcpplist,
  703. 'fortran': fortranlist, 'rust': rustlist
  704. }
  705. for key, value in compiler_args.items():
  706. self.add_compiler_args(key, value)
  707. if not isinstance(self, Executable) or 'export_dynamic' in kwargs:
  708. self.vala_header = kwargs.get('vala_header', self.name + '.h')
  709. self.vala_vapi = kwargs.get('vala_vapi', self.name + '.vapi')
  710. self.vala_gir = kwargs.get('vala_gir', None)
  711. dlist = stringlistify(kwargs.get('d_args', []))
  712. self.add_compiler_args('d', dlist)
  713. dfeatures = dict()
  714. dfeature_unittest = kwargs.get('d_unittest', False)
  715. if dfeature_unittest:
  716. dfeatures['unittest'] = dfeature_unittest
  717. dfeature_versions = kwargs.get('d_module_versions', [])
  718. if dfeature_versions:
  719. dfeatures['versions'] = dfeature_versions
  720. dfeature_debug = kwargs.get('d_debug', [])
  721. if dfeature_debug:
  722. dfeatures['debug'] = dfeature_debug
  723. if 'd_import_dirs' in kwargs:
  724. dfeature_import_dirs = extract_as_list(kwargs, 'd_import_dirs', unholder=True)
  725. for d in dfeature_import_dirs:
  726. if not isinstance(d, IncludeDirs):
  727. raise InvalidArguments('Arguments to d_import_dirs must be include_directories.')
  728. dfeatures['import_dirs'] = dfeature_import_dirs
  729. if dfeatures:
  730. self.d_features = dfeatures
  731. self.link_args = extract_as_list(kwargs, 'link_args')
  732. for i in self.link_args:
  733. if not isinstance(i, str):
  734. raise InvalidArguments('Link_args arguments must be strings.')
  735. for l in self.link_args:
  736. if '-Wl,-rpath' in l or l.startswith('-rpath'):
  737. mlog.warning('''Please do not define rpath with a linker argument, use install_rpath or build_rpath properties instead.
  738. This will become a hard error in a future Meson release.''')
  739. self.process_link_depends(kwargs.get('link_depends', []), environment)
  740. # Target-specific include dirs must be added BEFORE include dirs from
  741. # internal deps (added inside self.add_deps()) to override them.
  742. inclist = extract_as_list(kwargs, 'include_directories')
  743. self.add_include_dirs(inclist)
  744. # Add dependencies (which also have include_directories)
  745. deplist = extract_as_list(kwargs, 'dependencies')
  746. self.add_deps(deplist)
  747. # If an item in this list is False, the output corresponding to
  748. # the list index of that item will not be installed
  749. self.install_dir = typeslistify(kwargs.get('install_dir', [None]),
  750. (str, bool))
  751. self.install_mode = kwargs.get('install_mode', None)
  752. main_class = kwargs.get('main_class', '')
  753. if not isinstance(main_class, str):
  754. raise InvalidArguments('Main class must be a string')
  755. self.main_class = main_class
  756. if isinstance(self, Executable):
  757. self.gui_app = kwargs.get('gui_app', False)
  758. if not isinstance(self.gui_app, bool):
  759. raise InvalidArguments('Argument gui_app must be boolean.')
  760. elif 'gui_app' in kwargs:
  761. raise InvalidArguments('Argument gui_app can only be used on executables.')
  762. extra_files = extract_as_list(kwargs, 'extra_files')
  763. for i in extra_files:
  764. assert(isinstance(i, File))
  765. trial = os.path.join(environment.get_source_dir(), i.subdir, i.fname)
  766. if not(os.path.isfile(trial)):
  767. raise InvalidArguments('Tried to add non-existing extra file %s.' % i)
  768. self.extra_files = extra_files
  769. self.install_rpath = kwargs.get('install_rpath', '')
  770. if not isinstance(self.install_rpath, str):
  771. raise InvalidArguments('Install_rpath is not a string.')
  772. self.build_rpath = kwargs.get('build_rpath', '')
  773. if not isinstance(self.build_rpath, str):
  774. raise InvalidArguments('Build_rpath is not a string.')
  775. resources = extract_as_list(kwargs, 'resources')
  776. for r in resources:
  777. if not isinstance(r, str):
  778. raise InvalidArguments('Resource argument is not a string.')
  779. trial = os.path.join(environment.get_source_dir(), self.subdir, r)
  780. if not os.path.isfile(trial):
  781. raise InvalidArguments('Tried to add non-existing resource %s.' % r)
  782. self.resources = resources
  783. if 'name_prefix' in kwargs:
  784. name_prefix = kwargs['name_prefix']
  785. if isinstance(name_prefix, list):
  786. if name_prefix:
  787. raise InvalidArguments('name_prefix array must be empty to signify null.')
  788. elif not isinstance(name_prefix, str):
  789. raise InvalidArguments('name_prefix must be a string.')
  790. self.prefix = name_prefix
  791. self.name_prefix_set = True
  792. if 'name_suffix' in kwargs:
  793. name_suffix = kwargs['name_suffix']
  794. if isinstance(name_suffix, list):
  795. if name_suffix:
  796. raise InvalidArguments('name_suffix array must be empty to signify null.')
  797. else:
  798. if not isinstance(name_suffix, str):
  799. raise InvalidArguments('name_suffix must be a string.')
  800. if name_suffix == '':
  801. raise InvalidArguments('name_suffix should not be an empty string. '
  802. 'If you want meson to use the default behaviour '
  803. 'for each platform pass `[]` (empty array)')
  804. self.suffix = name_suffix
  805. self.name_suffix_set = True
  806. if isinstance(self, StaticLibrary):
  807. # You can't disable PIC on OS X. The compiler ignores -fno-PIC.
  808. # PIC is always on for Windows (all code is position-independent
  809. # since library loading is done differently)
  810. if for_darwin(self.is_cross, self.environment) or for_windows(self.is_cross, self.environment):
  811. self.pic = True
  812. else:
  813. self.pic = self._extract_pic_pie(kwargs, 'pic')
  814. if isinstance(self, Executable):
  815. # Executables must be PIE on Android
  816. if for_android(self.is_cross, self.environment):
  817. self.pie = True
  818. else:
  819. self.pie = self._extract_pic_pie(kwargs, 'pie')
  820. self.implicit_include_directories = kwargs.get('implicit_include_directories', True)
  821. if not isinstance(self.implicit_include_directories, bool):
  822. raise InvalidArguments('Implicit_include_directories must be a boolean.')
  823. self.gnu_symbol_visibility = kwargs.get('gnu_symbol_visibility', '')
  824. if not isinstance(self.gnu_symbol_visibility, str):
  825. raise InvalidArguments('GNU symbol visibility must be a string.')
  826. if self.gnu_symbol_visibility != '':
  827. permitted = ['default', 'internal', 'hidden', 'protected', 'inlineshidden']
  828. if self.gnu_symbol_visibility not in permitted:
  829. raise InvalidArguments('GNU symbol visibility arg %s not one of: %s',
  830. self.symbol_visibility, ', '.join(permitted))
  831. def _extract_pic_pie(self, kwargs, arg):
  832. # Check if we have -fPIC, -fpic, -fPIE, or -fpie in cflags
  833. all_flags = self.extra_args['c'] + self.extra_args['cpp']
  834. if '-f' + arg.lower() in all_flags or '-f' + arg.upper() in all_flags:
  835. mlog.warning("Use the '{}' kwarg instead of passing '{}' manually to {!r}".format(arg, '-f' + arg, self.name))
  836. return True
  837. val = kwargs.get(arg, False)
  838. if not isinstance(val, bool):
  839. raise InvalidArguments('Argument {} to {!r} must be boolean'.format(arg, self.name))
  840. return val
  841. def get_filename(self):
  842. return self.filename
  843. def get_outputs(self):
  844. return self.outputs
  845. def get_extra_args(self, language):
  846. return self.extra_args.get(language, [])
  847. def get_dependencies(self, exclude=None, internal=True):
  848. transitive_deps = []
  849. if exclude is None:
  850. exclude = []
  851. if internal:
  852. link_targets = itertools.chain(self.link_targets, self.link_whole_targets)
  853. else:
  854. # We don't want the 'internal' libraries when generating the
  855. # `Libs:` and `Libs.private:` lists in pkg-config files.
  856. link_targets = self.link_targets
  857. for t in link_targets:
  858. if t in transitive_deps or t in exclude:
  859. continue
  860. transitive_deps.append(t)
  861. if isinstance(t, StaticLibrary):
  862. transitive_deps += t.get_dependencies(transitive_deps + exclude, internal)
  863. return transitive_deps
  864. def get_source_subdir(self):
  865. return self.subdir
  866. def get_sources(self):
  867. return self.sources
  868. def get_objects(self):
  869. return self.objects
  870. def get_generated_sources(self):
  871. return self.generated
  872. def should_install(self):
  873. return self.need_install
  874. def has_pch(self):
  875. return len(self.pch) > 0
  876. def get_pch(self, language):
  877. try:
  878. return self.pch[language]
  879. except KeyError:
  880. return[]
  881. def get_include_dirs(self):
  882. return self.include_dirs
  883. def add_deps(self, deps):
  884. deps = listify(deps)
  885. for dep in deps:
  886. if hasattr(dep, 'held_object'):
  887. dep = dep.held_object
  888. if isinstance(dep, dependencies.InternalDependency):
  889. # Those parts that are internal.
  890. self.process_sourcelist(dep.sources)
  891. self.add_include_dirs(dep.include_directories)
  892. for l in dep.libraries:
  893. self.link(l)
  894. for l in dep.whole_libraries:
  895. self.link_whole(l)
  896. if dep.compile_args or dep.link_args:
  897. # Those parts that are external.
  898. extpart = dependencies.InternalDependency('undefined',
  899. [],
  900. dep.compile_args,
  901. dep.link_args,
  902. [], [], [], [])
  903. self.external_deps.append(extpart)
  904. # Deps of deps.
  905. self.add_deps(dep.ext_deps)
  906. elif isinstance(dep, dependencies.Dependency):
  907. self.external_deps.append(dep)
  908. self.process_sourcelist(dep.get_sources())
  909. elif isinstance(dep, BuildTarget):
  910. raise InvalidArguments('''Tried to use a build target as a dependency.
  911. You probably should put it in link_with instead.''')
  912. else:
  913. # This is a bit of a hack. We do not want Build to know anything
  914. # about the interpreter so we can't import it and use isinstance.
  915. # This should be reliable enough.
  916. if hasattr(dep, 'project_args_frozen') or hasattr(dep, 'global_args_frozen'):
  917. raise InvalidArguments('Tried to use subproject object as a dependency.\n'
  918. 'You probably wanted to use a dependency declared in it instead.\n'
  919. 'Access it by calling get_variable() on the subproject object.')
  920. raise InvalidArguments('Argument is of an unacceptable type {!r}.\nMust be '
  921. 'either an external dependency (returned by find_library() or '
  922. 'dependency()) or an internal dependency (returned by '
  923. 'declare_dependency()).'.format(type(dep).__name__))
  924. def get_external_deps(self):
  925. return self.external_deps
  926. def link(self, target):
  927. for t in listify(target, unholder=True):
  928. if not isinstance(t, Target):
  929. raise InvalidArguments('{!r} is not a target.'.format(t))
  930. if not t.is_linkable_target():
  931. raise InvalidArguments('Link target {!r} is not linkable.'.format(t))
  932. if isinstance(self, SharedLibrary) and isinstance(t, StaticLibrary) and not t.pic:
  933. msg = "Can't link non-PIC static library {!r} into shared library {!r}. ".format(t.name, self.name)
  934. msg += "Use the 'pic' option to static_library to build with PIC."
  935. raise InvalidArguments(msg)
  936. if self.is_cross != t.is_cross:
  937. raise InvalidArguments('Tried to mix cross built and native libraries in target {!r}'.format(self.name))
  938. self.link_targets.append(t)
  939. def link_whole(self, target):
  940. for t in listify(target, unholder=True):
  941. if not isinstance(t, StaticLibrary):
  942. raise InvalidArguments('{!r} is not a static library.'.format(t))
  943. if isinstance(self, SharedLibrary) and not t.pic:
  944. msg = "Can't link non-PIC static library {!r} into shared library {!r}. ".format(t.name, self.name)
  945. msg += "Use the 'pic' option to static_library to build with PIC."
  946. raise InvalidArguments(msg)
  947. if self.is_cross != t.is_cross:
  948. raise InvalidArguments('Tried to mix cross built and native libraries in target {!r}'.format(self.name))
  949. self.link_whole_targets.append(t)
  950. def add_pch(self, language, pchlist):
  951. if not pchlist:
  952. return
  953. elif len(pchlist) == 1:
  954. if not environment.is_header(pchlist[0]):
  955. raise InvalidArguments('PCH argument %s is not a header.' % pchlist[0])
  956. elif len(pchlist) == 2:
  957. if environment.is_header(pchlist[0]):
  958. if not environment.is_source(pchlist[1]):
  959. raise InvalidArguments('PCH definition must contain one header and at most one source.')
  960. elif environment.is_source(pchlist[0]):
  961. if not environment.is_header(pchlist[1]):
  962. raise InvalidArguments('PCH definition must contain one header and at most one source.')
  963. pchlist = [pchlist[1], pchlist[0]]
  964. else:
  965. raise InvalidArguments('PCH argument %s is of unknown type.' % pchlist[0])
  966. if (os.path.dirname(pchlist[0]) != os.path.dirname(pchlist[1])):
  967. raise InvalidArguments('PCH files must be stored in the same folder.')
  968. elif len(pchlist) > 2:
  969. raise InvalidArguments('PCH definition may have a maximum of 2 files.')
  970. for f in pchlist:
  971. if not os.path.isfile(os.path.join(self.environment.source_dir, self.subdir, f)):
  972. raise MesonException('File %s does not exist.' % f)
  973. self.pch[language] = pchlist
  974. def add_include_dirs(self, args):
  975. ids = []
  976. for a in args:
  977. # FIXME same hack, forcibly unpack from holder.
  978. if hasattr(a, 'held_object'):
  979. a = a.held_object
  980. if not isinstance(a, IncludeDirs):
  981. raise InvalidArguments('Include directory to be added is not an include directory object.')
  982. ids.append(a)
  983. self.include_dirs += ids
  984. def add_compiler_args(self, language, args):
  985. args = listify(args)
  986. for a in args:
  987. if not isinstance(a, (str, File)):
  988. raise InvalidArguments('A non-string passed to compiler args.')
  989. if language in self.extra_args:
  990. self.extra_args[language] += args
  991. else:
  992. self.extra_args[language] = args
  993. def get_aliases(self):
  994. return {}
  995. def get_langs_used_by_deps(self):
  996. '''
  997. Sometimes you want to link to a C++ library that exports C API, which
  998. means the linker must link in the C++ stdlib, and we must use a C++
  999. compiler for linking. The same is also applicable for objc/objc++, etc,
  1000. so we can keep using clink_langs for the priority order.
  1001. See: https://github.com/mesonbuild/meson/issues/1653
  1002. '''
  1003. langs = []
  1004. # Check if any of the external libraries were written in this language
  1005. for dep in self.external_deps:
  1006. if dep.language is None:
  1007. continue
  1008. if dep.language not in langs:
  1009. langs.append(dep.language)
  1010. # Check if any of the internal libraries this target links to were
  1011. # written in this language
  1012. for link_target in itertools.chain(self.link_targets, self.link_whole_targets):
  1013. for language in link_target.compilers:
  1014. if language not in langs:
  1015. langs.append(language)
  1016. return langs
  1017. def get_clink_dynamic_linker_and_stdlibs(self):
  1018. '''
  1019. We use the order of languages in `clink_langs` to determine which
  1020. linker to use in case the target has sources compiled with multiple
  1021. compilers. All languages other than those in this list have their own
  1022. linker.
  1023. Note that Vala outputs C code, so Vala sources can use any linker
  1024. that can link compiled C. We don't actually need to add an exception
  1025. for Vala here because of that.
  1026. '''
  1027. # Populate list of all compilers, not just those being used to compile
  1028. # sources in this target
  1029. if self.is_cross:
  1030. all_compilers = self.environment.coredata.cross_compilers
  1031. else:
  1032. all_compilers = self.environment.coredata.compilers
  1033. # Languages used by dependencies
  1034. dep_langs = self.get_langs_used_by_deps()
  1035. # Pick a compiler based on the language priority-order
  1036. for l in clink_langs:
  1037. if l in self.compilers or l in dep_langs:
  1038. try:
  1039. linker = all_compilers[l]
  1040. except KeyError:
  1041. raise MesonException(
  1042. 'Could not get a dynamic linker for build target {!r}. '
  1043. 'Requires a linker for language "{}", but that is not '
  1044. 'a project language.'.format(self.name, l))
  1045. stdlib_args = []
  1046. added_languages = set()
  1047. for dl in itertools.chain(self.compilers, dep_langs):
  1048. if dl != linker.language:
  1049. stdlib_args += all_compilers[dl].language_stdlib_only_link_flags()
  1050. added_languages.add(dl)
  1051. return linker, stdlib_args
  1052. m = 'Could not get a dynamic linker for build target {!r}'
  1053. raise AssertionError(m.format(self.name))
  1054. def get_using_msvc(self):
  1055. '''
  1056. Check if the dynamic linker is MSVC. Used by Executable, StaticLibrary,
  1057. and SharedLibrary for deciding when to use MSVC-specific file naming
  1058. and debug filenames.
  1059. If at least some code is built with MSVC and the final library is
  1060. linked with MSVC, we can be sure that some debug info will be
  1061. generated. We only check the dynamic linker here because the static
  1062. linker is guaranteed to be of the same type.
  1063. Interesting cases:
  1064. 1. The Vala compiler outputs C code to be compiled by whatever
  1065. C compiler we're using, so all objects will still be created by the
  1066. MSVC compiler.
  1067. 2. If the target contains only objects, process_compilers guesses and
  1068. picks the first compiler that smells right.
  1069. '''
  1070. linker, _ = self.get_clink_dynamic_linker_and_stdlibs()
  1071. # Mixing many languages with MSVC is not supported yet so ignore stdlibs.
  1072. if linker and linker.get_id() in ['msvc', 'clang-cl', 'llvm', 'dmd']:
  1073. return True
  1074. return False
  1075. def check_module_linking(self):
  1076. '''
  1077. Warn if shared modules are linked with target: (link_with) #2865
  1078. '''
  1079. for link_target in self.link_targets:
  1080. if isinstance(link_target, SharedModule):
  1081. if for_darwin(self.is_cross, self.environment):
  1082. raise MesonException('''target links against shared modules.
  1083. This is not permitted on OSX''')
  1084. else:
  1085. mlog.warning('''target links against shared modules. This is not
  1086. recommended as it is not supported on some platforms''')
  1087. return
  1088. class Generator:
  1089. def __init__(self, args, kwargs):
  1090. if len(args) != 1:
  1091. raise InvalidArguments('Generator requires exactly one positional argument: the executable')
  1092. exe = args[0]
  1093. if hasattr(exe, 'held_object'):
  1094. exe = exe.held_object
  1095. if not isinstance(exe, (Executable, dependencies.ExternalProgram)):
  1096. raise InvalidArguments('First generator argument must be an executable.')
  1097. self.exe = exe
  1098. self.depfile = None
  1099. self.capture = False
  1100. self.process_kwargs(kwargs)
  1101. def __repr__(self):
  1102. repr_str = "<{0}: {1}>"
  1103. return repr_str.format(self.__class__.__name__, self.exe)
  1104. def get_exe(self):
  1105. return self.exe
  1106. def process_kwargs(self, kwargs):
  1107. if 'arguments' not in kwargs:
  1108. raise InvalidArguments('Generator must have "arguments" keyword argument.')
  1109. args = kwargs['arguments']
  1110. if isinstance(args, str):
  1111. args = [args]
  1112. if not isinstance(args, list):
  1113. raise InvalidArguments('"Arguments" keyword argument must be a string or a list of strings.')
  1114. for a in args:
  1115. if not isinstance(a, str):
  1116. raise InvalidArguments('A non-string object in "arguments" keyword argument.')
  1117. self.arglist = args
  1118. if 'output' not in kwargs:
  1119. raise InvalidArguments('Generator must have "output" keyword argument.')
  1120. outputs = listify(kwargs['output'])
  1121. for rule in outputs:
  1122. if not isinstance(rule, str):
  1123. raise InvalidArguments('"output" may only contain strings.')
  1124. if '@BASENAME@' not in rule and '@PLAINNAME@' not in rule:
  1125. raise InvalidArguments('Every element of "output" must contain @BASENAME@ or @PLAINNAME@.')
  1126. if has_path_sep(rule):
  1127. raise InvalidArguments('"outputs" must not contain a directory separator.')
  1128. if len(outputs) > 1:
  1129. for o in outputs:
  1130. if '@OUTPUT@' in o:
  1131. raise InvalidArguments('Tried to use @OUTPUT@ in a rule with more than one output.')
  1132. self.outputs = outputs
  1133. if 'depfile' in kwargs:
  1134. depfile = kwargs['depfile']
  1135. if not isinstance(depfile, str):
  1136. raise InvalidArguments('Depfile must be a string.')
  1137. if os.path.basename(depfile) != depfile:
  1138. raise InvalidArguments('Depfile must be a plain filename without a subdirectory.')
  1139. self.depfile = depfile
  1140. if 'capture' in kwargs:
  1141. capture = kwargs['capture']
  1142. if not isinstance(capture, bool):
  1143. raise InvalidArguments('Capture must be boolean.')
  1144. self.capture = capture
  1145. def get_base_outnames(self, inname):
  1146. plainname = os.path.basename(inname)
  1147. basename = os.path.splitext(plainname)[0]
  1148. bases = [x.replace('@BASENAME@', basename).replace('@PLAINNAME@', plainname) for x in self.outputs]
  1149. return bases
  1150. def get_dep_outname(self, inname):
  1151. if self.depfile is None:
  1152. raise InvalidArguments('Tried to get dep name for rule that does not have dependency file defined.')
  1153. plainname = os.path.basename(inname)
  1154. basename = os.path.splitext(plainname)[0]
  1155. return self.depfile.replace('@BASENAME@', basename).replace('@PLAINNAME@', plainname)
  1156. def get_arglist(self, inname):
  1157. plainname = os.path.basename(inname)
  1158. basename = os.path.splitext(plainname)[0]
  1159. return [x.replace('@BASENAME@', basename).replace('@PLAINNAME@', plainname) for x in self.arglist]
  1160. def is_parent_path(self, parent, trial):
  1161. relpath = pathlib.PurePath(trial).relative_to(parent)
  1162. return relpath.parts[0] != '..' # For subdirs we can only go "down".
  1163. def process_files(self, name, files, state, preserve_path_from=None, extra_args=[]):
  1164. output = GeneratedList(self, state.subdir, preserve_path_from, extra_args=extra_args)
  1165. for f in files:
  1166. if isinstance(f, str):
  1167. f = File.from_source_file(state.environment.source_dir, state.subdir, f)
  1168. elif not isinstance(f, File):
  1169. raise InvalidArguments('{} arguments must be strings or files not {!r}.'.format(name, f))
  1170. if preserve_path_from:
  1171. abs_f = f.absolute_path(state.environment.source_dir, state.environment.build_dir)
  1172. if not self.is_parent_path(preserve_path_from, abs_f):
  1173. raise InvalidArguments('When using preserve_path_from, all input files must be in a subdirectory of the given dir.')
  1174. output.add_file(f, state)
  1175. return output
  1176. class GeneratedList:
  1177. def __init__(self, generator, subdir, preserve_path_from=None, extra_args=[]):
  1178. if hasattr(generator, 'held_object'):
  1179. generator = generator.held_object
  1180. self.generator = generator
  1181. self.name = self.generator.exe
  1182. self.subdir = subdir
  1183. self.infilelist = []
  1184. self.outfilelist = []
  1185. self.outmap = {}
  1186. self.extra_depends = []
  1187. self.preserve_path_from = preserve_path_from
  1188. self.extra_args = extra_args
  1189. def add_preserved_path_segment(self, infile, outfiles, state):
  1190. result = []
  1191. in_abs = infile.absolute_path(state.environment.source_dir, state.environment.build_dir)
  1192. assert(os.path.isabs(self.preserve_path_from))
  1193. rel = os.path.relpath(in_abs, self.preserve_path_from)
  1194. path_segment = os.path.dirname(rel)
  1195. for of in outfiles:
  1196. result.append(os.path.join(path_segment, of))
  1197. return result
  1198. def add_file(self, newfile, state):
  1199. self.infilelist.append(newfile)
  1200. outfiles = self.generator.get_base_outnames(newfile.fname)
  1201. if self.preserve_path_from:
  1202. outfiles = self.add_preserved_path_segment(newfile, outfiles, state)
  1203. self.outfilelist += outfiles
  1204. self.outmap[newfile] = outfiles
  1205. def get_inputs(self):
  1206. return self.infilelist
  1207. def get_outputs(self):
  1208. return self.outfilelist
  1209. def get_outputs_for(self, filename):
  1210. return self.outmap[filename]
  1211. def get_generator(self):
  1212. return self.generator
  1213. def get_extra_args(self):
  1214. return self.extra_args
  1215. class Executable(BuildTarget):
  1216. known_kwargs = known_exe_kwargs
  1217. def __init__(self, name, subdir, subproject, is_cross, sources, objects, environment, kwargs):
  1218. self.typename = 'executable'
  1219. if 'pie' not in kwargs and 'b_pie' in environment.coredata.base_options:
  1220. kwargs['pie'] = environment.coredata.base_options['b_pie'].value
  1221. super().__init__(name, subdir, subproject, is_cross, sources, objects, environment, kwargs)
  1222. # Unless overridden, executables have no suffix or prefix. Except on
  1223. # Windows and with C#/Mono executables where the suffix is 'exe'
  1224. if not hasattr(self, 'prefix'):
  1225. self.prefix = ''
  1226. if not hasattr(self, 'suffix'):
  1227. # Executable for Windows or C#/Mono
  1228. if (for_windows(is_cross, environment) or
  1229. for_cygwin(is_cross, environment) or 'cs' in self.compilers):
  1230. self.suffix = 'exe'
  1231. elif ('c' in self.compilers and self.compilers['c'].get_id().startswith('arm') or
  1232. 'cpp' in self.compilers and self.compilers['cpp'].get_id().startswith('arm')):
  1233. self.suffix = 'axf'
  1234. elif ('c' in self.compilers and self.compilers['c'].get_id().startswith('ccrx') or
  1235. 'cpp' in self.compilers and self.compilers['cpp'].get_id().startswith('ccrx')):
  1236. self.suffix = 'abs'
  1237. else:
  1238. self.suffix = ''
  1239. self.filename = self.name
  1240. if self.suffix:
  1241. self.filename += '.' + self.suffix
  1242. self.outputs = [self.filename]
  1243. # The import library this target will generate
  1244. self.import_filename = None
  1245. # The import library that Visual Studio would generate (and accept)
  1246. self.vs_import_filename = None
  1247. # The import library that GCC would generate (and prefer)
  1248. self.gcc_import_filename = None
  1249. # Check for export_dynamic
  1250. self.export_dynamic = False
  1251. if kwargs.get('export_dynamic'):
  1252. if not isinstance(kwargs['export_dynamic'], bool):
  1253. raise InvalidArguments('"export_dynamic" keyword argument must be a boolean')
  1254. self.export_dynamic = True
  1255. if kwargs.get('implib'):
  1256. self.export_dynamic = True
  1257. if self.export_dynamic and kwargs.get('implib') is False:
  1258. raise InvalidArguments('"implib" keyword argument must not be false for if "export_dynamic" is true')
  1259. # If using export_dynamic, set the import library name
  1260. if self.export_dynamic:
  1261. implib_basename = self.name + '.exe'
  1262. if not isinstance(kwargs.get('implib', False), bool):
  1263. implib_basename = kwargs['implib']
  1264. if for_windows(is_cross, environment) or for_cygwin(is_cross, environment):
  1265. self.vs_import_filename = '{0}.lib'.format(implib_basename)
  1266. self.gcc_import_filename = 'lib{0}.a'.format(implib_basename)
  1267. if self.get_using_msvc():
  1268. self.import_filename = self.vs_import_filename
  1269. else:
  1270. self.import_filename = self.gcc_import_filename
  1271. # Only linkwithable if using export_dynamic
  1272. self.is_linkwithable = self.export_dynamic
  1273. def get_default_install_dir(self, environment):
  1274. return environment.get_bindir()
  1275. def description(self):
  1276. '''Human friendly description of the executable'''
  1277. return self.name
  1278. def type_suffix(self):
  1279. return "@exe"
  1280. def get_import_filename(self):
  1281. """
  1282. The name of the import library that will be outputted by the compiler
  1283. Returns None if there is no import library required for this platform
  1284. """
  1285. return self.import_filename
  1286. def get_import_filenameslist(self):
  1287. if self.import_filename:
  1288. return [self.vs_import_filename, self.gcc_import_filename]
  1289. return []
  1290. def is_linkable_target(self):
  1291. return self.is_linkwithable
  1292. class StaticLibrary(BuildTarget):
  1293. known_kwargs = known_stlib_kwargs
  1294. def __init__(self, name, subdir, subproject, is_cross, sources, objects, environment, kwargs):
  1295. self.typename = 'static library'
  1296. if 'pic' not in kwargs and 'b_staticpic' in environment.coredata.base_options:
  1297. kwargs['pic'] = environment.coredata.base_options['b_staticpic'].value
  1298. super().__init__(name, subdir, subproject, is_cross, sources, objects, environment, kwargs)
  1299. if 'cs' in self.compilers:
  1300. raise InvalidArguments('Static libraries not supported for C#.')
  1301. if 'rust' in self.compilers:
  1302. # If no crate type is specified, or it's the generic lib type, use rlib
  1303. if not hasattr(self, 'rust_crate_type') or self.rust_crate_type == 'lib':
  1304. mlog.debug('Defaulting Rust static library target crate type to rlib')
  1305. self.rust_crate_type = 'rlib'
  1306. # Don't let configuration proceed with a non-static crate type
  1307. elif self.rust_crate_type not in ['rlib', 'staticlib']:
  1308. raise InvalidArguments('Crate type "{0}" invalid for static libraries; must be "rlib" or "staticlib"'.format(self.rust_crate_type))
  1309. # By default a static library is named libfoo.a even on Windows because
  1310. # MSVC does not have a consistent convention for what static libraries
  1311. # are called. The MSVC CRT uses libfoo.lib syntax but nothing else uses
  1312. # it and GCC only looks for static libraries called foo.lib and
  1313. # libfoo.a. However, we cannot use foo.lib because that's the same as
  1314. # the import library. Using libfoo.a is ok because people using MSVC
  1315. # always pass the library filename while linking anyway.
  1316. if not hasattr(self, 'prefix'):
  1317. self.prefix = 'lib'
  1318. if not hasattr(self, 'suffix'):
  1319. if 'rust' in self.compilers:
  1320. if not hasattr(self, 'rust_crate_type') or self.rust_crate_type == 'rlib':
  1321. # default Rust static library suffix
  1322. self.suffix = 'rlib'
  1323. elif self.rust_crate_type == 'staticlib':
  1324. self.suffix = 'a'
  1325. else:
  1326. self.suffix = 'a'
  1327. self.filename = self.prefix + self.name + '.' + self.suffix
  1328. self.outputs = [self.filename]
  1329. def get_link_deps_mapping(self, prefix, environment):
  1330. return {}
  1331. def get_default_install_dir(self, environment):
  1332. return environment.get_static_lib_dir()
  1333. def type_suffix(self):
  1334. return "@sta"
  1335. def process_kwargs(self, kwargs, environment):
  1336. super().process_kwargs(kwargs, environment)
  1337. if 'rust_crate_type' in kwargs:
  1338. rust_crate_type = kwargs['rust_crate_type']
  1339. if isinstance(rust_crate_type, str):
  1340. self.rust_crate_type = rust_crate_type
  1341. else:
  1342. raise InvalidArguments('Invalid rust_crate_type "{0}": must be a string.'.format(rust_crate_type))
  1343. def is_linkable_target(self):
  1344. return True
  1345. class SharedLibrary(BuildTarget):
  1346. known_kwargs = known_shlib_kwargs
  1347. def __init__(self, name, subdir, subproject, is_cross, sources, objects, environment, kwargs):
  1348. self.typename = 'shared library'
  1349. self.soversion = None
  1350. self.ltversion = None
  1351. # Max length 2, first element is compatibility_version, second is current_version
  1352. self.darwin_versions = []
  1353. self.vs_module_defs = None
  1354. # The import library this target will generate
  1355. self.import_filename = None
  1356. # The import library that Visual Studio would generate (and accept)
  1357. self.vs_import_filename = None
  1358. # The import library that GCC would generate (and prefer)
  1359. self.gcc_import_filename = None
  1360. super().__init__(name, subdir, subproject, is_cross, sources, objects, environment, kwargs)
  1361. if 'rust' in self.compilers:
  1362. # If no crate type is specified, or it's the generic lib type, use dylib
  1363. if not hasattr(self, 'rust_crate_type') or self.rust_crate_type == 'lib':
  1364. mlog.debug('Defaulting Rust dynamic library target crate type to "dylib"')
  1365. self.rust_crate_type = 'dylib'
  1366. # Don't let configuration proceed with a non-dynamic crate type
  1367. elif self.rust_crate_type not in ['dylib', 'cdylib']:
  1368. raise InvalidArguments('Crate type "{0}" invalid for dynamic libraries; must be "dylib" or "cdylib"'.format(self.rust_crate_type))
  1369. if not hasattr(self, 'prefix'):
  1370. self.prefix = None
  1371. if not hasattr(self, 'suffix'):
  1372. self.suffix = None
  1373. self.basic_filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
  1374. self.determine_filenames(is_cross, environment)
  1375. def get_link_deps_mapping(self, prefix, environment):
  1376. result = {}
  1377. mappings = self.get_transitive_link_deps_mapping(prefix, environment)
  1378. old = get_target_macos_dylib_install_name(self)
  1379. if old not in mappings:
  1380. fname = self.get_filename()
  1381. outdirs, _ = self.get_install_dir(self.environment)
  1382. new = os.path.join(prefix, outdirs[0], fname)
  1383. result.update({old: new})
  1384. mappings.update(result)
  1385. return mappings
  1386. def get_default_install_dir(self, environment):
  1387. return environment.get_shared_lib_dir()
  1388. def determine_filenames(self, is_cross, env):
  1389. """
  1390. See https://github.com/mesonbuild/meson/pull/417 for details.
  1391. First we determine the filename template (self.filename_tpl), then we
  1392. set the output filename (self.filename).
  1393. The template is needed while creating aliases (self.get_aliases),
  1394. which are needed while generating .so shared libraries for Linux.
  1395. Besides this, there's also the import library name, which is only used
  1396. on Windows since on that platform the linker uses a separate library
  1397. called the "import library" during linking instead of the shared
  1398. library (DLL). The toolchain will output an import library in one of
  1399. two formats: GCC or Visual Studio.
  1400. When we're building with Visual Studio, the import library that will be
  1401. generated by the toolchain is self.vs_import_filename, and with
  1402. MinGW/GCC, it's self.gcc_import_filename. self.import_filename will
  1403. always contain the import library name this target will generate.
  1404. """
  1405. prefix = ''
  1406. suffix = ''
  1407. self.filename_tpl = self.basic_filename_tpl
  1408. # NOTE: manual prefix/suffix override is currently only tested for C/C++
  1409. # C# and Mono
  1410. if 'cs' in self.compilers:
  1411. prefix = ''
  1412. suffix = 'dll'
  1413. self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
  1414. # C, C++, Swift, Vala
  1415. # Only Windows uses a separate import library for linking
  1416. # For all other targets/platforms import_filename stays None
  1417. elif for_windows(is_cross, env):
  1418. suffix = 'dll'
  1419. self.vs_import_filename = '{0}{1}.lib'.format(self.prefix if self.prefix is not None else '', self.name)
  1420. self.gcc_import_filename = '{0}{1}.dll.a'.format(self.prefix if self.prefix is not None else 'lib', self.name)
  1421. if self.get_using_msvc():
  1422. # Shared library is of the form foo.dll
  1423. prefix = ''
  1424. # Import library is called foo.lib
  1425. self.import_filename = self.vs_import_filename
  1426. # Assume GCC-compatible naming
  1427. else:
  1428. # Shared library is of the form libfoo.dll
  1429. prefix = 'lib'
  1430. # Import library is called libfoo.dll.a
  1431. self.import_filename = self.gcc_import_filename
  1432. # Shared library has the soversion if it is defined
  1433. if self.soversion:
  1434. self.filename_tpl = '{0.prefix}{0.name}-{0.soversion}.{0.suffix}'
  1435. else:
  1436. self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
  1437. elif for_cygwin(is_cross, env):
  1438. suffix = 'dll'
  1439. self.gcc_import_filename = '{0}{1}.dll.a'.format(self.prefix if self.prefix is not None else 'lib', self.name)
  1440. # Shared library is of the form cygfoo.dll
  1441. # (ld --dll-search-prefix=cyg is the default)
  1442. prefix = 'cyg'
  1443. # Import library is called libfoo.dll.a
  1444. self.import_filename = self.gcc_import_filename
  1445. if self.soversion:
  1446. self.filename_tpl = '{0.prefix}{0.name}-{0.soversion}.{0.suffix}'
  1447. else:
  1448. self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
  1449. elif for_darwin(is_cross, env):
  1450. prefix = 'lib'
  1451. suffix = 'dylib'
  1452. # On macOS, the filename can only contain the major version
  1453. if self.soversion:
  1454. # libfoo.X.dylib
  1455. self.filename_tpl = '{0.prefix}{0.name}.{0.soversion}.{0.suffix}'
  1456. else:
  1457. # libfoo.dylib
  1458. self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
  1459. elif for_android(is_cross, env):
  1460. prefix = 'lib'
  1461. suffix = 'so'
  1462. # Android doesn't support shared_library versioning
  1463. self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
  1464. else:
  1465. prefix = 'lib'
  1466. suffix = 'so'
  1467. if self.ltversion:
  1468. # libfoo.so.X[.Y[.Z]] (.Y and .Z are optional)
  1469. self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}.{0.ltversion}'
  1470. elif self.soversion:
  1471. # libfoo.so.X
  1472. self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}.{0.soversion}'
  1473. else:
  1474. # No versioning, libfoo.so
  1475. self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
  1476. if self.prefix is None:
  1477. self.prefix = prefix
  1478. if self.suffix is None:
  1479. self.suffix = suffix
  1480. self.filename = self.filename_tpl.format(self)
  1481. self.outputs = [self.filename]
  1482. @staticmethod
  1483. def _validate_darwin_versions(darwin_versions):
  1484. try:
  1485. if isinstance(darwin_versions, int):
  1486. darwin_versions = str(darwin_versions)
  1487. if isinstance(darwin_versions, str):
  1488. darwin_versions = 2 * [darwin_versions]
  1489. if not isinstance(darwin_versions, list):
  1490. raise InvalidArguments('Shared library darwin_versions: must be a string, integer,'
  1491. 'or a list, not {!r}'.format(darwin_versions))
  1492. if len(darwin_versions) > 2:
  1493. raise InvalidArguments('Shared library darwin_versions: list must contain 2 or fewer elements')
  1494. if len(darwin_versions) == 1:
  1495. darwin_versions = 2 * darwin_versions
  1496. for i, v in enumerate(darwin_versions[:]):
  1497. if isinstance(v, int):
  1498. v = str(v)
  1499. if not isinstance(v, str):
  1500. raise InvalidArguments('Shared library darwin_versions: list elements '
  1501. 'must be strings or integers, not {!r}'.format(v))
  1502. if not re.fullmatch(r'[0-9]+(\.[0-9]+){0,2}', v):
  1503. raise InvalidArguments('Shared library darwin_versions: must be X.Y.Z where '
  1504. 'X, Y, Z are numbers, and Y and Z are optional')
  1505. parts = v.split('.')
  1506. if len(parts) in (1, 2, 3) and int(parts[0]) > 65535:
  1507. raise InvalidArguments('Shared library darwin_versions: must be X.Y.Z '
  1508. 'where X is [0, 65535] and Y, Z are optional')
  1509. if len(parts) in (2, 3) and int(parts[1]) > 255:
  1510. raise InvalidArguments('Shared library darwin_versions: must be X.Y.Z '
  1511. 'where Y is [0, 255] and Y, Z are optional')
  1512. if len(parts) == 3 and int(parts[2]) > 255:
  1513. raise InvalidArguments('Shared library darwin_versions: must be X.Y.Z '
  1514. 'where Z is [0, 255] and Y, Z are optional')
  1515. darwin_versions[i] = v
  1516. except ValueError:
  1517. raise InvalidArguments('Shared library darwin_versions: value is invalid')
  1518. return darwin_versions
  1519. def process_kwargs(self, kwargs, environment):
  1520. super().process_kwargs(kwargs, environment)
  1521. if not for_android(self.is_cross, self.environment):
  1522. supports_versioning = True
  1523. else:
  1524. supports_versioning = False
  1525. if supports_versioning:
  1526. # Shared library version
  1527. if 'version' in kwargs:
  1528. self.ltversion = kwargs['version']
  1529. if not isinstance(self.ltversion, str):
  1530. raise InvalidArguments('Shared library version needs to be a string, not ' + type(self.ltversion).__name__)
  1531. if not re.fullmatch(r'[0-9]+(\.[0-9]+){0,2}', self.ltversion):
  1532. raise InvalidArguments('Invalid Shared library version "{0}". Must be of the form X.Y.Z where all three are numbers. Y and Z are optional.'.format(self.ltversion))
  1533. # Try to extract/deduce the soversion
  1534. if 'soversion' in kwargs:
  1535. self.soversion = kwargs['soversion']
  1536. if isinstance(self.soversion, int):
  1537. self.soversion = str(self.soversion)
  1538. if not isinstance(self.soversion, str):
  1539. raise InvalidArguments('Shared library soversion is not a string or integer.')
  1540. elif self.ltversion:
  1541. # library version is defined, get the soversion from that
  1542. # We replicate what Autotools does here and take the first
  1543. # number of the version by default.
  1544. self.soversion = self.ltversion.split('.')[0]
  1545. # macOS and iOS dylib compatibility_version and current_version
  1546. if 'darwin_versions' in kwargs:
  1547. self.darwin_versions = self._validate_darwin_versions(kwargs['darwin_versions'])
  1548. elif self.soversion:
  1549. # If unspecified, pick the soversion
  1550. self.darwin_versions = 2 * [self.soversion]
  1551. # Visual Studio module-definitions file
  1552. if 'vs_module_defs' in kwargs:
  1553. path = kwargs['vs_module_defs']
  1554. if hasattr(path, 'held_object'):
  1555. path = path.held_object
  1556. if isinstance(path, str):
  1557. if os.path.isabs(path):
  1558. self.vs_module_defs = File.from_absolute_file(path)
  1559. else:
  1560. self.vs_module_defs = File.from_source_file(environment.source_dir, self.subdir, path)
  1561. self.link_depends.append(self.vs_module_defs)
  1562. elif isinstance(path, File):
  1563. # When passing a generated file.
  1564. self.vs_module_defs = path
  1565. self.link_depends.append(path)
  1566. elif hasattr(path, 'get_filename'):
  1567. # When passing output of a Custom Target
  1568. path = File.from_built_file(path.subdir, path.get_filename())
  1569. self.vs_module_defs = path
  1570. self.link_depends.append(path)
  1571. else:
  1572. raise InvalidArguments(
  1573. 'Shared library vs_module_defs must be either a string, '
  1574. 'a file object or a Custom Target')
  1575. if 'rust_crate_type' in kwargs:
  1576. rust_crate_type = kwargs['rust_crate_type']
  1577. if isinstance(rust_crate_type, str):
  1578. self.rust_crate_type = rust_crate_type
  1579. else:
  1580. raise InvalidArguments('Invalid rust_crate_type "{0}": must be a string.'.format(rust_crate_type))
  1581. def get_import_filename(self):
  1582. """
  1583. The name of the import library that will be outputted by the compiler
  1584. Returns None if there is no import library required for this platform
  1585. """
  1586. return self.import_filename
  1587. def get_import_filenameslist(self):
  1588. if self.import_filename:
  1589. return [self.vs_import_filename, self.gcc_import_filename]
  1590. return []
  1591. def get_all_link_deps(self):
  1592. return [self] + self.get_transitive_link_deps()
  1593. def get_aliases(self):
  1594. """
  1595. If the versioned library name is libfoo.so.0.100.0, aliases are:
  1596. * libfoo.so.0 (soversion) -> libfoo.so.0.100.0
  1597. * libfoo.so (unversioned; for linking) -> libfoo.so.0
  1598. Same for dylib:
  1599. * libfoo.dylib (unversioned; for linking) -> libfoo.0.dylib
  1600. """
  1601. aliases = {}
  1602. # Aliases are only useful with .so and .dylib libraries. Also if
  1603. # there's no self.soversion (no versioning), we don't need aliases.
  1604. if self.suffix not in ('so', 'dylib') or not self.soversion:
  1605. return {}
  1606. # With .so libraries, the minor and micro versions are also in the
  1607. # filename. If ltversion != soversion we create an soversion alias:
  1608. # libfoo.so.0 -> libfoo.so.0.100.0
  1609. # Where libfoo.so.0.100.0 is the actual library
  1610. if self.suffix == 'so' and self.ltversion and self.ltversion != self.soversion:
  1611. alias_tpl = self.filename_tpl.replace('ltversion', 'soversion')
  1612. ltversion_filename = alias_tpl.format(self)
  1613. aliases[ltversion_filename] = self.filename
  1614. # libfoo.so.0/libfoo.0.dylib is the actual library
  1615. else:
  1616. ltversion_filename = self.filename
  1617. # Unversioned alias:
  1618. # libfoo.so -> libfoo.so.0
  1619. # libfoo.dylib -> libfoo.0.dylib
  1620. aliases[self.basic_filename_tpl.format(self)] = ltversion_filename
  1621. return aliases
  1622. def type_suffix(self):
  1623. return "@sha"
  1624. def is_linkable_target(self):
  1625. return True
  1626. # A shared library that is meant to be used with dlopen rather than linking
  1627. # into something else.
  1628. class SharedModule(SharedLibrary):
  1629. known_kwargs = known_shmod_kwargs
  1630. def __init__(self, name, subdir, subproject, is_cross, sources, objects, environment, kwargs):
  1631. if 'version' in kwargs:
  1632. raise MesonException('Shared modules must not specify the version kwarg.')
  1633. if 'soversion' in kwargs:
  1634. raise MesonException('Shared modules must not specify the soversion kwarg.')
  1635. super().__init__(name, subdir, subproject, is_cross, sources, objects, environment, kwargs)
  1636. self.typename = 'shared module'
  1637. def get_default_install_dir(self, environment):
  1638. return environment.get_shared_module_dir()
  1639. class CustomTarget(Target):
  1640. known_kwargs = set([
  1641. 'input',
  1642. 'output',
  1643. 'command',
  1644. 'capture',
  1645. 'install',
  1646. 'install_dir',
  1647. 'install_mode',
  1648. 'build_always',
  1649. 'build_always_stale',
  1650. 'depends',
  1651. 'depend_files',
  1652. 'depfile',
  1653. 'build_by_default',
  1654. 'override_options',
  1655. 'console',
  1656. ])
  1657. def __init__(self, name, subdir, subproject, kwargs, absolute_paths=False):
  1658. self.typename = 'custom'
  1659. super().__init__(name, subdir, subproject, False)
  1660. self.dependencies = []
  1661. self.extra_depends = []
  1662. self.depend_files = [] # Files that this target depends on but are not on the command line.
  1663. self.depfile = None
  1664. self.process_kwargs(kwargs)
  1665. self.extra_files = []
  1666. # Whether to use absolute paths for all files on the commandline
  1667. self.absolute_paths = absolute_paths
  1668. unknowns = []
  1669. for k in kwargs:
  1670. if k not in CustomTarget.known_kwargs:
  1671. unknowns.append(k)
  1672. if len(unknowns) > 0:
  1673. mlog.warning('Unknown keyword arguments in target %s: %s' %
  1674. (self.name, ', '.join(unknowns)))
  1675. def get_default_install_dir(self, environment):
  1676. return None
  1677. def __lt__(self, other):
  1678. return self.get_id() < other.get_id()
  1679. def __repr__(self):
  1680. repr_str = "<{0} {1}: {2}>"
  1681. return repr_str.format(self.__class__.__name__, self.get_id(), self.command)
  1682. def get_id(self):
  1683. return self.name + self.type_suffix()
  1684. def get_target_dependencies(self):
  1685. deps = self.dependencies[:]
  1686. deps += self.extra_depends
  1687. for c in self.sources:
  1688. if hasattr(c, 'held_object'):
  1689. c = c.held_object
  1690. if isinstance(c, (BuildTarget, CustomTarget)):
  1691. deps.append(c)
  1692. return deps
  1693. def get_transitive_build_target_deps(self):
  1694. '''
  1695. Recursively fetch the build targets that this custom target depends on,
  1696. whether through `command:`, `depends:`, or `sources:` The recursion is
  1697. only performed on custom targets.
  1698. This is useful for setting PATH on Windows for finding required DLLs.
  1699. F.ex, if you have a python script that loads a C module that links to
  1700. other DLLs in your project.
  1701. '''
  1702. bdeps = set()
  1703. deps = self.get_target_dependencies()
  1704. for d in deps:
  1705. if isinstance(d, BuildTarget):
  1706. bdeps.add(d)
  1707. elif isinstance(d, CustomTarget):
  1708. bdeps.update(d.get_transitive_build_target_deps())
  1709. return bdeps
  1710. def flatten_command(self, cmd):
  1711. cmd = listify(cmd, unholder=True)
  1712. final_cmd = []
  1713. for c in cmd:
  1714. if isinstance(c, str):
  1715. final_cmd.append(c)
  1716. elif isinstance(c, File):
  1717. self.depend_files.append(c)
  1718. final_cmd.append(c)
  1719. elif isinstance(c, dependencies.ExternalProgram):
  1720. if not c.found():
  1721. m = 'Tried to use not-found external program {!r} in "command"'
  1722. raise InvalidArguments(m.format(c.name))
  1723. path = c.get_path()
  1724. if os.path.isabs(path):
  1725. # Can only add a dependency on an external program which we
  1726. # know the absolute path of
  1727. self.depend_files.append(File.from_absolute_file(path))
  1728. final_cmd += c.get_command()
  1729. elif isinstance(c, (BuildTarget, CustomTarget)):
  1730. self.dependencies.append(c)
  1731. final_cmd.append(c)
  1732. elif isinstance(c, list):
  1733. final_cmd += self.flatten_command(c)
  1734. else:
  1735. raise InvalidArguments('Argument {!r} in "command" is invalid'.format(c))
  1736. return final_cmd
  1737. def process_kwargs(self, kwargs):
  1738. super().process_kwargs(kwargs)
  1739. self.sources = extract_as_list(kwargs, 'input', unholder=True)
  1740. if 'output' not in kwargs:
  1741. raise InvalidArguments('Missing keyword argument "output".')
  1742. self.outputs = listify(kwargs['output'])
  1743. # This will substitute values from the input into output and return it.
  1744. inputs = get_sources_string_names(self.sources)
  1745. values = get_filenames_templates_dict(inputs, [])
  1746. for i in self.outputs:
  1747. if not(isinstance(i, str)):
  1748. raise InvalidArguments('Output argument not a string.')
  1749. if i == '':
  1750. raise InvalidArguments('Output must not be empty.')
  1751. if i.strip() == '':
  1752. raise InvalidArguments('Output must not consist only of whitespace.')
  1753. if has_path_sep(i):
  1754. raise InvalidArguments('Output {!r} must not contain a path segment.'.format(i))
  1755. if '@INPUT@' in i or '@INPUT0@' in i:
  1756. m = 'Output cannot contain @INPUT@ or @INPUT0@, did you ' \
  1757. 'mean @PLAINNAME@ or @BASENAME@?'
  1758. raise InvalidArguments(m)
  1759. # We already check this during substitution, but the error message
  1760. # will be unclear/confusing, so check it here.
  1761. if len(inputs) != 1 and ('@PLAINNAME@' in i or '@BASENAME@' in i):
  1762. m = "Output cannot contain @PLAINNAME@ or @BASENAME@ when " \
  1763. "there is more than one input (we can't know which to use)"
  1764. raise InvalidArguments(m)
  1765. self.outputs = substitute_values(self.outputs, values)
  1766. self.capture = kwargs.get('capture', False)
  1767. if self.capture and len(self.outputs) != 1:
  1768. raise InvalidArguments('Capturing can only output to a single file.')
  1769. self.console = kwargs.get('console', False)
  1770. if not isinstance(self.console, bool):
  1771. raise InvalidArguments('"console" kwarg only accepts booleans')
  1772. if self.capture and self.console:
  1773. raise InvalidArguments("Can't both capture output and output to console")
  1774. if 'command' not in kwargs:
  1775. raise InvalidArguments('Missing keyword argument "command".')
  1776. if 'depfile' in kwargs:
  1777. depfile = kwargs['depfile']
  1778. if not isinstance(depfile, str):
  1779. raise InvalidArguments('Depfile must be a string.')
  1780. if os.path.basename(depfile) != depfile:
  1781. raise InvalidArguments('Depfile must be a plain filename without a subdirectory.')
  1782. self.depfile = depfile
  1783. self.command = self.flatten_command(kwargs['command'])
  1784. if self.capture:
  1785. for c in self.command:
  1786. if isinstance(c, str) and '@OUTPUT@' in c:
  1787. raise InvalidArguments('@OUTPUT@ is not allowed when capturing output.')
  1788. if 'install' in kwargs:
  1789. self.install = kwargs['install']
  1790. if not isinstance(self.install, bool):
  1791. raise InvalidArguments('"install" must be boolean.')
  1792. if self.install:
  1793. if 'install_dir' not in kwargs:
  1794. raise InvalidArguments('"install_dir" must be specified '
  1795. 'when installing a target')
  1796. if isinstance(kwargs['install_dir'], list):
  1797. FeatureNew('multiple install_dir for custom_target', '0.40.0').use(self.subproject)
  1798. # If an item in this list is False, the output corresponding to
  1799. # the list index of that item will not be installed
  1800. self.install_dir = typeslistify(kwargs['install_dir'], (str, bool))
  1801. self.install_mode = kwargs.get('install_mode', None)
  1802. else:
  1803. self.install = False
  1804. self.install_dir = [None]
  1805. self.install_mode = None
  1806. if 'build_always' in kwargs and 'build_always_stale' in kwargs:
  1807. raise InvalidArguments('build_always and build_always_stale are mutually exclusive. Combine build_by_default and build_always_stale.')
  1808. elif 'build_always' in kwargs:
  1809. mlog.deprecation('build_always is deprecated. Combine build_by_default and build_always_stale instead.')
  1810. if 'build_by_default' not in kwargs:
  1811. self.build_by_default = kwargs['build_always']
  1812. self.build_always_stale = kwargs['build_always']
  1813. elif 'build_always_stale' in kwargs:
  1814. self.build_always_stale = kwargs['build_always_stale']
  1815. if not isinstance(self.build_always_stale, bool):
  1816. raise InvalidArguments('Argument build_always_stale must be a boolean.')
  1817. extra_deps, depend_files = extract_as_list(kwargs, 'depends', 'depend_files', pop = False)
  1818. for ed in extra_deps:
  1819. while hasattr(ed, 'held_object'):
  1820. ed = ed.held_object
  1821. if not isinstance(ed, (CustomTarget, BuildTarget)):
  1822. raise InvalidArguments('Can only depend on toplevel targets: custom_target or build_target (executable or a library) got: %s(%s)'
  1823. % (type(ed), ed))
  1824. self.extra_depends.append(ed)
  1825. for i in depend_files:
  1826. if isinstance(i, (File, str)):
  1827. self.depend_files.append(i)
  1828. else:
  1829. mlog.debug(i)
  1830. raise InvalidArguments('Unknown type {!r} in depend_files.'.format(type(i).__name__))
  1831. def get_dependencies(self):
  1832. return self.dependencies
  1833. def should_install(self):
  1834. return self.install
  1835. def get_custom_install_dir(self):
  1836. return self.install_dir
  1837. def get_custom_install_mode(self):
  1838. return self.install_mode
  1839. def get_outputs(self):
  1840. return self.outputs
  1841. def get_filename(self):
  1842. return self.outputs[0]
  1843. def get_sources(self):
  1844. return self.sources
  1845. def get_generated_lists(self):
  1846. genlists = []
  1847. for c in self.sources:
  1848. if hasattr(c, 'held_object'):
  1849. c = c.held_object
  1850. if isinstance(c, GeneratedList):
  1851. genlists.append(c)
  1852. return genlists
  1853. def get_generated_sources(self):
  1854. return self.get_generated_lists()
  1855. def get_dep_outname(self, infilenames):
  1856. if self.depfile is None:
  1857. raise InvalidArguments('Tried to get depfile name for custom_target that does not have depfile defined.')
  1858. if len(infilenames):
  1859. plainname = os.path.basename(infilenames[0])
  1860. basename = os.path.splitext(plainname)[0]
  1861. return self.depfile.replace('@BASENAME@', basename).replace('@PLAINNAME@', plainname)
  1862. else:
  1863. if '@BASENAME@' in self.depfile or '@PLAINNAME@' in self.depfile:
  1864. raise InvalidArguments('Substitution in depfile for custom_target that does not have an input file.')
  1865. return self.depfile
  1866. def type_suffix(self):
  1867. return "@cus"
  1868. def __getitem__(self, index):
  1869. return CustomTargetIndex(self, self.outputs[index])
  1870. def __setitem__(self, index, value):
  1871. raise NotImplementedError
  1872. def __delitem__(self, index):
  1873. raise NotImplementedError
  1874. class RunTarget(Target):
  1875. def __init__(self, name, command, args, dependencies, subdir, subproject):
  1876. self.typename = 'run'
  1877. super().__init__(name, subdir, subproject, False)
  1878. self.command = command
  1879. self.args = args
  1880. self.dependencies = dependencies
  1881. def __lt__(self, other):
  1882. return self.get_id() < other.get_id()
  1883. def __repr__(self):
  1884. repr_str = "<{0} {1}: {2}>"
  1885. return repr_str.format(self.__class__.__name__, self.get_id(), self.command)
  1886. def get_dependencies(self):
  1887. return self.dependencies
  1888. def get_generated_sources(self):
  1889. return []
  1890. def get_sources(self):
  1891. return []
  1892. def should_install(self):
  1893. return False
  1894. def get_filename(self):
  1895. return self.name
  1896. def get_outputs(self):
  1897. if isinstance(self.name, str):
  1898. return [self.name]
  1899. elif isinstance(self.name, list):
  1900. return self.name
  1901. else:
  1902. raise RuntimeError('RunTarget: self.name is neither a list nor a string. This is a bug')
  1903. def type_suffix(self):
  1904. return "@run"
  1905. class Jar(BuildTarget):
  1906. known_kwargs = known_jar_kwargs
  1907. def __init__(self, name, subdir, subproject, is_cross, sources, objects, environment, kwargs):
  1908. self.typename = 'jar'
  1909. super().__init__(name, subdir, subproject, is_cross, sources, objects, environment, kwargs)
  1910. for s in self.sources:
  1911. if not s.endswith('.java'):
  1912. raise InvalidArguments('Jar source %s is not a java file.' % s)
  1913. for t in self.link_targets:
  1914. if not isinstance(t, Jar):
  1915. raise InvalidArguments('Link target %s is not a jar target.' % t)
  1916. self.filename = self.name + '.jar'
  1917. self.outputs = [self.filename]
  1918. self.java_args = kwargs.get('java_args', [])
  1919. def get_main_class(self):
  1920. return self.main_class
  1921. def type_suffix(self):
  1922. return "@jar"
  1923. def get_java_args(self):
  1924. return self.java_args
  1925. def validate_cross_install(self, environment):
  1926. # All jar targets are installable.
  1927. pass
  1928. def is_linkable_target(self):
  1929. return True
  1930. def get_classpath_args(self):
  1931. cp_paths = [os.path.join(l.get_subdir(), l.get_filename()) for l in self.link_targets]
  1932. cp_string = os.pathsep.join(cp_paths)
  1933. if cp_string:
  1934. return ['-cp', os.pathsep.join(cp_paths)]
  1935. return []
  1936. class CustomTargetIndex:
  1937. """A special opaque object returned by indexing a CustomTarget. This object
  1938. exists in meson, but acts as a proxy in the backends, making targets depend
  1939. on the CustomTarget it's derived from, but only adding one source file to
  1940. the sources.
  1941. """
  1942. def __init__(self, target, output):
  1943. self.typename = 'custom'
  1944. self.target = target
  1945. self.output = output
  1946. def __repr__(self):
  1947. return '<CustomTargetIndex: {!r}[{}]>'.format(
  1948. self.target, self.target.get_outputs().index(self.output))
  1949. def get_outputs(self):
  1950. return [self.output]
  1951. def get_subdir(self):
  1952. return self.target.get_subdir()
  1953. class ConfigureFile:
  1954. def __init__(self, subdir, sourcename, targetname, configuration_data):
  1955. self.subdir = subdir
  1956. self.sourcename = sourcename
  1957. self.targetname = targetname
  1958. self.configuration_data = configuration_data
  1959. def __repr__(self):
  1960. repr_str = "<{0}: {1} -> {2}>"
  1961. src = os.path.join(self.subdir, self.sourcename)
  1962. dst = os.path.join(self.subdir, self.targetname)
  1963. return repr_str.format(self.__class__.__name__, src, dst)
  1964. def get_configuration_data(self):
  1965. return self.configuration_data
  1966. def get_subdir(self):
  1967. return self.subdir
  1968. def get_source_name(self):
  1969. return self.sourcename
  1970. def get_target_name(self):
  1971. return self.targetname
  1972. class ConfigurationData:
  1973. def __init__(self):
  1974. super().__init__()
  1975. self.values = {}
  1976. def __repr__(self):
  1977. return repr(self.values)
  1978. def __contains__(self, value):
  1979. return value in self.values
  1980. def get(self, name):
  1981. return self.values[name] # (val, desc)
  1982. def keys(self):
  1983. return self.values.keys()
  1984. # A bit poorly named, but this represents plain data files to copy
  1985. # during install.
  1986. class Data:
  1987. def __init__(self, sources, install_dir, install_mode=None, rename=None):
  1988. self.sources = sources
  1989. self.install_dir = install_dir
  1990. self.install_mode = install_mode
  1991. self.sources = listify(self.sources)
  1992. for s in self.sources:
  1993. assert(isinstance(s, File))
  1994. if rename is None:
  1995. self.rename = [os.path.basename(f.fname) for f in self.sources]
  1996. else:
  1997. self.rename = stringlistify(rename)
  1998. if len(self.rename) != len(self.sources):
  1999. raise MesonException('Size of rename argument is different from number of sources')
  2000. class RunScript(dict):
  2001. def __init__(self, script, args):
  2002. super().__init__()
  2003. assert(isinstance(script, list))
  2004. assert(isinstance(args, list))
  2005. self['exe'] = script
  2006. self['args'] = args
  2007. class TestSetup:
  2008. def __init__(self, *, exe_wrapper=None, gdb=None, timeout_multiplier=None, env=None):
  2009. self.exe_wrapper = exe_wrapper
  2010. self.gdb = gdb
  2011. self.timeout_multiplier = timeout_multiplier
  2012. self.env = env
  2013. def get_sources_string_names(sources):
  2014. '''
  2015. For the specified list of @sources which can be strings, Files, or targets,
  2016. get all the output basenames.
  2017. '''
  2018. names = []
  2019. for s in sources:
  2020. if hasattr(s, 'held_object'):
  2021. s = s.held_object
  2022. if isinstance(s, str):
  2023. names.append(s)
  2024. elif isinstance(s, (BuildTarget, CustomTarget, CustomTargetIndex, GeneratedList)):
  2025. names += s.get_outputs()
  2026. elif isinstance(s, File):
  2027. names.append(s.fname)
  2028. else:
  2029. raise AssertionError('Unknown source type: {!r}'.format(s))
  2030. return names
  2031. def load(build_dir):
  2032. filename = os.path.join(build_dir, 'meson-private', 'build.dat')
  2033. load_fail_msg = 'Build data file {!r} is corrupted. Try with a fresh build tree.'.format(filename)
  2034. nonexisting_fail_msg = 'No such build data file as "{!r}".'.format(filename)
  2035. try:
  2036. with open(filename, 'rb') as f:
  2037. obj = pickle.load(f)
  2038. except FileNotFoundError:
  2039. raise MesonException(nonexisting_fail_msg)
  2040. except pickle.UnpicklingError:
  2041. raise MesonException(load_fail_msg)
  2042. if not isinstance(obj, Build):
  2043. raise MesonException(load_fail_msg)
  2044. return obj
  2045. def save(obj, filename):
  2046. with open(filename, 'wb') as f:
  2047. pickle.dump(obj, f)