building.py 31.3 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
import os
import sys
import string
30
import utils
G
goprife@gmail.com 已提交
31 32

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

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

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
# 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
73

74 75 76 77
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
        # 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:
87
                    print ('Error removing file: ' + e)
G
Grissiom 已提交
88 89 90
                    return -1
            return 0

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

93
        newargs = ' '.join(args[1:])
G
goprife@gmail.com 已提交
94
        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:
armink_ztl's avatar
armink_ztl 已提交
108 109 110 111 112
            print ('Error in calling command:' + cmdline.split(' ')[0])
            print ('Exception: ' + os.strerror(e.errno))
            if (os.strerror(e.errno) == "No such file or directory"):
                print ("\nPlease check Toolchains PATH setting.\n")

113
            return e.errno
G
Grissiom 已提交
114 115
        finally:
            os.environ['PATH'] = old_path
116

G
Grissiom 已提交
117
        return proc.wait()
G
goprife@gmail.com 已提交
118

119 120
# generate cconfig.h file
def GenCconfigFile(env, BuildOptions):
121
    import rtconfig
122

123 124 125 126 127
    if rtconfig.PLATFORM == 'gcc':
        contents = ''
        if not os.path.isfile('cconfig.h'):
            import gcc
            gcc.GenerateGCCConfig(rtconfig)
128

129 130
        # try again
        if os.path.isfile('cconfig.h'):
131
            f = open('cconfig.h', 'r')
132 133
            if f:
                contents = f.read()
armink_ztl's avatar
armink_ztl 已提交
134
                f.close()
135

136 137 138
                prep = PatchedPreProcessor()
                prep.process_contents(contents)
                options = prep.cpp_namespace
139

140 141 142 143
                BuildOptions.update(options)

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

145
def PrepareBuilding(env, root_directory, has_libcpu=False, remove_components = []):
G
goprife@gmail.com 已提交
146 147 148 149 150 151 152
    import rtconfig

    global BuildOptions
    global Projects
    global Env
    global Rtt_Root

153 154 155 156 157 158
    # ===== Add option to SCons =====
    AddOption('--dist',
                      dest = 'make-dist',
                      action = 'store_true',
                      default = False,
                      help = 'make distribution')
159 160 161 162 163
    AddOption('--dist-strip',
                      dest = 'make-dist-strip',
                      action = 'store_true',
                      default = False,
                      help = 'make distribution and strip useless files')
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
    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',
armink_ztl's avatar
armink_ztl 已提交
190
                      help = 'set target project: mdk/mdk4/mdk5/iar/vs/vsc/ua/cdk/ses')
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
    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 已提交
206
    Env = env
207
    Rtt_Root = os.path.abspath(root_directory)
B
Bernard Xiong 已提交
208 209 210 211 212

    # make an absolute root directory
    RTT_ROOT = Rtt_Root
    Export('RTT_ROOT')

213 214 215 216 217
    # set RTT_ROOT in ENV
    Env['RTT_ROOT'] = Rtt_Root
    # set BSP_ROOT in ENV
    Env['BSP_ROOT'] = Dir('#').abspath

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

220 221 222 223 224 225 226 227 228 229
    # {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'),
armink_ztl's avatar
armink_ztl 已提交
230 231
                'cdk':('gcc', 'gcc'),
                'ses' : ('gcc', 'gcc')}
232 233 234 235 236 237
    tgt_name = GetOption('target')

    if tgt_name:
        # --target will change the toolchain settings which clang-analyzer is
        # depend on
        if GetOption('clang-analyzer'):
238
            print ('--clang-analyzer cannot be used with --target')
239 240 241 242 243 244 245
            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
246
            utils.ReloadModule(rtconfig)
247
        except KeyError:
248
            print ('Unknow target: '+ tgt_name+'. Avaible targets: ' +', '.join(tgt_dict.keys()))
249 250 251 252 253 254 255
            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):
256
        if 'RTT_EXEC_PATH' in os.environ:
257 258
            # del the 'RTT_EXEC_PATH' and using the 'EXEC_PATH' setting on rtconfig.py
            del os.environ['RTT_EXEC_PATH']
