msvc9compiler.py 30 KB

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