msvccompiler.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. """distutils.msvccompiler
  2. Contains MSVCCompiler, an implementation of the abstract CCompiler class
  3. for the Microsoft Visual Studio.
  4. """
  5. # Written by Perry Stoll
  6. # hacked by Robin Becker and Thomas Heller to do a better job of
  7. # finding DevStudio (through the registry)
  8. __revision__ = "$Id$"
  9. import sys
  10. import os
  11. import string
  12. from distutils.errors import (DistutilsExecError, DistutilsPlatformError,
  13. CompileError, LibError, LinkError)
  14. from distutils.ccompiler import CCompiler, gen_lib_options
  15. from distutils import log
  16. _can_read_reg = 0
  17. try:
  18. import _winreg
  19. _can_read_reg = 1
  20. hkey_mod = _winreg
  21. RegOpenKeyEx = _winreg.OpenKeyEx
  22. RegEnumKey = _winreg.EnumKey
  23. RegEnumValue = _winreg.EnumValue
  24. RegError = _winreg.error
  25. except ImportError:
  26. try:
  27. import win32api
  28. import win32con
  29. _can_read_reg = 1
  30. hkey_mod = win32con
  31. RegOpenKeyEx = win32api.RegOpenKeyEx
  32. RegEnumKey = win32api.RegEnumKey
  33. RegEnumValue = win32api.RegEnumValue
  34. RegError = win32api.error
  35. except ImportError:
  36. log.info("Warning: Can't read registry to find the "
  37. "necessary compiler setting\n"
  38. "Make sure that Python modules _winreg, "
  39. "win32api or win32con are installed.")
  40. pass
  41. if _can_read_reg:
  42. HKEYS = (hkey_mod.HKEY_USERS,
  43. hkey_mod.HKEY_CURRENT_USER,
  44. hkey_mod.HKEY_LOCAL_MACHINE,
  45. hkey_mod.HKEY_CLASSES_ROOT)
  46. def read_keys(base, key):
  47. """Return list of registry keys."""
  48. try:
  49. handle = RegOpenKeyEx(base, key)
  50. except RegError:
  51. return None
  52. L = []
  53. i = 0
  54. while 1:
  55. try:
  56. k = RegEnumKey(handle, i)
  57. except RegError:
  58. break
  59. L.append(k)
  60. i = i + 1
  61. return L
  62. def read_values(base, key):
  63. """Return dict of registry keys and values.
  64. All names are converted to lowercase.
  65. """
  66. try:
  67. handle = RegOpenKeyEx(base, key)
  68. except RegError:
  69. return None
  70. d = {}
  71. i = 0
  72. while 1:
  73. try:
  74. name, value, type = RegEnumValue(handle, i)
  75. except RegError:
  76. break
  77. name = name.lower()
  78. d[convert_mbcs(name)] = convert_mbcs(value)
  79. i = i + 1
  80. return d
  81. def convert_mbcs(s):
  82. enc = getattr(s, "encode", None)
  83. if enc is not None:
  84. try:
  85. s = enc("mbcs")
  86. except UnicodeError:
  87. pass
  88. return s
  89. class MacroExpander:
  90. def __init__(self, version):
  91. self.macros = {}
  92. self.load_macros(version)
  93. def set_macro(self, macro, path, key):
  94. for base in HKEYS:
  95. d = read_values(base, path)
  96. if d:
  97. self.macros["$(%s)" % macro] = d[key]
  98. break
  99. def load_macros(self, version):
  100. vsbase = r"Software\Microsoft\VisualStudio\%0.1f" % version
  101. self.set_macro("VCInstallDir", vsbase + r"\Setup\VC", "productdir")
  102. self.set_macro("VSInstallDir", vsbase + r"\Setup\VS", "productdir")
  103. net = r"Software\Microsoft\.NETFramework"
  104. self.set_macro("FrameworkDir", net, "installroot")
  105. try:
  106. if version > 7.0:
  107. self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1")
  108. else:
  109. self.set_macro("FrameworkSDKDir", net, "sdkinstallroot")
  110. except KeyError:
  111. raise DistutilsPlatformError, \
  112. ("""Python was built with Visual Studio 2003;
  113. extensions must be built with a compiler than can generate compatible binaries.
  114. Visual Studio 2003 was not found on this system. If you have Cygwin installed,
  115. you can try compiling with MingW32, by passing "-c mingw32" to setup.py.""")
  116. p = r"Software\Microsoft\NET Framework Setup\Product"
  117. for base in HKEYS:
  118. try:
  119. h = RegOpenKeyEx(base, p)
  120. except RegError:
  121. continue
  122. key = RegEnumKey(h, 0)
  123. d = read_values(base, r"%s\%s" % (p, key))
  124. self.macros["$(FrameworkVersion)"] = d["version"]
  125. def sub(self, s):
  126. for k, v in self.macros.items():
  127. s = string.replace(s, k, v)
  128. return s
  129. def get_build_version():
  130. """Return the version of MSVC that was used to build Python.
  131. For Python 2.3 and up, the version number is included in
  132. sys.version. For earlier versions, assume the compiler is MSVC 6.
  133. """
  134. prefix = "MSC v."
  135. i = string.find(sys.version, prefix)
  136. if i == -1:
  137. return 6
  138. i = i + len(prefix)
  139. s, rest = sys.version[i:].split(" ", 1)
  140. majorVersion = int(s[:-2]) - 6
  141. minorVersion = int(s[2:3]) / 10.0
  142. # I don't think paths are affected by minor version in version 6
  143. if majorVersion == 6:
  144. minorVersion = 0
  145. if majorVersion >= 6:
  146. return majorVersion + minorVersion
  147. # else we don't know what version of the compiler this is
  148. return None
  149. def get_build_architecture():
  150. """Return the processor architecture.
  151. Possible results are "Intel", "Itanium", or "AMD64".
  152. """
  153. prefix = " bit ("
  154. i = string.find(sys.version, prefix)
  155. if i == -1:
  156. return "Intel"
  157. j = string.find(sys.version, ")", i)
  158. return sys.version[i+len(prefix):j]
  159. def normalize_and_reduce_paths(paths):
  160. """Return a list of normalized paths with duplicates removed.
  161. The current order of paths is maintained.
  162. """
  163. # Paths are normalized so things like: /a and /a/ aren't both preserved.
  164. reduced_paths = []
  165. for p in paths:
  166. np = os.path.normpath(p)
  167. # XXX(nnorwitz): O(n**2), if reduced_paths gets long perhaps use a set.
  168. if np not in reduced_paths:
  169. reduced_paths.append(np)
  170. return reduced_paths
  171. class MSVCCompiler (CCompiler) :
  172. """Concrete class that implements an interface to Microsoft Visual C++,
  173. as defined by the CCompiler abstract class."""
  174. compiler_type = 'msvc'
  175. # Just set this so CCompiler's constructor doesn't barf. We currently
  176. # don't use the 'set_executables()' bureaucracy provided by CCompiler,
  177. # as it really isn't necessary for this sort of single-compiler class.
  178. # Would be nice to have a consistent interface with UnixCCompiler,
  179. # though, so it's worth thinking about.
  180. executables = {}
  181. # Private class data (need to distinguish C from C++ source for compiler)
  182. _c_extensions = ['.c']
  183. _cpp_extensions = ['.cc', '.cpp', '.cxx']
  184. _rc_extensions = ['.rc']
  185. _mc_extensions = ['.mc']
  186. # Needed for the filename generation methods provided by the
  187. # base class, CCompiler.
  188. src_extensions = (_c_extensions + _cpp_extensions +
  189. _rc_extensions + _mc_extensions)
  190. res_extension = '.res'
  191. obj_extension = '.obj'
  192. static_lib_extension = '.lib'
  193. shared_lib_extension = '.dll'
  194. static_lib_format = shared_lib_format = '%s%s'
  195. exe_extension = '.exe'
  196. def __init__ (self, verbose=0, dry_run=0, force=0):
  197. CCompiler.__init__ (self, verbose, dry_run, force)
  198. self.__version = get_build_version()
  199. self.__arch = get_build_architecture()
  200. if self.__arch == "Intel":
  201. # x86
  202. if self.__version >= 7:
  203. self.__root = r"Software\Microsoft\VisualStudio"
  204. self.__macros = MacroExpander(self.__version)
  205. else:
  206. self.__root = r"Software\Microsoft\Devstudio"
  207. self.__product = "Visual Studio version %s" % self.__version
  208. else:
  209. # Win64. Assume this was built with the platform SDK
  210. self.__product = "Microsoft SDK compiler %s" % (self.__version + 6)
  211. self.initialized = False
  212. def initialize(self):
  213. self.__paths = []
  214. if "DISTUTILS_USE_SDK" in os.environ and "MSSdk" in os.environ and self.find_exe("cl.exe"):
  215. # Assume that the SDK set up everything alright; don't try to be
  216. # smarter
  217. self.cc = "cl.exe"
  218. self.linker = "link.exe"
  219. self.lib = "lib.exe"
  220. self.rc = "rc.exe"
  221. self.mc = "mc.exe"
  222. else:
  223. self.__paths = self.get_msvc_paths("path")
  224. if len (self.__paths) == 0:
  225. raise DistutilsPlatformError, \
  226. ("Python was built with %s, "
  227. "and extensions need to be built with the same "
  228. "version of the compiler, but it isn't installed." % self.__product)
  229. self.cc = self.find_exe("cl.exe")
  230. self.linker = self.find_exe("link.exe")
  231. self.lib = self.find_exe("lib.exe")
  232. self.rc = self.find_exe("rc.exe") # resource compiler
  233. self.mc = self.find_exe("mc.exe") # message compiler
  234. self.set_path_env_var('lib')
  235. self.set_path_env_var('include')
  236. # extend the MSVC path with the current path
  237. try:
  238. for p in string.split(os.environ['path'], ';'):
  239. self.__paths.append(p)
  240. except KeyError:
  241. pass
  242. self.__paths = normalize_and_reduce_paths(self.__paths)
  243. os.environ['path'] = string.join(self.__paths, ';')
  244. self.preprocess_options = None
  245. if self.__arch == "Intel":
  246. self.compile_options = [ '/nologo', '/Ox', '/MD', '/W3', '/GX' ,
  247. '/DNDEBUG']
  248. self.compile_options_debug = ['/nologo', '/Od', '/MDd', '/W3', '/GX',
  249. '/Z7', '/D_DEBUG']
  250. else:
  251. # Win64
  252. self.compile_options = [ '/nologo', '/Ox', '/MD', '/W3', '/GS-' ,
  253. '/DNDEBUG']
  254. self.compile_options_debug = ['/nologo', '/Od', '/MDd', '/W3', '/GS-',
  255. '/Z7', '/D_DEBUG']
  256. self.ldflags_shared = ['/DLL', '/nologo', '/INCREMENTAL:NO']
  257. if self.__version >= 7:
  258. self.ldflags_shared_debug = [
  259. '/DLL', '/nologo', '/INCREMENTAL:no', '/DEBUG'
  260. ]
  261. else:
  262. self.ldflags_shared_debug = [
  263. '/DLL', '/nologo', '/INCREMENTAL:no', '/pdb:None', '/DEBUG'
  264. ]
  265. self.ldflags_static = [ '/nologo']
  266. self.initialized = True
  267. # -- Worker methods ------------------------------------------------
  268. def object_filenames (self,
  269. source_filenames,
  270. strip_dir=0,
  271. output_dir=''):
  272. # Copied from ccompiler.py, extended to return .res as 'object'-file
  273. # for .rc input file
  274. if output_dir is None: output_dir = ''
  275. obj_names = []
  276. for src_name in source_filenames:
  277. (base, ext) = os.path.splitext (src_name)
  278. base = os.path.splitdrive(base)[1] # Chop off the drive
  279. base = base[os.path.isabs(base):] # If abs, chop off leading /
  280. if ext not in self.src_extensions:
  281. # Better to raise an exception instead of silently continuing
  282. # and later complain about sources and targets having
  283. # different lengths
  284. raise CompileError ("Don't know how to compile %s" % src_name)
  285. if strip_dir:
  286. base = os.path.basename (base)
  287. if ext in self._rc_extensions:
  288. obj_names.append (os.path.join (output_dir,
  289. base + self.res_extension))
  290. elif ext in self._mc_extensions:
  291. obj_names.append (os.path.join (output_dir,
  292. base + self.res_extension))
  293. else:
  294. obj_names.append (os.path.join (output_dir,
  295. base + self.obj_extension))
  296. return obj_names
  297. # object_filenames ()
  298. def compile(self, sources,
  299. output_dir=None, macros=None, include_dirs=None, debug=0,
  300. extra_preargs=None, extra_postargs=None, depends=None):
  301. if not self.initialized: self.initialize()
  302. macros, objects, extra_postargs, pp_opts, build = \
  303. self._setup_compile(output_dir, macros, include_dirs, sources,
  304. depends, extra_postargs)
  305. compile_opts = extra_preargs or []
  306. compile_opts.append ('/c')
  307. if debug:
  308. compile_opts.extend(self.compile_options_debug)
  309. else:
  310. compile_opts.extend(self.compile_options)
  311. for obj in objects:
  312. try:
  313. src, ext = build[obj]
  314. except KeyError:
  315. continue
  316. if debug:
  317. # pass the full pathname to MSVC in debug mode,
  318. # this allows the debugger to find the source file
  319. # without asking the user to browse for it
  320. src = os.path.abspath(src)
  321. if ext in self._c_extensions:
  322. input_opt = "/Tc" + src
  323. elif ext in self._cpp_extensions:
  324. input_opt = "/Tp" + src
  325. elif ext in self._rc_extensions:
  326. # compile .RC to .RES file
  327. input_opt = src
  328. output_opt = "/fo" + obj
  329. try:
  330. self.spawn ([self.rc] + pp_opts +
  331. [output_opt] + [input_opt])
  332. except DistutilsExecError, msg:
  333. raise CompileError, msg
  334. continue
  335. elif ext in self._mc_extensions:
  336. # Compile .MC to .RC file to .RES file.
  337. # * '-h dir' specifies the directory for the
  338. # generated include file
  339. # * '-r dir' specifies the target directory of the
  340. # generated RC file and the binary message resource
  341. # it includes
  342. #
  343. # For now (since there are no options to change this),
  344. # we use the source-directory for the include file and
  345. # the build directory for the RC file and message
  346. # resources. This works at least for win32all.
  347. h_dir = os.path.dirname (src)
  348. rc_dir = os.path.dirname (obj)
  349. try:
  350. # first compile .MC to .RC and .H file
  351. self.spawn ([self.mc] +
  352. ['-h', h_dir, '-r', rc_dir] + [src])
  353. base, _ = os.path.splitext (os.path.basename (src))
  354. rc_file = os.path.join (rc_dir, base + '.rc')
  355. # then compile .RC to .RES file
  356. self.spawn ([self.rc] +
  357. ["/fo" + obj] + [rc_file])
  358. except DistutilsExecError, msg:
  359. raise CompileError, msg
  360. continue
  361. else:
  362. # how to handle this file?
  363. raise CompileError (
  364. "Don't know how to compile %s to %s" % \
  365. (src, obj))
  366. output_opt = "/Fo" + obj
  367. try:
  368. self.spawn ([self.cc] + compile_opts + pp_opts +
  369. [input_opt, output_opt] +
  370. extra_postargs)
  371. except DistutilsExecError, msg:
  372. raise CompileError, msg
  373. return objects
  374. # compile ()
  375. def create_static_lib (self,
  376. objects,
  377. output_libname,
  378. output_dir=None,
  379. debug=0,
  380. target_lang=None):
  381. if not self.initialized: self.initialize()
  382. (objects, output_dir) = self._fix_object_args (objects, output_dir)
  383. output_filename = \
  384. self.library_filename (output_libname, output_dir=output_dir)
  385. if self._need_link (objects, output_filename):
  386. lib_args = objects + ['/OUT:' + output_filename]
  387. if debug:
  388. pass # XXX what goes here?
  389. try:
  390. self.spawn ([self.lib] + lib_args)
  391. except DistutilsExecError, msg:
  392. raise LibError, msg
  393. else:
  394. log.debug("skipping %s (up-to-date)", output_filename)
  395. # create_static_lib ()
  396. def link (self,
  397. target_desc,
  398. objects,
  399. output_filename,
  400. output_dir=None,
  401. libraries=None,
  402. library_dirs=None,
  403. runtime_library_dirs=None,
  404. export_symbols=None,
  405. debug=0,
  406. extra_preargs=None,
  407. extra_postargs=None,
  408. build_temp=None,
  409. target_lang=None):
  410. if not self.initialized: self.initialize()
  411. (objects, output_dir) = self._fix_object_args (objects, output_dir)
  412. (libraries, library_dirs, runtime_library_dirs) = \
  413. self._fix_lib_args (libraries, library_dirs, runtime_library_dirs)
  414. if runtime_library_dirs:
  415. self.warn ("I don't know what to do with 'runtime_library_dirs': "
  416. + str (runtime_library_dirs))
  417. lib_opts = gen_lib_options (self,
  418. library_dirs, runtime_library_dirs,
  419. libraries)
  420. if output_dir is not None:
  421. output_filename = os.path.join (output_dir, output_filename)
  422. if self._need_link (objects, output_filename):
  423. if target_desc == CCompiler.EXECUTABLE:
  424. if debug:
  425. ldflags = self.ldflags_shared_debug[1:]
  426. else:
  427. ldflags = self.ldflags_shared[1:]
  428. else:
  429. if debug:
  430. ldflags = self.ldflags_shared_debug
  431. else:
  432. ldflags = self.ldflags_shared
  433. export_opts = []
  434. for sym in (export_symbols or []):
  435. export_opts.append("/EXPORT:" + sym)
  436. ld_args = (ldflags + lib_opts + export_opts +
  437. objects + ['/OUT:' + output_filename])
  438. # The MSVC linker generates .lib and .exp files, which cannot be
  439. # suppressed by any linker switches. The .lib files may even be
  440. # needed! Make sure they are generated in the temporary build
  441. # directory. Since they have different names for debug and release
  442. # builds, they can go into the same directory.
  443. if export_symbols is not None:
  444. (dll_name, dll_ext) = os.path.splitext(
  445. os.path.basename(output_filename))
  446. implib_file = os.path.join(
  447. os.path.dirname(objects[0]),
  448. self.library_filename(dll_name))
  449. ld_args.append ('/IMPLIB:' + implib_file)
  450. if extra_preargs:
  451. ld_args[:0] = extra_preargs
  452. if extra_postargs:
  453. ld_args.extend(extra_postargs)
  454. self.mkpath (os.path.dirname (output_filename))
  455. try:
  456. self.spawn ([self.linker] + ld_args)
  457. except DistutilsExecError, msg:
  458. raise LinkError, msg
  459. else:
  460. log.debug("skipping %s (up-to-date)", output_filename)
  461. # link ()
  462. # -- Miscellaneous methods -----------------------------------------
  463. # These are all used by the 'gen_lib_options() function, in
  464. # ccompiler.py.
  465. def library_dir_option (self, dir):
  466. return "/LIBPATH:" + dir
  467. def runtime_library_dir_option (self, dir):
  468. raise DistutilsPlatformError, \
  469. "don't know how to set runtime library search path for MSVC++"
  470. def library_option (self, lib):
  471. return self.library_filename (lib)
  472. def find_library_file (self, dirs, lib, debug=0):
  473. # Prefer a debugging library if found (and requested), but deal
  474. # with it if we don't have one.
  475. if debug:
  476. try_names = [lib + "_d", lib]
  477. else:
  478. try_names = [lib]
  479. for dir in dirs:
  480. for name in try_names:
  481. libfile = os.path.join(dir, self.library_filename (name))
  482. if os.path.exists(libfile):
  483. return libfile
  484. else:
  485. # Oops, didn't find it in *any* of 'dirs'
  486. return None
  487. # find_library_file ()
  488. # Helper methods for using the MSVC registry settings
  489. def find_exe(self, exe):
  490. """Return path to an MSVC executable program.
  491. Tries to find the program in several places: first, one of the
  492. MSVC program search paths from the registry; next, the directories
  493. in the PATH environment variable. If any of those work, return an
  494. absolute path that is known to exist. If none of them work, just
  495. return the original program name, 'exe'.
  496. """
  497. for p in self.__paths:
  498. fn = os.path.join(os.path.abspath(p), exe)
  499. if os.path.isfile(fn):
  500. return fn
  501. # didn't find it; try existing path
  502. for p in string.split(os.environ['Path'],';'):
  503. fn = os.path.join(os.path.abspath(p),exe)
  504. if os.path.isfile(fn):
  505. return fn
  506. return exe
  507. def get_msvc_paths(self, path, platform='x86'):
  508. """Get a list of devstudio directories (include, lib or path).
  509. Return a list of strings. The list will be empty if unable to
  510. access the registry or appropriate registry keys not found.
  511. """
  512. if not _can_read_reg:
  513. return []
  514. path = path + " dirs"
  515. if self.__version >= 7:
  516. key = (r"%s\%0.1f\VC\VC_OBJECTS_PLATFORM_INFO\Win32\Directories"
  517. % (self.__root, self.__version))
  518. else:
  519. key = (r"%s\6.0\Build System\Components\Platforms"
  520. r"\Win32 (%s)\Directories" % (self.__root, platform))
  521. for base in HKEYS:
  522. d = read_values(base, key)
  523. if d:
  524. if self.__version >= 7:
  525. return string.split(self.__macros.sub(d[path]), ";")
  526. else:
  527. return string.split(d[path], ";")
  528. # MSVC 6 seems to create the registry entries we need only when
  529. # the GUI is run.
  530. if self.__version == 6:
  531. for base in HKEYS:
  532. if read_values(base, r"%s\6.0" % self.__root) is not None:
  533. self.warn("It seems you have Visual Studio 6 installed, "
  534. "but the expected registry settings are not present.\n"
  535. "You must at least run the Visual Studio GUI once "
  536. "so that these entries are created.")
  537. break
  538. return []
  539. def set_path_env_var(self, name):
  540. """Set environment variable 'name' to an MSVC path type value.
  541. This is equivalent to a SET command prior to execution of spawned
  542. commands.
  543. """
  544. if name == "lib":
  545. p = self.get_msvc_paths("library")
  546. else:
  547. p = self.get_msvc_paths(name)
  548. if p:
  549. os.environ[name] = string.join(p, ';')
  550. if get_build_version() >= 8.0:
  551. log.debug("Importing new compiler from distutils.msvc9compiler")
  552. OldMSVCCompiler = MSVCCompiler
  553. from distutils.msvc9compiler import MSVCCompiler
  554. # get_build_architecture not really relevant now we support cross-compile
  555. from distutils.msvc9compiler import MacroExpander