Debian Codegraph @

rpython/translator/platform/windows.py

raw symbols SCIP
1 """Support for Windows."""
2 from __future__ import print_function
3
4 import py, os, sys, re, shutil
5
6 from rpython.translator.platform import CompilationError
7 from rpython.translator.platform import log, _run_subprocess
8 from rpython.translator.platform import Platform, posix
9
10 import rpython
11 rpydir = str(py.path.local(rpython.__file__).join('..'))
12
13 def _get_compiler_type(cc, x64_flag):
14 if not cc:
15 cc = os.environ.get('CC','')
16 if not cc:
17 return MsvcPlatform(x64=x64_flag)
18 elif cc.startswith('mingw') or cc == 'gcc':
19 return MingwPlatform(cc)
20 return MsvcPlatform(cc=cc, x64=x64_flag)
21
22 def _get_vcver0():
23 # try to get the compiler which served to compile python
24 msc_pos = sys.version.find('MSC v.')
25 if msc_pos != -1:
26 msc_ver = int(sys.version[msc_pos+6:msc_pos+10])
27 # 1500 -> 90, 1900 -> 140
28 vsver = (msc_ver / 10) - 60
29 return vsver
30 return None
31
32 def Windows(cc=None):
33 return _get_compiler_type(cc, False)
34
35 def Windows_x64(cc=None, ver0=None):
36 #raise Exception("Win64 is not supported. You must either build for Win32"
37 # " or contribute the missing support in PyPy.")
38 return _get_compiler_type(cc, True)
39
40 def _find_vcvarsall(version, x64flag):
41 import rpython.tool.setuptools_msvc as msvc
42 if x64flag:
43 arch = 'x64'
44 else:
45 arch = 'x86'
46 if version >= 140:
47 return msvc.msvc14_get_vc_env(arch)
48 else:
49 return msvc.msvc9_query_vcvarsall(version / 10.0, arch)
50
51 def _get_msvc_env(vsver, x64flag):
52 vcdict = None
53 toolsdir = None
54 try:
55 toolsdir = os.environ['VS%sCOMNTOOLS' % vsver]
56 except KeyError:
57 # use setuptools from python3 to find tools
58 try:
59 vcdict = _find_vcvarsall(vsver, x64flag)
60 except ImportError as e:
61 if 'setuptools' in str(e):
62 log.error('is setuptools installed (perhaps try %s -mensurepip)?' % sys.executable)
63 log.error('looking for compiler %s raised exception "%s' % (vsver, str(e)))
64 except Exception as e:
65 log.error('looking for compiler %s raised exception "%s' % (vsver, str(e)))
66 return None
67 else:
68 if x64flag:
69 vsinstalldir = os.path.abspath(os.path.join(toolsdir, '..', '..'))
70 vcinstalldir = os.path.join(vsinstalldir, 'VC')
71 vcbindir = os.path.join(vcinstalldir, 'BIN')
72 vcvars = os.path.join(vcbindir, 'amd64', 'vcvarsamd64.bat')
73 else:
74 vcvars = os.path.join(toolsdir, 'vsvars32.bat')
75 if not os.path.exists(vcvars):
76 # even msdn does not know which to run
77 # see https://msdn.microsoft.com/en-us/library/1700bbwd(v=vs.90).aspx
78 # which names both
79 vcvars = os.path.join(toolsdir, 'vcvars32.bat')
80
81 import subprocess
82 try:
83 popen = subprocess.Popen('"%s" & set' % (vcvars,),
84 stdout=subprocess.PIPE,
85 stderr=subprocess.PIPE)
86
87 stdout, stderr = popen.communicate()
88 if popen.wait() != 0 or stdout[:5].lower() == 'error':
89 log.msg('Running "%s" errored: \n\nstdout:\n%s\n\nstderr:\n%s' % (
90 vcvars, stdout.split()[0], stderr))
91 return None
92 else:
93 log.msg('Running "%s" succeeded' %(vcvars,))
94 except Exception as e:
95 log.msg('Running "%s" failed: "%s"' % (vcvars, str(e)))
96 return None
97
98 stdout = stdout.replace("\r\n", "\n")
99 vcdict = {}
100 for line in stdout.split("\n"):
101 if '=' not in line:
102 continue
103 key, value = line.split('=', 1)
104 vcdict[key] = value
105 env = {}
106 for key, value in vcdict.items():
107 if key.upper() in ['PATH', 'INCLUDE', 'LIB']:
108 if sys.version_info[0] < 3:
109 env[key.upper()] = value.encode('utf-8')
110 else:
111 env[key.upper()] = value
112 if 'PATH' not in env:
113 log.msg('Did not find "PATH" in stdout\n%s' %(stdout))
114 if not _find_executable('mt.exe', env['PATH']):
115 # For some reason the sdk bin path is missing?
116 # put it together from some other env variables that happened to exist
117 # on the buildbot where this occurred
118 if 'WindowsSDKVersion' in vcdict and 'WindowsSdkDir' in vcdict:
119 binpath = vcdict['WindowsSdkDir'] + '\\bin\\' + vcdict['WindowsSDKVersion'] + 'x86'
120 env['PATH'] += ';' + binpath
121 if not _find_executable('mt.exe', env['PATH']):
122 log.msg('Could not find mt.exe on path=%s' % env['PATH'])
123 log.msg('Running vsver %s set this env' % vsver)
124 for key, value in vcdict.items():
125 log.msg('%s=%s' %(key, value))
126 log.msg("Updated environment with vsver %d, using x64 %s" % (vsver, x64flag,))
127 return env
128
129 def find_msvc_env(x64flag=False, ver0=None):
130 vcvers = [160, 150, 141, 140, 100, 90]
131 if ver0 in vcvers:
132 vcvers.insert(0, ver0)
133 errs = []
134 for vsver in vcvers:
135 env = _get_msvc_env(vsver, x64flag)
136 if env is not None:
137 return env, vsver
138 log.error("Could not find a Microsoft Compiler")
139 # Assume that the compiler is already part of the environment
140
141 # copied from distutils.spawn
142 def _find_executable(executable, path=None):
143 """Tries to find 'executable' in the directories listed in 'path'.
144
145 A string listing directories separated by 'os.pathsep'; defaults to
146 os.environ['PATH']. Returns the complete filename or None if not found.
147 """
148 if path is None:
149 path = os.environ['PATH']
150 paths = path.split(os.pathsep)
151
152 for ext in '.exe', '':
153 newexe = executable + ext
154
155 if os.path.isfile(newexe):
156 return newexe
157 else:
158 for p in paths:
159 f = os.path.join(p, newexe)
160 if os.path.isfile(f):
161 # the file exists, we have a shot at spawn working
162 return f
163 return None
164
165 class MsvcPlatform(Platform):
166 name = "msvc"
167 so_ext = 'dll'
168 exe_ext = 'exe'
169
170 relevant_environ = ('PATH', 'INCLUDE', 'LIB')
171
172 cc = 'cl.exe'
173 link = 'link.exe'
174 make = 'nmake'
175 if _find_executable('jom.exe'):
176 make = 'jom.exe'
177
178 cflags = ('/MD', '/O2', '/FS', '/Zi')
179 # allow >2GB address space, set stack to 3MB (1MB is too small)
180 link_flags = ('/nologo', '/debug','/LARGEADDRESSAWARE',
181 '/STACK:3145728', '/MANIFEST:EMBED')
182 standalone_only = ()
183 shared_only = ()
184 environ = None
185
186 def __init__(self, cc=None, x64=False, ver0=None):
187 self.x64 = x64
188 patch_os_env(self.externals)
189 self.c_environ = os.environ.copy()
190 if cc is None:
191 msvc_compiler_environ, self.vsver = find_msvc_env(x64, ver0=ver0)
192 Platform.__init__(self, 'cl.exe')
193 if msvc_compiler_environ:
194 self.c_environ.update(msvc_compiler_environ)
195 self.version = "MSVC %s" % str(self.vsver)
196 if self.vsver > 90:
197 tag = '14x'
198 else:
199 tag = '%d' % self.vsver
200 if x64:
201 self.externals_branch = 'win64_%s' % tag
202 else:
203 self.externals_branch = 'win32_%s' % tag
204 else:
205 self.cc = cc
206
207 # Try to find a masm assembler
208 # Dilemma: raise now or later if masm is not found. Postponing the
209 # exception means we can use a fake compiler for testing on linux
210 # but may mean cryptic error messages and wasted build time.
211 masm32 = "'Could not find ml.exe'"
212 masm64 = "'Could not find ml.exe'"
213 try:
214 returncode, stdout, stderr = _run_subprocess(
215 'ml.exe' if not x64 else 'ml64.exe', [], env=self.c_environ)
216 r = re.search('Macro Assembler', stderr)
217 except (EnvironmentError, OSError):
218 r = None
219 if r is not None:
220 masm32 = 'ml.exe'
221 masm64 = 'ml64.exe'
222 else:
223 if os.path.exists('c:/masm64/bin/masm64.exe'):
224 masm64 = 'c:/masm64/bin/masm64.exe'
225 if os.path.exists('c:/masm32/bin/masm32.exe'):
226 masm64 = 'c:/masm32/bin/masm32.exe'
227 if x64:
228 self.masm = masm64
229 else:
230 self.masm = masm32
231
232 # Install debug options only when interpreter is in debug mode
233 if sys.executable.lower().endswith('_d.exe'):
234 self.cflags = ['/MDd', '/Z7', '/Od']
235
236 # Increase stack size, for the linker and the stack check code.
237 stack_size = 8 << 20 # 8 Mb
238 self.link_flags = self.link_flags + ('/STACK:%d' % stack_size,)
239 # The following symbol is used in c/src/stack.h
240 self.cflags.append('/DMAX_STACK_SIZE=%d' % (stack_size - 1024))
241
242 def _includedirs(self, include_dirs):
243 return ['/I%s' % (idir,) for idir in include_dirs]
244
245 def _libs(self, libraries):
246 libs = []
247 for lib in libraries:
248 lib = str(lib)
249 if lib.endswith('.dll'):
250 lib = lib[:-4]
251 libs.append('%s.lib' % (lib,))
252 libs.append("kernel32.lib")
253 return libs
254
255 def _libdirs(self, library_dirs):
256 return ['/LIBPATH:%s' % (ldir,) for ldir in library_dirs]
257
258 def _linkfiles(self, link_files):
259 return list(link_files)
260
261 def _args_for_shared(self, args, **kwds):
262 return ['/dll'] + args
263
264 def check___thread(self):
265 # __declspec(thread) does not seem to work when using assembler.
266 # Returning False will cause the program to use TlsAlloc functions.
267 # see src/thread_win7.h
268 return False
269
270 def _link_args_from_eci(self, eci, standalone):
271 # Windows needs to resolve all symbols even for DLLs
272 return super(MsvcPlatform, self)._link_args_from_eci(eci, standalone=True)
273
274 def _compile_c_file(self, cc, cfile, compile_args):
275 oname = self._make_o_file(cfile, ext='obj')
276 # notabene: (tismer)
277 # This function may be called for .c but also .asm files.
278 # The c compiler accepts any order of arguments, while
279 # the assembler still has the old behavior that all options
280 # must come first, and after the file name all options are ignored.
281 # So please be careful with the order of parameters! ;-)
282 pdb_dir = oname.dirname
283 if pdb_dir:
284 compile_args = compile_args + ['/Fd%s\\' % (pdb_dir,)]
285 args = ['/nologo', '/c'] + compile_args + ['/Fo%s' % (oname,), str(cfile)]
286 self._execute_c_compiler(cc, args, oname)
287 return oname
288
289 def _link(self, cc, ofiles, link_args, standalone, exe_name):
290 args = ['/nologo'] + [str(ofile) for ofile in ofiles] + link_args
291 args += ['/out:%s' % (exe_name,), '/incremental:no']
292 if not standalone:
293 args = self._args_for_shared(args)
294
295 # Tell the linker to embed a manifest with the default
296 # UAC level asInvoker (Visual Studio 2008 +)
297 args += ["/MANIFEST:EMBED"]
298
299 self._execute_c_compiler(self.link, args, exe_name)
300
301 return exe_name
302
303 def _handle_error(self, returncode, stdout, stderr, outname):
304 if returncode != 0:
305 # Microsoft compilers write compilation errors to stdout
306 stderr = stdout + stderr
307 errorfile = outname.new(ext='errors')
308 errorfile.write(stderr, mode='wb')
309 if self.log_errors:
310 stderrlines = stderr.splitlines()
311 for line in stderrlines:
312 log.Error(line)
313 # ^^^ don't use ERROR, because it might actually be fine.
314 # Also, ERROR confuses lib-python/conftest.py.
315 raise CompilationError(stdout, stderr)
316
317
318 def gen_makefile(self, cfiles, eci, exe_name=None, path=None,
319 shared=False, headers_to_precompile=[],
320 no_precompile_cfiles = [], profopt=False, config=None):
321 cfiles = self._all_cfiles(cfiles, eci)
322
323 if path is None:
324 path = cfiles[0].dirpath()
325
326 rpypath = py.path.local(rpydir)
327 m = NMakefile(path)
328
329 if exe_name is None:
330 exe_name = cfiles[0].new(ext='')
331 if shared:
332 so_name = exe_name.new(purebasename='lib' + exe_name.basename,
333 ext=self.so_ext)
334 wtarget_name = exe_name.new(purebasename=exe_name.basename + 'w',
335 ext=self.exe_ext)
336 target_name = so_name.basename
337 m.so_name = path.join(target_name)
338 m.wtarget_name = path.join(wtarget_name.basename)
339 m.exe_name = path.join(exe_name.basename + '.' + self.exe_ext)
340 else:
341 target_name = exe_name.basename + '.' + self.exe_ext
342 wtarget_name = exe_name.basename + 'w.' + self.exe_ext
343 m.exe_name = path.join(target_name)
344 m.wtarget_name = path.join(wtarget_name)
345
346 m.eci = eci
347
348 linkflags = list(self.link_flags)
349 if shared:
350 linkflags = self._args_for_shared(linkflags)
351 linkflags += self._exportsymbols_link_flags()
352 # Make sure different functions end up at different addresses!
353 # This is required for the JIT.
354 linkflags.append('/opt:noicf')
355
356 def rpyrel(fpath):
357 rel = py.path.local(fpath).relto(rpypath)
358 if rel:
359 return os.path.join('$(RPYDIR)', rel)
360 else:
361 return fpath
362
363 rel_cfiles = [m.pathrel(cfile) for cfile in cfiles]
364 rel_ofiles = [rel_cfile[:rel_cfile.rfind('.')]+'.obj' for rel_cfile in rel_cfiles]
365 m.cfiles = rel_cfiles
366
367 rel_includedirs = [rpyrel(incldir) for incldir in
368 self.preprocess_include_dirs(eci.include_dirs)]
369 rel_libdirs = [rpyrel(libdir) for libdir in
370 self.preprocess_library_dirs(eci.library_dirs)]
371
372 m.comment('automatically generated makefile')
373 definitions = [
374 ('RPYDIR', '"%s"' % rpydir),
375 ('TARGET', target_name),
376 ('DEFAULT_TARGET', m.exe_name.basename),
377 ('SOURCES', rel_cfiles),
378 ('OBJECTS', rel_ofiles),
379 ('LIBS', self._libs(eci.libraries)),
380 ('LIBDIRS', self._libdirs(rel_libdirs)),
381 ('INCLUDEDIRS', self._includedirs(rel_includedirs)),
382 ('CFLAGS', self.cflags),
383 ('CFLAGSEXTRA', list(eci.compile_extra)),
384 ('LDFLAGS', linkflags),
385 ('LDFLAGSEXTRA', list(eci.link_extra)),
386 ('CC', self.cc),
387 ('CC_LINK', self.link),
388 ('LINKFILES', eci.link_files),
389 ('MASM', self.masm),
390 ('MAKE', 'nmake.exe'),
391 ('_WIN32', '1'),
392 ]
393 if shared:
394 definitions.insert(0, ('WTARGET', wtarget_name.basename))
395 if self.x64:
396 definitions.append(('_WIN64', '1'))
397
398 if shared and self.make == 'jom.exe':
399 # Add `.SYNC` for jom.exe and get it to create
400 # main.c, wmain.c in a separate step before trying to compile them
401 rules = [('all',
402 'main.c wmain.c .SYNC $(DEFAULT_TARGET) .SYNC $(WTARGET)',
403 []),
404 ]
405 else:
406 rules = [('all', '$(DEFAULT_TARGET) $(WTARGET)', []),]
407 rules += [
408 ('.asm.obj', '', '$(MASM) /nologo /Fo$@ /c $< $(INCLUDEDIRS)'),
409 ]
410
411 if len(headers_to_precompile)>0:
412 if shared:
413 no_precompile_cfiles += [m.makefile_dir / 'main.c',
414 m.makefile_dir / 'wmain.c']
415 stdafx_h = path.join('stdafx.h')
416 txt = '#ifndef PYPY_STDAFX_H\n'
417 txt += '#define PYPY_STDAFX_H\n'
418 txt += '\n'.join(['#include "' + m.pathrel(c) + '"' for c in headers_to_precompile])
419 txt += '\n#endif\n'
420 stdafx_h.write(txt)
421 stdafx_c = path.join('stdafx.c')
422 stdafx_c.write('#include "stdafx.h"\n')
423 definitions.append(('CREATE_PCH', '/Ycstdafx.h /Fpstdafx.pch /FIstdafx.h'))
424 definitions.append(('USE_PCH', '/Yustdafx.h /Fpstdafx.pch /FIstdafx.h'))
425 rules.append(('$(OBJECTS)', 'stdafx.pch', []))
426 rules.append(('stdafx.pch', 'stdafx.h',
427 '$(CC) stdafx.c /c /nologo $(CFLAGS) $(CFLAGSEXTRA) '
428 '$(CREATE_PCH) $(INCLUDEDIRS)'))
429 rules.append(('.c.obj', '',
430 '$(CC) /nologo $(CFLAGS) $(CFLAGSEXTRA) $(USE_PCH) '
431 '/Fo$@ /c $< $(INCLUDEDIRS)'))
432 #Do not use precompiled headers for some files
433 #rules.append((r'{..\module_cache}.c{..\module_cache}.obj', '',
434 # '$(CC) /nologo $(CFLAGS) $(CFLAGSEXTRA) /Fo$@ /c $< $(INCLUDEDIRS)'))
435 # nmake cannot handle wildcard target specifications, so we must
436 # create a rule for compiling each file from eci since they cannot use
437 # precompiled headers :(
438 no_precompile = []
439 for f in list(no_precompile_cfiles):
440 f = m.pathrel(py.path.local(f))
441 if f not in no_precompile and (f.endswith('.c') or f.endswith('.cpp')):
442 no_precompile.append(f)
443 target = f[:f.rfind('.')] + '.obj'
444 rules.append((target, f,
445 '$(CC) /nologo $(CFLAGS) $(CFLAGSEXTRA) '
446 '/Fo%s /c %s $(INCLUDEDIRS)' %(target, f)))
447
448 else:
449 rules.append(('.c.obj', '',
450 '$(CC) /nologo $(CFLAGS) $(CFLAGSEXTRA) '
451 '/Fo$@ /c $< $(INCLUDEDIRS)'))
452 if shared:
453 rules.append(('main.obj', 'main.c',
454 '$(CC) /nologo $(CFLAGS) $(CFLAGSEXTRA) '
455 '/Fo$@ /c main.c $(INCLUDEDIRS)'))
456 rules.append(('wmain.obj', 'wmain.c',
457 '$(CC) /nologo $(CFLAGS) $(CFLAGSEXTRA) '
458 '/Fo$@ /c wmain.c $(INCLUDEDIRS)'))
459
460 icon = config.translation.icon if config else None
461 manifest = config.translation.manifest if config else None
462 if icon:
463 shutil.copyfile(icon, str(path.join('icon.ico')))
464 rc_file = path.join('icon.rc')
465 rc_file.write('IDI_ICON1 ICON DISCARDABLE "icon.ico"')
466 rules.append(('icon.res', 'icon.rc', 'rc icon.rc'))
467 if manifest:
468 shutil.copyfile(manifest, str(path.join('pypy.manifest')))
469
470
471 for args in definitions:
472 m.definition(*args)
473
474 for rule in rules:
475 m.rule(*rule)
476
477 if len(headers_to_precompile) > 0:
478 # at least from VS2013 onwards we need to include PCH
479 # objects in the final link command
480 linkobjs = 'stdafx.obj '
481 else:
482 linkobjs = ''
483 if len(' '.join(rel_ofiles)) > 2048:
484 # command line is limited in length, use a response file
485 linkobjs += '@<<\n$(OBJECTS)\n<<'
486 else:
487 linkobjs += '$(OBJECTS)'
488 extra_deps = []
489 if icon and not shared:
490 extra_deps.append('icon.res')
491 linkobjs = 'icon.res ' + linkobjs
492 if manifest and not shared:
493 linkflags.append('/MANIFESTINPUT:pypy.manifest')
494 m.rule('$(TARGET)', ['$(OBJECTS)'] + extra_deps,
495 [ '$(CC_LINK) $(LDFLAGS) $(LDFLAGSEXTRA)' +
496 ' $(LINKFILES) /out:$@ $(LIBDIRS) $(LIBS) ' +
497 linkobjs,
498 ])
499 m.rule('debugmode_$(TARGET)', ['$(OBJECTS)'] + extra_deps,
500 [ '$(CC_LINK) /DEBUG $(LDFLAGS) $(LDFLAGSEXTRA)' +
501 ' $(LINKFILES) /out:$@ $(LIBDIRS) $(LIBS) ' +
502 linkobjs,
503 ])
504
505 if shared:
506 m.definition('SHARED_IMPORT_LIB', so_name.new(ext='lib').basename)
507 m.definition('PYPY_MAIN_FUNCTION', "pypy_main_startup")
508 m.rule('main.c', '',
509 'echo '
510 'typedef unsigned short ARGV_T; '
511 'int $(PYPY_MAIN_FUNCTION)(int, ARGV_T*[]); '
512 'int wmain(int argc, ARGV_T* argv[]) '
513 '{ return $(PYPY_MAIN_FUNCTION)(argc, argv); } > $@')
514 deps = ['main.obj']
515 m.rule('wmain.c', '',
516 ['echo #define WIN32_LEAN_AND_MEAN > [email protected]',
517 'echo #include "stdlib.h" >> [email protected]',
518 'echo #include "windows.h" >> [email protected]',
519 'echo int $(PYPY_MAIN_FUNCTION)(int, wchar_t*[]); >> [email protected]',
520 'echo int WINAPI wWinMain( >> [email protected]',
521 'echo HINSTANCE hInstance, /* handle to current instance */ >> [email protected]',
522 'echo HINSTANCE hPrevInstance, /* handle to previous instance */ >> [email protected]',
523 'echo LPWSTR lpCmdLine, /* pointer to command line */ >> [email protected]',
524 'echo int nCmdShow /* show state of window */ >> [email protected]',
525 'echo ) >> [email protected]',
526 'echo { return $(PYPY_MAIN_FUNCTION)(__argc, __wargv); } >> [email protected]',
527 'move [email protected] $@',
528 ])
529 wdeps = ['wmain.obj']
530 if icon:
531 deps.append('icon.res')
532 wdeps.append('icon.res')
533 manifest_args = '/MANIFEST:EMBED'
534 if manifest:
535 manifest_args += ' /MANIFESTINPUT:pypy.manifest'
536 m.rule('$(DEFAULT_TARGET)', ['$(TARGET)'] + deps,
537 ['$(CC_LINK) /DEBUG /LARGEADDRESSAWARE /STACK:3145728 ' +
538 ' '.join(deps) + ' $(SHARED_IMPORT_LIB) ' +
539 manifest_args + ' /out:$@ '
540 ])
541 m.rule('$(WTARGET)', ['$(TARGET)'] + wdeps,
542 ['$(CC_LINK) /DEBUG /LARGEADDRESSAWARE /STACK:3145728 ' +
543 '/SUBSYSTEM:WINDOWS ' +
544 ' '.join(wdeps) + ' $(SHARED_IMPORT_LIB) ' +
545 manifest_args + ' /out:$@ '
546 ])
547 m.rule('debugmode_$(DEFAULT_TARGET)', ['debugmode_$(TARGET)']+deps,
548 ['$(CC_LINK) /DEBUG /LARGEADDRESSAWARE /STACK:3145728 ' +
549 ' '.join(deps) + ' debugmode_$(SHARED_IMPORT_LIB) ' +
550 manifest_args + ' /out:$@ '
551 ])
552
553 return m
554
555 def execute_makefile(self, path_to_makefile, extra_opts=[]):
556 if isinstance(path_to_makefile, NMakefile):
557 path = path_to_makefile.makefile_dir
558 else:
559 path = path_to_makefile
560 log.execute('%s %s in %s' % (self.make, " ".join(extra_opts), path))
561 oldcwd = path.chdir()
562 try:
563 returncode, stdout, stderr = _run_subprocess(
564 self.make,
565 ['/nologo', '/f', str(path.join('Makefile'))] + extra_opts,
566 env = self.c_environ)
567 finally:
568 oldcwd.chdir()
569
570 self._handle_error(returncode, stdout, stderr, path.join('make'))
571
572 # These are the external libraries, created and maintained by get_externals.py
573 # The buildbot runs get_externals before building
574 def patch_os_env(externals = Platform.externals):
575 #print 'adding %s to PATH, INCLUDE, LIB' % basepath
576 binpath = externals + r'\bin'
577 path = os.environ['PATH']
578 if binpath not in path:
579 path = binpath + ';' + path
580 # make sure externals is in current path for tests and translating
581 os.environ['PATH'] = path
582 if externals not in os.environ.get('INCLUDE', ''):
583 os.environ['INCLUDE'] = externals + r'\include;' + os.environ.get('INCLUDE', '')
584 if externals not in os.environ.get('LIB', ''):
585 os.environ['LIB'] = externals + r'\lib;' + os.environ.get('LIB', '')
586 return None
587
588 class WinDefinition(posix.Definition):
589 def write(self, f):
590 def write_list(prefix, lst):
591 lst = lst or ['']
592 for i, fn in enumerate(lst):
593 print(prefix, fn, end=" ", file=f)
594 if i < len(lst)-1:
595 print('\\', file=f)
596 else:
597 print(file=f)
598 prefix = ' ' * len(prefix)
599 name, value = self.name, self.value
600 if isinstance(value, str):
601 f.write('%s = %s\n' % (name, value))
602 else:
603 write_list('%s =' % (name,), value)
604 f.write('\n')
605
606
607 class NMakefile(posix.GnuMakefile):
608 def write(self, out=None):
609 # nmake expands macros when it parses rules.
610 # Write all macros before the rules.
611 if out is None:
612 f = self.makefile_dir.join('Makefile').open('w')
613 else:
614 f = out
615 for line in self.lines:
616 if not isinstance(line, posix.Rule):
617 line.write(f)
618 for line in self.lines:
619 if isinstance(line, posix.Rule):
620 line.write(f)
621 f.flush()
622 if out is None:
623 f.close()
624
625 def definition(self, name, value):
626 defs = self.defs
627 defn = WinDefinition(name, value)
628 if name in defs:
629 self.lines[defs[name]] = defn
630 else:
631 defs[name] = len(self.lines)
632 self.lines.append(defn)
633
634 class MingwPlatform(posix.BasePosix):
635 name = 'mingw32'
636 standalone_only = ()
637 shared_only = ()
638 cflags = ('-O3',)
639 link_flags = ()
640 exe_ext = 'exe'
641 so_ext = 'dll'
642
643 def __init__(self, cc=None):
644 if not cc:
645 cc = 'gcc'
646 Platform.__init__(self, cc)
647
648 def _args_for_shared(self, args, **kwds):
649 return ['-shared'] + args
650
651 def _include_dirs_for_libffi(self):
652 return []
653
654 def _library_dirs_for_libffi(self):
655 return []
656
657 def _handle_error(self, returncode, stdout, stderr, outname):
658 # Mingw tools write compilation errors to stdout
659 super(MingwPlatform, self)._handle_error(
660 returncode, '', stderr + stdout, outname)