backends.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  1. # Copyright 2012-2016 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 os, pickle, re
  12. from .. import build
  13. from .. import dependencies
  14. from .. import mesonlib
  15. from .. import mlog
  16. from .. import compilers
  17. import json
  18. import subprocess
  19. from ..mesonlib import MesonException, OrderedSet
  20. from ..mesonlib import classify_unity_sources
  21. from ..mesonlib import File
  22. from ..compilers import CompilerArgs
  23. from collections import OrderedDict
  24. import shlex
  25. class CleanTrees:
  26. '''
  27. Directories outputted by custom targets that have to be manually cleaned
  28. because on Linux `ninja clean` only deletes empty directories.
  29. '''
  30. def __init__(self, build_dir, trees):
  31. self.build_dir = build_dir
  32. self.trees = trees
  33. class InstallData:
  34. def __init__(self, source_dir, build_dir, prefix, strip_bin,
  35. install_umask, mesonintrospect):
  36. self.source_dir = source_dir
  37. self.build_dir = build_dir
  38. self.prefix = prefix
  39. self.strip_bin = strip_bin
  40. self.install_umask = install_umask
  41. self.targets = []
  42. self.headers = []
  43. self.man = []
  44. self.data = []
  45. self.po_package_name = ''
  46. self.po = []
  47. self.install_scripts = []
  48. self.install_subdirs = []
  49. self.mesonintrospect = mesonintrospect
  50. class TargetInstallData:
  51. def __init__(self, fname, outdir, aliases, strip, install_name_mappings, install_rpath, install_mode):
  52. self.fname = fname
  53. self.outdir = outdir
  54. self.aliases = aliases
  55. self.strip = strip
  56. self.install_name_mappings = install_name_mappings
  57. self.install_rpath = install_rpath
  58. self.install_mode = install_mode
  59. class ExecutableSerialisation:
  60. def __init__(self, name, fname, cmd_args, env, is_cross, exe_wrapper,
  61. workdir, extra_paths, capture):
  62. self.name = name
  63. self.fname = fname
  64. self.cmd_args = cmd_args
  65. self.env = env
  66. self.is_cross = is_cross
  67. self.exe_runner = exe_wrapper
  68. self.workdir = workdir
  69. self.extra_paths = extra_paths
  70. self.capture = capture
  71. class TestSerialisation:
  72. def __init__(self, name, project, suite, fname, is_cross_built, exe_wrapper, is_parallel,
  73. cmd_args, env, should_fail, timeout, workdir, extra_paths):
  74. self.name = name
  75. self.project_name = project
  76. self.suite = suite
  77. self.fname = fname
  78. self.is_cross_built = is_cross_built
  79. self.exe_runner = exe_wrapper
  80. self.is_parallel = is_parallel
  81. self.cmd_args = cmd_args
  82. self.env = env
  83. self.should_fail = should_fail
  84. self.timeout = timeout
  85. self.workdir = workdir
  86. self.extra_paths = extra_paths
  87. class OptionProxy:
  88. def __init__(self, name, value):
  89. self.name = name
  90. self.value = value
  91. class OptionOverrideProxy:
  92. '''Mimic an option list but transparently override
  93. selected option values.'''
  94. def __init__(self, overrides, *options):
  95. self.overrides = overrides
  96. self.options = options
  97. def __getitem__(self, option_name):
  98. for opts in self.options:
  99. if option_name in opts:
  100. return self._get_override(option_name, opts[option_name])
  101. raise KeyError('Option not found', option_name)
  102. def _get_override(self, option_name, base_opt):
  103. if option_name in self.overrides:
  104. return OptionProxy(base_opt.name, base_opt.validate_value(self.overrides[option_name]))
  105. return base_opt
  106. # This class contains the basic functionality that is needed by all backends.
  107. # Feel free to move stuff in and out of it as you see fit.
  108. class Backend:
  109. def __init__(self, build):
  110. self.build = build
  111. self.environment = build.environment
  112. self.processed_targets = {}
  113. self.build_to_src = os.path.relpath(self.environment.get_source_dir(),
  114. self.environment.get_build_dir())
  115. def get_target_filename(self, t):
  116. if isinstance(t, build.CustomTarget):
  117. if len(t.get_outputs()) != 1:
  118. mlog.warning('custom_target {!r} has more than one output! '
  119. 'Using the first one.'.format(t.name))
  120. filename = t.get_outputs()[0]
  121. else:
  122. assert(isinstance(t, build.BuildTarget))
  123. filename = t.get_filename()
  124. return os.path.join(self.get_target_dir(t), filename)
  125. def get_target_filename_abs(self, target):
  126. return os.path.join(self.environment.get_build_dir(), self.get_target_filename(target))
  127. def get_builtin_options_for_target(self, target):
  128. return OptionOverrideProxy(target.option_overrides,
  129. self.environment.coredata.builtins)
  130. def get_base_options_for_target(self, target):
  131. return OptionOverrideProxy(target.option_overrides,
  132. self.environment.coredata.builtins,
  133. self.environment.coredata.base_options)
  134. def get_compiler_options_for_target(self, target):
  135. return OptionOverrideProxy(target.option_overrides,
  136. # no code depends on builtins for now
  137. self.environment.coredata.compiler_options)
  138. def get_option_for_target(self, option_name, target):
  139. if option_name in target.option_overrides:
  140. override = target.option_overrides[option_name]
  141. return self.environment.coredata.validate_option_value(option_name, override)
  142. return self.environment.coredata.get_builtin_option(option_name)
  143. def get_target_filename_for_linking(self, target):
  144. # On some platforms (msvc for instance), the file that is used for
  145. # dynamic linking is not the same as the dynamic library itself. This
  146. # file is called an import library, and we want to link against that.
  147. # On all other platforms, we link to the library directly.
  148. if isinstance(target, build.SharedLibrary):
  149. link_lib = target.get_import_filename() or target.get_filename()
  150. return os.path.join(self.get_target_dir(target), link_lib)
  151. elif isinstance(target, build.StaticLibrary):
  152. return os.path.join(self.get_target_dir(target), target.get_filename())
  153. elif isinstance(target, build.Executable):
  154. if target.import_filename:
  155. return os.path.join(self.get_target_dir(target), target.get_import_filename())
  156. else:
  157. return None
  158. raise AssertionError('BUG: Tried to link to {!r} which is not linkable'.format(target))
  159. def get_target_dir(self, target):
  160. if self.environment.coredata.get_builtin_option('layout') == 'mirror':
  161. dirname = target.get_subdir()
  162. else:
  163. dirname = 'meson-out'
  164. return dirname
  165. def get_target_dir_relative_to(self, t, o):
  166. '''Get a target dir relative to another target's directory'''
  167. target_dir = os.path.join(self.environment.get_build_dir(), self.get_target_dir(t))
  168. othert_dir = os.path.join(self.environment.get_build_dir(), self.get_target_dir(o))
  169. return os.path.relpath(target_dir, othert_dir)
  170. def get_target_source_dir(self, target):
  171. # if target dir is empty, avoid extraneous trailing / from os.path.join()
  172. target_dir = self.get_target_dir(target)
  173. if target_dir:
  174. return os.path.join(self.build_to_src, target_dir)
  175. return self.build_to_src
  176. def get_target_private_dir(self, target):
  177. return os.path.join(self.get_target_dir(target), target.get_id())
  178. def get_target_private_dir_abs(self, target):
  179. return os.path.join(self.environment.get_build_dir(), self.get_target_private_dir(target))
  180. def get_target_generated_dir(self, target, gensrc, src):
  181. """
  182. Takes a BuildTarget, a generator source (CustomTarget or GeneratedList),
  183. and a generated source filename.
  184. Returns the full path of the generated source relative to the build root
  185. """
  186. # CustomTarget generators output to the build dir of the CustomTarget
  187. if isinstance(gensrc, (build.CustomTarget, build.CustomTargetIndex)):
  188. return os.path.join(self.get_target_dir(gensrc), src)
  189. # GeneratedList generators output to the private build directory of the
  190. # target that the GeneratedList is used in
  191. return os.path.join(self.get_target_private_dir(target), src)
  192. def get_unity_source_file(self, target, suffix):
  193. # There is a potential conflict here, but it is unlikely that
  194. # anyone both enables unity builds and has a file called foo-unity.cpp.
  195. osrc = target.name + '-unity.' + suffix
  196. return mesonlib.File.from_built_file(self.get_target_private_dir(target), osrc)
  197. def generate_unity_files(self, target, unity_src):
  198. abs_files = []
  199. result = []
  200. compsrcs = classify_unity_sources(target.compilers.values(), unity_src)
  201. def init_language_file(suffix):
  202. unity_src = self.get_unity_source_file(target, suffix)
  203. outfileabs = unity_src.absolute_path(self.environment.get_source_dir(),
  204. self.environment.get_build_dir())
  205. outfileabs_tmp = outfileabs + '.tmp'
  206. abs_files.append(outfileabs)
  207. outfileabs_tmp_dir = os.path.dirname(outfileabs_tmp)
  208. if not os.path.exists(outfileabs_tmp_dir):
  209. os.makedirs(outfileabs_tmp_dir)
  210. result.append(unity_src)
  211. return open(outfileabs_tmp, 'w')
  212. # For each language, generate a unity source file and return the list
  213. for comp, srcs in compsrcs.items():
  214. with init_language_file(comp.get_default_suffix()) as ofile:
  215. for src in srcs:
  216. ofile.write('#include<%s>\n' % src)
  217. [mesonlib.replace_if_different(x, x + '.tmp') for x in abs_files]
  218. return result
  219. def relpath(self, todir, fromdir):
  220. return os.path.relpath(os.path.join('dummyprefixdir', todir),
  221. os.path.join('dummyprefixdir', fromdir))
  222. def flatten_object_list(self, target, proj_dir_to_build_root=''):
  223. return self._flatten_object_list(target, target.get_objects(), proj_dir_to_build_root)
  224. def _flatten_object_list(self, target, objects, proj_dir_to_build_root):
  225. obj_list = []
  226. for obj in objects:
  227. if isinstance(obj, str):
  228. o = os.path.join(proj_dir_to_build_root,
  229. self.build_to_src, target.get_subdir(), obj)
  230. obj_list.append(o)
  231. elif isinstance(obj, mesonlib.File):
  232. obj_list.append(obj.rel_to_builddir(self.build_to_src))
  233. elif isinstance(obj, build.ExtractedObjects):
  234. if obj.recursive:
  235. obj_list += self._flatten_object_list(obj.target, obj.objlist, proj_dir_to_build_root)
  236. obj_list += self.determine_ext_objs(obj, proj_dir_to_build_root)
  237. else:
  238. raise MesonException('Unknown data type in object list.')
  239. return obj_list
  240. def serialize_executable(self, exe, cmd_args, workdir, env={},
  241. extra_paths=None, capture=None):
  242. import hashlib
  243. if extra_paths is None:
  244. # The callee didn't check if we needed extra paths, so check it here
  245. if mesonlib.is_windows() or mesonlib.is_cygwin():
  246. extra_paths = self.determine_windows_extra_paths(exe, [])
  247. else:
  248. extra_paths = []
  249. # Can't just use exe.name here; it will likely be run more than once
  250. if isinstance(exe, (dependencies.ExternalProgram,
  251. build.BuildTarget, build.CustomTarget)):
  252. basename = exe.name
  253. else:
  254. basename = os.path.basename(exe)
  255. # Take a digest of the cmd args, env, workdir, and capture. This avoids
  256. # collisions and also makes the name deterministic over regenerations
  257. # which avoids a rebuild by Ninja because the cmdline stays the same.
  258. data = bytes(str(sorted(env.items())) + str(cmd_args) + str(workdir) + str(capture),
  259. encoding='utf-8')
  260. digest = hashlib.sha1(data).hexdigest()
  261. scratch_file = 'meson_exe_{0}_{1}.dat'.format(basename, digest)
  262. exe_data = os.path.join(self.environment.get_scratch_dir(), scratch_file)
  263. with open(exe_data, 'wb') as f:
  264. if isinstance(exe, dependencies.ExternalProgram):
  265. exe_cmd = exe.get_command()
  266. exe_needs_wrapper = False
  267. elif isinstance(exe, (build.BuildTarget, build.CustomTarget)):
  268. exe_cmd = [self.get_target_filename_abs(exe)]
  269. exe_needs_wrapper = exe.is_cross
  270. else:
  271. exe_cmd = [exe]
  272. exe_needs_wrapper = False
  273. is_cross_built = exe_needs_wrapper and \
  274. self.environment.is_cross_build() and \
  275. self.environment.cross_info.need_cross_compiler() and \
  276. self.environment.cross_info.need_exe_wrapper()
  277. if is_cross_built:
  278. exe_wrapper = self.environment.cross_info.config['binaries'].get('exe_wrapper', None)
  279. else:
  280. exe_wrapper = None
  281. es = ExecutableSerialisation(basename, exe_cmd, cmd_args, env,
  282. is_cross_built, exe_wrapper, workdir,
  283. extra_paths, capture)
  284. pickle.dump(es, f)
  285. return exe_data
  286. def serialize_tests(self):
  287. test_data = os.path.join(self.environment.get_scratch_dir(), 'meson_test_setup.dat')
  288. with open(test_data, 'wb') as datafile:
  289. self.write_test_file(datafile)
  290. benchmark_data = os.path.join(self.environment.get_scratch_dir(), 'meson_benchmark_setup.dat')
  291. with open(benchmark_data, 'wb') as datafile:
  292. self.write_benchmark_file(datafile)
  293. return test_data, benchmark_data
  294. def determine_linker_and_stdlib_args(self, target):
  295. '''
  296. If we're building a static library, there is only one static linker.
  297. Otherwise, we query the target for the dynamic linker.
  298. '''
  299. if isinstance(target, build.StaticLibrary):
  300. if target.is_cross:
  301. return self.build.static_cross_linker, []
  302. else:
  303. return self.build.static_linker, []
  304. l, stdlib_args = target.get_clink_dynamic_linker_and_stdlibs()
  305. return l, stdlib_args
  306. @staticmethod
  307. def _libdir_is_system(libdir, compilers):
  308. for cc in compilers.values():
  309. if libdir in cc.get_library_dirs():
  310. return True
  311. return False
  312. def rpaths_for_bundled_shared_libraries(self, target, exclude_system=True):
  313. paths = []
  314. for dep in target.external_deps:
  315. if not isinstance(dep, (dependencies.ExternalLibrary, dependencies.PkgConfigDependency)):
  316. continue
  317. la = dep.link_args
  318. if len(la) != 1 or not os.path.isabs(la[0]):
  319. continue
  320. # The only link argument is an absolute path to a library file.
  321. libpath = la[0]
  322. libdir = os.path.dirname(libpath)
  323. if exclude_system and self._libdir_is_system(libdir, target.compilers):
  324. # No point in adding system paths.
  325. continue
  326. # Windows doesn't support rpaths, but we use this function to
  327. # emulate rpaths by setting PATH, so also accept DLLs here
  328. if os.path.splitext(libpath)[1] not in ['.dll', '.lib', '.so', '.dylib']:
  329. continue
  330. if libdir.startswith(self.environment.get_source_dir()):
  331. rel_to_src = libdir[len(self.environment.get_source_dir()) + 1:]
  332. assert not os.path.isabs(rel_to_src), 'rel_to_src: {} is absolute'.format(rel_to_src)
  333. paths.append(os.path.join(self.build_to_src, rel_to_src))
  334. else:
  335. paths.append(libdir)
  336. return paths
  337. def determine_rpath_dirs(self, target):
  338. link_deps = target.get_all_link_deps()
  339. result = set()
  340. for ld in link_deps:
  341. if ld is target:
  342. continue
  343. result.add(self.get_target_dir(ld))
  344. result.update(self.rpaths_for_bundled_shared_libraries(target))
  345. return list(result)
  346. def object_filename_from_source(self, target, source):
  347. assert isinstance(source, mesonlib.File)
  348. build_dir = self.environment.get_build_dir()
  349. rel_src = source.rel_to_builddir(self.build_to_src)
  350. # foo.vala files compile down to foo.c and then foo.c.o, not foo.vala.o
  351. if rel_src.endswith(('.vala', '.gs')):
  352. # See description in generate_vala_compile for this logic.
  353. if source.is_built:
  354. if os.path.isabs(rel_src):
  355. rel_src = rel_src[len(build_dir) + 1:]
  356. rel_src = os.path.relpath(rel_src, self.get_target_private_dir(target))
  357. else:
  358. rel_src = os.path.basename(rel_src)
  359. # A meson- prefixed directory is reserved; hopefully no-one creates a file name with such a weird prefix.
  360. source = 'meson-generated_' + rel_src[:-5] + '.c'
  361. elif source.is_built:
  362. if os.path.isabs(rel_src):
  363. rel_src = rel_src[len(build_dir) + 1:]
  364. targetdir = self.get_target_private_dir(target)
  365. # A meson- prefixed directory is reserved; hopefully no-one creates a file name with such a weird prefix.
  366. source = 'meson-generated_' + os.path.relpath(rel_src, targetdir)
  367. else:
  368. if os.path.isabs(rel_src):
  369. # Not from the source directory; hopefully this doesn't conflict with user's source files.
  370. source = os.path.basename(rel_src)
  371. else:
  372. source = os.path.relpath(os.path.join(build_dir, rel_src),
  373. os.path.join(self.environment.get_source_dir(), target.get_subdir()))
  374. return source.replace('/', '_').replace('\\', '_') + '.' + self.environment.get_object_suffix()
  375. def determine_ext_objs(self, extobj, proj_dir_to_build_root):
  376. result = []
  377. # Merge sources and generated sources
  378. sources = list(extobj.srclist)
  379. for gensrc in extobj.genlist:
  380. for s in gensrc.get_outputs():
  381. path = self.get_target_generated_dir(extobj.target, gensrc, s)
  382. dirpart, fnamepart = os.path.split(path)
  383. sources.append(File(True, dirpart, fnamepart))
  384. # Filter out headers and all non-source files
  385. sources = [s for s in sources if self.environment.is_source(s) and not self.environment.is_header(s)]
  386. # extobj could contain only objects and no sources
  387. if not sources:
  388. return result
  389. targetdir = self.get_target_private_dir(extobj.target)
  390. # With unity builds, there's just one object that contains all the
  391. # sources, and we only support extracting all the objects in this mode,
  392. # so just return that.
  393. if self.is_unity(extobj.target):
  394. compsrcs = classify_unity_sources(extobj.target.compilers.values(), sources)
  395. sources = []
  396. for comp in compsrcs.keys():
  397. osrc = self.get_unity_source_file(extobj.target,
  398. comp.get_default_suffix())
  399. sources.append(osrc)
  400. for osrc in sources:
  401. objname = self.object_filename_from_source(extobj.target, osrc)
  402. objpath = os.path.join(proj_dir_to_build_root, targetdir, objname)
  403. result.append(objpath)
  404. return result
  405. def get_pch_include_args(self, compiler, target):
  406. args = []
  407. pchpath = self.get_target_private_dir(target)
  408. includeargs = compiler.get_include_args(pchpath, False)
  409. p = target.get_pch(compiler.get_language())
  410. if p:
  411. args += compiler.get_pch_use_args(pchpath, p[0])
  412. return includeargs + args
  413. @staticmethod
  414. def escape_extra_args(compiler, args):
  415. # No extra escaping/quoting needed when not running on Windows
  416. if not mesonlib.is_windows():
  417. return args
  418. extra_args = []
  419. # Compiler-specific escaping is needed for -D args but not for any others
  420. if compiler.get_id() == 'msvc':
  421. # MSVC needs escaping when a -D argument ends in \ or \"
  422. for arg in args:
  423. if arg.startswith('-D') or arg.startswith('/D'):
  424. # Without extra escaping for these two, the next character
  425. # gets eaten
  426. if arg.endswith('\\'):
  427. arg += '\\'
  428. elif arg.endswith('\\"'):
  429. arg = arg[:-2] + '\\\\"'
  430. extra_args.append(arg)
  431. else:
  432. # MinGW GCC needs all backslashes in defines to be doubly-escaped
  433. # FIXME: Not sure about Cygwin or Clang
  434. for arg in args:
  435. if arg.startswith('-D') or arg.startswith('/D'):
  436. arg = arg.replace('\\', '\\\\')
  437. extra_args.append(arg)
  438. return extra_args
  439. def generate_basic_compiler_args(self, target, compiler, no_warn_args=False):
  440. # Create an empty commands list, and start adding arguments from
  441. # various sources in the order in which they must override each other
  442. # starting from hard-coded defaults followed by build options and so on.
  443. commands = CompilerArgs(compiler)
  444. copt_proxy = self.get_compiler_options_for_target(target)
  445. # First, the trivial ones that are impossible to override.
  446. #
  447. # Add -nostdinc/-nostdinc++ if needed; can't be overridden
  448. commands += self.get_cross_stdlib_args(target, compiler)
  449. # Add things like /NOLOGO or -pipe; usually can't be overridden
  450. commands += compiler.get_always_args()
  451. # Only add warning-flags by default if the buildtype enables it, and if
  452. # we weren't explicitly asked to not emit warnings (for Vala, f.ex)
  453. if no_warn_args:
  454. commands += compiler.get_no_warn_args()
  455. elif self.get_option_for_target('buildtype', target) != 'plain':
  456. commands += compiler.get_warn_args(self.get_option_for_target('warning_level', target))
  457. # Add -Werror if werror=true is set in the build options set on the
  458. # command-line or default_options inside project(). This only sets the
  459. # action to be done for warnings if/when they are emitted, so it's ok
  460. # to set it after get_no_warn_args() or get_warn_args().
  461. if self.get_option_for_target('werror', target):
  462. commands += compiler.get_werror_args()
  463. # Add compile args for c_* or cpp_* build options set on the
  464. # command-line or default_options inside project().
  465. commands += compiler.get_option_compile_args(copt_proxy)
  466. # Add buildtype args: optimization level, debugging, etc.
  467. commands += compiler.get_buildtype_args(self.get_option_for_target('buildtype', target))
  468. # Add compile args added using add_project_arguments()
  469. commands += self.build.get_project_args(compiler, target.subproject)
  470. # Add compile args added using add_global_arguments()
  471. # These override per-project arguments
  472. commands += self.build.get_global_args(compiler)
  473. if not target.is_cross:
  474. # Compile args added from the env: CFLAGS/CXXFLAGS, etc. We want these
  475. # to override all the defaults, but not the per-target compile args.
  476. commands += self.environment.coredata.get_external_args(compiler.get_language())
  477. # Always set -fPIC for shared libraries
  478. if isinstance(target, build.SharedLibrary):
  479. commands += compiler.get_pic_args()
  480. # Set -fPIC for static libraries by default unless explicitly disabled
  481. if isinstance(target, build.StaticLibrary) and target.pic:
  482. commands += compiler.get_pic_args()
  483. # Add compile args needed to find external dependencies. Link args are
  484. # added while generating the link command.
  485. # NOTE: We must preserve the order in which external deps are
  486. # specified, so we reverse the list before iterating over it.
  487. for dep in reversed(target.get_external_deps()):
  488. if not dep.found():
  489. continue
  490. if compiler.language == 'vala':
  491. if isinstance(dep, dependencies.PkgConfigDependency):
  492. if dep.name == 'glib-2.0' and dep.version_reqs is not None:
  493. for req in dep.version_reqs:
  494. if req.startswith(('>=', '==')):
  495. commands += ['--target-glib', req[2:]]
  496. break
  497. commands += ['--pkg', dep.name]
  498. elif isinstance(dep, dependencies.ExternalLibrary):
  499. commands += dep.get_link_args('vala')
  500. else:
  501. commands += dep.get_compile_args()
  502. # Qt needs -fPIC for executables
  503. # XXX: We should move to -fPIC for all executables
  504. if isinstance(target, build.Executable):
  505. commands += dep.get_exe_args(compiler)
  506. # For 'automagic' deps: Boost and GTest. Also dependency('threads').
  507. # pkg-config puts the thread flags itself via `Cflags:`
  508. if dep.need_threads():
  509. commands += compiler.thread_flags(self.environment)
  510. elif dep.need_openmp():
  511. commands += compiler.openmp_flags()
  512. # Fortran requires extra include directives.
  513. if compiler.language == 'fortran':
  514. for lt in target.link_targets:
  515. priv_dir = self.get_target_private_dir(lt)
  516. commands += compiler.get_include_args(priv_dir, False)
  517. return commands
  518. def build_target_link_arguments(self, compiler, deps):
  519. args = []
  520. for d in deps:
  521. if not (d.is_linkable_target()):
  522. raise RuntimeError('Tried to link with a non-library target "%s".' % d.get_basename())
  523. d_arg = self.get_target_filename_for_linking(d)
  524. if not d_arg:
  525. continue
  526. if isinstance(compiler, (compilers.LLVMDCompiler, compilers.DmdDCompiler)):
  527. d_arg = '-L' + d_arg
  528. args.append(d_arg)
  529. return args
  530. def get_mingw_extra_paths(self, target):
  531. paths = OrderedSet()
  532. # The cross bindir
  533. root = self.environment.cross_info.get_root()
  534. if root:
  535. paths.add(os.path.join(root, 'bin'))
  536. # The toolchain bindir
  537. sys_root = self.environment.cross_info.get_sys_root()
  538. if sys_root:
  539. paths.add(os.path.join(sys_root, 'bin'))
  540. # Get program and library dirs from all target compilers
  541. if isinstance(target, build.BuildTarget):
  542. for cc in target.compilers.values():
  543. paths.update(cc.get_program_dirs())
  544. paths.update(cc.get_library_dirs())
  545. return list(paths)
  546. def determine_windows_extra_paths(self, target, extra_bdeps, is_cross=False):
  547. '''On Windows there is no such thing as an rpath.
  548. We must determine all locations of DLLs that this exe
  549. links to and return them so they can be used in unit
  550. tests.'''
  551. result = set()
  552. prospectives = set()
  553. if isinstance(target, build.BuildTarget):
  554. prospectives.update(target.get_transitive_link_deps())
  555. # External deps
  556. for deppath in self.rpaths_for_bundled_shared_libraries(target, exclude_system=False):
  557. result.add(os.path.normpath(os.path.join(self.environment.get_build_dir(), deppath)))
  558. for bdep in extra_bdeps:
  559. prospectives.update(bdep.get_transitive_link_deps())
  560. # Internal deps
  561. for ld in prospectives:
  562. if ld == '' or ld == '.':
  563. continue
  564. dirseg = os.path.join(self.environment.get_build_dir(), self.get_target_dir(ld))
  565. result.add(dirseg)
  566. if is_cross:
  567. result.update(self.get_mingw_extra_paths(target))
  568. return list(result)
  569. def write_benchmark_file(self, datafile):
  570. self.write_test_serialisation(self.build.get_benchmarks(), datafile)
  571. def write_test_file(self, datafile):
  572. self.write_test_serialisation(self.build.get_tests(), datafile)
  573. def write_test_serialisation(self, tests, datafile):
  574. arr = []
  575. for t in tests:
  576. exe = t.get_exe()
  577. if isinstance(exe, dependencies.ExternalProgram):
  578. cmd = exe.get_command()
  579. else:
  580. cmd = [os.path.join(self.environment.get_build_dir(), self.get_target_filename(t.get_exe()))]
  581. is_cross = self.environment.is_cross_build() and \
  582. self.environment.cross_info.need_cross_compiler() and \
  583. self.environment.cross_info.need_exe_wrapper()
  584. if isinstance(exe, build.BuildTarget):
  585. is_cross = is_cross and exe.is_cross
  586. if isinstance(exe, dependencies.ExternalProgram):
  587. # E.g. an external verifier or simulator program run on a generated executable.
  588. # Can always be run.
  589. is_cross = False
  590. if is_cross:
  591. exe_wrapper = self.environment.cross_info.config['binaries'].get('exe_wrapper', None)
  592. else:
  593. exe_wrapper = None
  594. if mesonlib.for_windows(is_cross, self.environment) or \
  595. mesonlib.for_cygwin(is_cross, self.environment):
  596. extra_bdeps = []
  597. if isinstance(exe, build.CustomTarget):
  598. extra_bdeps = exe.get_transitive_build_target_deps()
  599. extra_paths = self.determine_windows_extra_paths(exe, extra_bdeps, is_cross)
  600. else:
  601. extra_paths = []
  602. cmd_args = []
  603. for a in t.cmd_args:
  604. if hasattr(a, 'held_object'):
  605. a = a.held_object
  606. if isinstance(a, build.BuildTarget):
  607. extra_paths += self.determine_windows_extra_paths(a, [])
  608. if isinstance(a, mesonlib.File):
  609. a = os.path.join(self.environment.get_build_dir(), a.rel_to_builddir(self.build_to_src))
  610. cmd_args.append(a)
  611. elif isinstance(a, str):
  612. cmd_args.append(a)
  613. elif isinstance(a, build.Target):
  614. cmd_args.append(self.get_target_filename(a))
  615. else:
  616. raise MesonException('Bad object in test command.')
  617. ts = TestSerialisation(t.get_name(), t.project_name, t.suite, cmd, is_cross,
  618. exe_wrapper, t.is_parallel, cmd_args, t.env,
  619. t.should_fail, t.timeout, t.workdir, extra_paths)
  620. arr.append(ts)
  621. pickle.dump(arr, datafile)
  622. def generate_depmf_install(self, d):
  623. if self.build.dep_manifest_name is None:
  624. return
  625. ifilename = os.path.join(self.environment.get_build_dir(), 'depmf.json')
  626. ofilename = os.path.join(self.environment.get_prefix(), self.build.dep_manifest_name)
  627. mfobj = {'type': 'dependency manifest', 'version': '1.0', 'projects': self.build.dep_manifest}
  628. with open(ifilename, 'w') as f:
  629. f.write(json.dumps(mfobj))
  630. # Copy file from, to, and with mode unchanged
  631. d.data.append([ifilename, ofilename, None])
  632. def get_regen_filelist(self):
  633. '''List of all files whose alteration means that the build
  634. definition needs to be regenerated.'''
  635. deps = [os.path.join(self.build_to_src, df)
  636. for df in self.interpreter.get_build_def_files()]
  637. if self.environment.is_cross_build():
  638. deps.append(os.path.join(self.build_to_src,
  639. self.environment.coredata.cross_file))
  640. deps.append('meson-private/coredata.dat')
  641. if os.path.exists(os.path.join(self.environment.get_source_dir(), 'meson_options.txt')):
  642. deps.append(os.path.join(self.build_to_src, 'meson_options.txt'))
  643. for sp in self.build.subprojects.keys():
  644. fname = os.path.join(self.environment.get_source_dir(), sp, 'meson_options.txt')
  645. if os.path.isfile(fname):
  646. deps.append(os.path.join(self.build_to_src, sp, 'meson_options.txt'))
  647. return deps
  648. def exe_object_to_cmd_array(self, exe):
  649. if self.environment.is_cross_build() and \
  650. self.environment.cross_info.need_exe_wrapper() and \
  651. isinstance(exe, build.BuildTarget) and exe.is_cross:
  652. if 'exe_wrapper' not in self.environment.cross_info.config['binaries']:
  653. s = 'Can not use target %s as a generator because it is cross-built\n'
  654. s += 'and no exe wrapper is defined. You might want to set it to native instead.'
  655. s = s % exe.name
  656. raise MesonException(s)
  657. if isinstance(exe, build.BuildTarget):
  658. exe_arr = [os.path.join(self.environment.get_build_dir(), self.get_target_filename(exe))]
  659. else:
  660. exe_arr = exe.get_command()
  661. return exe_arr
  662. def replace_extra_args(self, args, genlist):
  663. final_args = []
  664. for a in args:
  665. if a == '@EXTRA_ARGS@':
  666. final_args += genlist.get_extra_args()
  667. else:
  668. final_args.append(a)
  669. return final_args
  670. def replace_outputs(self, args, private_dir, output_list):
  671. newargs = []
  672. regex = re.compile('@OUTPUT(\d+)@')
  673. for arg in args:
  674. m = regex.search(arg)
  675. while m is not None:
  676. index = int(m.group(1))
  677. src = '@OUTPUT%d@' % index
  678. arg = arg.replace(src, os.path.join(private_dir, output_list[index]))
  679. m = regex.search(arg)
  680. newargs.append(arg)
  681. return newargs
  682. def get_build_by_default_targets(self):
  683. result = OrderedDict()
  684. # Get all build and custom targets that must be built by default
  685. for name, t in self.build.get_targets().items():
  686. if t.build_by_default or t.install:
  687. result[name] = t
  688. # Get all targets used as test executables and arguments. These must
  689. # also be built by default. XXX: Sometime in the future these should be
  690. # built only before running tests.
  691. for t in self.build.get_tests():
  692. exe = t.exe
  693. if hasattr(exe, 'held_object'):
  694. exe = exe.held_object
  695. if isinstance(exe, (build.CustomTarget, build.BuildTarget)):
  696. result[exe.get_id()] = exe
  697. for arg in t.cmd_args:
  698. if hasattr(arg, 'held_object'):
  699. arg = arg.held_object
  700. if not isinstance(arg, (build.CustomTarget, build.BuildTarget)):
  701. continue
  702. result[arg.get_id()] = arg
  703. for dep in t.depends:
  704. assert isinstance(dep, (build.CustomTarget, build.BuildTarget))
  705. result[dep.get_id()] = dep
  706. return result
  707. def get_custom_target_provided_libraries(self, target):
  708. libs = []
  709. for t in target.get_generated_sources():
  710. if not isinstance(t, build.CustomTarget):
  711. continue
  712. for f in t.get_outputs():
  713. if self.environment.is_library(f):
  714. libs.append(os.path.join(self.get_target_dir(t), f))
  715. return libs
  716. def is_unity(self, target):
  717. optval = self.get_option_for_target('unity', target)
  718. if optval == 'on' or (optval == 'subprojects' and target.subproject != ''):
  719. return True
  720. return False
  721. def get_custom_target_sources(self, target):
  722. '''
  723. Custom target sources can be of various object types; strings, File,
  724. BuildTarget, even other CustomTargets.
  725. Returns the path to them relative to the build root directory.
  726. '''
  727. srcs = []
  728. for i in target.get_sources():
  729. if hasattr(i, 'held_object'):
  730. i = i.held_object
  731. if isinstance(i, str):
  732. fname = [os.path.join(self.build_to_src, target.subdir, i)]
  733. elif isinstance(i, build.BuildTarget):
  734. fname = [self.get_target_filename(i)]
  735. elif isinstance(i, (build.CustomTarget, build.CustomTargetIndex)):
  736. fname = [os.path.join(self.get_target_dir(i), p) for p in i.get_outputs()]
  737. elif isinstance(i, build.GeneratedList):
  738. fname = [os.path.join(self.get_target_private_dir(target), p) for p in i.get_outputs()]
  739. else:
  740. fname = [i.rel_to_builddir(self.build_to_src)]
  741. if target.absolute_paths:
  742. fname = [os.path.join(self.environment.get_build_dir(), f) for f in fname]
  743. srcs += fname
  744. return srcs
  745. def get_custom_target_depend_files(self, target, absolute_paths=False):
  746. deps = []
  747. for i in target.depend_files:
  748. if isinstance(i, mesonlib.File):
  749. if absolute_paths:
  750. deps.append(i.absolute_path(self.environment.get_source_dir(),
  751. self.environment.get_build_dir()))
  752. else:
  753. deps.append(i.rel_to_builddir(self.build_to_src))
  754. else:
  755. if absolute_paths:
  756. deps.append(os.path.join(self.environment.get_source_dir(), target.subdir, i))
  757. else:
  758. deps.append(os.path.join(self.build_to_src, target.subdir, i))
  759. return deps
  760. def eval_custom_target_command(self, target, absolute_outputs=False):
  761. # We want the outputs to be absolute only when using the VS backend
  762. # XXX: Maybe allow the vs backend to use relative paths too?
  763. source_root = self.build_to_src
  764. build_root = '.'
  765. outdir = self.get_target_dir(target)
  766. if absolute_outputs:
  767. source_root = self.environment.get_source_dir()
  768. build_root = self.environment.get_build_dir()
  769. outdir = os.path.join(self.environment.get_build_dir(), outdir)
  770. outputs = []
  771. for i in target.get_outputs():
  772. outputs.append(os.path.join(outdir, i))
  773. inputs = self.get_custom_target_sources(target)
  774. # Evaluate the command list
  775. cmd = []
  776. for i in target.command:
  777. if isinstance(i, build.Executable):
  778. cmd += self.exe_object_to_cmd_array(i)
  779. continue
  780. elif isinstance(i, build.CustomTarget):
  781. # GIR scanner will attempt to execute this binary but
  782. # it assumes that it is in path, so always give it a full path.
  783. tmp = i.get_outputs()[0]
  784. i = os.path.join(self.get_target_dir(i), tmp)
  785. elif isinstance(i, mesonlib.File):
  786. i = i.rel_to_builddir(self.build_to_src)
  787. if target.absolute_paths:
  788. i = os.path.join(self.environment.get_build_dir(), i)
  789. # FIXME: str types are blindly added ignoring 'target.absolute_paths'
  790. # because we can't know if they refer to a file or just a string
  791. elif not isinstance(i, str):
  792. err_msg = 'Argument {0} is of unknown type {1}'
  793. raise RuntimeError(err_msg.format(str(i), str(type(i))))
  794. elif '@SOURCE_ROOT@' in i:
  795. i = i.replace('@SOURCE_ROOT@', source_root)
  796. elif '@BUILD_ROOT@' in i:
  797. i = i.replace('@BUILD_ROOT@', build_root)
  798. elif '@DEPFILE@' in i:
  799. if target.depfile is None:
  800. msg = 'Custom target {!r} has @DEPFILE@ but no depfile ' \
  801. 'keyword argument.'.format(target.name)
  802. raise MesonException(msg)
  803. dfilename = os.path.join(outdir, target.depfile)
  804. i = i.replace('@DEPFILE@', dfilename)
  805. elif '@PRIVATE_OUTDIR_' in i:
  806. match = re.search('@PRIVATE_OUTDIR_(ABS_)?([^/\s*]*)@', i)
  807. if not match:
  808. msg = 'Custom target {!r} has an invalid argument {!r}' \
  809. ''.format(target.name, i)
  810. raise MesonException(msg)
  811. source = match.group(0)
  812. if match.group(1) is None and not target.absolute_paths:
  813. lead_dir = ''
  814. else:
  815. lead_dir = self.environment.get_build_dir()
  816. i = i.replace(source, os.path.join(lead_dir, outdir))
  817. cmd.append(i)
  818. # Substitute the rest of the template strings
  819. values = mesonlib.get_filenames_templates_dict(inputs, outputs)
  820. cmd = mesonlib.substitute_values(cmd, values)
  821. # This should not be necessary but removing it breaks
  822. # building GStreamer on Windows. The underlying issue
  823. # is problems with quoting backslashes on Windows
  824. # which is the seventh circle of hell. The downside is
  825. # that this breaks custom targets whose command lines
  826. # have backslashes. If you try to fix this be sure to
  827. # check that it does not break GST.
  828. #
  829. # The bug causes file paths such as c:\foo to get escaped
  830. # into c:\\foo.
  831. #
  832. # Unfortunately we have not been able to come up with an
  833. # isolated test case for this so unless you manage to come up
  834. # with one, the only way is to test the building with Gst's
  835. # setup. Note this in your MR or ping us and we will get it
  836. # fixed.
  837. #
  838. # https://github.com/mesonbuild/meson/pull/737
  839. cmd = [i.replace('\\', '/') for i in cmd]
  840. return inputs, outputs, cmd
  841. def run_postconf_scripts(self):
  842. env = {'MESON_SOURCE_ROOT': self.environment.get_source_dir(),
  843. 'MESON_BUILD_ROOT': self.environment.get_build_dir(),
  844. 'MESONINTROSPECT': ' '.join([shlex.quote(x) for x in self.environment.get_build_command() + ['introspect']]),
  845. }
  846. child_env = os.environ.copy()
  847. child_env.update(env)
  848. for s in self.build.postconf_scripts:
  849. cmd = s['exe'] + s['args']
  850. subprocess.check_call(cmd, env=child_env)