files: # Copyright 2013-2019 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.
  
  # This file contains the detection logic for external dependencies useful for
  # development purposes, such as testing, debugging, etc..
  
  import functools
  import glob
  import os
  import re
  
  from .. import mesonlib, mlog
  from ..mesonlib import version_compare, stringlistify, extract_as_list, MachineChoice
  from ..environment import get_llvm_tool_names
  from .base import (
      DependencyException, DependencyMethods, ExternalDependency, PkgConfigDependency,
      strip_system_libdirs, ConfigToolDependency, CMakeDependency, HasNativeKwarg
  )
  from .misc import ThreadDependency
  
  from typing import List, Tuple
  
  
  def get_shared_library_suffix(environment, for_machine: MachineChoice):
      """This is only gauranteed to work for languages that compile to machine
      code, not for languages like C# that use a bytecode and always end in .dll
      """
      m = environment.machines[for_machine]
      if m.is_windows():
          return '.dll'
      elif m.is_darwin():
          return '.dylib'
      return '.so'
  
  
  class GTestDependency(ExternalDependency):
      def __init__(self, environment, kwargs):
          super().__init__('gtest', environment, 'cpp', kwargs)
          self.main = kwargs.get('main', False)
          self.src_dirs = ['/usr/src/gtest/src', '/usr/src/googletest/googletest/src']
          self.detect()
          self._add_sub_dependency(ThreadDependency, environment, kwargs)
  
      def detect(self):
          gtest_detect = self.clib_compiler.find_library("gtest", self.env, [])
          gtest_main_detect = self.clib_compiler.find_library("gtest_main", self.env, [])
          if gtest_detect and (not self.main or gtest_main_detect):
              self.is_found = True
              self.compile_args = []
              self.link_args = gtest_detect
              if self.main:
                  self.link_args += gtest_main_detect
              self.sources = []
              self.prebuilt = True
          elif self.detect_srcdir():
              self.is_found = True
              self.compile_args = ['-I' + d for d in self.src_include_dirs]
              self.link_args = []
              if self.main:
                  self.sources = [self.all_src, self.main_src]
              else:
                  self.sources = [self.all_src]
              self.prebuilt = False
          else:
              self.is_found = False
  
      def detect_srcdir(self):
          for s in self.src_dirs:
              if os.path.exists(s):
                  self.src_dir = s
                  self.all_src = mesonlib.File.from_absolute_file(
                      os.path.join(self.src_dir, 'gtest-all.cc'))
                  self.main_src = mesonlib.File.from_absolute_file(
                      os.path.join(self.src_dir, 'gtest_main.cc'))
                  self.src_include_dirs = [os.path.normpath(os.path.join(self.src_dir, '..')),
                                           os.path.normpath(os.path.join(self.src_dir, '../include')),
                                           ]
                  return True
          return False
  
      def log_info(self):
          if self.prebuilt:
              return 'prebuilt'
          else:
              return 'building self'
  
      def log_tried(self):
          return 'system'
  
      @classmethod
      def _factory(cls, environment, kwargs):
          methods = cls._process_method_kw(kwargs)
          candidates = []
  
          if DependencyMethods.PKGCONFIG in methods:
              pcname = 'gtest_main' if kwargs.get('main', False) else 'gtest'
              candidates.append(functools.partial(PkgConfigDependency, pcname, environment, kwargs))
  
          if DependencyMethods.SYSTEM in methods:
              candidates.append(functools.partial(GTestDependency, environment, kwargs))
  
          return candidates
  
      @staticmethod
      def get_methods():
          return [DependencyMethods.PKGCONFIG, DependencyMethods.SYSTEM]
  
  
  class GMockDependency(ExternalDependency):
      def __init__(self, environment, kwargs):
          super().__init__('gmock', environment, 'cpp', kwargs)
          self.main = kwargs.get('main', False)
          self._add_sub_dependency(ThreadDependency, environment, kwargs)
  
          # If we are getting main() from GMock, we definitely
          # want to avoid linking in main() from GTest
          gtest_kwargs = kwargs.copy()
          if self.main:
              gtest_kwargs['main'] = False
  
          # GMock without GTest is pretty much useless
          # this also mimics the structure given in WrapDB,
          # where GMock always pulls in GTest
          gtest_dep = GTestDependency(environment, gtest_kwargs)
          if not gtest_dep.is_found:
              self.is_found = False
              return
          self.ext_deps.append(gtest_dep)
  
          # GMock may be a library or just source.
          # Work with both.
          gmock_detect = self.clib_compiler.find_library("gmock", self.env, [])
          gmock_main_detect = self.clib_compiler.find_library("gmock_main", self.env, [])
          if gmock_detect and (not self.main or gmock_main_detect):
              self.is_found = True
              self.link_args += gmock_detect
              if self.main:
                  self.link_args += gmock_main_detect
              self.prebuilt = True
              return
  
          for d in ['/usr/src/googletest/googlemock/src', '/usr/src/gmock/src', '/usr/src/gmock']:
              if os.path.exists(d):
                  self.is_found = True
                  # Yes, we need both because there are multiple
                  # versions of gmock that do different things.
                  d2 = os.path.normpath(os.path.join(d, '..'))
                  self.compile_args += ['-I' + d, '-I' + d2, '-I' + os.path.join(d2, 'include')]
                  all_src = mesonlib.File.from_absolute_file(os.path.join(d, 'gmock-all.cc'))
                  main_src = mesonlib.File.from_absolute_file(os.path.join(d, 'gmock_main.cc'))
                  if self.main:
                      self.sources += [all_src, main_src]
                  else:
                      self.sources += [all_src]
                  self.prebuilt = False
                  return
  
          self.is_found = False
  
      def log_info(self):
          if self.prebuilt:
              return 'prebuilt'
          else:
              return 'building self'
  
      def log_tried(self):
          return 'system'
  
      @classmethod
      def _factory(cls, environment, kwargs):
          methods = cls._process_method_kw(kwargs)
          candidates = []
  
          if DependencyMethods.PKGCONFIG in methods:
              pcname = 'gmock_main' if kwargs.get('main', False) else 'gmock'
              candidates.append(functools.partial(PkgConfigDependency, pcname, environment, kwargs))
  
          if DependencyMethods.SYSTEM in methods:
              candidates.append(functools.partial(GMockDependency, environment, kwargs))
  
          return candidates
  
      @staticmethod
      def get_methods():
          return [DependencyMethods.PKGCONFIG, DependencyMethods.SYSTEM]
  
  
  class LLVMDependencyConfigTool(ConfigToolDependency):
      """
      LLVM uses a special tool, llvm-config, which has arguments for getting
      c args, cxx args, and ldargs as well as version.
      """
      tool_name = 'llvm-config'
      __cpp_blacklist = {'-DNDEBUG'}
  
      def __init__(self, environment, kwargs):
          # Already called by `super().__init__`, but need `self.for_machine`
          # before `super().__init__` is called.
          HasNativeKwarg.__init__(self, kwargs)
  
          self.tools = get_llvm_tool_names('llvm-config')
  
          # Fedora starting with Fedora 30 adds a suffix of the number
          # of bits in the isa that llvm targets, for example, on x86_64
          # and aarch64 the name will be llvm-config-64, on x86 and arm
          # it will be llvm-config-32.
          if environment.machines[self.for_machine].is_64_bit:
              self.tools.append('llvm-config-64')
          else:
              self.tools.append('llvm-config-32')
  
          # It's necessary for LLVM <= 3.8 to use the C++ linker. For 3.9 and 4.0
          # the C linker works fine if only using the C API.
          super().__init__('LLVM', environment, 'cpp', kwargs)
          self.provided_modules = []
          self.required_modules = set()
          self.module_details = []
          if not self.is_found:
              return
          self.static = kwargs.get('static', False)
  
          self.provided_modules = self.get_config_value(['--components'], 'modules')
          modules = stringlistify(extract_as_list(kwargs, 'modules'))
          self.check_components(modules)
          opt_modules = stringlistify(extract_as_list(kwargs, 'optional_modules'))
          self.check_components(opt_modules, required=False)
  
          cargs = set(self.get_config_value(['--cppflags'], 'compile_args'))
          self.compile_args = list(cargs.difference(self.__cpp_blacklist))
  
          if version_compare(self.version, '>= 3.9'):
              self._set_new_link_args(environment)
          else:
              self._set_old_link_args()
          self.link_args = strip_system_libdirs(environment, self.for_machine, self.link_args)
          self.link_args = self.__fix_bogus_link_args(self.link_args)
          self._add_sub_dependency(ThreadDependency, environment, kwargs)
  
      def __fix_bogus_link_args(self, args):
          """This function attempts to fix bogus link arguments that llvm-config
          generates.
  
          Currently it works around the following:
              - FreeBSD: when statically linking -l/usr/lib/libexecinfo.so will
                be generated, strip the -l in cases like this.
              - Windows: We may get -LIBPATH:... which is later interpreted as
                "-L IBPATH:...", if we're using an msvc like compilers convert
                that to "/LIBPATH", otherwise to "-L ..."
          """
          cpp = self.env.coredata.compilers[self.for_machine]['cpp']
  
          new_args = []
          for arg in args:
              if arg.startswith('-l') and arg.endswith('.so'):
                  new_args.append(arg.lstrip('-l'))
              elif arg.startswith('-LIBPATH:'):
                  new_args.extend(cpp.get_linker_search_args(arg.lstrip('-LIBPATH:')))
              else:
                  new_args.append(arg)
          return new_args
  
      def __check_libfiles(self, shared):
          """Use llvm-config's --libfiles to check if libraries exist."""
          mode = '--link-shared' if shared else '--link-static'
  
          # Set self.required to true to force an exception in get_config_value
          # if the returncode != 0
          restore = self.required
          self.required = True
  
          try:
              # It doesn't matter what the stage is, the caller needs to catch
              # the exception anyway.
              self.link_args = self.get_config_value(['--libfiles', mode], '')
          finally:
              self.required = restore
  
      def _set_new_link_args(self, environment):
          """How to set linker args for LLVM versions >= 3.9"""
          mode = self.get_config_value(['--shared-mode'], 'link_args')[0]
          if not self.static and mode == 'static':
              # If llvm is configured with LLVM_BUILD_LLVM_DYLIB but not with
              # LLVM_LINK_LLVM_DYLIB and not LLVM_BUILD_SHARED_LIBS (which
              # upstreams doesn't recomend using), then llvm-config will lie to
              # you about how to do shared-linking. It wants to link to a a bunch
              # of individual shared libs (which don't exist because llvm wasn't
              # built with LLVM_BUILD_SHARED_LIBS.
              #
              # Therefore, we'll try to get the libfiles, if the return code is 0
              # or we get an empty list, then we'll try to build a working
              # configuration by hand.
              try:
                  self.__check_libfiles(True)
              except DependencyException:
                  lib_ext = get_shared_library_suffix(environment, self.for_machine)
                  libdir = self.get_config_value(['--libdir'], 'link_args')[0]
                  # Sort for reproducability
                  matches = sorted(glob.iglob(os.path.join(libdir, 'libLLVM*{}'.format(lib_ext))))
                  if not matches:
                      if self.required:
                          raise
                      self.is_found = False
                      return
  
                  self.link_args = self.get_config_value(['--ldflags'], 'link_args')
                  libname = os.path.basename(matches[0]).rstrip(lib_ext).lstrip('lib')
                  self.link_args.append('-l{}'.format(libname))
                  return
          elif self.static and mode == 'shared':
              # If, however LLVM_BUILD_SHARED_LIBS is true # (*cough* gentoo *cough*)
              # then this is correct. Building with LLVM_BUILD_SHARED_LIBS has a side
              # effect, it stops the generation of static archives. Therefore we need
              # to check for that and error out on static if this is the case
              try:
                  self.__check_libfiles(False)
              except DependencyException:
                  if self.required:
                      raise
                  self.is_found = False
                  return
  
          link_args = ['--link-static', '--system-libs'] if self.static else ['--link-shared']
          self.link_args = self.get_config_value(
              ['--libs', '--ldflags'] + link_args + list(self.required_modules),
              'link_args')
  
      def _set_old_link_args(self):
          """Setting linker args for older versions of llvm.
  
          Old versions of LLVM bring an extra level of insanity with them.
          llvm-config will provide the correct arguments for static linking, but
          not for shared-linnking, we have to figure those out ourselves, because
          of course we do.
          """
          if self.static:
              self.link_args = self.get_config_value(
                  ['--libs', '--ldflags', '--system-libs'] + list(self.required_modules),
                  'link_args')
          else:
              # llvm-config will provide arguments for static linking, so we get
              # to figure out for ourselves what to link with. We'll do that by
              # checking in the directory provided by --libdir for a library
              # called libLLVM-<ver>.(so|dylib|dll)
              libdir = self.get_config_value(['--libdir'], 'link_args')[0]
  
              expected_name = 'libLLVM-{}'.format(self.version)
              re_name = re.compile(r'{}.(so|dll|dylib)$'.format(expected_name))
  
              for file_ in os.listdir(libdir):
                  if re_name.match(file_):
                      self.link_args = ['-L{}'.format(libdir),
                                        '-l{}'.format(os.path.splitext(file_.lstrip('lib'))[0])]
                      break
              else:
                  raise DependencyException(
                      'Could not find a dynamically linkable library for LLVM.')
  
      def check_components(self, modules, required=True):
          """Check for llvm components (modules in meson terms).
  
          The required option is whether the module is required, not whether LLVM
          is required.
          """
          for mod in sorted(set(modules)):
              status = ''
  
              if mod not in self.provided_modules:
                  if required:
                      self.is_found = False
                      if self.required:
                          raise DependencyException(
                              'Could not find required LLVM Component: {}'.format(mod))
                      status = '(missing)'
                  else:
                      status = '(missing but optional)'
              else:
                  self.required_modules.add(mod)
  
              self.module_details.append(mod + status)
  
      def log_details(self):
          if self.module_details:
              return 'modules: ' + ', '.join(self.module_details)
          return ''
  
  class LLVMDependencyCMake(CMakeDependency):
      def __init__(self, env, kwargs):
          self.llvm_modules = stringlistify(extract_as_list(kwargs, 'modules'))
          self.llvm_opt_modules = stringlistify(extract_as_list(kwargs, 'optional_modules'))
          super().__init__(name='LLVM', environment=env, language='cpp', kwargs=kwargs)
  
          # Extract extra include directories and definitions
          inc_dirs = self.traceparser.get_cmake_var('PACKAGE_INCLUDE_DIRS')
          defs = self.traceparser.get_cmake_var('PACKAGE_DEFINITIONS')
          temp = ['-I' + x for x in inc_dirs] + defs
          self.compile_args += [x for x in temp if x not in self.compile_args]
         
  
  [... the rest is omitted ...]
