building.py 30.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#
# File      : building.py
# This file is part of RT-Thread RTOS
# COPYRIGHT (C) 2006 - 2015, RT-Thread Development Team
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License along
#  with this program; if not, write to the Free Software Foundation, Inc.,
#  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Change Logs:
# Date           Author       Notes
# 2015-01-20     Bernard      Add copyright information
23
# 2015-07-25     Bernard      Add LOCAL_CCFLAGS/LOCAL_CPPPATH/LOCAL_CPPDEFINES for
24
#                             group definition.
25 26
#

G
goprife@gmail.com 已提交
27 28 29 30 31
import os
import sys
import string

from SCons.Script import *
32
from utils import _make_path_relative
33
from mkdist import do_copy_file
G
goprife@gmail.com 已提交
34 35 36 37 38 39

BuildOptions = {}
Projects = []
Rtt_Root = ''
Env = None

40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
# SCons PreProcessor patch
def start_handling_includes(self, t=None):
    """
    Causes the PreProcessor object to start processing #import,
    #include and #include_next lines.

    This method will be called when a #if, #ifdef, #ifndef or #elif
    evaluates True, or when we reach the #else in a #if, #ifdef,
    #ifndef or #elif block where a condition already evaluated
    False.

    """
    d = self.dispatch_table
    p = self.stack[-1] if self.stack else self.default_table

    for k in ('import', 'include', 'include_next', 'define'):
        d[k] = p[k]

def stop_handling_includes(self, t=None):
    """
    Causes the PreProcessor object to stop processing #import,
    #include and #include_next lines.

    This method will be called when a #if, #ifdef, #ifndef or #elif
    evaluates False, or when we reach the #else in a #if, #ifdef,
    #ifndef or #elif block where a condition already evaluated True.
    """
    d = self.dispatch_table
    d['import'] = self.do_nothing
    d['include'] =  self.do_nothing
    d['include_next'] =  self.do_nothing
    d['define'] =  self.do_nothing
72

73 74 75 76
PatchedPreProcessor = SCons.cpp.PreProcessor
PatchedPreProcessor.start_handling_includes = start_handling_includes
PatchedPreProcessor.stop_handling_includes = stop_handling_includes

G
goprife@gmail.com 已提交
77 78
class Win32Spawn:
    def spawn(self, sh, escape, cmd, args, env):
G
Grissiom 已提交
79 80 81 82 83 84 85 86 87 88 89
        # deal with the cmd build-in commands which cannot be used in
        # subprocess.Popen
        if cmd == 'del':
            for f in args[1:]:
                try:
                    os.remove(f)
                except Exception as e:
                    print 'Error removing file: %s' % e
                    return -1
            return 0

G
goprife@gmail.com 已提交
90 91 92 93
        import subprocess

        newargs = string.join(args[1:], ' ')
        cmdline = cmd + " " + newargs
G
Grissiom 已提交
94 95

        # Make sure the env is constructed by strings
96
        _e = dict([(k, str(v)) for k, v in env.items()])
G
Grissiom 已提交
97 98 99 100 101 102

        # Windows(tm) CreateProcess does not use the env passed to it to find
        # the executables. So we have to modify our own PATH to make Popen
        # work.
        old_path = os.environ['PATH']
        os.environ['PATH'] = _e['PATH']
103

G
Grissiom 已提交
104
        try:
105
            proc = subprocess.Popen(cmdline, env=_e, shell=False)
G
Grissiom 已提交
106
        except Exception as e:
107 108 109
            print 'Error in calling:\n%s' % cmdline
            print 'Exception: %s: %s' % (e, os.strerror(e.errno))
            return e.errno
G
Grissiom 已提交
110 111
        finally:
            os.environ['PATH'] = old_path
112

G
Grissiom 已提交
113
        return proc.wait()
G
goprife@gmail.com 已提交
114

115 116
# generate cconfig.h file
def GenCconfigFile(env, BuildOptions):
117
    import rtconfig
118

119 120 121 122 123
    if rtconfig.PLATFORM == 'gcc':
        contents = ''
        if not os.path.isfile('cconfig.h'):
            import gcc
            gcc.GenerateGCCConfig(rtconfig)
124

125 126 127 128 129 130
        # try again
        if os.path.isfile('cconfig.h'):
            f = file('cconfig.h', 'r')
            if f:
                contents = f.read()
                f.close();
131

132 133 134
                prep = PatchedPreProcessor()
                prep.process_contents(contents)
                options = prep.cpp_namespace
135

136 137 138 139
                BuildOptions.update(options)

                # add HAVE_CCONFIG_H definition
                env.AppendUnique(CPPDEFINES = ['HAVE_CCONFIG_H'])
140

