mingw32ccompiler.py 21 KB

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