149256c3db67b8d6c17e4dac682034663c13a404
[mesa.git] / scons / generic.py
1 """generic
2
3 Generic tool that provides a commmon ground for all platforms.
4
5 """
6
7 #
8 # Copyright 2008 Tungsten Graphics, Inc., Cedar Park, Texas.
9 # All Rights Reserved.
10 #
11 # Permission is hereby granted, free of charge, to any person obtaining a
12 # copy of this software and associated documentation files (the
13 # "Software"), to deal in the Software without restriction, including
14 # without limitation the rights to use, copy, modify, merge, publish,
15 # distribute, sub license, and/or sell copies of the Software, and to
16 # permit persons to whom the Software is furnished to do so, subject to
17 # the following conditions:
18 #
19 # The above copyright notice and this permission notice (including the
20 # next paragraph) shall be included in all copies or substantial portions
21 # of the Software.
22 #
23 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
24 # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
26 # IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS BE LIABLE FOR
27 # ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
28 # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
29 # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 #
31
32
33 import os
34 import os.path
35 import re
36 import platform as _platform
37 import sys
38
39 import SCons.Action
40 import SCons.Builder
41 import SCons.Scanner
42
43
44 def symlink(target, source, env):
45 target = str(target[0])
46 source = str(source[0])
47 if os.path.islink(target) or os.path.exists(target):
48 os.remove(target)
49 os.symlink(os.path.basename(source), target)
50
51 def install_shared_library(env, source, version = ()):
52 source = str(source[0])
53 version = tuple(map(str, version))
54 target_dir = os.path.join(env.Dir('#.').srcnode().abspath, env['build'], 'lib')
55 target_name = '.'.join((str(source),) + version)
56 last = env.InstallAs(os.path.join(target_dir, target_name), source)
57 while len(version):
58 version = version[:-1]
59 target_name = '.'.join((str(source),) + version)
60 action = SCons.Action.Action(symlink, "$TARGET -> $SOURCE")
61 last = env.Command(os.path.join(target_dir, target_name), last, action)
62
63 def createInstallMethods(env):
64 env.AddMethod(install_shared_library, 'InstallSharedLibrary')
65
66
67 _platform_map = {
68 'linux2': 'linux',
69 'win32': 'windows',
70 }
71
72
73 _machine_map = {
74 'x86': 'x86',
75 'i386': 'x86',
76 'i486': 'x86',
77 'i586': 'x86',
78 'i686': 'x86',
79 'ppc': 'ppc',
80 'x86_64': 'x86_64',
81 }
82
83
84 _toolchain_map = {
85 'winddk': 'winddk',
86 'wince': 'wcesdk',
87 }
88
89
90 _bool_map = {
91 'y': 1,
92 'yes': 1,
93 't': 1,
94 'true': 1,
95 '1': 1,
96 'on': 1,
97 'all': 1,
98 'n': 0,
99 'no': 0,
100 'f': 0,
101 'false': 0,
102 '0': 0,
103 'off': 0,
104 'none': 0,
105 }
106
107
108 def num_jobs():
109 try:
110 return int(os.environ['NUMBER_OF_PROCESSORS'])
111 except (ValueError, KeyError):
112 pass
113
114 try:
115 return os.sysconf('SC_NPROCESSORS_ONLN')
116 except (ValueError, OSError, AttributeError):
117 pass
118
119 try:
120 return int(os.popen2("sysctl -n hw.ncpu")[1].read())
121 except ValueError:
122 pass
123
124 return 1
125
126
127 def generate(env):
128 """Common environment generation code"""
129
130 from SCons.Script import ARGUMENTS
131
132 # FIXME: this is already too late
133 #if env.get('quiet', False):
134 # quietCommandLines(env)
135
136
137 # Platform
138 try:
139 env['platform'] = ARGUMENTS['platform']
140 except KeyError:
141 env['platform'] = _platform_map.get(sys.platform, sys.platform)
142
143 # Machine
144 try:
145 env['machine'] = ARGUMENTS['machine']
146 except KeyError:
147 env['machine'] = _machine_map.get(os.environ.get('PROCESSOR_ARCHITECTURE', _platform.machine()), 'generic')
148
149 # Toolchain
150 try:
151 env['toolchain'] = ARGUMENTS['toolchain']
152 except KeyError:
153 if env['platform'] in ('windows', 'winddk', 'wince') and sys.platform != 'win32':
154 env['toolchain'] = 'crossmingw'
155 else:
156 env['toolchain'] = _toolchain_map.get(env['platform'], 'default')
157 if env['toolchain'] == 'crossmingw' and env['machine'] not in ('generic', 'x86'):
158 env['machine'] = 'x86'
159
160 try:
161 env['MSVS_VERSION'] = ARGUMENTS['MSVS_VERSION']
162 except KeyError:
163 pass
164
165 # Build type
166 env['debug'] = _bool_map[ARGUMENTS.get('debug', 'no')]
167 env['profile'] = _bool_map[ARGUMENTS.get('profile', 'no')]
168
169 # Put build output in a separate dir, which depends on the current
170 # configuration. See also http://www.scons.org/wiki/AdvancedBuildExample
171 try:
172 env['build'] = ARGUMENTS['build']
173 except KeyError:
174 build_topdir = 'build'
175 build_subdir = env['platform']
176 if env['machine'] != 'generic':
177 build_subdir += '-' + env['machine']
178 if env['debug']:
179 build_subdir += "-debug"
180 if env['profile']:
181 build_subdir += "-profile"
182 env['build'] = os.path.join(build_topdir, build_subdir)
183 # Place the .sconsign file in the build dir too, to avoid issues with
184 # different scons versions building the same source file
185 env.SConsignFile(os.path.join(env['build'], '.sconsign'))
186
187 # Parallel build
188 if env.GetOption('num_jobs') <= 1:
189 env.SetOption('num_jobs', num_jobs())
190
191 # Summary
192 print
193 print ' platform=%s' % env['platform']
194 print ' machine=%s' % env['machine']
195 print ' toolchain=%s' % env['toolchain']
196 print ' debug=%s' % ['no', 'yes'][env['debug']]
197 print ' profile=%s' % ['no', 'yes'][env['profile']]
198 print ' build=%s' % env['build']
199 print ' %s jobs' % env.GetOption('num_jobs')
200 print
201
202 # Load tool chain
203 env.Tool(env['toolchain'])
204
205 env['gcc'] = 'gcc' in os.path.basename(env['CC']).split('-')
206 env['msvc'] = env['CC'] == 'cl'
207
208 # shortcuts
209 debug = env['debug']
210 machine = env['machine']
211 platform = env['platform']
212 x86 = env['machine'] == 'x86'
213 ppc = env['machine'] == 'ppc'
214 gcc = env['gcc']
215 msvc = env['msvc']
216
217 # C preprocessor options
218 cppdefines = []
219 if debug:
220 cppdefines += ['DEBUG']
221 else:
222 cppdefines += ['NDEBUG']
223 if env['profile']:
224 cppdefines += ['PROFILE']
225 if platform == 'windows':
226 cppdefines += [
227 'WIN32',
228 '_WINDOWS',
229 #'_UNICODE',
230 #'UNICODE',
231 ]
232 if msvc:
233 cppdefines += [
234 'VC_EXTRALEAN',
235 '_USE_MATH_DEFINES',
236 '_CRT_SECURE_NO_WARNINGS',
237 '_CRT_SECURE_NO_DEPRECATE',
238 '_SCL_SECURE_NO_WARNINGS',
239 '_SCL_SECURE_NO_DEPRECATE',
240 ]
241 if debug:
242 cppdefines += ['_DEBUG']
243 if platform == 'winddk':
244 # Mimic WINDDK's builtin flags. See also:
245 # - WINDDK's bin/makefile.new i386mk.inc for more info.
246 # - buildchk_wxp_x86.log files, generated by the WINDDK's build
247 # - http://alter.org.ua/docs/nt_kernel/vc8_proj/
248 cppdefines += [
249 ('_X86_', '1'),
250 ('i386', '1'),
251 'STD_CALL',
252 ('CONDITION_HANDLING', '1'),
253 ('NT_INST', '0'),
254 ('WIN32', '100'),
255 ('_NT1X_', '100'),
256 ('WINNT', '1'),
257 ('_WIN32_WINNT', '0x0501'), # minimum required OS version
258 ('WINVER', '0x0501'),
259 ('_WIN32_IE', '0x0603'),
260 ('WIN32_LEAN_AND_MEAN', '1'),
261 ('DEVL', '1'),
262 ('__BUILDMACHINE__', 'WinDDK'),
263 ('FPO', '0'),
264 ]
265 if debug:
266 cppdefines += [('DBG', 1)]
267 if platform == 'wince':
268 cppdefines += [
269 '_CRT_SECURE_NO_DEPRECATE',
270 '_USE_32BIT_TIME_T',
271 'UNICODE',
272 '_UNICODE',
273 ('UNDER_CE', '600'),
274 ('_WIN32_WCE', '0x600'),
275 'WINCEOEM',
276 'WINCEINTERNAL',
277 'WIN32',
278 'STRICT',
279 'x86',
280 '_X86_',
281 'INTERNATIONAL',
282 ('INTLMSG_CODEPAGE', '1252'),
283 ]
284 env.Append(CPPDEFINES = cppdefines)
285
286 # C preprocessor includes
287 if platform == 'winddk':
288 env.Append(CPPPATH = [
289 env['SDK_INC_PATH'],
290 env['DDK_INC_PATH'],
291 env['WDM_INC_PATH'],
292 env['CRT_INC_PATH'],
293 ])
294
295 # C compiler options
296 cflags = [] # C
297 cxxflags = [] # C++
298 ccflags = [] # C & C++
299 if gcc:
300 if debug:
301 ccflags += ['-O0', '-g3']
302 elif env['toolchain'] == 'crossmingw':
303 ccflags += ['-O0', '-g3'] # mingw 4.2.1 optimizer is broken
304 else:
305 ccflags += ['-O3', '-g0']
306 if env['machine'] == 'x86':
307 ccflags += [
308 '-m32',
309 #'-march=pentium4',
310 '-mmmx', '-msse', '-msse2', # enable SIMD intrinsics
311 #'-mfpmath=sse',
312 ]
313 if env['machine'] == 'x86_64':
314 ccflags += ['-m64']
315 # See also:
316 # - http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html
317 ccflags += [
318 '-Wall',
319 '-Wmissing-field-initializers',
320 '-Wpointer-arith',
321 '-Wno-long-long',
322 '-ffast-math',
323 '-fmessage-length=0', # be nice to Eclipse
324 ]
325 cflags += [
326 '-Werror=declaration-after-statement',
327 '-Wmissing-prototypes',
328 '-std=gnu99',
329 ]
330 if msvc:
331 # See also:
332 # - http://msdn.microsoft.com/en-us/library/19z1t1wy.aspx
333 # - cl /?
334 if debug:
335 ccflags += [
336 '/Od', # disable optimizations
337 '/Oi', # enable intrinsic functions
338 '/Oy-', # disable frame pointer omission
339 '/GL-', # disable whole program optimization
340 ]
341 else:
342 ccflags += [
343 '/Ox', # maximum optimizations
344 '/Oi', # enable intrinsic functions
345 '/Ot', # favor code speed
346 #'/fp:fast', # fast floating point
347 ]
348 ccflags += [
349 '/W3', # warning level
350 #'/Wp64', # enable 64 bit porting warnings
351 ]
352 if env['machine'] == 'x86':
353 ccflags += [
354 #'/QIfist', # Suppress _ftol
355 #'/arch:SSE2', # use the SSE2 instructions
356 ]
357 if platform == 'windows':
358 ccflags += [
359 # TODO
360 ]
361 if platform == 'winddk':
362 ccflags += [
363 '/Zl', # omit default library name in .OBJ
364 '/Zp8', # 8bytes struct member alignment
365 '/Gy', # separate functions for linker
366 '/Gm-', # disable minimal rebuild
367 '/WX', # treat warnings as errors
368 '/Gz', # __stdcall Calling convention
369 '/GX-', # disable C++ EH
370 '/GR-', # disable C++ RTTI
371 '/GF', # enable read-only string pooling
372 '/G6', # optimize for PPro, P-II, P-III
373 '/Ze', # enable extensions
374 '/Gi-', # disable incremental compilation
375 '/QIfdiv-', # disable Pentium FDIV fix
376 '/hotpatch', # prepares an image for hotpatching.
377 #'/Z7', #enable old-style debug info
378 ]
379 if platform == 'wince':
380 # See also C:\WINCE600\public\common\oak\misc\makefile.def
381 ccflags += [
382 '/Zl', # omit default library name in .OBJ
383 '/GF', # enable read-only string pooling
384 '/GR-', # disable C++ RTTI
385 '/GS', # enable security checks
386 # Allow disabling language conformance to maintain backward compat
387 #'/Zc:wchar_t-', # don't force wchar_t as native type, instead of typedef
388 #'/Zc:forScope-', # don't enforce Standard C++ for scoping rules
389 #'/wd4867',
390 #'/wd4430',
391 #'/MT',
392 #'/U_MT',
393 ]
394 # Automatic pdb generation
395 # See http://scons.tigris.org/issues/show_bug.cgi?id=1656
396 env.EnsureSConsVersion(0, 98, 0)
397 env['PDB'] = '${TARGET.base}.pdb'
398 env.Append(CCFLAGS = ccflags)
399 env.Append(CFLAGS = cflags)
400 env.Append(CXXFLAGS = cxxflags)
401
402 if env['platform'] == 'windows' and msvc:
403 # Choose the appropriate MSVC CRT
404 # http://msdn.microsoft.com/en-us/library/2kzt1wy3.aspx
405 if env['debug']:
406 env.Append(CCFLAGS = ['/MTd'])
407 env.Append(SHCCFLAGS = ['/LDd'])
408 else:
409 env.Append(CCFLAGS = ['/MT'])
410 env.Append(SHCCFLAGS = ['/LD'])
411
412 # Assembler options
413 if gcc:
414 if env['machine'] == 'x86':
415 env.Append(ASFLAGS = ['-m32'])
416 if env['machine'] == 'x86_64':
417 env.Append(ASFLAGS = ['-m64'])
418
419 # Linker options
420 linkflags = []
421 if gcc:
422 if env['machine'] == 'x86':
423 linkflags += ['-m32']
424 if env['machine'] == 'x86_64':
425 linkflags += ['-m64']
426 if platform == 'windows' and msvc:
427 # See also:
428 # - http://msdn2.microsoft.com/en-us/library/y0zzbyt4.aspx
429 linkflags += [
430 '/fixed:no',
431 '/incremental:no',
432 ]
433 if platform == 'winddk':
434 linkflags += [
435 '/merge:_PAGE=PAGE',
436 '/merge:_TEXT=.text',
437 '/section:INIT,d',
438 '/opt:ref',
439 '/opt:icf',
440 '/ignore:4198,4010,4037,4039,4065,4070,4078,4087,4089,4221',
441 '/incremental:no',
442 '/fullbuild',
443 '/release',
444 '/nodefaultlib',
445 '/wx',
446 '/debug',
447 '/debugtype:cv',
448 '/version:5.1',
449 '/osversion:5.1',
450 '/functionpadmin:5',
451 '/safeseh',
452 '/pdbcompress',
453 '/stack:0x40000,0x1000',
454 '/driver',
455 '/align:0x80',
456 '/subsystem:native,5.01',
457 '/base:0x10000',
458
459 '/entry:DrvEnableDriver',
460 ]
461 if env['debug'] or env['profile']:
462 linkflags += [
463 '/MAP', # http://msdn.microsoft.com/en-us/library/k7xkk3e2.aspx
464 ]
465 if platform == 'wince':
466 linkflags += [
467 '/nodefaultlib',
468 #'/incremental:no',
469 #'/fullbuild',
470 '/entry:_DllMainCRTStartup',
471 ]
472 env.Append(LINKFLAGS = linkflags)
473
474 # Default libs
475 env.Append(LIBS = [])
476
477 # Custom builders and methods
478 env.Tool('custom')
479 createInstallMethods(env)
480
481 # for debugging
482 #print env.Dump()
483
484
485 def exists(env):
486 return 1