msvc9compiler.py 30 KB

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