msvc9compiler.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. """distutils.msvc9compiler
  2. Contains MSVCCompiler, an implementation of the abstract CCompiler class
  3. for the Microsoft Visual Studio 2008.
  4. The module is compatible with VS 2005 and VS 2008. You can find legacy support
  5. for older versions of VS in distutils.msvccompiler.
  6. """
  7. # Written by Perry Stoll
  8. # hacked by Robin Becker and Thomas Heller to do a better job of
  9. # finding DevStudio (through the registry)
  10. # ported to VS2005 and VS 2008 by Christian Heimes
  11. import os
  12. import subprocess
  13. import sys
  14. import re
  15. from distutils.errors import DistutilsExecError, DistutilsPlatformError, \
  16. CompileError, LibError, LinkError
  17. from distutils.ccompiler import CCompiler, gen_preprocess_options, \
  18. gen_lib_options
  19. from distutils import log
  20. from distutils.util import get_platform
  21. import winreg
  22. RegOpenKeyEx = winreg.OpenKeyEx
  23. RegEnumKey = winreg.EnumKey
  24. RegEnumValue = winreg.EnumValue
  25. RegError = winreg.error
  26. HKEYS = (winreg.HKEY_USERS,
  27. winreg.HKEY_CURRENT_USER,
  28. winreg.HKEY_LOCAL_MACHINE,
  29. winreg.HKEY_CLASSES_ROOT)
  30. NATIVE_WIN64 = (sys.platform == 'win32' and sys.maxsize > 2**32)
  31. if NATIVE_WIN64:
  32. # Visual C++ is a 32-bit application, so we need to look in
  33. # the corresponding registry branch, if we're running a
  34. # 64-bit Python on Win64
  35. VS_BASE = r"Software\Wow6432Node\Microsoft\VisualStudio\%0.1f"
  36. WINSDK_BASE = r"Software\Wow6432Node\Microsoft\Microsoft SDKs\Windows"
  37. NET_BASE = r"Software\Wow6432Node\Microsoft\.NETFramework"
  38. else:
  39. VS_BASE = r"Software\Microsoft\VisualStudio\%0.1f"
  40. WINSDK_BASE = r"Software\Microsoft\Microsoft SDKs\Windows"
  41. NET_BASE = r"Software\Microsoft\.NETFramework"
  42. # A map keyed by get_platform() return values to values accepted by
  43. # 'vcvarsall.bat'. Note a cross-compile may combine these (eg, 'x86_amd64' is
  44. # the param to cross-compile on x86 targeting amd64.)
  45. PLAT_TO_VCVARS = {
  46. 'win32' : 'x86',
  47. 'win-amd64' : 'amd64',
  48. 'win-ia64' : 'ia64',
  49. }
  50. class Reg:
  51. """Helper class to read values from the registry
  52. """
  53. def get_value(cls, path, key):
  54. for base in HKEYS:
  55. d = cls.read_values(base, path)
  56. if d and key in d:
  57. return d[key]
  58. raise KeyError(key)
  59. get_value = classmethod(get_value)
  60. def read_keys(cls, base, key):
  61. """Return list of registry keys."""
  62. try:
  63. handle = RegOpenKeyEx(base, key)
  64. except RegError:
  65. return None
  66. L = []
  67. i = 0
  68. while True:
  69. try:
  70. k = RegEnumKey(handle, i)
  71. except RegError:
  72. break
  73. L.append(k)
  74. i += 1
  75. return L
  76. read_keys = classmethod(read_keys)
  77. def read_values(cls, base, key):
  78. """Return dict of registry keys and values.
  79. All names are converted to lowercase.
  80. """
  81. try:
  82. handle = RegOpenKeyEx(base, key)
  83. except RegError:
  84. return None
  85. d = {}
  86. i = 0
  87. while True:
  88. try:
  89. name, value, type = RegEnumValue(handle, i)
  90. except RegError:
  91. break
  92. name = name.lower()
  93. d[cls.convert_mbcs(name)] = cls.convert_mbcs(value)
  94. i += 1
  95. return d
  96. read_values = classmethod(read_values)
  97. def convert_mbcs(s):
  98. dec = getattr(s, "decode", None)
  99. if dec is not None:
  100. try:
  101. s = dec("mbcs")
  102. except UnicodeError:
  103. pass
  104. return s
  105. convert_mbcs = staticmethod(convert_mbcs)
  106. class MacroExpander:
  107. def __init__(self, version):
  108. self.macros = {}
  109. self.vsbase = VS_BASE % version
  110. self.load_macros(version)
  111. def set_macro(self, macro, path, key):
  112. self.macros["$(%s)" % macro] = Reg.get_value(path, key)
  113. def load_macros(self, version):
  114. self.set_macro("VCInstallDir", self.vsbase + r"\Setup\VC", "productdir")
  115. self.set_macro("VSInstallDir", self.vsbase + r"\Setup\VS", "productdir")
  116. self.set_macro("FrameworkDir", NET_BASE, "installroot")
  117. try:
  118. if version >= 8.0:
  119. self.set_macro("FrameworkSDKDir", NET_BASE,
  120. "sdkinstallrootv2.0")
  121. else:
  122. raise KeyError("sdkinstallrootv2.0")
  123. except KeyError:
  124. raise DistutilsPlatformError(
  125. """Python was built with Visual Studio 2008;
  126. extensions must be built with a compiler than can generate compatible binaries.
  127. Visual Studio 2008 was not found on this system. If you have Cygwin installed,
  128. you can try compiling with MingW32, by passing "-c mingw32" to setup.py.""")
  129. if version >= 9.0:
  130. self.set_macro("FrameworkVersion", self.vsbase, "clr version")
  131. self.set_macro("WindowsSdkDir", WINSDK_BASE, "currentinstallfolder")
  132. else:
  133. p = r"Software\Microsoft\NET Framework Setup\Product"
  134. for base in HKEYS:
  135. try:
  136. h = RegOpenKeyEx(base, p)
  137. except RegError:
  138. continue
  139. key = RegEnumKey(h, 0)
  140. d = Reg.get_value(base, r"%s\%s" % (p, key))
  141. self.macros["$(FrameworkVersion)"] = d["version"]
  142. def sub(self, s):
  143. for k, v in self.macros.items():
  144. s = s.replace(k, v)
  145. return s
  146. def get_build_version():
  147. """Return the version of MSVC that was used to build Python.
  148. For Python 2.3 and up, the version number is included in
  149. sys.version. For earlier versions, assume the compiler is MSVC 6.
  150. """
  151. prefix = "MSC v."
  152. i = sys.version.find(prefix)
  153. if i == -1:
  154. return 6
  155. i = i + len(prefix)
  156. s, rest = sys.version[i:].split(" ", 1)
  157. majorVersion = int(s[:-2]) - 6
  158. if majorVersion >= 13:
  159. # v13 was skipped and should be v14
  160. majorVersion += 1
  161. minorVersion = int(s[2:3]) / 10.0
  162. # I don't think paths are affected by minor version in version 6
  163. if majorVersion == 6:
  164. minorVersion = 0
  165. if majorVersion >= 6:
  166. return majorVersion + minorVersion
  167. # else we don't know what version of the compiler this is
  168. return None
  169. def normalize_and_reduce_paths(paths):
  170. """Return a list of normalized paths with duplicates removed.
  171. The current order of paths is maintained.
  172. """
  173. # Paths are normalized so things like: /a and /a/ aren't both preserved.
  174. reduced_paths = []
  175. for p in paths:
  176. np = os.path.normpath(p)
  177. # XXX(nnorwitz): O(n**2), if reduced_paths gets long perhaps use a set.
  178. if np not in reduced_paths:
  179. reduced_paths.append(np)
  180. return reduced_paths
  181. def removeDuplicates(variable):
  182. """Remove duplicate values of an environment variable.
  183. """
  184. oldList = variable.split(os.pathsep)
  185. newList = []
  186. for i in oldList:
  187. if i not in newList:
  188. newList.append(i)
  189. newVariable = os.pathsep.join(newList)
  190. return newVariable
  191. def find_vcvarsall(version):
  192. """Find the vcvarsall.bat file
  193. At first it tries to find the productdir of VS 2008 in the registry. If
  194. that fails it falls back to the VS90COMNTOOLS env var.
  195. """
  196. vsbase = VS_BASE % version
  197. try:
  198. productdir = Reg.get_value(r"%s\Setup\VC" % vsbase,
  199. "productdir")
  200. except KeyError:
  201. log.debug("Unable to find productdir in registry")
  202. productdir = None
  203. if not productdir or not os.path.isdir(productdir):
  204. toolskey = "VS%0.f0COMNTOOLS" % version
  205. toolsdir = os.environ.get(toolskey, None)
  206. if toolsdir and os.path.isdir(toolsdir):
  207. productdir = os.path.join(toolsdir, os.pardir, os.pardir, "VC")
  208. productdir = os.path.abspath(productdir)
  209. if not os.path.isdir(productdir):
  210. log.debug("%s is not a valid directory" % productdir)
  211. return None
  212. else:
  213. log.debug("Env var %s is not set or invalid" % toolskey)
  214. if not productdir:
  215. log.debug("No productdir found")
  216. return None
  217. vcvarsall = os.path.join(productdir, "vcvarsall.bat")
  218. if os.path.isfile(vcvarsall):
  219. return vcvarsall
  220. log.debug("Unable to find vcvarsall.bat")
  221. return None
  222. def query_vcvarsall(version, arch="x86"):
  223. """Launch vcvarsall.bat and read the settings from its environment
  224. """
  225. vcvarsall = find_vcvarsall(version)
  226. interesting = set(("include", "lib", "libpath", "path"))
  227. result = {}
  228. if vcvarsall is None:
  229. raise DistutilsPlatformError("Unable to find vcvarsall.bat")
  230. log.debug("Calling 'vcvarsall.bat %s' (version=%s)", arch, version)
  231. popen = subprocess.Popen('"%s" %s & set' % (vcvarsall, arch),
  232. stdout=subprocess.PIPE,
  233. stderr=subprocess.PIPE)
  234. try:
  235. stdout, stderr = popen.communicate()
  236. if popen.wait() != 0:
  237. raise DistutilsPlatformError(stderr.decode("mbcs"))
  238. stdout = stdout.decode("mbcs")
  239. for line in stdout.split("\n"):
  240. line = Reg.convert_mbcs(line)
  241. if '=' not in line:
  242. continue
  243. line = line.strip()
  244. key, value = line.split('=', 1)
  245. key = key.lower()
  246. if key in interesting:
  247. if value.endswith(os.pathsep):
  248. value = value[:-1]
  249. result[key] = removeDuplicates(value)
  250. finally:
  251. popen.stdout.close()
  252. popen.stderr.close()
  253. if len(result) != len(interesting):
  254. raise ValueError(str(list(result.keys())))
  255. return result
  256. # More globals
  257. VERSION = get_build_version()
  258. if VERSION < 8.0:
  259. raise DistutilsPlatformError("VC %0.1f is not supported by this module" % VERSION)
  260. # MACROS = MacroExpander(VERSION)
  261. class MSVCCompiler(CCompiler) :
  262. """Concrete class that implements an interface to Microsoft Visual C++,
  263. as defined by the CCompiler abstract class."""
  264. compiler_type = 'msvc'
  265. # Just set this so CCompiler's constructor doesn't barf. We currently
  266. # don't use the 'set_executables()' bureaucracy provided by CCompiler,
  267. # as it really isn't necessary for this sort of single-compiler class.
  268. # Would be nice to have a consistent interface with UnixCCompiler,
  269. # though, so it's worth thinking about.
  270. executables = {}
  271. # Private class data (need to distinguish C from C++ source for compiler)
  272. _c_extensions = ['.c']
  273. _cpp_extensions = ['.cc', '.cpp', '.cxx']
  274. _rc_extensions = ['.rc']
  275. _mc_extensions = ['.mc']
  276. # Needed for the filename generation methods provided by the
  277. # base class, CCompiler.
  278. src_extensions = (_c_extensions + _cpp_extensions +
  279. _rc_extensions + _mc_extensions)
  280. res_extension = '.res'
  281. obj_extension = '.obj'
  282. static_lib_extension = '.lib'
  283. shared_lib_extension = '.dll'
  284. static_lib_format = shared_lib_format = '%s%s'
  285. exe_extension = '.exe'
  286. def __init__(self, verbose=0, dry_run=0, force=0):
  287. CCompiler.__init__ (self, verbose, dry_run, force)
  288. self.__version = VERSION
  289. self.__root = r"Software\Microsoft\VisualStudio"
  290. # self.__macros = MACROS
  291. self.__paths = []
  292. # target platform (.plat_name is consistent with 'bdist')
  293. self.plat_name = None
  294. self.__arch = None # deprecated name
  295. self.initialized = False
  296. def initialize(self, plat_name=None):
  297. # multi-init means we would need to check platform same each time...
  298. assert not self.initialized, "don't init multiple times"
  299. if plat_name is None:
  300. plat_name = get_platform()
  301. # sanity check for platforms to prevent obscure errors later.
  302. ok_plats = 'win32', 'win-amd64', 'win-ia64'
  303. if plat_name not in ok_plats:
  304. raise DistutilsPlatformError("--plat-name must be one of %s" %
  305. (ok_plats,))
  306. if "DISTUTILS_USE_SDK" in os.environ and "MSSdk" in os.environ and self.find_exe("cl.exe"):
  307. # Assume that the SDK set up everything alright; don't try to be
  308. # smarter
  309. self.cc = "cl.exe"
  310. self.linker = "link.exe"
  311. self.lib = "lib.exe"
  312. self.rc = "rc.exe"
  313. self.mc = "mc.exe"
  314. else:
  315. # On x86, 'vcvars32.bat amd64' creates an env that doesn't work;
  316. # to cross compile, you use 'x86_amd64'.
  317. # On AMD64, 'vcvars32.bat amd64' is a native build env; to cross
  318. # compile use 'x86' (ie, it runs the x86 compiler directly)
  319. # No idea how itanium handles this, if at all.
  320. if plat_name == get_platform() or plat_name == 'win32':
  321. # native build or cross-compile to win32
  322. plat_spec = PLAT_TO_VCVARS[plat_name]
  323. else:
  324. # cross compile from win32 -> some 64bit
  325. plat_spec = PLAT_TO_VCVARS[get_platform()] + '_' + \
  326. PLAT_TO_VCVARS[plat_name]
  327. vc_env = query_vcvarsall(VERSION, plat_spec)
  328. self.__paths = vc_env['path'].split(os.pathsep)
  329. os.environ['lib'] = vc_env['lib']
  330. os.environ['include'] = vc_env['include']
  331. if len(self.__paths) == 0:
  332. raise DistutilsPlatformError("Python was built with %s, "
  333. "and extensions need to be built with the same "
  334. "version of the compiler, but it isn't installed."
  335. % self.__product)
  336. self.cc = self.find_exe("cl.exe")
  337. self.linker = self.find_exe("link.exe")
  338. self.lib = self.find_exe("lib.exe")
  339. self.rc = self.find_exe("rc.exe") # resource compiler
  340. self.mc = self.find_exe("mc.exe") # message compiler
  341. #self.set_path_env_var('lib')
  342. #self.set_path_env_var('include')
  343. # extend the MSVC path with the current path
  344. try:
  345. for p in os.environ['path'].split(';'):
  346. self.__paths.append(p)
  347. except KeyError:
  348. pass
  349. self.__paths = normalize_and_reduce_paths(self.__paths)
  350. os.environ['path'] = ";".join(self.__paths)
  351. self.preprocess_options = None
  352. if self.__arch == "x86":
  353. self.compile_options = [ '/nologo', '/Ox', '/MD', '/W3',
  354. '/DNDEBUG']
  355. self.compile_options_debug = ['/nologo', '/Od', '/MDd', '/W3',
  356. '/Z7', '/D_DEBUG']
  357. else:
  358. # Win64
  359. self.compile_options = [ '/nologo', '/Ox', '/MD', '/W3', '/GS-' ,
  360. '/DNDEBUG']
  361. self.compile_options_debug = ['/nologo', '/Od', '/MDd', '/W3', '/GS-',
  362. '/Z7', '/D_DEBUG']
  363. self.ldflags_shared = ['/DLL', '/nologo', '/INCREMENTAL:NO']
  364. if self.__version >= 7:
  365. self.ldflags_shared_debug = [
  366. '/DLL', '/nologo', '/INCREMENTAL:no', '/DEBUG'
  367. ]
  368. self.ldflags_static = [ '/nologo']
  369. self.initialized = True
  370. # -- Worker methods ------------------------------------------------
  371. def object_filenames(self,
  372. source_filenames,
  373. strip_dir=0,
  374. output_dir=''):
  375. # Copied from ccompiler.py, extended to return .res as 'object'-file
  376. # for .rc input file
  377. if output_dir is None: output_dir = ''
  378. obj_names = []
  379. for src_name in source_filenames:
  380. (base, ext) = os.path.splitext (src_name)
  381. base = os.path.splitdrive(base)[1] # Chop off the drive
  382. base = base[os.path.isabs(base):] # If abs, chop off leading /
  383. if ext not in self.src_extensions:
  384. # Better to raise an exception instead of silently continuing
  385. # and later complain about sources and targets having
  386. # different lengths
  387. raise CompileError ("Don't know how to compile %s" % src_name)
  388. if strip_dir:
  389. base = os.path.basename (base)
  390. if ext in self._rc_extensions:
  391. obj_names.append (os.path.join (output_dir,
  392. base + self.res_extension))
  393. elif ext in self._mc_extensions:
  394. obj_names.append (os.path.join (output_dir,
  395. base + self.res_extension))
  396. else:
  397. obj_names.append (os.path.join (output_dir,
  398. base + self.obj_extension))
  399. return obj_names
  400. def compile(self, sources,
  401. output_dir=None, macros=None, include_dirs=None, debug=0,
  402. extra_preargs=None, extra_postargs=None, depends=None):
  403. if not self.initialized:
  404. self.initialize()
  405. compile_info = self._setup_compile(output_dir, macros, include_dirs,
  406. sources, depends, extra_postargs)
  407. macros, objects, extra_postargs, pp_opts, build = compile_info
  408. compile_opts = extra_preargs or []
  409. compile_opts.append ('/c')
  410. if debug:
  411. compile_opts.extend(self.compile_options_debug)
  412. else:
  413. compile_opts.extend(self.compile_options)
  414. for obj in objects:
  415. try:
  416. src, ext = build[obj]
  417. except KeyError:
  418. continue
  419. if debug:
  420. # pass the full pathname to MSVC in debug mode,
  421. # this allows the debugger to find the source file
  422. # without asking the user to browse for it
  423. src = os.path.abspath(src)
  424. if ext in self._c_extensions:
  425. input_opt = "/Tc" + src
  426. elif ext in self._cpp_extensions:
  427. input_opt = "/Tp" + src
  428. elif ext in self._rc_extensions:
  429. # compile .RC to .RES file
  430. input_opt = src
  431. output_opt = "/fo" + obj
  432. try:
  433. self.spawn([self.rc] + pp_opts +
  434. [output_opt] + [input_opt])
  435. except DistutilsExecError as msg:
  436. raise CompileError(msg)
  437. continue
  438. elif ext in self._mc_extensions:
  439. # Compile .MC to .RC file to .RES file.
  440. # * '-h dir' specifies the directory for the
  441. # generated include file
  442. # * '-r dir' specifies the target directory of the
  443. # generated RC file and the binary message resource
  444. # it includes
  445. #
  446. # For now (since there are no options to change this),
  447. # we use the source-directory for the include file and
  448. # the build directory for the RC file and message
  449. # resources. This works at least for win32all.
  450. h_dir = os.path.dirname(src)
  451. rc_dir = os.path.dirname(obj)
  452. try:
  453. # first compile .MC to .RC and .H file
  454. self.spawn([self.mc] +
  455. ['-h', h_dir, '-r', rc_dir] + [src])
  456. base, _ = os.path.splitext (os.path.basename (src))
  457. rc_file = os.path.join (rc_dir, base + '.rc')
  458. # then compile .RC to .RES file
  459. self.spawn([self.rc] +
  460. ["/fo" + obj] + [rc_file])
  461. except DistutilsExecError as msg:
  462. raise CompileError(msg)
  463. continue
  464. else:
  465. # how to handle this file?
  466. raise CompileError("Don't know how to compile %s to %s"
  467. % (src, obj))
  468. output_opt = "/Fo" + obj
  469. try:
  470. self.spawn([self.cc] + compile_opts + pp_opts +
  471. [input_opt, output_opt] +
  472. extra_postargs)
  473. except DistutilsExecError as msg:
  474. raise CompileError(msg)
  475. return objects
  476. def create_static_lib(self,
  477. objects,
  478. output_libname,
  479. output_dir=None,
  480. debug=0,
  481. target_lang=None):
  482. if not self.initialized:
  483. self.initialize()
  484. (objects, output_dir) = self._fix_object_args(objects, output_dir)
  485. output_filename = self.library_filename(output_libname,
  486. output_dir=output_dir)
  487. if self._need_link(objects, output_filename):
  488. lib_args = objects + ['/OUT:' + output_filename]
  489. if debug:
  490. pass # XXX what goes here?
  491. try:
  492. self.spawn([self.lib] + lib_args)
  493. except DistutilsExecError as msg:
  494. raise LibError(msg)
  495. else:
  496. log.debug("skipping %s (up-to-date)", output_filename)
  497. def link(self,
  498. target_desc,
  499. objects,
  500. output_filename,
  501. output_dir=None,
  502. libraries=None,
  503. library_dirs=None,
  504. runtime_library_dirs=None,
  505. export_symbols=None,
  506. debug=0,
  507. extra_preargs=None,
  508. extra_postargs=None,
  509. build_temp=None,
  510. target_lang=None):
  511. if not self.initialized:
  512. self.initialize()
  513. (objects, output_dir) = self._fix_object_args(objects, output_dir)
  514. fixed_args = self._fix_lib_args(libraries, library_dirs,
  515. runtime_library_dirs)
  516. (libraries, library_dirs, runtime_library_dirs) = fixed_args
  517. if runtime_library_dirs:
  518. self.warn ("I don't know what to do with 'runtime_library_dirs': "
  519. + str (runtime_library_dirs))
  520. lib_opts = gen_lib_options(self,
  521. library_dirs, runtime_library_dirs,
  522. libraries)
  523. if output_dir is not None:
  524. output_filename = os.path.join(output_dir, output_filename)
  525. if self._need_link(objects, output_filename):
  526. if target_desc == CCompiler.EXECUTABLE:
  527. if debug:
  528. ldflags = self.ldflags_shared_debug[1:]
  529. else:
  530. ldflags = self.ldflags_shared[1:]
  531. else:
  532. if debug:
  533. ldflags = self.ldflags_shared_debug
  534. else:
  535. ldflags = self.ldflags_shared
  536. export_opts = []
  537. for sym in (export_symbols or []):
  538. export_opts.append("/EXPORT:" + sym)
  539. ld_args = (ldflags + lib_opts + export_opts +
  540. objects + ['/OUT:' + output_filename])
  541. # The MSVC linker generates .lib and .exp files, which cannot be
  542. # suppressed by any linker switches. The .lib files may even be
  543. # needed! Make sure they are generated in the temporary build
  544. # directory. Since they have different names for debug and release
  545. # builds, they can go into the same directory.
  546. build_temp = os.path.dirname(objects[0])
  547. if export_symbols is not None:
  548. (dll_name, dll_ext) = os.path.splitext(
  549. os.path.basename(output_filename))
  550. implib_file = os.path.join(
  551. build_temp,
  552. self.library_filename(dll_name))
  553. ld_args.append ('/IMPLIB:' + implib_file)
  554. self.manifest_setup_ldargs(output_filename, build_temp, ld_args)
  555. if extra_preargs:
  556. ld_args[:0] = extra_preargs
  557. if extra_postargs:
  558. ld_args.extend(extra_postargs)
  559. self.mkpath(os.path.dirname(output_filename))
  560. try:
  561. self.spawn([self.linker] + ld_args)
  562. except DistutilsExecError as msg:
  563. raise LinkError(msg)
  564. # embed the manifest
  565. # XXX - this is somewhat fragile - if mt.exe fails, distutils
  566. # will still consider the DLL up-to-date, but it will not have a
  567. # manifest. Maybe we should link to a temp file? OTOH, that
  568. # implies a build environment error that shouldn't go undetected.
  569. mfinfo = self.manifest_get_embed_info(target_desc, ld_args)
  570. if mfinfo is not None:
  571. mffilename, mfid = mfinfo
  572. out_arg = '-outputresource:%s;%s' % (output_filename, mfid)
  573. try:
  574. self.spawn(['mt.exe', '-nologo', '-manifest',
  575. mffilename, out_arg])
  576. except DistutilsExecError as msg:
  577. raise LinkError(msg)
  578. else:
  579. log.debug("skipping %s (up-to-date)", output_filename)
  580. def manifest_setup_ldargs(self, output_filename, build_temp, ld_args):
  581. # If we need a manifest at all, an embedded manifest is recommended.
  582. # See MSDN article titled
  583. # "How to: Embed a Manifest Inside a C/C++ Application"
  584. # (currently at http://msdn2.microsoft.com/en-us/library/ms235591(VS.80).aspx)
  585. # Ask the linker to generate the manifest in the temp dir, so
  586. # we can check it, and possibly embed it, later.
  587. temp_manifest = os.path.join(
  588. build_temp,
  589. os.path.basename(output_filename) + ".manifest")
  590. ld_args.append('/MANIFESTFILE:' + temp_manifest)
  591. def manifest_get_embed_info(self, target_desc, ld_args):
  592. # If a manifest should be embedded, return a tuple of
  593. # (manifest_filename, resource_id). Returns None if no manifest
  594. # should be embedded. See http://bugs.python.org/issue7833 for why
  595. # we want to avoid any manifest for extension modules if we can)
  596. for arg in ld_args:
  597. if arg.startswith("/MANIFESTFILE:"):
  598. temp_manifest = arg.split(":", 1)[1]
  599. break
  600. else:
  601. # no /MANIFESTFILE so nothing to do.
  602. return None
  603. if target_desc == CCompiler.EXECUTABLE:
  604. # by default, executables always get the manifest with the
  605. # CRT referenced.
  606. mfid = 1
  607. else:
  608. # Extension modules try and avoid any manifest if possible.
  609. mfid = 2
  610. temp_manifest = self._remove_visual_c_ref(temp_manifest)
  611. if temp_manifest is None:
  612. return None
  613. return temp_manifest, mfid
  614. def _remove_visual_c_ref(self, manifest_file):
  615. try:
  616. # Remove references to the Visual C runtime, so they will
  617. # fall through to the Visual C dependency of Python.exe.
  618. # This way, when installed for a restricted user (e.g.
  619. # runtimes are not in WinSxS folder, but in Python's own
  620. # folder), the runtimes do not need to be in every folder
  621. # with .pyd's.
  622. # Returns either the filename of the modified manifest or
  623. # None if no manifest should be embedded.
  624. manifest_f = open(manifest_file)
  625. try:
  626. manifest_buf = manifest_f.read()
  627. finally:
  628. manifest_f.close()
  629. pattern = re.compile(
  630. r"""<assemblyIdentity.*?name=("|')Microsoft\."""\
  631. r"""VC\d{2}\.CRT("|').*?(/>|</assemblyIdentity>)""",
  632. re.DOTALL)
  633. manifest_buf = re.sub(pattern, "", manifest_buf)
  634. pattern = "<dependentAssembly>\s*</dependentAssembly>"
  635. manifest_buf = re.sub(pattern, "", manifest_buf)
  636. # Now see if any other assemblies are referenced - if not, we
  637. # don't want a manifest embedded.
  638. pattern = re.compile(
  639. r"""<assemblyIdentity.*?name=(?:"|')(.+?)(?:"|')"""
  640. r""".*?(?:/>|</assemblyIdentity>)""", re.DOTALL)
  641. if re.search(pattern, manifest_buf) is None:
  642. return None
  643. manifest_f = open(manifest_file, 'w')
  644. try:
  645. manifest_f.write(manifest_buf)
  646. return manifest_file
  647. finally:
  648. manifest_f.close()
  649. except OSError:
  650. pass
  651. # -- Miscellaneous methods -----------------------------------------
  652. # These are all used by the 'gen_lib_options() function, in
  653. # ccompiler.py.
  654. def library_dir_option(self, dir):
  655. return "/LIBPATH:" + dir
  656. def runtime_library_dir_option(self, dir):
  657. raise DistutilsPlatformError(
  658. "don't know how to set runtime library search path for MSVC++")
  659. def library_option(self, lib):
  660. return self.library_filename(lib)
  661. def find_library_file(self, dirs, lib, debug=0):
  662. # Prefer a debugging library if found (and requested), but deal
  663. # with it if we don't have one.
  664. if debug:
  665. try_names = [lib + "_d", lib]
  666. else:
  667. try_names = [lib]
  668. for dir in dirs:
  669. for name in try_names:
  670. libfile = os.path.join(dir, self.library_filename (name))
  671. if os.path.exists(libfile):
  672. return libfile
  673. else:
  674. # Oops, didn't find it in *any* of 'dirs'
  675. return None
  676. # Helper methods for using the MSVC registry settings
  677. def find_exe(self, exe):
  678. """Return path to an MSVC executable program.
  679. Tries to find the program in several places: first, one of the
  680. MSVC program search paths from the registry; next, the directories
  681. in the PATH environment variable. If any of those work, return an
  682. absolute path that is known to exist. If none of them work, just
  683. return the original program name, 'exe'.
  684. """
  685. for p in self.__paths:
  686. fn = os.path.join(os.path.abspath(p), exe)
  687. if os.path.isfile(fn):
  688. return fn
  689. # didn't find it; try existing path
  690. for p in os.environ['Path'].split(';'):
  691. fn = os.path.join(os.path.abspath(p),exe)
  692. if os.path.isfile(fn):
  693. return fn
  694. return exe