259
            utils.ReloadModule(rtconfig)
260

261 262 263 264 265
    # 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')
266
                Env['LINKFLAGS'] = Env['LINKFLAGS'].replace('RV31', 'armcc')
267

B
Bright Pan 已提交
268
        # reset AR command flags
B
bernard 已提交
269
        env['ARCOM'] = '$AR --create $TARGET $SOURCES'
270 271
        env['LIBPREFIX'] = ''
        env['LIBSUFFIX'] = '.lib'
B
bernard 已提交
272
        env['LIBLINKPREFIX'] = ''
273
        env['LIBLINKSUFFIX'] = '.lib'
B
bernard 已提交
274
        env['LIBDIRPREFIX'] = '--userlibpath '
B
bernard 已提交
275

G
goprife@gmail.com 已提交
276
    # patch for win32 spawn
G
Grissiom 已提交
277
    if env['PLATFORM'] == 'win32':
G
goprife@gmail.com 已提交
278 279 280
        win32_spawn = Win32Spawn()
        win32_spawn.env = env
        env['SPAWN'] = win32_spawn.spawn
G
Grissiom 已提交
281

282
    if env['PLATFORM'] == 'win32':
283 284 285
        os.environ['PATH'] = rtconfig.EXEC_PATH + ";" + os.environ['PATH']
    else:
        os.environ['PATH'] = rtconfig.EXEC_PATH + ":" + os.environ['PATH']
G
goprife@gmail.com 已提交
286 287 288

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

B
bernard 已提交
292 293 294 295 296
    # 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 已提交
297
    # parse rtconfig.h to get used component
298
    PreProcessor = PatchedPreProcessor()
299
    f = open('rtconfig.h', 'r')
G
goprife@gmail.com 已提交
300 301 302 303 304
    contents = f.read()
    f.close()
    PreProcessor.process_contents(contents)
    BuildOptions = PreProcessor.cpp_namespace

305 306 307 308 309 310 311 312 313 314
    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.
315 316 317 318 319
        # 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'])
320 321 322
        # remove the POST_ACTION as it will cause meaningless errors(file not
        # found or something like that).
        rtconfig.POST_ACTION = ''
323

324 325
    # generate cconfig.h file
    GenCconfigFile(env, BuildOptions)
G
goprife@gmail.com 已提交
326

327 328 329
    # 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'])
330

B
bernard 已提交
331 332 333 334 335
    if GetOption('genconfig'):
        from genconf import genconfig
        genconfig()
        exit(0)

B
Bernard Xiong 已提交
336
    if env['PLATFORM'] != 'win32':
337
        AddOption('--menuconfig',
B
Bernard Xiong 已提交
338 339 340 341 342 343 344 345 346
                    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)

347 348 349 350 351
    AddOption('--pyconfig',
                dest = 'pyconfig',
                action = 'store_true',
                default = False,
                help = 'make menuconfig for RT-Thread BSP')
armink_ztl's avatar
armink_ztl 已提交
352 353 354 355 356 357 358 359 360 361 362 363
    AddOption('--pyconfig-silent',
                dest = 'pyconfig_silent',
                action = 'store_true',
                default = False,
                help = 'Don`t show pyconfig window')

    if GetOption('pyconfig_silent'):    
        from menuconfig import pyconfig_silent

        pyconfig_silent(Rtt_Root)
        exit(0)
    elif GetOption('pyconfig'):
364
        from menuconfig import pyconfig
armink_ztl's avatar
armink_ztl 已提交
365

366 367 368
        pyconfig(Rtt_Root)
        exit(0)

B
bernard 已提交
369 370 371 372 373 374
    configfn = GetOption('useconfig')
    if configfn:
        from menuconfig import mk_rtconfig
        mk_rtconfig(configfn)
        exit(0)

375

376 377
    if not GetOption('verbose'):
        # override the default verbose command string
378
        env.Replace(
R
Rogerz Zhang 已提交
379
            ARCOMSTR = 'AR $TARGET',
380
            ASCOMSTR = 'AS $TARGET',
R
Rogerz Zhang 已提交
381
            ASPPCOMSTR = 'AS $TARGET',
382 383 384 385
            CCCOMSTR = 'CC $TARGET',
            CXXCOMSTR = 'CXX $TARGET',
            LINKCOMSTR = 'LINK $TARGET'
        )
