mingw32ccompiler.py 25 KB

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