Path: blob/master/ invest-robot-contest_TinkoffBotTwitch-main/venv/lib/python3.8/site-packages/numpy/distutils/mingw32ccompiler.py
7763 views
"""1Support code for building Python extensions on Windows.23# NT stuff4# 1. Make sure libpython<version>.a exists for gcc. If not, build it.5# 2. Force windows to use gcc (we're struggling with MSVC and g77 support)6# 3. Force windows to use g7778"""9import os10import platform11import sys12import subprocess13import re14import textwrap1516# Overwrite certain distutils.ccompiler functions:17import numpy.distutils.ccompiler # noqa: F40118from numpy.distutils import log19# NT stuff20# 1. Make sure libpython<version>.a exists for gcc. If not, build it.21# 2. Force windows to use gcc (we're struggling with MSVC and g77 support)22# --> this is done in numpy/distutils/ccompiler.py23# 3. Force windows to use g772425import distutils.cygwinccompiler26from distutils.unixccompiler import UnixCCompiler27from distutils.msvccompiler import get_build_version as get_build_msvc_version28from distutils.errors import UnknownFileError29from numpy.distutils.misc_util import (msvc_runtime_library,30msvc_runtime_version,31msvc_runtime_major,32get_build_architecture)3334def get_msvcr_replacement():35"""Replacement for outdated version of get_msvcr from cygwinccompiler"""36msvcr = msvc_runtime_library()37return [] if msvcr is None else [msvcr]3839# monkey-patch cygwinccompiler with our updated version from misc_util40# to avoid getting an exception raised on Python 3.541distutils.cygwinccompiler.get_msvcr = get_msvcr_replacement4243# Useful to generate table of symbols from a dll44_START = re.compile(r'\[Ordinal/Name Pointer\] Table')45_TABLE = re.compile(r'^\s+\[([\s*[0-9]*)\] ([a-zA-Z0-9_]*)')4647# the same as cygwin plus some additional parameters48class Mingw32CCompiler(distutils.cygwinccompiler.CygwinCCompiler):49""" A modified MingW32 compiler compatible with an MSVC built Python.5051"""5253compiler_type = 'mingw32'5455def __init__ (self,56verbose=0,57dry_run=0,58force=0):5960distutils.cygwinccompiler.CygwinCCompiler.__init__ (self, verbose,61dry_run, force)6263# **changes: eric jones 4/11/0164# 1. Check for import library on Windows. Build if it doesn't exist.6566build_import_library()6768# Check for custom msvc runtime library on Windows. Build if it doesn't exist.69msvcr_success = build_msvcr_library()70msvcr_dbg_success = build_msvcr_library(debug=True)71if msvcr_success or msvcr_dbg_success:72# add preprocessor statement for using customized msvcr lib73self.define_macro('NPY_MINGW_USE_CUSTOM_MSVCR')7475# Define the MSVC version as hint for MinGW76msvcr_version = msvc_runtime_version()77if msvcr_version:78self.define_macro('__MSVCRT_VERSION__', '0x%04i' % msvcr_version)7980# MS_WIN64 should be defined when building for amd64 on windows,81# but python headers define it only for MS compilers, which has all82# kind of bad consequences, like using Py_ModuleInit4 instead of83# Py_ModuleInit4_64, etc... So we add it here84if get_build_architecture() == 'AMD64':85self.set_executables(86compiler='gcc -g -DDEBUG -DMS_WIN64 -O0 -Wall',87compiler_so='gcc -g -DDEBUG -DMS_WIN64 -O0 -Wall '88'-Wstrict-prototypes',89linker_exe='gcc -g',90linker_so='gcc -g -shared')91else:92self.set_executables(93compiler='gcc -O2 -Wall',94compiler_so='gcc -O2 -Wall -Wstrict-prototypes',95linker_exe='g++ ',96linker_so='g++ -shared')97# added for python2.3 support98# we can't pass it through set_executables because pre 2.2 would fail99self.compiler_cxx = ['g++']100101# Maybe we should also append -mthreads, but then the finished dlls102# need another dll (mingwm10.dll see Mingw32 docs) (-mthreads: Support103# thread-safe exception handling on `Mingw32')104105# no additional libraries needed106#self.dll_libraries=[]107return108109# __init__ ()110111def link(self,112target_desc,113objects,114output_filename,115output_dir,116libraries,117library_dirs,118runtime_library_dirs,119export_symbols = None,120debug=0,121extra_preargs=None,122extra_postargs=None,123build_temp=None,124target_lang=None):125# Include the appropriate MSVC runtime library if Python was built126# with MSVC >= 7.0 (MinGW standard is msvcrt)127runtime_library = msvc_runtime_library()128if runtime_library:129if not libraries:130libraries = []131libraries.append(runtime_library)132args = (self,133target_desc,134objects,135output_filename,136output_dir,137libraries,138library_dirs,139runtime_library_dirs,140None, #export_symbols, we do this in our def-file141debug,142extra_preargs,143extra_postargs,144build_temp,145target_lang)146func = UnixCCompiler.link147func(*args[:func.__code__.co_argcount])148return149150def object_filenames (self,151source_filenames,152strip_dir=0,153output_dir=''):154if output_dir is None: output_dir = ''155obj_names = []156for src_name in source_filenames:157# use normcase to make sure '.rc' is really '.rc' and not '.RC'158(base, ext) = os.path.splitext (os.path.normcase(src_name))159160# added these lines to strip off windows drive letters161# without it, .o files are placed next to .c files162# instead of the build directory163drv, base = os.path.splitdrive(base)164if drv:165base = base[1:]166167if ext not in (self.src_extensions + ['.rc', '.res']):168raise UnknownFileError(169"unknown file type '%s' (from '%s')" % \170(ext, src_name))171if strip_dir:172base = os.path.basename (base)173if ext == '.res' or ext == '.rc':174# these need to be compiled to object files175obj_names.append (os.path.join (output_dir,176base + ext + self.obj_extension))177else:178obj_names.append (os.path.join (output_dir,179base + self.obj_extension))180return obj_names181182# object_filenames ()183184185def find_python_dll():186# We can't do much here:187# - find it in the virtualenv (sys.prefix)188# - find it in python main dir (sys.base_prefix, if in a virtualenv)189# - sys.real_prefix is main dir for virtualenvs in Python 2.7190# - in system32,191# - ortherwise (Sxs), I don't know how to get it.192stems = [sys.prefix]193if hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix:194stems.append(sys.base_prefix)195elif hasattr(sys, 'real_prefix') and sys.real_prefix != sys.prefix:196stems.append(sys.real_prefix)197198sub_dirs = ['', 'lib', 'bin']199# generate possible combinations of directory trees and sub-directories200lib_dirs = []201for stem in stems:202for folder in sub_dirs:203lib_dirs.append(os.path.join(stem, folder))204205# add system directory as well206if 'SYSTEMROOT' in os.environ:207lib_dirs.append(os.path.join(os.environ['SYSTEMROOT'], 'System32'))208209# search in the file system for possible candidates210major_version, minor_version = tuple(sys.version_info[:2])211implementation = platform.python_implementation()212if implementation == 'CPython':213dllname = f'python{major_version}{minor_version}.dll'214elif implementation == 'PyPy':215dllname = f'libpypy{major_version}-c.dll'216else:217dllname = 'Unknown platform {implementation}'218print("Looking for %s" % dllname)219for folder in lib_dirs:220dll = os.path.join(folder, dllname)221if os.path.exists(dll):222return dll223224raise ValueError("%s not found in %s" % (dllname, lib_dirs))225226def dump_table(dll):227st = subprocess.check_output(["objdump.exe", "-p", dll])228return st.split(b'\n')229230def generate_def(dll, dfile):231"""Given a dll file location, get all its exported symbols and dump them232into the given def file.233234The .def file will be overwritten"""235dump = dump_table(dll)236for i in range(len(dump)):237if _START.match(dump[i].decode()):238break239else:240raise ValueError("Symbol table not found")241242syms = []243for j in range(i+1, len(dump)):244m = _TABLE.match(dump[j].decode())245if m:246syms.append((int(m.group(1).strip()), m.group(2)))247else:248break249250if len(syms) == 0:251log.warn('No symbols found in %s' % dll)252253with open(dfile, 'w') as d:254d.write('LIBRARY %s\n' % os.path.basename(dll))255d.write(';CODE PRELOAD MOVEABLE DISCARDABLE\n')256d.write(';DATA PRELOAD SINGLE\n')257d.write('\nEXPORTS\n')258for s in syms:259#d.write('@%d %s\n' % (s[0], s[1]))260d.write('%s\n' % s[1])261262def find_dll(dll_name):263264arch = {'AMD64' : 'amd64',265'Intel' : 'x86'}[get_build_architecture()]266267def _find_dll_in_winsxs(dll_name):268# Walk through the WinSxS directory to find the dll.269winsxs_path = os.path.join(os.environ.get('WINDIR', r'C:\WINDOWS'),270'winsxs')271if not os.path.exists(winsxs_path):272return None273for root, dirs, files in os.walk(winsxs_path):274if dll_name in files and arch in root:275return os.path.join(root, dll_name)276return None277278def _find_dll_in_path(dll_name):279# First, look in the Python directory, then scan PATH for280# the given dll name.281for path in [sys.prefix] + os.environ['PATH'].split(';'):282filepath = os.path.join(path, dll_name)283if os.path.exists(filepath):284return os.path.abspath(filepath)285286return _find_dll_in_winsxs(dll_name) or _find_dll_in_path(dll_name)287288def build_msvcr_library(debug=False):289if os.name != 'nt':290return False291292# If the version number is None, then we couldn't find the MSVC runtime at293# all, because we are running on a Python distribution which is customed294# compiled; trust that the compiler is the same as the one available to us295# now, and that it is capable of linking with the correct runtime without296# any extra options.297msvcr_ver = msvc_runtime_major()298if msvcr_ver is None:299log.debug('Skip building import library: '300'Runtime is not compiled with MSVC')301return False302303# Skip using a custom library for versions < MSVC 8.0304if msvcr_ver < 80:305log.debug('Skip building msvcr library:'306' custom functionality not present')307return False308309msvcr_name = msvc_runtime_library()310if debug:311msvcr_name += 'd'312313# Skip if custom library already exists314out_name = "lib%s.a" % msvcr_name315out_file = os.path.join(sys.prefix, 'libs', out_name)316if os.path.isfile(out_file):317log.debug('Skip building msvcr library: "%s" exists' %318(out_file,))319return True320321# Find the msvcr dll322msvcr_dll_name = msvcr_name + '.dll'323dll_file = find_dll(msvcr_dll_name)324if not dll_file:325log.warn('Cannot build msvcr library: "%s" not found' %326msvcr_dll_name)327return False328329def_name = "lib%s.def" % msvcr_name330def_file = os.path.join(sys.prefix, 'libs', def_name)331332log.info('Building msvcr library: "%s" (from %s)' \333% (out_file, dll_file))334335# Generate a symbol definition file from the msvcr dll336generate_def(dll_file, def_file)337338# Create a custom mingw library for the given symbol definitions339cmd = ['dlltool', '-d', def_file, '-l', out_file]340retcode = subprocess.call(cmd)341342# Clean up symbol definitions343os.remove(def_file)344345return (not retcode)346347def build_import_library():348if os.name != 'nt':349return350351arch = get_build_architecture()352if arch == 'AMD64':353return _build_import_library_amd64()354elif arch == 'Intel':355return _build_import_library_x86()356else:357raise ValueError("Unhandled arch %s" % arch)358359def _check_for_import_lib():360"""Check if an import library for the Python runtime already exists."""361major_version, minor_version = tuple(sys.version_info[:2])362363# patterns for the file name of the library itself364patterns = ['libpython%d%d.a',365'libpython%d%d.dll.a',366'libpython%d.%d.dll.a']367368# directory trees that may contain the library369stems = [sys.prefix]370if hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix:371stems.append(sys.base_prefix)372elif hasattr(sys, 'real_prefix') and sys.real_prefix != sys.prefix:373stems.append(sys.real_prefix)374375# possible subdirectories within those trees where it is placed376sub_dirs = ['libs', 'lib']377378# generate a list of candidate locations379candidates = []380for pat in patterns:381filename = pat % (major_version, minor_version)382for stem_dir in stems:383for folder in sub_dirs:384candidates.append(os.path.join(stem_dir, folder, filename))385386# test the filesystem to see if we can find any of these387for fullname in candidates:388if os.path.isfile(fullname):389# already exists, in location given390return (True, fullname)391392# needs to be built, preferred location given first393return (False, candidates[0])394395def _build_import_library_amd64():396out_exists, out_file = _check_for_import_lib()397if out_exists:398log.debug('Skip building import library: "%s" exists', out_file)399return400401# get the runtime dll for which we are building import library402dll_file = find_python_dll()403log.info('Building import library (arch=AMD64): "%s" (from %s)' %404(out_file, dll_file))405406# generate symbol list from this library407def_name = "python%d%d.def" % tuple(sys.version_info[:2])408def_file = os.path.join(sys.prefix, 'libs', def_name)409generate_def(dll_file, def_file)410411# generate import library from this symbol list412cmd = ['dlltool', '-d', def_file, '-l', out_file]413subprocess.check_call(cmd)414415def _build_import_library_x86():416""" Build the import libraries for Mingw32-gcc on Windows417"""418out_exists, out_file = _check_for_import_lib()419if out_exists:420log.debug('Skip building import library: "%s" exists', out_file)421return422423lib_name = "python%d%d.lib" % tuple(sys.version_info[:2])424lib_file = os.path.join(sys.prefix, 'libs', lib_name)425if not os.path.isfile(lib_file):426# didn't find library file in virtualenv, try base distribution, too,427# and use that instead if found there. for Python 2.7 venvs, the base428# directory is in attribute real_prefix instead of base_prefix.429if hasattr(sys, 'base_prefix'):430base_lib = os.path.join(sys.base_prefix, 'libs', lib_name)431elif hasattr(sys, 'real_prefix'):432base_lib = os.path.join(sys.real_prefix, 'libs', lib_name)433else:434base_lib = '' # os.path.isfile('') == False435436if os.path.isfile(base_lib):437lib_file = base_lib438else:439log.warn('Cannot build import library: "%s" not found', lib_file)440return441log.info('Building import library (ARCH=x86): "%s"', out_file)442443from numpy.distutils import lib2def444445def_name = "python%d%d.def" % tuple(sys.version_info[:2])446def_file = os.path.join(sys.prefix, 'libs', def_name)447nm_output = lib2def.getnm(448lib2def.DEFAULT_NM + [lib_file], shell=False)449dlist, flist = lib2def.parse_nm(nm_output)450with open(def_file, 'w') as fid:451lib2def.output_def(dlist, flist, lib2def.DEF_HEADER, fid)452453dll_name = find_python_dll ()454455cmd = ["dlltool",456"--dllname", dll_name,457"--def", def_file,458"--output-lib", out_file]459status = subprocess.check_output(cmd)460if status:461log.warn('Failed to build import library for gcc. Linking will fail.')462return463464#=====================================465# Dealing with Visual Studio MANIFESTS466#=====================================467468# Functions to deal with visual studio manifests. Manifest are a mechanism to469# enforce strong DLL versioning on windows, and has nothing to do with470# distutils MANIFEST. manifests are XML files with version info, and used by471# the OS loader; they are necessary when linking against a DLL not in the472# system path; in particular, official python 2.6 binary is built against the473# MS runtime 9 (the one from VS 2008), which is not available on most windows474# systems; python 2.6 installer does install it in the Win SxS (Side by side)475# directory, but this requires the manifest for this to work. This is a big476# mess, thanks MS for a wonderful system.477478# XXX: ideally, we should use exactly the same version as used by python. I479# submitted a patch to get this version, but it was only included for python480# 2.6.1 and above. So for versions below, we use a "best guess".481_MSVCRVER_TO_FULLVER = {}482if sys.platform == 'win32':483try:484import msvcrt485# I took one version in my SxS directory: no idea if it is the good486# one, and we can't retrieve it from python487_MSVCRVER_TO_FULLVER['80'] = "8.0.50727.42"488_MSVCRVER_TO_FULLVER['90'] = "9.0.21022.8"489# Value from msvcrt.CRT_ASSEMBLY_VERSION under Python 3.3.0490# on Windows XP:491_MSVCRVER_TO_FULLVER['100'] = "10.0.30319.460"492crt_ver = getattr(msvcrt, 'CRT_ASSEMBLY_VERSION', None)493if crt_ver is not None: # Available at least back to Python 3.3494maj, min = re.match(r'(\d+)\.(\d)', crt_ver).groups()495_MSVCRVER_TO_FULLVER[maj + min] = crt_ver496del maj, min497del crt_ver498except ImportError:499# If we are here, means python was not built with MSVC. Not sure what500# to do in that case: manifest building will fail, but it should not be501# used in that case anyway502log.warn('Cannot import msvcrt: using manifest will not be possible')503504def msvc_manifest_xml(maj, min):505"""Given a major and minor version of the MSVCR, returns the506corresponding XML file."""507try:508fullver = _MSVCRVER_TO_FULLVER[str(maj * 10 + min)]509except KeyError:510raise ValueError("Version %d,%d of MSVCRT not supported yet" %511(maj, min)) from None512# Don't be fooled, it looks like an XML, but it is not. In particular, it513# should not have any space before starting, and its size should be514# divisible by 4, most likely for alignment constraints when the xml is515# embedded in the binary...516# This template was copied directly from the python 2.6 binary (using517# strings.exe from mingw on python.exe).518template = textwrap.dedent("""\519<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">520<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">521<security>522<requestedPrivileges>523<requestedExecutionLevel level="asInvoker" uiAccess="false"></requestedExecutionLevel>524</requestedPrivileges>525</security>526</trustInfo>527<dependency>528<dependentAssembly>529<assemblyIdentity type="win32" name="Microsoft.VC%(maj)d%(min)d.CRT" version="%(fullver)s" processorArchitecture="*" publicKeyToken="1fc8b3b9a1e18e3b"></assemblyIdentity>530</dependentAssembly>531</dependency>532</assembly>""")533534return template % {'fullver': fullver, 'maj': maj, 'min': min}535536def manifest_rc(name, type='dll'):537"""Return the rc file used to generate the res file which will be embedded538as manifest for given manifest file name, of given type ('dll' or539'exe').540541Parameters542----------543name : str544name of the manifest file to embed545type : str {'dll', 'exe'}546type of the binary which will embed the manifest547548"""549if type == 'dll':550rctype = 2551elif type == 'exe':552rctype = 1553else:554raise ValueError("Type %s not supported" % type)555556return """\557#include "winuser.h"558%d RT_MANIFEST %s""" % (rctype, name)559560def check_embedded_msvcr_match_linked(msver):561"""msver is the ms runtime version used for the MANIFEST."""562# check msvcr major version are the same for linking and563# embedding564maj = msvc_runtime_major()565if maj:566if not maj == int(msver):567raise ValueError(568"Discrepancy between linked msvcr " \569"(%d) and the one about to be embedded " \570"(%d)" % (int(msver), maj))571572def configtest_name(config):573base = os.path.basename(config._gen_temp_sourcefile("yo", [], "c"))574return os.path.splitext(base)[0]575576def manifest_name(config):577# Get configest name (including suffix)578root = configtest_name(config)579exext = config.compiler.exe_extension580return root + exext + ".manifest"581582def rc_name(config):583# Get configtest name (including suffix)584root = configtest_name(config)585return root + ".rc"586587def generate_manifest(config):588msver = get_build_msvc_version()589if msver is not None:590if msver >= 8:591check_embedded_msvcr_match_linked(msver)592ma_str, mi_str = str(msver).split('.')593# Write the manifest file594manxml = msvc_manifest_xml(int(ma_str), int(mi_str))595with open(manifest_name(config), "w") as man:596config.temp_files.append(manifest_name(config))597man.write(manxml)598599600