building.py 26.4 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 24
# 2015-07-25     Bernard      Add LOCAL_CCFLAGS/LOCAL_CPPPATH/LOCAL_CPPDEFINES for
#                             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 72 73 74 75 76 77
# 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
    
PatchedPreProcessor = SCons.cpp.PreProcessor
PatchedPreProcessor.start_handling_includes = start_handling_includes
PatchedPreProcessor.stop_handling_includes = stop_handling_includes


G
goprife@gmail.com 已提交
78 79
class Win32Spawn:
    def spawn(self, sh, escape, cmd, args, env):
G
Grissiom 已提交
80 81 82 83 84 85 86 87 88 89 90
        # 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 已提交
91 92 93 94
        import subprocess

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

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

        # 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']
104

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

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

116
def PrepareBuilding(env, root_directory, has_libcpu=False, remove_components = []):
G
goprife@gmail.com 已提交
117 118 119 120 121 122 123 124 125
    import SCons.cpp
    import rtconfig

    global BuildOptions
    global Projects
    global Env
    global Rtt_Root

    Env = env
126
    Rtt_Root = os.path.abspath(root_directory)
G
goprife@gmail.com 已提交
127

128 129 130 131 132
    # 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')
P
prife 已提交
133
                Env['LINKFLAGS']=Env['LINKFLAGS'].replace('RV31', 'armcc')
134

B
Bright Pan 已提交
135
        # reset AR command flags
B
bernard 已提交
136 137
        env['ARCOM'] = '$AR --create $TARGET $SOURCES'
        env['LIBPREFIX']   = ''
B
bernard 已提交
138
        env['LIBSUFFIX']   = '.lib'
B
bernard 已提交
139
        env['LIBLINKPREFIX'] = ''
B
bernard 已提交
140
        env['LIBLINKSUFFIX']   = '.lib'
B
bernard 已提交
141
        env['LIBDIRPREFIX'] = '--userlibpath '
B
bernard 已提交
142

G
goprife@gmail.com 已提交
143
    # patch for win32 spawn
G
Grissiom 已提交
144
    if env['PLATFORM'] == 'win32':
G
goprife@gmail.com 已提交
145 146 147
        win32_spawn = Win32Spawn()
        win32_spawn.env = env
        env['SPAWN'] = win32_spawn.spawn
G
Grissiom 已提交
148

149
    if env['PLATFORM'] == 'win32':
150 151 152
        os.environ['PATH'] = rtconfig.EXEC_PATH + ";" + os.environ['PATH']
    else:
        os.environ['PATH'] = rtconfig.EXEC_PATH + ":" + os.environ['PATH']
G
goprife@gmail.com 已提交
153 154 155

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

B
bernard 已提交
159 160 161 162 163
    # 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 已提交
164
    # parse rtconfig.h to get used component
165
    PreProcessor = PatchedPreProcessor()
G
goprife@gmail.com 已提交
166 167 168 169 170 171
    f = file('rtconfig.h', 'r')
    contents = f.read()
    f.close()
    PreProcessor.process_contents(contents)
    BuildOptions = PreProcessor.cpp_namespace

B
Bright Pan 已提交
172
    # add copy option
173 174 175 176 177
    AddOption('--copy',
                      dest='copy',
                      action='store_true',
                      default=False,
                      help='copy rt-thread directory to local.')
178 179 180 181 182
    AddOption('--copy-header',
                      dest='copy-header',
                      action='store_true',
                      default=False,
                      help='copy header of rt-thread directory to local.')
B
bernard 已提交
183 184 185 186 187
    AddOption('--dist',
                      dest = 'make-dist',
                      action = 'store_true',
                      default=False,
                      help = 'make distribution')
188 189 190 191 192
    AddOption('--cscope',
                      dest='cscope',
                      action='store_true',
                      default=False,
                      help='Build Cscope cross reference database. Requires cscope installed.')
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
    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.')

    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.
213 214 215 216 217
        # 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'])
218 219 220
        # remove the POST_ACTION as it will cause meaningless errors(file not
        # found or something like that).
        rtconfig.POST_ACTION = ''
221

222
    # add build library option
B
Bright Pan 已提交
223 224
    AddOption('--buildlib',
                      dest='buildlib',
225 226
                      type='string',
                      help='building library of a component')