141
def PrepareBuilding(env, root_directory, has_libcpu=False, remove_components = []):
G
goprife@gmail.com 已提交
142 143 144 145 146 147 148
    import rtconfig

    global BuildOptions
    global Projects
    global Env
    global Rtt_Root

149 150 151 152 153 154
    # ===== Add option to SCons =====
    AddOption('--dist',
                      dest = 'make-dist',
                      action = 'store_true',
                      default = False,
                      help = 'make distribution')
155 156 157 158 159
    AddOption('--dist-strip',
                      dest = 'make-dist-strip',
                      action = 'store_true',
                      default = False,
                      help = 'make distribution and strip useless files')
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
    AddOption('--cscope',
                      dest = 'cscope',
                      action = 'store_true',
                      default = False,
                      help = 'Build Cscope cross reference database. Requires cscope installed.')
    AddOption('--clang-analyzer',
                      dest = 'clang-analyzer',
                      action = 'store_true',
                      default = False,
                      help = 'Perform static analyze with Clang-analyzer. ' + \
                           'Requires Clang installed.\n' + \
                           'It is recommended to use with scan-build like this:\n' + \
                           '`scan-build scons --clang-analyzer`\n' + \
                           'If things goes well, scan-build will instruct you to invoke scan-view.')
    AddOption('--buildlib',
                      dest = 'buildlib',
                      type = 'string',
                      help = 'building library of a component')
    AddOption('--cleanlib',
                      dest = 'cleanlib',
                      action = 'store_true',
                      default = False,
                      help = 'clean up the library by --buildlib')
    AddOption('--target',
                      dest = 'target',
                      type = 'string',
                      help = 'set target project: mdk/mdk4/mdk5/iar/vs/vsc/ua/cdk')
    AddOption('--genconfig',
                dest = 'genconfig',
                action = 'store_true',
                default = False,
                help = 'Generate .config from rtconfig.h')
    AddOption('--useconfig',
                dest = 'useconfig',
                type = 'string',
                help = 'make rtconfig.h from config file.')
    AddOption('--verbose',
                dest = 'verbose',
                action = 'store_true',
                default = False,
                help = 'print verbose information during build')

G
goprife@gmail.com 已提交
202
    Env = env
203
    Rtt_Root = os.path.abspath(root_directory)
204 205 206 207 208
    # set RTT_ROOT in ENV
    Env['RTT_ROOT'] = Rtt_Root
    # set BSP_ROOT in ENV
    Env['BSP_ROOT'] = Dir('#').abspath

209
    sys.path = sys.path + [os.path.join(Rtt_Root, 'tools')]
G
goprife@gmail.com 已提交
210

211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
    # {target_name:(CROSS_TOOL, PLATFORM)}
    tgt_dict = {'mdk':('keil', 'armcc'),
                'mdk4':('keil', 'armcc'),
                'mdk5':('keil', 'armcc'),
                'iar':('iar', 'iar'),
                'vs':('msvc', 'cl'),
                'vs2012':('msvc', 'cl'),
                'vsc' : ('gcc', 'gcc'),
                'cb':('keil', 'armcc'),
                'ua':('gcc', 'gcc'),
                'cdk':('gcc', 'gcc')}
    tgt_name = GetOption('target')

    if tgt_name:
        # --target will change the toolchain settings which clang-analyzer is
        # depend on
        if GetOption('clang-analyzer'):
            print '--clang-analyzer cannot be used with --target'
            sys.exit(1)

        SetOption('no_exec', 1)
        try:
            rtconfig.CROSS_TOOL, rtconfig.PLATFORM = tgt_dict[tgt_name]
            # replace the 'RTT_CC' to 'CROSS_TOOL'
            os.environ['RTT_CC'] = rtconfig.CROSS_TOOL
            reload(rtconfig)
        except KeyError:
            print 'Unknow target: %s. Avaible targets: %s' % \
                    (tgt_name, ', '.join(tgt_dict.keys()))
            sys.exit(1)
    elif (GetDepend('RT_USING_NEWLIB') == False and GetDepend('RT_USING_NOLIBC') == False) \
        and rtconfig.PLATFORM == 'gcc':
        AddDepend('RT_USING_MINILIBC')

    # auto change the 'RTT_EXEC_PATH' when 'rtconfig.EXEC_PATH' get failed
    if not os.path.exists(rtconfig.EXEC_PATH):
247
        if 'RTT_EXEC_PATH' in os.environ:
248 249 250
            # del the 'RTT_EXEC_PATH' and using the 'EXEC_PATH' setting on rtconfig.py
            del os.environ['RTT_EXEC_PATH']
            reload(rtconfig)
251

252 253 254 255 256
    # add compability with Keil MDK 4.6 which changes the directory of armcc.exe
    if rtconfig.PLATFORM == 'armcc':
        if not os.path.isfile(os.path.join(rtconfig.EXEC_PATH, 'armcc.exe')):
            if rtconfig.EXEC_PATH.find('bin40') > 0:
                rtconfig.EXEC_PATH = rtconfig.EXEC_PATH.replace('bin40', 'armcc/bin')