files: mesonbuild/dependencies/dev.py
files: # Copyright 2013-2019 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.
  
  # This file contains the detection logic for external dependencies useful for
  # development purposes, such as testing, debugging, etc..
  
  import functools
  import glob
  import os
  import re
  
  from .. import mesonlib, mlog
  from ..mesonlib import version_compare, stringlistify, extract_as_list, MachineChoice
  from .base import (
      DependencyException, DependencyMethods, ExternalDependency, PkgConfigDependency,
      strip_system_libdirs, ConfigToolDependency, CMakeDependency, HasNativeKwarg
  )
  from .misc import ThreadDependency
  
  from typing import List, Tuple
  
  
  def get_shared_library_suffix(environment, for_machine: MachineChoice):
      """This is only gauranteed to work for languages that compile to machine
      code, not for languages like C# that use a bytecode and always end in .dll
      """
      m = environment.machines[for_machine]
      if m.is_windows():
          return '.dll'
      elif m.is_darwin():
          return '.dylib'
      return '.so'
  
  
  class GTestDependency(ExternalDependency):
      def __init__(self, environment, kwargs):
          super().__init__('gtest', environment, 'cpp', kwargs)
          self.main = kwargs.get('main', False)
          self.src_dirs = ['/usr/src/gtest/src', '/usr/src/googletest/googletest/src']
          self.detect()
          self._add_sub_dependency(ThreadDependency, environment, kwargs)
  
      def detect(self):
          gtest_detect = self.clib_compiler.find_library("gtest", self.env, [])
          gtest_main_detect = self.clib_compiler.find_library("gtest_main", self.env, [])
          if gtest_detect and (not self.main or gtest_main_detect):
              self.is_found = True
              self.compile_args = []
              self.link_args = gtest_detect
              if self.main:
                  self.link_args += gtest_main_detect
              self.sources = []
              self.prebuilt = True
          elif self.detect_srcdir():
              self.is_found = True
              self.compile_args = ['-I' + d for d in self.src_include_dirs]
              self.link_args = []
              if self.main:
                  self.sources = [self.all_src, self.main_src]
              else:
                  self.sources = [self.all_src]
              self.prebuilt = False
          else:
              self.is_found = False
  
      def detect_srcdir(self):
          for s in self.src_dirs:
              if os.path.exists(s):
                  self.src_dir = s
                  self.all_src = mesonlib.File.from_absolute_file(
                      os.path.join(self.src_dir, 'gtest-all.cc'))
                  self.main_src = mesonlib.File.from_absolute_file(
                      os.path.join(self.src_dir, 'gtest_main.cc'))
                  self.src_include_dirs = [os.path.normpath(os.path.join(self.src_dir, '..')),
                                           os.path.normpath(os.path.join(self.src_dir, '../include')),
                                           ]
                  return True
          return False
  
      def log_info(self):
          if self.prebuilt:
              return 'prebuilt'
          else:
              return 'building self'
  
      def log_tried(self):
          return 'system'
  
      @classmethod
      def _factory(cls, environment, kwargs):
          methods = cls._process_method_kw(kwargs)
          candidates = []
  
          if DependencyMethods.PKGCONFIG in methods:
              pcname = 'gtest_main' if kwargs.get('main', False) else 'gtest'
              candidates.append(functools.partial(PkgConfigDependency, pcname, environment, kwargs))
  
          if DependencyMethods.SYSTEM in methods:
              candidates.append(functools.partial(GTestDependency, environment, kwargs))
  
          return candidates
  
      @staticmethod
      def get_methods():
          return [DependencyMethods.PKGCONFIG, DependencyMethods.SYSTEM]
  
  
  class GMockDependency(ExternalDependency):
      def __init__(self, environment, kwargs):
          super().__init__('gmock', environment, 'cpp', kwargs)
          self.main = kwargs.get('main', False)
          self._add_sub_dependency(ThreadDependency, environment, kwargs)
  
          # If we are getting main() from GMock, we definitely
          # want to avoid linking in main() from GTest
          gtest_kwargs = kwargs.copy()
          if self.main:
              gtest_kwargs['main'] = False
  
          # GMock without GTest is pretty much useless
          # this also mimics the structure given in WrapDB,
          # where GMock always pulls in GTest
          gtest_dep = GTestDependency(environment, gtest_kwargs)
          if not gtest_dep.is_found:
              self.is_found = False
              return
          self.ext_deps.append(gtest_dep)
  
          # GMock may be a library or just source.
          # Work with both.
          gmock_detect = self.clib_compiler.find_library("gmock", self.env, [])
          gmock_main_detect = self.clib_compiler.find_library("gmock_main", self.env, [])
          if gmock_detect and (not self.main or gmock_main_detect):
              self.is_found = True
              self.link_args += gmock_detect
              if self.main:
                  self.link_args += gmock_main_detect
              self.prebuilt = True
              return
  
          for d in ['/usr/src/googletest/googlemock/src', '/usr/src/gmock/src', '/usr/src/gmock']:
              if os.path.exists(d):
                  self.is_found = True
                  # Yes, we need both because there are multiple
                  # versions of gmock that do different things.
                  d2 = os.path.normpath(os.path.join(d, '..'))
                  self.compile_args += ['-I' + d, '-I' + d2, '-I' + os.path.join(d2, 'include')]
                  all_src = mesonlib.File.from_absolute_file(os.path.join(d, 'gmock-all.cc'))
                  main_src = mesonlib.File.from_absolute_file(os.path.join(d, 'gmock_main.cc'))
                  if self.main:
                      self.sources += [all_src, main_src]
                  else:
                      self.sources += [all_src]
                  self.prebuilt = False
                  return
  
          self.is_found = False
  
      def log_info(self):
          if self.prebuilt:
              return 'prebuilt'
          else:
              return 'building self'
  
      def log_tried(self):
          return 'system'
  
      @classmethod
      def _factory(cls, environment, kwargs):
          methods = cls._process_method_kw(kwargs)
          candidates = []
  
          if DependencyMethods.PKGCONFIG in methods:
              pcname = 'gmock_main' if kwargs.get('main', False) else 'gmock'
              candidates.append(functools.partial(PkgConfigDependency, pcname, environment, kwargs))
  
          if DependencyMethods.SYSTEM in methods:
              candidates.append(functools.partial(GMockDependency, environment, kwargs))
  
          return candidates
  
      @staticmethod
      def get_methods():
          return [DependencyMethods.PKGCONFIG, DependencyMethods.SYSTEM]
  
  
  class LLVMDependencyConfigTool(ConfigToolDependency):
      """
      LLVM uses a special tool, llvm-config, which has arguments for getting
      c args, cxx args, and ldargs as well as version.
      """
      tool_name = 'llvm-config'
      __cpp_blacklist = {'-DNDEBUG'}
  
      def __init__(self, environment, kwargs):
          # Already called by `super().__init__`, but need `self.for_machine`
          # before `super().__init__` is called.
          HasNativeKwarg.__init__(self, kwargs)
  
          # Ordered list of llvm-config binaries to try. Start with base, then try
          # newest back to oldest (3.5 is arbitrary), and finally the devel version.
          # Please note that llvm-config-6.0 is a development snapshot and it should
          # not be moved to the beginning of the list.
          self.tools = [
              'llvm-config', # base
              'llvm-config-8',   'llvm-config80',
              'llvm-config-7',   'llvm-config70',
              'llvm-config-6.0', 'llvm-config60',
              'llvm-config-5.0', 'llvm-config50',
              'llvm-config-4.0', 'llvm-config40',
              'llvm-config-3.9', 'llvm-config39',
              'llvm-config-3.8', 'llvm-config38',
              'llvm-config-3.7', 'llvm-config37',
              'llvm-config-3.6', 'llvm-config36',
              'llvm-config-3.5', 'llvm-config35',
              'llvm-config-9',     # Debian development snapshot
              'llvm-config-devel', # FreeBSD development snapshot
          ]
  
          # Fedora starting with Fedora 30 adds a suffix of the number
          # of bits in the isa that llvm targets, for example, on x86_64
          # and aarch64 the name will be llvm-config-64, on x86 and arm
          # it will be llvm-config-32.
          if environment.machines[self.for_machine].is_64_bit:
              self.tools.append('llvm-config-64')
          else:
              self.tools.append('llvm-config-32')
  
          # It's necessary for LLVM <= 3.8 to use the C++ linker. For 3.9 and 4.0
          # the C linker works fine if only using the C API.
          super().__init__('LLVM', environment, 'cpp', kwargs)
          self.provided_modules = []
          self.required_modules = set()
          self.module_details = []
          if not self.is_found:
              return
          self.static = kwargs.get('static', False)
  
          self.provided_modules = self.get_config_value(['--components'], 'modules')
          modules = stringlistify(extract_as_list(kwargs, 'modules'))
          self.check_components(modules)
          opt_modules = stringlistify(extract_as_list(kwargs, 'optional_modules'))
          self.check_components(opt_modules, required=False)
  
          cargs = set(self.get_config_value(['--cppflags'], 'compile_args'))
          self.compile_args = list(cargs.difference(self.__cpp_blacklist))
  
          if version_compare(self.version, '>= 3.9'):
              self._set_new_link_args(environment)
          else:
              self._set_old_link_args()
          self.link_args = strip_system_libdirs(environment, self.for_machine, self.link_args)
          self.link_args = self.__fix_bogus_link_args(self.link_args)
          self._add_sub_dependency(ThreadDependency, environment, kwargs)
  
      def __fix_bogus_link_args(self, args):
          """This function attempts to fix bogus link arguments that llvm-config
          generates.
  
          Currently it works around the following:
              - FreeBSD: when statically linking -l/usr/lib/libexecinfo.so will
                be generated, strip the -l in cases like this.
              - Windows: We may get -LIBPATH:... which is later interpreted as
                "-L IBPATH:...", if we're using an msvc like compilers convert
                that to "/LIBPATH", otherwise to "-L ..."
          """
          cpp = self.env.coredata.compilers[self.for_machine]['cpp']
  
          new_args = []
          for arg in args:
              if arg.startswith('-l') and arg.endswith('.so'):
                  new_args.append(arg.lstrip('-l'))
              elif arg.startswith('-LIBPATH:'):
                  new_args.extend(cpp.get_linker_search_args(arg.lstrip('-LIBPATH:')))
              else:
                  new_args.append(arg)
          return new_args
  
      def __check_libfiles(self, shared):
          """Use llvm-config's --libfiles to check if libraries exist."""
          mode = '--link-shared' if shared else '--link-static'
  
          # Set self.required to true to force an exception in get_config_value
          # if the returncode != 0
          restore = self.required
          self.required = True
  
          try:
              # It doesn't matter what the stage is, the caller needs to catch
              # the exception anyway.
              self.link_args = self.get_config_value(['--libfiles', mode], '')
          finally:
              self.required = restore
  
      def _set_new_link_args(self, environment):
          """How to set linker args for LLVM versions >= 3.9"""
          mode = self.get_config_value(['--shared-mode'], 'link_args')[0]
          if not self.static and mode == 'static':
              # If llvm is configured with LLVM_BUILD_LLVM_DYLIB but not with
              # LLVM_LINK_LLVM_DYLIB and not LLVM_BUILD_SHARED_LIBS (which
              # upstreams doesn't recomend using), then llvm-config will lie to
              # you about how to do shared-linking. It wants to link to a a bunch
              # of individual shared libs (which don't exist because llvm wasn't
              # built with LLVM_BUILD_SHARED_LIBS.
              #
              # Therefore, we'll try to get the libfiles, if the return code is 0
              # or we get an empty list, then we'll try to build a working
              # configuration by hand.
              try:
                  self.__check_libfiles(True)
              except DependencyException:
                  lib_ext = get_shared_library_suffix(environment, self.for_machine)
                  libdir = self.get_config_value(['--libdir'], 'link_args')[0]
                  # Sort for reproducability
                  matches = sorted(glob.iglob(os.path.join(libdir, 'libLLVM*{}'.format(lib_ext))))
                  if not matches:
                      if self.required:
                          raise
                      self.is_found = False
                      return
  
                  self.link_args = self.get_config_value(['--ldflags'], 'link_args')
                  libname = os.path.basename(matches[0]).rstrip(lib_ext).lstrip('lib')
                  self.link_args.append('-l{}'.format(libname))
                  return
          elif self.static and mode == 'shared':
              # If, however LLVM_BUILD_SHARED_LIBS is true # (*cough* gentoo *cough*)
              # then this is correct. Building with LLVM_BUILD_SHARED_LIBS has a side
              # effect, it stops the generation of static archives. Therefore we need
              # to check for that and error out on static if this is the case
              try:
                  self.__check_libfiles(False)
              except DependencyException:
                  if self.required:
                      raise
                  self.is_found = False
                  return
  
          link_args = ['--link-static', '--system-libs'] if self.static else ['--link-shared']
          self.link_args = self.get_config_value(
              ['--libs', '--ldflags'] + link_args + list(self.required_modules),
              'link_args')
  
      def _set_old_link_args(self):
          """Setting linker args for older versions of llvm.
  
          Old versions of LLVM bring an extra level of insanity with them.
          llvm-config will provide the correct arguments for static linking, but
          not for shared-linnking, we have to figure those out ourselves, because
          of course we do.
          """
          if self.static:
              self.link_args = self.get_config_value(
                  ['--libs', '--ldflags', '--system-libs'] + list(self.required_modules),
                  'link_args')
          else:
              # llvm-config will provide arguments for static linking, so we get
              # to figure out for ourselves what to link with. We'll do that by
              # checking in the directory provided by --libdir for a library
              # called libLLVM-<ver>.(so|dylib|dll)
              libdir = self.get_config_value(['--libdir'], 'link_args')[0]
  
              expected_name = 'libLLVM-{}'.format(self.version)
              re_name = re.compile(r'{}.(so|dll|dylib)$'.format(expected_name))
  
              for file_ in os.listdir(libdir):
                  if re_name.match(file_):
                      self.link_args = ['-L{}'.format(libdir),
                                        '-l{}'.format(os.path.splitext(file_.lstrip('lib'))[0])]
                      break
              else:
                  raise DependencyException(
                      'Could not find a dynamically linkable library for LLVM.')
  
      def check_components(self, modules, required=True):
          """Check for llvm components (modules in meson terms).
  
          The required option is whether the module is required, not whether LLVM
          is required.
          """
          for mod in sorted(set(modules)):
              status = ''
  
              if mod not in self.provided_modules:
                  if required:
                      self.is_found = False
                      if self.required:
                          raise DependencyException(
                              'Could not find required LLVM Component: {}'.format(mod))
                      status = '(missing)'
                 
  
  [... the rest is omitted ...]
