/
backends.py
2030 lines (1838 loc) · 96.5 KB
/
backends.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2012-2016 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
from collections import OrderedDict
from dataclasses import dataclass, InitVar
from functools import lru_cache
from itertools import chain
from pathlib import Path
import copy
import enum
import json
import os
import pickle
import re
import shutil
import typing as T
import hashlib
from .. import build
from .. import dependencies
from .. import programs
from .. import mesonlib
from .. import mlog
from ..compilers import LANGUAGES_USING_LDFLAGS, detect
from ..mesonlib import (
File, MachineChoice, MesonException, OrderedSet,
classify_unity_sources, OptionKey, join_args,
ExecutableSerialisation
)
if T.TYPE_CHECKING:
from .._typing import ImmutableListProtocol
from ..arglist import CompilerArgs
from ..compilers import Compiler
from ..environment import Environment
from ..interpreter import Interpreter, Test
from ..linkers.linkers import StaticLinker
from ..mesonlib import FileMode, FileOrString
from typing_extensions import TypedDict
_ALL_SOURCES_TYPE = T.List[T.Union[File, build.CustomTarget, build.CustomTargetIndex, build.GeneratedList]]
class TargetIntrospectionData(TypedDict):
language: str
compiler: T.List[str]
parameters: T.List[str]
sources: T.List[str]
generated_sources: T.List[str]
# Languages that can mix with C or C++ but don't support unity builds yet
# because the syntax we use for unity builds is specific to C/++/ObjC/++.
# Assembly files cannot be unitified and neither can LLVM IR files
LANGS_CANT_UNITY = ('d', 'fortran', 'vala')
@dataclass(eq=False)
class RegenInfo:
source_dir: str
build_dir: str
depfiles: T.List[str]
class TestProtocol(enum.Enum):
EXITCODE = 0
TAP = 1
GTEST = 2
RUST = 3
@classmethod
def from_str(cls, string: str) -> 'TestProtocol':
if string == 'exitcode':
return cls.EXITCODE
elif string == 'tap':
return cls.TAP
elif string == 'gtest':
return cls.GTEST
elif string == 'rust':
return cls.RUST
raise MesonException(f'unknown test format {string}')
def __str__(self) -> str:
cls = type(self)
if self is cls.EXITCODE:
return 'exitcode'
elif self is cls.GTEST:
return 'gtest'
elif self is cls.RUST:
return 'rust'
return 'tap'
@dataclass(eq=False)
class CleanTrees:
'''
Directories outputted by custom targets that have to be manually cleaned
because on Linux `ninja clean` only deletes empty directories.
'''
build_dir: str
trees: T.List[str]
@dataclass(eq=False)
class InstallData:
source_dir: str
build_dir: str
prefix: str
libdir: str
strip_bin: T.List[str]
# TODO: in python 3.8 or with typing_Extensions this could be:
# `T.Union[T.Literal['preserve'], int]`, which would be more accurate.
install_umask: T.Union[str, int]
mesonintrospect: T.List[str]
version: str
def __post_init__(self) -> None:
self.targets: T.List[TargetInstallData] = []
self.headers: T.List[InstallDataBase] = []
self.man: T.List[InstallDataBase] = []
self.emptydir: T.List[InstallEmptyDir] = []
self.data: T.List[InstallDataBase] = []
self.symlinks: T.List[InstallSymlinkData] = []
self.install_scripts: T.List[ExecutableSerialisation] = []
self.install_subdirs: T.List[SubdirInstallData] = []
@dataclass(eq=False)
class TargetInstallData:
fname: str
outdir: str
outdir_name: InitVar[T.Optional[str]]
strip: bool
install_name_mappings: T.Mapping[str, str]
rpath_dirs_to_remove: T.Set[bytes]
install_rpath: str
# TODO: install_mode should just always be a FileMode object
install_mode: T.Optional['FileMode']
subproject: str
optional: bool = False
tag: T.Optional[str] = None
can_strip: bool = False
def __post_init__(self, outdir_name: T.Optional[str]) -> None:
if outdir_name is None:
outdir_name = os.path.join('{prefix}', self.outdir)
self.out_name = os.path.join(outdir_name, os.path.basename(self.fname))
@dataclass(eq=False)
class InstallEmptyDir:
path: str
install_mode: 'FileMode'
subproject: str
tag: T.Optional[str] = None
@dataclass(eq=False)
class InstallDataBase:
path: str
install_path: str
install_path_name: str
install_mode: 'FileMode'
subproject: str
tag: T.Optional[str] = None
data_type: T.Optional[str] = None
@dataclass(eq=False)
class InstallSymlinkData:
target: str
name: str
install_path: str
subproject: str
tag: T.Optional[str] = None
allow_missing: bool = False
# cannot use dataclass here because "exclude" is out of order
class SubdirInstallData(InstallDataBase):
def __init__(self, path: str, install_path: str, install_path_name: str,
install_mode: 'FileMode', exclude: T.Tuple[T.Set[str], T.Set[str]],
subproject: str, tag: T.Optional[str] = None, data_type: T.Optional[str] = None):
super().__init__(path, install_path, install_path_name, install_mode, subproject, tag, data_type)
self.exclude = exclude
@dataclass(eq=False)
class TestSerialisation:
name: str
project_name: str
suite: T.List[str]
fname: T.List[str]
is_cross_built: bool
exe_wrapper: T.Optional[programs.ExternalProgram]
needs_exe_wrapper: bool
is_parallel: bool
cmd_args: T.List[str]
env: build.EnvironmentVariables
should_fail: bool
timeout: T.Optional[int]
workdir: T.Optional[str]
extra_paths: T.List[str]
protocol: TestProtocol
priority: int
cmd_is_built: bool
cmd_is_exe: bool
depends: T.List[str]
version: str
verbose: bool
def __post_init__(self) -> None:
if self.exe_wrapper is not None:
assert isinstance(self.exe_wrapper, programs.ExternalProgram)
def get_backend_from_name(backend: str, build: T.Optional[build.Build] = None, interpreter: T.Optional['Interpreter'] = None) -> T.Optional['Backend']:
if backend == 'ninja':
from . import ninjabackend
return ninjabackend.NinjaBackend(build, interpreter)
elif backend == 'vs':
from . import vs2010backend
return vs2010backend.autodetect_vs_version(build, interpreter)
elif backend == 'vs2010':
from . import vs2010backend
return vs2010backend.Vs2010Backend(build, interpreter)
elif backend == 'vs2012':
from . import vs2012backend
return vs2012backend.Vs2012Backend(build, interpreter)
elif backend == 'vs2013':
from . import vs2013backend
return vs2013backend.Vs2013Backend(build, interpreter)
elif backend == 'vs2015':
from . import vs2015backend
return vs2015backend.Vs2015Backend(build, interpreter)
elif backend == 'vs2017':
from . import vs2017backend
return vs2017backend.Vs2017Backend(build, interpreter)
elif backend == 'vs2019':
from . import vs2019backend
return vs2019backend.Vs2019Backend(build, interpreter)
elif backend == 'vs2022':
from . import vs2022backend
return vs2022backend.Vs2022Backend(build, interpreter)
elif backend == 'xcode':
from . import xcodebackend
return xcodebackend.XCodeBackend(build, interpreter)
elif backend == 'none':
from . import nonebackend
return nonebackend.NoneBackend(build, interpreter)
return None
def get_genvslite_backend(genvsname: str, build: T.Optional[build.Build] = None, interpreter: T.Optional['Interpreter'] = None) -> T.Optional['Backend']:
if genvsname == 'vs2022':
from . import vs2022backend
return vs2022backend.Vs2022Backend(build, interpreter, gen_lite = True)
return None
# This class contains the basic functionality that is needed by all backends.
# Feel free to move stuff in and out of it as you see fit.
class Backend:
environment: T.Optional['Environment']
name = '<UNKNOWN>'
def __init__(self, build: T.Optional[build.Build], interpreter: T.Optional['Interpreter']):
# Make it possible to construct a dummy backend
# This is used for introspection without a build directory
if build is None:
self.environment = None
return
self.build = build
self.interpreter = interpreter
self.environment = build.environment
self.processed_targets: T.Set[str] = set()
self.build_dir = self.environment.get_build_dir()
self.source_dir = self.environment.get_source_dir()
self.build_to_src = mesonlib.relpath(self.environment.get_source_dir(),
self.environment.get_build_dir())
self.src_to_build = mesonlib.relpath(self.environment.get_build_dir(),
self.environment.get_source_dir())
# If requested via 'capture = True', returns captured compile args per
# target (e.g. captured_args[target]) that can be used later, for example,
# to populate things like intellisense fields in generated visual studio
# projects (as is the case when using '--genvslite').
#
# 'vslite_ctx' is only provided when
# we expect this backend setup/generation to make use of previously captured
# compile args (as is the case when using '--genvslite').
def generate(self, capture: bool = False, vslite_ctx: dict = None) -> T.Optional[dict]:
raise RuntimeError(f'generate is not implemented in {type(self).__name__}')
def get_target_filename(self, t: T.Union[build.Target, build.CustomTargetIndex], *, warn_multi_output: bool = True) -> str:
if isinstance(t, build.CustomTarget):
if warn_multi_output and len(t.get_outputs()) != 1:
mlog.warning(f'custom_target {t.name!r} has more than one output! '
f'Using the first one. Consider using `{t.name}[0]`.')
filename = t.get_outputs()[0]
elif isinstance(t, build.CustomTargetIndex):
filename = t.get_outputs()[0]
else:
assert isinstance(t, build.BuildTarget), t
filename = t.get_filename()
return os.path.join(self.get_target_dir(t), filename)
def get_target_filename_abs(self, target: T.Union[build.Target, build.CustomTargetIndex]) -> str:
return os.path.join(self.environment.get_build_dir(), self.get_target_filename(target))
def get_source_dir_include_args(self, target: build.BuildTarget, compiler: 'Compiler', *, absolute_path: bool = False) -> T.List[str]:
curdir = target.get_subdir()
if absolute_path:
lead = self.source_dir
else:
lead = self.build_to_src
tmppath = os.path.normpath(os.path.join(lead, curdir))
return compiler.get_include_args(tmppath, False)
def get_build_dir_include_args(self, target: build.BuildTarget, compiler: 'Compiler', *, absolute_path: bool = False) -> T.List[str]:
if absolute_path:
curdir = os.path.join(self.build_dir, target.get_subdir())
else:
curdir = target.get_subdir()
if curdir == '':
curdir = '.'
return compiler.get_include_args(curdir, False)
def get_target_filename_for_linking(self, target: T.Union[build.Target, build.CustomTargetIndex]) -> T.Optional[str]:
# On some platforms (msvc for instance), the file that is used for
# dynamic linking is not the same as the dynamic library itself. This
# file is called an import library, and we want to link against that.
# On all other platforms, we link to the library directly.
if isinstance(target, build.SharedLibrary):
link_lib = target.get_import_filename() or target.get_filename()
return os.path.join(self.get_target_dir(target), link_lib)
elif isinstance(target, build.StaticLibrary):
return os.path.join(self.get_target_dir(target), target.get_filename())
elif isinstance(target, (build.CustomTarget, build.CustomTargetIndex)):
if not target.is_linkable_target():
raise MesonException(f'Tried to link against custom target "{target.name}", which is not linkable.')
return os.path.join(self.get_target_dir(target), target.get_filename())
elif isinstance(target, build.Executable):
if target.import_filename:
return os.path.join(self.get_target_dir(target), target.get_import_filename())
else:
return None
raise AssertionError(f'BUG: Tried to link to {target!r} which is not linkable')
@lru_cache(maxsize=None)
def get_target_dir(self, target: T.Union[build.Target, build.CustomTargetIndex]) -> str:
if isinstance(target, build.RunTarget):
# this produces no output, only a dummy top-level name
dirname = ''
elif self.environment.coredata.get_option(OptionKey('layout')) == 'mirror':
dirname = target.get_subdir()
else:
dirname = 'meson-out'
return dirname
def get_target_dir_relative_to(self, t: build.Target, o: build.Target) -> str:
'''Get a target dir relative to another target's directory'''
target_dir = os.path.join(self.environment.get_build_dir(), self.get_target_dir(t))
othert_dir = os.path.join(self.environment.get_build_dir(), self.get_target_dir(o))
return os.path.relpath(target_dir, othert_dir)
def get_target_source_dir(self, target: build.Target) -> str:
# if target dir is empty, avoid extraneous trailing / from os.path.join()
target_dir = self.get_target_dir(target)
if target_dir:
return os.path.join(self.build_to_src, target_dir)
return self.build_to_src
def get_target_private_dir(self, target: T.Union[build.BuildTarget, build.CustomTarget, build.CustomTargetIndex]) -> str:
return os.path.join(self.get_target_filename(target, warn_multi_output=False) + '.p')
def get_target_private_dir_abs(self, target: T.Union[build.BuildTarget, build.CustomTarget, build.CustomTargetIndex]) -> str:
return os.path.join(self.environment.get_build_dir(), self.get_target_private_dir(target))
@lru_cache(maxsize=None)
def get_target_generated_dir(
self, target: T.Union[build.BuildTarget, build.CustomTarget, build.CustomTargetIndex],
gensrc: T.Union[build.CustomTarget, build.CustomTargetIndex, build.GeneratedList],
src: str) -> str:
"""
Takes a BuildTarget, a generator source (CustomTarget or GeneratedList),
and a generated source filename.
Returns the full path of the generated source relative to the build root
"""
# CustomTarget generators output to the build dir of the CustomTarget
if isinstance(gensrc, (build.CustomTarget, build.CustomTargetIndex)):
return os.path.join(self.get_target_dir(gensrc), src)
# GeneratedList generators output to the private build directory of the
# target that the GeneratedList is used in
return os.path.join(self.get_target_private_dir(target), src)
def get_unity_source_file(self, target: T.Union[build.BuildTarget, build.CustomTarget, build.CustomTargetIndex],
suffix: str, number: int) -> mesonlib.File:
# There is a potential conflict here, but it is unlikely that
# anyone both enables unity builds and has a file called foo-unity.cpp.
osrc = f'{target.name}-unity{number}.{suffix}'
return mesonlib.File.from_built_file(self.get_target_private_dir(target), osrc)
def generate_unity_files(self, target: build.BuildTarget, unity_src: str) -> T.List[mesonlib.File]:
abs_files: T.List[str] = []
result: T.List[mesonlib.File] = []
compsrcs = classify_unity_sources(target.compilers.values(), unity_src)
unity_size = target.get_option(OptionKey('unity_size'))
assert isinstance(unity_size, int), 'for mypy'
def init_language_file(suffix: str, unity_file_number: int) -> T.TextIO:
unity_src = self.get_unity_source_file(target, suffix, unity_file_number)
outfileabs = unity_src.absolute_path(self.environment.get_source_dir(),
self.environment.get_build_dir())
outfileabs_tmp = outfileabs + '.tmp'
abs_files.append(outfileabs)
outfileabs_tmp_dir = os.path.dirname(outfileabs_tmp)
if not os.path.exists(outfileabs_tmp_dir):
os.makedirs(outfileabs_tmp_dir)
result.append(unity_src)
return open(outfileabs_tmp, 'w', encoding='utf-8')
# For each language, generate unity source files and return the list
for comp, srcs in compsrcs.items():
files_in_current = unity_size + 1
unity_file_number = 0
# TODO: this could be simplified with an algorithm that pre-sorts
# the sources into the size of chunks we want
ofile = None
for src in srcs:
if files_in_current >= unity_size:
if ofile:
ofile.close()
ofile = init_language_file(comp.get_default_suffix(), unity_file_number)
unity_file_number += 1
files_in_current = 0
ofile.write(f'#include<{src}>\n')
files_in_current += 1
if ofile:
ofile.close()
for x in abs_files:
mesonlib.replace_if_different(x, x + '.tmp')
return result
@staticmethod
def relpath(todir: str, fromdir: str) -> str:
return os.path.relpath(os.path.join('dummyprefixdir', todir),
os.path.join('dummyprefixdir', fromdir))
def flatten_object_list(self, target: build.BuildTarget, proj_dir_to_build_root: str = ''
) -> T.Tuple[T.List[str], T.List[build.BuildTargetTypes]]:
obj_list, deps = self._flatten_object_list(target, target.get_objects(), proj_dir_to_build_root)
return list(dict.fromkeys(obj_list)), deps
def determine_ext_objs(self, objects: build.ExtractedObjects, proj_dir_to_build_root: str = '') -> T.List[str]:
obj_list, _ = self._flatten_object_list(objects.target, [objects], proj_dir_to_build_root)
return list(dict.fromkeys(obj_list))
def _flatten_object_list(self, target: build.BuildTarget,
objects: T.Sequence[T.Union[str, 'File', build.ExtractedObjects]],
proj_dir_to_build_root: str) -> T.Tuple[T.List[str], T.List[build.BuildTargetTypes]]:
obj_list: T.List[str] = []
deps: T.List[build.BuildTargetTypes] = []
for obj in objects:
if isinstance(obj, str):
o = os.path.join(proj_dir_to_build_root,
self.build_to_src, target.get_subdir(), obj)
obj_list.append(o)
elif isinstance(obj, mesonlib.File):
if obj.is_built:
o = os.path.join(proj_dir_to_build_root,
obj.rel_to_builddir(self.build_to_src))
obj_list.append(o)
else:
o = os.path.join(proj_dir_to_build_root,
self.build_to_src)
obj_list.append(obj.rel_to_builddir(o))
elif isinstance(obj, build.ExtractedObjects):
if obj.recursive:
objs, d = self._flatten_object_list(obj.target, obj.objlist, proj_dir_to_build_root)
obj_list.extend(objs)
deps.extend(d)
obj_list.extend(self._determine_ext_objs(obj, proj_dir_to_build_root))
deps.append(obj.target)
else:
raise MesonException('Unknown data type in object list.')
return obj_list, deps
@staticmethod
def is_swift_target(target: build.BuildTarget) -> bool:
for s in target.sources:
if s.endswith('swift'):
return True
return False
def determine_swift_dep_dirs(self, target: build.BuildTarget) -> T.List[str]:
result: T.List[str] = []
for l in target.link_targets:
result.append(self.get_target_private_dir_abs(l))
return result
def get_executable_serialisation(
self, cmd: T.Sequence[T.Union[programs.ExternalProgram, build.BuildTarget, build.CustomTarget, File, str]],
workdir: T.Optional[str] = None,
extra_bdeps: T.Optional[T.List[build.BuildTarget]] = None,
capture: T.Optional[bool] = None,
feed: T.Optional[bool] = None,
env: T.Optional[build.EnvironmentVariables] = None,
tag: T.Optional[str] = None,
verbose: bool = False,
installdir_map: T.Optional[T.Dict[str, str]] = None) -> 'ExecutableSerialisation':
# XXX: cmd_args either need to be lowered to strings, or need to be checked for non-string arguments, right?
exe, *raw_cmd_args = cmd
if isinstance(exe, programs.ExternalProgram):
exe_cmd = exe.get_command()
exe_for_machine = exe.for_machine
elif isinstance(exe, build.BuildTarget):
exe_cmd = [self.get_target_filename_abs(exe)]
exe_for_machine = exe.for_machine
elif isinstance(exe, build.CustomTarget):
# The output of a custom target can either be directly runnable
# or not, that is, a script, a native binary or a cross compiled
# binary when exe wrapper is available and when it is not.
# This implementation is not exhaustive but it works in the
# common cases.
exe_cmd = [self.get_target_filename_abs(exe)]
exe_for_machine = MachineChoice.BUILD
elif isinstance(exe, mesonlib.File):
exe_cmd = [exe.rel_to_builddir(self.environment.source_dir)]
exe_for_machine = MachineChoice.BUILD
else:
exe_cmd = [exe]
exe_for_machine = MachineChoice.BUILD
cmd_args: T.List[str] = []
for c in raw_cmd_args:
if isinstance(c, programs.ExternalProgram):
p = c.get_path()
assert isinstance(p, str)
cmd_args.append(p)
elif isinstance(c, (build.BuildTarget, build.CustomTarget)):
cmd_args.append(self.get_target_filename_abs(c))
elif isinstance(c, mesonlib.File):
cmd_args.append(c.rel_to_builddir(self.environment.source_dir))
else:
cmd_args.append(c)
machine = self.environment.machines[exe_for_machine]
if machine.is_windows() or machine.is_cygwin():
extra_paths = self.determine_windows_extra_paths(exe, extra_bdeps or [])
else:
extra_paths = []
is_cross_built = not self.environment.machines.matches_build_machine(exe_for_machine)
if is_cross_built and self.environment.need_exe_wrapper():
exe_wrapper = self.environment.get_exe_wrapper()
if not exe_wrapper or not exe_wrapper.found():
msg = 'An exe_wrapper is needed but was not found. Please define one ' \
'in cross file and check the command and/or add it to PATH.'
raise MesonException(msg)
else:
if exe_cmd[0].endswith('.jar'):
exe_cmd = ['java', '-jar'] + exe_cmd
elif exe_cmd[0].endswith('.exe') and not (mesonlib.is_windows() or mesonlib.is_cygwin() or mesonlib.is_wsl()):
exe_cmd = ['mono'] + exe_cmd
exe_wrapper = None
workdir = workdir or self.environment.get_build_dir()
return ExecutableSerialisation(exe_cmd + cmd_args, env,
exe_wrapper, workdir,
extra_paths, capture, feed, tag, verbose, installdir_map)
def as_meson_exe_cmdline(self, exe: T.Union[str, mesonlib.File, build.BuildTarget, build.CustomTarget, programs.ExternalProgram],
cmd_args: T.Sequence[T.Union[str, mesonlib.File, build.BuildTarget, build.CustomTarget, programs.ExternalProgram]],
workdir: T.Optional[str] = None,
extra_bdeps: T.Optional[T.List[build.BuildTarget]] = None,
capture: T.Optional[bool] = None,
feed: T.Optional[bool] = None,
force_serialize: bool = False,
env: T.Optional[build.EnvironmentVariables] = None,
verbose: bool = False) -> T.Tuple[T.Sequence[T.Union[str, File, build.Target, programs.ExternalProgram]], str]:
'''
Serialize an executable for running with a generator or a custom target
'''
cmd: T.List[T.Union[str, mesonlib.File, build.BuildTarget, build.CustomTarget, programs.ExternalProgram]] = []
cmd.append(exe)
cmd.extend(cmd_args)
es = self.get_executable_serialisation(cmd, workdir, extra_bdeps, capture, feed, env, verbose=verbose)
reasons: T.List[str] = []
if es.extra_paths:
reasons.append('to set PATH')
if es.exe_wrapper:
reasons.append('to use exe_wrapper')
if workdir:
reasons.append('to set workdir')
if any('\n' in c for c in es.cmd_args):
reasons.append('because command contains newlines')
if env and env.varnames:
reasons.append('to set env')
# force_serialize passed to this function means that the VS backend has
# decided it absolutely cannot use real commands. This is "always",
# because it's not clear what will work (other than compilers) and so
# we don't bother to handle a variety of common cases that probably do
# work.
#
# It's also overridden for a few conditions that can't be handled
# inside a command line
can_use_env = not force_serialize
force_serialize = force_serialize or bool(reasons)
if capture:
reasons.append('to capture output')
if feed:
reasons.append('to feed input')
if can_use_env and reasons == ['to set env'] and shutil.which('env'):
envlist = []
for k, v in env.get_env({}).items():
envlist.append(f'{k}={v}')
return ['env'] + envlist + es.cmd_args, ', '.join(reasons)
if not force_serialize:
if not capture and not feed:
return es.cmd_args, ''
args: T.List[str] = []
if capture:
args += ['--capture', str(capture)]
if feed:
args += ['--feed', str(feed)]
return (
self.environment.get_build_command() + ['--internal', 'exe'] + args + ['--'] + es.cmd_args,
', '.join(reasons)
)
if isinstance(exe, (programs.ExternalProgram,
build.BuildTarget, build.CustomTarget)):
basename = os.path.basename(exe.name)
elif isinstance(exe, mesonlib.File):
basename = os.path.basename(exe.fname)
else:
basename = os.path.basename(exe)
# Can't just use exe.name here; it will likely be run more than once
# Take a digest of the cmd args, env, workdir, capture, and feed. This
# avoids collisions and also makes the name deterministic over
# regenerations which avoids a rebuild by Ninja because the cmdline
# stays the same.
hasher = hashlib.sha1()
if es.env:
es.env.hash(hasher)
hasher.update(bytes(str(es.cmd_args), encoding='utf-8'))
hasher.update(bytes(str(es.workdir), encoding='utf-8'))
hasher.update(bytes(str(capture), encoding='utf-8'))
hasher.update(bytes(str(feed), encoding='utf-8'))
digest = hasher.hexdigest()
scratch_file = f'meson_exe_{basename}_{digest}.dat'
exe_data = os.path.join(self.environment.get_scratch_dir(), scratch_file)
with open(exe_data, 'wb') as f:
pickle.dump(es, f)
return (self.environment.get_build_command() + ['--internal', 'exe', '--unpickle', exe_data],
', '.join(reasons))
def serialize_tests(self) -> T.Tuple[str, str]:
test_data = os.path.join(self.environment.get_scratch_dir(), 'meson_test_setup.dat')
with open(test_data, 'wb') as datafile:
self.write_test_file(datafile)
benchmark_data = os.path.join(self.environment.get_scratch_dir(), 'meson_benchmark_setup.dat')
with open(benchmark_data, 'wb') as datafile:
self.write_benchmark_file(datafile)
return test_data, benchmark_data
def determine_linker_and_stdlib_args(self, target: build.BuildTarget) -> T.Tuple[T.Union['Compiler', 'StaticLinker'], T.List[str]]:
'''
If we're building a static library, there is only one static linker.
Otherwise, we query the target for the dynamic linker.
'''
if isinstance(target, build.StaticLibrary):
return self.build.static_linker[target.for_machine], []
l, stdlib_args = target.get_clink_dynamic_linker_and_stdlibs()
return l, stdlib_args
@staticmethod
def _libdir_is_system(libdir: str, compilers: T.Mapping[str, 'Compiler'], env: 'Environment') -> bool:
libdir = os.path.normpath(libdir)
for cc in compilers.values():
if libdir in cc.get_library_dirs(env):
return True
return False
def get_external_rpath_dirs(self, target: build.BuildTarget) -> T.Set[str]:
args: T.List[str] = []
for lang in LANGUAGES_USING_LDFLAGS:
try:
e = self.environment.coredata.get_external_link_args(target.for_machine, lang)
if isinstance(e, str):
args.append(e)
else:
args.extend(e)
except Exception:
pass
return self.get_rpath_dirs_from_link_args(args)
@staticmethod
def get_rpath_dirs_from_link_args(args: T.List[str]) -> T.Set[str]:
dirs: T.Set[str] = set()
# Match rpath formats:
# -Wl,-rpath=
# -Wl,-rpath,
rpath_regex = re.compile(r'-Wl,-rpath[=,]([^,]+)')
# Match solaris style compat runpath formats:
# -Wl,-R
# -Wl,-R,
runpath_regex = re.compile(r'-Wl,-R[,]?([^,]+)')
# Match symbols formats:
# -Wl,--just-symbols=
# -Wl,--just-symbols,
symbols_regex = re.compile(r'-Wl,--just-symbols[=,]([^,]+)')
for arg in args:
rpath_match = rpath_regex.match(arg)
if rpath_match:
for dir in rpath_match.group(1).split(':'):
dirs.add(dir)
runpath_match = runpath_regex.match(arg)
if runpath_match:
for dir in runpath_match.group(1).split(':'):
# The symbols arg is an rpath if the path is a directory
if Path(dir).is_dir():
dirs.add(dir)
symbols_match = symbols_regex.match(arg)
if symbols_match:
for dir in symbols_match.group(1).split(':'):
# Prevent usage of --just-symbols to specify rpath
if Path(dir).is_dir():
raise MesonException(f'Invalid arg for --just-symbols, {dir} is a directory.')
return dirs
@lru_cache(maxsize=None)
def rpaths_for_non_system_absolute_shared_libraries(self, target: build.BuildTarget, exclude_system: bool = True) -> 'ImmutableListProtocol[str]':
paths: OrderedSet[str] = OrderedSet()
srcdir = self.environment.get_source_dir()
for dep in target.external_deps:
if dep.type_name not in {'library', 'pkgconfig'}:
continue
for libpath in dep.link_args:
# For all link args that are absolute paths to a library file, add RPATH args
if not os.path.isabs(libpath):
continue
libdir = os.path.dirname(libpath)
if exclude_system and self._libdir_is_system(libdir, target.compilers, self.environment):
# No point in adding system paths.
continue
# Don't remove rpaths specified in LDFLAGS.
if libdir in self.get_external_rpath_dirs(target):
continue
# Windows doesn't support rpaths, but we use this function to
# emulate rpaths by setting PATH
# .dll is there for mingw gcc
if os.path.splitext(libpath)[1] not in {'.dll', '.lib', '.so', '.dylib'}:
continue
try:
commonpath = os.path.commonpath((libdir, srcdir))
except ValueError: # when paths are on different drives on Windows
commonpath = ''
if commonpath == srcdir:
rel_to_src = libdir[len(srcdir) + 1:]
assert not os.path.isabs(rel_to_src), f'rel_to_src: {rel_to_src} is absolute'
paths.add(os.path.join(self.build_to_src, rel_to_src))
else:
paths.add(libdir)
# Don't remove rpaths specified by the dependency
paths.difference_update(self.get_rpath_dirs_from_link_args(dep.link_args))
for i in chain(target.link_targets, target.link_whole_targets):
if isinstance(i, build.BuildTarget):
paths.update(self.rpaths_for_non_system_absolute_shared_libraries(i, exclude_system))
return list(paths)
# This may take other types
def determine_rpath_dirs(self, target: T.Union[build.BuildTarget, build.CustomTarget, build.CustomTargetIndex]
) -> T.Tuple[str, ...]:
result: OrderedSet[str]
if self.environment.coredata.get_option(OptionKey('layout')) == 'mirror':
# Need a copy here
result = OrderedSet(target.get_link_dep_subdirs())
else:
result = OrderedSet()
result.add('meson-out')
if isinstance(target, build.BuildTarget):
result.update(self.rpaths_for_non_system_absolute_shared_libraries(target))
target.rpath_dirs_to_remove.update([d.encode('utf-8') for d in result])
return tuple(result)
@staticmethod
def canonicalize_filename(fname: str) -> str:
parts = Path(fname).parts
hashed = ''
if len(parts) > 5:
temp = '/'.join(parts[-5:])
# is it shorter to hash the beginning of the path?
if len(fname) > len(temp) + 41:
hashed = hashlib.sha1(fname.encode('utf-8')).hexdigest() + '_'
fname = temp
for ch in ('/', '\\', ':'):
fname = fname.replace(ch, '_')
return hashed + fname
def object_filename_from_source(self, target: build.BuildTarget, source: 'FileOrString') -> str:
assert isinstance(source, mesonlib.File)
if isinstance(target, build.CompileTarget):
return target.sources_map[source]
build_dir = self.environment.get_build_dir()
rel_src = source.rel_to_builddir(self.build_to_src)
# foo.vala files compile down to foo.c and then foo.c.o, not foo.vala.o
if rel_src.endswith(('.vala', '.gs')):
# See description in generate_vala_compile for this logic.
if source.is_built:
if os.path.isabs(rel_src):
rel_src = rel_src[len(build_dir) + 1:]
rel_src = os.path.relpath(rel_src, self.get_target_private_dir(target))
else:
rel_src = os.path.basename(rel_src)
# A meson- prefixed directory is reserved; hopefully no-one creates a file name with such a weird prefix.
gen_source = 'meson-generated_' + rel_src[:-5] + '.c'
elif source.is_built:
if os.path.isabs(rel_src):
rel_src = rel_src[len(build_dir) + 1:]
targetdir = self.get_target_private_dir(target)
# A meson- prefixed directory is reserved; hopefully no-one creates a file name with such a weird prefix.
gen_source = 'meson-generated_' + os.path.relpath(rel_src, targetdir)
else:
if os.path.isabs(rel_src):
# Use the absolute path directly to avoid file name conflicts
gen_source = rel_src
else:
gen_source = os.path.relpath(os.path.join(build_dir, rel_src),
os.path.join(self.environment.get_source_dir(), target.get_subdir()))
machine = self.environment.machines[target.for_machine]
return self.canonicalize_filename(gen_source) + '.' + machine.get_object_suffix()
def _determine_ext_objs(self, extobj: 'build.ExtractedObjects', proj_dir_to_build_root: str) -> T.List[str]:
result: T.List[str] = []
targetdir = self.get_target_private_dir(extobj.target)
# Merge sources and generated sources
raw_sources = list(extobj.srclist)
for gensrc in extobj.genlist:
for r in gensrc.get_outputs():
path = self.get_target_generated_dir(extobj.target, gensrc, r)
dirpart, fnamepart = os.path.split(path)
raw_sources.append(File(True, dirpart, fnamepart))
# Filter out headers and all non-source files
sources: T.List['FileOrString'] = []
for s in raw_sources:
if self.environment.is_source(s):
sources.append(s)
elif self.environment.is_object(s):
result.append(s.relative_name())
# MSVC generate an object file for PCH
if extobj.pch:
for lang, pch in extobj.target.pch.items():
compiler = extobj.target.compilers[lang]
if compiler.get_argument_syntax() == 'msvc':
objname = self.get_msvc_pch_objname(lang, pch)
result.append(os.path.join(proj_dir_to_build_root, targetdir, objname))
# extobj could contain only objects and no sources
if not sources:
return result
# With unity builds, sources don't map directly to objects,
# we only support extracting all the objects in this mode,
# so just return all object files.
if extobj.target.is_unity:
compsrcs = classify_unity_sources(extobj.target.compilers.values(), sources)
sources = []
unity_size = extobj.target.get_option(OptionKey('unity_size'))
assert isinstance(unity_size, int), 'for mypy'
for comp, srcs in compsrcs.items():
if comp.language in LANGS_CANT_UNITY:
sources += srcs
continue
for i in range(len(srcs) // unity_size + 1):
_src = self.get_unity_source_file(extobj.target,
comp.get_default_suffix(), i)
sources.append(_src)
for osrc in sources:
objname = self.object_filename_from_source(extobj.target, osrc)
objpath = os.path.join(proj_dir_to_build_root, targetdir, objname)
result.append(objpath)
return result
def get_pch_include_args(self, compiler: 'Compiler', target: build.BuildTarget) -> T.List[str]:
args: T.List[str] = []
pchpath = self.get_target_private_dir(target)
includeargs = compiler.get_include_args(pchpath, False)
p = target.get_pch(compiler.get_language())
if p:
args += compiler.get_pch_use_args(pchpath, p[0])
return includeargs + args
def get_msvc_pch_objname(self, lang: str, pch: T.List[str]) -> str:
if len(pch) == 1:
# Same name as in create_msvc_pch_implementation() below.
return f'meson_pch-{lang}.obj'
return os.path.splitext(pch[1])[0] + '.obj'
def create_msvc_pch_implementation(self, target: build.BuildTarget, lang: str, pch_header: str) -> str:
# We have to include the language in the file name, otherwise
# pch.c and pch.cpp will both end up as pch.obj in VS backends.
impl_name = f'meson_pch-{lang}.{lang}'
pch_rel_to_build = os.path.join(self.get_target_private_dir(target), impl_name)
# Make sure to prepend the build dir, since the working directory is
# not defined. Otherwise, we might create the file in the wrong path.
pch_file = os.path.join(self.build_dir, pch_rel_to_build)
os.makedirs(os.path.dirname(pch_file), exist_ok=True)
content = f'#include "{os.path.basename(pch_header)}"'
pch_file_tmp = pch_file + '.tmp'
with open(pch_file_tmp, 'w', encoding='utf-8') as f:
f.write(content)
mesonlib.replace_if_different(pch_file, pch_file_tmp)
return pch_rel_to_build
def target_uses_pch(self, target: build.BuildTarget) -> bool:
try:
return T.cast('bool', target.get_option(OptionKey('b_pch')))
except KeyError:
return False
@staticmethod
def escape_extra_args(args: T.List[str]) -> T.List[str]:
# all backslashes in defines are doubly-escaped
extra_args: T.List[str] = []
for arg in args:
if arg.startswith(('-D', '/D')):
arg = arg.replace('\\', '\\\\')
extra_args.append(arg)
return extra_args
def get_no_stdlib_args(self, target: 'build.BuildTarget', compiler: 'Compiler') -> T.List[str]:
if compiler.language in self.build.stdlibs[target.for_machine]:
return compiler.get_no_stdinc_args()
return []
def generate_basic_compiler_args(self, target: build.BuildTarget, compiler: 'Compiler', no_warn_args: bool = False) -> 'CompilerArgs':
# Create an empty commands list, and start adding arguments from
# various sources in the order in which they must override each other
# starting from hard-coded defaults followed by build options and so on.
commands = compiler.compiler_args()
copt_proxy = target.get_options()
# First, the trivial ones that are impossible to override.
#
# Add -nostdinc/-nostdinc++ if needed; can't be overridden
commands += self.get_no_stdlib_args(target, compiler)
# Add things like /NOLOGO or -pipe; usually can't be overridden
commands += compiler.get_always_args()
# Only add warning-flags by default if the buildtype enables it, and if
# we weren't explicitly asked to not emit warnings (for Vala, f.ex)
if no_warn_args:
commands += compiler.get_no_warn_args()
else:
# warning_level is a string, but mypy can't determine that
commands += compiler.get_warn_args(T.cast('str', target.get_option(OptionKey('warning_level'))))
# Add -Werror if werror=true is set in the build options set on the
# command-line or default_options inside project(). This only sets the
# action to be done for warnings if/when they are emitted, so it's ok
# to set it after get_no_warn_args() or get_warn_args().
if target.get_option(OptionKey('werror')):
commands += compiler.get_werror_args()
# Add compile args for c_* or cpp_* build options set on the
# command-line or default_options inside project().
commands += compiler.get_option_compile_args(copt_proxy)
# Add buildtype args: optimization level, debugging, etc.