B
Bright Pan 已提交
227 228
    AddOption('--cleanlib',
                      dest='cleanlib',
B
bernard 已提交
229 230 231
                      action='store_true',
                      default=False,
                      help='clean up the library by --buildlib')
232

G
goprife@gmail.com 已提交
233 234 235 236
    # add target option
    AddOption('--target',
                      dest='target',
                      type='string',
237
                      help='set target project: mdk/mdk4/iar/vs/ua')
G
goprife@gmail.com 已提交
238 239 240 241

    #{target_name:(CROSS_TOOL, PLATFORM)}
    tgt_dict = {'mdk':('keil', 'armcc'),
                'mdk4':('keil', 'armcc'),
B
Bright Pan 已提交
242
                'mdk5':('keil', 'armcc'),
243
                'iar':('iar', 'iar'),
wuyangyong's avatar
wuyangyong 已提交
244
                'vs':('msvc', 'cl'),
245
                'vs2012':('msvc', 'cl'),
B
bernard 已提交
246
                'cb':('keil', 'armcc'),
B
Bernard Xiong 已提交
247
                'ua':('gcc', 'gcc')}
G
goprife@gmail.com 已提交
248 249
    tgt_name = GetOption('target')
    if tgt_name:
250 251 252 253 254 255
        # --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)

G
goprife@gmail.com 已提交
256 257 258 259 260 261 262 263
        SetOption('no_exec', 1)
        try:
            rtconfig.CROSS_TOOL, rtconfig.PLATFORM = tgt_dict[tgt_name]
        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) \
264
        and rtconfig.PLATFORM == 'gcc':
G
goprife@gmail.com 已提交
265 266
        AddDepend('RT_USING_MINILIBC')

B
bernard 已提交
267 268 269 270 271 272 273 274 275 276
    AddOption('--genconfig', 
                dest = 'genconfig',
                action = 'store_true',
                default = False, 
                help = 'Generate .config from rtconfig.h')
    if GetOption('genconfig'):
        from genconf import genconfig
        genconfig()
        exit(0)

B
Bernard Xiong 已提交
277 278 279 280 281 282 283 284 285 286 287
    if env['PLATFORM'] != 'win32':
        AddOption('--menuconfig', 
                    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)

B
bernard 已提交
288 289 290 291 292 293 294 295 296 297
    AddOption('--useconfig',
                dest = 'useconfig',
                type='string',
                help = 'make rtconfig.h from config file.')
    configfn = GetOption('useconfig')
    if configfn:
        from menuconfig import mk_rtconfig
        mk_rtconfig(configfn)
        exit(0)

298
    # add comstr option
299 300
    AddOption('--verbose',
                dest='verbose',
301
                action='store_true',
B
Bernard Xiong 已提交
302
                default=False,
303
                help='print verbose information during build')
304

305 306
    if not GetOption('verbose'):
        # override the default verbose command string
307
        env.Replace(
R
Rogerz Zhang 已提交
308
            ARCOMSTR = 'AR $TARGET',
309
            ASCOMSTR = 'AS $TARGET',
R
Rogerz Zhang 已提交
310
            ASPPCOMSTR = 'AS $TARGET',
311 312 313 314
            CCCOMSTR = 'CC $TARGET',
            CXXCOMSTR = 'CXX $TARGET',
            LINKCOMSTR = 'LINK $TARGET'
        )
G
goprife@gmail.com 已提交
315

316 317 318 319 320
    # fix the linker for C++
    if GetDepend('RT_USING_CPLUSPLUS'):
        if env['LINK'].find('gcc') != -1:
            env['LINK'] = env['LINK'].replace('gcc', 'g++')

321 322 323
    # 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 已提交
324
    bsp_vdir = 'build'
325 326 327
    kernel_vdir = 'build/kernel'
    # board build script
    objs = SConscript('SConscript', variant_dir=bsp_vdir, duplicate=0)
G
goprife@gmail.com 已提交
328
    # include kernel
329
    objs.extend(SConscript(Rtt_Root + '/src/SConscript', variant_dir=kernel_vdir + '/src', duplicate=0))
G
goprife@gmail.com 已提交
330 331
    # include libcpu
    if not has_libcpu:
