| 1 |
# SPDX-License-Identifier: Apache-2.0 |
| 2 |
# Copyright 2015 The Meson development team |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
import enum |
| 7 |
import os |
| 8 |
import re |
| 9 |
import typing as T |
| 10 |
|
| 11 |
|
| 12 |
from . import ExtensionModule, ModuleInfo |
| 13 |
from . import ModuleReturnValue |
| 14 |
from .. import mesonlib, build |
| 15 |
from .. import mlog |
| 16 |
from ..interpreter.type_checking import DEPEND_FILES_KW, DEPENDS_KW, INCLUDE_DIRECTORIES |
| 17 |
from ..interpreterbase.decorators import ContainerTypeInfo, FeatureNew, KwargInfo, typed_kwargs, typed_pos_args |
| 18 |
from ..mesonlib import MachineChoice, MesonException |
| 19 |
from ..programs import ExternalProgram |
| 20 |
|
| 21 |
if T.TYPE_CHECKING: |
| 22 |
from . import ModuleState |
| 23 |
from ..compilers.compilers import Language, Compiler |
| 24 |
from ..interpreter import Interpreter |
| 25 |
from ..programs import CommandList |
| 26 |
|
| 27 |
from typing_extensions import Literal, TypedDict |
| 28 |
|
| 29 |
class CompileResources(TypedDict): |
| 30 |
|
| 31 |
depend_files: T.List[mesonlib.FileOrString] |
| 32 |
depends: T.List[T.Union[build.BuildTarget, build.CustomTarget]] |
| 33 |
include_directories: T.List[T.Union[str, build.IncludeDirs]] |
| 34 |
implicit_include_directories: bool |
| 35 |
args: T.List[str] |
| 36 |
|
| 37 |
|
| 38 |
class ResourceCompilerType(enum.Enum): |
| 39 |
windres = 1 |
| 40 |
rc = 2 |
| 41 |
wrc = 3 |
| 42 |
|
| 43 |
class WindowsModule(ExtensionModule): |
| 44 |
|
| 45 |
INFO = ModuleInfo('windows') |
| 46 |
|
| 47 |
def __init__(self, interpreter: 'Interpreter'): |
| 48 |
super().__init__(interpreter) |
| 49 |
self._rescomp: T.Optional[T.Tuple[ExternalProgram, ResourceCompilerType]] = None |
| 50 |
self.methods.update({ |
| 51 |
'compile_resources': self.compile_resources, |
| 52 |
}) |
| 53 |
|
| 54 |
def detect_compiler(self, compilers: T.Dict[Language, 'Compiler']) -> 'Compiler': |
| 55 |
# https://github.com/python/mypy/issues/18826 |
| 56 |
# However, we need to support versions of mypy that cannot deduce the |
| 57 |
# tuple either. |
| 58 |
for l in T.cast('T.Tuple[Language, ...]', ('c', 'cpp')): |
| 59 |
if l in compilers: |
| 60 |
return compilers[l] |
| 61 |
raise MesonException('Resource compilation requires a C or C++ compiler.') |
| 62 |
|
| 63 |
def _find_resource_compiler(self, state: 'ModuleState') -> T.Tuple[ExternalProgram, ResourceCompilerType]: |
| 64 |
# FIXME: Does not handle `native: true` executables, see |
| 65 |
# See https://github.com/mesonbuild/meson/issues/1531 |
| 66 |
# Take a parameter instead of the hardcoded definition below |
| 67 |
for_machine = MachineChoice.HOST |
| 68 |
|
| 69 |
if self._rescomp: |
| 70 |
return self._rescomp |
| 71 |
|
| 72 |
# Will try cross / native file and then env var |
| 73 |
rescomp = ExternalProgram.from_bin_list(state.environment, for_machine, 'windres') |
| 74 |
|
| 75 |
if not rescomp or not rescomp.found(): |
| 76 |
def search_programs(names: T.List[str]) -> T.Optional[ExternalProgram]: |
| 77 |
for name in names: |
| 78 |
program = ExternalProgram(name, silent=True) |
| 79 |
if program.found(): |
| 80 |
return program |
| 81 |
return None |
| 82 |
|
| 83 |
comp = self.detect_compiler(state.environment.coredata.compilers[for_machine]) |
| 84 |
if comp.linker and comp.linker.id in {'link', 'lld-link'}: |
| 85 |
rescomp = search_programs(['rc', 'llvm-rc']) |
| 86 |
else: |
| 87 |
rescomp = search_programs(['windres', 'llvm-windres']) |
| 88 |
|
| 89 |
if not rescomp: |
| 90 |
raise MesonException('Could not find Windows resource compiler') |
| 91 |
|
| 92 |
for (arg, match, rc_type) in [ |
| 93 |
('/?', '^.*Microsoft.*Resource Compiler.*$', ResourceCompilerType.rc), |
| 94 |
('/?', 'LLVM Resource Converter.*$', ResourceCompilerType.rc), |
| 95 |
('--version', '^.*GNU windres.*$', ResourceCompilerType.windres), |
| 96 |
('--version', '^.*Wine Resource Compiler.*$', ResourceCompilerType.wrc), |
| 97 |
]: |
| 98 |
p, o, e = mesonlib.Popen_safe(rescomp.get_command() + [arg]) |
| 99 |
m = re.search(match, o, re.MULTILINE) |
| 100 |
if m: |
| 101 |
mlog.log('Windows resource compiler: %s' % m.group()) |
| 102 |
self._rescomp = (rescomp, rc_type) |
| 103 |
break |
| 104 |
else: |
| 105 |
raise MesonException('Could not determine type of Windows resource compiler') |
| 106 |
|
| 107 |
return self._rescomp |
| 108 |
|
| 109 |
@typed_pos_args('windows.compile_resources', varargs=(str, mesonlib.File, build.CustomTarget, build.CustomTargetIndex), min_varargs=1) |
| 110 |
@typed_kwargs( |
| 111 |
'windows.compile_resources', |
| 112 |
DEPEND_FILES_KW.evolve(since='0.47.0'), |
| 113 |
DEPENDS_KW.evolve(since='0.47.0'), |
| 114 |
INCLUDE_DIRECTORIES, |
| 115 |
KwargInfo('implicit_include_directories', bool, default=False, since='1.11.0'), |
| 116 |
KwargInfo('args', ContainerTypeInfo(list, str), default=[], listify=True), |
| 117 |
) |
| 118 |
def compile_resources(self, state: 'ModuleState', |
| 119 |
args: T.Tuple[T.List[T.Union[str, mesonlib.File, build.CustomTarget, build.CustomTargetIndex]]], |
| 120 |
kwargs: 'CompileResources') -> ModuleReturnValue: |
| 121 |
extra_args = kwargs['args'].copy() |
| 122 |
wrc_depend_files = state._interpreter.source_strings_to_files(kwargs['depend_files']) |
| 123 |
wrc_depends = kwargs['depends'] |
| 124 |
for d in wrc_depends: |
| 125 |
if isinstance(d, build.CustomTarget): |
| 126 |
extra_args += state.get_include_args([ |
| 127 |
build.IncludeDirs('', [], False, state.current_build_project, |
| 128 |
[self.interpreter.backend.get_target_dir(d)]) |
| 129 |
]) |
| 130 |
extra_args += state.get_include_args(kwargs['include_directories'], kwargs['implicit_include_directories']) |
| 131 |
|
| 132 |
rescomp, rescomp_type = self._find_resource_compiler(state) |
| 133 |
if rescomp_type == ResourceCompilerType.rc: |
| 134 |
# RC is used to generate .res files, a special binary resource |
| 135 |
# format, which can be passed directly to LINK (apparently LINK uses |
| 136 |
# CVTRES internally to convert this to a COFF object) |
| 137 |
suffix = 'res' |
| 138 |
res_args = extra_args + ['/nologo', '/fo@OUTPUT@', '@INPUT@'] |
| 139 |
elif rescomp_type == ResourceCompilerType.windres: |
| 140 |
# ld only supports object files, so windres is used to generate a |
| 141 |
# COFF object |
| 142 |
suffix = 'o' |
| 143 |
res_args = extra_args + ['@INPUT@', '@OUTPUT@'] |
| 144 |
|
| 145 |
m = 'Argument {!r} has a space which may not work with windres due to ' \ |
| 146 |
'a MinGW bug: https://sourceware.org/bugzilla/show_bug.cgi?id=4933' |
| 147 |
for arg in extra_args: |
| 148 |
if ' ' in arg: |
| 149 |
mlog.warning(m.format(arg), fatal=False) |
| 150 |
else: |
| 151 |
suffix = 'o' |
| 152 |
res_args = extra_args + ['@INPUT@', '-o', '@OUTPUT@'] |
| 153 |
|
| 154 |
res_targets: T.List[build.CustomTarget] = [] |
| 155 |
|
| 156 |
def get_names() -> T.Iterable[T.Tuple[str, str, T.Union[mesonlib.File, build.CustomTargetIndex]]]: |
| 157 |
for src in args[0]: |
| 158 |
if isinstance(src, str): |
| 159 |
yield os.path.join(state.subdir, src), src, mesonlib.File.from_source_file(state.environment.source_dir, state.subdir, src) |
| 160 |
elif isinstance(src, mesonlib.File): |
| 161 |
yield src.relative_name(), src.fname, src |
| 162 |
elif isinstance(src, build.CustomTargetIndex): |
| 163 |
FeatureNew.single_use('windows.compile_resource CustomTargetIndex in positional arguments', '0.61.0', |
| 164 |
state.subproject, location=state.current_node) |
| 165 |
# This dance avoids a case where two indexes of the same |
| 166 |
# target are given as separate arguments. |
| 167 |
yield (f'{src.get_id()}_{src.target.get_outputs().index(src.output)}', |
| 168 |
f'windows_compile_resources_{src.get_filename()}', src) |
| 169 |
else: |
| 170 |
if len(src.get_outputs()) > 1: |
| 171 |
FeatureNew.single_use('windows.compile_resource CustomTarget with multiple outputs in positional arguments', |
| 172 |
'0.61.0', state.subproject, location=state.current_node) |
| 173 |
for i, out in enumerate(src.get_outputs()): |
| 174 |
# Chances are that src.get_filename() is already the name of that |
| 175 |
# target, add a prefix to avoid name clash. |
| 176 |
yield f'{src.get_id()}_{i}', f'windows_compile_resources_{i}_{out}', src[i] |
| 177 |
|
| 178 |
for name, name_formatted, src in get_names(): |
| 179 |
# Path separators are not allowed in target names |
| 180 |
name = name.replace('/', '_').replace('\\', '_').replace(':', '_') |
| 181 |
name_formatted = name_formatted.replace('/', '_').replace('\\', '_').replace(':', '_') |
| 182 |
output = f'{name}_@BASENAME@.{suffix}' |
| 183 |
depfile: T.Optional[str] = None |
| 184 |
depfile_type: T.Optional[Literal['gcc', 'msvc']] = None |
| 185 |
command: CommandList = [] |
| 186 |
|
| 187 |
if rescomp_type == ResourceCompilerType.rc: |
| 188 |
compiler = self.detect_compiler(state.environment.coredata.compilers[MachineChoice.HOST]) |
| 189 |
command.extend(state.environment.get_build_command()) |
| 190 |
command.extend(['--internal', 'rc', |
| 191 |
'--rc', *rescomp.get_command(), |
| 192 |
'--cl', *compiler.get_exelist(False)]) |
| 193 |
|
| 194 |
if compiler.id in {'msvc', 'clang-cl', 'intel-cl'}: |
| 195 |
depfile_type = 'msvc' |
| 196 |
command.extend(['--Xarg=/showIncludes', |
| 197 |
'--Xarg=/EP', |
| 198 |
'--Xarg=/nologo', |
| 199 |
'--Xarg=/DRC_INVOKED', |
| 200 |
'--Xarg=/Tc@INPUT@', |
| 201 |
]) |
| 202 |
else: |
| 203 |
depfile = f'{output}.d' |
| 204 |
depfile_type = 'gcc' |
| 205 |
command.extend(['--Xarg=-xc', |
| 206 |
'--Xarg=-E', |
| 207 |
'--Xarg=-MD', |
| 208 |
'--Xarg=-MQ@OUTPUT@', |
| 209 |
'--Xarg=-MF@DEPFILE@', |
| 210 |
'--Xarg=-DRC_INVOKED', |
| 211 |
]) |
| 212 |
else: |
| 213 |
command.extend(rescomp.get_command()) |
| 214 |
|
| 215 |
command.extend(res_args) |
| 216 |
|
| 217 |
# instruct binutils windres to generate a preprocessor depfile |
| 218 |
if rescomp_type == ResourceCompilerType.windres: |
| 219 |
depfile = f'{output}.d' |
| 220 |
depfile_type = 'gcc' |
| 221 |
command.extend(['--preprocessor-arg=-MD', |
| 222 |
'--preprocessor-arg=-MQ@OUTPUT@', |
| 223 |
'--preprocessor-arg=-MF@DEPFILE@']) |
| 224 |
|
| 225 |
res_targets.append(build.CustomTarget( |
| 226 |
name_formatted, |
| 227 |
state.subdir, |
| 228 |
state.environment, |
| 229 |
command, |
| 230 |
[src], |
| 231 |
[output], |
| 232 |
state.current_build_project, |
| 233 |
depfile=depfile, |
| 234 |
depfile_type=depfile_type, |
| 235 |
depend_files=wrc_depend_files, |
| 236 |
extra_depends=wrc_depends, |
| 237 |
description='Compiling Windows resource {}', |
| 238 |
)) |
| 239 |
|
| 240 |
return ModuleReturnValue(res_targets, [res_targets]) |
| 241 |
|
| 242 |
def initialize(interp: 'Interpreter') -> WindowsModule: |
| 243 |
return WindowsModule(interp) |