mingw32ccompiler.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. """
  2. Support code for building Python extensions on Windows.
  3. # NT stuff
  4. # 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 g77
  7. """
  8. import os
  9. import platform
  10. import sys
  11. import subprocess
  12. import re
  13. import textwrap
  14. # Overwrite certain distutils.ccompiler functions:
  15. import numpy.distutils.ccompiler # noqa: F401
  16. from numpy.distutils import log
  17. # NT stuff
  18. # 1. Make sure libpython<version>.a exists for gcc. If not, build it.
  19. # 2. Force windows to use gcc (we're struggling with MSVC and g77 support)
  20. # --> this is done in numpy/distutils/ccompiler.py
  21. # 3. Force windows to use g77
  22. import distutils.cygwinccompiler
  23. from distutils.unixccompiler import UnixCCompiler
  24. from distutils.msvccompiler import get_build_version as get_build_msvc_version
  25. from distutils.errors import UnknownFileError
  26. from numpy.distutils.misc_util import (msvc_runtime_library,
  27. msvc_runtime_version,
  28. msvc_runtime_major,
  29. get_build_architecture)
  30. def get_msvcr_replacement():
  31. """Replacement for outdated version of get_msvcr from cygwinccompiler"""
  32. msvcr = msvc_runtime_library()
  33. return [] if msvcr is None else [msvcr]
  34. # Useful to generate table of symbols from a dll
  35. _START = re.compile(r'\[Ordinal/Name Pointer\] Table')
  36. _TABLE = re.compile(r'^\s+\[([\s*[0-9]*)\] ([a-zA-Z0-9_]*)')
  37. # the same as cygwin plus some additional parameters
  38. class Mingw32CCompiler(distutils.cygwinccompiler.CygwinCCompiler):
  39. """ A modified MingW32 compiler compatible with an MSVC built Python.
  40. """
  41. compiler_type = 'mingw32'
  42. def __init__ (self,
  43. verbose=0,
  44. dry_run=0,
  45. force=0):
  46. distutils.cygwinccompiler.CygwinCCompiler.__init__ (self, verbose,
  47. dry_run, force)
  48. # **changes: eric jones 4/11/01
  49. # 1. Check for import library on Windows. Build if it doesn't exist.
  50. build_import_library()
  51. # Check for custom msvc runtime library on Windows. Build if it doesn't exist.
  52. msvcr_success = build_msvcr_library()
  53. msvcr_dbg_success = build_msvcr_library(debug=True)
  54. if msvcr_success or msvcr_dbg_success:
  55. # add preprocessor statement for using customized msvcr lib
  56. self.define_macro('NPY_MINGW_USE_CUSTOM_MSVCR')
  57. # Define the MSVC version as hint for MinGW
  58. msvcr_version = msvc_runtime_version()
  59. if msvcr_version:
  60. self.define_macro('__MSVCRT_VERSION__', '0x%04i' % msvcr_version)
  61. # MS_WIN64 should be defined when building for amd64 on windows,
  62. # but python headers define it only for MS compilers, which has all
  63. # kind of bad consequences, like using Py_ModuleInit4 instead of
  64. # Py_ModuleInit4_64, etc... So we add it here
  65. if get_build_architecture() == 'AMD64':
  66. self.set_executables(
  67. compiler='gcc -g -DDEBUG -DMS_WIN64 -O0 -Wall',
  68. compiler_so='gcc -g -DDEBUG -DMS_WIN64 -O0 -Wall '
  69. '-Wstrict-prototypes',
  70. linker_exe='gcc -g',
  71. linker_so='gcc -g -shared')
  72. else:
  73. self.set_executables(
  74. compiler='gcc -O2 -Wall',
  75. compiler_so='gcc -O2 -Wall -Wstrict-prototypes',
  76. linker_exe='g++ ',
  77. linker_so='g++ -shared')
  78. # added for python2.3 support
  79. # we can't pass it through set_executables because pre 2.2 would fail
  80. self.compiler_cxx = ['g++']
  81. # Maybe we should also append -mthreads, but then the finished dlls
  82. # need another dll (mingwm10.dll see Mingw32 docs) (-mthreads: Support
  83. # thread-safe exception handling on `Mingw32')
  84. # no additional libraries needed
  85. #self.dll_libraries=[]
  86. return
  87. # __init__ ()
  88. def link(self,
  89. target_desc,
  90. objects,
  91. output_filename,
  92. output_dir,
  93. libraries,
  94. library_dirs,
  95. runtime_library_dirs,
  96. export_symbols = None,
  97. debug=0,
  98. extra_preargs=None,
  99. extra_postargs=None,
  100. build_temp=None,
  101. target_lang=None):
  102. # Include the appropriate MSVC runtime library if Python was built
  103. # with MSVC >= 7.0 (MinGW standard is msvcrt)
  104. runtime_library = msvc_runtime_library()
  105. if runtime_library:
  106. if not libraries:
  107. libraries = []
  108. libraries.append(runtime_library)
  109. args = (self,
  110. target_desc,
  111. objects,
  112. output_filename,
  113. output_dir,
  114. libraries,
  115. library_dirs,
  116. runtime_library_dirs,
  117. None, #export_symbols, we do this in our def-file
  118. debug,
  119. extra_preargs,
  120. extra_postargs,
  121. build_temp,
  122. target_lang)
  123. func = UnixCCompiler.link
  124. func(*args[:func.__code__.co_argcount])
  125. return
  126. def object_filenames (self,
  127. source_filenames,
  128. strip_dir=0,
  129. output_dir=''):
  130. if output_dir is None: output_dir = ''
  131. obj_names = []
  132. for src_name in source_filenames:
  133. # use normcase to make sure '.rc' is really '.rc' and not '.RC'
  134. (base, ext) = os.path.splitext (os.path.normcase(src_name))
  135. # added these lines to strip off windows drive letters
  136. # without it, .o files are placed next to .c files
  137. # instead of the build directory
  138. drv, base = os.path.splitdrive(base)
  139. if drv:
  140. base = base[1:]
  141. if ext not in (self.src_extensions + ['.rc', '.res']):
  142. raise UnknownFileError(
  143. "unknown file type '%s' (from '%s')" % \
  144. (ext, src_name))
  145. if strip_dir:
  146. base = os.path.basename (base)
  147. if ext == '.res' or ext == '.rc':
  148. # these need to be compiled to object files
  149. obj_names.append (os.path.join (output_dir,
  150. base + ext + self.obj_extension))
  151. else:
  152. obj_names.append (os.path.join (output_dir,
  153. base + self.obj_extension))
  154. return obj_names
  155. # object_filenames ()
  156. def find_python_dll():
  157. # We can't do much here:
  158. # - find it in the virtualenv (sys.prefix)
  159. # - find it in python main dir (sys.base_prefix, if in a virtualenv)
  160. # - in system32,
  161. # - ortherwise (Sxs), I don't know how to get it.
  162. stems = [sys.prefix]
  163. if sys.base_prefix != sys.prefix:
  164. stems.append(sys.base_prefix)
  165. sub_dirs = ['', 'lib', 'bin']
  166. # generate possible combinations of directory trees and sub-directories
  167. lib_dirs = []
  168. for stem in stems:
  169. for folder in sub_dirs:
  170. lib_dirs.append(os.path.join(stem, folder))
  171. # add system directory as well
  172. if 'SYSTEMROOT' in os.environ:
  173. lib_dirs.append(os.path.join(os.environ['SYSTEMROOT'], 'System32'))
  174. # search in the file system for possible candidates
  175. major_version, minor_version = tuple(sys.version_info[:2])
  176. implementation = platform.python_implementation()
  177. if implementation == 'CPython':
  178. dllname = f'python{major_version}{minor_version}.dll'
  179. elif implementation == 'PyPy':
  180. dllname = f'libpypy{major_version}-c.dll'
  181. else:
  182. dllname = f'Unknown platform {implementation}'
  183. print("Looking for %s" % dllname)
  184. for folder in lib_dirs:
  185. dll = os.path.join(folder, dllname)
  186. if os.path.exists(dll):
  187. return dll
  188. raise ValueError("%s not found in %s" % (dllname, lib_dirs))
  189. def dump_table(dll):
  190. st = subprocess.check_output(["objdump.exe", "-p", dll])
  191. return st.split(b'\n')
  192. def generate_def(dll, dfile):
  193. """Given a dll file location, get all its exported symbols and dump them
  194. into the given def file.
  195. The .def file will be overwritten"""
  196. dump = dump_table(dll)
  197. for i in range(len(dump)):
  198. if _START.match(dump[i].decode()):
  199. break
  200. else:
  201. raise ValueError("Symbol table not found")
  202. syms = []
  203. for j in range(i+1, len(dump)):
  204. m = _TABLE.match(dump[j].decode())
  205. if m:
  206. syms.append((int(m.group(1).strip()), m.group(2)))
  207. else:
  208. break
  209. if len(syms) == 0:
  210. log.warn('No symbols found in %s' % dll)
  211. with open(dfile, 'w') as d:
  212. d.write('LIBRARY %s\n' % os.path.basename(dll))
  213. d.write(';CODE PRELOAD MOVEABLE DISCARDABLE\n')
  214. d.write(';DATA PRELOAD SINGLE\n')
  215. d.write('\nEXPORTS\n')
  216. for s in syms:
  217. #d.write('@%d %s\n' % (s[0], s[1]))
  218. d.write('%s\n' % s[1])
  219. def find_dll(dll_name):
  220. arch = {'AMD64' : 'amd64',
  221. 'Intel' : 'x86'}[get_build_architecture()]
  222. def _find_dll_in_winsxs(dll_name):
  223. # Walk through the WinSxS directory to find the dll.
  224. winsxs_path = os.path.join(os.environ.get('WINDIR', r'C:\WINDOWS'),
  225. 'winsxs')
  226. if not os.path.exists(winsxs_path):
  227. return None
  228. for root, dirs, files in os.walk(winsxs_path):
  229. if dll_name in files and arch in root:
  230. return os.path.join(root, dll_name)
  231. return None
  232. def _find_dll_in_path(dll_name):
  233. # First, look in the Python directory, then scan PATH for
  234. # the given dll name.
  235. for path in [sys.prefix] + os.environ['PATH'].split(';'):
  236. filepath = os.path.join(path, dll_name)
  237. if os.path.exists(filepath):
  238. return os.path.abspath(filepath)
  239. return _find_dll_in_winsxs(dll_name) or _find_dll_in_path(dll_name)
  240. def build_msvcr_library(debug=False):
  241. if os.name != 'nt':
  242. return False
  243. # If the version number is None, then we couldn't find the MSVC runtime at
  244. # all, because we are running on a Python distribution which is customed
  245. # compiled; trust that the compiler is the same as the one available to us
  246. # now, and that it is capable of linking with the correct runtime without
  247. # any extra options.
  248. msvcr_ver = msvc_runtime_major()
  249. if msvcr_ver is None:
  250. log.debug('Skip building import library: '
  251. 'Runtime is not compiled with MSVC')
  252. return False
  253. # Skip using a custom library for versions < MSVC 8.0
  254. if msvcr_ver < 80:
  255. log.debug('Skip building msvcr library:'
  256. ' custom functionality not present')
  257. return False
  258. msvcr_name = msvc_runtime_library()
  259. if debug:
  260. msvcr_name += 'd'
  261. # Skip if custom library already exists
  262. out_name = "lib%s.a" % msvcr_name
  263. out_file = os.path.join(sys.prefix, 'libs', out_name)
  264. if os.path.isfile(out_file):
  265. log.debug('Skip building msvcr library: "%s" exists' %
  266. (out_file,))
  267. return True
  268. # Find the msvcr dll
  269. msvcr_dll_name = msvcr_name + '.dll'
  270. dll_file = find_dll(msvcr_dll_name)
  271. if not dll_file:
  272. log.warn('Cannot build msvcr library: "%s" not found' %
  273. msvcr_dll_name)
  274. return False
  275. def_name = "lib%s.def" % msvcr_name
  276. def_file = os.path.join(sys.prefix, 'libs', def_name)
  277. log.info('Building msvcr library: "%s" (from %s)' \
  278. % (out_file, dll_file))
  279. # Generate a symbol definition file from the msvcr dll
  280. generate_def(dll_file, def_file)
  281. # Create a custom mingw library for the given symbol definitions
  282. cmd = ['dlltool', '-d', def_file, '-l', out_file]
  283. retcode = subprocess.call(cmd)
  284. # Clean up symbol definitions
  285. os.remove(def_file)
  286. return (not retcode)
  287. def build_import_library():
  288. if os.name != 'nt':
  289. return
  290. arch = get_build_architecture()
  291. if arch == 'AMD64':
  292. return _build_import_library_amd64()
  293. elif arch == 'Intel':
  294. return _build_import_library_x86()
  295. else:
  296. raise ValueError("Unhandled arch %s" % arch)
  297. def _check_for_import_lib():
  298. """Check if an import library for the Python runtime already exists."""
  299. major_version, minor_version = tuple(sys.version_info[:2])
  300. # patterns for the file name of the library itself
  301. patterns = ['libpython%d%d.a',
  302. 'libpython%d%d.dll.a',
  303. 'libpython%d.%d.dll.a']
  304. # directory trees that may contain the library
  305. stems = [sys.prefix]
  306. if hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix:
  307. stems.append(sys.base_prefix)
  308. elif hasattr(sys, 'real_prefix') and sys.real_prefix != sys.prefix:
  309. stems.append(sys.real_prefix)
  310. # possible subdirectories within those trees where it is placed
  311. sub_dirs = ['libs', 'lib']
  312. # generate a list of candidate locations
  313. candidates = []
  314. for pat in patterns:
  315. filename = pat % (major_version, minor_version)
  316. for stem_dir in stems:
  317. for folder in sub_dirs:
  318. candidates.append(os.path.join(stem_dir, folder, filename))
  319. # test the filesystem to see if we can find any of these
  320. for fullname in candidates:
  321. if os.path.isfile(fullname):
  322. # already exists, in location given
  323. return (True, fullname)
  324. # needs to be built, preferred location given first
  325. return (False, candidates[0])
  326. def _build_import_library_amd64():
  327. out_exists, out_file = _check_for_import_lib()
  328. if out_exists:
  329. log.debug('Skip building import library: "%s" exists', out_file)
  330. return
  331. # get the runtime dll for which we are building import library
  332. dll_file = find_python_dll()
  333. log.info('Building import library (arch=AMD64): "%s" (from %s)' %
  334. (out_file, dll_file))
  335. # generate symbol list from this library
  336. def_name = "python%d%d.def" % tuple(sys.version_info[:2])
  337. def_file = os.path.join(sys.prefix, 'libs', def_name)
  338. generate_def(dll_file, def_file)
  339. # generate import library from this symbol list
  340. cmd = ['dlltool', '-d', def_file, '-l', out_file]
  341. subprocess.check_call(cmd)
  342. def _build_import_library_x86():
  343. """ Build the import libraries for Mingw32-gcc on Windows
  344. """
  345. out_exists, out_file = _check_for_import_lib()
  346. if out_exists:
  347. log.debug('Skip building import library: "%s" exists', out_file)
  348. return
  349. lib_name = "python%d%d.lib" % tuple(sys.version_info[:2])
  350. lib_file = os.path.join(sys.prefix, 'libs', lib_name)
  351. if not os.path.isfile(lib_file):
  352. # didn't find library file in virtualenv, try base distribution, too,
  353. # and use that instead if found there. for Python 2.7 venvs, the base
  354. # directory is in attribute real_prefix instead of base_prefix.
  355. if hasattr(sys, 'base_prefix'):
  356. base_lib = os.path.join(sys.base_prefix, 'libs', lib_name)
  357. elif hasattr(sys, 'real_prefix'):
  358. base_lib = os.path.join(sys.real_prefix, 'libs', lib_name)
  359. else:
  360. base_lib = '' # os.path.isfile('') == False
  361. if os.path.isfile(base_lib):
  362. lib_file = base_lib
  363. else:
  364. log.warn('Cannot build import library: "%s" not found', lib_file)
  365. return
  366. log.info('Building import library (ARCH=x86): "%s"', out_file)
  367. from numpy.distutils import lib2def
  368. def_name = "python%d%d.def" % tuple(sys.version_info[:2])
  369. def_file = os.path.join(sys.prefix, 'libs', def_name)
  370. nm_output = lib2def.getnm(
  371. lib2def.DEFAULT_NM + [lib_file], shell=False)
  372. dlist, flist = lib2def.parse_nm(nm_output)
  373. with open(def_file, 'w') as fid:
  374. lib2def.output_def(dlist, flist, lib2def.DEF_HEADER, fid)
  375. dll_name = find_python_dll ()
  376. cmd = ["dlltool",
  377. "--dllname", dll_name,
  378. "--def", def_file,
  379. "--output-lib", out_file]
  380. status = subprocess.check_output(cmd)
  381. if status:
  382. log.warn('Failed to build import library for gcc. Linking will fail.')
  383. return
  384. #=====================================
  385. # Dealing with Visual Studio MANIFESTS
  386. #=====================================
  387. # Functions to deal with visual studio manifests. Manifest are a mechanism to
  388. # enforce strong DLL versioning on windows, and has nothing to do with
  389. # distutils MANIFEST. manifests are XML files with version info, and used by
  390. # the OS loader; they are necessary when linking against a DLL not in the
  391. # system path; in particular, official python 2.6 binary is built against the
  392. # MS runtime 9 (the one from VS 2008), which is not available on most windows
  393. # systems; python 2.6 installer does install it in the Win SxS (Side by side)
  394. # directory, but this requires the manifest for this to work. This is a big
  395. # mess, thanks MS for a wonderful system.
  396. # XXX: ideally, we should use exactly the same version as used by python. I
  397. # submitted a patch to get this version, but it was only included for python
  398. # 2.6.1 and above. So for versions below, we use a "best guess".
  399. _MSVCRVER_TO_FULLVER = {}
  400. if sys.platform == 'win32':
  401. try:
  402. import msvcrt
  403. # I took one version in my SxS directory: no idea if it is the good
  404. # one, and we can't retrieve it from python
  405. _MSVCRVER_TO_FULLVER['80'] = "8.0.50727.42"
  406. _MSVCRVER_TO_FULLVER['90'] = "9.0.21022.8"
  407. # Value from msvcrt.CRT_ASSEMBLY_VERSION under Python 3.3.0
  408. # on Windows XP:
  409. _MSVCRVER_TO_FULLVER['100'] = "10.0.30319.460"
  410. crt_ver = getattr(msvcrt, 'CRT_ASSEMBLY_VERSION', None)
  411. if crt_ver is not None: # Available at least back to Python 3.3
  412. maj, min = re.match(r'(\d+)\.(\d)', crt_ver).groups()
  413. _MSVCRVER_TO_FULLVER[maj + min] = crt_ver
  414. del maj, min
  415. del crt_ver
  416. except ImportError:
  417. # If we are here, means python was not built with MSVC. Not sure what
  418. # to do in that case: manifest building will fail, but it should not be
  419. # used in that case anyway
  420. log.warn('Cannot import msvcrt: using manifest will not be possible')
  421. def msvc_manifest_xml(maj, min):
  422. """Given a major and minor version of the MSVCR, returns the
  423. corresponding XML file."""
  424. try:
  425. fullver = _MSVCRVER_TO_FULLVER[str(maj * 10 + min)]
  426. except KeyError:
  427. raise ValueError("Version %d,%d of MSVCRT not supported yet" %
  428. (maj, min)) from None
  429. # Don't be fooled, it looks like an XML, but it is not. In particular, it
  430. # should not have any space before starting, and its size should be
  431. # divisible by 4, most likely for alignment constraints when the xml is
  432. # embedded in the binary...
  433. # This template was copied directly from the python 2.6 binary (using
  434. # strings.exe from mingw on python.exe).
  435. template = textwrap.dedent("""\
  436. <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  437. <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
  438. <security>
  439. <requestedPrivileges>
  440. <requestedExecutionLevel level="asInvoker" uiAccess="false"></requestedExecutionLevel>
  441. </requestedPrivileges>
  442. </security>
  443. </trustInfo>
  444. <dependency>
  445. <dependentAssembly>
  446. <assemblyIdentity type="win32" name="Microsoft.VC%(maj)d%(min)d.CRT" version="%(fullver)s" processorArchitecture="*" publicKeyToken="1fc8b3b9a1e18e3b"></assemblyIdentity>
  447. </dependentAssembly>
  448. </dependency>
  449. </assembly>""")
  450. return template % {'fullver': fullver, 'maj': maj, 'min': min}
  451. def manifest_rc(name, type='dll'):
  452. """Return the rc file used to generate the res file which will be embedded
  453. as manifest for given manifest file name, of given type ('dll' or
  454. 'exe').
  455. Parameters
  456. ----------
  457. name : str
  458. name of the manifest file to embed
  459. type : str {'dll', 'exe'}
  460. type of the binary which will embed the manifest
  461. """
  462. if type == 'dll':
  463. rctype = 2
  464. elif type == 'exe':
  465. rctype = 1
  466. else:
  467. raise ValueError("Type %s not supported" % type)
  468. return """\
  469. #include "winuser.h"
  470. %d RT_MANIFEST %s""" % (rctype, name)
  471. def check_embedded_msvcr_match_linked(msver):
  472. """msver is the ms runtime version used for the MANIFEST."""
  473. # check msvcr major version are the same for linking and
  474. # embedding
  475. maj = msvc_runtime_major()
  476. if maj:
  477. if not maj == int(msver):
  478. raise ValueError(
  479. "Discrepancy between linked msvcr " \
  480. "(%d) and the one about to be embedded " \
  481. "(%d)" % (int(msver), maj))
  482. def configtest_name(config):
  483. base = os.path.basename(config._gen_temp_sourcefile("yo", [], "c"))
  484. return os.path.splitext(base)[0]
  485. def manifest_name(config):
  486. # Get configest name (including suffix)
  487. root = configtest_name(config)
  488. exext = config.compiler.exe_extension
  489. return root + exext + ".manifest"
  490. def rc_name(config):
  491. # Get configtest name (including suffix)
  492. root = configtest_name(config)
  493. return root + ".rc"
  494. def generate_manifest(config):
  495. msver = get_build_msvc_version()
  496. if msver is not None:
  497. if msver >= 8:
  498. check_embedded_msvcr_match_linked(msver)
  499. ma_str, mi_str = str(msver).split('.')
  500. # Write the manifest file
  501. manxml = msvc_manifest_xml(int(ma_str), int(mi_str))
  502. with open(manifest_name(config), "w") as man:
  503. config.temp_files.append(manifest_name(config))
  504. man.write(manxml)