257
                Env['LINKFLAGS'] = Env['LINKFLAGS'].replace('RV31', 'armcc')
258

B
Bright Pan 已提交
259
        # reset AR command flags
B
bernard 已提交
260
        env['ARCOM'] = '$AR --create $TARGET $SOURCES'
261 262
        env['LIBPREFIX'] = ''
        env['LIBSUFFIX'] = '.lib'
B
bernard 已提交
263
        env['LIBLINKPREFIX'] = ''
264
        env['LIBLINKSUFFIX'] = '.lib'
B
bernard 已提交
265
        env['LIBDIRPREFIX'] = '--userlibpath '
B
bernard 已提交
266

G
goprife@gmail.com 已提交
267
    # patch for win32 spawn
G
Grissiom 已提交
268
    if env['PLATFORM'] == 'win32':
G
goprife@gmail.com 已提交
269 270 271
        win32_spawn = Win32Spawn()
        win32_spawn.env = env
        env['SPAWN'] = win32_spawn.spawn
G
Grissiom 已提交
272

273
    if env['PLATFORM'] == 'win32':
274 275 276
        os.environ['PATH'] = rtconfig.EXEC_PATH + ";" + os.environ['PATH']
    else:
        os.environ['PATH'] = rtconfig.EXEC_PATH + ":" + os.environ['PATH']
G
goprife@gmail.com 已提交
277 278 279

    # add program path
    env.PrependENVPath('PATH', rtconfig.EXEC_PATH)
280 281
    # add rtconfig.h path
    env.Append(CPPPATH = [str(Dir('#').abspath)])
G
goprife@gmail.com 已提交
282

B
bernard 已提交
283 284 285 286 287
    # add library build action
    act = SCons.Action.Action(BuildLibInstallAction, 'Install compiled library... $TARGET')
    bld = Builder(action = act)
    Env.Append(BUILDERS = {'BuildLib': bld})

G
goprife@gmail.com 已提交
288
    # parse rtconfig.h to get used component
289
    PreProcessor = PatchedPreProcessor()
G
goprife@gmail.com 已提交
290 291 292 293 294 295
    f = file('rtconfig.h', 'r')
    contents = f.read()
    f.close()
    PreProcessor.process_contents(contents)
    BuildOptions = PreProcessor.cpp_namespace

296 297 298 299 300 301 302 303 304 305
    if GetOption('clang-analyzer'):
        # perform what scan-build does
        env.Replace(
                CC   = 'ccc-analyzer',
                CXX  = 'c++-analyzer',
                # skip as and link
                LINK = 'true',
                AS   = 'true',)
        env["ENV"].update(x for x in os.environ.items() if x[0].startswith("CCC_"))
        # only check, don't compile. ccc-analyzer use CCC_CC as the CC.
306 307 308 309 310
        # fsyntax-only will give us some additional warning messages
        env['ENV']['CCC_CC']  = 'clang'
        env.Append(CFLAGS=['-fsyntax-only', '-Wall', '-Wno-invalid-source-encoding'])
        env['ENV']['CCC_CXX'] = 'clang++'
        env.Append(CXXFLAGS=['-fsyntax-only', '-Wall', '-Wno-invalid-source-encoding'])
311 312 313
        # remove the POST_ACTION as it will cause meaningless errors(file not
        # found or something like that).
        rtconfig.POST_ACTION = ''
314

315 316
    # generate cconfig.h file
    GenCconfigFile(env, BuildOptions)
G
goprife@gmail.com 已提交
317

318 319 320
    # auto append '_REENT_SMALL' when using newlib 'nano.specs' option
    if rtconfig.PLATFORM == 'gcc' and str(env['LINKFLAGS']).find('nano.specs') != -1:
        env.AppendUnique(CPPDEFINES = ['_REENT_SMALL'])
321

B
bernard 已提交
322 323 324 325 326
    if GetOption('genconfig'):
        from genconf import genconfig
        genconfig()
        exit(0)

B
Bernard Xiong 已提交
327
    if env['PLATFORM'] != 'win32':
328
        AddOption('--menuconfig',
B
Bernard Xiong 已提交
329 330 331 332 333 334 335 336 337
                    dest = 'menuconfig',
                    action = 'store_true',
                    default = False,
                    help = 'make menuconfig for RT-Thread BSP')
        if GetOption('menuconfig'):
            from menuconfig import menuconfig
            menuconfig(Rtt_Root)
            exit(0)

338 339 340 341 342 343 344 345 346 347
    AddOption('--pyconfig',
                dest = 'pyconfig',
                action = 'store_true',
                default = False,
                help = 'make menuconfig for RT-Thread BSP')
    if GetOption('pyconfig'):
        from menuconfig import pyconfig
        pyconfig(Rtt_Root)
        exit(0)