332 333
        objs.extend(SConscript(Rtt_Root + '/libcpu/SConscript',
                    variant_dir=kernel_vdir + '/libcpu', duplicate=0))
334

G
goprife@gmail.com 已提交
335
    # include components
336
    objs.extend(SConscript(Rtt_Root + '/components/SConscript',
337
                           variant_dir=kernel_vdir + '/components',
338 339
                           duplicate=0,
                           exports='remove_components'))
G
goprife@gmail.com 已提交
340 341 342

    return objs

B
Bernard Xiong 已提交
343
def PrepareModuleBuilding(env, root_directory, bsp_directory):
G
goprife@gmail.com 已提交
344 345
    import rtconfig

346
    global BuildOptions
G
goprife@gmail.com 已提交
347 348 349
    global Env
    global Rtt_Root

350 351 352 353 354 355
    # patch for win32 spawn
    if env['PLATFORM'] == 'win32':
        win32_spawn = Win32Spawn()
        win32_spawn.env = env
        env['SPAWN'] = win32_spawn.spawn

G
goprife@gmail.com 已提交
356 357 358
    Env = env
    Rtt_Root = root_directory

B
Bernard Xiong 已提交
359
    # parse bsp rtconfig.h to get used component
360
    PreProcessor = PatchedPreProcessor()
B
Bernard Xiong 已提交
361 362 363 364 365 366
    f = file(bsp_directory + '/rtconfig.h', 'r')
    contents = f.read()
    f.close()
    PreProcessor.process_contents(contents)
    BuildOptions = PreProcessor.cpp_namespace

B
Bright Pan 已提交
367 368 369
    # add build/clean library option for library checking
    AddOption('--buildlib',
              dest='buildlib',
B
bernard 已提交
370 371
              type='string',
              help='building library of a component')
B
Bright Pan 已提交
372 373
    AddOption('--cleanlib',
              dest='cleanlib',
B
bernard 已提交
374 375 376 377
              action='store_true',
              default=False,
              help='clean up the library by --buildlib')

G
goprife@gmail.com 已提交
378 379 380
    # add program path
    env.PrependENVPath('PATH', rtconfig.EXEC_PATH)

wuyangyong's avatar
wuyangyong 已提交
381 382 383 384 385 386 387
def GetConfigValue(name):
    assert type(name) == str, 'GetConfigValue: only string parameter is valid'
    try:
        return BuildOptions[name]
    except:
        return ''

G
goprife@gmail.com 已提交
388 389 390 391 392 393 394
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 已提交
395

G
goprife@gmail.com 已提交
396 397 398 399 400 401 402 403 404 405
        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 已提交
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
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 已提交
439 440 441
def AddDepend(option):
    BuildOptions[option] = 1

442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
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']
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476

    # 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']

477 478 479 480 481
    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']
482 483 484
    if group.has_key('LIBS'):
        if src_group.has_key('LIBS'):
            src_group['LIBS'] = src_group['LIBS'] + group['LIBS']
485
        else:
486 487 488 489 490 491
            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']
492

G
goprife@gmail.com 已提交
493 494 495 496 497
def DefineGroup(name, src, depend, **parameters):
    global Env
    if not GetDepend(depend):
        return []

498 499 500 501 502 503 504 505
    # 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 已提交
506 507
    group = parameters
    group['name'] = name
508
    group['path'] = group_path
B
bernard 已提交
509
    if type(src) == type(['src1']):
G
goprife@gmail.com 已提交
510 511 512 513 514
        group['src'] = File(src)
    else:
        group['src'] = src

    if group.has_key('CCFLAGS'):
515
        Env.AppendUnique(CCFLAGS = group['CCFLAGS'])
G
goprife@gmail.com 已提交
516
    if group.has_key('CPPPATH'):
517
        Env.AppendUnique(CPPPATH = group['CPPPATH'])
G
goprife@gmail.com 已提交
518
    if group.has_key('CPPDEFINES'):
519
        Env.AppendUnique(CPPDEFINES = group['CPPDEFINES'])
G
goprife@gmail.com 已提交
520
    if group.has_key('LINKFLAGS'):
521
        Env.AppendUnique(LINKFLAGS = group['LINKFLAGS'])
B
bernard 已提交
522

