Regression: Add ANSI colours to highlight test status
[gem5.git] / SConstruct
1 # -*- mode:python -*-
2
3 # Copyright (c) 2011 Advanced Micro Devices, Inc.
4 # Copyright (c) 2009 The Hewlett-Packard Development Company
5 # Copyright (c) 2004-2005 The Regents of The University of Michigan
6 # All rights reserved.
7 #
8 # Redistribution and use in source and binary forms, with or without
9 # modification, are permitted provided that the following conditions are
10 # met: redistributions of source code must retain the above copyright
11 # notice, this list of conditions and the following disclaimer;
12 # redistributions in binary form must reproduce the above copyright
13 # notice, this list of conditions and the following disclaimer in the
14 # documentation and/or other materials provided with the distribution;
15 # neither the name of the copyright holders nor the names of its
16 # contributors may be used to endorse or promote products derived from
17 # this software without specific prior written permission.
18 #
19 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 #
31 # Authors: Steve Reinhardt
32 # Nathan Binkert
33
34 ###################################################
35 #
36 # SCons top-level build description (SConstruct) file.
37 #
38 # While in this directory ('gem5'), just type 'scons' to build the default
39 # configuration (see below), or type 'scons build/<CONFIG>/<binary>'
40 # to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
41 # the optimized full-system version).
42 #
43 # You can build gem5 in a different directory as long as there is a
44 # 'build/<CONFIG>' somewhere along the target path. The build system
45 # expects that all configs under the same build directory are being
46 # built for the same host system.
47 #
48 # Examples:
49 #
50 # The following two commands are equivalent. The '-u' option tells
51 # scons to search up the directory tree for this SConstruct file.
52 # % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
53 # % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
54 #
55 # The following two commands are equivalent and demonstrate building
56 # in a directory outside of the source tree. The '-C' option tells
57 # scons to chdir to the specified directory to find this SConstruct
58 # file.
59 # % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
60 # % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
61 #
62 # You can use 'scons -H' to print scons options. If you're in this
63 # 'gem5' directory (or use -u or -C to tell scons where to find this
64 # file), you can use 'scons -h' to print all the gem5-specific build
65 # options as well.
66 #
67 ###################################################
68
69 # Check for recent-enough Python and SCons versions.
70 try:
71 # Really old versions of scons only take two options for the
72 # function, so check once without the revision and once with the
73 # revision, the first instance will fail for stuff other than
74 # 0.98, and the second will fail for 0.98.0
75 EnsureSConsVersion(0, 98)
76 EnsureSConsVersion(0, 98, 1)
77 except SystemExit, e:
78 print """
79 For more details, see:
80 http://gem5.org/Dependencies
81 """
82 raise
83
84 # We ensure the python version early because we have stuff that
85 # requires python 2.4
86 try:
87 EnsurePythonVersion(2, 4)
88 except SystemExit, e:
89 print """
90 You can use a non-default installation of the Python interpreter by
91 either (1) rearranging your PATH so that scons finds the non-default
92 'python' first or (2) explicitly invoking an alternative interpreter
93 on the scons script.
94
95 For more details, see:
96 http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
97 """
98 raise
99
100 # Global Python includes
101 import os
102 import re
103 import subprocess
104 import sys
105
106 from os import mkdir, environ
107 from os.path import abspath, basename, dirname, expanduser, normpath
108 from os.path import exists, isdir, isfile
109 from os.path import join as joinpath, split as splitpath
110
111 # SCons includes
112 import SCons
113 import SCons.Node
114
115 extra_python_paths = [
116 Dir('src/python').srcnode().abspath, # gem5 includes
117 Dir('ext/ply').srcnode().abspath, # ply is used by several files
118 ]
119
120 sys.path[1:1] = extra_python_paths
121
122 from m5.util import compareVersions, readCommand
123 from m5.util.terminal import get_termcap
124
125 help_texts = {
126 "options" : "",
127 "global_vars" : "",
128 "local_vars" : ""
129 }
130
131 Export("help_texts")
132
133
134 # There's a bug in scons in that (1) by default, the help texts from
135 # AddOption() are supposed to be displayed when you type 'scons -h'
136 # and (2) you can override the help displayed by 'scons -h' using the
137 # Help() function, but these two features are incompatible: once
138 # you've overridden the help text using Help(), there's no way to get
139 # at the help texts from AddOptions. See:
140 # http://scons.tigris.org/issues/show_bug.cgi?id=2356
141 # http://scons.tigris.org/issues/show_bug.cgi?id=2611
142 # This hack lets us extract the help text from AddOptions and
143 # re-inject it via Help(). Ideally someday this bug will be fixed and
144 # we can just use AddOption directly.
145 def AddLocalOption(*args, **kwargs):
146 col_width = 30
147
148 help = " " + ", ".join(args)
149 if "help" in kwargs:
150 length = len(help)
151 if length >= col_width:
152 help += "\n" + " " * col_width
153 else:
154 help += " " * (col_width - length)
155 help += kwargs["help"]
156 help_texts["options"] += help + "\n"
157
158 AddOption(*args, **kwargs)
159
160 AddLocalOption('--colors', dest='use_colors', action='store_true',
161 help="Add color to abbreviated scons output")
162 AddLocalOption('--no-colors', dest='use_colors', action='store_false',
163 help="Don't add color to abbreviated scons output")
164 AddLocalOption('--default', dest='default', type='string', action='store',
165 help='Override which build_opts file to use for defaults')
166 AddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
167 help='Disable style checking hooks')
168 AddLocalOption('--update-ref', dest='update_ref', action='store_true',
169 help='Update test reference outputs')
170 AddLocalOption('--verbose', dest='verbose', action='store_true',
171 help='Print full tool command lines')
172
173 termcap = get_termcap(GetOption('use_colors'))
174
175 ########################################################################
176 #
177 # Set up the main build environment.
178 #
179 ########################################################################
180 use_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH', 'PATH',
181 'PYTHONPATH', 'RANLIB' ])
182
183 use_env = {}
184 for key,val in os.environ.iteritems():
185 if key in use_vars or key.startswith("M5"):
186 use_env[key] = val
187
188 main = Environment(ENV=use_env)
189 main.Decider('MD5-timestamp')
190 main.root = Dir(".") # The current directory (where this file lives).
191 main.srcdir = Dir("src") # The source directory
192
193 # add useful python code PYTHONPATH so it can be used by subprocesses
194 # as well
195 main.AppendENVPath('PYTHONPATH', extra_python_paths)
196
197 ########################################################################
198 #
199 # Mercurial Stuff.
200 #
201 # If the gem5 directory is a mercurial repository, we should do some
202 # extra things.
203 #
204 ########################################################################
205
206 hgdir = main.root.Dir(".hg")
207
208 mercurial_style_message = """
209 You're missing the gem5 style hook, which automatically checks your code
210 against the gem5 style rules on hg commit and qrefresh commands. This
211 script will now install the hook in your .hg/hgrc file.
212 Press enter to continue, or ctrl-c to abort: """
213
214 mercurial_style_hook = """
215 # The following lines were automatically added by gem5/SConstruct
216 # to provide the gem5 style-checking hooks
217 [extensions]
218 style = %s/util/style.py
219
220 [hooks]
221 pretxncommit.style = python:style.check_style
222 pre-qrefresh.style = python:style.check_style
223 # End of SConstruct additions
224
225 """ % (main.root.abspath)
226
227 mercurial_lib_not_found = """
228 Mercurial libraries cannot be found, ignoring style hook. If
229 you are a gem5 developer, please fix this and run the style
230 hook. It is important.
231 """
232
233 # Check for style hook and prompt for installation if it's not there.
234 # Skip this if --ignore-style was specified, there's no .hg dir to
235 # install a hook in, or there's no interactive terminal to prompt.
236 if not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
237 style_hook = True
238 try:
239 from mercurial import ui
240 ui = ui.ui()
241 ui.readconfig(hgdir.File('hgrc').abspath)
242 style_hook = ui.config('hooks', 'pretxncommit.style', None) and \
243 ui.config('hooks', 'pre-qrefresh.style', None)
244 except ImportError:
245 print mercurial_lib_not_found
246
247 if not style_hook:
248 print mercurial_style_message,
249 # continue unless user does ctrl-c/ctrl-d etc.
250 try:
251 raw_input()
252 except:
253 print "Input exception, exiting scons.\n"
254 sys.exit(1)
255 hgrc_path = '%s/.hg/hgrc' % main.root.abspath
256 print "Adding style hook to", hgrc_path, "\n"
257 try:
258 hgrc = open(hgrc_path, 'a')
259 hgrc.write(mercurial_style_hook)
260 hgrc.close()
261 except:
262 print "Error updating", hgrc_path
263 sys.exit(1)
264
265
266 ###################################################
267 #
268 # Figure out which configurations to set up based on the path(s) of
269 # the target(s).
270 #
271 ###################################################
272
273 # Find default configuration & binary.
274 Default(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
275
276 # helper function: find last occurrence of element in list
277 def rfind(l, elt, offs = -1):
278 for i in range(len(l)+offs, 0, -1):
279 if l[i] == elt:
280 return i
281 raise ValueError, "element not found"
282
283 # Take a list of paths (or SCons Nodes) and return a list with all
284 # paths made absolute and ~-expanded. Paths will be interpreted
285 # relative to the launch directory unless a different root is provided
286 def makePathListAbsolute(path_list, root=GetLaunchDir()):
287 return [abspath(joinpath(root, expanduser(str(p))))
288 for p in path_list]
289
290 # Each target must have 'build' in the interior of the path; the
291 # directory below this will determine the build parameters. For
292 # example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
293 # recognize that ALPHA_SE specifies the configuration because it
294 # follow 'build' in the build path.
295
296 # The funky assignment to "[:]" is needed to replace the list contents
297 # in place rather than reassign the symbol to a new list, which
298 # doesn't work (obviously!).
299 BUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
300
301 # Generate a list of the unique build roots and configs that the
302 # collected targets reference.
303 variant_paths = []
304 build_root = None
305 for t in BUILD_TARGETS:
306 path_dirs = t.split('/')
307 try:
308 build_top = rfind(path_dirs, 'build', -2)
309 except:
310 print "Error: no non-leaf 'build' dir found on target path", t
311 Exit(1)
312 this_build_root = joinpath('/',*path_dirs[:build_top+1])
313 if not build_root:
314 build_root = this_build_root
315 else:
316 if this_build_root != build_root:
317 print "Error: build targets not under same build root\n"\
318 " %s\n %s" % (build_root, this_build_root)
319 Exit(1)
320 variant_path = joinpath('/',*path_dirs[:build_top+2])
321 if variant_path not in variant_paths:
322 variant_paths.append(variant_path)
323
324 # Make sure build_root exists (might not if this is the first build there)
325 if not isdir(build_root):
326 mkdir(build_root)
327 main['BUILDROOT'] = build_root
328
329 Export('main')
330
331 main.SConsignFile(joinpath(build_root, "sconsign"))
332
333 # Default duplicate option is to use hard links, but this messes up
334 # when you use emacs to edit a file in the target dir, as emacs moves
335 # file to file~ then copies to file, breaking the link. Symbolic
336 # (soft) links work better.
337 main.SetOption('duplicate', 'soft-copy')
338
339 #
340 # Set up global sticky variables... these are common to an entire build
341 # tree (not specific to a particular build like ALPHA_SE)
342 #
343
344 global_vars_file = joinpath(build_root, 'variables.global')
345
346 global_vars = Variables(global_vars_file, args=ARGUMENTS)
347
348 global_vars.AddVariables(
349 ('CC', 'C compiler', environ.get('CC', main['CC'])),
350 ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
351 ('BATCH', 'Use batch pool for build and tests', False),
352 ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
353 ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
354 ('EXTRAS', 'Add extra directories to the compilation', '')
355 )
356
357 # Update main environment with values from ARGUMENTS & global_vars_file
358 global_vars.Update(main)
359 help_texts["global_vars"] += global_vars.GenerateHelpText(main)
360
361 # Save sticky variable settings back to current variables file
362 global_vars.Save(global_vars_file, main)
363
364 # Parse EXTRAS variable to build list of all directories where we're
365 # look for sources etc. This list is exported as extras_dir_list.
366 base_dir = main.srcdir.abspath
367 if main['EXTRAS']:
368 extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
369 else:
370 extras_dir_list = []
371
372 Export('base_dir')
373 Export('extras_dir_list')
374
375 # the ext directory should be on the #includes path
376 main.Append(CPPPATH=[Dir('ext')])
377
378 def strip_build_path(path, env):
379 path = str(path)
380 variant_base = env['BUILDROOT'] + os.path.sep
381 if path.startswith(variant_base):
382 path = path[len(variant_base):]
383 elif path.startswith('build/'):
384 path = path[6:]
385 return path
386
387 # Generate a string of the form:
388 # common/path/prefix/src1, src2 -> tgt1, tgt2
389 # to print while building.
390 class Transform(object):
391 # all specific color settings should be here and nowhere else
392 tool_color = termcap.Normal
393 pfx_color = termcap.Yellow
394 srcs_color = termcap.Yellow + termcap.Bold
395 arrow_color = termcap.Blue + termcap.Bold
396 tgts_color = termcap.Yellow + termcap.Bold
397
398 def __init__(self, tool, max_sources=99):
399 self.format = self.tool_color + (" [%8s] " % tool) \
400 + self.pfx_color + "%s" \
401 + self.srcs_color + "%s" \
402 + self.arrow_color + " -> " \
403 + self.tgts_color + "%s" \
404 + termcap.Normal
405 self.max_sources = max_sources
406
407 def __call__(self, target, source, env, for_signature=None):
408 # truncate source list according to max_sources param
409 source = source[0:self.max_sources]
410 def strip(f):
411 return strip_build_path(str(f), env)
412 if len(source) > 0:
413 srcs = map(strip, source)
414 else:
415 srcs = ['']
416 tgts = map(strip, target)
417 # surprisingly, os.path.commonprefix is a dumb char-by-char string
418 # operation that has nothing to do with paths.
419 com_pfx = os.path.commonprefix(srcs + tgts)
420 com_pfx_len = len(com_pfx)
421 if com_pfx:
422 # do some cleanup and sanity checking on common prefix
423 if com_pfx[-1] == ".":
424 # prefix matches all but file extension: ok
425 # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
426 com_pfx = com_pfx[0:-1]
427 elif com_pfx[-1] == "/":
428 # common prefix is directory path: OK
429 pass
430 else:
431 src0_len = len(srcs[0])
432 tgt0_len = len(tgts[0])
433 if src0_len == com_pfx_len:
434 # source is a substring of target, OK
435 pass
436 elif tgt0_len == com_pfx_len:
437 # target is a substring of source, need to back up to
438 # avoid empty string on RHS of arrow
439 sep_idx = com_pfx.rfind(".")
440 if sep_idx != -1:
441 com_pfx = com_pfx[0:sep_idx]
442 else:
443 com_pfx = ''
444 elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
445 # still splitting at file extension: ok
446 pass
447 else:
448 # probably a fluke; ignore it
449 com_pfx = ''
450 # recalculate length in case com_pfx was modified
451 com_pfx_len = len(com_pfx)
452 def fmt(files):
453 f = map(lambda s: s[com_pfx_len:], files)
454 return ', '.join(f)
455 return self.format % (com_pfx, fmt(srcs), fmt(tgts))
456
457 Export('Transform')
458
459 # enable the regression script to use the termcap
460 main['TERMCAP'] = termcap
461
462 if GetOption('verbose'):
463 def MakeAction(action, string, *args, **kwargs):
464 return Action(action, *args, **kwargs)
465 else:
466 MakeAction = Action
467 main['CCCOMSTR'] = Transform("CC")
468 main['CXXCOMSTR'] = Transform("CXX")
469 main['ASCOMSTR'] = Transform("AS")
470 main['SWIGCOMSTR'] = Transform("SWIG")
471 main['ARCOMSTR'] = Transform("AR", 0)
472 main['LINKCOMSTR'] = Transform("LINK", 0)
473 main['RANLIBCOMSTR'] = Transform("RANLIB", 0)
474 main['M4COMSTR'] = Transform("M4")
475 main['SHCCCOMSTR'] = Transform("SHCC")
476 main['SHCXXCOMSTR'] = Transform("SHCXX")
477 Export('MakeAction')
478
479 CXX_version = readCommand([main['CXX'],'--version'], exception=False)
480 CXX_V = readCommand([main['CXX'],'-V'], exception=False)
481
482 main['GCC'] = CXX_version and CXX_version.find('g++') >= 0
483 main['SUNCC'] = CXX_V and CXX_V.find('Sun C++') >= 0
484 main['ICC'] = CXX_V and CXX_V.find('Intel') >= 0
485 main['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
486 if main['GCC'] + main['SUNCC'] + main['ICC'] + main['CLANG'] > 1:
487 print 'Error: How can we have two at the same time?'
488 Exit(1)
489
490 # Set up default C++ compiler flags
491 if main['GCC']:
492 main.Append(CCFLAGS=['-pipe'])
493 main.Append(CCFLAGS=['-fno-strict-aliasing'])
494 main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
495 # Read the GCC version to check for versions with bugs
496 # Note CCVERSION doesn't work here because it is run with the CC
497 # before we override it from the command line
498 gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
499 main['GCC_VERSION'] = gcc_version
500 if not compareVersions(gcc_version, '4.4.1') or \
501 not compareVersions(gcc_version, '4.4.2'):
502 print 'Info: Tree vectorizer in GCC 4.4.1 & 4.4.2 is buggy, disabling.'
503 main.Append(CCFLAGS=['-fno-tree-vectorize'])
504 if compareVersions(gcc_version, '4.6') >= 0:
505 main.Append(CXXFLAGS=['-std=c++0x'])
506 elif main['ICC']:
507 pass #Fix me... add warning flags once we clean up icc warnings
508 elif main['SUNCC']:
509 main.Append(CCFLAGS=['-Qoption ccfe'])
510 main.Append(CCFLAGS=['-features=gcc'])
511 main.Append(CCFLAGS=['-features=extensions'])
512 main.Append(CCFLAGS=['-library=stlport4'])
513 main.Append(CCFLAGS=['-xar'])
514 #main.Append(CCFLAGS=['-instances=semiexplicit'])
515 elif main['CLANG']:
516 clang_version_re = re.compile(".* version (\d+\.\d+)")
517 clang_version_match = clang_version_re.match(CXX_version)
518 if (clang_version_match):
519 clang_version = clang_version_match.groups()[0]
520 if compareVersions(clang_version, "2.9") < 0:
521 print 'Error: clang version 2.9 or newer required.'
522 print ' Installed version:', clang_version
523 Exit(1)
524 else:
525 print 'Error: Unable to determine clang version.'
526 Exit(1)
527
528 main.Append(CCFLAGS=['-pipe'])
529 main.Append(CCFLAGS=['-fno-strict-aliasing'])
530 main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
531 main.Append(CCFLAGS=['-Wno-tautological-compare'])
532 main.Append(CCFLAGS=['-Wno-self-assign'])
533 # Ruby makes frequent use of extraneous parantheses in the printing
534 # of if-statements
535 main.Append(CCFLAGS=['-Wno-parentheses'])
536
537 if compareVersions(clang_version, "3") >= 0:
538 main.Append(CXXFLAGS=['-std=c++0x'])
539 else:
540 print 'Error: Don\'t know what compiler options to use for your compiler.'
541 print ' Please fix SConstruct and src/SConscript and try again.'
542 Exit(1)
543
544 # Set up common yacc/bison flags (needed for Ruby)
545 main['YACCFLAGS'] = '-d'
546 main['YACCHXXFILESUFFIX'] = '.hh'
547
548 # Do this after we save setting back, or else we'll tack on an
549 # extra 'qdo' every time we run scons.
550 if main['BATCH']:
551 main['CC'] = main['BATCH_CMD'] + ' ' + main['CC']
552 main['CXX'] = main['BATCH_CMD'] + ' ' + main['CXX']
553 main['AS'] = main['BATCH_CMD'] + ' ' + main['AS']
554 main['AR'] = main['BATCH_CMD'] + ' ' + main['AR']
555 main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
556
557 if sys.platform == 'cygwin':
558 # cygwin has some header file issues...
559 main.Append(CCFLAGS=["-Wno-uninitialized"])
560
561 # Check for SWIG
562 if not main.has_key('SWIG'):
563 print 'Error: SWIG utility not found.'
564 print ' Please install (see http://www.swig.org) and retry.'
565 Exit(1)
566
567 # Check for appropriate SWIG version
568 swig_version = readCommand(('swig', '-version'), exception='').split()
569 # First 3 words should be "SWIG Version x.y.z"
570 if len(swig_version) < 3 or \
571 swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
572 print 'Error determining SWIG version.'
573 Exit(1)
574
575 min_swig_version = '1.3.28'
576 if compareVersions(swig_version[2], min_swig_version) < 0:
577 print 'Error: SWIG version', min_swig_version, 'or newer required.'
578 print ' Installed version:', swig_version[2]
579 Exit(1)
580
581 # Set up SWIG flags & scanner
582 swig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
583 main.Append(SWIGFLAGS=swig_flags)
584
585 # filter out all existing swig scanners, they mess up the dependency
586 # stuff for some reason
587 scanners = []
588 for scanner in main['SCANNERS']:
589 skeys = scanner.skeys
590 if skeys == '.i':
591 continue
592
593 if isinstance(skeys, (list, tuple)) and '.i' in skeys:
594 continue
595
596 scanners.append(scanner)
597
598 # add the new swig scanner that we like better
599 from SCons.Scanner import ClassicCPP as CPPScanner
600 swig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
601 scanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
602
603 # replace the scanners list that has what we want
604 main['SCANNERS'] = scanners
605
606 # Add a custom Check function to the Configure context so that we can
607 # figure out if the compiler adds leading underscores to global
608 # variables. This is needed for the autogenerated asm files that we
609 # use for embedding the python code.
610 def CheckLeading(context):
611 context.Message("Checking for leading underscore in global variables...")
612 # 1) Define a global variable called x from asm so the C compiler
613 # won't change the symbol at all.
614 # 2) Declare that variable.
615 # 3) Use the variable
616 #
617 # If the compiler prepends an underscore, this will successfully
618 # link because the external symbol 'x' will be called '_x' which
619 # was defined by the asm statement. If the compiler does not
620 # prepend an underscore, this will not successfully link because
621 # '_x' will have been defined by assembly, while the C portion of
622 # the code will be trying to use 'x'
623 ret = context.TryLink('''
624 asm(".globl _x; _x: .byte 0");
625 extern int x;
626 int main() { return x; }
627 ''', extension=".c")
628 context.env.Append(LEADING_UNDERSCORE=ret)
629 context.Result(ret)
630 return ret
631
632 # Platform-specific configuration. Note again that we assume that all
633 # builds under a given build root run on the same host platform.
634 conf = Configure(main,
635 conf_dir = joinpath(build_root, '.scons_config'),
636 log_file = joinpath(build_root, 'scons_config.log'),
637 custom_tests = { 'CheckLeading' : CheckLeading })
638
639 # Check for leading underscores. Don't really need to worry either
640 # way so don't need to check the return code.
641 conf.CheckLeading()
642
643 # Check if we should compile a 64 bit binary on Mac OS X/Darwin
644 try:
645 import platform
646 uname = platform.uname()
647 if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
648 if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
649 main.Append(CCFLAGS=['-arch', 'x86_64'])
650 main.Append(CFLAGS=['-arch', 'x86_64'])
651 main.Append(LINKFLAGS=['-arch', 'x86_64'])
652 main.Append(ASFLAGS=['-arch', 'x86_64'])
653 except:
654 pass
655
656 # Recent versions of scons substitute a "Null" object for Configure()
657 # when configuration isn't necessary, e.g., if the "--help" option is
658 # present. Unfortuantely this Null object always returns false,
659 # breaking all our configuration checks. We replace it with our own
660 # more optimistic null object that returns True instead.
661 if not conf:
662 def NullCheck(*args, **kwargs):
663 return True
664
665 class NullConf:
666 def __init__(self, env):
667 self.env = env
668 def Finish(self):
669 return self.env
670 def __getattr__(self, mname):
671 return NullCheck
672
673 conf = NullConf(main)
674
675 # Find Python include and library directories for embedding the
676 # interpreter. For consistency, we will use the same Python
677 # installation used to run scons (and thus this script). If you want
678 # to link in an alternate version, see above for instructions on how
679 # to invoke scons with a different copy of the Python interpreter.
680 from distutils import sysconfig
681
682 py_getvar = sysconfig.get_config_var
683
684 py_debug = getattr(sys, 'pydebug', False)
685 py_version = 'python' + py_getvar('VERSION') + (py_debug and "_d" or "")
686
687 py_general_include = sysconfig.get_python_inc()
688 py_platform_include = sysconfig.get_python_inc(plat_specific=True)
689 py_includes = [ py_general_include ]
690 if py_platform_include != py_general_include:
691 py_includes.append(py_platform_include)
692
693 py_lib_path = [ py_getvar('LIBDIR') ]
694 # add the prefix/lib/pythonX.Y/config dir, but only if there is no
695 # shared library in prefix/lib/.
696 if not py_getvar('Py_ENABLE_SHARED'):
697 py_lib_path.append(py_getvar('LIBPL'))
698
699 py_libs = []
700 for lib in py_getvar('LIBS').split() + py_getvar('SYSLIBS').split():
701 if not lib.startswith('-l'):
702 # Python requires some special flags to link (e.g. -framework
703 # common on OS X systems), assume appending preserves order
704 main.Append(LINKFLAGS=[lib])
705 else:
706 lib = lib[2:]
707 if lib not in py_libs:
708 py_libs.append(lib)
709 py_libs.append(py_version)
710
711 main.Append(CPPPATH=py_includes)
712 main.Append(LIBPATH=py_lib_path)
713
714 # Cache build files in the supplied directory.
715 if main['M5_BUILD_CACHE']:
716 print 'Using build cache located at', main['M5_BUILD_CACHE']
717 CacheDir(main['M5_BUILD_CACHE'])
718
719
720 # verify that this stuff works
721 if not conf.CheckHeader('Python.h', '<>'):
722 print "Error: can't find Python.h header in", py_includes
723 Exit(1)
724
725 for lib in py_libs:
726 if not conf.CheckLib(lib):
727 print "Error: can't find library %s required by python" % lib
728 Exit(1)
729
730 # On Solaris you need to use libsocket for socket ops
731 if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
732 if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
733 print "Can't find library with socket calls (e.g. accept())"
734 Exit(1)
735
736 # Check for zlib. If the check passes, libz will be automatically
737 # added to the LIBS environment variable.
738 if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
739 print 'Error: did not find needed zlib compression library '\
740 'and/or zlib.h header file.'
741 print ' Please install zlib and try again.'
742 Exit(1)
743
744 # Check for librt.
745 have_posix_clock = \
746 conf.CheckLibWithHeader(None, 'time.h', 'C',
747 'clock_nanosleep(0,0,NULL,NULL);') or \
748 conf.CheckLibWithHeader('rt', 'time.h', 'C',
749 'clock_nanosleep(0,0,NULL,NULL);')
750
751 if not have_posix_clock:
752 print "Can't find library for POSIX clocks."
753
754 # Check for <fenv.h> (C99 FP environment control)
755 have_fenv = conf.CheckHeader('fenv.h', '<>')
756 if not have_fenv:
757 print "Warning: Header file <fenv.h> not found."
758 print " This host has no IEEE FP rounding mode control."
759
760 ######################################################################
761 #
762 # Finish the configuration
763 #
764 main = conf.Finish()
765
766 ######################################################################
767 #
768 # Collect all non-global variables
769 #
770
771 # Define the universe of supported ISAs
772 all_isa_list = [ ]
773 Export('all_isa_list')
774
775 class CpuModel(object):
776 '''The CpuModel class encapsulates everything the ISA parser needs to
777 know about a particular CPU model.'''
778
779 # Dict of available CPU model objects. Accessible as CpuModel.dict.
780 dict = {}
781 list = []
782 defaults = []
783
784 # Constructor. Automatically adds models to CpuModel.dict.
785 def __init__(self, name, filename, includes, strings, default=False):
786 self.name = name # name of model
787 self.filename = filename # filename for output exec code
788 self.includes = includes # include files needed in exec file
789 # The 'strings' dict holds all the per-CPU symbols we can
790 # substitute into templates etc.
791 self.strings = strings
792
793 # This cpu is enabled by default
794 self.default = default
795
796 # Add self to dict
797 if name in CpuModel.dict:
798 raise AttributeError, "CpuModel '%s' already registered" % name
799 CpuModel.dict[name] = self
800 CpuModel.list.append(name)
801
802 Export('CpuModel')
803
804 # Sticky variables get saved in the variables file so they persist from
805 # one invocation to the next (unless overridden, in which case the new
806 # value becomes sticky).
807 sticky_vars = Variables(args=ARGUMENTS)
808 Export('sticky_vars')
809
810 # Sticky variables that should be exported
811 export_vars = []
812 Export('export_vars')
813
814 # Walk the tree and execute all SConsopts scripts that wil add to the
815 # above variables
816 if not GetOption('verbose'):
817 print "Reading SConsopts"
818 for bdir in [ base_dir ] + extras_dir_list:
819 if not isdir(bdir):
820 print "Error: directory '%s' does not exist" % bdir
821 Exit(1)
822 for root, dirs, files in os.walk(bdir):
823 if 'SConsopts' in files:
824 if GetOption('verbose'):
825 print "Reading", joinpath(root, 'SConsopts')
826 SConscript(joinpath(root, 'SConsopts'))
827
828 all_isa_list.sort()
829
830 sticky_vars.AddVariables(
831 EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
832 ListVariable('CPU_MODELS', 'CPU models',
833 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
834 sorted(CpuModel.list)),
835 BoolVariable('NO_FAST_ALLOC', 'Disable fast object allocator', False),
836 BoolVariable('FORCE_FAST_ALLOC',
837 'Enable fast object allocator, even for gem5.debug', False),
838 BoolVariable('FAST_ALLOC_STATS', 'Enable fast object allocator statistics',
839 False),
840 BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
841 False),
842 BoolVariable('SS_COMPATIBLE_FP',
843 'Make floating-point results compatible with SimpleScalar',
844 False),
845 BoolVariable('USE_SSE2',
846 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
847 False),
848 BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
849 BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
850 BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
851 )
852
853 # These variables get exported to #defines in config/*.hh (see src/SConscript).
854 export_vars += ['USE_FENV', 'NO_FAST_ALLOC', 'FORCE_FAST_ALLOC',
855 'FAST_ALLOC_STATS', 'SS_COMPATIBLE_FP',
856 'TARGET_ISA', 'CP_ANNOTATE', 'USE_POSIX_CLOCK' ]
857
858 ###################################################
859 #
860 # Define a SCons builder for configuration flag headers.
861 #
862 ###################################################
863
864 # This function generates a config header file that #defines the
865 # variable symbol to the current variable setting (0 or 1). The source
866 # operands are the name of the variable and a Value node containing the
867 # value of the variable.
868 def build_config_file(target, source, env):
869 (variable, value) = [s.get_contents() for s in source]
870 f = file(str(target[0]), 'w')
871 print >> f, '#define', variable, value
872 f.close()
873 return None
874
875 # Combine the two functions into a scons Action object.
876 config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
877
878 # The emitter munges the source & target node lists to reflect what
879 # we're really doing.
880 def config_emitter(target, source, env):
881 # extract variable name from Builder arg
882 variable = str(target[0])
883 # True target is config header file
884 target = joinpath('config', variable.lower() + '.hh')
885 val = env[variable]
886 if isinstance(val, bool):
887 # Force value to 0/1
888 val = int(val)
889 elif isinstance(val, str):
890 val = '"' + val + '"'
891
892 # Sources are variable name & value (packaged in SCons Value nodes)
893 return ([target], [Value(variable), Value(val)])
894
895 config_builder = Builder(emitter = config_emitter, action = config_action)
896
897 main.Append(BUILDERS = { 'ConfigFile' : config_builder })
898
899 # libelf build is shared across all configs in the build root.
900 main.SConscript('ext/libelf/SConscript',
901 variant_dir = joinpath(build_root, 'libelf'))
902
903 # gzstream build is shared across all configs in the build root.
904 main.SConscript('ext/gzstream/SConscript',
905 variant_dir = joinpath(build_root, 'gzstream'))
906
907 ###################################################
908 #
909 # This function is used to set up a directory with switching headers
910 #
911 ###################################################
912
913 main['ALL_ISA_LIST'] = all_isa_list
914 def make_switching_dir(dname, switch_headers, env):
915 # Generate the header. target[0] is the full path of the output
916 # header to generate. 'source' is a dummy variable, since we get the
917 # list of ISAs from env['ALL_ISA_LIST'].
918 def gen_switch_hdr(target, source, env):
919 fname = str(target[0])
920 f = open(fname, 'w')
921 isa = env['TARGET_ISA'].lower()
922 print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
923 f.close()
924
925 # Build SCons Action object. 'varlist' specifies env vars that this
926 # action depends on; when env['ALL_ISA_LIST'] changes these actions
927 # should get re-executed.
928 switch_hdr_action = MakeAction(gen_switch_hdr,
929 Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
930
931 # Instantiate actions for each header
932 for hdr in switch_headers:
933 env.Command(hdr, [], switch_hdr_action)
934 Export('make_switching_dir')
935
936 ###################################################
937 #
938 # Define build environments for selected configurations.
939 #
940 ###################################################
941
942 for variant_path in variant_paths:
943 print "Building in", variant_path
944
945 # Make a copy of the build-root environment to use for this config.
946 env = main.Clone()
947 env['BUILDDIR'] = variant_path
948
949 # variant_dir is the tail component of build path, and is used to
950 # determine the build parameters (e.g., 'ALPHA_SE')
951 (build_root, variant_dir) = splitpath(variant_path)
952
953 # Set env variables according to the build directory config.
954 sticky_vars.files = []
955 # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
956 # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
957 # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
958 current_vars_file = joinpath(build_root, 'variables', variant_dir)
959 if isfile(current_vars_file):
960 sticky_vars.files.append(current_vars_file)
961 print "Using saved variables file %s" % current_vars_file
962 else:
963 # Build dir-specific variables file doesn't exist.
964
965 # Make sure the directory is there so we can create it later
966 opt_dir = dirname(current_vars_file)
967 if not isdir(opt_dir):
968 mkdir(opt_dir)
969
970 # Get default build variables from source tree. Variables are
971 # normally determined by name of $VARIANT_DIR, but can be
972 # overridden by '--default=' arg on command line.
973 default = GetOption('default')
974 opts_dir = joinpath(main.root.abspath, 'build_opts')
975 if default:
976 default_vars_files = [joinpath(build_root, 'variables', default),
977 joinpath(opts_dir, default)]
978 else:
979 default_vars_files = [joinpath(opts_dir, variant_dir)]
980 existing_files = filter(isfile, default_vars_files)
981 if existing_files:
982 default_vars_file = existing_files[0]
983 sticky_vars.files.append(default_vars_file)
984 print "Variables file %s not found,\n using defaults in %s" \
985 % (current_vars_file, default_vars_file)
986 else:
987 print "Error: cannot find variables file %s or " \
988 "default file(s) %s" \
989 % (current_vars_file, ' or '.join(default_vars_files))
990 Exit(1)
991
992 # Apply current variable settings to env
993 sticky_vars.Update(env)
994
995 help_texts["local_vars"] += \
996 "Build variables for %s:\n" % variant_dir \
997 + sticky_vars.GenerateHelpText(env)
998
999 # Process variable settings.
1000
1001 if not have_fenv and env['USE_FENV']:
1002 print "Warning: <fenv.h> not available; " \
1003 "forcing USE_FENV to False in", variant_dir + "."
1004 env['USE_FENV'] = False
1005
1006 if not env['USE_FENV']:
1007 print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1008 print " FP results may deviate slightly from other platforms."
1009
1010 if env['EFENCE']:
1011 env.Append(LIBS=['efence'])
1012
1013 # Save sticky variable settings back to current variables file
1014 sticky_vars.Save(current_vars_file, env)
1015
1016 if env['USE_SSE2']:
1017 env.Append(CCFLAGS=['-msse2'])
1018
1019 # The src/SConscript file sets up the build rules in 'env' according
1020 # to the configured variables. It returns a list of environments,
1021 # one for each variant build (debug, opt, etc.)
1022 envList = SConscript('src/SConscript', variant_dir = variant_path,
1023 exports = 'env')
1024
1025 # Set up the regression tests for each build.
1026 for e in envList:
1027 SConscript('tests/SConscript',
1028 variant_dir = joinpath(variant_path, 'tests', e.Label),
1029 exports = { 'env' : e }, duplicate = False)
1030
1031 # base help text
1032 Help('''
1033 Usage: scons [scons options] [build variables] [target(s)]
1034
1035 Extra scons options:
1036 %(options)s
1037
1038 Global build variables:
1039 %(global_vars)s
1040
1041 %(local_vars)s
1042 ''' % help_texts)