B
bernard 已提交
348 349 350 351 352 353
    configfn = GetOption('useconfig')
    if configfn:
        from menuconfig import mk_rtconfig
        mk_rtconfig(configfn)
        exit(0)

354

355 356
    if not GetOption('verbose'):
        # override the default verbose command string
357
        env.Replace(
R
Rogerz Zhang 已提交
358
            ARCOMSTR = 'AR $TARGET',
359
            ASCOMSTR = 'AS $TARGET',
R
Rogerz Zhang 已提交
360
            ASPPCOMSTR = 'AS $TARGET',
361 362 363 364
            CCCOMSTR = 'CC $TARGET',
            CXXCOMSTR = 'CXX $TARGET',
            LINKCOMSTR = 'LINK $TARGET'
        )
G
goprife@gmail.com 已提交
365

366 367 368 369 370
    # fix the linker for C++
    if GetDepend('RT_USING_CPLUSPLUS'):
        if env['LINK'].find('gcc') != -1:
            env['LINK'] = env['LINK'].replace('gcc', 'g++')

371 372 373
    # we need to seperate the variant_dir for BSPs and the kernels. BSPs could
    # have their own components etc. If they point to the same folder, SCons
    # would find the wrong source code to compile.
B
Bernard Xiong 已提交
374
    bsp_vdir = 'build'
375 376 377
    kernel_vdir = 'build/kernel'
    # board build script
    objs = SConscript('SConscript', variant_dir=bsp_vdir, duplicate=0)
G
goprife@gmail.com 已提交
378
    # include kernel
379
    objs.extend(SConscript(Rtt_Root + '/src/SConscript', variant_dir=kernel_vdir + '/src', duplicate=0))
G
goprife@gmail.com 已提交
380 381
    # include libcpu
    if not has_libcpu:
382 383
        objs.extend(SConscript(Rtt_Root + '/libcpu/SConscript',
                    variant_dir=kernel_vdir + '/libcpu', duplicate=0))
384

G
goprife@gmail.com 已提交
385
    # include components
386
    objs.extend(SConscript(Rtt_Root + '/components/SConscript',
387
                           variant_dir=kernel_vdir + '/components',
388 389
                           duplicate=0,
                           exports='remove_components'))
G
goprife@gmail.com 已提交
390 391 392

    return objs

B
Bernard Xiong 已提交
393
def PrepareModuleBuilding(env, root_directory, bsp_directory):
G
goprife@gmail.com 已提交
394 395
    import rtconfig

396
    global BuildOptions
G
goprife@gmail.com 已提交
397 398 399
    global Env
    global Rtt_Root

400 401 402 403 404 405
    # patch for win32 spawn
    if env['PLATFORM'] == 'win32':
        win32_spawn = Win32Spawn()
        win32_spawn.env = env
        env['SPAWN'] = win32_spawn.spawn

G
goprife@gmail.com 已提交
406 407 408
    Env = env
    Rtt_Root = root_directory

B
Bernard Xiong 已提交
409
    # parse bsp rtconfig.h to get used component
410
    PreProcessor = PatchedPreProcessor()
B
Bernard Xiong 已提交
411 412 413 414 415 416
    f = file(bsp_directory + '/rtconfig.h', 'r')
    contents = f.read()
    f.close()
    PreProcessor.process_contents(contents)
    BuildOptions = PreProcessor.cpp_namespace

B
Bright Pan 已提交
417 418 419
    # add build/clean library option for library checking
    AddOption('--buildlib',
              dest='buildlib',
B
bernard 已提交
420 421
              type='string',
              help='building library of a component')
B
Bright Pan 已提交
422 423
    AddOption('--cleanlib',
              dest='cleanlib',
B
bernard 已提交
424 425 426 427
              action='store_true',
              default=False,
              help='clean up the library by --buildlib')

G
goprife@gmail.com 已提交
428 429 430
    # add program path
    env.PrependENVPath('PATH', rtconfig.EXEC_PATH)

wuyangyong's avatar
wuyangyong 已提交
431 432 433 434 435 436 437
def GetConfigValue(name):
    assert type(name) == str, 'GetConfigValue: only string parameter is valid'
    try:
        return BuildOptions[name]
    except:
        return ''

G
goprife@gmail.com 已提交
438 439 440 441 442 443 444
def GetDepend(depend):
    building = True
    if type(depend) == type('str'):
        if not BuildOptions.has_key(depend) or BuildOptions[depend] == 0:
            building = False
        elif BuildOptions[depend] != '':
            return BuildOptions[depend]
B
Bright Pan 已提交
445

