build.py 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723
  1. # Copyright 2012-2017 The Meson development team
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. # Unless required by applicable law or agreed to in writing, software
  7. # distributed under the License is distributed on an "AS IS" BASIS,
  8. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. # See the License for the specific language governing permissions and
  10. # limitations under the License.
  11. import copy, os, re
  12. from collections import OrderedDict
  13. from . import environment
  14. from . import dependencies
  15. from . import mlog
  16. from .mesonlib import File, MesonException
  17. from .mesonlib import flatten, typeslistify, stringlistify, classify_unity_sources
  18. from .mesonlib import get_filenames_templates_dict, substitute_values
  19. from .environment import for_windows, for_darwin, for_cygwin
  20. from .compilers import is_object, clike_langs, sort_clike, lang_suffixes
  21. known_basic_kwargs = {'install': True,
  22. 'c_pch': True,
  23. 'cpp_pch': True,
  24. 'c_args': True,
  25. 'objc_args': True,
  26. 'objcpp_args': True,
  27. 'cpp_args': True,
  28. 'cs_args': True,
  29. 'vala_args': True,
  30. 'fortran_args': True,
  31. 'd_args': True,
  32. 'java_args': True,
  33. 'rust_args': True,
  34. 'link_args': True,
  35. 'link_depends': True,
  36. 'link_with': True,
  37. 'link_whole': True,
  38. 'include_directories': True,
  39. 'dependencies': True,
  40. 'install_dir': True,
  41. 'main_class': True,
  42. 'name_suffix': True,
  43. 'gui_app': True,
  44. 'extra_files': True,
  45. 'install_rpath': True,
  46. 'resources': True,
  47. 'sources': True,
  48. 'objects': True,
  49. 'native': True,
  50. 'build_by_default': True,
  51. 'override_options': True,
  52. }
  53. # These contain kwargs supported by both static and shared libraries. These are
  54. # combined here because a library() call might be shared_library() or
  55. # static_library() at runtime based on the configuration.
  56. # FIXME: Find a way to pass that info down here so we can have proper target
  57. # kwargs checking when specifically using shared_library() or static_library().
  58. known_lib_kwargs = known_basic_kwargs.copy()
  59. known_lib_kwargs.update({'version': True, # Only for shared libs
  60. 'soversion': True, # Only for shared libs
  61. 'name_prefix': True,
  62. 'vs_module_defs': True, # Only for shared libs
  63. 'vala_header': True,
  64. 'vala_vapi': True,
  65. 'vala_gir': True,
  66. 'pic': True, # Only for static libs
  67. })
  68. class InvalidArguments(MesonException):
  69. pass
  70. class Build:
  71. """A class that holds the status of one build including
  72. all dependencies and so on.
  73. """
  74. def __init__(self, environment):
  75. self.project_name = 'name of master project'
  76. self.project_version = None
  77. self.environment = environment
  78. self.projects = {}
  79. self.targets = OrderedDict()
  80. self.compilers = OrderedDict()
  81. self.cross_compilers = OrderedDict()
  82. self.global_args = {}
  83. self.projects_args = {}
  84. self.global_link_args = {}
  85. self.projects_link_args = {}
  86. self.tests = []
  87. self.benchmarks = []
  88. self.headers = []
  89. self.man = []
  90. self.data = []
  91. self.static_linker = None
  92. self.static_cross_linker = None
  93. self.subprojects = {}
  94. self.install_scripts = []
  95. self.postconf_scripts = []
  96. self.install_dirs = []
  97. self.dep_manifest_name = None
  98. self.dep_manifest = {}
  99. self.cross_stdlibs = {}
  100. self.test_setups = {}
  101. def add_compiler(self, compiler):
  102. if self.static_linker is None and compiler.needs_static_linker():
  103. self.static_linker = self.environment.detect_static_linker(compiler)
  104. lang = compiler.get_language()
  105. if lang not in self.compilers:
  106. self.compilers[lang] = compiler
  107. def add_cross_compiler(self, compiler):
  108. if not self.cross_compilers:
  109. self.static_cross_linker = self.environment.detect_static_linker(compiler)
  110. lang = compiler.get_language()
  111. if lang not in self.cross_compilers:
  112. self.cross_compilers[lang] = compiler
  113. def get_project(self):
  114. return self.projects['']
  115. def get_targets(self):
  116. return self.targets
  117. def get_tests(self):
  118. return self.tests
  119. def get_benchmarks(self):
  120. return self.benchmarks
  121. def get_headers(self):
  122. return self.headers
  123. def get_man(self):
  124. return self.man
  125. def get_data(self):
  126. return self.data
  127. def get_install_subdirs(self):
  128. return self.install_dirs
  129. def get_global_args(self, compiler):
  130. return self.global_args.get(compiler.get_language(), [])
  131. def get_project_args(self, compiler, project):
  132. args = self.projects_args.get(project)
  133. if not args:
  134. return []
  135. return args.get(compiler.get_language(), [])
  136. def get_global_link_args(self, compiler):
  137. return self.global_link_args.get(compiler.get_language(), [])
  138. def get_project_link_args(self, compiler, project):
  139. link_args = self.projects_link_args.get(project)
  140. if not link_args:
  141. return []
  142. return link_args.get(compiler.get_language(), [])
  143. class IncludeDirs:
  144. def __init__(self, curdir, dirs, is_system, extra_build_dirs=None):
  145. self.curdir = curdir
  146. self.incdirs = dirs
  147. self.is_system = is_system
  148. # Interpreter has validated that all given directories
  149. # actually exist.
  150. if extra_build_dirs is None:
  151. self.extra_build_dirs = []
  152. else:
  153. self.extra_build_dirs = extra_build_dirs
  154. def __repr__(self):
  155. r = '<{} {}/{}>'
  156. return r.format(self.__class__.__name__, self.curdir, self.incdirs)
  157. def get_curdir(self):
  158. return self.curdir
  159. def get_incdirs(self):
  160. return self.incdirs
  161. def get_extra_build_dirs(self):
  162. return self.extra_build_dirs
  163. class ExtractedObjects:
  164. '''
  165. Holds a list of sources for which the objects must be extracted
  166. '''
  167. def __init__(self, target, srclist, is_unity):
  168. self.target = target
  169. self.srclist = srclist
  170. if is_unity:
  171. self.check_unity_compatible()
  172. def __repr__(self):
  173. r = '<{0} {1!r}: {2}>'
  174. return r.format(self.__class__.__name__, self.target.name, self.srclist)
  175. def check_unity_compatible(self):
  176. # Figure out if the extracted object list is compatible with a Unity
  177. # build. When we're doing a Unified build, we go through the sources,
  178. # and create a single source file from each subset of the sources that
  179. # can be compiled with a specific compiler. Then we create one object
  180. # from each unified source file.
  181. # If the list of sources for which we want objects is the same as the
  182. # list of sources that go into each unified build, we're good.
  183. srclist_set = set(self.srclist)
  184. # Objects for all the sources are required, so we're compatible
  185. if srclist_set == set(self.target.sources):
  186. return
  187. # Check if the srclist is a subset (of the target's sources) that is
  188. # going to form a unified source file and a single object
  189. compsrcs = classify_unity_sources(self.target.compilers.values(),
  190. self.target.sources)
  191. for srcs in compsrcs.values():
  192. if srclist_set == set(srcs):
  193. return
  194. msg = 'Single object files can not be extracted in Unity builds. ' \
  195. 'You can only extract all the object files at once.'
  196. raise MesonException(msg)
  197. class EnvironmentVariables:
  198. def __init__(self):
  199. self.envvars = []
  200. def __repr__(self):
  201. repr_str = "<{0}: {1}>"
  202. return repr_str.format(self.__class__.__name__, self.envvars)
  203. def get_value(self, values, kwargs):
  204. separator = kwargs.get('separator', os.pathsep)
  205. value = ''
  206. for var in values:
  207. value += separator + var
  208. return separator, value.strip(separator)
  209. def set(self, env, name, values, kwargs):
  210. return self.get_value(values, kwargs)[1]
  211. def append(self, env, name, values, kwargs):
  212. sep, value = self.get_value(values, kwargs)
  213. if name in env:
  214. return env[name] + sep + value
  215. return value
  216. def prepend(self, env, name, values, kwargs):
  217. sep, value = self.get_value(values, kwargs)
  218. if name in env:
  219. return value + sep + env[name]
  220. return value
  221. def get_env(self, full_env):
  222. env = {}
  223. for method, name, values, kwargs in self.envvars:
  224. env[name] = method(full_env, name, values, kwargs)
  225. return env
  226. class Target:
  227. def __init__(self, name, subdir, build_by_default):
  228. if '/' in name or '\\' in name:
  229. # Fix failing test 53 when this becomes an error.
  230. mlog.warning('''Target "%s" has a path separator in its name.
  231. This is not supported, it can cause unexpected failures and will become
  232. a hard error in the future.''' % name)
  233. self.name = name
  234. self.subdir = subdir
  235. self.build_by_default = build_by_default
  236. self.install = False
  237. self.build_always = False
  238. self.option_overrides = {}
  239. def get_basename(self):
  240. return self.name
  241. def get_subdir(self):
  242. return self.subdir
  243. def process_kwargs(self, kwargs):
  244. if 'build_by_default' in kwargs:
  245. self.build_by_default = kwargs['build_by_default']
  246. if not isinstance(self.build_by_default, bool):
  247. raise InvalidArguments('build_by_default must be a boolean value.')
  248. self.option_overrides = self.parse_overrides(kwargs)
  249. def parse_overrides(self, kwargs):
  250. result = {}
  251. overrides = stringlistify(kwargs.get('override_options', []))
  252. for o in overrides:
  253. if '=' not in o:
  254. raise InvalidArguments('Overrides must be of form "key=value"')
  255. k, v = o.split('=', 1)
  256. k = k.strip()
  257. v = v.strip()
  258. result[k] = v
  259. return result
  260. class BuildTarget(Target):
  261. def __init__(self, name, subdir, subproject, is_cross, sources, objects, environment, kwargs):
  262. super().__init__(name, subdir, True)
  263. self.subproject = subproject # Can not be calculated from subdir as subproject dirname can be changed per project.
  264. self.is_cross = is_cross
  265. unity_opt = environment.coredata.get_builtin_option('unity')
  266. self.is_unity = unity_opt == 'on' or (unity_opt == 'subprojects' and subproject != '')
  267. self.environment = environment
  268. self.sources = []
  269. self.compilers = OrderedDict()
  270. self.objects = []
  271. self.external_deps = []
  272. self.include_dirs = []
  273. self.link_targets = []
  274. self.link_whole_targets = []
  275. self.link_depends = []
  276. self.name_prefix_set = False
  277. self.name_suffix_set = False
  278. self.filename = 'no_name'
  279. # The list of all files outputted by this target. Useful in cases such
  280. # as Vala which generates .vapi and .h besides the compiled output.
  281. self.outputs = [self.filename]
  282. self.need_install = False
  283. self.pch = {}
  284. self.extra_args = {}
  285. self.generated = []
  286. self.extra_files = []
  287. # Sources can be:
  288. # 1. Pre-existing source files in the source tree
  289. # 2. Pre-existing sources generated by configure_file in the build tree
  290. # 3. Sources files generated by another target or a Generator
  291. self.process_sourcelist(sources)
  292. # Objects can be:
  293. # 1. Pre-existing objects provided by the user with the `objects:` kwarg
  294. # 2. Compiled objects created by and extracted from another target
  295. self.process_objectlist(objects)
  296. self.process_kwargs(kwargs, environment)
  297. self.check_unknown_kwargs(kwargs)
  298. if not self.sources and not self.generated and not self.objects:
  299. raise InvalidArguments('Build target %s has no sources.' % name)
  300. self.process_compilers()
  301. self.validate_sources()
  302. self.validate_cross_install(environment)
  303. def __lt__(self, other):
  304. return self.get_id() < other.get_id()
  305. def __repr__(self):
  306. repr_str = "<{0} {1}: {2}>"
  307. return repr_str.format(self.__class__.__name__, self.get_id(), self.filename)
  308. def validate_cross_install(self, environment):
  309. if environment.is_cross_build() and not self.is_cross and self.install:
  310. raise InvalidArguments('Tried to install a natively built target in a cross build.')
  311. def get_id(self):
  312. # This ID must also be a valid file name on all OSs.
  313. # It should also avoid shell metacharacters for obvious
  314. # reasons.
  315. base = self.name + self.type_suffix()
  316. if self.subproject == '':
  317. return base
  318. return self.subproject + '@@' + base
  319. def check_unknown_kwargs(self, kwargs):
  320. # Override this method in derived classes that have more
  321. # keywords.
  322. self.check_unknown_kwargs_int(kwargs, known_basic_kwargs)
  323. def check_unknown_kwargs_int(self, kwargs, known_kwargs):
  324. unknowns = []
  325. for k in kwargs:
  326. if k not in known_kwargs:
  327. unknowns.append(k)
  328. if len(unknowns) > 0:
  329. mlog.warning('Unknown keyword argument(s) in target %s: %s.' %
  330. (self.name, ', '.join(unknowns)))
  331. def process_objectlist(self, objects):
  332. assert(isinstance(objects, list))
  333. for s in objects:
  334. if hasattr(s, 'held_object'):
  335. s = s.held_object
  336. if isinstance(s, (str, File, ExtractedObjects)):
  337. self.objects.append(s)
  338. elif isinstance(s, (GeneratedList, CustomTarget)):
  339. msg = 'Generated files are not allowed in the \'objects\' kwarg ' + \
  340. 'for target {!r}.\nIt is meant only for '.format(self.name) + \
  341. 'pre-built object files that are shipped with the\nsource ' + \
  342. 'tree. Try adding it in the list of sources.'
  343. raise InvalidArguments(msg)
  344. else:
  345. msg = 'Bad object of type {!r} in target {!r}.'.format(type(s).__name__, self.name)
  346. raise InvalidArguments(msg)
  347. def process_sourcelist(self, sources):
  348. if not isinstance(sources, list):
  349. sources = [sources]
  350. added_sources = {} # If the same source is defined multiple times, use it only once.
  351. for s in sources:
  352. # Holder unpacking. Ugly.
  353. if hasattr(s, 'held_object'):
  354. s = s.held_object
  355. if isinstance(s, File):
  356. if s not in added_sources:
  357. self.sources.append(s)
  358. added_sources[s] = True
  359. elif isinstance(s, (GeneratedList, CustomTarget)):
  360. self.generated.append(s)
  361. else:
  362. msg = 'Bad source of type {!r} in target {!r}.'.format(type(s).__name__, self.name)
  363. raise InvalidArguments(msg)
  364. @staticmethod
  365. def can_compile_remove_sources(compiler, sources):
  366. removed = False
  367. for s in sources[:]:
  368. if compiler.can_compile(s):
  369. sources.remove(s)
  370. removed = True
  371. return removed
  372. def process_compilers(self):
  373. '''
  374. Populate self.compilers, which is the list of compilers that this
  375. target will use for compiling all its sources.
  376. We also add compilers that were used by extracted objects to simplify
  377. dynamic linker determination.
  378. '''
  379. if not self.sources and not self.generated and not self.objects:
  380. return
  381. # Populate list of compilers
  382. if self.is_cross:
  383. compilers = self.environment.coredata.cross_compilers
  384. else:
  385. compilers = self.environment.coredata.compilers
  386. # Pre-existing sources
  387. sources = list(self.sources)
  388. # All generated sources
  389. for gensrc in self.generated:
  390. for s in gensrc.get_outputs():
  391. # Generated objects can't be compiled, so don't use them for
  392. # compiler detection. If our target only has generated objects,
  393. # we will fall back to using the first c-like compiler we find,
  394. # which is what we need.
  395. if not is_object(s):
  396. sources.append(s)
  397. # Sources that were used to create our extracted objects
  398. for o in self.objects:
  399. if not isinstance(o, ExtractedObjects):
  400. continue
  401. for s in o.srclist:
  402. # Don't add Vala sources since that will pull in the Vala
  403. # compiler even though we will never use it since we are
  404. # dealing with compiled C code.
  405. if not s.endswith(lang_suffixes['vala']):
  406. sources.append(s)
  407. if sources:
  408. # For each source, try to add one compiler that can compile it.
  409. # It's ok if no compilers can do so, because users are expected to
  410. # be able to add arbitrary non-source files to the sources list.
  411. for s in sources:
  412. for lang, compiler in compilers.items():
  413. if compiler.can_compile(s):
  414. if lang not in self.compilers:
  415. self.compilers[lang] = compiler
  416. break
  417. # Re-sort according to clike_langs
  418. self.compilers = OrderedDict(sorted(self.compilers.items(),
  419. key=lambda t: sort_clike(t[0])))
  420. else:
  421. # No source files, target consists of only object files of unknown
  422. # origin. Just add the first clike compiler that we have and hope
  423. # that it can link these objects
  424. for lang in clike_langs:
  425. if lang in compilers:
  426. self.compilers[lang] = compilers[lang]
  427. break
  428. # If all our sources are Vala, our target also needs the C compiler but
  429. # it won't get added above.
  430. if 'vala' in self.compilers and 'c' not in self.compilers:
  431. self.compilers['c'] = compilers['c']
  432. def validate_sources(self):
  433. if not self.sources:
  434. return
  435. for lang in ('cs', 'java'):
  436. if lang in self.compilers:
  437. check_sources = list(self.sources)
  438. compiler = self.compilers[lang]
  439. if not self.can_compile_remove_sources(compiler, check_sources):
  440. m = 'No {} sources found in target {!r}'.format(lang, self.name)
  441. raise InvalidArguments(m)
  442. if check_sources:
  443. m = '{0} targets can only contain {0} files:\n'.format(lang.capitalize())
  444. m += '\n'.join([repr(c) for c in check_sources])
  445. raise InvalidArguments(m)
  446. # CSharp and Java targets can't contain any other file types
  447. assert(len(self.compilers) == 1)
  448. return
  449. def process_link_depends(self, sources, environment):
  450. """Process the link_depends keyword argument.
  451. This is designed to handle strings, Files, and the output of Custom
  452. Targets. Notably it doesn't handle generator() returned objects, since
  453. adding them as a link depends would inherently cause them to be
  454. generated twice, since the output needs to be passed to the ld_args and
  455. link_depends.
  456. """
  457. if not isinstance(sources, list):
  458. sources = [sources]
  459. for s in sources:
  460. if hasattr(s, 'held_object'):
  461. s = s.held_object
  462. if isinstance(s, File):
  463. self.link_depends.append(s)
  464. elif isinstance(s, str):
  465. self.link_depends.append(
  466. File.from_source_file(environment.source_dir, self.subdir, s))
  467. elif hasattr(s, 'get_outputs'):
  468. self.link_depends.extend(
  469. [File.from_built_file(s.subdir, p) for p in s.get_outputs()])
  470. else:
  471. raise InvalidArguments(
  472. 'Link_depends arguments must be strings, Files, '
  473. 'or a Custom Target, or lists thereof.')
  474. def get_original_kwargs(self):
  475. return self.kwargs
  476. def unpack_holder(self, d):
  477. if not isinstance(d, list):
  478. d = [d]
  479. newd = []
  480. for i in d:
  481. if hasattr(i, 'held_object'):
  482. newd.append(i.held_object)
  483. else:
  484. newd.append(i)
  485. return newd
  486. def copy_kwargs(self, kwargs):
  487. self.kwargs = copy.copy(kwargs)
  488. # This sucks quite badly. Arguments
  489. # are holders but they can't be pickled
  490. # so unpack those known.
  491. if 'dependencies' in self.kwargs:
  492. self.kwargs['dependencies'] = self.unpack_holder(self.kwargs['dependencies'])
  493. if 'link_with' in self.kwargs:
  494. self.kwargs['link_with'] = self.unpack_holder(self.kwargs['link_with'])
  495. def extract_objects(self, srclist):
  496. obj_src = []
  497. for src in srclist:
  498. if not isinstance(src, str):
  499. raise MesonException('Object extraction arguments must be strings.')
  500. src = File(False, self.subdir, src)
  501. if src not in self.sources:
  502. raise MesonException('Tried to extract unknown source %s.' % src)
  503. obj_src.append(src)
  504. return ExtractedObjects(self, obj_src, self.is_unity)
  505. def extract_all_objects(self):
  506. return ExtractedObjects(self, self.sources, self.is_unity)
  507. def get_all_link_deps(self):
  508. return self.get_transitive_link_deps()
  509. def get_transitive_link_deps(self):
  510. result = []
  511. for i in self.link_targets:
  512. result += i.get_all_link_deps()
  513. return result
  514. def get_custom_install_dir(self):
  515. return self.install_dir
  516. def process_kwargs(self, kwargs, environment):
  517. super().process_kwargs(kwargs)
  518. self.copy_kwargs(kwargs)
  519. kwargs.get('modules', [])
  520. self.need_install = kwargs.get('install', self.need_install)
  521. llist = kwargs.get('link_with', [])
  522. if not isinstance(llist, list):
  523. llist = [llist]
  524. for linktarget in llist:
  525. # Sorry for this hack. Keyword targets are kept in holders
  526. # in kwargs. Unpack here without looking at the exact type.
  527. if hasattr(linktarget, "held_object"):
  528. linktarget = linktarget.held_object
  529. self.link(linktarget)
  530. lwhole = kwargs.get('link_whole', [])
  531. if not isinstance(lwhole, list):
  532. lwhole = [lwhole]
  533. for linktarget in lwhole:
  534. # Sorry for this hack. Keyword targets are kept in holders
  535. # in kwargs. Unpack here without looking at the exact type.
  536. if hasattr(linktarget, "held_object"):
  537. linktarget = linktarget.held_object
  538. self.link_whole(linktarget)
  539. c_pchlist = kwargs.get('c_pch', [])
  540. if not isinstance(c_pchlist, list):
  541. c_pchlist = [c_pchlist]
  542. self.add_pch('c', c_pchlist)
  543. cpp_pchlist = kwargs.get('cpp_pch', [])
  544. if not isinstance(cpp_pchlist, list):
  545. cpp_pchlist = [cpp_pchlist]
  546. self.add_pch('cpp', cpp_pchlist)
  547. clist = kwargs.get('c_args', [])
  548. if not isinstance(clist, list):
  549. clist = [clist]
  550. self.add_compiler_args('c', clist)
  551. cpplist = kwargs.get('cpp_args', [])
  552. if not isinstance(cpplist, list):
  553. cpplist = [cpplist]
  554. self.add_compiler_args('cpp', cpplist)
  555. cslist = kwargs.get('cs_args', [])
  556. if not isinstance(cslist, list):
  557. cslist = [cslist]
  558. self.add_compiler_args('cs', cslist)
  559. valalist = kwargs.get('vala_args', [])
  560. if not isinstance(valalist, list):
  561. valalist = [valalist]
  562. self.add_compiler_args('vala', valalist)
  563. objclist = kwargs.get('objc_args', [])
  564. if not isinstance(objclist, list):
  565. objclist = [objclist]
  566. self.add_compiler_args('objc', objclist)
  567. objcpplist = kwargs.get('objcpp_args', [])
  568. if not isinstance(objcpplist, list):
  569. objcpplist = [objcpplist]
  570. self.add_compiler_args('objcpp', objcpplist)
  571. fortranlist = kwargs.get('fortran_args', [])
  572. if not isinstance(fortranlist, list):
  573. fortranlist = [fortranlist]
  574. self.add_compiler_args('fortran', fortranlist)
  575. rustlist = kwargs.get('rust_args', [])
  576. if not isinstance(rustlist, list):
  577. rustlist = [rustlist]
  578. self.add_compiler_args('rust', rustlist)
  579. if not isinstance(self, Executable):
  580. self.vala_header = kwargs.get('vala_header', self.name + '.h')
  581. self.vala_vapi = kwargs.get('vala_vapi', self.name + '.vapi')
  582. self.vala_gir = kwargs.get('vala_gir', None)
  583. dlist = stringlistify(kwargs.get('d_args', []))
  584. self.add_compiler_args('d', dlist)
  585. self.link_args = flatten(kwargs.get('link_args', []))
  586. for i in self.link_args:
  587. if not isinstance(i, str):
  588. raise InvalidArguments('Link_args arguments must be strings.')
  589. self.process_link_depends(kwargs.get('link_depends', []), environment)
  590. # Target-specific include dirs must be added BEFORE include dirs from
  591. # internal deps (added inside self.add_deps()) to override them.
  592. inclist = kwargs.get('include_directories', [])
  593. if not isinstance(inclist, list):
  594. inclist = [inclist]
  595. self.add_include_dirs(inclist)
  596. # Add dependencies (which also have include_directories)
  597. deplist = kwargs.get('dependencies', [])
  598. if not isinstance(deplist, list):
  599. deplist = [deplist]
  600. self.add_deps(deplist)
  601. # If an item in this list is False, the output corresponding to
  602. # the list index of that item will not be installed
  603. self.install_dir = typeslistify(kwargs.get('install_dir', [None]),
  604. (str, bool))
  605. main_class = kwargs.get('main_class', '')
  606. if not isinstance(main_class, str):
  607. raise InvalidArguments('Main class must be a string')
  608. self.main_class = main_class
  609. if isinstance(self, Executable):
  610. self.gui_app = kwargs.get('gui_app', False)
  611. if not isinstance(self.gui_app, bool):
  612. raise InvalidArguments('Argument gui_app must be boolean.')
  613. elif 'gui_app' in kwargs:
  614. raise InvalidArguments('Argument gui_app can only be used on executables.')
  615. extra_files = kwargs.get('extra_files', [])
  616. if not isinstance(extra_files, list):
  617. extra_files = [extra_files]
  618. for i in extra_files:
  619. assert(isinstance(i, File))
  620. trial = os.path.join(environment.get_source_dir(), i.subdir, i.fname)
  621. if not(os.path.isfile(trial)):
  622. raise InvalidArguments('Tried to add non-existing extra file %s.' % i)
  623. self.extra_files = extra_files
  624. self.install_rpath = kwargs.get('install_rpath', '')
  625. if not isinstance(self.install_rpath, str):
  626. raise InvalidArguments('Install_rpath is not a string.')
  627. resources = kwargs.get('resources', [])
  628. if not isinstance(resources, list):
  629. resources = [resources]
  630. for r in resources:
  631. if not isinstance(r, str):
  632. raise InvalidArguments('Resource argument is not a string.')
  633. trial = os.path.join(environment.get_source_dir(), self.subdir, r)
  634. if not os.path.isfile(trial):
  635. raise InvalidArguments('Tried to add non-existing resource %s.' % r)
  636. self.resources = resources
  637. if 'name_prefix' in kwargs:
  638. name_prefix = kwargs['name_prefix']
  639. if isinstance(name_prefix, list):
  640. if name_prefix:
  641. raise InvalidArguments('name_prefix array must be empty to signify null.')
  642. elif not isinstance(name_prefix, str):
  643. raise InvalidArguments('name_prefix must be a string.')
  644. self.prefix = name_prefix
  645. self.name_prefix_set = True
  646. if 'name_suffix' in kwargs:
  647. name_suffix = kwargs['name_suffix']
  648. if isinstance(name_suffix, list):
  649. if name_suffix:
  650. raise InvalidArguments('name_suffix array must be empty to signify null.')
  651. else:
  652. if not isinstance(name_suffix, str):
  653. raise InvalidArguments('name_suffix must be a string.')
  654. self.suffix = name_suffix
  655. self.name_suffix_set = True
  656. if isinstance(self, StaticLibrary):
  657. # You can't disable PIC on OS X. The compiler ignores -fno-PIC.
  658. # PIC is always on for Windows (all code is position-independent
  659. # since library loading is done differently)
  660. if for_darwin(self.is_cross, self.environment) or for_windows(self.is_cross, self.environment):
  661. self.pic = True
  662. elif '-fPIC' in clist + cpplist:
  663. mlog.warning("Use the 'pic' kwarg instead of passing -fPIC manually to static library {!r}".format(self.name))
  664. self.pic = True
  665. else:
  666. self.pic = kwargs.get('pic', False)
  667. if not isinstance(self.pic, bool):
  668. raise InvalidArguments('Argument pic to static library {!r} must be boolean'.format(self.name))
  669. def get_filename(self):
  670. return self.filename
  671. def get_outputs(self):
  672. return self.outputs
  673. def get_extra_args(self, language):
  674. return self.extra_args.get(language, [])
  675. def get_dependencies(self):
  676. transitive_deps = []
  677. for t in self.link_targets + self.link_whole_targets:
  678. transitive_deps.append(t)
  679. if isinstance(t, StaticLibrary):
  680. transitive_deps += t.get_dependencies()
  681. return transitive_deps
  682. def get_source_subdir(self):
  683. return self.subdir
  684. def get_sources(self):
  685. return self.sources
  686. def get_objects(self):
  687. return self.objects
  688. def get_generated_sources(self):
  689. return self.generated
  690. def should_install(self):
  691. return self.need_install
  692. def has_pch(self):
  693. return len(self.pch) > 0
  694. def get_pch(self, language):
  695. try:
  696. return self.pch[language]
  697. except KeyError:
  698. return[]
  699. def get_include_dirs(self):
  700. return self.include_dirs
  701. def add_deps(self, deps):
  702. if not isinstance(deps, list):
  703. deps = [deps]
  704. for dep in deps:
  705. if hasattr(dep, 'held_object'):
  706. dep = dep.held_object
  707. if isinstance(dep, dependencies.InternalDependency):
  708. # Those parts that are internal.
  709. self.process_sourcelist(dep.sources)
  710. self.add_include_dirs(dep.include_directories)
  711. for l in dep.libraries:
  712. self.link(l)
  713. # Those parts that are external.
  714. extpart = dependencies.InternalDependency('undefined',
  715. [],
  716. dep.compile_args,
  717. dep.link_args,
  718. [], [], [])
  719. self.external_deps.append(extpart)
  720. # Deps of deps.
  721. self.add_deps(dep.ext_deps)
  722. elif isinstance(dep, dependencies.ExternalDependency):
  723. self.external_deps.append(dep)
  724. self.process_sourcelist(dep.get_sources())
  725. elif isinstance(dep, BuildTarget):
  726. raise InvalidArguments('''Tried to use a build target as a dependency.
  727. You probably should put it in link_with instead.''')
  728. else:
  729. # This is a bit of a hack. We do not want Build to know anything
  730. # about the interpreter so we can't import it and use isinstance.
  731. # This should be reliable enough.
  732. if hasattr(dep, 'args_frozen'):
  733. raise InvalidArguments('Tried to use subproject object as a dependency.\n'
  734. 'You probably wanted to use a dependency declared in it instead.\n'
  735. 'Access it by calling get_variable() on the subproject object.')
  736. raise InvalidArguments('Argument is of an unacceptable type {!r}.\nMust be '
  737. 'either an external dependency (returned by find_library() or '
  738. 'dependency()) or an internal dependency (returned by '
  739. 'declare_dependency()).'.format(type(dep).__name__))
  740. def get_external_deps(self):
  741. return self.external_deps
  742. def link(self, target):
  743. for t in flatten(target):
  744. if hasattr(t, 'held_object'):
  745. t = t.held_object
  746. if not isinstance(t, (StaticLibrary, SharedLibrary)):
  747. raise InvalidArguments('Link target {!r} is not library.'.format(t))
  748. if isinstance(self, SharedLibrary) and isinstance(t, StaticLibrary) and not t.pic:
  749. msg = "Can't link non-PIC static library {!r} into shared library {!r}. ".format(t.name, self.name)
  750. msg += "Use the 'pic' option to static_library to build with PIC."
  751. raise InvalidArguments(msg)
  752. if self.is_cross != t.is_cross:
  753. raise InvalidArguments('Tried to mix cross built and native libraries in target {!r}'.format(self.name))
  754. self.link_targets.append(t)
  755. def link_whole(self, target):
  756. for t in flatten(target):
  757. if hasattr(t, 'held_object'):
  758. t = t.held_object
  759. if not isinstance(t, StaticLibrary):
  760. raise InvalidArguments('{!r} is not a static library.'.format(t))
  761. if isinstance(self, SharedLibrary) and not t.pic:
  762. msg = "Can't link non-PIC static library {!r} into shared library {!r}. ".format(t.name, self.name)
  763. msg += "Use the 'pic' option to static_library to build with PIC."
  764. raise InvalidArguments(msg)
  765. if self.is_cross != t.is_cross:
  766. raise InvalidArguments('Tried to mix cross built and native libraries in target {!r}'.format(self.name))
  767. self.link_whole_targets.append(t)
  768. def add_pch(self, language, pchlist):
  769. if not pchlist:
  770. return
  771. elif len(pchlist) == 1:
  772. if not environment.is_header(pchlist[0]):
  773. raise InvalidArguments('PCH argument %s is not a header.' % pchlist[0])
  774. elif len(pchlist) == 2:
  775. if environment.is_header(pchlist[0]):
  776. if not environment.is_source(pchlist[1]):
  777. raise InvalidArguments('PCH definition must contain one header and at most one source.')
  778. elif environment.is_source(pchlist[0]):
  779. if not environment.is_header(pchlist[1]):
  780. raise InvalidArguments('PCH definition must contain one header and at most one source.')
  781. pchlist = [pchlist[1], pchlist[0]]
  782. else:
  783. raise InvalidArguments('PCH argument %s is of unknown type.' % pchlist[0])
  784. elif len(pchlist) > 2:
  785. raise InvalidArguments('PCH definition may have a maximum of 2 files.')
  786. self.pch[language] = pchlist
  787. def add_include_dirs(self, args):
  788. ids = []
  789. for a in args:
  790. # FIXME same hack, forcibly unpack from holder.
  791. if hasattr(a, 'held_object'):
  792. a = a.held_object
  793. if not isinstance(a, IncludeDirs):
  794. raise InvalidArguments('Include directory to be added is not an include directory object.')
  795. ids.append(a)
  796. self.include_dirs += ids
  797. def add_compiler_args(self, language, args):
  798. args = flatten(args)
  799. for a in args:
  800. if not isinstance(a, (str, File)):
  801. raise InvalidArguments('A non-string passed to compiler args.')
  802. if language in self.extra_args:
  803. self.extra_args[language] += args
  804. else:
  805. self.extra_args[language] = args
  806. def get_aliases(self):
  807. return {}
  808. def get_langs_used_by_deps(self):
  809. '''
  810. Sometimes you want to link to a C++ library that exports C API, which
  811. means the linker must link in the C++ stdlib, and we must use a C++
  812. compiler for linking. The same is also applicable for objc/objc++, etc,
  813. so we can keep using clike_langs for the priority order.
  814. See: https://github.com/mesonbuild/meson/issues/1653
  815. '''
  816. langs = []
  817. # Check if any of the external libraries were written in this language
  818. for dep in self.external_deps:
  819. if dep.language not in langs:
  820. langs.append(dep.language)
  821. # Check if any of the internal libraries this target links to were
  822. # written in this language
  823. for link_target in self.link_targets:
  824. for language in link_target.compilers:
  825. if language not in langs:
  826. langs.append(language)
  827. return langs
  828. def get_clike_dynamic_linker(self):
  829. '''
  830. We use the order of languages in `clike_langs` to determine which
  831. linker to use in case the target has sources compiled with multiple
  832. compilers. All languages other than those in this list have their own
  833. linker.
  834. Note that Vala outputs C code, so Vala sources can use any linker
  835. that can link compiled C. We don't actually need to add an exception
  836. for Vala here because of that.
  837. '''
  838. # Populate list of all compilers, not just those being used to compile
  839. # sources in this target
  840. if self.is_cross:
  841. all_compilers = self.environment.coredata.cross_compilers
  842. else:
  843. all_compilers = self.environment.coredata.compilers
  844. # Languages used by dependencies
  845. dep_langs = self.get_langs_used_by_deps()
  846. # Pick a compiler based on the language priority-order
  847. for l in clike_langs:
  848. if l in self.compilers or l in dep_langs:
  849. try:
  850. return all_compilers[l]
  851. except KeyError:
  852. raise MesonException(
  853. 'Could not get a dynamic linker for build target {!r}. '
  854. 'Requires a linker for language "{}", but that is not '
  855. 'a project language.'.format(self.name, l))
  856. m = 'Could not get a dynamic linker for build target {!r}'
  857. raise AssertionError(m.format(self.name))
  858. def get_using_msvc(self):
  859. '''
  860. Check if the dynamic linker is MSVC. Used by Executable, StaticLibrary,
  861. and SharedLibrary for deciding when to use MSVC-specific file naming
  862. and debug filenames.
  863. If at least some code is built with MSVC and the final library is
  864. linked with MSVC, we can be sure that some debug info will be
  865. generated. We only check the dynamic linker here because the static
  866. linker is guaranteed to be of the same type.
  867. Interesting cases:
  868. 1. The Vala compiler outputs C code to be compiled by whatever
  869. C compiler we're using, so all objects will still be created by the
  870. MSVC compiler.
  871. 2. If the target contains only objects, process_compilers guesses and
  872. picks the first compiler that smells right.
  873. '''
  874. linker = self.get_clike_dynamic_linker()
  875. if linker and linker.get_id() == 'msvc':
  876. return True
  877. return False
  878. class Generator:
  879. def __init__(self, args, kwargs):
  880. if len(args) != 1:
  881. raise InvalidArguments('Generator requires exactly one positional argument: the executable')
  882. exe = args[0]
  883. if hasattr(exe, 'held_object'):
  884. exe = exe.held_object
  885. if not isinstance(exe, (Executable, dependencies.ExternalProgram)):
  886. raise InvalidArguments('First generator argument must be an executable.')
  887. self.exe = exe
  888. self.depfile = None
  889. self.process_kwargs(kwargs)
  890. def __repr__(self):
  891. repr_str = "<{0}: {1}>"
  892. return repr_str.format(self.__class__.__name__, self.exe)
  893. def get_exe(self):
  894. return self.exe
  895. def process_kwargs(self, kwargs):
  896. if 'arguments' not in kwargs:
  897. raise InvalidArguments('Generator must have "arguments" keyword argument.')
  898. args = kwargs['arguments']
  899. if isinstance(args, str):
  900. args = [args]
  901. if not isinstance(args, list):
  902. raise InvalidArguments('"Arguments" keyword argument must be a string or a list of strings.')
  903. for a in args:
  904. if not isinstance(a, str):
  905. raise InvalidArguments('A non-string object in "arguments" keyword argument.')
  906. self.arglist = args
  907. if 'output' not in kwargs:
  908. raise InvalidArguments('Generator must have "output" keyword argument.')
  909. outputs = kwargs['output']
  910. if not isinstance(outputs, list):
  911. outputs = [outputs]
  912. for rule in outputs:
  913. if not isinstance(rule, str):
  914. raise InvalidArguments('"output" may only contain strings.')
  915. if '@BASENAME@' not in rule and '@PLAINNAME@' not in rule:
  916. raise InvalidArguments('Every element of "output" must contain @BASENAME@ or @PLAINNAME@.')
  917. if '/' in rule or '\\' in rule:
  918. raise InvalidArguments('"outputs" must not contain a directory separator.')
  919. if len(outputs) > 1:
  920. for o in outputs:
  921. if '@OUTPUT@' in o:
  922. raise InvalidArguments('Tried to use @OUTPUT@ in a rule with more than one output.')
  923. self.outputs = outputs
  924. if 'depfile' in kwargs:
  925. depfile = kwargs['depfile']
  926. if not isinstance(depfile, str):
  927. raise InvalidArguments('Depfile must be a string.')
  928. if os.path.split(depfile)[1] != depfile:
  929. raise InvalidArguments('Depfile must be a plain filename without a subdirectory.')
  930. self.depfile = depfile
  931. def get_base_outnames(self, inname):
  932. plainname = os.path.split(inname)[1]
  933. basename = os.path.splitext(plainname)[0]
  934. return [x.replace('@BASENAME@', basename).replace('@PLAINNAME@', plainname) for x in self.outputs]
  935. def get_dep_outname(self, inname):
  936. if self.depfile is None:
  937. raise InvalidArguments('Tried to get dep name for rule that does not have dependency file defined.')
  938. plainname = os.path.split(inname)[1]
  939. basename = os.path.splitext(plainname)[0]
  940. return self.depfile.replace('@BASENAME@', basename).replace('@PLAINNAME@', plainname)
  941. def get_arglist(self):
  942. return self.arglist
  943. def process_files(self, name, files, state, extra_args=[]):
  944. output = GeneratedList(self, extra_args=extra_args)
  945. for f in files:
  946. if isinstance(f, str):
  947. f = File.from_source_file(state.environment.source_dir, state.subdir, f)
  948. elif not isinstance(f, File):
  949. raise InvalidArguments('{} arguments must be strings or files not {!r}.'.format(name, f))
  950. output.add_file(f)
  951. return output
  952. class GeneratedList:
  953. def __init__(self, generator, extra_args=[]):
  954. if hasattr(generator, 'held_object'):
  955. generator = generator.held_object
  956. self.generator = generator
  957. self.name = self.generator.exe
  958. self.infilelist = []
  959. self.outfilelist = []
  960. self.outmap = {}
  961. self.extra_depends = []
  962. self.extra_args = extra_args
  963. def add_file(self, newfile):
  964. self.infilelist.append(newfile)
  965. outfiles = self.generator.get_base_outnames(newfile.fname)
  966. self.outfilelist += outfiles
  967. self.outmap[newfile] = outfiles
  968. def get_inputs(self):
  969. return self.infilelist
  970. def get_outputs(self):
  971. return self.outfilelist
  972. def get_outputs_for(self, filename):
  973. return self.outmap[filename]
  974. def get_generator(self):
  975. return self.generator
  976. def get_extra_args(self):
  977. return self.extra_args
  978. class Executable(BuildTarget):
  979. def __init__(self, name, subdir, subproject, is_cross, sources, objects, environment, kwargs):
  980. super().__init__(name, subdir, subproject, is_cross, sources, objects, environment, kwargs)
  981. # Unless overriden, executables have no suffix or prefix. Except on
  982. # Windows and with C#/Mono executables where the suffix is 'exe'
  983. if not hasattr(self, 'prefix'):
  984. self.prefix = ''
  985. if not hasattr(self, 'suffix'):
  986. # Executable for Windows or C#/Mono
  987. if (for_windows(is_cross, environment) or
  988. for_cygwin(is_cross, environment) or 'cs' in self.compilers):
  989. self.suffix = 'exe'
  990. else:
  991. self.suffix = ''
  992. self.filename = self.name
  993. if self.suffix:
  994. self.filename += '.' + self.suffix
  995. self.outputs = [self.filename]
  996. def type_suffix(self):
  997. return "@exe"
  998. class StaticLibrary(BuildTarget):
  999. def __init__(self, name, subdir, subproject, is_cross, sources, objects, environment, kwargs):
  1000. if 'pic' not in kwargs and 'b_staticpic' in environment.coredata.base_options:
  1001. kwargs['pic'] = environment.coredata.base_options['b_staticpic'].value
  1002. super().__init__(name, subdir, subproject, is_cross, sources, objects, environment, kwargs)
  1003. if 'cs' in self.compilers:
  1004. raise InvalidArguments('Static libraries not supported for C#.')
  1005. # By default a static library is named libfoo.a even on Windows because
  1006. # MSVC does not have a consistent convention for what static libraries
  1007. # are called. The MSVC CRT uses libfoo.lib syntax but nothing else uses
  1008. # it and GCC only looks for static libraries called foo.lib and
  1009. # libfoo.a. However, we cannot use foo.lib because that's the same as
  1010. # the import library. Using libfoo.a is ok because people using MSVC
  1011. # always pass the library filename while linking anyway.
  1012. if not hasattr(self, 'prefix'):
  1013. self.prefix = 'lib'
  1014. if not hasattr(self, 'suffix'):
  1015. # Rust static library crates have .rlib suffix
  1016. if 'rust' in self.compilers:
  1017. self.suffix = 'rlib'
  1018. else:
  1019. self.suffix = 'a'
  1020. self.filename = self.prefix + self.name + '.' + self.suffix
  1021. self.outputs = [self.filename]
  1022. def type_suffix(self):
  1023. return "@sta"
  1024. def check_unknown_kwargs(self, kwargs):
  1025. self.check_unknown_kwargs_int(kwargs, known_lib_kwargs)
  1026. class SharedLibrary(BuildTarget):
  1027. def __init__(self, name, subdir, subproject, is_cross, sources, objects, environment, kwargs):
  1028. self.soversion = None
  1029. self.ltversion = None
  1030. self.vs_module_defs = None
  1031. # The import library this target will generate
  1032. self.import_filename = None
  1033. # The import library that Visual Studio would generate (and accept)
  1034. self.vs_import_filename = None
  1035. # The import library that GCC would generate (and prefer)
  1036. self.gcc_import_filename = None
  1037. super().__init__(name, subdir, subproject, is_cross, sources, objects, environment, kwargs)
  1038. if not hasattr(self, 'prefix'):
  1039. self.prefix = None
  1040. if not hasattr(self, 'suffix'):
  1041. self.suffix = None
  1042. self.basic_filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
  1043. self.determine_filenames(is_cross, environment)
  1044. def determine_filenames(self, is_cross, env):
  1045. """
  1046. See https://github.com/mesonbuild/meson/pull/417 for details.
  1047. First we determine the filename template (self.filename_tpl), then we
  1048. set the output filename (self.filename).
  1049. The template is needed while creating aliases (self.get_aliases),
  1050. which are needed while generating .so shared libraries for Linux.
  1051. Besides this, there's also the import library name, which is only used
  1052. on Windows since on that platform the linker uses a separate library
  1053. called the "import library" during linking instead of the shared
  1054. library (DLL). The toolchain will output an import library in one of
  1055. two formats: GCC or Visual Studio.
  1056. When we're building with Visual Studio, the import library that will be
  1057. generated by the toolchain is self.vs_import_filename, and with
  1058. MinGW/GCC, it's self.gcc_import_filename. self.import_filename will
  1059. always contain the import library name this target will generate.
  1060. """
  1061. prefix = ''
  1062. suffix = ''
  1063. self.filename_tpl = self.basic_filename_tpl
  1064. # If the user already provided the prefix and suffix to us, we don't
  1065. # need to do any filename suffix/prefix detection.
  1066. # NOTE: manual prefix/suffix override is currently only tested for C/C++
  1067. if self.prefix is not None and self.suffix is not None:
  1068. pass
  1069. # C# and Mono
  1070. elif 'cs' in self.compilers:
  1071. prefix = ''
  1072. suffix = 'dll'
  1073. self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
  1074. # Rust
  1075. elif 'rust' in self.compilers:
  1076. # Currently, we always build --crate-type=rlib
  1077. prefix = 'lib'
  1078. suffix = 'rlib'
  1079. self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
  1080. # C, C++, Swift, Vala
  1081. # Only Windows uses a separate import library for linking
  1082. # For all other targets/platforms import_filename stays None
  1083. elif for_windows(is_cross, env):
  1084. suffix = 'dll'
  1085. self.vs_import_filename = '{0}.lib'.format(self.name)
  1086. self.gcc_import_filename = 'lib{0}.dll.a'.format(self.name)
  1087. if self.get_using_msvc():
  1088. # Shared library is of the form foo.dll
  1089. prefix = ''
  1090. # Import library is called foo.lib
  1091. self.import_filename = self.vs_import_filename
  1092. # Assume GCC-compatible naming
  1093. else:
  1094. # Shared library is of the form libfoo.dll
  1095. prefix = 'lib'
  1096. # Import library is called libfoo.dll.a
  1097. self.import_filename = self.gcc_import_filename
  1098. # Shared library has the soversion if it is defined
  1099. if self.soversion:
  1100. self.filename_tpl = '{0.prefix}{0.name}-{0.soversion}.{0.suffix}'
  1101. else:
  1102. self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
  1103. elif for_cygwin(is_cross, env):
  1104. suffix = 'dll'
  1105. self.gcc_import_filename = 'lib{0}.dll.a'.format(self.name)
  1106. # Shared library is of the form cygfoo.dll
  1107. # (ld --dll-search-prefix=cyg is the default)
  1108. prefix = 'cyg'
  1109. # Import library is called libfoo.dll.a
  1110. self.import_filename = self.gcc_import_filename
  1111. if self.soversion:
  1112. self.filename_tpl = '{0.prefix}{0.name}-{0.soversion}.{0.suffix}'
  1113. else:
  1114. self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
  1115. elif for_darwin(is_cross, env):
  1116. prefix = 'lib'
  1117. suffix = 'dylib'
  1118. # On macOS, the filename can only contain the major version
  1119. if self.soversion:
  1120. # libfoo.X.dylib
  1121. self.filename_tpl = '{0.prefix}{0.name}.{0.soversion}.{0.suffix}'
  1122. else:
  1123. # libfoo.dylib
  1124. self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
  1125. else:
  1126. prefix = 'lib'
  1127. suffix = 'so'
  1128. if self.ltversion:
  1129. # libfoo.so.X[.Y[.Z]] (.Y and .Z are optional)
  1130. self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}.{0.ltversion}'
  1131. elif self.soversion:
  1132. # libfoo.so.X
  1133. self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}.{0.soversion}'
  1134. else:
  1135. # No versioning, libfoo.so
  1136. self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
  1137. if self.prefix is None:
  1138. self.prefix = prefix
  1139. if self.suffix is None:
  1140. self.suffix = suffix
  1141. self.filename = self.filename_tpl.format(self)
  1142. self.outputs = [self.filename]
  1143. def process_kwargs(self, kwargs, environment):
  1144. super().process_kwargs(kwargs, environment)
  1145. # Shared library version
  1146. if 'version' in kwargs:
  1147. self.ltversion = kwargs['version']
  1148. if not isinstance(self.ltversion, str):
  1149. raise InvalidArguments('Shared library version needs to be a string, not ' + type(self.ltversion).__name__)
  1150. if not re.fullmatch(r'[0-9]+(\.[0-9]+){0,2}', self.ltversion):
  1151. 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))
  1152. # Try to extract/deduce the soversion
  1153. if 'soversion' in kwargs:
  1154. self.soversion = kwargs['soversion']
  1155. if isinstance(self.soversion, int):
  1156. self.soversion = str(self.soversion)
  1157. if not isinstance(self.soversion, str):
  1158. raise InvalidArguments('Shared library soversion is not a string or integer.')
  1159. elif self.ltversion:
  1160. # library version is defined, get the soversion from that
  1161. # We replicate what Autotools does here and take the first
  1162. # number of the version by default.
  1163. self.soversion = self.ltversion.split('.')[0]
  1164. # Visual Studio module-definitions file
  1165. if 'vs_module_defs' in kwargs:
  1166. path = kwargs['vs_module_defs']
  1167. if hasattr(path, 'held_object'):
  1168. path = path.held_object
  1169. if isinstance(path, str):
  1170. if os.path.isabs(path):
  1171. self.vs_module_defs = File.from_absolute_file(path)
  1172. else:
  1173. self.vs_module_defs = File.from_source_file(environment.source_dir, self.subdir, path)
  1174. self.link_depends.append(self.vs_module_defs)
  1175. elif isinstance(path, File):
  1176. # When passing a generated file.
  1177. self.vs_module_defs = path
  1178. self.link_depends.append(path)
  1179. elif hasattr(path, 'get_filename'):
  1180. # When passing output of a Custom Target
  1181. path = File.from_built_file(path.subdir, path.get_filename())
  1182. self.vs_module_defs = path
  1183. self.link_depends.append(path)
  1184. else:
  1185. raise InvalidArguments(
  1186. 'Shared library vs_module_defs must be either a string, '
  1187. 'a file object or a Custom Target')
  1188. def check_unknown_kwargs(self, kwargs):
  1189. self.check_unknown_kwargs_int(kwargs, known_lib_kwargs)
  1190. def get_import_filename(self):
  1191. """
  1192. The name of the import library that will be outputted by the compiler
  1193. Returns None if there is no import library required for this platform
  1194. """
  1195. return self.import_filename
  1196. def get_import_filenameslist(self):
  1197. if self.import_filename:
  1198. return [self.vs_import_filename, self.gcc_import_filename]
  1199. return []
  1200. def get_all_link_deps(self):
  1201. return [self] + self.get_transitive_link_deps()
  1202. def get_aliases(self):
  1203. """
  1204. If the versioned library name is libfoo.so.0.100.0, aliases are:
  1205. * libfoo.so.0 (soversion) -> libfoo.so.0.100.0
  1206. * libfoo.so (unversioned; for linking) -> libfoo.so.0
  1207. Same for dylib:
  1208. * libfoo.dylib (unversioned; for linking) -> libfoo.0.dylib
  1209. """
  1210. aliases = {}
  1211. # Aliases are only useful with .so and .dylib libraries. Also if
  1212. # there's no self.soversion (no versioning), we don't need aliases.
  1213. if self.suffix not in ('so', 'dylib') or not self.soversion:
  1214. return {}
  1215. # With .so libraries, the minor and micro versions are also in the
  1216. # filename. If ltversion != soversion we create an soversion alias:
  1217. # libfoo.so.0 -> libfoo.so.0.100.0
  1218. # Where libfoo.so.0.100.0 is the actual library
  1219. if self.suffix == 'so' and self.ltversion and self.ltversion != self.soversion:
  1220. alias_tpl = self.filename_tpl.replace('ltversion', 'soversion')
  1221. ltversion_filename = alias_tpl.format(self)
  1222. aliases[ltversion_filename] = self.filename
  1223. # libfoo.so.0/libfoo.0.dylib is the actual library
  1224. else:
  1225. ltversion_filename = self.filename
  1226. # Unversioned alias:
  1227. # libfoo.so -> libfoo.so.0
  1228. # libfoo.dylib -> libfoo.0.dylib
  1229. aliases[self.basic_filename_tpl.format(self)] = ltversion_filename
  1230. return aliases
  1231. def type_suffix(self):
  1232. return "@sha"
  1233. # A shared library that is meant to be used with dlopen rather than linking
  1234. # into something else.
  1235. class SharedModule(SharedLibrary):
  1236. def __init__(self, name, subdir, subproject, is_cross, sources, objects, environment, kwargs):
  1237. if 'version' in kwargs:
  1238. raise MesonException('Shared modules must not specify the version kwarg.')
  1239. if 'soversion' in kwargs:
  1240. raise MesonException('Shared modules must not specify the soversion kwarg.')
  1241. super().__init__(name, subdir, subproject, is_cross, sources, objects, environment, kwargs)
  1242. self.import_filename = None
  1243. class CustomTarget(Target):
  1244. known_kwargs = {'input': True,
  1245. 'output': True,
  1246. 'command': True,
  1247. 'capture': False,
  1248. 'install': True,
  1249. 'install_dir': True,
  1250. 'build_always': True,
  1251. 'depends': True,
  1252. 'depend_files': True,
  1253. 'depfile': True,
  1254. 'build_by_default': True,
  1255. 'override_options': True,
  1256. }
  1257. def __init__(self, name, subdir, kwargs, absolute_paths=False):
  1258. super().__init__(name, subdir, False)
  1259. self.dependencies = []
  1260. self.extra_depends = []
  1261. self.depend_files = [] # Files that this target depends on but are not on the command line.
  1262. self.depfile = None
  1263. self.process_kwargs(kwargs)
  1264. self.extra_files = []
  1265. # Whether to use absolute paths for all files on the commandline
  1266. self.absolute_paths = absolute_paths
  1267. unknowns = []
  1268. for k in kwargs:
  1269. if k not in CustomTarget.known_kwargs:
  1270. unknowns.append(k)
  1271. if len(unknowns) > 0:
  1272. mlog.warning('Unknown keyword arguments in target %s: %s' %
  1273. (self.name, ', '.join(unknowns)))
  1274. def __lt__(self, other):
  1275. return self.get_id() < other.get_id()
  1276. def __repr__(self):
  1277. repr_str = "<{0} {1}: {2}>"
  1278. return repr_str.format(self.__class__.__name__, self.get_id(), self.command)
  1279. def get_id(self):
  1280. return self.name + self.type_suffix()
  1281. def get_target_dependencies(self):
  1282. deps = self.dependencies[:]
  1283. deps += self.extra_depends
  1284. for c in self.sources:
  1285. if hasattr(c, 'held_object'):
  1286. c = c.held_object
  1287. if isinstance(c, (BuildTarget, CustomTarget)):
  1288. deps.append(c)
  1289. return deps
  1290. def flatten_command(self, cmd):
  1291. if not isinstance(cmd, list):
  1292. cmd = [cmd]
  1293. final_cmd = []
  1294. for c in cmd:
  1295. if hasattr(c, 'held_object'):
  1296. c = c.held_object
  1297. if isinstance(c, str):
  1298. final_cmd.append(c)
  1299. elif isinstance(c, File):
  1300. self.depend_files.append(c)
  1301. final_cmd.append(c)
  1302. elif isinstance(c, dependencies.ExternalProgram):
  1303. if not c.found():
  1304. m = 'Tried to use not-found external program {!r} in "command"'
  1305. raise InvalidArguments(m.format(c.name))
  1306. self.depend_files.append(File.from_absolute_file(c.get_path()))
  1307. final_cmd += c.get_command()
  1308. elif isinstance(c, (BuildTarget, CustomTarget)):
  1309. self.dependencies.append(c)
  1310. final_cmd.append(c)
  1311. elif isinstance(c, list):
  1312. final_cmd += self.flatten_command(c)
  1313. else:
  1314. raise InvalidArguments('Argument {!r} in "command" is invalid'.format(c))
  1315. return final_cmd
  1316. def process_kwargs(self, kwargs):
  1317. super().process_kwargs(kwargs)
  1318. self.sources = kwargs.get('input', [])
  1319. self.sources = flatten(self.sources)
  1320. if 'output' not in kwargs:
  1321. raise InvalidArguments('Missing keyword argument "output".')
  1322. self.outputs = kwargs['output']
  1323. if not isinstance(self.outputs, list):
  1324. self.outputs = [self.outputs]
  1325. # This will substitute values from the input into output and return it.
  1326. inputs = get_sources_string_names(self.sources)
  1327. values = get_filenames_templates_dict(inputs, [])
  1328. for i in self.outputs:
  1329. if not(isinstance(i, str)):
  1330. raise InvalidArguments('Output argument not a string.')
  1331. if '/' in i:
  1332. raise InvalidArguments('Output must not contain a path segment.')
  1333. if '@INPUT@' in i or '@INPUT0@' in i:
  1334. m = 'Output cannot contain @INPUT@ or @INPUT0@, did you ' \
  1335. 'mean @PLAINNAME@ or @BASENAME@?'
  1336. raise InvalidArguments(m)
  1337. # We already check this during substitution, but the error message
  1338. # will be unclear/confusing, so check it here.
  1339. if len(inputs) != 1 and ('@PLAINNAME@' in i or '@BASENAME@' in i):
  1340. m = "Output cannot contain @PLAINNAME@ or @BASENAME@ when " \
  1341. "there is more than one input (we can't know which to use)"
  1342. raise InvalidArguments(m)
  1343. self.outputs = substitute_values(self.outputs, values)
  1344. self.capture = kwargs.get('capture', False)
  1345. if self.capture and len(self.outputs) != 1:
  1346. raise InvalidArguments('Capturing can only output to a single file.')
  1347. if 'command' not in kwargs:
  1348. raise InvalidArguments('Missing keyword argument "command".')
  1349. if 'depfile' in kwargs:
  1350. depfile = kwargs['depfile']
  1351. if not isinstance(depfile, str):
  1352. raise InvalidArguments('Depfile must be a string.')
  1353. if os.path.split(depfile)[1] != depfile:
  1354. raise InvalidArguments('Depfile must be a plain filename without a subdirectory.')
  1355. self.depfile = depfile
  1356. self.command = self.flatten_command(kwargs['command'])
  1357. if self.capture:
  1358. for c in self.command:
  1359. if isinstance(c, str) and '@OUTPUT@' in c:
  1360. raise InvalidArguments('@OUTPUT@ is not allowed when capturing output.')
  1361. if 'install' in kwargs:
  1362. self.install = kwargs['install']
  1363. if not isinstance(self.install, bool):
  1364. raise InvalidArguments('"install" must be boolean.')
  1365. if self.install:
  1366. if 'install_dir' not in kwargs:
  1367. raise InvalidArguments('"install_dir" must be specified '
  1368. 'when installing a target')
  1369. # If an item in this list is False, the output corresponding to
  1370. # the list index of that item will not be installed
  1371. self.install_dir = typeslistify(kwargs['install_dir'], (str, bool))
  1372. else:
  1373. self.install = False
  1374. self.install_dir = [None]
  1375. self.build_always = kwargs.get('build_always', False)
  1376. if not isinstance(self.build_always, bool):
  1377. raise InvalidArguments('Argument build_always must be a boolean.')
  1378. extra_deps = kwargs.get('depends', [])
  1379. if not isinstance(extra_deps, list):
  1380. extra_deps = [extra_deps]
  1381. for ed in extra_deps:
  1382. while hasattr(ed, 'held_object'):
  1383. ed = ed.held_object
  1384. if not isinstance(ed, (CustomTarget, BuildTarget)):
  1385. raise InvalidArguments('Can only depend on toplevel targets: custom_target or build_target (executable or a library)')
  1386. self.extra_depends.append(ed)
  1387. depend_files = kwargs.get('depend_files', [])
  1388. if not isinstance(depend_files, list):
  1389. depend_files = [depend_files]
  1390. for i in depend_files:
  1391. if isinstance(i, (File, str)):
  1392. self.depend_files.append(i)
  1393. else:
  1394. mlog.debug(i)
  1395. raise InvalidArguments('Unknown type {!r} in depend_files.'.format(type(i).__name__))
  1396. def get_dependencies(self):
  1397. return self.dependencies
  1398. def should_install(self):
  1399. return self.install
  1400. def get_custom_install_dir(self):
  1401. return self.install_dir
  1402. def get_outputs(self):
  1403. return self.outputs
  1404. def get_filename(self):
  1405. return self.outputs[0]
  1406. def get_sources(self):
  1407. return self.sources
  1408. def get_generated_lists(self):
  1409. genlists = []
  1410. for c in self.sources:
  1411. if hasattr(c, 'held_object'):
  1412. c = c.held_object
  1413. if isinstance(c, GeneratedList):
  1414. genlists.append(c)
  1415. return genlists
  1416. def get_generated_sources(self):
  1417. return self.get_generated_lists()
  1418. def type_suffix(self):
  1419. return "@cus"
  1420. class RunTarget(Target):
  1421. def __init__(self, name, command, args, dependencies, subdir):
  1422. super().__init__(name, subdir, False)
  1423. self.command = command
  1424. self.args = args
  1425. self.dependencies = dependencies
  1426. def __lt__(self, other):
  1427. return self.get_id() < other.get_id()
  1428. def __repr__(self):
  1429. repr_str = "<{0} {1}: {2}>"
  1430. return repr_str.format(self.__class__.__name__, self.get_id(), self.command)
  1431. def get_id(self):
  1432. return self.name + self.type_suffix()
  1433. def get_dependencies(self):
  1434. return self.dependencies
  1435. def get_generated_sources(self):
  1436. return []
  1437. def get_sources(self):
  1438. return []
  1439. def should_install(self):
  1440. return False
  1441. def get_filename(self):
  1442. return self.name
  1443. def type_suffix(self):
  1444. return "@run"
  1445. class Jar(BuildTarget):
  1446. def __init__(self, name, subdir, subproject, is_cross, sources, objects, environment, kwargs):
  1447. super().__init__(name, subdir, subproject, is_cross, sources, objects, environment, kwargs)
  1448. for s in self.sources:
  1449. if not s.endswith('.java'):
  1450. raise InvalidArguments('Jar source %s is not a java file.' % s)
  1451. self.filename = self.name + '.jar'
  1452. self.outputs = [self.filename]
  1453. self.java_args = kwargs.get('java_args', [])
  1454. def get_main_class(self):
  1455. return self.main_class
  1456. def type_suffix(self):
  1457. return "@jar"
  1458. def get_java_args(self):
  1459. return self.java_args
  1460. def validate_cross_install(self, environment):
  1461. # All jar targets are installable.
  1462. pass
  1463. class ConfigureFile:
  1464. def __init__(self, subdir, sourcename, targetname, configuration_data):
  1465. self.subdir = subdir
  1466. self.sourcename = sourcename
  1467. self.targetname = targetname
  1468. self.configuration_data = configuration_data
  1469. def __repr__(self):
  1470. repr_str = "<{0}: {1} -> {2}>"
  1471. src = os.path.join(self.subdir, self.sourcename)
  1472. dst = os.path.join(self.subdir, self.targetname)
  1473. return repr_str.format(self.__class__.__name__, src, dst)
  1474. def get_configuration_data(self):
  1475. return self.configuration_data
  1476. def get_subdir(self):
  1477. return self.subdir
  1478. def get_source_name(self):
  1479. return self.sourcename
  1480. def get_target_name(self):
  1481. return self.targetname
  1482. class ConfigurationData:
  1483. def __init__(self):
  1484. super().__init__()
  1485. self.values = {}
  1486. def __repr__(self):
  1487. return repr(self.values)
  1488. def __contains__(self, value):
  1489. return value in self.values
  1490. def get(self, name):
  1491. return self.values[name] # (val, desc)
  1492. def keys(self):
  1493. return self.values.keys()
  1494. # A bit poorly named, but this represents plain data files to copy
  1495. # during install.
  1496. class Data:
  1497. def __init__(self, sources, install_dir, install_mode=None):
  1498. self.sources = sources
  1499. self.install_dir = install_dir
  1500. self.install_mode = install_mode
  1501. if not isinstance(self.sources, list):
  1502. self.sources = [self.sources]
  1503. for s in self.sources:
  1504. assert(isinstance(s, File))
  1505. class RunScript(dict):
  1506. def __init__(self, script, args):
  1507. super().__init__()
  1508. assert(isinstance(script, list))
  1509. assert(isinstance(args, list))
  1510. self['exe'] = script
  1511. self['args'] = args
  1512. class TestSetup:
  1513. def __init__(self, *, exe_wrapper=None, gdb=None, timeout_multiplier=None, env=None):
  1514. self.exe_wrapper = exe_wrapper
  1515. self.gdb = gdb
  1516. self.timeout_multiplier = timeout_multiplier
  1517. self.env = env
  1518. def get_sources_string_names(sources):
  1519. '''
  1520. For the specified list of @sources which can be strings, Files, or targets,
  1521. get all the output basenames.
  1522. '''
  1523. names = []
  1524. for s in sources:
  1525. if hasattr(s, 'held_object'):
  1526. s = s.held_object
  1527. if isinstance(s, str):
  1528. names.append(s)
  1529. elif isinstance(s, (BuildTarget, CustomTarget, GeneratedList)):
  1530. names += s.get_outputs()
  1531. elif isinstance(s, File):
  1532. names.append(s.fname)
  1533. else:
  1534. raise AssertionError('Unknown source type: {!r}'.format(s))
  1535. return names