G
goprife@gmail.com 已提交
386

387 388 389 390 391
    # fix the linker for C++
    if GetDepend('RT_USING_CPLUSPLUS'):
        if env['LINK'].find('gcc') != -1:
            env['LINK'] = env['LINK'].replace('gcc', 'g++')

392 393 394
    # 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 已提交
395
    bsp_vdir = 'build'
396 397 398
    kernel_vdir = 'build/kernel'
    # board build script
    objs = SConscript('SConscript', variant_dir=bsp_vdir, duplicate=0)
G
goprife@gmail.com 已提交
399
    # include kernel
400
    objs.extend(SConscript(Rtt_Root + '/src/SConscript', variant_dir=kernel_vdir + '/src', duplicate=0))
G
goprife@gmail.com 已提交
401 402
    # include libcpu
    if not has_libcpu:
403 404
        objs.extend(SConscript(Rtt_Root + '/libcpu/SConscript',
                    variant_dir=kernel_vdir + '/libcpu', duplicate=0))
405

G
goprife@gmail.com 已提交
406
    # include components
407
    objs.extend(SConscript(Rtt_Root + '/components/SConscript',
408
                           variant_dir=kernel_vdir + '/components',
409 410
                           duplicate=0,
                           exports='remove_components'))
G
goprife@gmail.com 已提交
411 412 413

    return objs

B
Bernard Xiong 已提交
414
def PrepareModuleBuilding(env, root_directory, bsp_directory):
G
goprife@gmail.com 已提交
415 416
    import rtconfig

417
    global BuildOptions
G
goprife@gmail.com 已提交
418 419 420
    global Env
    global Rtt_Root

421 422 423 424 425 426
    # patch for win32 spawn
    if env['PLATFORM'] == 'win32':
        win32_spawn = Win32Spawn()
        win32_spawn.env = env
        env['SPAWN'] = win32_spawn.spawn

G
goprife@gmail.com 已提交
427 428 429
    Env = env
    Rtt_Root = root_directory

B
Bernard Xiong 已提交
430
    # parse bsp rtconfig.h to get used component
431
    PreProcessor = PatchedPreProcessor()
432
    f = open(bsp_directory + '/rtconfig.h', 'r')
B
Bernard Xiong 已提交
433 434 435 436 437
    contents = f.read()
    f.close()
    PreProcessor.process_contents(contents)
    BuildOptions = PreProcessor.cpp_namespace

B
Bright Pan 已提交
438 439 440
    # add build/clean library option for library checking
    AddOption('--buildlib',
              dest='buildlib',
B
bernard 已提交
441 442
              type='string',
              help='building library of a component')
B
Bright Pan 已提交
443 444
    AddOption('--cleanlib',
              dest='cleanlib',
B
bernard 已提交
445 446 447 448
              action='store_true',
              default=False,
              help='clean up the library by --buildlib')

G
goprife@gmail.com 已提交
449 450 451
    # add program path
    env.PrependENVPath('PATH', rtconfig.EXEC_PATH)

wuyangyong's avatar
wuyangyong 已提交
452 453 454 455 456 457 458
def GetConfigValue(name):
    assert type(name) == str, 'GetConfigValue: only string parameter is valid'
    try:
        return BuildOptions[name]
    except:
        return ''

G
goprife@gmail.com 已提交
459 460 461
def GetDepend(depend):
    building = True
    if type(depend) == type('str'):
462
        if not depend in BuildOptions or BuildOptions[depend] == 0:
G
goprife@gmail.com 已提交
463 464 465
            building = False
        elif BuildOptions[depend] != '':
            return BuildOptions[depend]
B
Bright Pan 已提交
466

G
goprife@gmail.com 已提交
467 468 469 470 471
        return building

    # for list type depend
    for item in depend:
        if item != '':
472
            if not item in BuildOptions or BuildOptions[item] == 0:
G
goprife@gmail.com 已提交
473 474 475 476
                building = False

    return building

