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