mingw32ccompiler.py 25 KB

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