B
Bernard Xiong 已提交
477 478 479 480 481 482
def LocalOptions(config_filename):
    from SCons.Script import SCons

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

483
    f = open(config_filename, 'r')
B
Bernard Xiong 已提交
484 485 486 487 488 489 490 491 492 493 494
    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'):
495
        if not depend in options or options[depend] == 0:
B
Bernard Xiong 已提交
496 497 498 499 500 501 502 503 504
            building = False
        elif options[depend] != '':
            return options[depend]

        return building

    # for list type depend
    for item in depend:
        if item != '':
505
            if not item in options or options[item] == 0:
B
Bernard Xiong 已提交
506 507 508 509
                building = False

    return building

G
goprife@gmail.com 已提交
510 511 512
def AddDepend(option):
    BuildOptions[option] = 1

513 514
def MergeGroup(src_group, group):
    src_group['src'] = src_group['src'] + group['src']
515 516
    if 'CCFLAGS' in group:
        if 'CCFLAGS' in src_group:
517 518 519
            src_group['CCFLAGS'] = src_group['CCFLAGS'] + group['CCFLAGS']
        else:
            src_group['CCFLAGS'] = group['CCFLAGS']
520 521
    if 'CPPPATH' in group:
        if 'CPPPATH' in src_group:
522 523 524
            src_group['CPPPATH'] = src_group['CPPPATH'] + group['CPPPATH']
        else:
            src_group['CPPPATH'] = group['CPPPATH']
525 526
    if 'CPPDEFINES' in group:
        if 'CPPDEFINES' in src_group:
527 528 529
            src_group['CPPDEFINES'] = src_group['CPPDEFINES'] + group['CPPDEFINES']
        else:
            src_group['CPPDEFINES'] = group['CPPDEFINES']
530 531
    if 'ASFLAGS' in group:
        if 'ASFLAGS' in src_group:
532 533 534
            src_group['ASFLAGS'] = src_group['ASFLAGS'] + group['ASFLAGS']
        else:
            src_group['ASFLAGS'] = group['ASFLAGS']
535 536

    # for local CCFLAGS/CPPPATH/CPPDEFINES
537 538
    if 'LOCAL_CCFLAGS' in group:
        if 'LOCAL_CCFLAGS' in src_group:
539 540 541
            src_group['LOCAL_CCFLAGS'] = src_group['LOCAL_CCFLAGS'] + group['LOCAL_CCFLAGS']
        else:
            src_group['LOCAL_CCFLAGS'] = group['LOCAL_CCFLAGS']
542 543
    if 'LOCAL_CPPPATH' in group:
        if 'LOCAL_CPPPATH' in src_group:
544 545 546
            src_group['LOCAL_CPPPATH'] = src_group['LOCAL_CPPPATH'] + group['LOCAL_CPPPATH']
        else:
            src_group['LOCAL_CPPPATH'] = group['LOCAL_CPPPATH']
547 548
    if 'LOCAL_CPPDEFINES' in group:
        if 'LOCAL_CPPDEFINES' in src_group:
549 550 551 552
            src_group['LOCAL_CPPDEFINES'] = src_group['LOCAL_CPPDEFINES'] + group['LOCAL_CPPDEFINES']
        else:
            src_group['LOCAL_CPPDEFINES'] = group['LOCAL_CPPDEFINES']

553 554
    if 'LINKFLAGS' in group:
        if 'LINKFLAGS' in src_group:
555 556 557
            src_group['LINKFLAGS'] = src_group['LINKFLAGS'] + group['LINKFLAGS']
        else:
            src_group['LINKFLAGS'] = group['LINKFLAGS']
558 559
    if 'LIBS' in group:
        if 'LIBS' in src_group:
560
            src_group['LIBS'] = src_group['LIBS'] + group['LIBS']
561
        else:
562
            src_group['LIBS'] = group['LIBS']
563 564
    if 'LIBPATH' in group:
        if 'LIBPATH' in src_group:
565 566 567
            src_group['LIBPATH'] = src_group['LIBPATH'] + group['LIBPATH']
        else:
            src_group['LIBPATH'] = group['LIBPATH']
