build.py 107 KB

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