files: mesonbuild/dependencies/dev.py
files: # 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.
  
  import os, platform, re, sys, shutil, subprocess, typing
  import tempfile
  import shlex
  
  from . import coredata
  from .linkers import ArLinker, ArmarLinker, VisualStudioLinker, DLinker, CcrxLinker, IntelVisualStudioLinker
  from . import mesonlib
  from .mesonlib import (
      MesonException, EnvironmentException, MachineChoice, Popen_safe,
      PerMachineDefaultable, PerThreeMachineDefaultable, split_args, quote_arg
  )
  from . import mlog
  
  from .envconfig import (
      BinaryTable, Directories, MachineInfo, MesonConfigFile,
      Properties, known_cpu_families,
  )
  from . import compilers
  from .compilers import (
      Compiler,
      CompilerType,
      is_assembly,
      is_header,
      is_library,
      is_llvm_ir,
      is_object,
      is_source,
  )
  from .linkers import (
      AppleDynamicLinker,
      ArmClangDynamicLinker,
      ArmDynamicLinker,
      CcrxDynamicLinker,
      ClangClDynamicLinker,
      DynamicLinker,
      GnuDynamicLinker,
      LLVMDynamicLinker,
      MSVCDynamicLinker,
      OptlinkDynamicLinker,
      PGIDynamicLinker,
      PGIStaticLinker,
      SolarisDynamicLinker,
      XildAppleDynamicLinker,
      XildLinuxDynamicLinker,
      XilinkDynamicLinker,
      CudaLinker,
  )
  from functools import lru_cache
  from .compilers import (
      ArmCCompiler,
      ArmCPPCompiler,
      ArmclangCCompiler,
      ArmclangCPPCompiler,
      ClangCCompiler,
      ClangCPPCompiler,
      ClangObjCCompiler,
      ClangObjCPPCompiler,
      ClangClCCompiler,
      ClangClCPPCompiler,
      FlangFortranCompiler,
      G95FortranCompiler,
      GnuCCompiler,
      GnuCPPCompiler,
      GnuFortranCompiler,
      GnuObjCCompiler,
      GnuObjCPPCompiler,
      ElbrusCCompiler,
      ElbrusCPPCompiler,
      ElbrusFortranCompiler,
      EmscriptenCCompiler,
      EmscriptenCPPCompiler,
      IntelCCompiler,
      IntelClCCompiler,
      IntelCPPCompiler,
      IntelClCPPCompiler,
      IntelFortranCompiler,
      IntelClFortranCompiler,
      JavaCompiler,
      MonoCompiler,
      CudaCompiler,
      VisualStudioCsCompiler,
      NAGFortranCompiler,
      Open64FortranCompiler,
      PathScaleFortranCompiler,
      PGICCompiler,
      PGICPPCompiler,
      PGIFortranCompiler,
      RustCompiler,
      CcrxCCompiler,
      CcrxCPPCompiler,
      SunFortranCompiler,
      ValaCompiler,
      VisualStudioCCompiler,
      VisualStudioCPPCompiler,
  )
  
  build_filename = 'meson.build'
  
  CompilersDict = typing.Dict[str, Compiler]
  
  def detect_gcovr(min_version='3.3', new_rootdir_version='4.2', log=False):
      gcovr_exe = 'gcovr'
      try:
          p, found = Popen_safe([gcovr_exe, '--version'])[0:2]
      except (FileNotFoundError, PermissionError):
          # Doesn't exist in PATH or isn't executable
          return None, None
      found = search_version(found)
      if p.returncode == 0 and mesonlib.version_compare(found, '>=' + min_version):
          if log:
              mlog.log('Found gcovr-{} at {}'.format(found, quote_arg(shutil.which(gcovr_exe))))
          return gcovr_exe, mesonlib.version_compare(found, '>=' + new_rootdir_version)
      return None, None
  
  def find_coverage_tools():
      gcovr_exe, gcovr_new_rootdir = detect_gcovr()
  
      lcov_exe = 'lcov'
      genhtml_exe = 'genhtml'
  
      if not mesonlib.exe_exists([lcov_exe, '--version']):
          lcov_exe = None
      if not mesonlib.exe_exists([genhtml_exe, '--version']):
          genhtml_exe = None
  
      return gcovr_exe, gcovr_new_rootdir, lcov_exe, genhtml_exe
  
  def detect_ninja(version: str = '1.5', log: bool = False) -> str:
      env_ninja = os.environ.get('NINJA', None)
      for n in [env_ninja] if env_ninja else ['ninja', 'ninja-build', 'samu']:
          try:
              p, found = Popen_safe([n, '--version'])[0:2]
          except (FileNotFoundError, PermissionError):
              # Doesn't exist in PATH or isn't executable
              continue
          found = found.strip()
          # Perhaps we should add a way for the caller to know the failure mode
          # (not found or too old)
          if p.returncode == 0 and mesonlib.version_compare(found, '>=' + version):
              n = shutil.which(n)
              if log:
                  name = os.path.basename(n)
                  if name.endswith('-' + found):
                      name = name[0:-1 - len(found)]
                  if name == 'ninja-build':
                      name = 'ninja'
                  if name == 'samu':
                      name = 'samurai'
                  mlog.log('Found {}-{} at {}'.format(name, found, quote_arg(n)))
              return n
  
  def get_llvm_tool_names(tool: str) -> typing.List[str]:
      # Ordered list of possible suffixes of LLVM executables to try. Start with
      # base, then try newest back to oldest (3.5 is arbitrary), and finally the
      # devel version. Please note that the development snapshot in Debian does
      # not have a distinct name. Do not move it to the beginning of the list
      # unless it becomes a stable release.
      suffixes = [
          '', # base (no suffix)
          '-8',   '80',
          '-7',   '70',
          '-6.0', '60',
          '-5.0', '50',
          '-4.0', '40',
          '-3.9', '39',
          '-3.8', '38',
          '-3.7', '37',
          '-3.6', '36',
          '-3.5', '35',
          '-9',     # Debian development snapshot
          '-devel', # FreeBSD development snapshot
      ]
      names = []
      for suffix in suffixes:
          names.append(tool + suffix)
      return names
  
  def detect_scanbuild():
      """ Look for scan-build binary on build platform
  
      First, if a SCANBUILD env variable has been provided, give it precedence
      on all platforms.
  
      For most platforms, scan-build is found is the PATH contains a binary
      named "scan-build". However, some distribution's package manager (FreeBSD)
      don't. For those, loop through a list of candidates to see if one is
      available.
  
      Return: a single-element list of the found scan-build binary ready to be
          passed to Popen()
      """
      exelist = []
      if 'SCANBUILD' in os.environ:
          exelist = split_args(os.environ['SCANBUILD'])
  
      else:
          tools = get_llvm_tool_names('scan-build')
          for tool in tools:
              if shutil.which(tool) is not None:
                  exelist = [shutil.which(tool)]
                  break
  
      if exelist:
          tool = exelist[0]
          if os.path.isfile(tool) and os.access(tool, os.X_OK):
              return [tool]
      return []
  
  def detect_native_windows_arch():
      """
      The architecture of Windows itself: x86, amd64 or arm64
      """
      # These env variables are always available. See:
      # https://msdn.microsoft.com/en-us/library/aa384274(VS.85).aspx
      # https://blogs.msdn.microsoft.com/david.wang/2006/03/27/howto-detect-process-bitness/
      arch = os.environ.get('PROCESSOR_ARCHITEW6432', '').lower()
      if not arch:
          try:
              # If this doesn't exist, something is messing with the environment
              arch = os.environ['PROCESSOR_ARCHITECTURE'].lower()
          except KeyError:
              raise EnvironmentException('Unable to detect native OS architecture')
      return arch
  
  def detect_windows_arch(compilers: CompilersDict) -> str:
      """
      Detecting the 'native' architecture of Windows is not a trivial task. We
      cannot trust that the architecture that Python is built for is the 'native'
      one because you can run 32-bit apps on 64-bit Windows using WOW64 and
      people sometimes install 32-bit Python on 64-bit Windows.
  
      We also can't rely on the architecture of the OS itself, since it's
      perfectly normal to compile and run 32-bit applications on Windows as if
      they were native applications. It's a terrible experience to require the
      user to supply a cross-info file to compile 32-bit applications on 64-bit
      Windows. Thankfully, the only way to compile things with Visual Studio on
      Windows is by entering the 'msvc toolchain' environment, which can be
      easily detected.
  
      In the end, the sanest method is as follows:
      1. Check environment variables that are set by Windows and WOW64 to find out
         if this is x86 (possibly in WOW64), if so use that as our 'native'
         architecture.
      2. If the compiler toolchain target architecture is x86, use that as our
        'native' architecture.
      3. Otherwise, use the actual Windows architecture
  
      """
      os_arch = detect_native_windows_arch()
      if os_arch == 'x86':
          return os_arch
      # If we're on 64-bit Windows, 32-bit apps can be compiled without
      # cross-compilation. So if we're doing that, just set the native arch as
      # 32-bit and pretend like we're running under WOW64. Else, return the
      # actual Windows architecture that we deduced above.
      for compiler in compilers.values():
          if compiler.id == 'msvc' and (compiler.target == 'x86' or compiler.target == '80x86'):
              return 'x86'
          if compiler.id == 'clang-cl' and compiler.target == 'x86':
              return 'x86'
          if compiler.id == 'gcc' and compiler.has_builtin_define('__i386__'):
              return 'x86'
      return os_arch
  
  def any_compiler_has_define(compilers: CompilersDict, define):
      for c in compilers.values():
          try:
              if c.has_builtin_define(define):
                  return True
          except mesonlib.MesonException:
              # Ignore compilers that do not support has_builtin_define.
              pass
      return False
  
  def detect_cpu_family(compilers: CompilersDict) -> str:
      """
      Python is inconsistent in its platform module.
      It returns different values for the same cpu.
      For x86 it might return 'x86', 'i686' or somesuch.
      Do some canonicalization.
      """
      if mesonlib.is_windows():
          trial = detect_windows_arch(compilers)
      elif mesonlib.is_freebsd() or mesonlib.is_netbsd() or mesonlib.is_openbsd():
          trial = platform.processor().lower()
      else:
          trial = platform.machine().lower()
      if trial.startswith('i') and trial.endswith('86'):
          trial = 'x86'
      elif trial == 'bepc':
          trial = 'x86'
      elif trial.startswith('arm') or trial.startswith('earm'):
          trial = 'arm'
      elif trial.startswith(('powerpc64', 'ppc64')):
          trial = 'ppc64'
      elif trial.startswith(('powerpc', 'ppc')):
          trial = 'ppc'
      elif trial == 'macppc':
          trial = 'ppc'
      elif trial in ('amd64', 'x64', 'i86pc'):
          trial = 'x86_64'
  
      # On Linux (and maybe others) there can be any mixture of 32/64 bit code in
      # the kernel, Python, system, 32-bit chroot on 64-bit host, etc. The only
      # reliable way to know is to check the compiler defines.
      if trial == 'x86_64':
          if any_compiler_has_define(compilers, '__i386__'):
              trial = 'x86'
      elif trial == 'aarch64':
          if any_compiler_has_define(compilers, '__arm__'):
              trial = 'arm'
      # Add more quirks here as bugs are reported. Keep in sync with detect_cpu()
      # below.
      elif trial == 'parisc64':
          # ATM there is no 64 bit userland for PA-RISC. Thus always
          # report it as 32 bit for simplicity.
          trial = 'parisc'
  
      if trial not in known_cpu_families:
          mlog.warning('Unknown CPU family {!r}, please report this at '
                       'https://github.com/mesonbuild/meson/issues/new with the'
                       'output of `uname -a` and `cat /proc/cpuinfo`'.format(trial))
  
      return trial
  
  def detect_cpu(compilers: CompilersDict):
      if mesonlib.is_windows():
          trial = detect_windows_arch(compilers)
      elif mesonlib.is_freebsd() or mesonlib.is_netbsd() or mesonlib.is_openbsd():
          trial = platform.processor().lower()
      else:
          trial = platform.machine().lower()
      if trial in ('amd64', 'x64', 'i86pc'):
          trial = 'x86_64'
      if trial == 'x86_64':
          # Same check as above for cpu_family
          if any_compiler_has_define(compilers, '__i386__'):
              trial = 'i686' # All 64 bit cpus have at least this level of x86 support.
      elif trial == 'aarch64':
          # Same check as above for cpu_family
          if any_compiler_has_define(compilers, '__arm__'):
              trial = 'arm'
      elif trial.startswith('earm'):
          trial = 'arm'
      elif trial == 'e2k':
          # Make more precise CPU detection for Elbrus platform.
          trial = platform.processor().lower()
      # Add more quirks here as bugs are reported. Keep in sync with
      # detect_cpu_family() above.
      return trial
  
  def detect_system():
      system = platform.system().lower()
      if system.startswith('cygwin'):
          return 'cygwin'
      return system
  
  def detect_msys2_arch():
      if 'MSYSTEM_CARCH' in os.environ:
          return os.environ['MSYSTEM_CARCH']
      return None
  
  def detect_machine_info(compilers: typing.Optional[CompilersDict] = None) -> MachineInfo:
      """Detect the machine we're running on
  
      If compilers are not provided, we cannot know as much. None out those
      fields to avoid accidentally depending on partial knowledge. The
      underlying ''detect_*'' method can be called to explicitly use the
      partial information.
      """
      return MachineInfo(
          detect_system(),
          detect_cpu_family(compilers) if compilers is not None else None,
          detect_cpu(compilers) if compilers is not None else None,
          sys.byteorder)
  
  # TODO make this compare two `MachineInfo`s purely. How important is the
  # `detect_cpu_family({})` distinction? It is the one impediment to that.
  def machine_info_can_run(machine_info: MachineInfo):
      """Whether we can run binaries for this machine on the current machine.
  
      Can almost always run 32-bit binaries on 64-bit natively if the host
      and build systems are the same. We don't pass any compilers to
      detect_cpu_family() here because we always want to know the OS
      architecture, not what the compiler environment tells us.
      """
      if machine_info.system != detect_system():
          return False
      true_build_cpu_family = detect_cpu_family({})
      return \
          (machine_info.cpu_family == true_build_cpu_family) or \
          ((true_build_cpu_family == 'x86_64') and (machine_info.cpu_family == 'x86'))
  
  def search_version(text):
      # Usually of the type 4.1.4 but compiler output may contain
      # stuff like this:
      # (Sourcery CodeBench Lite 2014.05-29) 4.8.3 20140320 (prerelease)
      # Limiting major version number to two digits seems to work
      # thus far.
  
  [... the rest is omitted ...]