568 569
    if 'LOCAL_ASFLAGS' in group:
        if 'LOCAL_ASFLAGS' in src_group:
570 571 572
            src_group['LOCAL_ASFLAGS'] = src_group['LOCAL_ASFLAGS'] + group['LOCAL_ASFLAGS']
        else:
            src_group['LOCAL_ASFLAGS'] = group['LOCAL_ASFLAGS']
573

G
goprife@gmail.com 已提交
574 575 576 577 578
def DefineGroup(name, src, depend, **parameters):
    global Env
    if not GetDepend(depend):
        return []

579 580 581 582 583 584 585 586
    # 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 已提交
587 588
    group = parameters
    group['name'] = name
589
    group['path'] = group_path
590
    if type(src) == type([]):
G
goprife@gmail.com 已提交
591 592 593 594
        group['src'] = File(src)
    else:
        group['src'] = src

595
    if 'CCFLAGS' in group:
596
        Env.AppendUnique(CCFLAGS = group['CCFLAGS'])
597
    if 'CPPPATH' in group:
598 599 600 601
        paths = []
        for item in group['CPPPATH']:
            paths.append(os.path.abspath(item))
        group['CPPPATH'] = paths
602
        Env.AppendUnique(CPPPATH = group['CPPPATH'])
603
    if 'CPPDEFINES' in group:
604
        Env.AppendUnique(CPPDEFINES = group['CPPDEFINES'])
605
    if 'LINKFLAGS' in group:
606
        Env.AppendUnique(LINKFLAGS = group['LINKFLAGS'])
607
    if 'ASFLAGS' in group:
608
        Env.AppendUnique(ASFLAGS = group['ASFLAGS'])
609 610 611 612 613 614 615 616 617 618 619 620
    if 'LOCAL_CPPPATH' in group:
        paths = []
        for item in group['LOCAL_CPPPATH']:
            paths.append(os.path.abspath(item))
        group['LOCAL_CPPPATH'] = paths

    import rtconfig
    if rtconfig.PLATFORM == 'gcc':
        if 'CCFLAGS' in group:
            group['CCFLAGS'] = utils.GCCC99Patch(group['CCFLAGS'])
        if 'LOCAL_CCFLAGS' in group:
            group['LOCAL_CCFLAGS'] = utils.GCCC99Patch(group['LOCAL_CCFLAGS'])
B
bernard 已提交
621

B
Bright Pan 已提交
622
    # check whether to clean up library
B
bernard 已提交
623
    if GetOption('cleanlib') and os.path.exists(os.path.join(group['path'], GroupLibFullName(name, Env))):
B
bernard 已提交
624
        if group['src'] != []:
625
            print ('Remove library:'+ GroupLibFullName(name, Env))
B
bernard 已提交
626 627 628
            fn = os.path.join(group['path'], GroupLibFullName(name, Env))
            if os.path.exists(fn):
                os.unlink(fn)
B
bernard 已提交
629

630
    if 'LIBS' in group:
631
        Env.AppendUnique(LIBS = group['LIBS'])
632
    if 'LIBPATH' in group:
633
        Env.AppendUnique(LIBPATH = group['LIBPATH'])
G
goprife@gmail.com 已提交
634

635
    # check whether to build group library
636
    if 'LIBRARY' in group:
637 638
        objs = Env.Library(name, group['src'])
    else:
639
        # only add source
640
        objs = group['src']
G
goprife@gmail.com 已提交
641

B
Bright Pan 已提交
642
    # merge group
643 644 645 646 647 648
    for g in Projects:
        if g['name'] == name:
            # merge to this group
            MergeGroup(g, group)
            return objs

B
Bright Pan 已提交
649
    # add a new group
650 651
    Projects.append(group)

G
goprife@gmail.com 已提交
652 653 654 655 656 657 658 659 660
    return objs

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

661 662 663 664 665 666 667 668 669 670 671
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 已提交
672
def GroupLibName(name, env):
B
bernard 已提交
673 674 675 676 677 678 679 680 681 682
    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 已提交
683 684 685 686 687