B
Bright Pan 已提交
523
    # check whether to clean up library
B
bernard 已提交
524
    if GetOption('cleanlib') and os.path.exists(os.path.join(group['path'], GroupLibFullName(name, Env))):
B
bernard 已提交
525
        if group['src'] != []:
B
bernard 已提交
526
            print 'Remove library:', GroupLibFullName(name, Env)
B
bernard 已提交
527 528 529
            fn = os.path.join(group['path'], GroupLibFullName(name, Env))
            if os.path.exists(fn):
                os.unlink(fn)
B
bernard 已提交
530 531

    # check whether exist group library
B
bernard 已提交
532
    if not GetOption('buildlib') and os.path.exists(os.path.join(group['path'], GroupLibFullName(name, Env))):
B
bernard 已提交
533
        group['src'] = []
534 535 536 537
        if group.has_key('LIBS'): group['LIBS'] = group['LIBS'] + [GroupLibName(name, Env)]
        else : group['LIBS'] = [GroupLibName(name, Env)]
        if group.has_key('LIBPATH'): group['LIBPATH'] = group['LIBPATH'] + [GetCurrentDir()]
        else : group['LIBPATH'] = [GetCurrentDir()]
B
bernard 已提交
538

539
    if group.has_key('LIBS'):
540
        Env.AppendUnique(LIBS = group['LIBS'])
541
    if group.has_key('LIBPATH'):
542
        Env.AppendUnique(LIBPATH = group['LIBPATH'])
G
goprife@gmail.com 已提交
543

544
    # check whether to build group library
G
goprife@gmail.com 已提交
545
    if group.has_key('LIBRARY'):
546 547
        objs = Env.Library(name, group['src'])
    else:
548
        # only add source
549
        objs = group['src']
G
goprife@gmail.com 已提交
550

B
Bright Pan 已提交
551
    # merge group
552 553 554 555 556 557
    for g in Projects:
        if g['name'] == name:
            # merge to this group
            MergeGroup(g, group)
            return objs

B
Bright Pan 已提交
558
    # add a new group
559 560
    Projects.append(group)

G
goprife@gmail.com 已提交
561 562 563 564 565 566 567 568 569
    return objs

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

570 571 572 573 574 575 576 577 578 579 580
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 已提交
581
def GroupLibName(name, env):
B
bernard 已提交
582 583 584 585 586 587 588 589 590 591
    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 已提交
592 593 594 595 596

def BuildLibInstallAction(target, source, env):
    lib_name = GetOption('buildlib')
    for Group in Projects:
        if Group['name'] == lib_name:
B
bernard 已提交
597
            lib_name = GroupLibFullName(Group['name'], env)
B
bernard 已提交
598 599 600 601 602
            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

603
def DoBuilding(target, objects):
604 605 606 607 608 609 610 611 612 613 614

    # 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

615 616
    # handle local group
    def local_group(group, objects):
617 618 619 620 621 622
        if group.has_key('LOCAL_CCFLAGS') or group.has_key('LOCAL_CPPPATH') or group.has_key('LOCAL_CPPDEFINES'):
            CCFLAGS = Env.get('CCFLAGS', '') + group.get('LOCAL_CCFLAGS', '')
            CPPPATH = Env.get('CPPPATH', ['']) + group.get('LOCAL_CPPPATH', [''])
            CPPDEFINES = Env.get('CPPDEFINES', ['']) + group.get('LOCAL_CPPDEFINES', [''])

            for source in group['src']:
623 624 625 626 627 628 629 630
                objects.append(Env.Object(source, CCFLAGS = CCFLAGS,
                    CPPPATH = CPPPATH, CPPDEFINES = CPPDEFINES))

            return True

        return False

    objects = one_list(objects)
631

632 633 634 635
    program = None
    # check whether special buildlib option
    lib_name = GetOption('buildlib')
    if lib_name:
636
        objects = [] # remove all of objects
637 638 639
        # build library with special component
        for Group in Projects:
            if Group['name'] == lib_name:
B
bernard 已提交
640
                lib_name = GroupLibName(Group['name'], Env)
641 642 643
                if not local_group(Group, objects):
                    objects = Env.Object(Group['src'])

644
                program = Env.Library(lib_name, objects)
B
bernard 已提交
645 646 647 648

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