G
goprife@gmail.com 已提交
446 447 448 449 450 451 452 453 454 455
        return building

    # for list type depend
    for item in depend:
        if item != '':
            if not BuildOptions.has_key(item) or BuildOptions[item] == 0:
                building = False

    return building

B
Bernard Xiong 已提交
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
def LocalOptions(config_filename):
    from SCons.Script import SCons

    # parse wiced_config.h to get used component
    PreProcessor = SCons.cpp.PreProcessor()

    f = file(config_filename, 'r')
    contents = f.read()
    f.close()

    PreProcessor.process_contents(contents)
    local_options = PreProcessor.cpp_namespace

    return local_options

def GetLocalDepend(options, depend):
    building = True
    if type(depend) == type('str'):
        if not options.has_key(depend) or options[depend] == 0:
            building = False
        elif options[depend] != '':
            return options[depend]

        return building

    # for list type depend
    for item in depend:
        if item != '':
            if not options.has_key(item) or options[item] == 0:
                building = False

    return building

G
goprife@gmail.com 已提交
489 490 491
def AddDepend(option):
    BuildOptions[option] = 1

492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
def MergeGroup(src_group, group):
    src_group['src'] = src_group['src'] + group['src']
    if group.has_key('CCFLAGS'):
        if src_group.has_key('CCFLAGS'):
            src_group['CCFLAGS'] = src_group['CCFLAGS'] + group['CCFLAGS']
        else:
            src_group['CCFLAGS'] = group['CCFLAGS']
    if group.has_key('CPPPATH'):
        if src_group.has_key('CPPPATH'):
            src_group['CPPPATH'] = src_group['CPPPATH'] + group['CPPPATH']
        else:
            src_group['CPPPATH'] = group['CPPPATH']
    if group.has_key('CPPDEFINES'):
        if src_group.has_key('CPPDEFINES'):
            src_group['CPPDEFINES'] = src_group['CPPDEFINES'] + group['CPPDEFINES']
        else:
            src_group['CPPDEFINES'] = group['CPPDEFINES']
509 510 511 512 513
    if group.has_key('ASFLAGS'):
        if src_group.has_key('ASFLAGS'):
            src_group['ASFLAGS'] = src_group['ASFLAGS'] + group['ASFLAGS']
        else:
            src_group['ASFLAGS'] = group['ASFLAGS']
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531

    # for local CCFLAGS/CPPPATH/CPPDEFINES
    if group.has_key('LOCAL_CCFLAGS'):
        if src_group.has_key('LOCAL_CCFLAGS'):
            src_group['LOCAL_CCFLAGS'] = src_group['LOCAL_CCFLAGS'] + group['LOCAL_CCFLAGS']
        else:
            src_group['LOCAL_CCFLAGS'] = group['LOCAL_CCFLAGS']
    if group.has_key('LOCAL_CPPPATH'):
        if src_group.has_key('LOCAL_CPPPATH'):
            src_group['LOCAL_CPPPATH'] = src_group['LOCAL_CPPPATH'] + group['LOCAL_CPPPATH']
        else:
            src_group['LOCAL_CPPPATH'] = group['LOCAL_CPPPATH']
    if group.has_key('LOCAL_CPPDEFINES'):
        if src_group.has_key('LOCAL_CPPDEFINES'):
            src_group['LOCAL_CPPDEFINES'] = src_group['LOCAL_CPPDEFINES'] + group['LOCAL_CPPDEFINES']
        else:
            src_group['LOCAL_CPPDEFINES'] = group['LOCAL_CPPDEFINES']

532 533 534 535 536
    if group.has_key('LINKFLAGS'):
        if src_group.has_key('LINKFLAGS'):
            src_group['LINKFLAGS'] = src_group['LINKFLAGS'] + group['LINKFLAGS']
        else:
            src_group['LINKFLAGS'] = group['LINKFLAGS']
537 538 539
    if group.has_key('LIBS'):
        if src_group.has_key('LIBS'):
            src_group['LIBS'] = src_group['LIBS'] + group['LIBS']
540
        else:
541 542 543 544 545 546
            src_group['LIBS'] = group['LIBS']
    if group.has_key('LIBPATH'):
        if src_group.has_key('LIBPATH'):
            src_group['LIBPATH'] = src_group['LIBPATH'] + group['LIBPATH']
        else:
            src_group['LIBPATH'] = group['LIBPATH']
547 548 549 550 551
    if group.has_key('LOCAL_ASFLAGS'):
        if src_group.has_key('LOCAL_ASFLAGS'):
            src_group['LOCAL_ASFLAGS'] = src_group['LOCAL_ASFLAGS'] + group['LOCAL_ASFLAGS']
        else:
            src_group['LOCAL_ASFLAGS'] = group['LOCAL_ASFLAGS']
552

G
goprife@gmail.com 已提交
553 554 555 556 557
def DefineGroup(name, src, depend, **parameters):
    global Env
    if not GetDepend(depend):
        return []

