Debian Codegraph @

mesonbuild/scripts/env2mfile.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2022 The Meson development team
3
4 from __future__ import annotations
5
6 from dataclasses import dataclass, field
7 import sys, os, subprocess, shutil
8 import pathlib
9 import shlex
10 import typing as T
11
12 from .. import envconfig
13 from .. import mlog
14 from ..compilers import compilers
15 from ..compilers.detect import defaults as compiler_names
16
17 if T.TYPE_CHECKING:
18 import argparse
19
20 from ..compilers.compilers import Language
21
22 # Note: when adding arguments, please also add them to the completion
23 # scripts in $MESONSRC/data/shell-completions/
24 def add_arguments(parser: 'argparse.ArgumentParser') -> None:
25 action = parser.add_mutually_exclusive_group(required=True)
26 action.add_argument('--cross', default=False, action='store_true',
27 help='Generate a cross compilation file.')
28 action.add_argument('--native', default=False, action='store_true',
29 help='Generate a native compilation file.')
30 action.add_argument('--android', default=False, action='store_true',
31 help='Generate cross files for Android toolchains.')
32
33 parser.add_argument('--debarch', default=None,
34 help='The dpkg architecture to generate.')
35 parser.add_argument('--gccsuffix', default="",
36 help='A particular gcc version suffix if necessary.')
37 parser.add_argument('-o', required=True, dest='outfile',
38 help='The output file or directory (for Android).')
39 parser.add_argument('--use-for-build', default=False, action='store_true',
40 help='Use _FOR_BUILD envvars.')
41 parser.add_argument('--system', default=None,
42 help='Define system for cross compilation.')
43 parser.add_argument('--subsystem', default=None,
44 help='Define subsystem for cross compilation.')
45 parser.add_argument('--kernel', default=None,
46 help='Define kernel for cross compilation.')
47 parser.add_argument('--cpu', default=None,
48 help='Define cpu for cross compilation.')
49 parser.add_argument('--cpu-family', default=None,
50 help='Define cpu family for cross compilation.')
51 parser.add_argument('--endian', default='little', choices=['big', 'little'],
52 help='Define endianness for cross compilation.')
53
54 @dataclass
55 class MachineInfo:
56 compilers: T.Dict[str, T.List[str]] = field(default_factory=dict)
57 binaries: T.Dict[str, T.List[str]] = field(default_factory=dict)
58 properties: T.Dict[str, T.Union[str, T.List[str]]] = field(default_factory=dict)
59 compile_args: T.Dict[str, T.List[str]] = field(default_factory=dict)
60 link_args: T.Dict[str, T.List[str]] = field(default_factory=dict)
61 cmake: T.Dict[str, T.Union[str, T.List[str]]] = field(default_factory=dict)
62
63 system: T.Optional[str] = None
64 subsystem: T.Optional[str] = None
65 kernel: T.Optional[str] = None
66 cpu: T.Optional[str] = None
67 cpu_family: T.Optional[str] = None
68 endian: T.Optional[str] = None
69
70 #parser = argparse.ArgumentParser(description='''Generate cross compilation definition file for the Meson build system.
71 #
72 #If you do not specify the --arch argument, Meson assumes that running
73 #plain 'dpkg-architecture' will return correct information for the
74 #host system.
75 #
76 #This script must be run in an environment where CPPFLAGS et al are set to the
77 #same values used in the actual compilation.
78 #'''
79 #)
80
81 def locate_path(program: str) -> T.List[str]:
82 if os.path.isabs(program):
83 return [program]
84 for d in os.get_exec_path():
85 f = os.path.join(d, program)
86 if os.access(f, os.X_OK):
87 return [f]
88 raise ValueError("%s not found on $PATH" % program)
89
90 def write_args_line(ofile: T.TextIO, name: str, args: T.Union[str, T.List[str]]) -> None:
91 if len(args) == 0:
92 return
93 if isinstance(args, str):
94 ostr = name + "= '" + args + "'\n"
95 else:
96 ostr = name + ' = ['
97 ostr += ', '.join("'" + i + "'" for i in args)
98 ostr += ']\n'
99 ofile.write(ostr)
100
101 def get_args_from_envvars(infos: MachineInfo) -> None:
102 cppflags = shlex.split(os.environ.get('CPPFLAGS', ''))
103 cflags = shlex.split(os.environ.get('CFLAGS', ''))
104 cxxflags = shlex.split(os.environ.get('CXXFLAGS', ''))
105 objcflags = shlex.split(os.environ.get('OBJCFLAGS', ''))
106 objcxxflags = shlex.split(os.environ.get('OBJCXXFLAGS', ''))
107 ldflags = shlex.split(os.environ.get('LDFLAGS', ''))
108
109 c_args = cppflags + cflags
110 cpp_args = cppflags + cxxflags
111 c_link_args = cflags + ldflags
112 cpp_link_args = cxxflags + ldflags
113
114 objc_args = cppflags + objcflags
115 objcpp_args = cppflags + objcxxflags
116 objc_link_args = objcflags + ldflags
117 objcpp_link_args = objcxxflags + ldflags
118
119 if c_args:
120 infos.compile_args['c'] = c_args
121 if c_link_args:
122 infos.link_args['c'] = c_link_args
123 if cpp_args:
124 infos.compile_args['cpp'] = cpp_args
125 if cpp_link_args:
126 infos.link_args['cpp'] = cpp_link_args
127 if objc_args:
128 infos.compile_args['objc'] = objc_args
129 if objc_link_args:
130 infos.link_args['objc'] = objc_link_args
131 if objcpp_args:
132 infos.compile_args['objcpp'] = objcpp_args
133 if objcpp_link_args:
134 infos.link_args['objcpp'] = objcpp_link_args
135
136 # map from DEB_HOST_GNU_CPU to Meson machine.cpu_family()
137 deb_cpu_family_map = {
138 'mips64el': 'mips64',
139 'i686': 'x86',
140 'powerpc64le': 'ppc64',
141 }
142
143 # map from DEB_HOST_ARCH to Meson machine.cpu()
144 deb_arch_cpu_map = {
145 'armhf': 'arm7hlf',
146 }
147
148 # map from DEB_HOST_GNU_CPU to Meson machine.cpu()
149 deb_cpu_map = {
150 'mips64el': 'mips64',
151 'powerpc64le': 'ppc64',
152 }
153
154 # map from DEB_HOST_ARCH_OS to Meson machine.system()
155 deb_os_map = {
156 'hurd': 'gnu',
157 }
158
159 # map from DEB_HOST_ARCH_OS to Meson machine.kernel()
160 deb_kernel_map = {
161 'kfreebsd': 'freebsd',
162 'hurd': 'gnu',
163 }
164
165 def replace_special_cases(special_cases: T.Mapping[str, str], name: str) -> str:
166 '''
167 If name is a key in special_cases, replace it with the value, or otherwise
168 pass it through unchanged.
169 '''
170 return special_cases.get(name, name)
171
172 def deb_detect_cmake(infos: MachineInfo, data: T.Dict[str, str]) -> None:
173 system_name_map = {'linux': 'Linux', 'kfreebsd': 'kFreeBSD', 'hurd': 'GNU'}
174 system_processor_map = {'arm': 'armv7l', 'mips64el': 'mips64', 'powerpc64le': 'ppc64le'}
175
176 infos.cmake["CMAKE_C_COMPILER"] = infos.compilers['c']
177 try:
178 infos.cmake["CMAKE_CXX_COMPILER"] = infos.compilers['cpp']
179 except KeyError:
180 pass
181 infos.cmake["CMAKE_SYSTEM_NAME"] = system_name_map[data['DEB_HOST_ARCH_OS']]
182 infos.cmake["CMAKE_SYSTEM_PROCESSOR"] = replace_special_cases(system_processor_map, data['DEB_HOST_GNU_CPU'])
183
184 def deb_compiler_lookup(infos: MachineInfo, compilerstems: T.List[T.Tuple[str, str]], host_arch: str, gccsuffix: str) -> None:
185 for langname, stem in compilerstems:
186 compilername = f'{host_arch}-{stem}{gccsuffix}'
187 try:
188 p = locate_path(compilername)
189 infos.compilers[langname] = p
190 except ValueError:
191 pass
192
193 def detect_cross_debianlike(options: T.Any) -> MachineInfo:
194 if options.debarch == 'auto':
195 cmd = ['dpkg-architecture']
196 else:
197 cmd = ['dpkg-architecture', '-a' + options.debarch]
198 output = subprocess.check_output(cmd, universal_newlines=True,
199 stderr=subprocess.DEVNULL)
200 return dpkg_architecture_to_machine_info(output, options)
201
202 def dpkg_architecture_to_machine_info(output: str, options: T.Any) -> MachineInfo:
203 data = {}
204 for line in output.split('\n'):
205 line = line.strip()
206 if line == '':
207 continue
208 k, v = line.split('=', 1)
209 data[k] = v
210 host_arch = data['DEB_HOST_GNU_TYPE']
211 host_os = replace_special_cases(deb_os_map, data['DEB_HOST_ARCH_OS'])
212 host_subsystem = host_os
213 host_kernel = replace_special_cases(deb_kernel_map, data['DEB_HOST_ARCH_OS'])
214 host_cpu_family = replace_special_cases(deb_cpu_family_map, data['DEB_HOST_GNU_CPU'])
215 host_cpu = deb_arch_cpu_map.get(data['DEB_HOST_ARCH'],
216 replace_special_cases(deb_cpu_map, data['DEB_HOST_GNU_CPU']))
217 host_endian = data['DEB_HOST_ARCH_ENDIAN']
218
219 compilerstems = [('c', 'gcc'),
220 ('cpp', 'g++'),
221 ('objc', 'gobjc'),
222 ('objcpp', 'gobjc++')]
223 infos = MachineInfo()
224 deb_compiler_lookup(infos, compilerstems, host_arch, options.gccsuffix)
225 if len(infos.compilers) == 0:
226 print('Warning: no compilers were detected.')
227 infos.binaries['ar'] = locate_path("%s-ar" % host_arch)
228 infos.binaries['strip'] = locate_path("%s-strip" % host_arch)
229 infos.binaries['objcopy'] = locate_path("%s-objcopy" % host_arch)
230 infos.binaries['ld'] = locate_path("%s-ld" % host_arch)
231 try:
232 infos.binaries['cmake'] = locate_path("cmake")
233 deb_detect_cmake(infos, data)
234 except ValueError:
235 pass
236 for tool in [
237 'g-ir-annotation-tool',
238 'g-ir-compiler',
239 'g-ir-doc-tool',
240 'g-ir-generate',
241 'g-ir-inspect',
242 'g-ir-scanner',
243 'pkg-config',
244 'vapigen',
245 ]:
246 try:
247 infos.binaries[tool] = locate_path("%s-%s" % (host_arch, tool))
248 except ValueError:
249 pass # optional
250 for tool, exe in [
251 ('exe_wrapper', 'cross-exe-wrapper'),
252 ]:
253 try:
254 infos.binaries[tool] = locate_path("%s-%s" % (host_arch, exe))
255 except ValueError:
256 pass
257 for tool, exe in [
258 ('vala', 'valac'),
259 ]:
260 try:
261 infos.compilers[tool] = locate_path("%s-%s" % (host_arch, exe))
262 except ValueError:
263 pass
264 try:
265 infos.binaries['cups-config'] = locate_path("cups-config")
266 except ValueError:
267 pass
268 infos.system = host_os
269 infos.subsystem = host_subsystem
270 infos.kernel = host_kernel
271 infos.cpu_family = host_cpu_family
272 infos.cpu = host_cpu
273 infos.endian = host_endian
274
275 get_args_from_envvars(infos)
276 return infos
277
278 def write_machine_file(infos: MachineInfo, ofilename: str, write_system_info: bool) -> None:
279 tmpfilename = ofilename + '~'
280 with open(tmpfilename, 'w', encoding='utf-8') as ofile:
281 ofile.write('[binaries]\n')
282 ofile.write('# Compilers\n')
283 for langname in sorted(infos.compilers.keys()):
284 compiler = infos.compilers[langname]
285 write_args_line(ofile, langname, compiler)
286 ofile.write('\n')
287
288 ofile.write('# Other binaries\n')
289 for exename in sorted(infos.binaries.keys()):
290 exe = infos.binaries[exename]
291 write_args_line(ofile, exename, exe)
292 ofile.write('\n')
293
294 ofile.write('[built-in options]\n')
295 all_langs = list(set(infos.compile_args.keys()).union(set(infos.link_args.keys())))
296 all_langs.sort()
297 for lang in all_langs:
298 if lang in infos.compile_args:
299 write_args_line(ofile, lang + '_args', infos.compile_args[lang])
300 if lang in infos.link_args:
301 write_args_line(ofile, lang + '_link_args', infos.link_args[lang])
302 ofile.write('\n')
303
304 ofile.write('[properties]\n')
305 for k, v in infos.properties.items():
306 write_args_line(ofile, k, v)
307 ofile.write('\n')
308
309 if infos.cmake:
310 ofile.write('[cmake]\n\n')
311 for k, v in infos.cmake.items():
312 write_args_line(ofile, k, v)
313 ofile.write('\n')
314
315 if write_system_info:
316 ofile.write('[host_machine]\n')
317 ofile.write(f"cpu = '{infos.cpu}'\n")
318 ofile.write(f"cpu_family = '{infos.cpu_family}'\n")
319 ofile.write(f"endian = '{infos.endian}'\n")
320 ofile.write(f"system = '{infos.system}'\n")
321 if infos.subsystem:
322 ofile.write(f"subsystem = '{infos.subsystem}'\n")
323 if infos.kernel:
324 ofile.write(f"kernel = '{infos.kernel}'\n")
325
326 os.replace(tmpfilename, ofilename)
327
328 def detect_language_args_from_envvars(langname: str, envvar_suffix: str = '') -> T.Tuple[T.List[str], T.List[str]]:
329 compile_args = []
330 if langname in compilers.CFLAGS_MAPPING:
331 compile_args = shlex.split(os.environ.get(
332 compilers.CFLAGS_MAPPING[T.cast('Language', langname)] + envvar_suffix, ''))
333 if langname in compilers.LANGUAGES_USING_CPPFLAGS:
334 cppflags = tuple(shlex.split(os.environ.get('CPPFLAGS' + envvar_suffix, '')))
335 lang_compile_args = list(cppflags) + compile_args
336 else:
337 lang_compile_args = compile_args
338 lang_link_args = []
339 if langname in compilers.LANGUAGES_USING_LDFLAGS:
340 lang_link_args += shlex.split(os.environ.get('LDFLAGS' + envvar_suffix, ''))
341 lang_link_args += compile_args
342 return (lang_compile_args, lang_link_args)
343
344 def detect_compilers_from_envvars(envvar_suffix: str = '') -> MachineInfo:
345 infos = MachineInfo()
346 for langname, envvarnames in envconfig.ENV_VAR_COMPILER_MAP.items():
347 for envvarname in envvarnames:
348 compilerstr = os.environ.get(envvarname + envvar_suffix)
349 if not compilerstr:
350 continue
351 if os.path.exists(compilerstr):
352 compiler = [compilerstr]
353 else:
354 compiler = shlex.split(compilerstr)
355 infos.compilers[langname] = compiler
356 lang_compile_args, lang_link_args = detect_language_args_from_envvars(langname, envvar_suffix)
357 if lang_compile_args:
358 infos.compile_args[langname] = lang_compile_args
359 if lang_link_args:
360 infos.link_args[langname] = lang_link_args
361 break
362 return infos
363
364 def detect_binaries_from_envvars(infos: MachineInfo, envvar_suffix: str = '') -> None:
365 for binname, envvar_bases in envconfig.ENV_VAR_TOOL_MAP.items():
366 for envvar_base in envvar_bases:
367 envvar = envvar_base + envvar_suffix
368 binstr = os.environ.get(envvar)
369 if binstr:
370 infos.binaries[binname] = shlex.split(binstr)
371 break
372
373 def detect_properties_from_envvars(infos: MachineInfo, envvar_suffix: str = '') -> None:
374 var = os.environ.get('PKG_CONFIG_LIBDIR' + envvar_suffix)
375 if var is not None:
376 infos.properties['pkg_config_libdir'] = var
377 var = os.environ.get('PKG_CONFIG_SYSROOT_DIR' + envvar_suffix)
378 if var is not None:
379 infos.properties['sys_root'] = var
380
381 def detect_cross_system(infos: MachineInfo, options: T.Any) -> None:
382 for optname in ('system', 'subsystem', 'kernel', 'cpu', 'cpu_family', 'endian'):
383 v = getattr(options, optname)
384 if not v:
385 mlog.error(f'Cross property "{optname}" missing, set it with --{optname.replace("_", "-")}.')
386 sys.exit(1)
387 setattr(infos, optname, v)
388
389 def detect_cross_env(options: T.Any) -> MachineInfo:
390 if options.debarch:
391 print('Detecting cross environment via dpkg-architecture.')
392 infos = detect_cross_debianlike(options)
393 else:
394 print('Detecting cross environment via environment variables.')
395 infos = detect_compilers_from_envvars()
396 detect_cross_system(infos, options)
397 detect_binaries_from_envvars(infos)
398 detect_properties_from_envvars(infos)
399 return infos
400
401 def add_compiler_if_missing(infos: MachineInfo, langname: str, exe_names: T.List[str]) -> None:
402 if langname in infos.compilers:
403 return
404 for exe_name in exe_names:
405 lookup = shutil.which(exe_name)
406 if not lookup:
407 continue
408 compflags, linkflags = detect_language_args_from_envvars(langname)
409 infos.compilers[langname] = [lookup]
410 if compflags:
411 infos.compile_args[langname] = compflags
412 if linkflags:
413 infos.link_args[langname] = linkflags
414 return
415
416 def detect_missing_native_compilers(infos: MachineInfo) -> None:
417 # T.Any per-platform special detection should go here.
418 for langname, exes in compiler_names.items():
419 if langname not in envconfig.ENV_VAR_COMPILER_MAP:
420 continue
421 add_compiler_if_missing(infos, langname, exes)
422
423 def detect_missing_native_binaries(infos: MachineInfo) -> None:
424 # T.Any per-platform special detection should go here.
425 for toolname in sorted(envconfig.ENV_VAR_TOOL_MAP.keys()):
426 if toolname in infos.binaries:
427 continue
428 exe = shutil.which(toolname)
429 if exe:
430 infos.binaries[toolname] = [exe]
431
432 def detect_native_env(options: T.Any) -> MachineInfo:
433 if options.use_for_build:
434 mlog.log('Using _FOR_BUILD envvars for detection (native file for use during cross compilation)')
435 esuffix = '_FOR_BUILD'
436 else:
437 esuffix = ''
438 infos = detect_compilers_from_envvars(esuffix)
439 detect_missing_native_compilers(infos)
440 detect_binaries_from_envvars(infos, esuffix)
441 detect_missing_native_binaries(infos)
442 detect_properties_from_envvars(infos, esuffix)
443 return infos
444
445 ANDROID_CPU_TO_MESON_CPU_FAMILY: dict[str, str] = {
446 'aarch64': 'aarch64',
447 'armv7a': 'arm',
448 'i686': 'x86',
449 'x86_64': 'x86_64',
450 'riscv64': 'riscv64',
451 }
452
453 class AndroidDetector:
454 def __init__(self, options: T.Any):
455 import platform
456 self.platform = platform.system().lower()
457 self.options = options
458
459 if self.platform == 'windows':
460 self.build_machine_id = 'windows-X86_64'
461 self.command_suffix = '.cmd'
462 self.exe_suffix = '.exe'
463 elif self.platform == 'darwin':
464 self.build_machine_id = 'darwin-x86_64' # Yes, even on aarch64 for some reason
465 self.command_suffix = ''
466 self.exe_suffix = ''
467 elif self.platform == 'linux':
468 self.build_machine_id = 'linux-x86_64'
469 self.command_suffix = ''
470 self.exe_suffix = ''
471 else:
472 sys.exit('Android lookup only supported on Linux, Windows and macOS. Patches welcome.')
473 self.outdir = pathlib.Path(options.outfile)
474
475 def detect_android_sdk_root(self) -> None:
476 home = pathlib.Path.home()
477 if self.platform == 'windows':
478 sdk_root = home / 'AppData/Local/Android/Sdk'
479 elif self.platform == 'darwin':
480 sdk_root = home / 'Library/Android/Sdk'
481 elif self.platform == 'linux':
482 sdk_root = home / 'Android/Sdk'
483 else:
484 sys.exit('Unsupported platform.')
485 if not sdk_root.is_dir():
486 sys.exit(f'Could not locate Android SDK root in {sdk_root}.')
487 ndk_root = sdk_root / 'ndk'
488 if not ndk_root.is_dir():
489 sys.exit(f'Could not locate Android ndk in {ndk_root}')
490 self.ndk_root = ndk_root
491
492 def detect_toolchains(self) -> None:
493 self.detect_android_sdk_root()
494 if not self.outdir.is_dir():
495 self.outdir.mkdir()
496 for ndk in self.ndk_root.glob('*'):
497 if not ndk.is_dir():
498 continue
499 self.process_ndk(ndk)
500
501 def process_ndk(self, ndk: pathlib.Path) -> None:
502 ndk_version = ndk.parts[-1]
503 toolchain_root = ndk / f'toolchains/llvm/prebuilt/{self.build_machine_id}'
504 bindir = toolchain_root / 'bin'
505 if not bindir.is_dir():
506 sys.exit(f'Could not detect toolchain in {toolchain_root}.')
507 ar_path = bindir / f'llvm-ar{self.exe_suffix}'
508 if not ar_path.is_file():
509 sys.exit(f'Could not detect llvm-ar in {toolchain_root}.')
510 ar_str = str(ar_path).replace('\\', '/')
511 strip_path = bindir / f'llvm-strip{self.exe_suffix}'
512 if not strip_path.is_file():
513 sys.exit(f'Could not detect llvm-strip n {toolchain_root}.')
514 strip_str = str(strip_path).replace('\\', '/')
515 for compiler in bindir.glob('*-clang++'):
516 parts = compiler.parts[-1].split('-')
517 assert len(parts) == 4
518 cpu = parts[0]
519 assert parts[1] == 'linux'
520 android_version = parts[2]
521 cpp_compiler_str = str(compiler).replace('\\', '/')
522 c_compiler_str = cpp_compiler_str[:-2]
523 cpp_compiler_str += self.command_suffix
524 c_compiler_str += self.command_suffix
525 crossfile_name = f'android-{ndk_version}-{android_version}-{cpu}-cross.txt'
526 with open(pathlib.Path(self.options.outfile) / crossfile_name, 'w', encoding='utf-8') as ofile:
527 ofile.write('[binaries]\n')
528 ofile.write(f"c = '{c_compiler_str}'\n")
529 ofile.write(f"cpp = '{cpp_compiler_str}'\n")
530 ofile.write(f"ar = '{ar_str}'\n")
531 ofile.write(f"strip = '{strip_str}'\n")
532
533 ofile.write('\n[host_machine]\n')
534 ofile.write("system = 'android'\n")
535 ofile.write(f"cpu_family = '{ANDROID_CPU_TO_MESON_CPU_FAMILY[cpu]}'\n")
536 ofile.write(f"cpu = '{cpu}'\n")
537 ofile.write("endian = 'little'\n")
538
539
540 def run(options: argparse.Namespace) -> int:
541 mlog.notice('This functionality is experimental and subject to change.')
542 if options.cross:
543 if options.use_for_build:
544 sys.exit('--use-for-build only makes sense for --native, not --cross')
545 infos = detect_cross_env(options)
546 write_system_info = True
547 write_machine_file(infos, options.outfile, write_system_info)
548 elif options.native:
549 infos = detect_native_env(options)
550 write_system_info = False
551 write_machine_file(infos, options.outfile, write_system_info)
552 elif options.android:
553 ad = AndroidDetector(options)
554 ad.detect_toolchains()
555 else:
556 raise ValueError("Encountered unreachable code-path")
557
558 return 0