ยปCore Development>Code coverage>Lib/distutils/msvc9compiler.py

Python code coverage for Lib/distutils/msvc9compiler.py

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