build.py 75 KB

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