558 559 560 561 562 563 564 565
    # find exist group and get path of group
    group_path = ''
    for g in Projects:
        if g['name'] == name:
            group_path = g['path']
    if group_path == '':
        group_path = GetCurrentDir()

G
goprife@gmail.com 已提交
566 567
    group = parameters
    group['name'] = name
568
    group['path'] = group_path
569
    if type(src) == type([]):
G
goprife@gmail.com 已提交
570 571 572 573 574
        group['src'] = File(src)
    else:
        group['src'] = src

    if group.has_key('CCFLAGS'):
575
        Env.AppendUnique(CCFLAGS = group['CCFLAGS'])
G
goprife@gmail.com 已提交
576
    if group.has_key('CPPPATH'):
577
        Env.AppendUnique(CPPPATH = group['CPPPATH'])
G
goprife@gmail.com 已提交
578
    if group.has_key('CPPDEFINES'):
579
        Env.AppendUnique(CPPDEFINES = group['CPPDEFINES'])
G
goprife@gmail.com 已提交
580
    if group.has_key('LINKFLAGS'):
581
        Env.AppendUnique(LINKFLAGS = group['LINKFLAGS'])
582 583
    if group.has_key('ASFLAGS'):
        Env.AppendUnique(ASFLAGS = group['ASFLAGS'])
B
bernard 已提交
584

B
Bright Pan 已提交
585
    # check whether to clean up library
B
bernard 已提交
586
    if GetOption('cleanlib') and os.path.exists(os.path.join(group['path'], GroupLibFullName(name, Env))):
B
bernard 已提交
587
        if group['src'] != []:
B
bernard 已提交
588
            print 'Remove library:', GroupLibFullName(name, Env)
B
bernard 已提交
589 590 591
            fn = os.path.join(group['path'], GroupLibFullName(name, Env))
            if os.path.exists(fn):
                os.unlink(fn)
B
bernard 已提交
592

593
    if group.has_key('LIBS'):
594
        Env.AppendUnique(LIBS = group['LIBS'])
595
    if group.has_key('LIBPATH'):
596
        Env.AppendUnique(LIBPATH = group['LIBPATH'])
G
goprife@gmail.com 已提交
597

598
    # check whether to build group library
G
goprife@gmail.com 已提交
599
    if group.has_key('LIBRARY'):
600 601
        objs = Env.Library(name, group['src'])
    else:
602
        # only add source
603
        objs = group['src']
G
goprife@gmail.com 已提交
604

B
Bright Pan 已提交
605
    # merge group
606 607 608 609 610 611
    for g in Projects:
        if g['name'] == name:
            # merge to this group
            MergeGroup(g, group)
            return objs

B
Bright Pan 已提交
612
    # add a new group
613 614
    Projects.append(group)

G
goprife@gmail.com 已提交
615 616 617 618 619 620 621 622 623
    return objs

def GetCurrentDir():
    conscript = File('SConscript')
    fn = conscript.rfile()
    name = fn.name
    path = os.path.dirname(fn.abspath)
    return path

624 625 626 627 628 629 630 631 632 633 634
PREBUILDING = []
def RegisterPreBuildingAction(act):
    global PREBUILDING
    assert callable(act), 'Could only register callable objects. %s received' % repr(act)
    PREBUILDING.append(act)

def PreBuilding():
    global PREBUILDING
    for a in PREBUILDING:
        a()

B
bernard 已提交
635
def GroupLibName(name, env):
B
bernard 已提交
636 637 638 639 640 641 642 643 644 645
    import rtconfig
    if rtconfig.PLATFORM == 'armcc':
        return name + '_rvds'
    elif rtconfig.PLATFORM == 'gcc':
        return name + '_gcc'

    return name

def GroupLibFullName(name, env):
    return env['LIBPREFIX'] + GroupLibName(name, env) + env['LIBSUFFIX']
B
bernard 已提交
646 647 648 649 650

def BuildLibInstallAction(target, source, env):
    lib_name = GetOption('buildlib')
    for Group in Projects:
        if Group['name'] == lib_name:
B
bernard 已提交
651
            lib_name = GroupLibFullName(Group['name'], env)
B
bernard 已提交
652 653 654 655 656
            dst_name = os.path.join(Group['path'], lib_name)
            print 'Copy %s => %s' % (lib_name, dst_name)
            do_copy_file(lib_name, dst_name)
            break

657
def DoBuilding(target, objects):
658 659 660 661 662 663 664 665 666 667 668

    # merge all objects into one list
    def one_list(l):
        lst = []
        for item in l:
            if type(item) == type([]):
                lst += one_list(item)
            else:
                lst.append(item)
        return lst

669 670
    # handle local group
    def local_group(group, objects):
