| 1 |
# SPDX-License-Identifier: Apache-2.0 |
| 2 |
# Copyright 2020 The Meson development team |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
from pathlib import Path |
| 7 |
from .traceparser import CMakeTraceParser |
| 8 |
from ..envconfig import CMakeSkipCompilerTest |
| 9 |
from .common import language_map, cmake_get_generator_args |
| 10 |
from .. import mlog |
| 11 |
|
| 12 |
import os.path |
| 13 |
import shutil |
| 14 |
import typing as T |
| 15 |
from enum import Enum |
| 16 |
from textwrap import dedent |
| 17 |
|
| 18 |
if T.TYPE_CHECKING: |
| 19 |
from .executor import CMakeExecutor |
| 20 |
from ..environment import Environment |
| 21 |
from ..compilers import Compiler |
| 22 |
from ..mesonlib import MachineChoice |
| 23 |
|
| 24 |
class CMakeExecScope(Enum): |
| 25 |
SUBPROJECT = 'subproject' |
| 26 |
DEPENDENCY = 'dependency' |
| 27 |
|
| 28 |
class CMakeToolchain: |
| 29 |
def __init__(self, cmakebin: 'CMakeExecutor', env: 'Environment', for_machine: MachineChoice, exec_scope: CMakeExecScope, build_dir: Path, preload_file: T.Optional[Path] = None) -> None: |
| 30 |
self.env = env |
| 31 |
self.cmakebin = cmakebin |
| 32 |
self.for_machine = for_machine |
| 33 |
self.exec_scope = exec_scope |
| 34 |
self.preload_file = preload_file |
| 35 |
self.build_dir = build_dir |
| 36 |
self.build_dir = self.build_dir.resolve() |
| 37 |
self.toolchain_file = build_dir / 'CMakeMesonToolchainFile.cmake' |
| 38 |
self.cmcache_file = build_dir / 'CMakeCache.txt' |
| 39 |
self.minfo = self.env.machines[self.for_machine] |
| 40 |
self.properties = self.env.properties[self.for_machine] |
| 41 |
self.compilers = self.env.coredata.compilers[self.for_machine] |
| 42 |
self.cmakevars = self.env.cmakevars[self.for_machine] |
| 43 |
self.cmakestate = self.env.coredata.cmake_cache[self.for_machine] |
| 44 |
|
| 45 |
self.variables = self.get_defaults() |
| 46 |
self.variables.update(self.cmakevars.get_variables()) |
| 47 |
|
| 48 |
# Determine whether CMake the compiler test should be skipped |
| 49 |
skip_status = self.properties.get_cmake_skip_compiler_test() |
| 50 |
self.skip_check = skip_status == CMakeSkipCompilerTest.ALWAYS |
| 51 |
if skip_status == CMakeSkipCompilerTest.DEP_ONLY and self.exec_scope == CMakeExecScope.DEPENDENCY: |
| 52 |
self.skip_check = True |
| 53 |
if not self.properties.get_cmake_defaults(): |
| 54 |
self.skip_check = False |
| 55 |
|
| 56 |
assert self.toolchain_file.is_absolute() |
| 57 |
|
| 58 |
def write(self) -> Path: |
| 59 |
if not self.toolchain_file.parent.exists(): |
| 60 |
self.toolchain_file.parent.mkdir(parents=True) |
| 61 |
self.toolchain_file.write_text(self.generate(), encoding='utf-8') |
| 62 |
self.cmcache_file.write_text(self.generate_cache(), encoding='utf-8') |
| 63 |
mlog.cmd_ci_include(self.toolchain_file.as_posix()) |
| 64 |
return self.toolchain_file |
| 65 |
|
| 66 |
def get_cmake_args(self) -> T.List[str]: |
| 67 |
args = ['-DCMAKE_TOOLCHAIN_FILE=' + self.toolchain_file.as_posix()] |
| 68 |
if self.preload_file is not None: |
| 69 |
args += ['-DMESON_PRELOAD_FILE=' + self.preload_file.as_posix()] |
| 70 |
return args |
| 71 |
|
| 72 |
@staticmethod |
| 73 |
def _print_vars(vars: T.Dict[str, T.List[str]]) -> str: |
| 74 |
res = '' |
| 75 |
for key, value in vars.items(): |
| 76 |
res += 'set(' + key |
| 77 |
for i in value: |
| 78 |
res += f' "{i}"' |
| 79 |
res += ')\n' |
| 80 |
return res |
| 81 |
|
| 82 |
def generate(self) -> str: |
| 83 |
res = dedent('''\ |
| 84 |
###################################### |
| 85 |
### AUTOMATICALLY GENERATED FILE ### |
| 86 |
###################################### |
| 87 |
|
| 88 |
# This file was generated from the configuration in the |
| 89 |
# relevant meson machine file. See the meson documentation |
| 90 |
# https://mesonbuild.com/Machine-files.html for more information |
| 91 |
|
| 92 |
if(DEFINED MESON_PRELOAD_FILE) |
| 93 |
include("${MESON_PRELOAD_FILE}") |
| 94 |
endif() |
| 95 |
|
| 96 |
''') |
| 97 |
|
| 98 |
# Escape all \ in the values |
| 99 |
for key, value in self.variables.items(): |
| 100 |
self.variables[key] = [x.replace('\\', '/') for x in value] |
| 101 |
|
| 102 |
# Set compiler |
| 103 |
if self.skip_check: |
| 104 |
self.update_cmake_compiler_state() |
| 105 |
res += '# CMake compiler state variables\n' |
| 106 |
for lang, vars in self.cmakestate: |
| 107 |
res += f'# -- Variables for language {lang}\n' |
| 108 |
res += self._print_vars(vars) |
| 109 |
res += '\n' |
| 110 |
res += '\n' |
| 111 |
|
| 112 |
# Set variables from the current machine config |
| 113 |
res += '# Variables from meson\n' |
| 114 |
res += self._print_vars(self.variables) |
| 115 |
res += '\n' |
| 116 |
|
| 117 |
# Add the user provided toolchain file |
| 118 |
user_file = self.properties.get_cmake_toolchain_file() |
| 119 |
if user_file is not None: |
| 120 |
res += dedent(''' |
| 121 |
# Load the CMake toolchain file specified by the user |
| 122 |
include("{}") |
| 123 |
|
| 124 |
'''.format(user_file.as_posix())) |
| 125 |
|
| 126 |
return res |
| 127 |
|
| 128 |
def generate_cache(self) -> str: |
| 129 |
if not self.skip_check: |
| 130 |
return '' |
| 131 |
|
| 132 |
res = '' |
| 133 |
for name, v in self.cmakestate.cmake_cache.items(): |
| 134 |
res += f'{name}:{v.type}={";".join(v.value)}\n' |
| 135 |
return res |
| 136 |
|
| 137 |
def get_defaults(self) -> T.Dict[str, T.List[str]]: |
| 138 |
defaults: T.Dict[str, T.List[str]] = {} |
| 139 |
|
| 140 |
# Do nothing if the user does not want automatic defaults |
| 141 |
if not self.properties.get_cmake_defaults(): |
| 142 |
return defaults |
| 143 |
|
| 144 |
# Best effort to map the meson system name to CMAKE_SYSTEM_NAME, which |
| 145 |
# is not trivial since CMake lacks a list of all supported |
| 146 |
# CMAKE_SYSTEM_NAME values. |
| 147 |
SYSTEM_MAP: T.Dict[str, str] = { |
| 148 |
'android': 'Android', |
| 149 |
'linux': 'Linux', |
| 150 |
'windows': 'Windows', |
| 151 |
'freebsd': 'FreeBSD', |
| 152 |
'darwin': 'Darwin', |
| 153 |
} |
| 154 |
|
| 155 |
# Only set these in a cross build. Otherwise CMake will trip up in native |
| 156 |
# builds and thing they are cross (which causes TRY_RUN() to break) |
| 157 |
if self.env.is_cross_build(when_building_for=self.for_machine): |
| 158 |
# OHOS is modelled as an Android subsystem in meson, but CMake has a |
| 159 |
# dedicated OHOS system name, so map it explicitly. |
| 160 |
if self.minfo.is_ohos(): |
| 161 |
system_name = 'OHOS' |
| 162 |
else: |
| 163 |
system_name = SYSTEM_MAP.get(self.minfo.system, self.minfo.system) |
| 164 |
defaults['CMAKE_SYSTEM_NAME'] = [system_name] |
| 165 |
defaults['CMAKE_SYSTEM_PROCESSOR'] = [self.minfo.cpu_family] |
| 166 |
|
| 167 |
defaults['CMAKE_SIZEOF_VOID_P'] = ['8' if self.minfo.is_64_bit else '4'] |
| 168 |
|
| 169 |
sys_root = self.properties.get_sys_root() |
| 170 |
if sys_root: |
| 171 |
defaults['CMAKE_SYSROOT'] = [sys_root] |
| 172 |
|
| 173 |
def make_abs(exe: str) -> str: |
| 174 |
if Path(exe).is_absolute(): |
| 175 |
return exe |
| 176 |
|
| 177 |
p = shutil.which(exe) |
| 178 |
if p is None: |
| 179 |
return exe |
| 180 |
return p |
| 181 |
|
| 182 |
# Set the compiler variables |
| 183 |
comp_obj = self.compilers.get('c', self.compilers.get('cpp', None)) |
| 184 |
if comp_obj and comp_obj.get_id() == 'msvc': |
| 185 |
debug_args = comp_obj.get_debug_args(True) |
| 186 |
if '/Z7' in debug_args: |
| 187 |
defaults['CMAKE_MSVC_DEBUG_INFORMATION_FORMAT'] = ['Embedded'] |
| 188 |
elif '/Zi' in debug_args: |
| 189 |
defaults['CMAKE_MSVC_DEBUG_INFORMATION_FORMAT'] = ['ProgramDatabase'] |
| 190 |
elif '/ZI' in debug_args: |
| 191 |
defaults['CMAKE_MSVC_DEBUG_INFORMATION_FORMAT'] = ['EditAndContinue'] |
| 192 |
|
| 193 |
for lang, comp_obj in self.compilers.items(): |
| 194 |
language = language_map.get(lang) |
| 195 |
|
| 196 |
if not language: |
| 197 |
continue # unsupported language |
| 198 |
|
| 199 |
prefix = 'CMAKE_{}_'.format(language) |
| 200 |
|
| 201 |
exe_list = comp_obj.get_exelist() |
| 202 |
if not exe_list: |
| 203 |
continue |
| 204 |
|
| 205 |
if len(exe_list) >= 2 and not self.is_cmdline_option(comp_obj, exe_list[1]): |
| 206 |
defaults[prefix + 'COMPILER_LAUNCHER'] = [make_abs(exe_list[0])] |
| 207 |
exe_list = exe_list[1:] |
| 208 |
|
| 209 |
exe_list[0] = make_abs(exe_list[0]) |
| 210 |
defaults[prefix + 'COMPILER'] = exe_list |
| 211 |
if comp_obj.get_id() == 'clang-cl': |
| 212 |
defaults['CMAKE_LINKER'] = comp_obj.get_linker_exelist() |
| 213 |
if lang.startswith('objc') and comp_obj.get_id().startswith('clang'): |
| 214 |
defaults[f'{prefix}FLAGS'] = ['-D__STDC__=1'] |
| 215 |
|
| 216 |
return defaults |
| 217 |
|
| 218 |
@staticmethod |
| 219 |
def is_cmdline_option(compiler: 'Compiler', arg: str) -> bool: |
| 220 |
if compiler.get_argument_syntax() == 'msvc': |
| 221 |
return arg.startswith('/') |
| 222 |
else: |
| 223 |
if os.path.basename(compiler.get_exe()) == 'zig' and arg in {'ar', 'cc', 'c++', 'dlltool', 'lib', 'ranlib', 'objcopy', 'rc'}: |
| 224 |
return True |
| 225 |
return arg.startswith('-') |
| 226 |
|
| 227 |
def update_cmake_compiler_state(self) -> None: |
| 228 |
# Check if all variables are already cached |
| 229 |
if self.cmakestate.languages.issuperset(self.compilers.keys()): |
| 230 |
return |
| 231 |
|
| 232 |
# Generate the CMakeLists.txt |
| 233 |
mlog.debug('CMake Toolchain: Calling CMake once to generate the compiler state') |
| 234 |
languages = list(self.compilers.keys()) |
| 235 |
lang_ids = [language_map.get(x) for x in languages if x in language_map] |
| 236 |
cmake_content = dedent(f''' |
| 237 |
cmake_minimum_required(VERSION 3.10) |
| 238 |
project(CompInfo {' '.join(lang_ids)}) |
| 239 |
''') |
| 240 |
|
| 241 |
build_dir = Path(self.env.scratch_dir) / '__CMake_compiler_info__' |
| 242 |
build_dir.mkdir(parents=True, exist_ok=True) |
| 243 |
cmake_file = build_dir / 'CMakeLists.txt' |
| 244 |
cmake_file.write_text(cmake_content, encoding='utf-8') |
| 245 |
|
| 246 |
# Generate the temporary toolchain file |
| 247 |
temp_toolchain_file = build_dir / 'CMakeMesonTempToolchainFile.cmake' |
| 248 |
temp_toolchain_file.write_text(CMakeToolchain._print_vars(self.variables), encoding='utf-8') |
| 249 |
|
| 250 |
# Configure |
| 251 |
trace = CMakeTraceParser(self.cmakebin.version(), build_dir, self.env) |
| 252 |
self.cmakebin.set_exec_mode(print_cmout=False, always_capture_stderr=trace.requires_stderr()) |
| 253 |
cmake_args = [] |
| 254 |
cmake_args += trace.trace_args() |
| 255 |
cmake_args += cmake_get_generator_args(self.env) |
| 256 |
cmake_args += [f'-DCMAKE_TOOLCHAIN_FILE={temp_toolchain_file.as_posix()}', '.'] |
| 257 |
rc, raw_stdout, raw_trace = self.cmakebin.call(cmake_args, build_dir=build_dir, disable_cache=True) |
| 258 |
|
| 259 |
if rc != 0: |
| 260 |
mlog.warning('CMake Toolchain: Failed to determine CMake compilers state') |
| 261 |
mlog.debug(f' -- return code: {rc}') |
| 262 |
for line in raw_stdout.split('\n'): |
| 263 |
mlog.debug(f' -- stdout: {line.rstrip()}') |
| 264 |
for line in raw_trace.split('\n'): |
| 265 |
mlog.debug(f' -- stderr: {line.rstrip()}') |
| 266 |
return |
| 267 |
|
| 268 |
# Parse output |
| 269 |
trace.parse(raw_trace) |
| 270 |
self.cmakestate.cmake_cache = {**trace.cache} |
| 271 |
|
| 272 |
vars_by_file = {k.name: v for (k, v) in trace.vars_by_file.items()} |
| 273 |
|
| 274 |
for lang in languages: |
| 275 |
lang_cmake = language_map.get(lang, lang.upper()) |
| 276 |
file_name = f'CMake{lang_cmake}Compiler.cmake' |
| 277 |
vars = vars_by_file.setdefault(file_name, {}) |
| 278 |
vars.pop(f'CMAKE_{lang_cmake}_COMPILER_LOADED', None) |
| 279 |
vars[f'CMAKE_{lang_cmake}_COMPILER_FORCED'] = ['1'] |
| 280 |
self.cmakestate.update(lang, vars) |