mingw32ccompiler.py 22 KB

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