mesa: use new ST_CALLOC_STRUCT() macro in gallium state tracker
[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 quietCommandLines(env):
45 # Quiet command lines
46 # See also http://www.scons.org/wiki/HidingCommandLinesInOutput
47 env['CCCOMSTR'] = "Compiling $SOURCE ..."
48 env['CXXCOMSTR'] = "Compiling $SOURCE ..."
49 env['ARCOMSTR'] = "Archiving $TARGET ..."
50 env['RANLIBCOMSTR'] = ""
51 env['LINKCOMSTR'] = "Linking $TARGET ..."
52
53
54 def createConvenienceLibBuilder(env):
55 """This is a utility function that creates the ConvenienceLibrary
56 Builder in an Environment if it is not there already.
57
58 If it is already there, we return the existing one.
59
60 Based on the stock StaticLibrary and SharedLibrary builders.
61 """
62
63 try:
64 convenience_lib = env['BUILDERS']['ConvenienceLibrary']
65 except KeyError:
66 action_list = [ SCons.Action.Action("$ARCOM", "$ARCOMSTR") ]
67 if env.Detect('ranlib'):
68 ranlib_action = SCons.Action.Action("$RANLIBCOM", "$RANLIBCOMSTR")
69 action_list.append(ranlib_action)
70
71 convenience_lib = SCons.Builder.Builder(action = action_list,
72 emitter = '$LIBEMITTER',
73 prefix = '$LIBPREFIX',
74 suffix = '$LIBSUFFIX',
75 src_suffix = '$SHOBJSUFFIX',
76 src_builder = 'SharedObject')
77 env['BUILDERS']['ConvenienceLibrary'] = convenience_lib
78
79 return convenience_lib
80
81
82 # TODO: handle import statements with multiple modules
83 # TODO: handle from import statements
84 import_re = re.compile(r'^import\s+(\S+)$', re.M)
85
86 def python_scan(node, env, path):
87 # http://www.scons.org/doc/0.98.5/HTML/scons-user/c2781.html#AEN2789
88 contents = node.get_contents()
89 source_dir = node.get_dir()
90 imports = import_re.findall(contents)
91 results = []
92 for imp in imports:
93 for dir in path:
94 file = os.path.join(str(dir), imp.replace('.', os.sep) + '.py')
95 if os.path.exists(file):
96 results.append(env.File(file))
97 break
98 file = os.path.join(str(dir), imp.replace('.', os.sep), '__init__.py')
99 if os.path.exists(file):
100 results.append(env.File(file))
101 break
102 return results
103
104 python_scanner = SCons.Scanner.Scanner(function = python_scan, skeys = ['.py'])
105
106
107 def code_generate(env, script, target, source, command):
108 """Method to simplify code generation via python scripts.
109
110 http://www.scons.org/wiki/UsingCodeGenerators
111 http://www.scons.org/doc/0.98.5/HTML/scons-user/c2768.html
112 """
113
114 # We're generating code using Python scripts, so we have to be
115 # careful with our scons elements. This entry represents
116 # the generator file *in the source directory*.
117 script_src = env.File(script).srcnode()
118
119 # This command creates generated code *in the build directory*.
120 command = command.replace('$SCRIPT', script_src.path)
121 code = env.Command(target, source, command)
122
123 # Explicitly mark that the generated code depends on the generator,
124 # and on implicitly imported python modules
125 path = (script_src.get_dir(),)
126 deps = [script_src]
127 deps += script_src.get_implicit_deps(env, python_scanner, path)
128 env.Depends(code, deps)
129
130 # Running the Python script causes .pyc files to be generated in the
131 # source directory. When we clean up, they should go too. So add side
132 # effects for .pyc files
133 for dep in deps:
134 pyc = env.File(str(dep) + 'c')
135 env.SideEffect(pyc, code)
136
137 return code
138
139
140 def createCodeGenerateMethod(env):
141 env.Append(SCANNERS = python_scanner)
142 env.AddMethod(code_generate, 'CodeGenerate')
143
144
145 def symlink(target, source, env):
146 target = str(target[0])
147 source = str(source[0])
148 if os.path.islink(target) or os.path.exists(target):
149 os.remove(target)
150 os.symlink(os.path.basename(source), target)
151
152 def install_shared_library(env, source, version = ()):
153 source = str(source[0])
154 version = tuple(map(str, version))
155 target_dir = os.path.join(env.Dir('#.').srcnode().abspath, env['build'], 'lib')
156 target_name = '.'.join((str(source),) + version)
157 last = env.InstallAs(os.path.join(target_dir, target_name), source)
158 while len(version):
159 version = version[:-1]
160 target_name = '.'.join((str(source),) + version)
161 action = SCons.Action.Action(symlink, "$TARGET -> $SOURCE")
162 last = env.Command(os.path.join(target_dir, target_name), last, action)
163
164 def createInstallMethods(env):
165 env.AddMethod(install_shared_library, 'InstallSharedLibrary')
166
167
168 _platform_map = {
169 'linux2': 'linux',
170 'win32': 'windows',
171 }
172
173
174 _machine_map = {
175 'x86': 'x86',
176 'i386': 'x86',
177 'i486': 'x86',
178 'i586': 'x86',
179 'i686': 'x86',
180 'ppc': 'ppc',
181 'x86_64': 'x86_64',
182 }
183
184
185 _toolchain_map = {
186 'winddk': 'winddk',
187 'wince': 'wcesdk',
188 }
189
190
191 _bool_map = {
192 'y': 1,
193 'yes': 1,
194 't': 1,
195 'true': 1,
196 '1': 1,
197 'on': 1,
198 'all': 1,
199 'n': 0,
200 'no': 0,
201 'f': 0,
202 'false': 0,
203 '0': 0,
204 'off': 0,
205 'none': 0,
206 }
207
208
209 def num_jobs():
210 try:
211 return int(os.environ['NUMBER_OF_PROCESSORS'])
212 except (ValueError, KeyError):
213 pass
214
215 try:
216 return os.sysconf('SC_NPROCESSORS_ONLN')
217 except (ValueError, OSError, AttributeError):
218 pass
219
220 try:
221 return int(os.popen2("sysctl -n hw.ncpu")[1].read())
222 except ValueError:
223 pass
224
225 return 1
226
227
228 def generate(env):
229 """Common environment generation code"""
230
231 from SCons.Script import ARGUMENTS
232
233 # FIXME: this is already too late
234 #if env.get('quiet', False):
235 # quietCommandLines(env)
236
237
238 # Platform
239 try:
240 env['platform'] = ARGUMENTS['platform']
241 except KeyError:
242 env['platform'] = _platform_map.get(sys.platform, sys.platform)
243
244 # Machine
245 try:
246 env['machine'] = ARGUMENTS['machine']
247 except KeyError:
248 env['machine'] = _machine_map.get(os.environ.get('PROCESSOR_ARCHITECTURE', _platform.machine()), 'generic')
249
250 # Toolchain
251 try:
252 env['toolchain'] = ARGUMENTS['toolchain']
253 except KeyError:
254 if env['platform'] in ('windows', 'winddk', 'wince') and sys.platform != 'win32':
255 env['toolchain'] = 'crossmingw'
256 else:
257 env['toolchain'] = _toolchain_map.get(env['platform'], 'default')
258 if env['toolchain'] == 'crossmingw' and env['machine'] not in ('generic', 'x86'):
259 env['machine'] = 'x86'
260
261 try:
262 env['MSVS_VERSION'] = ARGUMENTS['MSVS_VERSION']
263 except KeyError:
264 pass
265
266 # Build type
267 env['debug'] = _bool_map[ARGUMENTS.get('debug', 'no')]
268 env['profile'] = _bool_map[ARGUMENTS.get('profile', 'no')]
269
270 # Put build output in a separate dir, which depends on the current
271 # configuration. See also http://www.scons.org/wiki/AdvancedBuildExample
272 try:
273 env['build'] = ARGUMENTS['build']
274 except KeyError:
275 build_topdir = 'build'
276 build_subdir = env['platform']
277 if env['machine'] != 'generic':
278 build_subdir += '-' + env['machine']
279 if env['debug']:
280 build_subdir += "-debug"
281 if env['profile']:
282 build_subdir += "-profile"
283 env['build'] = os.path.join(build_topdir, build_subdir)
284 # Place the .sconsign file in the build dir too, to avoid issues with
285 # different scons versions building the same source file
286 env.SConsignFile(os.path.join(env['build'], '.sconsign'))
287
288 # Parallel build
289 if env.GetOption('num_jobs') <= 1:
290 env.SetOption('num_jobs', num_jobs())
291
292 # Summary
293 print
294 print ' platform=%s' % env['platform']
295 print ' machine=%s' % env['machine']
296 print ' toolchain=%s' % env['toolchain']
297 print ' debug=%s' % ['no', 'yes'][env['debug']]
298 print ' profile=%s' % ['no', 'yes'][env['profile']]
299 print ' build=%s' % env['build']
300 print ' %s jobs' % env.GetOption('num_jobs')
301 print
302
303 # Load tool chain
304 env.Tool(env['toolchain'])
305
306 # shortcuts
307 debug = env['debug']
308 machine = env['machine']
309 platform = env['platform']
310 x86 = env['machine'] == 'x86'
311 ppc = env['machine'] == 'ppc'
312 gcc = env['platform'] in ('linux', 'freebsd', 'darwin') or env['toolchain'] == 'crossmingw'
313 msvc = env['platform'] in ('windows', 'winddk', 'wince') and env['toolchain'] != 'crossmingw'
314
315 # C preprocessor options
316 cppdefines = []
317 if debug:
318 cppdefines += ['DEBUG']
319 else:
320 cppdefines += ['NDEBUG']
321 if env['profile']:
322 cppdefines += ['PROFILE']
323 if platform == 'windows':
324 cppdefines += [
325 'WIN32',
326 '_WINDOWS',
327 #'_UNICODE',
328 #'UNICODE',
329 # http://msdn2.microsoft.com/en-us/library/6dwk3a1z.aspx,
330 #'WIN32_LEAN_AND_MEAN',
331 'VC_EXTRALEAN',
332 '_CRT_SECURE_NO_DEPRECATE',
333 ]
334 if debug:
335 cppdefines += ['_DEBUG']
336 if platform == 'winddk':
337 # Mimic WINDDK's builtin flags. See also:
338 # - WINDDK's bin/makefile.new i386mk.inc for more info.
339 # - buildchk_wxp_x86.log files, generated by the WINDDK's build
340 # - http://alter.org.ua/docs/nt_kernel/vc8_proj/
341 cppdefines += [
342 ('_X86_', '1'),
343 ('i386', '1'),
344 'STD_CALL',
345 ('CONDITION_HANDLING', '1'),
346 ('NT_INST', '0'),
347 ('WIN32', '100'),
348 ('_NT1X_', '100'),
349 ('WINNT', '1'),
350 ('_WIN32_WINNT', '0x0501'), # minimum required OS version
351 ('WINVER', '0x0501'),
352 ('_WIN32_IE', '0x0603'),
353 ('WIN32_LEAN_AND_MEAN', '1'),
354 ('DEVL', '1'),
355 ('__BUILDMACHINE__', 'WinDDK'),
356 ('FPO', '0'),
357 ]
358 if debug:
359 cppdefines += [('DBG', 1)]
360 if platform == 'wince':
361 cppdefines += [
362 '_CRT_SECURE_NO_DEPRECATE',
363 '_USE_32BIT_TIME_T',
364 'UNICODE',
365 '_UNICODE',
366 ('UNDER_CE', '600'),
367 ('_WIN32_WCE', '0x600'),
368 'WINCEOEM',
369 'WINCEINTERNAL',
370 'WIN32',
371 'STRICT',
372 'x86',
373 '_X86_',
374 'INTERNATIONAL',
375 ('INTLMSG_CODEPAGE', '1252'),
376 ]
377 env.Append(CPPDEFINES = cppdefines)
378
379 # C preprocessor includes
380 if platform == 'winddk':
381 env.Append(CPPPATH = [
382 env['SDK_INC_PATH'],
383 env['DDK_INC_PATH'],
384 env['WDM_INC_PATH'],
385 env['CRT_INC_PATH'],
386 ])
387
388 # C compiler options
389 cflags = [] # C
390 cxxflags = [] # C++
391 ccflags = [] # C & C++
392 if gcc:
393 if debug:
394 ccflags += ['-O0', '-g3']
395 else:
396 ccflags += ['-O3', '-g0']
397 if env['profile']:
398 ccflags += ['-pg']
399 if env['machine'] == 'x86':
400 ccflags += [
401 '-m32',
402 #'-march=pentium4',
403 '-mmmx', '-msse', '-msse2', # enable SIMD intrinsics
404 #'-mfpmath=sse',
405 ]
406 if env['machine'] == 'x86_64':
407 ccflags += ['-m64']
408 ccflags += [
409 '-Wall',
410 '-Wmissing-prototypes',
411 '-Wno-long-long',
412 '-ffast-math',
413 '-pedantic',
414 '-fmessage-length=0', # be nice to Eclipse
415 ]
416 cflags += [
417 '-Wmissing-prototypes',
418 ]
419 if msvc:
420 # See also:
421 # - http://msdn.microsoft.com/en-us/library/19z1t1wy.aspx
422 # - cl /?
423 if debug:
424 ccflags += [
425 '/Od', # disable optimizations
426 '/Oi', # enable intrinsic functions
427 '/Oy-', # disable frame pointer omission
428 '/GL-', # disable whole program optimization
429 ]
430 else:
431 ccflags += [
432 '/Ox', # maximum optimizations
433 '/Oi', # enable intrinsic functions
434 '/Ot', # favor code speed
435 #'/fp:fast', # fast floating point
436 ]
437 if env['profile']:
438 ccflags += [
439 '/Gh', # enable _penter hook function
440 '/GH', # enable _pexit hook function
441 ]
442 ccflags += [
443 '/W3', # warning level
444 #'/Wp64', # enable 64 bit porting warnings
445 ]
446 if env['machine'] == 'x86':
447 ccflags += [
448 #'/QIfist', # Suppress _ftol
449 #'/arch:SSE2', # use the SSE2 instructions
450 ]
451 if platform == 'windows':
452 ccflags += [
453 # TODO
454 ]
455 if platform == 'winddk':
456 ccflags += [
457 '/Zl', # omit default library name in .OBJ
458 '/Zp8', # 8bytes struct member alignment
459 '/Gy', # separate functions for linker
460 '/Gm-', # disable minimal rebuild
461 '/WX', # treat warnings as errors
462 '/Gz', # __stdcall Calling convention
463 '/GX-', # disable C++ EH
464 '/GR-', # disable C++ RTTI
465 '/GF', # enable read-only string pooling
466 '/G6', # optimize for PPro, P-II, P-III
467 '/Ze', # enable extensions
468 '/Gi-', # disable incremental compilation
469 '/QIfdiv-', # disable Pentium FDIV fix
470 '/hotpatch', # prepares an image for hotpatching.
471 #'/Z7', #enable old-style debug info
472 ]
473 if platform == 'wince':
474 # See also C:\WINCE600\public\common\oak\misc\makefile.def
475 ccflags += [
476 '/Zl', # omit default library name in .OBJ
477 '/GF', # enable read-only string pooling
478 '/GR-', # disable C++ RTTI
479 '/GS', # enable security checks
480 # Allow disabling language conformance to maintain backward compat
481 #'/Zc:wchar_t-', # don't force wchar_t as native type, instead of typedef
482 #'/Zc:forScope-', # don't enforce Standard C++ for scoping rules
483 #'/wd4867',
484 #'/wd4430',
485 #'/MT',
486 #'/U_MT',
487 ]
488 # Automatic pdb generation
489 # See http://scons.tigris.org/issues/show_bug.cgi?id=1656
490 env.EnsureSConsVersion(0, 98, 0)
491 env['PDB'] = '${TARGET.base}.pdb'
492 env.Append(CCFLAGS = ccflags)
493 env.Append(CFLAGS = cflags)
494 env.Append(CXXFLAGS = cxxflags)
495
496 if env['platform'] == 'windows' and msvc:
497 # Choose the appropriate MSVC CRT
498 # http://msdn.microsoft.com/en-us/library/2kzt1wy3.aspx
499 if env['debug']:
500 env.Append(CCFLAGS = ['/MTd'])
501 env.Append(SHCCFLAGS = ['/LDd'])
502 else:
503 env.Append(CCFLAGS = ['/MT'])
504 env.Append(SHCCFLAGS = ['/LD'])
505
506 # Assembler options
507 if gcc:
508 if env['machine'] == 'x86':
509 env.Append(ASFLAGS = ['-m32'])
510 if env['machine'] == 'x86_64':
511 env.Append(ASFLAGS = ['-m64'])
512
513 # Linker options
514 linkflags = []
515 if gcc:
516 if env['machine'] == 'x86':
517 linkflags += ['-m32']
518 if env['machine'] == 'x86_64':
519 linkflags += ['-m64']
520 if platform == 'windows' and msvc:
521 # See also:
522 # - http://msdn2.microsoft.com/en-us/library/y0zzbyt4.aspx
523 linkflags += [
524 '/fixed:no',
525 '/incremental:no',
526 ]
527 if platform == 'winddk':
528 linkflags += [
529 '/merge:_PAGE=PAGE',
530 '/merge:_TEXT=.text',
531 '/section:INIT,d',
532 '/opt:ref',
533 '/opt:icf',
534 '/ignore:4198,4010,4037,4039,4065,4070,4078,4087,4089,4221',
535 '/incremental:no',
536 '/fullbuild',
537 '/release',
538 '/nodefaultlib',
539 '/wx',
540 '/debug',
541 '/debugtype:cv',
542 '/version:5.1',
543 '/osversion:5.1',
544 '/functionpadmin:5',
545 '/safeseh',
546 '/pdbcompress',
547 '/stack:0x40000,0x1000',
548 '/driver',
549 '/align:0x80',
550 '/subsystem:native,5.01',
551 '/base:0x10000',
552
553 '/entry:DrvEnableDriver',
554 ]
555 if env['profile']:
556 linkflags += [
557 '/MAP', # http://msdn.microsoft.com/en-us/library/k7xkk3e2.aspx
558 ]
559 if platform == 'wince':
560 linkflags += [
561 '/nodefaultlib',
562 #'/incremental:no',
563 #'/fullbuild',
564 '/entry:_DllMainCRTStartup',
565 ]
566 env.Append(LINKFLAGS = linkflags)
567
568 # Default libs
569 env.Append(LIBS = [])
570
571 # Custom builders and methods
572 createConvenienceLibBuilder(env)
573 createCodeGenerateMethod(env)
574 createInstallMethods(env)
575
576 # for debugging
577 #print env.Dump()
578
579
580 def exists(env):
581 return 1