backends.py 36 KB

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