def BuildLibInstallAction(target, source, env):
    lib_name = GetOption('buildlib')
    for Group in Projects:
        if Group['name'] == lib_name:
B
bernard 已提交
688
            lib_name = GroupLibFullName(Group['name'], env)
B
bernard 已提交
689
            dst_name = os.path.join(Group['path'], lib_name)
690
            print ('Copy '+lib_name+' => ' +dst_name)
B
bernard 已提交
691 692 693
            do_copy_file(lib_name, dst_name)
            break

694
def DoBuilding(target, objects):
695 696 697 698 699 700 701 702 703 704 705

    # 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

706 707
    # handle local group
    def local_group(group, objects):
708
        if 'LOCAL_CCFLAGS' in group or 'LOCAL_CPPPATH' in group or 'LOCAL_CPPDEFINES' in group or 'LOCAL_ASFLAGS' in group:
709 710 711
            CCFLAGS = Env.get('CCFLAGS', '') + group.get('LOCAL_CCFLAGS', '')
            CPPPATH = Env.get('CPPPATH', ['']) + group.get('LOCAL_CPPPATH', [''])
            CPPDEFINES = Env.get('CPPDEFINES', ['']) + group.get('LOCAL_CPPDEFINES', [''])
712
            ASFLAGS = Env.get('ASFLAGS', '') + group.get('LOCAL_ASFLAGS', '')
713 714

            for source in group['src']:
715
                objects.append(Env.Object(source, CCFLAGS = CCFLAGS, ASFLAGS = ASFLAGS,
716 717 718 719 720 721 722
                    CPPPATH = CPPPATH, CPPDEFINES = CPPDEFINES))

            return True

        return False

    objects = one_list(objects)
723

724 725 726 727
    program = None
    # check whether special buildlib option
    lib_name = GetOption('buildlib')
    if lib_name:
728
        objects = [] # remove all of objects
729 730 731
        # build library with special component
        for Group in Projects:
            if Group['name'] == lib_name:
B
bernard 已提交
732
                lib_name = GroupLibName(Group['name'], Env)
733 734 735
                if not local_group(Group, objects):
                    objects = Env.Object(Group['src'])

736
                program = Env.Library(lib_name, objects)
B
bernard 已提交
737 738 739 740

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

741 742
                break
    else:
743 744
        # remove source files with local flags setting
        for group in Projects:
745
            if 'LOCAL_CCFLAGS' in group or 'LOCAL_CPPPATH' in group or 'LOCAL_CPPDEFINES' in group:
746 747 748 749 750 751 752 753 754
                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)

755 756 757
        program = Env.Program(target, objects)

    EndBuilding(target, program)
758

759
def GenTargetProject(program = None):
G
goprife@gmail.com 已提交
760 761

    if GetOption('target') == 'mdk':
B
bernard 已提交
762 763
        from keil import MDKProject
        from keil import MDK4Project
B
Bright Pan 已提交
764
        from keil import MDK5Project
B
bernard 已提交
765

G
goprife@gmail.com 已提交
766 767 768 769 770 771 772 773
        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 已提交
774 775 776 777
                template = os.path.isfile('template.uvprojx')
                if template:
                    MDK5Project('project.uvprojx', Projects)
                else:
778
                    print ('No template project file found.')
B
Bright Pan 已提交
779

G
goprife@gmail.com 已提交
780
    if GetOption('target') == 'mdk4':
B
bernard 已提交
781
        from keil import MDK4Project
G
goprife@gmail.com 已提交
782 783
        MDK4Project('project.uvproj', Projects)

B
Bright Pan 已提交
784 785 786 787
    if GetOption('target') == 'mdk5':
        from keil import MDK5Project
        MDK5Project('project.uvprojx', Projects)

G
goprife@gmail.com 已提交
788
    if GetOption('target') == 'iar':
B
bernard 已提交
789
        from iar import IARProject
B
Bright Pan 已提交
790
        IARProject('project.ewp', Projects)
791

792
    if GetOption('target') == 'vs':
B
bernard 已提交
793
        from vs import VSProject
794
        VSProject('project.vcproj', Projects, program)
795

796
    if GetOption('target') == 'vs2012':