671
        if group.has_key('LOCAL_CCFLAGS') or group.has_key('LOCAL_CPPPATH') or group.has_key('LOCAL_CPPDEFINES') or group.has_key('LOCAL_ASFLAGS'):
672 673 674
            CCFLAGS = Env.get('CCFLAGS', '') + group.get('LOCAL_CCFLAGS', '')
            CPPPATH = Env.get('CPPPATH', ['']) + group.get('LOCAL_CPPPATH', [''])
            CPPDEFINES = Env.get('CPPDEFINES', ['']) + group.get('LOCAL_CPPDEFINES', [''])
675
            ASFLAGS = Env.get('ASFLAGS', '') + group.get('LOCAL_ASFLAGS', '')
676 677

            for source in group['src']:
678
                objects.append(Env.Object(source, CCFLAGS = CCFLAGS, ASFLAGS = ASFLAGS,
679 680 681 682 683 684 685
                    CPPPATH = CPPPATH, CPPDEFINES = CPPDEFINES))

            return True

        return False

    objects = one_list(objects)
686

687 688 689 690
    program = None
    # check whether special buildlib option
    lib_name = GetOption('buildlib')
    if lib_name:
691
        objects = [] # remove all of objects
692 693 694
        # build library with special component
        for Group in Projects:
            if Group['name'] == lib_name:
B
bernard 已提交
695
                lib_name = GroupLibName(Group['name'], Env)
696 697 698
                if not local_group(Group, objects):
                    objects = Env.Object(Group['src'])

699
                program = Env.Library(lib_name, objects)
B
bernard 已提交
700 701 702 703

                # add library copy action
                Env.BuildLib(lib_name, program)

704 705
                break
    else:
706 707 708 709 710 711 712 713 714 715 716 717
        # remove source files with local flags setting
        for group in Projects:
            if group.has_key('LOCAL_CCFLAGS') or group.has_key('LOCAL_CPPPATH') or group.has_key('LOCAL_CPPDEFINES'):
                for source in group['src']:
                    for obj in objects:
                        if source.abspath == obj.abspath or (len(obj.sources) > 0 and source.abspath == obj.sources[0].abspath):
                            objects.remove(obj)

        # re-add the source files to the objects
        for group in Projects:
            local_group(group, objects)

718 719 720
        program = Env.Program(target, objects)

    EndBuilding(target, program)
721

722
def GenTargetProject(program = None):
G
goprife@gmail.com 已提交
723 724

    if GetOption('target') == 'mdk':
B
bernard 已提交
725 726
        from keil import MDKProject
        from keil import MDK4Project
B
Bright Pan 已提交
727
        from keil import MDK5Project
B
bernard 已提交
728

G
goprife@gmail.com 已提交
729 730 731 732 733 734 735 736
        template = os.path.isfile('template.Uv2')
        if template:
            MDKProject('project.Uv2', Projects)
        else:
            template = os.path.isfile('template.uvproj')
            if template:
                MDK4Project('project.uvproj', Projects)
            else:
B
Bright Pan 已提交
737 738 739 740 741 742
                template = os.path.isfile('template.uvprojx')
                if template:
                    MDK5Project('project.uvprojx', Projects)
                else:
                    print 'No template project file found.'

G
goprife@gmail.com 已提交
743
    if GetOption('target') == 'mdk4':
B
bernard 已提交
744
        from keil import MDK4Project
G
goprife@gmail.com 已提交
745 746
        MDK4Project('project.uvproj', Projects)

B
Bright Pan 已提交
747 748 749 750
    if GetOption('target') == 'mdk5':
        from keil import MDK5Project
        MDK5Project('project.uvprojx', Projects)

G
goprife@gmail.com 已提交
751
    if GetOption('target') == 'iar':
B
bernard 已提交
752
        from iar import IARProject
B
Bright Pan 已提交
753
        IARProject('project.ewp', Projects)
754

755
    if GetOption('target') == 'vs':
B
bernard 已提交
756
        from vs import VSProject
757
        VSProject('project.vcproj', Projects, program)
758

759
    if GetOption('target') == 'vs2012':
B
bernard 已提交
760
        from vs2012 import VS2012Project
761 762
        VS2012Project('project.vcxproj', Projects, program)

wuyangyong's avatar
wuyangyong 已提交
763
    if GetOption('target') == 'cb':
B
bernard 已提交
764
        from codeblocks import CBProject
wuyangyong's avatar
wuyangyong 已提交
765 766
        CBProject('project.cbp', Projects, program)

B
bernard 已提交
767 768 769
    if GetOption('target') == 'ua':
        from ua import PrepareUA
        PrepareUA(Projects, Rtt_Root, str(Dir('#')))
B
Bright Pan 已提交
770

771 772 773
    if GetOption('target') == 'vsc':
        from vsc import GenerateVSCode
        GenerateVSCode(Env)
774