files: mesonbuild/environment.py
files: # 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.
  
  import os, platform, re, sys, shutil, subprocess, typing
  import tempfile
  import shlex
  
  from . import coredata
  from .linkers import ArLinker, ArmarLinker, VisualStudioLinker, DLinker, CcrxLinker, IntelVisualStudioLinker
  from . import mesonlib
  from .mesonlib import (
      MesonException, EnvironmentException, MachineChoice, Popen_safe,
      PerMachineDefaultable, PerThreeMachineDefaultable, split_args, quote_arg
  )
  from . import mlog
  
  from .envconfig import (
      BinaryTable, Directories, MachineInfo, MesonConfigFile,
      Properties, known_cpu_families,
  )
  from . import compilers
  from .compilers import (
      Compiler,
      CompilerType,
      is_assembly,
      is_header,
      is_library,
      is_llvm_ir,
      is_object,
      is_source,
  )
  from .linkers import (
      AppleDynamicLinker,
      ArmClangDynamicLinker,
      ArmDynamicLinker,
      CcrxDynamicLinker,
      ClangClDynamicLinker,
      DynamicLinker,
      GnuDynamicLinker,
      LLVMDynamicLinker,
      MSVCDynamicLinker,
      OptlinkDynamicLinker,
      PGIDynamicLinker,
      PGIStaticLinker,
      SolarisDynamicLinker,
      XildAppleDynamicLinker,
      XildLinuxDynamicLinker,
      XilinkDynamicLinker,
      CudaLinker,
  )
  from functools import lru_cache
  from .compilers import (
      ArmCCompiler,
      ArmCPPCompiler,
      ArmclangCCompiler,
      ArmclangCPPCompiler,
      ClangCCompiler,
      ClangCPPCompiler,
      ClangObjCCompiler,
      ClangObjCPPCompiler,
      ClangClCCompiler,
      ClangClCPPCompiler,
      FlangFortranCompiler,
      G95FortranCompiler,
      GnuCCompiler,
      GnuCPPCompiler,
      GnuFortranCompiler,
      GnuObjCCompiler,
      GnuObjCPPCompiler,
      ElbrusCCompiler,
      ElbrusCPPCompiler,
      ElbrusFortranCompiler,
      EmscriptenCCompiler,
      EmscriptenCPPCompiler,
      IntelCCompiler,
      IntelClCCompiler,
      IntelCPPCompiler,
      IntelClCPPCompiler,
      IntelFortranCompiler,
      IntelClFortranCompiler,
      JavaCompiler,
      MonoCompiler,
      CudaCompiler,
      VisualStudioCsCompiler,
      NAGFortranCompiler,
      Open64FortranCompiler,
      PathScaleFortranCompiler,
      PGICCompiler,
      PGICPPCompiler,
      PGIFortranCompiler,
      RustCompiler,
      CcrxCCompiler,
      CcrxCPPCompiler,
      SunFortranCompiler,
      ValaCompiler,
      VisualStudioCCompiler,
      VisualStudioCPPCompiler,
  )
  
  build_filename = 'meson.build'
  
  CompilersDict = typing.Dict[str, Compiler]
  
  def detect_gcovr(min_version='3.3', new_rootdir_version='4.2', log=False):
      gcovr_exe = 'gcovr'
      try:
          p, found = Popen_safe([gcovr_exe, '--version'])[0:2]
      except (FileNotFoundError, PermissionError):
          # Doesn't exist in PATH or isn't executable
          return None, None
      found = search_version(found)
      if p.returncode == 0 and mesonlib.version_compare(found, '>=' + min_version):
          if log:
              mlog.log('Found gcovr-{} at {}'.format(found, quote_arg(shutil.which(gcovr_exe))))
          return gcovr_exe, mesonlib.version_compare(found, '>=' + new_rootdir_version)
      return None, None
  
  def find_coverage_tools():
      gcovr_exe, gcovr_new_rootdir = detect_gcovr()
  
      lcov_exe = 'lcov'
      genhtml_exe = 'genhtml'
  
      if not mesonlib.exe_exists([lcov_exe, '--version']):
          lcov_exe = None
      if not mesonlib.exe_exists([genhtml_exe, '--version']):
          genhtml_exe = None
  
      return gcovr_exe, gcovr_new_rootdir, lcov_exe, genhtml_exe
  
  def detect_ninja(version: str = '1.5', log: bool = False) -> str:
      env_ninja = os.environ.get('NINJA', None)
      for n in [env_ninja] if env_ninja else ['ninja', 'ninja-build', 'samu']:
          try:
              p, found = Popen_safe([n, '--version'])[0:2]
          except (FileNotFoundError, PermissionError):
              # Doesn't exist in PATH or isn't executable
              continue
          found = found.strip()
          # Perhaps we should add a way for the caller to know the failure mode
          # (not found or too old)
          if p.returncode == 0 and mesonlib.version_compare(found, '>=' + version):
              n = shutil.which(n)
              if log:
                  name = os.path.basename(n)
                  if name.endswith('-' + found):
                      name = name[0:-1 - len(found)]
                  if name == 'ninja-build':
                      name = 'ninja'
                  if name == 'samu':
                      name = 'samurai'
                  mlog.log('Found {}-{} at {}'.format(name, found, quote_arg(n)))
              return n
  
  def detect_scanbuild():
      """ Look for scan-build binary on build platform
  
      First, if a SCANBUILD env variable has been provided, give it precedence
      on all platforms.
  
      For most platforms, scan-build is found is the PATH contains a binary
      named "scan-build". However, some distribution's package manager (FreeBSD)
      don't. For those, loop through a list of candidates to see if one is
      available.
  
      Return: a single-element list of the found scan-build binary ready to be
          passed to Popen()
      """
      exelist = []
      if 'SCANBUILD' in os.environ:
          exelist = split_args(os.environ['SCANBUILD'])
  
      else:
          tools = [
              'scan-build',  # base
              'scan-build-8',   'scan-build80',
              'scan-build-7',   'scan-build70',
              'scan-build-6.0', 'scan-build60',
              'scan-build-5.0', 'scan-build50',
              'scan-build-4.0', 'scan-build40',
              'scan-build-3.9', 'scan-build39',
              'scan-build-3.8', 'scan-build38',
              'scan-build-3.7', 'scan-build37',
              'scan-build-3.6', 'scan-build36',
              'scan-build-3.5', 'scan-build35',
              'scan-build-9',   'scan-build-devel',  # development snapshot
          ]
          for tool in tools:
              if shutil.which(tool) is not None:
                  exelist = [shutil.which(tool)]
                  break
  
      if exelist:
          tool = exelist[0]
          if os.path.isfile(tool) and os.access(tool, os.X_OK):
              return [tool]
      return []
  
  def detect_native_windows_arch():
      """
      The architecture of Windows itself: x86, amd64 or arm64
      """
      # These env variables are always available. See:
      # https://msdn.microsoft.com/en-us/library/aa384274(VS.85).aspx
      # https://blogs.msdn.microsoft.com/david.wang/2006/03/27/howto-detect-process-bitness/
      arch = os.environ.get('PROCESSOR_ARCHITEW6432', '').lower()
      if not arch:
          try:
              # If this doesn't exist, something is messing with the environment
              arch = os.environ['PROCESSOR_ARCHITECTURE'].lower()
          except KeyError:
              raise EnvironmentException('Unable to detect native OS architecture')
      return arch
  
  def detect_windows_arch(compilers: CompilersDict) -> str:
      """
      Detecting the 'native' architecture of Windows is not a trivial task. We
      cannot trust that the architecture that Python is built for is the 'native'
      one because you can run 32-bit apps on 64-bit Windows using WOW64 and
      people sometimes install 32-bit Python on 64-bit Windows.
  
      We also can't rely on the architecture of the OS itself, since it's
      perfectly normal to compile and run 32-bit applications on Windows as if
      they were native applications. It's a terrible experience to require the
      user to supply a cross-info file to compile 32-bit applications on 64-bit
      Windows. Thankfully, the only way to compile things with Visual Studio on
      Windows is by entering the 'msvc toolchain' environment, which can be
      easily detected.
  
      In the end, the sanest method is as follows:
      1. Check environment variables that are set by Windows and WOW64 to find out
         if this is x86 (possibly in WOW64), if so use that as our 'native'
         architecture.
      2. If the compiler toolchain target architecture is x86, use that as our
        'native' architecture.
      3. Otherwise, use the actual Windows architecture
  
      """
      os_arch = detect_native_windows_arch()
      if os_arch == 'x86':
          return os_arch
      # If we're on 64-bit Windows, 32-bit apps can be compiled without
      # cross-compilation. So if we're doing that, just set the native arch as
      # 32-bit and pretend like we're running under WOW64. Else, return the
      # actual Windows architecture that we deduced above.
      for compiler in compilers.values():
          if compiler.id == 'msvc' and (compiler.target == 'x86' or compiler.target == '80x86'):
              return 'x86'
          if compiler.id == 'clang-cl' and compiler.target == 'x86':
              return 'x86'
          if compiler.id == 'gcc' and compiler.has_builtin_define('__i386__'):
              return 'x86'
      return os_arch
  
  def any_compiler_has_define(compilers: CompilersDict, define):
      for c in compilers.values():
          try:
              if c.has_builtin_define(define):
                  return True
          except mesonlib.MesonException:
              # Ignore compilers that do not support has_builtin_define.
              pass
      return False
  
  def detect_cpu_family(compilers: CompilersDict) -> str:
      """
      Python is inconsistent in its platform module.
      It returns different values for the same cpu.
      For x86 it might return 'x86', 'i686' or somesuch.
      Do some canonicalization.
      """
      if mesonlib.is_windows():
          trial = detect_windows_arch(compilers)
      elif mesonlib.is_freebsd() or mesonlib.is_netbsd() or mesonlib.is_openbsd():
          trial = platform.processor().lower()
      else:
          trial = platform.machine().lower()
      if trial.startswith('i') and trial.endswith('86'):
          trial = 'x86'
      elif trial == 'bepc':
          trial = 'x86'
      elif trial.startswith('arm') or trial.startswith('earm'):
          trial = 'arm'
      elif trial.startswith(('powerpc64', 'ppc64')):
          trial = 'ppc64'
      elif trial.startswith(('powerpc', 'ppc')):
          trial = 'ppc'
      elif trial == 'macppc':
          trial = 'ppc'
      elif trial in ('amd64', 'x64', 'i86pc'):
          trial = 'x86_64'
  
      # On Linux (and maybe others) there can be any mixture of 32/64 bit code in
      # the kernel, Python, system, 32-bit chroot on 64-bit host, etc. The only
      # reliable way to know is to check the compiler defines.
      if trial == 'x86_64':
          if any_compiler_has_define(compilers, '__i386__'):
              trial = 'x86'
      elif trial == 'aarch64':
          if any_compiler_has_define(compilers, '__arm__'):
              trial = 'arm'
      # Add more quirks here as bugs are reported. Keep in sync with detect_cpu()
      # below.
      elif trial == 'parisc64':
          # ATM there is no 64 bit userland for PA-RISC. Thus always
          # report it as 32 bit for simplicity.
          trial = 'parisc'
  
      if trial not in known_cpu_families:
          mlog.warning('Unknown CPU family {!r}, please report this at '
                       'https://github.com/mesonbuild/meson/issues/new with the'
                       'output of `uname -a` and `cat /proc/cpuinfo`'.format(trial))
  
      return trial
  
  def detect_cpu(compilers: CompilersDict):
      if mesonlib.is_windows():
          trial = detect_windows_arch(compilers)
      elif mesonlib.is_freebsd() or mesonlib.is_netbsd() or mesonlib.is_openbsd():
          trial = platform.processor().lower()
      else:
          trial = platform.machine().lower()
      if trial in ('amd64', 'x64', 'i86pc'):
          trial = 'x86_64'
      if trial == 'x86_64':
          # Same check as above for cpu_family
          if any_compiler_has_define(compilers, '__i386__'):
              trial = 'i686' # All 64 bit cpus have at least this level of x86 support.
      elif trial == 'aarch64':
          # Same check as above for cpu_family
          if any_compiler_has_define(compilers, '__arm__'):
              trial = 'arm'
      elif trial.startswith('earm'):
          trial = 'arm'
      elif trial == 'e2k':
          # Make more precise CPU detection for Elbrus platform.
          trial = platform.processor().lower()
      # Add more quirks here as bugs are reported. Keep in sync with
      # detect_cpu_family() above.
      return trial
  
  def detect_system():
      system = platform.system().lower()
      if system.startswith('cygwin'):
          return 'cygwin'
      return system
  
  def detect_msys2_arch():
      if 'MSYSTEM_CARCH' in os.environ:
          return os.environ['MSYSTEM_CARCH']
      return None
  
  def detect_machine_info(compilers: typing.Optional[CompilersDict] = None) -> MachineInfo:
      """Detect the machine we're running on
  
      If compilers are not provided, we cannot know as much. None out those
      fields to avoid accidentally depending on partial knowledge. The
      underlying ''detect_*'' method can be called to explicitly use the
      partial information.
      """
      return MachineInfo(
          detect_system(),
          detect_cpu_family(compilers) if compilers is not None else None,
          detect_cpu(compilers) if compilers is not None else None,
          sys.byteorder)
  
  # TODO make this compare two `MachineInfo`s purely. How important is the
  # `detect_cpu_family({})` distinction? It is the one impediment to that.
  def machine_info_can_run(machine_info: MachineInfo):
      """Whether we can run binaries for this machine on the current machine.
  
      Can almost always run 32-bit binaries on 64-bit natively if the host
      and build systems are the same. We don't pass any compilers to
      detect_cpu_family() here because we always want to know the OS
      architecture, not what the compiler environment tells us.
      """
      if machine_info.system != detect_system():
          return False
      true_build_cpu_family = detect_cpu_family({})
      return \
          (machine_info.cpu_family == true_build_cpu_family) or \
          ((true_build_cpu_family == 'x86_64') and (machine_info.cpu_family == 'x86'))
  
  def search_version(text):
      # Usually of the type 4.1.4 but compiler output may contain
      # stuff like this:
      # (Sourcery CodeBench Lite 2014.05-29) 4.8.3 20140320 (prerelease)
      # Limiting major version number to two digits seems to work
      # thus far. When we get to GCC 100, this will break, but
      # if we are still relevant when that happens, it can be
      # considered an achievement in itself.
      #
      # This regex is reaching magic levels. If it ever needs
      # to be updated, do not complexify but convert to something
      # saner instead.
      # We'll demystify it a bit with a verbose definition.
     
  
  [... the rest is omitted ...]
files: mesonbuild/environment.py