B
bernard 已提交
797
        from vs2012 import VS2012Project
798 799
        VS2012Project('project.vcxproj', Projects, program)

wuyangyong's avatar
wuyangyong 已提交
800
    if GetOption('target') == 'cb':
B
bernard 已提交
801
        from codeblocks import CBProject
wuyangyong's avatar
wuyangyong 已提交
802 803
        CBProject('project.cbp', Projects, program)

B
bernard 已提交
804 805 806
    if GetOption('target') == 'ua':
        from ua import PrepareUA
        PrepareUA(Projects, Rtt_Root, str(Dir('#')))
B
Bright Pan 已提交
807

808 809 810
    if GetOption('target') == 'vsc':
        from vsc import GenerateVSCode
        GenerateVSCode(Env)
811

812 813 814
    if GetOption('target') == 'cdk':
        from cdk import CDKProject
        CDKProject('project.cdkproj', Projects)
815

armink_ztl's avatar
armink_ztl 已提交
816 817 818 819
    if GetOption('target') == 'ses':
        from ses import SESProject
        SESProject(Env)

820 821 822 823 824 825 826 827
def EndBuilding(target, program = None):
    import rtconfig

    need_exit = False

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

armink_ztl's avatar
armink_ztl 已提交
828 829 830 831 832 833
    if hasattr(rtconfig, 'BSP_LIBRARY_TYPE'):
        Env['bsp_lib_type'] = rtconfig.BSP_LIBRARY_TYPE

    if hasattr(rtconfig, 'dist_handle'):
        Env['dist_handle'] = rtconfig.dist_handle

834 835 836 837 838 839 840 841 842
    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 已提交
843 844 845 846
    BSP_ROOT = Dir('#').abspath
    if GetOption('make-dist') and program != None:
        from mkdist import MkDist
        MkDist(program, BSP_ROOT, Rtt_Root, Env)
847 848 849
    if GetOption('make-dist-strip') and program != None:
        from mkdist import MkDist_Strip
        MkDist_Strip(program, BSP_ROOT, Rtt_Root, Env)
850
        need_exit = True
851 852 853 854
    if GetOption('cscope'):
        from cscope import CscopeDatabase
        CscopeDatabase(Projects)

855 856
    if not GetOption('help') and not GetOption('target'):
        if not os.path.exists(rtconfig.EXEC_PATH):
857
            print ("Error: the toolchain path (" + rtconfig.EXEC_PATH + ") is not exist, please check 'EXEC_PATH' in path or rtconfig.py.")
858 859 860 861
            need_exit = True

    if need_exit:
        exit(0)
862

G
goprife@gmail.com 已提交
863
def SrcRemove(src, remove):
G
Grissiom 已提交
864 865 866
    if not src:
        return

X
xieyangrun 已提交
867
    src_bak = src[:]
868 869 870 871 872 873

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

X
xieyangrun 已提交
874
        for item in src_bak:
875 876 877 878
            if type(item) == type('str'):
                item_str = item
            else:
                item_str = item.rstr()
879

880 881 882
            if os.path.isabs(item_str):
                item_str = os.path.relpath(item_str, GetCurrentDir())
            item_str = os.path.normpath(item_str)
883 884

            if item_str == remove:
X
xieyangrun 已提交
885
                src.remove(item)
886 887 888 889 890 891 892
    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 已提交
893
            for item in src_bak:
894 895 896 897 898 899 900 901 902 903
                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 已提交
904
                    src.remove(item)
905 906 907 908 909 910 911

def GetVersion():
    import SCons.cpp
    import string

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

B
Bright Pan 已提交
912
    # parse rtdef.h to get RT-Thread version
913
    prepcessor = PatchedPreProcessor()
914
    f = open(rtdef, 'r')
915 916 917 918 919 920 921 922
    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']))

923
    if 'RT_REVISION' in def_ns:
924 925 926 927
        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)
928

929 930 931 932
def GlobSubDir(sub_dir, ext_name):
    import os
    import glob

933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
    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
948

949 950 951 952
def PackageSConscript(package):
    from package import BuildPackage

    return BuildPackage(package)