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

Python code coverage for Lib/packaging/compiler/msvc9compiler.py

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