775 776 777
    if GetOption('target') == 'cdk':
        from cdk import CDKProject
        CDKProject('project.cdkproj', Projects)
778

779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
def EndBuilding(target, program = None):
    import rtconfig

    need_exit = False

    Env['target']  = program
    Env['project'] = Projects

    Env.AddPostAction(target, rtconfig.POST_ACTION)
    # Add addition clean files
    Clean(target, 'cconfig.h')
    Clean(target, 'rtua.py')
    Clean(target, 'rtua.pyc')

    if GetOption('target'):
        GenTargetProject(program)

B
bernard 已提交
796 797 798 799
    BSP_ROOT = Dir('#').abspath
    if GetOption('make-dist') and program != None:
        from mkdist import MkDist
        MkDist(program, BSP_ROOT, Rtt_Root, Env)
800 801 802
    if GetOption('make-dist-strip') and program != None:
        from mkdist import MkDist_Strip
        MkDist_Strip(program, BSP_ROOT, Rtt_Root, Env)
803
        need_exit = True
804 805 806 807
    if GetOption('cscope'):
        from cscope import CscopeDatabase
        CscopeDatabase(Projects)

808 809
    if not GetOption('help') and not GetOption('target'):
        if not os.path.exists(rtconfig.EXEC_PATH):
810 811 812 813 814
            print "Error: the toolchain path (%s) is not exist, please check 'EXEC_PATH' in path or rtconfig.py." % rtconfig.EXEC_PATH
            need_exit = True

    if need_exit:
        exit(0)
815

G
goprife@gmail.com 已提交
816
def SrcRemove(src, remove):
G
Grissiom 已提交
817 818 819
    if not src:
        return

X
xieyangrun 已提交
820
    src_bak = src[:]
821 822 823 824 825 826

    if type(remove) == type('str'):
        if os.path.isabs(remove):
            remove = os.path.relpath(remove, GetCurrentDir())
        remove = os.path.normpath(remove)

X
xieyangrun 已提交
827
        for item in src_bak:
828 829 830 831
            if type(item) == type('str'):
                item_str = item
            else:
                item_str = item.rstr()
832

833 834 835
            if os.path.isabs(item_str):
                item_str = os.path.relpath(item_str, GetCurrentDir())
            item_str = os.path.normpath(item_str)
836 837

            if item_str == remove:
X
xieyangrun 已提交
838
                src.remove(item)
839 840 841 842 843 844 845
    else:
        for remove_item in remove:
            remove_str = str(remove_item)
            if os.path.isabs(remove_str):
                remove_str = os.path.relpath(remove_str, GetCurrentDir())
            remove_str = os.path.normpath(remove_str)

X
xieyangrun 已提交
846
            for item in src_bak:
847 848 849 850 851 852 853 854 855 856
                if type(item) == type('str'):
                    item_str = item
                else:
                    item_str = item.rstr()

                if os.path.isabs(item_str):
                    item_str = os.path.relpath(item_str, GetCurrentDir())
                item_str = os.path.normpath(item_str)

                if item_str == remove_str:
X
xieyangrun 已提交
857
                    src.remove(item)
858 859 860 861 862 863 864

def GetVersion():
    import SCons.cpp
    import string

    rtdef = os.path.join(Rtt_Root, 'include', 'rtdef.h')

B
Bright Pan 已提交
865
    # parse rtdef.h to get RT-Thread version
866
    prepcessor = PatchedPreProcessor()
867 868 869 870 871 872 873 874 875 876 877 878 879 880
    f = file(rtdef, 'r')
    contents = f.read()
    f.close()
    prepcessor.process_contents(contents)
    def_ns = prepcessor.cpp_namespace

    version = int(filter(lambda ch: ch in '0123456789.', def_ns['RT_VERSION']))
    subversion = int(filter(lambda ch: ch in '0123456789.', def_ns['RT_SUBVERSION']))

    if def_ns.has_key('RT_REVISION'):
        revision = int(filter(lambda ch: ch in '0123456789.', def_ns['RT_REVISION']))
        return '%d.%d.%d' % (version, subversion, revision)

    return '0.%d.%d' % (version, subversion)
881

882 883 884 885
def GlobSubDir(sub_dir, ext_name):
    import os
    import glob

886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
    def glob_source(sub_dir, ext_name):
        list = os.listdir(sub_dir)
        src = glob.glob(os.path.join(sub_dir, ext_name))

        for item in list:
            full_subdir = os.path.join(sub_dir, item)
            if os.path.isdir(full_subdir):
                src += glob_source(full_subdir, ext_name)
        return src

    dst = []
    src = glob_source(sub_dir, ext_name)
    for item in src:
        dst.append(os.path.relpath(item, sub_dir))
    return dst
901

902 903 904 905
def PackageSConscript(package):
    from package import BuildPackage

    return BuildPackage(package)