649 650
                break
    else:
651 652 653 654 655 656 657 658 659 660 661 662
        # 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)

663 664 665 666
        program = Env.Program(target, objects)

    EndBuilding(target, program)

667
def EndBuilding(target, program = None):
G
goprife@gmail.com 已提交
668
    import rtconfig
669

G
goprife@gmail.com 已提交
670 671 672
    Env.AddPostAction(target, rtconfig.POST_ACTION)

    if GetOption('target') == 'mdk':
B
bernard 已提交
673 674
        from keil import MDKProject
        from keil import MDK4Project
B
Bright Pan 已提交
675
        from keil import MDK5Project
B
bernard 已提交
676

G
goprife@gmail.com 已提交
677 678 679 680 681 682 683 684
        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 已提交
685 686 687 688 689 690
                template = os.path.isfile('template.uvprojx')
                if template:
                    MDK5Project('project.uvprojx', Projects)
                else:
                    print 'No template project file found.'

G
goprife@gmail.com 已提交
691
    if GetOption('target') == 'mdk4':
B
bernard 已提交
692
        from keil import MDK4Project
G
goprife@gmail.com 已提交
693 694
        MDK4Project('project.uvproj', Projects)

B
Bright Pan 已提交
695 696 697 698
    if GetOption('target') == 'mdk5':
        from keil import MDK5Project
        MDK5Project('project.uvprojx', Projects)

G
goprife@gmail.com 已提交
699
    if GetOption('target') == 'iar':
B
bernard 已提交
700
        from iar import IARProject
B
Bright Pan 已提交
701
        IARProject('project.ewp', Projects)
702

703
    if GetOption('target') == 'vs':
B
bernard 已提交
704
        from vs import VSProject
705
        VSProject('project.vcproj', Projects, program)
706

707
    if GetOption('target') == 'vs2012':
B
bernard 已提交
708
        from vs2012 import VS2012Project
709 710
        VS2012Project('project.vcxproj', Projects, program)

wuyangyong's avatar
wuyangyong 已提交
711
    if GetOption('target') == 'cb':
B
bernard 已提交
712
        from codeblocks import CBProject
wuyangyong's avatar
wuyangyong 已提交
713 714
        CBProject('project.cbp', Projects, program)

B
bernard 已提交
715 716 717
    if GetOption('target') == 'ua':
        from ua import PrepareUA
        PrepareUA(Projects, Rtt_Root, str(Dir('#')))
B
Bright Pan 已提交
718

B
bernard 已提交
719
    BSP_ROOT = Dir('#').abspath
720
    if GetOption('copy') and program != None:
B
bernard 已提交
721 722 723
        from mkdist import MakeCopy
        MakeCopy(program, BSP_ROOT, Rtt_Root, Env)
        exit(0)
724
    if GetOption('copy-header') and program != None:
B
bernard 已提交
725 726 727 728 729 730 731
        from mkdist import MakeCopyHeader
        MakeCopyHeader(program, BSP_ROOT, Rtt_Root, Env)
        exit(0)
    if GetOption('make-dist') and program != None:
        from mkdist import MkDist
        MkDist(program, BSP_ROOT, Rtt_Root, Env)
        exit(0)
732 733 734 735
    if GetOption('cscope'):
        from cscope import CscopeDatabase
        CscopeDatabase(Projects)

G
goprife@gmail.com 已提交
736
def SrcRemove(src, remove):
G
Grissiom 已提交
737 738 739
    if not src:
        return

740 741
    for item in src:
        if type(item) == type('str'):
742 743
            if os.path.basename(item) in remove:
                src.remove(item)
744 745 746
        else:
            if os.path.basename(item.rstr()) in remove:
                src.remove(item)
747 748 749 750 751 752 753

def GetVersion():
    import SCons.cpp
    import string

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

B
Bright Pan 已提交
754
    # parse rtdef.h to get RT-Thread version
755
    prepcessor = PatchedPreProcessor()
756 757 758 759 760 761 762 763 764 765 766 767 768 769
    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)
770

771 772 773 774
def GlobSubDir(sub_dir, ext_name):
    import os
    import glob

775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
    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
790

791 792 793 794 795
def PackageSConscript(package):
    from package import BuildPackage

    return BuildPackage(package)

796