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 configparser, os, platform, re, shlex, shutil, subprocess
  
  from . import coredata
  from .linkers import ArLinker, VisualStudioLinker
  from . import mesonlib
  from .mesonlib import EnvironmentException, Popen_safe
  from . import mlog
  
  from . import compilers
  from .compilers import (
      CLANG_OSX,
      CLANG_STANDARD,
      CLANG_WIN,
      GCC_CYGWIN,
      GCC_MINGW,
      GCC_OSX,
      GCC_STANDARD,
      ICC_STANDARD,
      is_assembly,
      is_header,
      is_library,
      is_llvm_ir,
      is_object,
      is_source,
  )
  from .compilers import (
      ArmCCompiler,
      ArmCPPCompiler,
      ArmclangCCompiler,
      ArmclangCPPCompiler,
      ClangCCompiler,
      ClangCPPCompiler,
      ClangObjCCompiler,
      ClangObjCPPCompiler,
      G95FortranCompiler,
      GnuCCompiler,
      GnuCPPCompiler,
      GnuFortranCompiler,
      GnuObjCCompiler,
      GnuObjCPPCompiler,
      ElbrusCCompiler,
      ElbrusCPPCompiler,
      ElbrusFortranCompiler,
      IntelCCompiler,
      IntelCPPCompiler,
      IntelFortranCompiler,
      JavaCompiler,
      MonoCompiler,
      VisualStudioCsCompiler,
      NAGFortranCompiler,
      Open64FortranCompiler,
      PathScaleFortranCompiler,
      PGIFortranCompiler,
      RustCompiler,
      SunFortranCompiler,
      ValaCompiler,
      VisualStudioCCompiler,
      VisualStudioCPPCompiler,
  )
  
  build_filename = 'meson.build'
  
  known_cpu_families = (
      'aarch64',
      'arm',
      'e2k',
      'ia64',
      'mips',
      'mips64',
      'parisc',
      'ppc',
      'ppc64',
      'riscv32',
      'riscv64',
      'sparc',
      'sparc64',
      'x86',
      'x86_64'
  )
  
  def detect_gcovr(version='3.1', 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:
          if log:
              mlog.log('Found gcovr-{} at {}'.format(found, shlex.quote(shutil.which(gcovr_exe))))
          return gcovr_exe, mesonlib.version_compare(found, '>=' + 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='1.5', log=False):
      for n in ['ninja', 'ninja-build']:
          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):
              if log:
                  mlog.log('Found ninja-{} at {}'.format(found, shlex.quote(shutil.which(n))))
              return n
  
  def detect_native_windows_arch():
      """
      The architecture of Windows itself: x86 or amd64
      """
      # 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):
      """
      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 if we're in an MSVC toolchain environment, and if so, return the
         MSVC toolchain architecture as our 'native' architecture.
      2. If not, check environment variables that are set by Windows and WOW64 to
         find out the architecture that Windows is built for, and use that as our
         'native' architecture.
      """
      os_arch = detect_native_windows_arch()
      if os_arch != 'amd64':
          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():
          # Check if we're using and inside an MSVC toolchain environment
          if compiler.id == 'msvc' and 'VCINSTALLDIR' in os.environ:
              if float(compiler.get_toolset_version()) < 10.0:
                  # On MSVC 2008 and earlier, check 'BUILD_PLAT', where
                  # 'Win32' means 'x86'
                  platform = os.environ.get('BUILD_PLAT', 'x86')
                  if platform == 'Win32':
                      return 'x86'
              else:
                  # On MSVC 2010 and later 'Platform' is only set when the
                  # target arch is not 'x86'.  It's 'x64' when targeting
                  # x86_64 and 'arm' when targeting ARM.
                  platform = os.environ.get('Platform', 'x86').lower()
              if platform == 'x86':
                  return platform
          if compiler.id == 'gcc' and compiler.has_builtin_define('__i386__'):
              return 'x86'
      return os_arch
  
  def detect_cpu_family(compilers):
      """
      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)
      else:
          trial = platform.machine().lower()
      if trial.startswith('i') and trial.endswith('86'):
          return 'x86'
      if trial.startswith('arm'):
          return 'arm'
      if trial.startswith('ppc64'):
          return 'ppc64'
      if trial in ('amd64', 'x64'):
          trial = 'x86_64'
      if trial == 'x86_64':
          # On Linux (and maybe others) there can be any mixture of 32/64 bit
          # code in the kernel, Python, system etc. The only reliable way
          # to know is to check the compiler defines.
          for c in compilers.values():
              try:
                  if c.has_builtin_define('__i386__'):
                      return 'x86'
              except mesonlib.MesonException:
                  # Ignore compilers that do not support has_builtin_define.
                  pass
          return 'x86_64'
      # Add fixes here as bugs are reported.
  
      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):
      if mesonlib.is_windows():
          trial = detect_windows_arch(compilers)
      else:
          trial = platform.machine().lower()
      if trial in ('amd64', 'x64'):
          trial = 'x86_64'
      if trial == 'x86_64':
          # Same check as above for cpu_family
          for c in compilers.values():
              try:
                  if c.has_builtin_define('__i386__'):
                      return 'i686' # All 64 bit cpus have at least this level of x86 support.
              except mesonlib.MesonException:
                  pass
          return 'x86_64'
      if trial == 'e2k':
          # Make more precise CPU detection for Elbrus platform.
          trial = platform.processor().lower()
      # Add fixes here as bugs are reported.
      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 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.
      version_regex = '(?<!(\d|\.))(\d{1,2}(\.\d+)+(-[a-zA-Z0-9]+)?)'
      match = re.search(version_regex, text)
      if match:
          return match.group(0)
      return 'unknown version'
  
  class Environment:
      private_dir = 'meson-private'
      log_dir = 'meson-logs'
  
      def __init__(self, source_dir, build_dir, options):
          self.source_dir = source_dir
          self.build_dir = build_dir
          self.scratch_dir = os.path.join(build_dir, Environment.private_dir)
          self.log_dir = os.path.join(build_dir, Environment.log_dir)
          os.makedirs(self.scratch_dir, exist_ok=True)
          os.makedirs(self.log_dir, exist_ok=True)
          try:
              self.coredata = coredata.load(self.get_build_dir())
              self.first_invocation = False
          except FileNotFoundError:
              # WARNING: Don't use any values from coredata in __init__. It gets
              # re-initialized with project options by the interpreter during
              # build file parsing.
              self.coredata = coredata.CoreData(options)
              # Used by the regenchecker script, which runs meson
              self.coredata.meson_command = mesonlib.meson_command
              self.first_invocation = True
          self.cross_info = None
          self.exe_wrapper = None
          if self.coredata.cross_file:
              self.cross_info = CrossBuildInfo(self.coredata.cross_file)
              if 'exe_wrapper' in self.cross_info.config['binaries']:
                  from .dependencies import ExternalProgram
                  self.exe_wrapper = ExternalProgram.from_cross_info(self.cross_info, 'exe_wrapper')
          self.cmd_line_options = options.cmd_line_options.copy()
  
          # List of potential compilers.
          if mesonlib.is_windows():
              self.default_c = ['cl', 'cc', 'gcc', 'clang']
              self.default_cpp = ['cl', 'c++', 'g++', 'clang++']
          else:
              self.default_c = ['cc', 'gcc', 'clang']
              self.default_cpp = ['c++', 'g++', 'clang++']
          if mesonlib.is_windows():
              self.default_cs = ['csc', 'mcs']
          else:
              self.default_cs = ['mcs', 'csc']
          self.default_objc = ['cc']
          self.default_objcpp = ['c++']
          self.default_fortran = ['gfortran', 'g95', 'f95', 'f90', 'f77', 'ifort']
          self.default_rust = ['rustc']
          self.default_static_linker = ['ar']
          self.vs_static_linker = ['lib']
          self.gcc_static_linker = ['gcc-ar']
          self.clang_static_linker = ['llvm-ar']
  
          # Various prefixes and suffixes for import libraries, shared libraries,
          # static libraries, and executables.
          # Versioning is added to these names in the backends as-needed.
          cross = self.is_cross_build()
          if mesonlib.for_windows(cross, self):
              self.exe_suffix = 'exe'
              self.object_suffix = 'obj'
              self.win_libdir_layout = True
          elif mesonlib.for_cygwin(cross, self):
              self.exe_suffix = 'exe'
              self.object_suffix = 'o'
              self.win_libdir_layout = True
          else:
              self.exe_suffix = ''
              self.object_suffix = 'o'
              self.win_libdir_layout = False
          if 'STRIP' in os.environ:
              self.native_strip_bin = shlex.split(os.environ['STRIP'])
          else:
              self.native_strip_bin = ['strip']
  
      def is_cross_build(self):
          return self.cross_info is not None
  
      def dump_coredata(self):
          return coredata.save(self.coredata, self.get_build_dir())
  
      def get_script_dir(self):
          import mesonbuild.scripts
          return os.path.dirname(mesonbuild.scripts.__file__)
  
      def get_log_dir(self):
          return self.log_dir
  
      def get_coredata(self):
          return self.coredata
  
      def get_build_command(self, unbuffered=False):
          cmd = mesonlib.meson_command[:]
          if unbuffered and 'python' in cmd[0]:
              cmd.insert(1, '-u')
          return cmd
  
      def is_header(self, fname):
          return is_header(fname)
  
      def is_source(self, fname):
          return is_source(fname)
  
      def is_assembly(self, fname):
          return is_assembly(fname)
  
      def is_llvm_ir(self, fname):
          return is_llvm_ir(fname)
  
      def is_object(self, fname):
          return is_object(fname)
  
      def is_library(self, fname):
          return is_library(fname)
  
      @staticmethod
      def get_gnu_compiler_defines(compiler):
          """
          Detect GNU compiler platform type (Apple, MinGW, Unix)
          """
          # Arguments to output compiler pre-processor defines to stdout
          # gcc, g++, and gfortran all support these arguments
          args = compiler + ['-E', '-dM', '-']
          p, output, error = Popen_safe(args, write='', stdin=subprocess.PIPE)
          if p.returncode != 0:
              raise EnvironmentException('Unable to detect GNU compiler type:\n' + output + error)
          # Parse several lines of the type:
          # `#define ___SOME_DEF some_value`
          # and extract `___SOME_DEF`
          defines = {}
          for line in output.split('\n'):
              if not line:
                  continue
              d, *rest = line.split(' ', 2)
              if d != '#define':
                  continue
              if len(rest) == 1:
                  defines[rest] = True
              if len(rest) == 2:
                  defines[rest[0]] = rest[1]
          return defines
  
      @staticmethod
      def get_gnu_version_from_defines(defines):
          dot = '.'
          major = defines.get('__GNUC__', '0')
          minor = defines.get('__GNUC_MINOR__', '0')
          patch = defines.get('__GNUC_PATCHLEVEL__', '0')
          return dot.join((major, minor, patch))
  
      @staticmethod
      def get_lcc_version_from_defines(defines):
          dot = '.'
          generation_and_major = defines.get('__LCC__', '100')
          generation = generation_and_major[:1]
          major = generation_and_major[1:]
          minor = defines.get('__LCC_MINOR__', '0')
          return dot.join((generation, major, minor))
  
      @staticmethod
      def get_gnu_compiler_type(defines):
          # Detect GCC type (Apple, MinGW, Cygwin, Unix)
          if '__APPLE__' in defines:
              return GCC_OSX
          elif '__MINGW32__' in defines or '__MINGW64__' in defines:
              return GCC_MINGW
          elif '__CYGWIN__' in defines:
              return GCC_CYGWIN
          return GCC_STANDARD
  
      def warn_about_lang_pointing_to_cross(self, compiler_exe, evar):
          evar_str = os.environ.get(evar, 'WHO_WOULD_CALL_THEIR_COMPILER_WITH_THIS_NAME')
          if evar_str == compiler_exe:
              mlog.warning('''Env var %s seems to point to the cross compiler.
  This is probably wrong, it should always point to the native compiler.''' % evar)
  
      def _get_compilers(self, lang, evar, want_cross):
          '''
          The list of compilers is detected in the exact same way for
          C, C++, ObjC, ObjC++, Fortran, CS so consolidate it here.
          '''
          if self.is_cross_build() and want_cross:
              if lang not in self.cross_info.config['binaries']:
                  raise EnvironmentException('{!r} compiler binary not defined in cross file'.format(lang))
              compilers = mesonlib.stringlistify(self.cross_info.config['binaries'][lang])
              # Ensure ccache exists and remove it if it doesn't
              if compilers[0] == 'ccache':
                  compilers = compilers[1:]
                  ccache = self.detect_ccache()
              else:
                  ccache = []
              self.warn_about_lang_pointing_to_cross(compilers[0], evar)
              # Return value has to be a list of compiler 'choices'
              compilers = [compilers]
              is_cross = True
              exe_wrap = self.get_exe_wrapper()
          elif evar in os.environ:
              compilers = shlex.split(os.environ[evar])
              # Ensure ccache exists and remove it if it doesn't
              if compilers[0] == 'ccache':
                  compilers = compilers[1:]
                  ccache = self.detect_ccache()
              else:
                  ccache = []
              # Return value has to be a list of compiler 'choices'
              compilers = [compilers]
              is_cross = False
              exe_wrap = None
          else:
              compilers = getattr(self, 'default_' + lang)
              ccache = self.detect_ccache()
              is_cross = False
              exe_wrap = None
          return compilers, ccache, is_cross, exe_wrap
  
      def _handle_exceptions(self, exceptions, binaries, bintype='compiler'):
          errmsg = 'Unknown {}(s): {}'.format(bintype, binaries)
          if exceptions:
              errmsg += '\nThe follow exceptions were encountered:'
              for (c, e) in exceptions.items():
                  errmsg += '\nRunning "{0}" gave "{1}"'.format(c, e)
          raise EnvironmentException(errmsg)
  
      def _detect_c_or_cpp_compiler(self, lang, evar, want_cross):
          popen_exceptions = {}
          compilers, ccache, is_cross, exe_wrap = self._get_compilers(lang, evar, want_cross)
          for compiler in compilers:
              if isinstance(compiler, str):
                  compiler = [compiler]
              if 'cl' in compiler or 'cl.exe' in compiler:
                  # Watcom C provides it's own cl.exe clone that mimics an older
                  # version of Microsoft's compiler. Since Watcom's cl.exe is
                  # just a wrapper, we skip using it if we detect its presence
                  # so as not to confuse Meson when configuring for MSVC.
                  #
                  # Additionally the help text of Watcom's cl.exe is paged, and
                  # the binary will not exit without human intervention. In
                  # practice, Meson will block waiting for Watcom's cl.exe to
                  # exit, which requires user input and thus will never exit.
                  if 'WATCOM' in os.environ:
                      def sanitize(p):
                          return os.path.normcase(os.path.abspath(p))
  
                      watcom_cls = [sanitize(os.path.join(os.environ['WATCOM'], 'BINNT', 'cl')),
                                    sanitize(os.path.join(os.environ['WATCOM'], 'BINNT', 'cl.exe'))]
                      found_cl = sanitize(shutil.which('cl'))
                      if found_cl in watcom_cls:
                          continue
                  arg = '/?'
              elif 'armcc' in compiler[0]:
                  arg = '--vsn'
              else:
                  arg = '--version'
              try:
                  p, out, err = Popen_safe(compiler + [arg])
              except OSError as e:
                  popen_exceptions[' '.join(compiler + [arg])] = e
                  continue
              version = search_version(out)
              full_version = out.split('\n', 1)[0]
  
              guess_gcc_or_lcc = False
              if 'Free Software Foundation' in out:
                  guess_gcc_or_lcc = 'gcc'
              if 'e2k' in out and 'lcc' in out:
                  guess_gcc_or_lcc = 'lcc'
  
              if guess_gcc_or_lcc:
                  defines = self.get_gnu_compiler_defines(compiler)
                  if not defines:
                      popen_exceptions[' '.join(compiler)] = 'no pre-processor defines'
                      continue
                  gtype = self.get_gnu_compiler_type(defines)
                  if guess_gcc_or_lcc == 'lcc':
                      version = self.get_lcc_version_from_defines(defines)
                      cls = ElbrusCCompiler if lang == 'c' else ElbrusCPPCompiler
                  else:
                      version = self.get_gnu_version_from_defines(defines)
                      cls = GnuCCompiler if lang == 'c' else GnuCPPCompiler
                  return cls(ccache + compiler, version, gtype, is_cross, exe_wrap, defines, full_version=full_version)
  
              if 'armclang' in out:
                  # The compiler version is not present in the first line of output,
                  # instead it is present in second line, startswith 'Component:'.
                  # So, searching for the 'Component' in out although we know it is
                  # present in second line, as we are not sure about the
                  # output format in future versions
                  arm_ver_str = re.search('.*Component.*', out)
                  if arm_ver_str is None:
                      popen_exceptions[' '.join(compiler)] = 'version string not found'
                      continue
                  arm_ver_str = arm_ver_str.group(0)
                  # Override previous values
                  version = search_version(arm_ver_str)
                  full_version = arm_ver_str
                  cls = ArmclangCCompiler if lang == 'c' else ArmclangCPPCompiler
                  return cls(ccache + compiler, version, is_cross, exe_wrap, full_version=full_version)
              if 'clang' in out:
                  if 'Apple' in out or mesonlib.for_darwin(want_cross, self):
                      cltype = CLANG_OSX
                  elif 'windows' in out or mesonlib.for_windows(want_cross, self):
                      cltype = CLANG_WIN
                  else:
                      cltype = CLANG_STANDARD
                  cls = ClangCCompiler if lang == 'c' else ClangCPPCompiler
                  return cls(ccache + compiler, version, cltype, is_cross, exe_wrap, full_version=full_version)
              if 'Microsoft' in out or 'Microsoft' in err:
                  # Latest versions of Visual Studio print version
                  # number to stderr but earlier ones print version
                  # on stdout.  Why? Lord only knows.
                  # Check both outputs to figure out version.
                  version = search_version(err)
                  if version == 'unknown version':
                      version = search_version(out)
                  if version == 'unknown version':
                      m = 'Failed to detect MSVC compiler arch: stderr was\n{!r}'
                      raise EnvironmentException(m.format(err))
                  is_64 = err.split('\n')[0].endswith(' x64')
                  cls = VisualStudioCCompiler if lang == 'c' else VisualStudioCPPCompiler
                  return cls(compiler, version, is_cross, exe_wrap, is_64)
              if '(ICC)' in out:
                  # TODO: add microsoft add check OSX
                  inteltype = ICC_STANDARD
                  cls = IntelCCompiler if lang == 'c' else IntelCPPCompiler
                  return cls(ccache + compiler, version, inteltype, is_cross, exe_wrap, full_version=full_version)
              if 'ARM' in out:
                  cls = ArmCCompiler if lang == 'c' else ArmCPPCompiler
                  return cls(ccache + compiler, version, is_cross, exe_wrap, full_version=full_version)
          self._handle_exceptions(popen_exceptions, compilers)
  
      def detect_c_compiler(self, want_cross):
          return self._detect_c_or_cpp_compiler('c', 'CC', want_cross)
  
      def detect_cpp_compiler(self, want_cross):
          return self._detect_c_or_cpp_compiler('cpp', 'CXX', want_cross)
  
      def detect_fortran_compiler(self, want_cross):
          popen_exceptions = {}
          compilers, ccache, is_cross, exe_wrap = self._get_compilers('fortran', 'FC', want_cross)
          for compiler in compilers:
              if isinstance(compiler, str):
                  compiler = [compiler]
              for arg in ['--version', '-V']:
                  try:
                      p, out, err = Popen_safe(compiler + [arg])
                  except OSError as e:
                      popen_exceptions[' '.join(compiler + [arg])] = e
                      continue
  
                  version = search_version(out)
                  full_version = out.split('\n', 1)[0]
  
                  guess_gcc_or_lcc = False
                  if 'GNU Fortran' in out:
                      guess_gcc_or_lcc = 'gcc'
                  if 'e2k' in out and 'lcc' in out:
                      guess_gcc_or_lcc = 'lcc'
  
                  if guess_gcc_or_lcc:
                      defines = self.get_gnu_compiler_defines(compiler)
                      if not defines:
                          popen_exceptions[' '.join(compiler)] = 'no pre-processor defines'
                          continue
                      gtype = self.get_gnu_compiler_type(defines)
                      if guess_gcc_or_lcc == 'lcc':
                          version = self.get_lcc_version_from_defines(defines)
                          cls = ElbrusFortranCompiler
                      else:
                          version = self.get_gnu_version_from_defines(defines)
                          cls = GnuFortranCompiler
                      return cls(compiler, version, gtype, is_cross, exe_wrap, defines, full_version=full_version)
  
                  if 'G95' in out:
                      return G95FortranCompiler(compiler, version, is_cross, exe_wrap, full_version=full_version)
  
                  if 'Sun Fortran' in err:
                      version = search_version(err)
                      return SunFortranCompiler(compiler, version, is_cross, exe_wrap, full_version=full_version)
  
                  if 'ifort (IFORT)' in out:
                      return IntelFortranCompiler(compiler, version, is_cross, exe_wrap, full_version=full_version)
  
                  if 'PathScale EKOPath(tm)' in err:
                      return PathScaleFortranCompiler(compiler, version, is_cross, exe_wrap, full_version=full_version)
  
                  if 'PGI Compilers' in out:
                      return PGIFortranCompiler(compiler, version, is_cross, exe_wrap, full_version=full_version)
  
                  if 'Open64 Compiler Suite' in err:
                      return Open64FortranCompiler(compiler, version, is_cross, exe_wrap, full_version=full_version)
  
                  if 'NAG Fortran' in err:
                      return NAGFortranCompiler(compiler, version, is_cross, exe_wrap, full_version=full_version)
          self._handle_exceptions(popen_exceptions, compilers)
  
      def get_scratch_dir(self):
          return self.scratch_dir
  
      def detect_objc_compiler(self, want_cross):
          popen_exceptions = {}
          compilers, ccache, is_cross, exe_wrap = self._get_compilers('objc', 'OBJC', want_cross)
          for compiler in compilers:
              if isinstance(compiler, str):
                  compiler = [compiler]
              arg = ['--version']
              try:
                  p, out, err = Popen_safe(compiler + arg)
              except OSError as e:
                  popen_exceptions[' '.join(compiler + arg)] = e
                  continue
              version = search_version(out)
              if 'Free Software Foundation' in out or ('e2k' in out and 'lcc' in out):
                  defines = self.get_gnu_compiler_defines(compiler)
                  if not defines:
                      popen_exceptions[' '.join(compiler)] = 'no pre-processor defines'
                      continue
                  gtype = self.get_gnu_compiler_type(defines)
                  version = self.get_gnu_version_from_defines(defines)
                  return GnuObjCCompiler(ccache + compiler, version, gtype, is_cross, exe_wrap, defines)
              if out.startswith('Apple LLVM'):
                  return ClangObjCCompiler(ccache + compiler, version, CLANG_OSX, is_cross, exe_wrap)
              if out.startswith('clang'):
                  return ClangObjCCompiler(ccache + compiler, version, CLANG_STANDARD, is_cross, exe_wrap)
          self._handle_exceptions(popen_exceptions, compilers)
  
      def detect_objcpp_compiler(self, want_cross):
          popen_exceptions = {}
          compilers, ccache, is_cross, exe_wrap = self._get_compilers('objcpp', 'OBJCXX', want_cross)
          for compiler in compilers:
              if isinstance(compiler, str):
                  compiler = [compiler]
              arg = ['--version']
              try:
                  p, out, err = Popen_safe(compiler + arg)
              except OSError as e:
                  popen_exceptions[' '.join(compiler + arg)] = e
                  continue
              version = search_version(out)
              if 'Free Software Foundation' in out or ('e2k' in out and 'lcc' in out):
                  defines = self.get_gnu_compiler_defines(compiler)
                  if not defines:
                      popen_exceptions[' '.join(compiler)] = 'no pre-processor defines'
                      continue
                  gtype = self.get_gnu_compiler_type(defines)
                  version = self.get_gnu_version_from_defines(defines)
                  return GnuObjCPPCompiler(ccache + compiler, version, gtype, is_cross, exe_wrap, defines)
              if out.startswith('Apple LLVM'):
                  return ClangObjCPPCompiler(ccache + compiler, version, CLANG_OSX, is_cross, exe_wrap)
              if out.startswith('clang'):
                  return ClangObjCPPCompiler(ccache + compiler, version, CLANG_STANDARD, is_cross, exe_wrap)
          self._handle_exceptions(popen_exceptions, compilers)
  
      def detect_java_compiler(self):
          exelist = ['javac']
          try:
              p, out, err = Popen_safe(exelist + ['-version'])
          except OSError:
              raise EnvironmentException('Could not execute Java compiler "%s"' % ' '.join(exelist))
          version = search_version(err)
          if 'javac' in out or 'javac' in err:
              return JavaCompiler(exelist, version)
          raise EnvironmentException('Unknown compiler "' + ' '.join(exelist) + '"')
  
      def detect_cs_compiler(self):
          compilers, ccache, is_cross, exe_wrap = self._get_compilers('cs', 'CSC', False)
          popen_exceptions = {}
          for comp in compilers:
              if not isinstance(comp, list):
                  comp = [comp]
              try:
                  p, out, err = Popen_safe(comp + ['--version'])
              except OSError as e:
                  popen_exceptions[' '.join(comp + ['--version'])] = e
                  continue
  
              version = search_version(out)
              if 'Mono' in out:
                  return MonoCompiler(comp, version)
              elif "Visual C#" in out:
                  return VisualStudioCsCompiler(comp, version)
  
          self._handle_exceptions(popen_exceptions, compilers)
  
      def detect_vala_compiler(self):
          if 'VALAC' in os.environ:
              exelist = shlex.split(os.environ['VALAC'])
          else:
              exelist = ['valac']
          try:
              p, out = Popen_safe(exelist + ['--version'])[0:2]
          except OSError:
              raise EnvironmentException('Could not execute Vala compiler "%s"' % ' '.join(exelist))
          version = search_version(out)
          if 'Vala' in out:
              return ValaCompiler(exelist, version)
          raise EnvironmentException('Unknown compiler "' + ' '.join(exelist) + '"')
  
      def detect_rust_compiler(self, want_cross):
          popen_exceptions = {}
          compilers, ccache, is_cross, exe_wrap = self._get_compilers('rust', 'RUSTC', want_cross)
          for compiler in compilers:
              if isinstance(compiler, str):
                  compiler = [compiler]
              arg = ['--version']
              try:
                  p, out = Popen_safe(compiler + arg)[0:2]
              except OSError as e:
                  popen_exceptions[' '.join(compiler + arg)] = e
                  continue
  
              version = search_version(out)
  
              if 'rustc' in out:
                  return RustCompiler(compiler, version, is_cross, exe_wrap)
  
          self._handle_exceptions(popen_exceptions, compilers)
  
      def detect_d_compiler(self, want_cross):
          is_cross = False
          # Search for a D compiler.
          # We prefer LDC over GDC unless overridden with the DC
          # environment variable because LDC has a much more
          # up to date language version at time (2016).
          if 'DC' in os.environ:
              exelist = shlex.split(os.environ['DC'])
          elif self.is_cross_build() and want_cross:
              exelist = mesonlib.stringlistify(self.cross_info.config['binaries']['d'])
              is_cross = True
          elif shutil.which("ldc2"):
              exelist = ['ldc2']
          elif shutil.which("ldc"):
              exelist = ['ldc']
          elif shutil.which("gdc"):
              exelist = ['gdc']
          elif shutil.which("dmd"):
              exelist = ['dmd']
          else:
              raise EnvironmentException('Could not find any supported D compiler.')
  
          try:
              p, out = Popen_safe(exelist + ['--version'])[0:2]
          except OSError:
              raise EnvironmentException('Could not execute D compiler "%s"' % ' '.join(exelist))
          version = search_version(out)
          full_version = out.split('\n', 1)[0]
          if 'LLVM D compiler' in out:
              return compilers.LLVMDCompiler(exelist, version, is_cross, full_version=full_version)
          elif 'gdc' in out:
              return compilers.GnuDCompiler(exelist, version, is_cross, full_version=full_version)
          elif 'The D Language Foundation' in out or 'Digital Mars' in out:
              return compilers.DmdDCompiler(exelist, version, is_cross, full_version=full_version)
          raise EnvironmentException('Unknown compiler "' + ' '.join(exelist) + '"')
  
      def detect_swift_compiler(self):
          exelist = ['swiftc']
          try:
              p, _, err = Popen_safe(exelist + ['-v'])
          except OSError:
              raise EnvironmentException('Could not execute Swift compiler "%s"' % ' '.join(exelist))
          version = search_version(err)
          if 'Swift' in err:
              return compilers.SwiftCompiler(exelist, version)
          raise EnvironmentException('Unknown compiler "' + ' '.join(exelist) + '"')
  
      def detect_static_linker(self, compiler):
          if compiler.is_cross:
              linker = self.cross_info.config['binaries']['ar']
              if isinstance(linker, str):
                  linker = [linker]
              linkers = [linker]
          else:
              evar = 'AR'
              if evar in os.environ:
                  linkers = [shlex.split(os.environ[evar])]
              elif isinstance(compiler, compilers.VisualStudioCCompiler):
                  linkers = [self.vs_static_linker]
              elif isinstance(compiler, compilers.GnuCompiler):
                  # Use gcc-ar if available; needed for LTO
                  linkers = [self.gcc_static_linker, self.default_static_linker]
              elif isinstance(compiler, compilers.ClangCompiler):
                  # Use llvm-ar if available; needed for LTO
                  linkers = [self.clang_static_linker, self.default_static_linker]
              else:
                  linkers = [self.default_static_linker]
          popen_exceptions = {}
          for linker in linkers:
              if 'lib' in linker or 'lib.exe' in linker:
                  arg = '/?'
              else:
                  arg = '--version'
              try:
                  p, out, err = Popen_safe(linker + [arg])
              except OSError as e:
                  popen_exceptions[' '.join(linker + [arg])] = e
                  continue
              if '/OUT:' in out or '/OUT:' in err:
                  return VisualStudioLinker(linker)
              if p.returncode == 0:
                  return ArLinker(linker)
              if p.returncode == 1 and err.startswith('usage'): # OSX
                  return ArLinker(linker)
          self._handle_exceptions(popen_exceptions, linkers, 'linker')
          raise EnvironmentException('Unknown static linker "%s"' % ' '.join(linkers))
  
      def detect_ccache(self):
          try:
              has_ccache = subprocess.call(['ccache', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
          except OSError:
              has_ccache = 1
          if has_ccache == 0:
              cmdlist = ['ccache']
          else:
              cmdlist = []
          return cmdlist
  
      def get_source_dir(self):
          return self.source_dir
  
      def get_build_dir(self):
          return self.build_dir
  
      def get_exe_suffix(self):
          return self.exe_suffix
  
      def get_import_lib_dir(self):
          "Install dir for the import library (library used for linking)"
          return self.get_libdir()
  
      def get_shared_module_dir(self):
          "Install dir for shared modules that are loaded at runtime"
          return self.get_libdir()
  
      def get_shared_lib_dir(self):
          "Install dir for the shared library"
          if self.win_libdir_layout:
              return self.get_bindir()
          return self.get_libdir()
  
      def get_static_lib_dir(self):
          "Install dir for the static library"
          return self.get_libdir()
  
      def get_object_suffix(self):
          return self.object_suffix
  
      def get_prefix(self):
          return self.coredata.get_builtin_option('prefix')
  
      def get_libdir(self):
          return self.coredata.get_builtin_option('libdir')
  
      def get_libexecdir(self):
          return self.coredata.get_builtin_option('libexecdir')
  
      def get_bindir(self):
          return self.coredata.get_builtin_option('bindir')
  
      def get_includedir(self):
          return self.coredata.get_builtin_option('includedir')
  
      def get_mandir(self):
          return self.coredata.get_builtin_option('mandir')
  
      def get_datadir(self):
          return self.coredata.get_builtin_option('datadir')
  
      def get_compiler_system_dirs(self):
          for comp in self.coredata.compilers.values():
              if isinstance(comp, compilers.ClangCompiler):
                  index = 1
                  break
              elif isinstance(comp, compilers.GnuCompiler):
                  index = 2
                  break
          else:
              # This option is only supported by gcc and clang. If we don't get a
              # GCC or Clang compiler return and empty list.
              return []
  
          p, out, _ = Popen_safe(comp.get_exelist() + ['-print-search-dirs'])
          if p.returncode != 0:
              raise mesonlib.MesonException('Could not calculate system search dirs')
          out = out.split('\n')[index].lstrip('libraries: =').split(':')
          return [os.path.normpath(p) for p in out]
  
      def get_exe_wrapper(self):
          if not self.cross_info.need_exe_wrapper():
              from .dependencies import EmptyExternalProgram
              return EmptyExternalProgram()
          return self.exe_wrapper
  
  
  class CrossBuildInfo:
      def __init__(self, filename):
          self.config = {'properties': {}}
          self.parse_datafile(filename)
          if 'target_machine' in self.config:
              return
          if 'host_machine' not in self.config:
              raise mesonlib.MesonException('Cross info file must have either host or a target machine.')
          if 'binaries' not in self.config:
              raise mesonlib.MesonException('Cross file is missing "binaries".')
  
      def ok_type(self, i):
          return isinstance(i, (str, int, bool))
  
      def parse_datafile(self, filename):
          config = configparser.ConfigParser()
          try:
              with open(filename, 'r') as f:
                  config.read_file(f, filename)
          except FileNotFoundError:
              raise EnvironmentException('File not found: %s.' % filename)
          # This is a bit hackish at the moment.
          for s in config.sections():
              self.config[s] = {}
              for entry in config[s]:
                  value = config[s][entry]
                  if ' ' in entry or '\t' in entry or "'" in entry or '"' in entry:
                      raise EnvironmentException('Malformed variable name %s in cross file..' % entry)
                  try:
                      res = eval(value, {'__builtins__': None}, {'true': True, 'false': False})
                  except Exception:
                      raise EnvironmentException('Malformed value in cross file variable %s.' % entry)
  
                  if entry == 'cpu_family' and res not in known_cpu_families:
                      mlog.warning('Unknown CPU family %s, please report this at https://github.com/mesonbuild/meson/issues/new' % value)
  
                  if self.ok_type(res):
                      self.config[s][entry] = res
                  elif isinstance(res, list):
                      for i in res:
                          if not self.ok_type(i):
                              raise EnvironmentException('Malformed value in cross file variable %s.' % entry)
                      self.config[s][entry] = res
                  else:
                      raise EnvironmentException('Malformed value in cross file variable %s.' % entry)
  
      def has_host(self):
          return 'host_machine' in self.config
  
      def has_target(self):
          return 'target_machine' in self.config
  
      def has_stdlib(self, language):
          return language + '_stdlib' in self.config['properties']
  
      def get_stdlib(self, language):
          return self.config['properties'][language + '_stdlib']
  
      def get_host_system(self):
          "Name of host system like 'linux', or None"
          if self.has_host():
              return self.config['host_machine']['system']
          return None
  
      def get_properties(self):
          return self.config['properties']
  
      def get_root(self):
          return self.get_properties().get('root', None)
  
      def get_sys_root(self):
          return self.get_properties().get('sys_root', None)
  
      # When compiling a cross compiler we use the native compiler for everything.
      # But not when cross compiling a cross compiler.
      def need_cross_compiler(self):
          return 'host_machine' in self.config
  
      def need_exe_wrapper(self):
          value = self.config['properties'].get('needs_exe_wrapper', None)
          if value is not None:
              return value
          # 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 self.has_host() and detect_cpu_family({}) == 'x86_64' and \
             self.config['host_machine']['cpu_family'] == 'x86' and \
             self.config['host_machine']['system'] == detect_system():
              return False
          return True
  
  
  class MachineInfo:
      def __init__(self, system, cpu_family, cpu, endian):
          self.system = system
          self.cpu_family = cpu_family
          self.cpu = cpu
          self.endian = endian
  
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 configparser, os, platform, re, shlex, shutil, subprocess
  
  from . import coredata
  from .linkers import ArLinker, VisualStudioLinker
  from . import mesonlib
  from .mesonlib import EnvironmentException, Popen_safe
  from . import mlog
  
  from . import compilers
  from .compilers import (
      CLANG_OSX,
      CLANG_STANDARD,
      CLANG_WIN,
      GCC_CYGWIN,
      GCC_MINGW,
      GCC_OSX,
      GCC_STANDARD,
      ICC_STANDARD,
      is_assembly,
      is_header,
      is_library,
      is_llvm_ir,
      is_object,
      is_source,
  )
  from .compilers import (
      ArmCCompiler,
      ArmCPPCompiler,
      ArmclangCCompiler,
      ArmclangCPPCompiler,
      ClangCCompiler,
      ClangCPPCompiler,
      ClangObjCCompiler,
      ClangObjCPPCompiler,
      G95FortranCompiler,
      GnuCCompiler,
      GnuCPPCompiler,
      GnuFortranCompiler,
      GnuObjCCompiler,
      GnuObjCPPCompiler,
      ElbrusCCompiler,
      ElbrusCPPCompiler,
      ElbrusFortranCompiler,
      IntelCCompiler,
      IntelCPPCompiler,
      IntelFortranCompiler,
      JavaCompiler,
      MonoCompiler,
      VisualStudioCsCompiler,
      NAGFortranCompiler,
      Open64FortranCompiler,
      PathScaleFortranCompiler,
      PGIFortranCompiler,
      RustCompiler,
      SunFortranCompiler,
      ValaCompiler,
      VisualStudioCCompiler,
      VisualStudioCPPCompiler,
  )
  
  build_filename = 'meson.build'
  
  known_cpu_families = (
      'aarch64',
      'arm',
      'e2k',
      'ia64',
      'mips',
      'mips64',
      'parisc',
      'ppc',
      'ppc64',
      'riscv32',
      'riscv64',
      'sparc',
      'sparc64',
      'x86',
      'x86_64'
  )
  
  def detect_gcovr(version='3.1', 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:
          if log:
              mlog.log('Found gcovr-{} at {}'.format(found, shlex.quote(shutil.which(gcovr_exe))))
          return gcovr_exe, mesonlib.version_compare(found, '>=' + 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='1.5', log=False):
      for n in ['ninja', 'ninja-build']:
          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):
              if log:
                  mlog.log('Found ninja-{} at {}'.format(found, shlex.quote(shutil.which(n))))
              return n
  
  def detect_native_windows_arch():
      """
      The architecture of Windows itself: x86 or amd64
      """
      # 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):
      """
      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 if we're in an MSVC toolchain environment, and if so, return the
         MSVC toolchain architecture as our 'native' architecture.
      2. If not, check environment variables that are set by Windows and WOW64 to
         find out the architecture that Windows is built for, and use that as our
         'native' architecture.
      """
      os_arch = detect_native_windows_arch()
      if os_arch != 'amd64':
          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():
          # Check if we're using and inside an MSVC toolchain environment
          if compiler.id == 'msvc' and 'VCINSTALLDIR' in os.environ:
              if float(compiler.get_toolset_version()) < 10.0:
                  # On MSVC 2008 and earlier, check 'BUILD_PLAT', where
                  # 'Win32' means 'x86'
                  platform = os.environ.get('BUILD_PLAT', 'x86')
                  if platform == 'Win32':
                      return 'x86'
              else:
                  # On MSVC 2010 and later 'Platform' is only set when the
                  # target arch is not 'x86'.  It's 'x64' when targeting
                  # x86_64 and 'arm' when targeting ARM.
                  platform = os.environ.get('Platform', 'x86').lower()
              if platform == 'x86':
                  return platform
          if compiler.id == 'gcc' and compiler.has_builtin_define('__i386__'):
              return 'x86'
      return os_arch
  
  def detect_cpu_family(compilers):
      """
      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)
      else:
          trial = platform.machine().lower()
      if trial.startswith('i') and trial.endswith('86'):
          return 'x86'
      if trial.startswith('arm'):
          return 'arm'
      if trial.startswith('ppc64'):
          return 'ppc64'
      if trial in ('amd64', 'x64'):
          trial = 'x86_64'
      if trial == 'x86_64':
          # On Linux (and maybe others) there can be any mixture of 32/64 bit
          # code in the kernel, Python, system etc. The only reliable way
          # to know is to check the compiler defines.
          for c in compilers.values():
              try:
                  if c.has_builtin_define('__i386__'):
                      return 'x86'
              except mesonlib.MesonException:
                  # Ignore compilers that do not support has_builtin_define.
                  pass
          return 'x86_64'
      # Add fixes here as bugs are reported.
  
      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):
      if mesonlib.is_windows():
          trial = detect_windows_arch(compilers)
      else:
          trial = platform.machine().lower()
      if trial in ('amd64', 'x64'):
          trial = 'x86_64'
      if trial == 'x86_64':
          # Same check as above for cpu_family
          for c in compilers.values():
              try:
                  if c.has_builtin_define('__i386__'):
                      return 'i686' # All 64 bit cpus have at least this level of x86 support.
              except mesonlib.MesonException:
                  pass
          return 'x86_64'
      if trial == 'e2k':
          # Make more precise CPU detection for Elbrus platform.
          trial = platform.processor().lower()
      # Add fixes here as bugs are reported.
      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 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.
      version_regex = '(?<!(\d|\.))(\d{1,2}(\.\d+)+(-[a-zA-Z0-9]+)?)'
      match = re.search(version_regex, text)
      if match:
          return match.group(0)
      return 'unknown version'
  
  class Environment:
      private_dir = 'meson-private'
      log_dir = 'meson-logs'
  
      def __init__(self, source_dir, build_dir, options):
          self.source_dir = source_dir
          self.build_dir = build_dir
          self.scratch_dir = os.path.join(build_dir, Environment.private_dir)
          self.log_dir = os.path.join(build_dir, Environment.log_dir)
          os.makedirs(self.scratch_dir, exist_ok=True)
          os.makedirs(self.log_dir, exist_ok=True)
          try:
              self.coredata = coredata.load(self.get_build_dir())
              self.first_invocation = False
          except FileNotFoundError:
              # WARNING: Don't use any values from coredata in __init__. It gets
              # re-initialized with project options by the interpreter during
              # build file parsing.
              self.coredata = coredata.CoreData(options)
              # Used by the regenchecker script, which runs meson
              self.coredata.meson_command = mesonlib.meson_command
              self.first_invocation = True
          self.cross_info = None
          self.exe_wrapper = None
          if self.coredata.cross_file:
              self.cross_info = CrossBuildInfo(self.coredata.cross_file)
              if 'exe_wrapper' in self.cross_info.config['binaries']:
                  from .dependencies import ExternalProgram
                  self.exe_wrapper = ExternalProgram.from_cross_info(self.cross_info, 'exe_wrapper')
          self.cmd_line_options = options.cmd_line_options.copy()
  
          # List of potential compilers.
          if mesonlib.is_windows():
              self.default_c = ['cl', 'cc', 'gcc', 'clang']
              self.default_cpp = ['cl', 'c++', 'g++', 'clang++']
          else:
              self.default_c = ['cc', 'gcc', 'clang']
              self.default_cpp = ['c++', 'g++', 'clang++']
          if mesonlib.is_windows():
              self.default_cs = ['csc', 'mcs']
          else:
              self.default_cs = ['mcs', 'csc']
          self.default_objc = ['cc']
          self.default_objcpp = ['c++']
          self.default_fortran = ['gfortran', 'g95', 'f95', 'f90', 'f77', 'ifort']
          self.default_rust = ['rustc']
          self.default_static_linker = ['ar']
          self.vs_static_linker = ['lib']
          self.gcc_static_linker = ['gcc-ar']
          self.clang_static_linker = ['llvm-ar']
  
          # Various prefixes and suffixes for import libraries, shared libraries,
          # static libraries, and executables.
          # Versioning is added to these names in the backends as-needed.
          cross = self.is_cross_build()
          if (not cross and mesonlib.is_windows()) \
                  or (cross and self.cross_info.has_host() and self.cross_info.config['host_machine']['system'] == 'windows'):
              self.exe_suffix = 'exe'
              self.object_suffix = 'obj'
              self.win_libdir_layout = True
          elif (not cross and mesonlib.is_cygwin()) \
                  or (cross and self.cross_info.has_host() and self.cross_info.config['host_machine']['system'] == 'cygwin'):
              self.exe_suffix = 'exe'
              self.object_suffix = 'o'
              self.win_libdir_layout = True
          else:
              self.exe_suffix = ''
              self.object_suffix = 'o'
              self.win_libdir_layout = False
          if 'STRIP' in os.environ:
              self.native_strip_bin = shlex.split(os.environ['STRIP'])
          else:
              self.native_strip_bin = ['strip']
  
      def is_cross_build(self):
          return self.cross_info is not None
  
      def dump_coredata(self):
          return coredata.save(self.coredata, self.get_build_dir())
  
      def get_script_dir(self):
          import mesonbuild.scripts
          return os.path.dirname(mesonbuild.scripts.__file__)
  
      def get_log_dir(self):
          return self.log_dir
  
      def get_coredata(self):
          return self.coredata
  
      def get_build_command(self, unbuffered=False):
          cmd = mesonlib.meson_command[:]
          if unbuffered and 'python' in cmd[0]:
              cmd.insert(1, '-u')
          return cmd
  
      def is_header(self, fname):
          return is_header(fname)
  
      def is_source(self, fname):
          return is_source(fname)
  
      def is_assembly(self, fname):
          return is_assembly(fname)
  
      def is_llvm_ir(self, fname):
          return is_llvm_ir(fname)
  
      def is_object(self, fname):
          return is_object(fname)
  
      def is_library(self, fname):
          return is_library(fname)
  
      @staticmethod
      def get_gnu_compiler_defines(compiler):
          """
          Detect GNU compiler platform type (Apple, MinGW, Unix)
          """
          # Arguments to output compiler pre-processor defines to stdout
          # gcc, g++, and gfortran all support these arguments
          args = compiler + ['-E', '-dM', '-']
          p, output, error = Popen_safe(args, write='', stdin=subprocess.PIPE)
          if p.returncode != 0:
              raise EnvironmentException('Unable to detect GNU compiler type:\n' + output + error)
          # Parse several lines of the type:
          # `#define ___SOME_DEF some_value`
          # and extract `___SOME_DEF`
          defines = {}
          for line in output.split('\n'):
              if not line:
                  continue
              d, *rest = line.split(' ', 2)
              if d != '#define':
                  continue
              if len(rest) == 1:
                  defines[rest] = True
              if len(rest) == 2:
                  defines[rest[0]] = rest[1]
          return defines
  
      @staticmethod
      def get_gnu_version_from_defines(defines):
          dot = '.'
          major = defines.get('__GNUC__', '0')
          minor = defines.get('__GNUC_MINOR__', '0')
          patch = defines.get('__GNUC_PATCHLEVEL__', '0')
          return dot.join((major, minor, patch))
  
      @staticmethod
      def get_lcc_version_from_defines(defines):
          dot = '.'
          generation_and_major = defines.get('__LCC__', '100')
          generation = generation_and_major[:1]
          major = generation_and_major[1:]
          minor = defines.get('__LCC_MINOR__', '0')
          return dot.join((generation, major, minor))
  
      @staticmethod
      def get_gnu_compiler_type(defines):
          # Detect GCC type (Apple, MinGW, Cygwin, Unix)
          if '__APPLE__' in defines:
              return GCC_OSX
          elif '__MINGW32__' in defines or '__MINGW64__' in defines:
              return GCC_MINGW
          elif '__CYGWIN__' in defines:
              return GCC_CYGWIN
          return GCC_STANDARD
  
      def warn_about_lang_pointing_to_cross(self, compiler_exe, evar):
          evar_str = os.environ.get(evar, 'WHO_WOULD_CALL_THEIR_COMPILER_WITH_THIS_NAME')
          if evar_str == compiler_exe:
              mlog.warning('''Env var %s seems to point to the cross compiler.
  This is probably wrong, it should always point to the native compiler.''' % evar)
  
      def _get_compilers(self, lang, evar, want_cross):
          '''
          The list of compilers is detected in the exact same way for
          C, C++, ObjC, ObjC++, Fortran, CS so consolidate it here.
          '''
          if self.is_cross_build() and want_cross:
              if lang not in self.cross_info.config['binaries']:
                  raise EnvironmentException('{!r} compiler binary not defined in cross file'.format(lang))
              compilers = mesonlib.stringlistify(self.cross_info.config['binaries'][lang])
              # Ensure ccache exists and remove it if it doesn't
              if compilers[0] == 'ccache':
                  compilers = compilers[1:]
                  ccache = self.detect_ccache()
              else:
                  ccache = []
              self.warn_about_lang_pointing_to_cross(compilers[0], evar)
              # Return value has to be a list of compiler 'choices'
              compilers = [compilers]
              is_cross = True
              exe_wrap = self.get_exe_wrapper()
          elif evar in os.environ:
              compilers = shlex.split(os.environ[evar])
              # Ensure ccache exists and remove it if it doesn't
              if compilers[0] == 'ccache':
                  compilers = compilers[1:]
                  ccache = self.detect_ccache()
              else:
                  ccache = []
              # Return value has to be a list of compiler 'choices'
              compilers = [compilers]
              is_cross = False
              exe_wrap = None
          else:
              compilers = getattr(self, 'default_' + lang)
              ccache = self.detect_ccache()
              is_cross = False
              exe_wrap = None
          return compilers, ccache, is_cross, exe_wrap
  
      def _handle_exceptions(self, exceptions, binaries, bintype='compiler'):
          errmsg = 'Unknown {}(s): {}'.format(bintype, binaries)
          if exceptions:
              errmsg += '\nThe follow exceptions were encountered:'
              for (c, e) in exceptions.items():
                  errmsg += '\nRunning "{0}" gave "{1}"'.format(c, e)
          raise EnvironmentException(errmsg)
  
      def _detect_c_or_cpp_compiler(self, lang, evar, want_cross):
          popen_exceptions = {}
          compilers, ccache, is_cross, exe_wrap = self._get_compilers(lang, evar, want_cross)
          for compiler in compilers:
              if isinstance(compiler, str):
                  compiler = [compiler]
              if 'cl' in compiler or 'cl.exe' in compiler:
                  # Watcom C provides it's own cl.exe clone that mimics an older
                  # version of Microsoft's compiler. Since Watcom's cl.exe is
                  # just a wrapper, we skip using it if we detect its presence
                  # so as not to confuse Meson when configuring for MSVC.
                  #
                  # Additionally the help text of Watcom's cl.exe is paged, and
                  # the binary will not exit without human intervention. In
                  # practice, Meson will block waiting for Watcom's cl.exe to
                  # exit, which requires user input and thus will never exit.
                  if 'WATCOM' in os.environ:
                      def sanitize(p):
                          return os.path.normcase(os.path.abspath(p))
  
                      watcom_cls = [sanitize(os.path.join(os.environ['WATCOM'], 'BINNT', 'cl')),
                                    sanitize(os.path.join(os.environ['WATCOM'], 'BINNT', 'cl.exe'))]
                      found_cl = sanitize(shutil.which('cl'))
                      if found_cl in watcom_cls:
                          continue
                  arg = '/?'
              elif 'armcc' in compiler[0]:
                  arg = '--vsn'
              else:
                  arg = '--version'
              try:
                  p, out, err = Popen_safe(compiler + [arg])
              except OSError as e:
                  popen_exceptions[' '.join(compiler + [arg])] = e
                  continue
              version = search_version(out)
              full_version = out.split('\n', 1)[0]
  
              guess_gcc_or_lcc = False
              if 'Free Software Foundation' in out:
                  guess_gcc_or_lcc = 'gcc'
              if 'e2k' in out and 'lcc' in out:
                  guess_gcc_or_lcc = 'lcc'
  
              if guess_gcc_or_lcc:
                  defines = self.get_gnu_compiler_defines(compiler)
                  if not defines:
                      popen_exceptions[' '.join(compiler)] = 'no pre-processor defines'
                      continue
                  gtype = self.get_gnu_compiler_type(defines)
                  if guess_gcc_or_lcc == 'lcc':
                      version = self.get_lcc_version_from_defines(defines)
                      cls = ElbrusCCompiler if lang == 'c' else ElbrusCPPCompiler
                  else:
                      version = self.get_gnu_version_from_defines(defines)
                      cls = GnuCCompiler if lang == 'c' else GnuCPPCompiler
                  return cls(ccache + compiler, version, gtype, is_cross, exe_wrap, defines, full_version=full_version)
  
              if 'armclang' in out:
                  # The compiler version is not present in the first line of output,
                  # instead it is present in second line, startswith 'Component:'.
                  # So, searching for the 'Component' in out although we know it is
                  # present in second line, as we are not sure about the
                  # output format in future versions
                  arm_ver_str = re.search('.*Component.*', out)
                  if arm_ver_str is None:
                      popen_exceptions[' '.join(compiler)] = 'version string not found'
                      continue
                  arm_ver_str = arm_ver_str.group(0)
                  # Override previous values
                  version = search_version(arm_ver_str)
                  full_version = arm_ver_str
                  cls = ArmclangCCompiler if lang == 'c' else ArmclangCPPCompiler
                  return cls(ccache + compiler, version, is_cross, exe_wrap, full_version=full_version)
              if 'clang' in out:
                  if 'Apple' in out or mesonlib.for_darwin(want_cross, self):
                      cltype = CLANG_OSX
                  elif 'windows' in out or mesonlib.for_windows(want_cross, self):
                      cltype = CLANG_WIN
                  else:
                      cltype = CLANG_STANDARD
                  cls = ClangCCompiler if lang == 'c' else ClangCPPCompiler
                  return cls(ccache + compiler, version, cltype, is_cross, exe_wrap, full_version=full_version)
              if 'Microsoft' in out or 'Microsoft' in err:
                  # Latest versions of Visual Studio print version
                  # number to stderr but earlier ones print version
                  # on stdout.  Why? Lord only knows.
                  # Check both outputs to figure out version.
                  version = search_version(err)
                  if version == 'unknown version':
                      version = search_version(out)
                  if version == 'unknown version':
                      m = 'Failed to detect MSVC compiler arch: stderr was\n{!r}'
                      raise EnvironmentException(m.format(err))
                  is_64 = err.split('\n')[0].endswith(' x64')
                  cls = VisualStudioCCompiler if lang == 'c' else VisualStudioCPPCompiler
                  return cls(compiler, version, is_cross, exe_wrap, is_64)
              if '(ICC)' in out:
                  # TODO: add microsoft add check OSX
                  inteltype = ICC_STANDARD
                  cls = IntelCCompiler if lang == 'c' else IntelCPPCompiler
                  return cls(ccache + compiler, version, inteltype, is_cross, exe_wrap, full_version=full_version)
              if 'ARM' in out:
                  cls = ArmCCompiler if lang == 'c' else ArmCPPCompiler
                  return cls(ccache + compiler, version, is_cross, exe_wrap, full_version=full_version)
          self._handle_exceptions(popen_exceptions, compilers)
  
      def detect_c_compiler(self, want_cross):
          return self._detect_c_or_cpp_compiler('c', 'CC', want_cross)
  
      def detect_cpp_compiler(self, want_cross):
          return self._detect_c_or_cpp_compiler('cpp', 'CXX', want_cross)
  
      def detect_fortran_compiler(self, want_cross):
          popen_exceptions = {}
          compilers, ccache, is_cross, exe_wrap = self._get_compilers('fortran', 'FC', want_cross)
          for compiler in compilers:
              if isinstance(compiler, str):
                  compiler = [compiler]
              for arg in ['--version', '-V']:
                  try:
                      p, out, err = Popen_safe(compiler + [arg])
                  except OSError as e:
                      popen_exceptions[' '.join(compiler + [arg])] = e
                      continue
  
                  version = search_version(out)
                  full_version = out.split('\n', 1)[0]
  
                  guess_gcc_or_lcc = False
                  if 'GNU Fortran' in out:
                      guess_gcc_or_lcc = 'gcc'
                  if 'e2k' in out and 'lcc' in out:
                      guess_gcc_or_lcc = 'lcc'
  
                  if guess_gcc_or_lcc:
                      defines = self.get_gnu_compiler_defines(compiler)
                      if not defines:
                          popen_exceptions[' '.join(compiler)] = 'no pre-processor defines'
                          continue
                      gtype = self.get_gnu_compiler_type(defines)
                      if guess_gcc_or_lcc == 'lcc':
                          version = self.get_lcc_version_from_defines(defines)
                          cls = ElbrusFortranCompiler
                      else:
                          version = self.get_gnu_version_from_defines(defines)
                          cls = GnuFortranCompiler
                      return cls(compiler, version, gtype, is_cross, exe_wrap, defines, full_version=full_version)
  
                  if 'G95' in out:
                      return G95FortranCompiler(compiler, version, is_cross, exe_wrap, full_version=full_version)
  
                  if 'Sun Fortran' in err:
                      version = search_version(err)
                      return SunFortranCompiler(compiler, version, is_cross, exe_wrap, full_version=full_version)
  
                  if 'ifort (IFORT)' in out:
                      return IntelFortranCompiler(compiler, version, is_cross, exe_wrap, full_version=full_version)
  
                  if 'PathScale EKOPath(tm)' in err:
                      return PathScaleFortranCompiler(compiler, version, is_cross, exe_wrap, full_version=full_version)
  
                  if 'PGI Compilers' in out:
                      return PGIFortranCompiler(compiler, version, is_cross, exe_wrap, full_version=full_version)
  
                  if 'Open64 Compiler Suite' in err:
                      return Open64FortranCompiler(compiler, version, is_cross, exe_wrap, full_version=full_version)
  
                  if 'NAG Fortran' in err:
                      return NAGFortranCompiler(compiler, version, is_cross, exe_wrap, full_version=full_version)
          self._handle_exceptions(popen_exceptions, compilers)
  
      def get_scratch_dir(self):
          return self.scratch_dir
  
      def detect_objc_compiler(self, want_cross):
          popen_exceptions = {}
          compilers, ccache, is_cross, exe_wrap = self._get_compilers('objc', 'OBJC', want_cross)
          for compiler in compilers:
              if isinstance(compiler, str):
                  compiler = [compiler]
              arg = ['--version']
              try:
                  p, out, err = Popen_safe(compiler + arg)
              except OSError as e:
                  popen_exceptions[' '.join(compiler + arg)] = e
                  continue
              version = search_version(out)
              if 'Free Software Foundation' in out or ('e2k' in out and 'lcc' in out):
                  defines = self.get_gnu_compiler_defines(compiler)
                  if not defines:
                      popen_exceptions[' '.join(compiler)] = 'no pre-processor defines'
                      continue
                  gtype = self.get_gnu_compiler_type(defines)
                  version = self.get_gnu_version_from_defines(defines)
                  return GnuObjCCompiler(ccache + compiler, version, gtype, is_cross, exe_wrap, defines)
              if out.startswith('Apple LLVM'):
                  return ClangObjCCompiler(ccache + compiler, version, CLANG_OSX, is_cross, exe_wrap)
              if out.startswith('clang'):
                  return ClangObjCCompiler(ccache + compiler, version, CLANG_STANDARD, is_cross, exe_wrap)
          self._handle_exceptions(popen_exceptions, compilers)
  
      def detect_objcpp_compiler(self, want_cross):
          popen_exceptions = {}
          compilers, ccache, is_cross, exe_wrap = self._get_compilers('objcpp', 'OBJCXX', want_cross)
          for compiler in compilers:
              if isinstance(compiler, str):
                  compiler = [compiler]
              arg = ['--version']
              try:
                  p, out, err = Popen_safe(compiler + arg)
              except OSError as e:
                  popen_exceptions[' '.join(compiler + arg)] = e
                  continue
              version = search_version(out)
              if 'Free Software Foundation' in out or ('e2k' in out and 'lcc' in out):
                  defines = self.get_gnu_compiler_defines(compiler)
                  if not defines:
                      popen_exceptions[' '.join(compiler)] = 'no pre-processor defines'
                      continue
                  gtype = self.get_gnu_compiler_type(defines)
                  version = self.get_gnu_version_from_defines(defines)
                  return GnuObjCPPCompiler(ccache + compiler, version, gtype, is_cross, exe_wrap, defines)
              if out.startswith('Apple LLVM'):
                  return ClangObjCPPCompiler(ccache + compiler, version, CLANG_OSX, is_cross, exe_wrap)
              if out.startswith('clang'):
                  return ClangObjCPPCompiler(ccache + compiler, version, CLANG_STANDARD, is_cross, exe_wrap)
          self._handle_exceptions(popen_exceptions, compilers)
  
      def detect_java_compiler(self):
          exelist = ['javac']
          try:
              p, out, err = Popen_safe(exelist + ['-version'])
          except OSError:
              raise EnvironmentException('Could not execute Java compiler "%s"' % ' '.join(exelist))
          version = search_version(err)
          if 'javac' in out or 'javac' in err:
              return JavaCompiler(exelist, version)
          raise EnvironmentException('Unknown compiler "' + ' '.join(exelist) + '"')
  
      def detect_cs_compiler(self):
          compilers, ccache, is_cross, exe_wrap = self._get_compilers('cs', 'CSC', False)
          popen_exceptions = {}
          for comp in compilers:
              if not isinstance(comp, list):
                  comp = [comp]
              try:
                  p, out, err = Popen_safe(comp + ['--version'])
              except OSError as e:
                  popen_exceptions[' '.join(comp + ['--version'])] = e
                  continue
  
              version = search_version(out)
              if 'Mono' in out:
                  return MonoCompiler(comp, version)
              elif "Visual C#" in out:
                  return VisualStudioCsCompiler(comp, version)
  
          self._handle_exceptions(popen_exceptions, compilers)
  
      def detect_vala_compiler(self):
          if 'VALAC' in os.environ:
              exelist = shlex.split(os.environ['VALAC'])
          else:
              exelist = ['valac']
          try:
              p, out = Popen_safe(exelist + ['--version'])[0:2]
          except OSError:
              raise EnvironmentException('Could not execute Vala compiler "%s"' % ' '.join(exelist))
          version = search_version(out)
          if 'Vala' in out:
              return ValaCompiler(exelist, version)
          raise EnvironmentException('Unknown compiler "' + ' '.join(exelist) + '"')
  
      def detect_rust_compiler(self, want_cross):
          popen_exceptions = {}
          compilers, ccache, is_cross, exe_wrap = self._get_compilers('rust', 'RUSTC', want_cross)
          for compiler in compilers:
              if isinstance(compiler, str):
                  compiler = [compiler]
              arg = ['--version']
              try:
                  p, out = Popen_safe(compiler + arg)[0:2]
              except OSError as e:
                  popen_exceptions[' '.join(compiler + arg)] = e
                  continue
  
              version = search_version(out)
  
              if 'rustc' in out:
                  return RustCompiler(compiler, version, is_cross, exe_wrap)
  
          self._handle_exceptions(popen_exceptions, compilers)
  
      def detect_d_compiler(self, want_cross):
          is_cross = False
          # Search for a D compiler.
          # We prefer LDC over GDC unless overridden with the DC
          # environment variable because LDC has a much more
          # up to date language version at time (2016).
          if 'DC' in os.environ:
              exelist = shlex.split(os.environ['DC'])
          elif self.is_cross_build() and want_cross:
              exelist = mesonlib.stringlistify(self.cross_info.config['binaries']['d'])
              is_cross = True
          elif shutil.which("ldc2"):
              exelist = ['ldc2']
          elif shutil.which("ldc"):
              exelist = ['ldc']
          elif shutil.which("gdc"):
              exelist = ['gdc']
          elif shutil.which("dmd"):
              exelist = ['dmd']
          else:
              raise EnvironmentException('Could not find any supported D compiler.')
  
          try:
              p, out = Popen_safe(exelist + ['--version'])[0:2]
          except OSError:
              raise EnvironmentException('Could not execute D compiler "%s"' % ' '.join(exelist))
          version = search_version(out)
          full_version = out.split('\n', 1)[0]
          if 'LLVM D compiler' in out:
              return compilers.LLVMDCompiler(exelist, version, is_cross, full_version=full_version)
          elif 'gdc' in out:
              return compilers.GnuDCompiler(exelist, version, is_cross, full_version=full_version)
          elif 'The D Language Foundation' in out or 'Digital Mars' in out:
              return compilers.DmdDCompiler(exelist, version, is_cross, full_version=full_version)
          raise EnvironmentException('Unknown compiler "' + ' '.join(exelist) + '"')
  
      def detect_swift_compiler(self):
          exelist = ['swiftc']
          try:
              p, _, err = Popen_safe(exelist + ['-v'])
          except OSError:
              raise EnvironmentException('Could not execute Swift compiler "%s"' % ' '.join(exelist))
          version = search_version(err)
          if 'Swift' in err:
              return compilers.SwiftCompiler(exelist, version)
          raise EnvironmentException('Unknown compiler "' + ' '.join(exelist) + '"')
  
      def detect_static_linker(self, compiler):
          if compiler.is_cross:
              linker = self.cross_info.config['binaries']['ar']
              if isinstance(linker, str):
                  linker = [linker]
              linkers = [linker]
          else:
              evar = 'AR'
              if evar in os.environ:
                  linkers = [shlex.split(os.environ[evar])]
              elif isinstance(compiler, compilers.VisualStudioCCompiler):
                  linkers = [self.vs_static_linker]
              elif isinstance(compiler, compilers.GnuCompiler):
                  # Use gcc-ar if available; needed for LTO
                  linkers = [self.gcc_static_linker, self.default_static_linker]
              elif isinstance(compiler, compilers.ClangCompiler):
                  # Use llvm-ar if available; needed for LTO
                  linkers = [self.clang_static_linker, self.default_static_linker]
              else:
                  linkers = [self.default_static_linker]
          popen_exceptions = {}
          for linker in linkers:
              if 'lib' in linker or 'lib.exe' in linker:
                  arg = '/?'
              else:
                  arg = '--version'
              try:
                  p, out, err = Popen_safe(linker + [arg])
              except OSError as e:
                  popen_exceptions[' '.join(linker + [arg])] = e
                  continue
              if '/OUT:' in out or '/OUT:' in err:
                  return VisualStudioLinker(linker)
              if p.returncode == 0:
                  return ArLinker(linker)
              if p.returncode == 1 and err.startswith('usage'): # OSX
                  return ArLinker(linker)
          self._handle_exceptions(popen_exceptions, linkers, 'linker')
          raise EnvironmentException('Unknown static linker "%s"' % ' '.join(linkers))
  
      def detect_ccache(self):
          try:
              has_ccache = subprocess.call(['ccache', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
          except OSError:
              has_ccache = 1
          if has_ccache == 0:
              cmdlist = ['ccache']
          else:
              cmdlist = []
          return cmdlist
  
      def get_source_dir(self):
          return self.source_dir
  
      def get_build_dir(self):
          return self.build_dir
  
      def get_exe_suffix(self):
          return self.exe_suffix
  
      def get_import_lib_dir(self):
          "Install dir for the import library (library used for linking)"
          return self.get_libdir()
  
      def get_shared_module_dir(self):
          "Install dir for shared modules that are loaded at runtime"
          return self.get_libdir()
  
      def get_shared_lib_dir(self):
          "Install dir for the shared library"
          if self.win_libdir_layout:
              return self.get_bindir()
          return self.get_libdir()
  
      def get_static_lib_dir(self):
          "Install dir for the static library"
          return self.get_libdir()
  
      def get_object_suffix(self):
          return self.object_suffix
  
      def get_prefix(self):
          return self.coredata.get_builtin_option('prefix')
  
      def get_libdir(self):
          return self.coredata.get_builtin_option('libdir')
  
      def get_libexecdir(self):
          return self.coredata.get_builtin_option('libexecdir')
  
      def get_bindir(self):
          return self.coredata.get_builtin_option('bindir')
  
      def get_includedir(self):
          return self.coredata.get_builtin_option('includedir')
  
      def get_mandir(self):
          return self.coredata.get_builtin_option('mandir')
  
      def get_datadir(self):
          return self.coredata.get_builtin_option('datadir')
  
      def get_compiler_system_dirs(self):
          for comp in self.coredata.compilers.values():
              if isinstance(comp, compilers.ClangCompiler):
                  index = 1
                  break
              elif isinstance(comp, compilers.GnuCompiler):
                  index = 2
                  break
          else:
              # This option is only supported by gcc and clang. If we don't get a
              # GCC or Clang compiler return and empty list.
              return []
  
          p, out, _ = Popen_safe(comp.get_exelist() + ['-print-search-dirs'])
          if p.returncode != 0:
              raise mesonlib.MesonException('Could not calculate system search dirs')
          out = out.split('\n')[index].lstrip('libraries: =').split(':')
          return [os.path.normpath(p) for p in out]
  
      def get_exe_wrapper(self):
          if not self.cross_info.need_exe_wrapper():
              from .dependencies import EmptyExternalProgram
              return EmptyExternalProgram()
          return self.exe_wrapper
  
  
  class CrossBuildInfo:
      def __init__(self, filename):
          self.config = {'properties': {}}
          self.parse_datafile(filename)
          if 'target_machine' in self.config:
              return
          if 'host_machine' not in self.config:
              raise mesonlib.MesonException('Cross info file must have either host or a target machine.')
          if 'binaries' not in self.config:
              raise mesonlib.MesonException('Cross file is missing "binaries".')
  
      def ok_type(self, i):
          return isinstance(i, (str, int, bool))
  
      def parse_datafile(self, filename):
          config = configparser.ConfigParser()
          try:
              with open(filename, 'r') as f:
                  config.read_file(f, filename)
          except FileNotFoundError:
              raise EnvironmentException('File not found: %s.' % filename)
          # This is a bit hackish at the moment.
          for s in config.sections():
              self.config[s] = {}
              for entry in config[s]:
                  value = config[s][entry]
                  if ' ' in entry or '\t' in entry or "'" in entry or '"' in entry:
                      raise EnvironmentException('Malformed variable name %s in cross file..' % entry)
                  try:
                      res = eval(value, {'__builtins__': None}, {'true': True, 'false': False})
                  except Exception:
                      raise EnvironmentException('Malformed value in cross file variable %s.' % entry)
  
                  if entry == 'cpu_family' and res not in known_cpu_families:
                      mlog.warning('Unknown CPU family %s, please report this at https://github.com/mesonbuild/meson/issues/new' % value)
  
                  if self.ok_type(res):
                      self.config[s][entry] = res
                  elif isinstance(res, list):
                      for i in res:
                          if not self.ok_type(i):
                              raise EnvironmentException('Malformed value in cross file variable %s.' % entry)
                      self.config[s][entry] = res
                  else:
                      raise EnvironmentException('Malformed value in cross file variable %s.' % entry)
  
      def has_host(self):
          return 'host_machine' in self.config
  
      def has_target(self):
          return 'target_machine' in self.config
  
      def has_stdlib(self, language):
          return language + '_stdlib' in self.config['properties']
  
      def get_stdlib(self, language):
          return self.config['properties'][language + '_stdlib']
  
      def get_properties(self):
          return self.config['properties']
  
      def get_root(self):
          return self.get_properties().get('root', None)
  
      def get_sys_root(self):
          return self.get_properties().get('sys_root', None)
  
      # When compiling a cross compiler we use the native compiler for everything.
      # But not when cross compiling a cross compiler.
      def need_cross_compiler(self):
          return 'host_machine' in self.config
  
      def need_exe_wrapper(self):
          value = self.config['properties'].get('needs_exe_wrapper', None)
          if value is not None:
              return value
          # 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 self.has_host() and detect_cpu_family({}) == 'x86_64' and \
             self.config['host_machine']['cpu_family'] == 'x86' and \
             self.config['host_machine']['system'] == detect_system():
              return False
          return True
  
  
  class MachineInfo:
      def __init__(self, system, cpu_family, cpu, endian):
          self.system = system
          self.cpu_family = cpu_family
          self.cpu = cpu
          self.endian = endian
  
files: mesonbuild/environment.py
files: # Copyright 2012-2015 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.
  
  """A library of random helper functionality."""
  
  import sys
  import stat
  import time
  import platform, subprocess, operator, os, shutil, re
  import collections
  from mesonbuild import mlog
  
  have_fcntl = False
  have_msvcrt = False
  # {subproject: project_meson_version}
  project_meson_versions = {}
  
  try:
      import fcntl
      have_fcntl = True
  except Exception:
      pass
  
  try:
      import msvcrt
      have_msvcrt = True
  except Exception:
      pass
  
  from glob import glob
  
  if os.path.basename(sys.executable) == 'meson.exe':
      # In Windows and using the MSI installed executable.
      python_command = [sys.executable, 'runpython']
  else:
      python_command = [sys.executable]
  meson_command = None
  
  def is_ascii_string(astring):
      try:
          if isinstance(astring, str):
              astring.encode('ascii')
          if isinstance(astring, bytes):
              astring.decode('ascii')
      except UnicodeDecodeError:
          return False
      return True
  
  def check_direntry_issues(direntry_array):
      import locale
      # Warn if the locale is not UTF-8. This can cause various unfixable issues
      # such as os.stat not being able to decode filenames with unicode in them.
      # There is no way to reset both the preferred encoding and the filesystem
      # encoding, so we can just warn about it.
      e = locale.getpreferredencoding()
      if e.upper() != 'UTF-8' and not is_windows():
          if not isinstance(direntry_array, list):
              direntry_array = [direntry_array]
          for de in direntry_array:
              if is_ascii_string(de):
                  continue
              mlog.warning('''You are using {!r} which is not a Unicode-compatible '
  locale but you are trying to access a file system entry called {!r} which is
  not pure ASCII. This may cause problems.
  '''.format(e, de), file=sys.stderr)
  
  # Put this in objects that should not get dumped to pickle files
  # by accident.
  import threading
  an_unpicklable_object = threading.Lock()
  
  class MesonException(Exception):
      '''Exceptions thrown by Meson'''
  
      def get_msg_with_context(self):
          s = ''
          if hasattr(self, 'lineno') and hasattr(self, 'file'):
              s = get_error_location_string(self.file, self.lineno) + ' '
          s += str(self)
          return s
  
  class EnvironmentException(MesonException):
      '''Exceptions thrown while processing and creating the build environment'''
  
  class FileMode:
      # The first triad is for owner permissions, the second for group permissions,
      # and the third for others (everyone else).
      # For the 1st character:
      #  'r' means can read
      #  '-' means not allowed
      # For the 2nd character:
      #  'w' means can write
      #  '-' means not allowed
      # For the 3rd character:
      #  'x' means can execute
      #  's' means can execute and setuid/setgid is set (owner/group triads only)
      #  'S' means cannot execute and setuid/setgid is set (owner/group triads only)
      #  't' means can execute and sticky bit is set ("others" triads only)
      #  'T' means cannot execute and sticky bit is set ("others" triads only)
      #  '-' means none of these are allowed
      #
      # The meanings of 'rwx' perms is not obvious for directories; see:
      # https://www.hackinglinuxexposed.com/articles/20030424.html
      #
      # For information on this notation such as setuid/setgid/sticky bits, see:
      # https://en.wikipedia.org/wiki/File_system_permissions#Symbolic_notation
      symbolic_perms_regex = re.compile('[r-][w-][xsS-]' # Owner perms
                                        '[r-][w-][xsS-]' # Group perms
                                        '[r-][w-][xtT-]') # Others perms
  
      def __init__(self, perms=None, owner=None, group=None):
          self.perms_s = perms
          self.perms = self.perms_s_to_bits(perms)
          self.owner = owner
          self.group = group
  
      def __repr__(self):
          ret = '<FileMode: {!r} owner={} group={}'
          return ret.format(self.perms_s, self.owner, self.group)
  
      @classmethod
      def perms_s_to_bits(cls, perms_s):
          '''
          Does the opposite of stat.filemode(), converts strings of the form
          'rwxr-xr-x' to st_mode enums which can be passed to os.chmod()
          '''
          if perms_s is None:
              # No perms specified, we will not touch the permissions
              return -1
          eg = 'rwxr-xr-x'
          if not isinstance(perms_s, str):
              msg = 'Install perms must be a string. For example, {!r}'
              raise MesonException(msg.format(eg))
          if len(perms_s) != 9 or not cls.symbolic_perms_regex.match(perms_s):
              msg = 'File perms {!r} must be exactly 9 chars. For example, {!r}'
              raise MesonException(msg.format(perms_s, eg))
          perms = 0
          # Owner perms
          if perms_s[0] == 'r':
              perms |= stat.S_IRUSR
          if perms_s[1] == 'w':
              perms |= stat.S_IWUSR
          if perms_s[2] == 'x':
              perms |= stat.S_IXUSR
          elif perms_s[2] == 'S':
              perms |= stat.S_ISUID
          elif perms_s[2] == 's':
              perms |= stat.S_IXUSR
              perms |= stat.S_ISUID
          # Group perms
          if perms_s[3] == 'r':
              perms |= stat.S_IRGRP
          if perms_s[4] == 'w':
              perms |= stat.S_IWGRP
          if perms_s[5] == 'x':
              perms |= stat.S_IXGRP
          elif perms_s[5] == 'S':
              perms |= stat.S_ISGID
          elif perms_s[5] == 's':
              perms |= stat.S_IXGRP
              perms |= stat.S_ISGID
          # Others perms
          if perms_s[6] == 'r':
              perms |= stat.S_IROTH
          if perms_s[7] == 'w':
              perms |= stat.S_IWOTH
          if perms_s[8] == 'x':
              perms |= stat.S_IXOTH
          elif perms_s[8] == 'T':
              perms |= stat.S_ISVTX
          elif perms_s[8] == 't':
              perms |= stat.S_IXOTH
              perms |= stat.S_ISVTX
          return perms
  
  class File:
      def __init__(self, is_built, subdir, fname):
          self.is_built = is_built
          self.subdir = subdir
          self.fname = fname
          assert(isinstance(self.subdir, str))
          assert(isinstance(self.fname, str))
  
      def __str__(self):
          return self.relative_name()
  
      def __repr__(self):
          ret = '<File: {0}'
          if not self.is_built:
              ret += ' (not built)'
          ret += '>'
          return ret.format(self.relative_name())
  
      @staticmethod
      def from_source_file(source_root, subdir, fname):
          if not os.path.isfile(os.path.join(source_root, subdir, fname)):
              raise MesonException('File %s does not exist.' % fname)
          return File(False, subdir, fname)
  
      @staticmethod
      def from_built_file(subdir, fname):
          return File(True, subdir, fname)
  
      @staticmethod
      def from_absolute_file(fname):
          return File(False, '', fname)
  
      def rel_to_builddir(self, build_to_src):
          if self.is_built:
              return self.relative_name()
          else:
              return os.path.join(build_to_src, self.subdir, self.fname)
  
      def absolute_path(self, srcdir, builddir):
          absdir = srcdir
          if self.is_built:
              absdir = builddir
          return os.path.join(absdir, self.relative_name())
  
      def endswith(self, ending):
          return self.fname.endswith(ending)
  
      def split(self, s):
          return self.fname.split(s)
  
      def __eq__(self, other):
          return (self.fname, self.subdir, self.is_built) == (other.fname, other.subdir, other.is_built)
  
      def __hash__(self):
          return hash((self.fname, self.subdir, self.is_built))
  
      def relative_name(self):
          return os.path.join(self.subdir, self.fname)
  
  def get_compiler_for_source(compilers, src):
      for comp in compilers:
          if comp.can_compile(src):
              return comp
      raise RuntimeError('No specified compiler can handle file {!s}'.format(src))
  
  def classify_unity_sources(compilers, sources):
      compsrclist = {}
      for src in sources:
          comp = get_compiler_for_source(compilers, src)
          if comp not in compsrclist:
              compsrclist[comp] = [src]
          else:
              compsrclist[comp].append(src)
      return compsrclist
  
  def is_osx():
      return platform.system().lower() == 'darwin'
  
  def is_linux():
      return platform.system().lower() == 'linux'
  
  def is_android():
      return platform.system().lower() == 'android'
  
  def is_haiku():
      return platform.system().lower() == 'haiku'
  
  def is_openbsd():
      return platform.system().lower() == 'openbsd'
  
  def is_windows():
      platname = platform.system().lower()
      return platname == 'windows' or 'mingw' in platname
  
  def is_cygwin():
      platname = platform.system().lower()
      return platname.startswith('cygwin')
  
  def is_debianlike():
      return os.path.isfile('/etc/debian_version')
  
  def is_dragonflybsd():
      return platform.system().lower() == 'dragonfly'
  
  def is_freebsd():
      return platform.system().lower() == 'freebsd'
  
  def for_windows(is_cross, env):
      """
      Host machine is windows?
  
      Note: 'host' is the machine on which compiled binaries will run
      """
      if not is_cross:
          return is_windows()
      return env.cross_info.get_host_system() == 'windows'
  
  def for_cygwin(is_cross, env):
      """
      Host machine is cygwin?
  
      Note: 'host' is the machine on which compiled binaries will run
      """
      if not is_cross:
          return is_cygwin()
      return env.cross_info.get_host_system() == 'cygwin'
  
  def for_linux(is_cross, env):
      """
      Host machine is linux?
  
      Note: 'host' is the machine on which compiled binaries will run
      """
      if not is_cross:
          return is_linux()
      return env.cross_info.get_host_system() == 'linux'
  
  def for_darwin(is_cross, env):
      """
      Host machine is Darwin (iOS/OS X)?
  
      Note: 'host' is the machine on which compiled binaries will run
      """
      if not is_cross:
          return is_osx()
      return env.cross_info.get_host_system() in ('darwin', 'ios')
  
  def for_android(is_cross, env):
      """
      Host machine is Android?
  
      Note: 'host' is the machine on which compiled binaries will run
      """
      if not is_cross:
          return is_android()
      return env.cross_info.get_host_system() == 'android'
  
  def for_haiku(is_cross, env):
      """
      Host machine is Haiku?
  
      Note: 'host' is the machine on which compiled binaries will run
      """
      if not is_cross:
          return is_haiku()
      return env.cross_info.get_host_system() == 'haiku'
  
  def for_openbsd(is_cross, env):
      """
      Host machine is OpenBSD?
  
      Note: 'host' is the machine on which compiled binaries will run
      """
      if not is_cross:
          return is_openbsd()
      elif env.cross_info.has_host():
          return env.cross_info.config['host_machine']['system'] == 'openbsd'
      return False
  
  def exe_exists(arglist):
      try:
          p = subprocess.Popen(arglist, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
          p.communicate()
          if p.returncode == 0:
              return True
      except FileNotFoundError:
          pass
      return False
  
  def detect_vcs(source_dir):
      vcs_systems = [
          dict(name = 'git',        cmd = 'git', repo_dir = '.git', get_rev = 'git describe --dirty=+', rev_regex = '(.*)', dep = '.git/logs/HEAD'),
          dict(name = 'mercurial',  cmd = 'hg',  repo_dir = '.hg',  get_rev = 'hg id -i',               rev_regex = '(.*)', dep = '.hg/dirstate'),
          dict(name = 'subversion', cmd = 'svn', repo_dir = '.svn', get_rev = 'svn info',               rev_regex = 'Revision: (.*)', dep = '.svn/wc.db'),
          dict(name = 'bazaar',     cmd = 'bzr', repo_dir = '.bzr', get_rev = 'bzr revno',              rev_regex = '(.*)', dep = '.bzr'),
      ]
  
      segs = source_dir.replace('\\', '/').split('/')
      for i in range(len(segs), -1, -1):
          curdir = '/'.join(segs[:i])
          for vcs in vcs_systems:
              if os.path.isdir(os.path.join(curdir, vcs['repo_dir'])) and shutil.which(vcs['cmd']):
                  vcs['wc_dir'] = curdir
                  return vcs
      return None
  
  def grab_leading_numbers(vstr, strict=False):
      result = []
      for x in vstr.rstrip('.').split('.'):
          try:
              result.append(int(x))
          except ValueError as e:
              if strict:
                  msg = 'Invalid version to compare against: {!r}; only ' \
                        'numeric digits separated by "." are allowed: ' + str(e)
                  raise MesonException(msg.format(vstr))
              break
      return result
  
  def make_same_len(listA, listB):
      maxlen = max(len(listA), len(listB))
      for i in listA, listB:
          for n in range(len(i), maxlen):
              i.append(0)
  
  numpart = re.compile('[0-9.]+')
  
  def version_compare(vstr1, vstr2, strict=False):
      match = numpart.match(vstr1.strip())
      if match is None:
          msg = 'Uncomparable version string {!r}.'
          raise MesonException(msg.format(vstr1))
      vstr1 = match.group(0)
      if vstr2.startswith('>='):
          cmpop = operator.ge
          vstr2 = vstr2[2:]
      elif vstr2.startswith('<='):
          cmpop = operator.le
          vstr2 = vstr2[2:]
      elif vstr2.startswith('!='):
          cmpop = operator.ne
          vstr2 = vstr2[2:]
      elif vstr2.startswith('=='):
          cmpop = operator.eq
          vstr2 = vstr2[2:]
      elif vstr2.startswith('='):
          cmpop = operator.eq
          vstr2 = vstr2[1:]
      elif vstr2.startswith('>'):
          cmpop = operator.gt
          vstr2 = vstr2[1:]
      elif vstr2.startswith('<'):
          cmpop = operator.lt
          vstr2 = vstr2[1:]
      else:
          cmpop = operator.eq
      varr1 = grab_leading_numbers(vstr1, strict)
      varr2 = grab_leading_numbers(vstr2, strict)
      make_same_len(varr1, varr2)
      return cmpop(varr1, varr2)
  
  def version_compare_many(vstr1, conditions):
      if not isinstance(conditions, (list, tuple, frozenset)):
          conditions = [conditions]
      found = []
      not_found = []
      for req in conditions:
          if not version_compare(vstr1, req, strict=True):
              not_found.append(req)
          else:
              found.append(req)
      return not_found == [], not_found, found
  
  
  def version_compare_condition_with_min(condition, minimum):
      match = numpart.match(minimum.strip())
      if match is None:
          msg = 'Uncomparable version string {!r}.'
          raise MesonException(msg.format(minimum))
      minimum = match.group(0)
      if condition.startswith('>='):
          cmpop = operator.le
          condition = condition[2:]
      elif condition.startswith('<='):
          return True
          condition = condition[2:]
      elif condition.startswith('!='):
          return True
          condition = condition[2:]
      elif condition.startswith('=='):
          cmpop = operator.le
          condition = condition[2:]
      elif condition.startswith('='):
          cmpop = operator.le
          condition = condition[1:]
      elif condition.startswith('>'):
          cmpop = operator.lt
          condition = condition[1:]
      elif condition.startswith('<'):
          return True
          condition = condition[2:]
      else:
          cmpop = operator.le
      varr1 = grab_leading_numbers(minimum, True)
      varr2 = grab_leading_numbers(condition, True)
      make_same_len(varr1, varr2)
      return cmpop(varr1, varr2)
  
  def version_compare_condition_with_max(condition, maximum):
      match = numpart.match(maximum.strip())
      if match is None:
          msg = 'Uncomparable version string {!r}.'
          raise MesonException(msg.format(maximum))
      maximum = match.group(0)
      if condition.startswith('>='):
          return False
          condition = condition[2:]
      elif condition.startswith('<='):
          cmpop = operator.ge
          condition = condition[2:]
      elif condition.startswith('!='):
          return False
          condition = condition[2:]
      elif condition.startswith('=='):
          cmpop = operator.ge
          condition = condition[2:]
      elif condition.startswith('='):
          cmpop = operator.ge
          condition = condition[1:]
      elif condition.startswith('>'):
          return False
          condition = condition[1:]
      elif condition.startswith('<'):
          cmpop = operator.gt
          condition = condition[2:]
      else:
          cmpop = operator.ge
      varr1 = grab_leading_numbers(maximum, True)
      varr2 = grab_leading_numbers(condition, True)
      make_same_len(varr1, varr2)
      return cmpop(varr1, varr2)
  
  
  def default_libdir():
      if is_debianlike():
          try:
              pc = subprocess.Popen(['dpkg-architecture', '-qDEB_HOST_MULTIARCH'],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.DEVNULL)
              (stdo, _) = pc.communicate()
              if pc.returncode == 0:
                  archpath = stdo.decode().strip()
                  return 'lib/' + archpath
          except Exception:
              pass
      if os.path.isdir('/usr/lib64') and not os.path.islink('/usr/lib64'):
          return 'lib64'
      return 'lib'
  
  def default_libexecdir():
      # There is no way to auto-detect this, so it must be set at build time
      return 'libexec'
  
  def default_prefix():
      return 'c:/' if is_windows() else '/usr/local'
  
  def get_library_dirs():
      if is_windows():
          return ['C:/mingw/lib'] # Fixme
      if is_osx():
          return ['/usr/lib'] # Fix me as well.
      # The following is probably Debian/Ubuntu specific.
      # /usr/local/lib is first because it contains stuff
      # installed by the sysadmin and is probably more up-to-date
      # than /usr/lib. If you feel that this search order is
      # problematic, please raise the issue on the mailing list.
      unixdirs = ['/usr/local/lib', '/usr/lib', '/lib']
      plat = subprocess.check_output(['uname', '-m']).decode().strip()
      # This is a terrible hack. I admit it and I'm really sorry.
      # I just don't know what the correct solution is.
      if plat == 'i686':
          plat = 'i386'
      if plat.startswith('arm'):
          plat = 'arm'
      unixdirs += glob('/usr/lib/' + plat + '*')
      if os.path.exists('/usr/lib64'):
          unixdirs.append('/usr/lib64')
      unixdirs += glob('/lib/' + plat + '*')
      if os.path.exists('/lib64'):
          unixdirs.append('/lib64')
      unixdirs += glob('/lib/' + plat + '*')
      return unixdirs
  
  def has_path_sep(name, sep='/\\'):
      'Checks if any of the specified @sep path separators are in @name'
      for each in sep:
          if each in name:
              return True
      return False
  
  def do_replacement(regex, line, format, confdata):
      missing_variables = set()
      start_tag = '@'
      backslash_tag = '\\@'
      if format == 'cmake':
          start_tag = '${'
          backslash_tag = '\\${'
  
      def variable_replace(match):
          # Pairs of escape characters before '@' or '\@'
          if match.group(0).endswith('\\'):
              num_escapes = match.end(0) - match.start(0)
              return '\\' * (num_escapes // 2)
          # Single escape character and '@'
          elif match.group(0) == backslash_tag:
              return start_tag
          # Template variable to be replaced
          else:
              varname = match.group(1)
              if varname in confdata:
                  (var, desc) = confdata.get(varname)
                  if isinstance(var, str):
                      pass
                  elif isinstance(var, int):
                      var = str(var)
                  else:
                      msg = 'Tried to replace variable {!r} value with ' \
                            'something other than a string or int: {!r}'
                      raise MesonException(msg.format(varname, var))
              else:
                  missing_variables.add(varname)
                  var = ''
              return var
      return re.sub(regex, variable_replace, line), missing_variables
  
  def do_mesondefine(line, confdata):
      arr = line.split()
      if len(arr) != 2:
          raise MesonException('#mesondefine does not contain exactly two tokens: %s' % line.strip())
      varname = arr[1]
      try:
          (v, desc) = confdata.get(varname)
      except KeyError:
          return '/* #undef %s */\n' % varname
      if isinstance(v, bool):
          if v:
              return '#define %s\n' % varname
          else:
              return '#undef %s\n' % varname
      elif isinstance(v, int):
          return '#define %s %d\n' % (varname, v)
      elif isinstance(v, str):
          return '#define %s %s\n' % (varname, v)
      else:
          raise MesonException('#mesondefine argument "%s" is of unknown type.' % varname)
  
  
  def do_conf_file(src, dst, confdata, format, encoding='utf-8'):
      try:
          with open(src, encoding=encoding) as f:
              data = f.readlines()
      except Exception as e:
          raise MesonException('Could not read input file %s: %s' % (src, str(e)))
      # Only allow (a-z, A-Z, 0-9, _, -) as valid characters for a define
      # Also allow escaping '@' with '\@'
      if format in ['meson', 'cmake@']:
          regex = re.compile(r'(?:\\\\)+(?=\\?@)|\\@|@([-a-zA-Z0-9_]+)@')
      elif format == 'cmake':
          regex = re.compile(r'(?:\\\\)+(?=\\?\$)|\\\${|\${([-a-zA-Z0-9_]+)}')
      else:
          raise MesonException('Format "{}" not handled'.format(format))
  
      search_token = '#mesondefine'
      if format != 'meson':
          search_token = '#cmakedefine'
  
      result = []
      missing_variables = set()
      # Detect when the configuration data is empty and no tokens were found
      # during substitution so we can warn the user to use the `copy:` kwarg.
      confdata_useless = not confdata.keys()
      for line in data:
          if line.startswith(search_token):
              confdata_useless = False
              line = do_mesondefine(line, confdata)
          else:
              line, missing = do_replacement(regex, line, format, confdata)
              missing_variables.update(missing)
              if missing:
                  confdata_useless = False
          result.append(line)
      dst_tmp = dst + '~'
      try:
          with open(dst_tmp, 'w', encoding=encoding) as f:
              f.writelines(result)
      except Exception as e:
          raise MesonException('Could not write output file %s: %s' % (dst, str(e)))
      shutil.copymode(src, dst_tmp)
      replace_if_different(dst, dst_tmp)
      return missing_variables, confdata_useless
  
  CONF_C_PRELUDE = '''/*
   * Autogenerated by the Meson build system.
   * Do not edit, your changes will be lost.
   */
  
  #pragma once
  
  '''
  
  CONF_NASM_PRELUDE = '''; Autogenerated by the Meson build system.
  ; Do not edit, your changes will be lost.
  
  '''
  
  def dump_conf_header(ofilename, cdata, output_format):
      if output_format == 'c':
          prelude = CONF_C_PRELUDE
          prefix = '#'
      elif output_format == 'nasm':
          prelude = CONF_NASM_PRELUDE
          prefix = '%'
  
      ofilename_tmp = ofilename + '~'
      with open(ofilename_tmp, 'w', encoding='utf-8') as ofile:
          ofile.write(prelude)
          for k in sorted(cdata.keys()):
              (v, desc) = cdata.get(k)
              if desc:
                  if output_format == 'c':
                      ofile.write('/* %s */\n' % desc)
                  elif output_format == 'nasm':
                      for line in desc.split('\n'):
                          ofile.write('; %s\n' % line)
              if isinstance(v, bool):
                  if v:
                      ofile.write('%sdefine %s\n\n' % (prefix, k))
                  else:
                      ofile.write('%sundef %s\n\n' % (prefix, k))
              elif isinstance(v, (int, str)):
                  ofile.write('%sdefine %s %s\n\n' % (prefix, k, v))
              else:
                  raise MesonException('Unknown data type in configuration file entry: ' + k)
      replace_if_different(ofilename, ofilename_tmp)
  
  def replace_if_different(dst, dst_tmp):
      # If contents are identical, don't touch the file to prevent
      # unnecessary rebuilds.
      different = True
      try:
          with open(dst, 'rb') as f1, open(dst_tmp, 'rb') as f2:
              if f1.read() == f2.read():
                  different = False
      except FileNotFoundError:
          pass
      if different:
          os.replace(dst_tmp, dst)
      else:
          os.unlink(dst_tmp)
  
  def listify(item, flatten=True, unholder=False):
      '''
      Returns a list with all args embedded in a list if they are not a list.
      This function preserves order.
      @flatten: Convert lists of lists to a flat list
      @unholder: Replace each item with the object it holds, if required
  
      Note: unholding only works recursively when flattening
      '''
      if not isinstance(item, list):
          if unholder and hasattr(item, 'held_object'):
              item = item.held_object
          return [item]
      result = []
      for i in item:
          if unholder and hasattr(i, 'held_object'):
              i = i.held_object
          if flatten and isinstance(i, list):
              result += listify(i, flatten=True, unholder=unholder)
          else:
              result.append(i)
      return result
  
  
  def extract_as_list(dict_object, *keys, pop=False, **kwargs):
      '''
      Extracts all values from given dict_object and listifies them.
      '''
      result = []
      fetch = dict_object.get
      if pop:
          fetch = dict_object.pop
      # If there's only one key, we don't return a list with one element
      if len(keys) == 1:
          return listify(fetch(keys[0], []), **kwargs)
      # Return a list of values corresponding to *keys
      for key in keys:
          result.append(listify(fetch(key, []), **kwargs))
      return result
  
  
  def typeslistify(item, types):
      '''
      Ensure that type(@item) is one of @types or a
      list of items all of which are of type @types
      '''
      if isinstance(item, types):
          item = [item]
      if not isinstance(item, list):
          raise MesonException('Item must be a list or one of {!r}'.format(types))
      for i in item:
          if i is not None and not isinstance(i, types):
              raise MesonException('List item must be one of {!r}'.format(types))
      return item
  
  def stringlistify(item):
      return typeslistify(item, str)
  
  def expand_arguments(args):
      expended_args = []
      for arg in args:
          if not arg.startswith('@'):
              expended_args.append(arg)
              continue
  
          args_file = arg[1:]
          try:
              with open(args_file) as f:
                  extended_args = f.read().split()
              expended_args += extended_args
          except Exception as e:
              print('Error expanding command line arguments, %s not found' % args_file)
              print(e)
              return None
      return expended_args
  
  def Popen_safe(args, write=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs):
      import locale
      encoding = locale.getpreferredencoding()
      if sys.version_info < (3, 6) or not sys.stdout.encoding or encoding.upper() != 'UTF-8':
          return Popen_safe_legacy(args, write=write, stdout=stdout, stderr=stderr, **kwargs)
      p = subprocess.Popen(args, universal_newlines=True, close_fds=False,
                           stdout=stdout, stderr=stderr, **kwargs)
      o, e = p.communicate(write)
      return p, o, e
  
  def Popen_safe_legacy(args, write=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs):
      p = subprocess.Popen(args, universal_newlines=False,
                           stdout=stdout, stderr=stderr, **kwargs)
      if write is not None:
          write = write.encode('utf-8')
      o, e = p.communicate(write)
      if o is not None:
          if sys.stdout.encoding:
              o = o.decode(encoding=sys.stdout.encoding, errors='replace').replace('\r\n', '\n')
          else:
              o = o.decode(errors='replace').replace('\r\n', '\n')
      if e is not None:
          if sys.stderr.encoding:
              e = e.decode(encoding=sys.stderr.encoding, errors='replace').replace('\r\n', '\n')
          else:
              e = e.decode(errors='replace').replace('\r\n', '\n')
      return p, o, e
  
  def iter_regexin_iter(regexiter, initer):
      '''
      Takes each regular expression in @regexiter and tries to search for it in
      every item in @initer. If there is a match, returns that match.
      Else returns False.
      '''
      for regex in regexiter:
          for ii in initer:
              if not isinstance(ii, str):
                  continue
              match = re.search(regex, ii)
              if match:
                  return match.group()
      return False
  
  def _substitute_values_check_errors(command, values):
      # Error checking
      inregex = ('@INPUT([0-9]+)?@', '@PLAINNAME@', '@BASENAME@')
      outregex = ('@OUTPUT([0-9]+)?@', '@OUTDIR@')
      if '@INPUT@' not in values:
          # Error out if any input-derived templates are present in the command
          match = iter_regexin_iter(inregex, command)
          if match:
              m = 'Command cannot have {!r}, since no input files were specified'
              raise MesonException(m.format(match))
      else:
          if len(values['@INPUT@']) > 1:
              # Error out if @PLAINNAME@ or @BASENAME@ is present in the command
              match = iter_regexin_iter(inregex[1:], command)
              if match:
                  raise MesonException('Command cannot have {!r} when there is '
                                       'more than one input file'.format(match))
          # Error out if an invalid @INPUTnn@ template was specified
          for each in command:
              if not isinstance(each, str):
                  continue
              match = re.search(inregex[0], each)
              if match and match.group() not in values:
                  m = 'Command cannot have {!r} since there are only {!r} inputs'
                  raise MesonException(m.format(match.group(), len(values['@INPUT@'])))
      if '@OUTPUT@' not in values:
          # Error out if any output-derived templates are present in the command
          match = iter_regexin_iter(outregex, command)
          if match:
              m = 'Command cannot have {!r} since there are no outputs'
              raise MesonException(m.format(match))
      else:
          # Error out if an invalid @OUTPUTnn@ template was specified
          for each in command:
              if not isinstance(each, str):
                  continue
              match = re.search(outregex[0], each)
              if match and match.group() not in values:
                  m = 'Command cannot have {!r} since there are only {!r} outputs'
                  raise MesonException(m.format(match.group(), len(values['@OUTPUT@'])))
  
  def substitute_values(command, values):
      '''
      Substitute the template strings in the @values dict into the list of
      strings @command and return a new list. For a full list of the templates,
      see get_filenames_templates_dict()
  
      If multiple inputs/outputs are given in the @values dictionary, we
      substitute @INPUT@ and @OUTPUT@ only if they are the entire string, not
      just a part of it, and in that case we substitute *all* of them.
      '''
      # Error checking
      _substitute_values_check_errors(command, values)
      # Substitution
      outcmd = []
      rx_keys = [re.escape(key) for key in values if key not in ('@INPUT@', '@OUTPUT@')]
      value_rx = re.compile('|'.join(rx_keys)) if rx_keys else None
      for vv in command:
          if not isinstance(vv, str):
              outcmd.append(vv)
          elif '@INPUT@' in vv:
              inputs = values['@INPUT@']
              if vv == '@INPUT@':
                  outcmd += inputs
              elif len(inputs) == 1:
                  outcmd.append(vv.replace('@INPUT@', inputs[0]))
              else:
                  raise MesonException("Command has '@INPUT@' as part of a "
                                       "string and more than one input file")
          elif '@OUTPUT@' in vv:
              outputs = values['@OUTPUT@']
              if vv == '@OUTPUT@':
                  outcmd += outputs
              elif len(outputs) == 1:
                  outcmd.append(vv.replace('@OUTPUT@', outputs[0]))
              else:
                  raise MesonException("Command has '@OUTPUT@' as part of a "
                                       "string and more than one output file")
          # Append values that are exactly a template string.
          # This is faster than a string replace.
          elif vv in values:
              outcmd.append(values[vv])
          # Substitute everything else with replacement
          elif value_rx:
              outcmd.append(value_rx.sub(lambda m: values[m.group(0)], vv))
          else:
              outcmd.append(vv)
      return outcmd
  
  def get_filenames_templates_dict(inputs, outputs):
      '''
      Create a dictionary with template strings as keys and values as values for
      the following templates:
  
      @INPUT@  - the full path to one or more input files, from @inputs
      @OUTPUT@ - the full path to one or more output files, from @outputs
      @OUTDIR@ - the full path to the directory containing the output files
  
      If there is only one input file, the following keys are also created:
  
      @PLAINNAME@ - the filename of the input file
      @BASENAME@ - the filename of the input file with the extension removed
  
      If there is more than one input file, the following keys are also created:
  
      @INPUT0@, @INPUT1@, ... one for each input file
  
      If there is more than one output file, the following keys are also created:
  
      @OUTPUT0@, @OUTPUT1@, ... one for each output file
      '''
      values = {}
      # Gather values derived from the input
      if inputs:
          # We want to substitute all the inputs.
          values['@INPUT@'] = inputs
          for (ii, vv) in enumerate(inputs):
              # Write out @INPUT0@, @INPUT1@, ...
              values['@INPUT{}@'.format(ii)] = vv
          if len(inputs) == 1:
              # Just one value, substitute @PLAINNAME@ and @BASENAME@
              values['@PLAINNAME@'] = plain = os.path.basename(inputs[0])
              values['@BASENAME@'] = os.path.splitext(plain)[0]
      if outputs:
          # Gather values derived from the outputs, similar to above.
          values['@OUTPUT@'] = outputs
          for (ii, vv) in enumerate(outputs):
              values['@OUTPUT{}@'.format(ii)] = vv
          # Outdir should be the same for all outputs
          values['@OUTDIR@'] = os.path.dirname(outputs[0])
          # Many external programs fail on empty arguments.
          if values['@OUTDIR@'] == '':
              values['@OUTDIR@'] = '.'
      return values
  
  
  def _make_tree_writable(topdir):
      # Ensure all files and directories under topdir are writable
      # (and readable) by owner.
      for d, _, files in os.walk(topdir):
          os.chmod(d, os.stat(d).st_mode | stat.S_IWRITE | stat.S_IREAD)
          for fname in files:
              fpath = os.path.join(d, fname)
              if os.path.isfile(fpath):
                  os.chmod(fpath, os.stat(fpath).st_mode | stat.S_IWRITE | stat.S_IREAD)
  
  
  def windows_proof_rmtree(f):
      # On Windows if anyone is holding a file open you can't
      # delete it. As an example an anti virus scanner might
      # be scanning files you are trying to delete. The only
      # way to fix this is to try again and again.
      delays = [0.1, 0.1, 0.2, 0.2, 0.2, 0.5, 0.5, 1, 1, 1, 1, 2]
      # Start by making the tree wriable.
      _make_tree_writable(f)
      for d in delays:
          try:
              shutil.rmtree(f)
              return
          except FileNotFoundError:
              return
          except (OSError, PermissionError):
              time.sleep(d)
      # Try one last time and throw if it fails.
      shutil.rmtree(f)
  
  
  def detect_subprojects(spdir_name, current_dir='', result=None):
      if result is None:
          result = {}
      spdir = os.path.join(current_dir, spdir_name)
      if not os.path.exists(spdir):
          return result
      for trial in glob(os.path.join(spdir, '*')):
          basename = os.path.basename(trial)
          if trial == 'packagecache':
              continue
          append_this = True
          if os.path.isdir(trial):
              detect_subprojects(spdir_name, trial, result)
          elif trial.endswith('.wrap') and os.path.isfile(trial):
              basename = os.path.splitext(basename)[0]
          else:
              append_this = False
          if append_this:
              if basename in result:
                  result[basename].append(trial)
              else:
                  result[basename] = [trial]
      return result
  
  def get_error_location_string(fname, lineno):
      return '{}:{}:'.format(fname, lineno)
  
  def substring_is_in_list(substr, strlist):
      for s in strlist:
          if substr in s:
              return True
      return False
  
  class OrderedSet(collections.MutableSet):
      """A set that preserves the order in which items are added, by first
      insertion.
      """
      def __init__(self, iterable=None):
          self.__container = collections.OrderedDict()
          if iterable:
              self.update(iterable)
  
      def __contains__(self, value):
          return value in self.__container
  
      def __iter__(self):
          return iter(self.__container.keys())
  
      def __len__(self):
          return len(self.__container)
  
      def __repr__(self):
          # Don't print 'OrderedSet("")' for an empty set.
          if self.__container:
              return 'OrderedSet("{}")'.format(
                  '", "'.join(repr(e) for e in self.__container.keys()))
          return 'OrderedSet()'
  
      def add(self, value):
          self.__container[value] = None
  
      def discard(self, value):
          if value in self.__container:
              del self.__container[value]
  
      def update(self, iterable):
          for item in iterable:
              self.__container[item] = None
  
      def difference(self, set_):
          return type(self)(e for e in self if e not in set_)
  
  class BuildDirLock:
  
      def __init__(self, builddir):
          self.lockfilename = os.path.join(builddir, 'meson-private/meson.lock')
  
      def __enter__(self):
          self.lockfile = open(self.lockfilename, 'w')
          try:
              if have_fcntl:
                  fcntl.flock(self.lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
              elif have_msvcrt:
                  msvcrt.locking(self.lockfile.fileno(), msvcrt.LK_NBLCK, 1)
          except (BlockingIOError, PermissionError):
              self.lockfile.close()
              raise MesonException('Some other Meson process is already using this build directory. Exiting.')
  
      def __exit__(self, *args):
          if have_fcntl:
              fcntl.flock(self.lockfile, fcntl.LOCK_UN)
          elif have_msvcrt:
              msvcrt.locking(self.lockfile.fileno(), msvcrt.LK_UNLCK, 1)
          self.lockfile.close()
  
files: mesonbuild/mesonlib.py
files: # Copyright 2012-2015 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.
  
  """A library of random helper functionality."""
  
  import sys
  import stat
  import time
  import platform, subprocess, operator, os, shutil, re
  import collections
  from mesonbuild import mlog
  
  have_fcntl = False
  have_msvcrt = False
  # {subproject: project_meson_version}
  project_meson_versions = {}
  
  try:
      import fcntl
      have_fcntl = True
  except Exception:
      pass
  
  try:
      import msvcrt
      have_msvcrt = True
  except Exception:
      pass
  
  from glob import glob
  
  if os.path.basename(sys.executable) == 'meson.exe':
      # In Windows and using the MSI installed executable.
      python_command = [sys.executable, 'runpython']
  else:
      python_command = [sys.executable]
  meson_command = None
  
  def is_ascii_string(astring):
      try:
          if isinstance(astring, str):
              astring.encode('ascii')
          if isinstance(astring, bytes):
              astring.decode('ascii')
      except UnicodeDecodeError:
          return False
      return True
  
  def check_direntry_issues(direntry_array):
      import locale
      # Warn if the locale is not UTF-8. This can cause various unfixable issues
      # such as os.stat not being able to decode filenames with unicode in them.
      # There is no way to reset both the preferred encoding and the filesystem
      # encoding, so we can just warn about it.
      e = locale.getpreferredencoding()
      if e.upper() != 'UTF-8' and not is_windows():
          if not isinstance(direntry_array, list):
              direntry_array = [direntry_array]
          for de in direntry_array:
              if is_ascii_string(de):
                  continue
              mlog.warning('''You are using {!r} which is not a Unicode-compatible '
  locale but you are trying to access a file system entry called {!r} which is
  not pure ASCII. This may cause problems.
  '''.format(e, de), file=sys.stderr)
  
  # Put this in objects that should not get dumped to pickle files
  # by accident.
  import threading
  an_unpicklable_object = threading.Lock()
  
  class MesonException(Exception):
      '''Exceptions thrown by Meson'''
  
      def get_msg_with_context(self):
          s = ''
          if hasattr(self, 'lineno') and hasattr(self, 'file'):
              s = get_error_location_string(self.file, self.lineno) + ' '
          s += str(self)
          return s
  
  class EnvironmentException(MesonException):
      '''Exceptions thrown while processing and creating the build environment'''
  
  class FileMode:
      # The first triad is for owner permissions, the second for group permissions,
      # and the third for others (everyone else).
      # For the 1st character:
      #  'r' means can read
      #  '-' means not allowed
      # For the 2nd character:
      #  'w' means can write
      #  '-' means not allowed
      # For the 3rd character:
      #  'x' means can execute
      #  's' means can execute and setuid/setgid is set (owner/group triads only)
      #  'S' means cannot execute and setuid/setgid is set (owner/group triads only)
      #  't' means can execute and sticky bit is set ("others" triads only)
      #  'T' means cannot execute and sticky bit is set ("others" triads only)
      #  '-' means none of these are allowed
      #
      # The meanings of 'rwx' perms is not obvious for directories; see:
      # https://www.hackinglinuxexposed.com/articles/20030424.html
      #
      # For information on this notation such as setuid/setgid/sticky bits, see:
      # https://en.wikipedia.org/wiki/File_system_permissions#Symbolic_notation
      symbolic_perms_regex = re.compile('[r-][w-][xsS-]' # Owner perms
                                        '[r-][w-][xsS-]' # Group perms
                                        '[r-][w-][xtT-]') # Others perms
  
      def __init__(self, perms=None, owner=None, group=None):
          self.perms_s = perms
          self.perms = self.perms_s_to_bits(perms)
          self.owner = owner
          self.group = group
  
      def __repr__(self):
          ret = '<FileMode: {!r} owner={} group={}'
          return ret.format(self.perms_s, self.owner, self.group)
  
      @classmethod
      def perms_s_to_bits(cls, perms_s):
          '''
          Does the opposite of stat.filemode(), converts strings of the form
          'rwxr-xr-x' to st_mode enums which can be passed to os.chmod()
          '''
          if perms_s is None:
              # No perms specified, we will not touch the permissions
              return -1
          eg = 'rwxr-xr-x'
          if not isinstance(perms_s, str):
              msg = 'Install perms must be a string. For example, {!r}'
              raise MesonException(msg.format(eg))
          if len(perms_s) != 9 or not cls.symbolic_perms_regex.match(perms_s):
              msg = 'File perms {!r} must be exactly 9 chars. For example, {!r}'
              raise MesonException(msg.format(perms_s, eg))
          perms = 0
          # Owner perms
          if perms_s[0] == 'r':
              perms |= stat.S_IRUSR
          if perms_s[1] == 'w':
              perms |= stat.S_IWUSR
          if perms_s[2] == 'x':
              perms |= stat.S_IXUSR
          elif perms_s[2] == 'S':
              perms |= stat.S_ISUID
          elif perms_s[2] == 's':
              perms |= stat.S_IXUSR
              perms |= stat.S_ISUID
          # Group perms
          if perms_s[3] == 'r':
              perms |= stat.S_IRGRP
          if perms_s[4] == 'w':
              perms |= stat.S_IWGRP
          if perms_s[5] == 'x':
              perms |= stat.S_IXGRP
          elif perms_s[5] == 'S':
              perms |= stat.S_ISGID
          elif perms_s[5] == 's':
              perms |= stat.S_IXGRP
              perms |= stat.S_ISGID
          # Others perms
          if perms_s[6] == 'r':
              perms |= stat.S_IROTH
          if perms_s[7] == 'w':
              perms |= stat.S_IWOTH
          if perms_s[8] == 'x':
              perms |= stat.S_IXOTH
          elif perms_s[8] == 'T':
              perms |= stat.S_ISVTX
          elif perms_s[8] == 't':
              perms |= stat.S_IXOTH
              perms |= stat.S_ISVTX
          return perms
  
  class File:
      def __init__(self, is_built, subdir, fname):
          self.is_built = is_built
          self.subdir = subdir
          self.fname = fname
          assert(isinstance(self.subdir, str))
          assert(isinstance(self.fname, str))
  
      def __str__(self):
          return self.relative_name()
  
      def __repr__(self):
          ret = '<File: {0}'
          if not self.is_built:
              ret += ' (not built)'
          ret += '>'
          return ret.format(self.relative_name())
  
      @staticmethod
      def from_source_file(source_root, subdir, fname):
          if not os.path.isfile(os.path.join(source_root, subdir, fname)):
              raise MesonException('File %s does not exist.' % fname)
          return File(False, subdir, fname)
  
      @staticmethod
      def from_built_file(subdir, fname):
          return File(True, subdir, fname)
  
      @staticmethod
      def from_absolute_file(fname):
          return File(False, '', fname)
  
      def rel_to_builddir(self, build_to_src):
          if self.is_built:
              return self.relative_name()
          else:
              return os.path.join(build_to_src, self.subdir, self.fname)
  
      def absolute_path(self, srcdir, builddir):
          absdir = srcdir
          if self.is_built:
              absdir = builddir
          return os.path.join(absdir, self.relative_name())
  
      def endswith(self, ending):
          return self.fname.endswith(ending)
  
      def split(self, s):
          return self.fname.split(s)
  
      def __eq__(self, other):
          return (self.fname, self.subdir, self.is_built) == (other.fname, other.subdir, other.is_built)
  
      def __hash__(self):
          return hash((self.fname, self.subdir, self.is_built))
  
      def relative_name(self):
          return os.path.join(self.subdir, self.fname)
  
  def get_compiler_for_source(compilers, src):
      for comp in compilers:
          if comp.can_compile(src):
              return comp
      raise RuntimeError('No specified compiler can handle file {!s}'.format(src))
  
  def classify_unity_sources(compilers, sources):
      compsrclist = {}
      for src in sources:
          comp = get_compiler_for_source(compilers, src)
          if comp not in compsrclist:
              compsrclist[comp] = [src]
          else:
              compsrclist[comp].append(src)
      return compsrclist
  
  def is_osx():
      return platform.system().lower() == 'darwin'
  
  def is_linux():
      return platform.system().lower() == 'linux'
  
  def is_android():
      return platform.system().lower() == 'android'
  
  def is_haiku():
      return platform.system().lower() == 'haiku'
  
  def is_openbsd():
      return platform.system().lower() == 'openbsd'
  
  def is_windows():
      platname = platform.system().lower()
      return platname == 'windows' or 'mingw' in platname
  
  def is_cygwin():
      platname = platform.system().lower()
      return platname.startswith('cygwin')
  
  def is_debianlike():
      return os.path.isfile('/etc/debian_version')
  
  def is_dragonflybsd():
      return platform.system().lower() == 'dragonfly'
  
  def is_freebsd():
      return platform.system().lower() == 'freebsd'
  
  def for_windows(is_cross, env):
      """
      Host machine is windows?
  
      Note: 'host' is the machine on which compiled binaries will run
      """
      if not is_cross:
          return is_windows()
      elif env.cross_info.has_host():
          return env.cross_info.config['host_machine']['system'] == 'windows'
      return False
  
  def for_cygwin(is_cross, env):
      """
      Host machine is cygwin?
  
      Note: 'host' is the machine on which compiled binaries will run
      """
      if not is_cross:
          return is_cygwin()
      elif env.cross_info.has_host():
          return env.cross_info.config['host_machine']['system'] == 'cygwin'
      return False
  
  def for_linux(is_cross, env):
      """
      Host machine is linux?
  
      Note: 'host' is the machine on which compiled binaries will run
      """
      if not is_cross:
          return is_linux()
      elif env.cross_info.has_host():
          return env.cross_info.config['host_machine']['system'] == 'linux'
      return False
  
  def for_darwin(is_cross, env):
      """
      Host machine is Darwin (iOS/OS X)?
  
      Note: 'host' is the machine on which compiled binaries will run
      """
      if not is_cross:
          return is_osx()
      elif env.cross_info.has_host():
          return env.cross_info.config['host_machine']['system'] in ('darwin', 'ios')
      return False
  
  def for_android(is_cross, env):
      """
      Host machine is Android?
  
      Note: 'host' is the machine on which compiled binaries will run
      """
      if not is_cross:
          return is_android()
      elif env.cross_info.has_host():
          return env.cross_info.config['host_machine']['system'] == 'android'
      return False
  
  def for_haiku(is_cross, env):
      """
      Host machine is Haiku?
  
      Note: 'host' is the machine on which compiled binaries will run
      """
      if not is_cross:
          return is_haiku()
      elif env.cross_info.has_host():
          return env.cross_info.config['host_machine']['system'] == 'haiku'
      return False
  
  def for_openbsd(is_cross, env):
      """
      Host machine is OpenBSD?
  
      Note: 'host' is the machine on which compiled binaries will run
      """
      if not is_cross:
          return is_openbsd()
      elif env.cross_info.has_host():
          return env.cross_info.config['host_machine']['system'] == 'openbsd'
      return False
  
  def exe_exists(arglist):
      try:
          p = subprocess.Popen(arglist, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
          p.communicate()
          if p.returncode == 0:
              return True
      except FileNotFoundError:
          pass
      return False
  
  def detect_vcs(source_dir):
      vcs_systems = [
          dict(name = 'git',        cmd = 'git', repo_dir = '.git', get_rev = 'git describe --dirty=+', rev_regex = '(.*)', dep = '.git/logs/HEAD'),
          dict(name = 'mercurial',  cmd = 'hg',  repo_dir = '.hg',  get_rev = 'hg id -i',               rev_regex = '(.*)', dep = '.hg/dirstate'),
          dict(name = 'subversion', cmd = 'svn', repo_dir = '.svn', get_rev = 'svn info',               rev_regex = 'Revision: (.*)', dep = '.svn/wc.db'),
          dict(name = 'bazaar',     cmd = 'bzr', repo_dir = '.bzr', get_rev = 'bzr revno',              rev_regex = '(.*)', dep = '.bzr'),
      ]
  
      segs = source_dir.replace('\\', '/').split('/')
      for i in range(len(segs), -1, -1):
          curdir = '/'.join(segs[:i])
          for vcs in vcs_systems:
              if os.path.isdir(os.path.join(curdir, vcs['repo_dir'])) and shutil.which(vcs['cmd']):
                  vcs['wc_dir'] = curdir
                  return vcs
      return None
  
  def grab_leading_numbers(vstr, strict=False):
      result = []
      for x in vstr.rstrip('.').split('.'):
          try:
              result.append(int(x))
          except ValueError as e:
              if strict:
                  msg = 'Invalid version to compare against: {!r}; only ' \
                        'numeric digits separated by "." are allowed: ' + str(e)
                  raise MesonException(msg.format(vstr))
              break
      return result
  
  def make_same_len(listA, listB):
      maxlen = max(len(listA), len(listB))
      for i in listA, listB:
          for n in range(len(i), maxlen):
              i.append(0)
  
  numpart = re.compile('[0-9.]+')
  
  def version_compare(vstr1, vstr2, strict=False):
      match = numpart.match(vstr1.strip())
      if match is None:
          msg = 'Uncomparable version string {!r}.'
          raise MesonException(msg.format(vstr1))
      vstr1 = match.group(0)
      if vstr2.startswith('>='):
          cmpop = operator.ge
          vstr2 = vstr2[2:]
      elif vstr2.startswith('<='):
          cmpop = operator.le
          vstr2 = vstr2[2:]
      elif vstr2.startswith('!='):
          cmpop = operator.ne
          vstr2 = vstr2[2:]
      elif vstr2.startswith('=='):
          cmpop = operator.eq
          vstr2 = vstr2[2:]
      elif vstr2.startswith('='):
          cmpop = operator.eq
          vstr2 = vstr2[1:]
      elif vstr2.startswith('>'):
          cmpop = operator.gt
          vstr2 = vstr2[1:]
      elif vstr2.startswith('<'):
          cmpop = operator.lt
          vstr2 = vstr2[1:]
      else:
          cmpop = operator.eq
      varr1 = grab_leading_numbers(vstr1, strict)
      varr2 = grab_leading_numbers(vstr2, strict)
      make_same_len(varr1, varr2)
      return cmpop(varr1, varr2)
  
  def version_compare_many(vstr1, conditions):
      if not isinstance(conditions, (list, tuple, frozenset)):
          conditions = [conditions]
      found = []
      not_found = []
      for req in conditions:
          if not version_compare(vstr1, req, strict=True):
              not_found.append(req)
          else:
              found.append(req)
      return not_found == [], not_found, found
  
  
  def version_compare_condition_with_min(condition, minimum):
      match = numpart.match(minimum.strip())
      if match is None:
          msg = 'Uncomparable version string {!r}.'
          raise MesonException(msg.format(minimum))
      minimum = match.group(0)
      if condition.startswith('>='):
          cmpop = operator.le
          condition = condition[2:]
      elif condition.startswith('<='):
          return True
          condition = condition[2:]
      elif condition.startswith('!='):
          return True
          condition = condition[2:]
      elif condition.startswith('=='):
          cmpop = operator.le
          condition = condition[2:]
      elif condition.startswith('='):
          cmpop = operator.le
          condition = condition[1:]
      elif condition.startswith('>'):
          cmpop = operator.lt
          condition = condition[1:]
      elif condition.startswith('<'):
          return True
          condition = condition[2:]
      else:
          cmpop = operator.le
      varr1 = grab_leading_numbers(minimum, True)
      varr2 = grab_leading_numbers(condition, True)
      make_same_len(varr1, varr2)
      return cmpop(varr1, varr2)
  
  def version_compare_condition_with_max(condition, maximum):
      match = numpart.match(maximum.strip())
      if match is None:
          msg = 'Uncomparable version string {!r}.'
          raise MesonException(msg.format(maximum))
      maximum = match.group(0)
      if condition.startswith('>='):
          return False
          condition = condition[2:]
      elif condition.startswith('<='):
          cmpop = operator.ge
          condition = condition[2:]
      elif condition.startswith('!='):
          return False
          condition = condition[2:]
      elif condition.startswith('=='):
          cmpop = operator.ge
          condition = condition[2:]
      elif condition.startswith('='):
          cmpop = operator.ge
          condition = condition[1:]
      elif condition.startswith('>'):
          return False
          condition = condition[1:]
      elif condition.startswith('<'):
          cmpop = operator.gt
          condition = condition[2:]
      else:
          cmpop = operator.ge
      varr1 = grab_leading_numbers(maximum, True)
      varr2 = grab_leading_numbers(condition, True)
      make_same_len(varr1, varr2)
      return cmpop(varr1, varr2)
  
  
  def default_libdir():
      if is_debianlike():
          try:
              pc = subprocess.Popen(['dpkg-architecture', '-qDEB_HOST_MULTIARCH'],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.DEVNULL)
              (stdo, _) = pc.communicate()
              if pc.returncode == 0:
                  archpath = stdo.decode().strip()
                  return 'lib/' + archpath
          except Exception:
              pass
      if os.path.isdir('/usr/lib64') and not os.path.islink('/usr/lib64'):
          return 'lib64'
      return 'lib'
  
  def default_libexecdir():
      # There is no way to auto-detect this, so it must be set at build time
      return 'libexec'
  
  def default_prefix():
      return 'c:/' if is_windows() else '/usr/local'
  
  def get_library_dirs():
      if is_windows():
          return ['C:/mingw/lib'] # Fixme
      if is_osx():
          return ['/usr/lib'] # Fix me as well.
      # The following is probably Debian/Ubuntu specific.
      # /usr/local/lib is first because it contains stuff
      # installed by the sysadmin and is probably more up-to-date
      # than /usr/lib. If you feel that this search order is
      # problematic, please raise the issue on the mailing list.
      unixdirs = ['/usr/local/lib', '/usr/lib', '/lib']
      plat = subprocess.check_output(['uname', '-m']).decode().strip()
      # This is a terrible hack. I admit it and I'm really sorry.
      # I just don't know what the correct solution is.
      if plat == 'i686':
          plat = 'i386'
      if plat.startswith('arm'):
          plat = 'arm'
      unixdirs += glob('/usr/lib/' + plat + '*')
      if os.path.exists('/usr/lib64'):
          unixdirs.append('/usr/lib64')
      unixdirs += glob('/lib/' + plat + '*')
      if os.path.exists('/lib64'):
          unixdirs.append('/lib64')
      unixdirs += glob('/lib/' + plat + '*')
      return unixdirs
  
  def has_path_sep(name, sep='/\\'):
      'Checks if any of the specified @sep path separators are in @name'
      for each in sep:
          if each in name:
              return True
      return False
  
  def do_replacement(regex, line, format, confdata):
      missing_variables = set()
      start_tag = '@'
      backslash_tag = '\\@'
      if format == 'cmake':
          start_tag = '${'
          backslash_tag = '\\${'
  
      def variable_replace(match):
          # Pairs of escape characters before '@' or '\@'
          if match.group(0).endswith('\\'):
              num_escapes = match.end(0) - match.start(0)
              return '\\' * (num_escapes // 2)
          # Single escape character and '@'
          elif match.group(0) == backslash_tag:
              return start_tag
          # Template variable to be replaced
          else:
              varname = match.group(1)
              if varname in confdata:
                  (var, desc) = confdata.get(varname)
                  if isinstance(var, str):
                      pass
                  elif isinstance(var, int):
                      var = str(var)
                  else:
                      msg = 'Tried to replace variable {!r} value with ' \
                            'something other than a string or int: {!r}'
                      raise MesonException(msg.format(varname, var))
              else:
                  missing_variables.add(varname)
                  var = ''
              return var
      return re.sub(regex, variable_replace, line), missing_variables
  
  def do_mesondefine(line, confdata):
      arr = line.split()
      if len(arr) != 2:
          raise MesonException('#mesondefine does not contain exactly two tokens: %s' % line.strip())
      varname = arr[1]
      try:
          (v, desc) = confdata.get(varname)
      except KeyError:
          return '/* #undef %s */\n' % varname
      if isinstance(v, bool):
          if v:
              return '#define %s\n' % varname
          else:
              return '#undef %s\n' % varname
      elif isinstance(v, int):
          return '#define %s %d\n' % (varname, v)
      elif isinstance(v, str):
          return '#define %s %s\n' % (varname, v)
      else:
          raise MesonException('#mesondefine argument "%s" is of unknown type.' % varname)
  
  
  def do_conf_file(src, dst, confdata, format, encoding='utf-8'):
      try:
          with open(src, encoding=encoding) as f:
              data = f.readlines()
      except Exception as e:
          raise MesonException('Could not read input file %s: %s' % (src, str(e)))
      # Only allow (a-z, A-Z, 0-9, _, -) as valid characters for a define
      # Also allow escaping '@' with '\@'
      if format in ['meson', 'cmake@']:
          regex = re.compile(r'(?:\\\\)+(?=\\?@)|\\@|@([-a-zA-Z0-9_]+)@')
      elif format == 'cmake':
          regex = re.compile(r'(?:\\\\)+(?=\\?\$)|\\\${|\${([-a-zA-Z0-9_]+)}')
      else:
          raise MesonException('Format "{}" not handled'.format(format))
  
      search_token = '#mesondefine'
      if format != 'meson':
          search_token = '#cmakedefine'
  
      result = []
      missing_variables = set()
      # Detect when the configuration data is empty and no tokens were found
      # during substitution so we can warn the user to use the `copy:` kwarg.
      confdata_useless = not confdata.keys()
      for line in data:
          if line.startswith(search_token):
              confdata_useless = False
              line = do_mesondefine(line, confdata)
          else:
              line, missing = do_replacement(regex, line, format, confdata)
              missing_variables.update(missing)
              if missing:
                  confdata_useless = False
          result.append(line)
      dst_tmp = dst + '~'
      try:
          with open(dst_tmp, 'w', encoding=encoding) as f:
              f.writelines(result)
      except Exception as e:
          raise MesonException('Could not write output file %s: %s' % (dst, str(e)))
      shutil.copymode(src, dst_tmp)
      replace_if_different(dst, dst_tmp)
      return missing_variables, confdata_useless
  
  CONF_C_PRELUDE = '''/*
   * Autogenerated by the Meson build system.
   * Do not edit, your changes will be lost.
   */
  
  #pragma once
  
  '''
  
  CONF_NASM_PRELUDE = '''; Autogenerated by the Meson build system.
  ; Do not edit, your changes will be lost.
  
  '''
  
  def dump_conf_header(ofilename, cdata, output_format):
      if output_format == 'c':
          prelude = CONF_C_PRELUDE
          prefix = '#'
      elif output_format == 'nasm':
          prelude = CONF_NASM_PRELUDE
          prefix = '%'
  
      ofilename_tmp = ofilename + '~'
      with open(ofilename_tmp, 'w', encoding='utf-8') as ofile:
          ofile.write(prelude)
          for k in sorted(cdata.keys()):
              (v, desc) = cdata.get(k)
              if desc:
                  if output_format == 'c':
                      ofile.write('/* %s */\n' % desc)
                  elif output_format == 'nasm':
                      for line in desc.split('\n'):
                          ofile.write('; %s\n' % line)
              if isinstance(v, bool):
                  if v:
                      ofile.write('%sdefine %s\n\n' % (prefix, k))
                  else:
                      ofile.write('%sundef %s\n\n' % (prefix, k))
              elif isinstance(v, (int, str)):
                  ofile.write('%sdefine %s %s\n\n' % (prefix, k, v))
              else:
                  raise MesonException('Unknown data type in configuration file entry: ' + k)
      replace_if_different(ofilename, ofilename_tmp)
  
  def replace_if_different(dst, dst_tmp):
      # If contents are identical, don't touch the file to prevent
      # unnecessary rebuilds.
      different = True
      try:
          with open(dst, 'rb') as f1, open(dst_tmp, 'rb') as f2:
              if f1.read() == f2.read():
                  different = False
      except FileNotFoundError:
          pass
      if different:
          os.replace(dst_tmp, dst)
      else:
          os.unlink(dst_tmp)
  
  def listify(item, flatten=True, unholder=False):
      '''
      Returns a list with all args embedded in a list if they are not a list.
      This function preserves order.
      @flatten: Convert lists of lists to a flat list
      @unholder: Replace each item with the object it holds, if required
  
      Note: unholding only works recursively when flattening
      '''
      if not isinstance(item, list):
          if unholder and hasattr(item, 'held_object'):
              item = item.held_object
          return [item]
      result = []
      for i in item:
          if unholder and hasattr(i, 'held_object'):
              i = i.held_object
          if flatten and isinstance(i, list):
              result += listify(i, flatten=True, unholder=unholder)
          else:
              result.append(i)
      return result
  
  
  def extract_as_list(dict_object, *keys, pop=False, **kwargs):
      '''
      Extracts all values from given dict_object and listifies them.
      '''
      result = []
      fetch = dict_object.get
      if pop:
          fetch = dict_object.pop
      # If there's only one key, we don't return a list with one element
      if len(keys) == 1:
          return listify(fetch(keys[0], []), **kwargs)
      # Return a list of values corresponding to *keys
      for key in keys:
          result.append(listify(fetch(key, []), **kwargs))
      return result
  
  
  def typeslistify(item, types):
      '''
      Ensure that type(@item) is one of @types or a
      list of items all of which are of type @types
      '''
      if isinstance(item, types):
          item = [item]
      if not isinstance(item, list):
          raise MesonException('Item must be a list or one of {!r}'.format(types))
      for i in item:
          if i is not None and not isinstance(i, types):
              raise MesonException('List item must be one of {!r}'.format(types))
      return item
  
  def stringlistify(item):
      return typeslistify(item, str)
  
  def expand_arguments(args):
      expended_args = []
      for arg in args:
          if not arg.startswith('@'):
              expended_args.append(arg)
              continue
  
          args_file = arg[1:]
          try:
              with open(args_file) as f:
                  extended_args = f.read().split()
              expended_args += extended_args
          except Exception as e:
              print('Error expanding command line arguments, %s not found' % args_file)
              print(e)
              return None
      return expended_args
  
  def Popen_safe(args, write=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs):
      import locale
      encoding = locale.getpreferredencoding()
      if sys.version_info < (3, 6) or not sys.stdout.encoding or encoding.upper() != 'UTF-8':
          return Popen_safe_legacy(args, write=write, stdout=stdout, stderr=stderr, **kwargs)
      p = subprocess.Popen(args, universal_newlines=True, close_fds=False,
                           stdout=stdout, stderr=stderr, **kwargs)
      o, e = p.communicate(write)
      return p, o, e
  
  def Popen_safe_legacy(args, write=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs):
      p = subprocess.Popen(args, universal_newlines=False,
                           stdout=stdout, stderr=stderr, **kwargs)
      if write is not None:
          write = write.encode('utf-8')
      o, e = p.communicate(write)
      if o is not None:
          if sys.stdout.encoding:
              o = o.decode(encoding=sys.stdout.encoding, errors='replace').replace('\r\n', '\n')
          else:
              o = o.decode(errors='replace').replace('\r\n', '\n')
      if e is not None:
          if sys.stderr.encoding:
              e = e.decode(encoding=sys.stderr.encoding, errors='replace').replace('\r\n', '\n')
          else:
              e = e.decode(errors='replace').replace('\r\n', '\n')
      return p, o, e
  
  def iter_regexin_iter(regexiter, initer):
      '''
      Takes each regular expression in @regexiter and tries to search for it in
      every item in @initer. If there is a match, returns that match.
      Else returns False.
      '''
      for regex in regexiter:
          for ii in initer:
              if not isinstance(ii, str):
                  continue
              match = re.search(regex, ii)
              if match:
                  return match.group()
      return False
  
  def _substitute_values_check_errors(command, values):
      # Error checking
      inregex = ('@INPUT([0-9]+)?@', '@PLAINNAME@', '@BASENAME@')
      outregex = ('@OUTPUT([0-9]+)?@', '@OUTDIR@')
      if '@INPUT@' not in values:
          # Error out if any input-derived templates are present in the command
          match = iter_regexin_iter(inregex, command)
          if match:
              m = 'Command cannot have {!r}, since no input files were specified'
              raise MesonException(m.format(match))
      else:
          if len(values['@INPUT@']) > 1:
              # Error out if @PLAINNAME@ or @BASENAME@ is present in the command
              match = iter_regexin_iter(inregex[1:], command)
              if match:
                  raise MesonException('Command cannot have {!r} when there is '
                                       'more than one input file'.format(match))
          # Error out if an invalid @INPUTnn@ template was specified
          for each in command:
              if not isinstance(each, str):
                  continue
              match = re.search(inregex[0], each)
              if match and match.group() not in values:
                  m = 'Command cannot have {!r} since there are only {!r} inputs'
                  raise MesonException(m.format(match.group(), len(values['@INPUT@'])))
      if '@OUTPUT@' not in values:
          # Error out if any output-derived templates are present in the command
          match = iter_regexin_iter(outregex, command)
          if match:
              m = 'Command cannot have {!r} since there are no outputs'
              raise MesonException(m.format(match))
      else:
          # Error out if an invalid @OUTPUTnn@ template was specified
          for each in command:
              if not isinstance(each, str):
                  continue
              match = re.search(outregex[0], each)
              if match and match.group() not in values:
                  m = 'Command cannot have {!r} since there are only {!r} outputs'
                  raise MesonException(m.format(match.group(), len(values['@OUTPUT@'])))
  
  def substitute_values(command, values):
      '''
      Substitute the template strings in the @values dict into the list of
      strings @command and return a new list. For a full list of the templates,
      see get_filenames_templates_dict()
  
      If multiple inputs/outputs are given in the @values dictionary, we
      substitute @INPUT@ and @OUTPUT@ only if they are the entire string, not
      just a part of it, and in that case we substitute *all* of them.
      '''
      # Error checking
      _substitute_values_check_errors(command, values)
      # Substitution
      outcmd = []
      rx_keys = [re.escape(key) for key in values if key not in ('@INPUT@', '@OUTPUT@')]
      value_rx = re.compile('|'.join(rx_keys)) if rx_keys else None
      for vv in command:
          if not isinstance(vv, str):
              outcmd.append(vv)
          elif '@INPUT@' in vv:
              inputs = values['@INPUT@']
              if vv == '@INPUT@':
                  outcmd += inputs
              elif len(inputs) == 1:
                  outcmd.append(vv.replace('@INPUT@', inputs[0]))
              else:
                  raise MesonException("Command has '@INPUT@' as part of a "
                                       "string and more than one input file")
          elif '@OUTPUT@' in vv:
              outputs = values['@OUTPUT@']
              if vv == '@OUTPUT@':
                  outcmd += outputs
              elif len(outputs) == 1:
                  outcmd.append(vv.replace('@OUTPUT@', outputs[0]))
              else:
                  raise MesonException("Command has '@OUTPUT@' as part of a "
                                       "string and more than one output file")
          # Append values that are exactly a template string.
          # This is faster than a string replace.
          elif vv in values:
              outcmd.append(values[vv])
          # Substitute everything else with replacement
          elif value_rx:
              outcmd.append(value_rx.sub(lambda m: values[m.group(0)], vv))
          else:
              outcmd.append(vv)
      return outcmd
  
  def get_filenames_templates_dict(inputs, outputs):
      '''
      Create a dictionary with template strings as keys and values as values for
      the following templates:
  
      @INPUT@  - the full path to one or more input files, from @inputs
      @OUTPUT@ - the full path to one or more output files, from @outputs
      @OUTDIR@ - the full path to the directory containing the output files
  
      If there is only one input file, the following keys are also created:
  
      @PLAINNAME@ - the filename of the input file
      @BASENAME@ - the filename of the input file with the extension removed
  
      If there is more than one input file, the following keys are also created:
  
      @INPUT0@, @INPUT1@, ... one for each input file
  
      If there is more than one output file, the following keys are also created:
  
      @OUTPUT0@, @OUTPUT1@, ... one for each output file
      '''
      values = {}
      # Gather values derived from the input
      if inputs:
          # We want to substitute all the inputs.
          values['@INPUT@'] = inputs
          for (ii, vv) in enumerate(inputs):
              # Write out @INPUT0@, @INPUT1@, ...
              values['@INPUT{}@'.format(ii)] = vv
          if len(inputs) == 1:
              # Just one value, substitute @PLAINNAME@ and @BASENAME@
              values['@PLAINNAME@'] = plain = os.path.basename(inputs[0])
              values['@BASENAME@'] = os.path.splitext(plain)[0]
      if outputs:
          # Gather values derived from the outputs, similar to above.
          values['@OUTPUT@'] = outputs
          for (ii, vv) in enumerate(outputs):
              values['@OUTPUT{}@'.format(ii)] = vv
          # Outdir should be the same for all outputs
          values['@OUTDIR@'] = os.path.dirname(outputs[0])
          # Many external programs fail on empty arguments.
          if values['@OUTDIR@'] == '':
              values['@OUTDIR@'] = '.'
      return values
  
  
  def _make_tree_writable(topdir):
      # Ensure all files and directories under topdir are writable
      # (and readable) by owner.
      for d, _, files in os.walk(topdir):
          os.chmod(d, os.stat(d).st_mode | stat.S_IWRITE | stat.S_IREAD)
          for fname in files:
              fpath = os.path.join(d, fname)
              if os.path.isfile(fpath):
                  os.chmod(fpath, os.stat(fpath).st_mode | stat.S_IWRITE | stat.S_IREAD)
  
  
  def windows_proof_rmtree(f):
      # On Windows if anyone is holding a file open you can't
      # delete it. As an example an anti virus scanner might
      # be scanning files you are trying to delete. The only
      # way to fix this is to try again and again.
      delays = [0.1, 0.1, 0.2, 0.2, 0.2, 0.5, 0.5, 1, 1, 1, 1, 2]
      # Start by making the tree wriable.
      _make_tree_writable(f)
      for d in delays:
          try:
              shutil.rmtree(f)
              return
          except FileNotFoundError:
              return
          except (OSError, PermissionError):
              time.sleep(d)
      # Try one last time and throw if it fails.
      shutil.rmtree(f)
  
  
  def detect_subprojects(spdir_name, current_dir='', result=None):
      if result is None:
          result = {}
      spdir = os.path.join(current_dir, spdir_name)
      if not os.path.exists(spdir):
          return result
      for trial in glob(os.path.join(spdir, '*')):
          basename = os.path.basename(trial)
          if trial == 'packagecache':
              continue
          append_this = True
          if os.path.isdir(trial):
              detect_subprojects(spdir_name, trial, result)
          elif trial.endswith('.wrap') and os.path.isfile(trial):
              basename = os.path.splitext(basename)[0]
          else:
              append_this = False
          if append_this:
              if basename in result:
                  result[basename].append(trial)
              else:
                  result[basename] = [trial]
      return result
  
  def get_error_location_string(fname, lineno):
      return '{}:{}:'.format(fname, lineno)
  
  def substring_is_in_list(substr, strlist):
      for s in strlist:
          if substr in s:
              return True
      return False
  
  class OrderedSet(collections.MutableSet):
      """A set that preserves the order in which items are added, by first
      insertion.
      """
      def __init__(self, iterable=None):
          self.__container = collections.OrderedDict()
          if iterable:
              self.update(iterable)
  
      def __contains__(self, value):
          return value in self.__container
  
      def __iter__(self):
          return iter(self.__container.keys())
  
      def __len__(self):
          return len(self.__container)
  
      def __repr__(self):
          # Don't print 'OrderedSet("")' for an empty set.
          if self.__container:
              return 'OrderedSet("{}")'.format(
                  '", "'.join(repr(e) for e in self.__container.keys()))
          return 'OrderedSet()'
  
      def add(self, value):
          self.__container[value] = None
  
      def discard(self, value):
          if value in self.__container:
              del self.__container[value]
  
      def update(self, iterable):
          for item in iterable:
              self.__container[item] = None
  
      def difference(self, set_):
          return type(self)(e for e in self if e not in set_)
  
  class BuildDirLock:
  
      def __init__(self, builddir):
          self.lockfilename = os.path.join(builddir, 'meson-private/meson.lock')
  
      def __enter__(self):
          self.lockfile = open(self.lockfilename, 'w')
          try:
              if have_fcntl:
                  fcntl.flock(self.lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
              elif have_msvcrt:
                  msvcrt.locking(self.lockfile.fileno(), msvcrt.LK_NBLCK, 1)
          except (BlockingIOError, PermissionError):
              self.lockfile.close()
              raise MesonException('Some other Meson process is already using this build directory. Exiting.')
  
      def __exit__(self, *args):
          if have_fcntl:
              fcntl.flock(self.lockfile, fcntl.LOCK_UN)
          elif have_msvcrt:
              msvcrt.locking(self.lockfile.fileno(), msvcrt.LK_UNLCK, 1)
          self.lockfile.close()
  
files: mesonbuild/mesonlib.py