building.py 34.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
# 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
X
xieyangrun 已提交
31
import operator
G
goprife@gmail.com 已提交
32 33

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

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

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

75 76 77 78
PatchedPreProcessor = SCons.cpp.PreProcessor
PatchedPreProcessor.start_handling_includes = start_handling_includes
PatchedPreProcessor.stop_handling_includes = stop_handling_includes

G
goprife@gmail.com 已提交
79 80
class Win32Spawn:
    def spawn(self, sh, escape, cmd, args, env):
G
Grissiom 已提交
81 82 83 84 85 86 87
        # 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:
88
                    print ('Error removing file: ' + e)
G
Grissiom 已提交
89 90 91
                    return -1
            return 0

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

94
        newargs = ' '.join(args[1:])
G
goprife@gmail.com 已提交
95
        cmdline = cmd + " " + newargs
G
Grissiom 已提交
96 97

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

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

G
Grissiom 已提交
106
        try:
107
            proc = subprocess.Popen(cmdline, env=_e, shell=False)
G
Grissiom 已提交
108
        except Exception as e:
109 110 111 112 113
            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")

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

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

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

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

130 131
        # try again
        if os.path.isfile('cconfig.h'):
132
            f = open('cconfig.h', 'r')
133 134
            if f:
                contents = f.read()
135
                f.close()
136

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

141 142 143 144
                BuildOptions.update(options)

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

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

    global BuildOptions
    global Projects
    global Env
    global Rtt_Root

154 155 156 157 158 159
    # ===== Add option to SCons =====
    AddOption('--dist',
                      dest = 'make-dist',
                      action = 'store_true',
                      default = False,
                      help = 'make distribution')
160 161 162 163 164
    AddOption('--dist-strip',
                      dest = 'make-dist-strip',
                      action = 'store_true',
                      default = False,
                      help = 'make distribution and strip useless files')
S
SummerGift 已提交
165 166
    AddOption('--dist-ide',
                      dest = 'make-dist-ide',
167
                      action = 'store_true',
S
SummerGift 已提交
168
                      default = False,
169
                      help = 'make distribution for RT-Thread Studio IDE')
170
    AddOption('--project-path',
171
                      dest = 'project-path',
172
                      type = 'string',
173
                      default = None,
174 175
                      help = 'set dist-ide project output path')
    AddOption('--project-name',
176
                      dest = 'project-name',
177
                      type = 'string',
178
                      default = None,
179
                      help = 'set project name')
180 181 182 183 184
    AddOption('--reset-project-config',
                      dest = 'reset-project-config',
                      action = 'store_true',
                      default = False,
                      help = 'reset the project configurations to default')
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
    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',
M
mx 已提交
211
                      help = 'set target project: mdk/mdk4/mdk5/iar/vs/vsc/ua/cdk/ses/makefile/eclipse/codelite')
csdn_JZ_'s avatar
csdn_JZ_ 已提交
212 213 214 215 216
    AddOption('--stackanalysis',
                dest = 'stackanalysis',
                action = 'store_true',
                default = False,
                help = 'thread stack static analysis')
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
    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 已提交
232
    Env = env
233
    Rtt_Root = os.path.abspath(root_directory)
B
Bernard Xiong 已提交
234 235 236 237 238

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

239 240 241 242 243
    # set RTT_ROOT in ENV
    Env['RTT_ROOT'] = Rtt_Root
    # set BSP_ROOT in ENV
    Env['BSP_ROOT'] = Dir('#').abspath

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

246 247 248 249 250 251 252 253 254 255
    # {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'),
256
                'cdk':('gcc', 'gcc'),
257
                'makefile':('gcc', 'gcc'),
B
Bernard Xiong 已提交
258
                'eclipse':('gcc', 'gcc'),
M
mx 已提交
259 260
                'ses' : ('gcc', 'gcc'),
                'codelite' : ('gcc', 'gcc')}
261 262 263 264 265 266
    tgt_name = GetOption('target')

    if tgt_name:
        # --target will change the toolchain settings which clang-analyzer is
        # depend on
        if GetOption('clang-analyzer'):
267
            print ('--clang-analyzer cannot be used with --target')
268 269 270 271 272 273 274
            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
275
            utils.ReloadModule(rtconfig)
276
        except KeyError:
277
            print ('Unknow target: '+ tgt_name+'. Avaible targets: ' +', '.join(tgt_dict.keys()))
278 279 280 281 282 283 284
            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):
285
        if 'RTT_EXEC_PATH' in os.environ:
286 287
            # del the 'RTT_EXEC_PATH' and using the 'EXEC_PATH' setting on rtconfig.py
            del os.environ['RTT_EXEC_PATH']
288
            utils.ReloadModule(rtconfig)
289

290
    # add compability with Keil MDK 4.6 which changes the directory of armcc.exe
L
liruncong 已提交
291 292
    if rtconfig.PLATFORM == 'armcc' or rtconfig.PLATFORM == 'armclang':
        if rtconfig.PLATFORM == 'armcc' and not os.path.isfile(os.path.join(rtconfig.EXEC_PATH, 'armcc.exe')):
293 294
            if rtconfig.EXEC_PATH.find('bin40') > 0:
                rtconfig.EXEC_PATH = rtconfig.EXEC_PATH.replace('bin40', 'armcc/bin')
295
                Env['LINKFLAGS'] = Env['LINKFLAGS'].replace('RV31', 'armcc')
296

B
Bright Pan 已提交
297
        # reset AR command flags
B
bernard 已提交
298
        env['ARCOM'] = '$AR --create $TARGET $SOURCES'
299 300
        env['LIBPREFIX'] = ''
        env['LIBSUFFIX'] = '.lib'
B
bernard 已提交
301
        env['LIBLINKPREFIX'] = ''
302
        env['LIBLINKSUFFIX'] = '.lib'
B
bernard 已提交
303
        env['LIBDIRPREFIX'] = '--userlibpath '
B
bernard 已提交
304

305 306 307 308 309 310 311
    elif rtconfig.PLATFORM == 'iar':
        env['LIBPREFIX'] = ''
        env['LIBSUFFIX'] = '.a'
        env['LIBLINKPREFIX'] = ''
        env['LIBLINKSUFFIX'] = '.a'
        env['LIBDIRPREFIX'] = '--search '

G
goprife@gmail.com 已提交
312
    # patch for win32 spawn
G
Grissiom 已提交
313
    if env['PLATFORM'] == 'win32':
G
goprife@gmail.com 已提交
314 315 316
        win32_spawn = Win32Spawn()
        win32_spawn.env = env
        env['SPAWN'] = win32_spawn.spawn
G
Grissiom 已提交
317

318
    if env['PLATFORM'] == 'win32':
319 320 321
        os.environ['PATH'] = rtconfig.EXEC_PATH + ";" + os.environ['PATH']
    else:
        os.environ['PATH'] = rtconfig.EXEC_PATH + ":" + os.environ['PATH']
G
goprife@gmail.com 已提交
322 323

    # add program path
324
    env.PrependENVPath('PATH', os.environ['PATH'])
325 326
    # add rtconfig.h/BSP path into Kernel group
    DefineGroup("Kernel", [], [], CPPPATH=[str(Dir('#').abspath)])
G
goprife@gmail.com 已提交
327

B
bernard 已提交
328 329 330 331 332
    # 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 已提交
333
    # parse rtconfig.h to get used component
334
    PreProcessor = PatchedPreProcessor()
335
    f = open('rtconfig.h', 'r')
G
goprife@gmail.com 已提交
336 337 338 339 340
    contents = f.read()
    f.close()
    PreProcessor.process_contents(contents)
    BuildOptions = PreProcessor.cpp_namespace

341 342 343 344 345 346 347 348 349 350
    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.
351 352 353 354 355
        # 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'])
356 357 358
        # remove the POST_ACTION as it will cause meaningless errors(file not
        # found or something like that).
        rtconfig.POST_ACTION = ''
359

360 361
    # generate cconfig.h file
    GenCconfigFile(env, BuildOptions)
G
goprife@gmail.com 已提交
362

363 364 365
    # 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'])
366

B
bernard 已提交
367 368 369 370 371
    if GetOption('genconfig'):
        from genconf import genconfig
        genconfig()
        exit(0)

csdn_JZ_'s avatar
csdn_JZ_ 已提交
372 373 374 375 376
    if GetOption('stackanalysis'):
        from WCS import ThreadStackStaticAnalysis
        ThreadStackStaticAnalysis(Env)
        exit(0)
    
B
Bernard Xiong 已提交
377
    if env['PLATFORM'] != 'win32':
378
        AddOption('--menuconfig',
B
Bernard Xiong 已提交
379 380 381 382 383 384 385 386 387
                    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)

388 389 390 391
    AddOption('--pyconfig',
                dest = 'pyconfig',
                action = 'store_true',
                default = False,
392
                help = 'Python GUI menuconfig for RT-Thread BSP')
393 394 395 396 397 398 399
    AddOption('--pyconfig-silent',
                dest = 'pyconfig_silent',
                action = 'store_true',
                default = False,
                help = 'Don`t show pyconfig window')

    if GetOption('pyconfig_silent'):    
400
        from menuconfig import guiconfig_silent
401

402
        guiconfig_silent(Rtt_Root)
403 404
        exit(0)
    elif GetOption('pyconfig'):
405 406 407 408
        from menuconfig import guiconfig

        guiconfig(Rtt_Root)
        exit(0)
409

B
bernard 已提交
410 411 412 413 414 415
    configfn = GetOption('useconfig')
    if configfn:
        from menuconfig import mk_rtconfig
        mk_rtconfig(configfn)
        exit(0)

416

417 418
    if not GetOption('verbose'):
        # override the default verbose command string
419
        env.Replace(
R
Rogerz Zhang 已提交
420
            ARCOMSTR = 'AR $TARGET',
421
            ASCOMSTR = 'AS $TARGET',
R
Rogerz Zhang 已提交
422
            ASPPCOMSTR = 'AS $TARGET',
423 424 425 426
            CCCOMSTR = 'CC $TARGET',
            CXXCOMSTR = 'CXX $TARGET',
            LINKCOMSTR = 'LINK $TARGET'
        )
G
goprife@gmail.com 已提交
427

428 429 430 431 432
    # fix the linker for C++
    if GetDepend('RT_USING_CPLUSPLUS'):
        if env['LINK'].find('gcc') != -1:
            env['LINK'] = env['LINK'].replace('gcc', 'g++')

433 434 435
    # 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 已提交
436
    bsp_vdir = 'build'
437 438 439
    kernel_vdir = 'build/kernel'
    # board build script
    objs = SConscript('SConscript', variant_dir=bsp_vdir, duplicate=0)
G
goprife@gmail.com 已提交
440
    # include kernel
441
    objs.extend(SConscript(Rtt_Root + '/src/SConscript', variant_dir=kernel_vdir + '/src', duplicate=0))
G
goprife@gmail.com 已提交
442 443
    # include libcpu
    if not has_libcpu:
444 445
        objs.extend(SConscript(Rtt_Root + '/libcpu/SConscript',
                    variant_dir=kernel_vdir + '/libcpu', duplicate=0))
446

G
goprife@gmail.com 已提交
447
    # include components
448
    objs.extend(SConscript(Rtt_Root + '/components/SConscript',
449
                           variant_dir=kernel_vdir + '/components',
450 451
                           duplicate=0,
                           exports='remove_components'))
G
goprife@gmail.com 已提交
452 453 454

    return objs

B
Bernard Xiong 已提交
455
def PrepareModuleBuilding(env, root_directory, bsp_directory):
G
goprife@gmail.com 已提交
456 457
    import rtconfig

458
    global BuildOptions
G
goprife@gmail.com 已提交
459 460 461
    global Env
    global Rtt_Root

462 463 464 465 466 467
    # patch for win32 spawn
    if env['PLATFORM'] == 'win32':
        win32_spawn = Win32Spawn()
        win32_spawn.env = env
        env['SPAWN'] = win32_spawn.spawn

G
goprife@gmail.com 已提交
468 469 470
    Env = env
    Rtt_Root = root_directory

B
Bernard Xiong 已提交
471
    # parse bsp rtconfig.h to get used component
472
    PreProcessor = PatchedPreProcessor()
473
    f = open(bsp_directory + '/rtconfig.h', 'r')
B
Bernard Xiong 已提交
474 475 476 477 478
    contents = f.read()
    f.close()
    PreProcessor.process_contents(contents)
    BuildOptions = PreProcessor.cpp_namespace

B
Bright Pan 已提交
479 480 481
    # add build/clean library option for library checking
    AddOption('--buildlib',
              dest='buildlib',
B
bernard 已提交
482 483
              type='string',
              help='building library of a component')
B
Bright Pan 已提交
484 485
    AddOption('--cleanlib',
              dest='cleanlib',
B
bernard 已提交
486 487 488 489
              action='store_true',
              default=False,
              help='clean up the library by --buildlib')

G
goprife@gmail.com 已提交
490 491 492
    # add program path
    env.PrependENVPath('PATH', rtconfig.EXEC_PATH)

wuyangyong's avatar
wuyangyong 已提交
493 494 495 496 497 498 499
def GetConfigValue(name):
    assert type(name) == str, 'GetConfigValue: only string parameter is valid'
    try:
        return BuildOptions[name]
    except:
        return ''

G
goprife@gmail.com 已提交
500 501 502
def GetDepend(depend):
    building = True
    if type(depend) == type('str'):
503
        if not depend in BuildOptions or BuildOptions[depend] == 0:
G
goprife@gmail.com 已提交
504 505 506
            building = False
        elif BuildOptions[depend] != '':
            return BuildOptions[depend]
B
Bright Pan 已提交
507

G
goprife@gmail.com 已提交
508 509 510 511 512
        return building

    # for list type depend
    for item in depend:
        if item != '':
513
            if not item in BuildOptions or BuildOptions[item] == 0:
G
goprife@gmail.com 已提交
514 515 516 517
                building = False

    return building

B
Bernard Xiong 已提交
518 519 520 521 522 523
def LocalOptions(config_filename):
    from SCons.Script import SCons

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

524
    f = open(config_filename, 'r')
B
Bernard Xiong 已提交
525 526 527 528 529 530 531 532 533 534 535
    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'):
536
        if not depend in options or options[depend] == 0:
B
Bernard Xiong 已提交
537 538 539 540 541 542 543 544 545
            building = False
        elif options[depend] != '':
            return options[depend]

        return building

    # for list type depend
    for item in depend:
        if item != '':
546
            if not item in options or options[item] == 0:
B
Bernard Xiong 已提交
547 548 549 550
                building = False

    return building

G
goprife@gmail.com 已提交
551 552 553
def AddDepend(option):
    BuildOptions[option] = 1

554 555
def MergeGroup(src_group, group):
    src_group['src'] = src_group['src'] + group['src']
556 557
    if 'CCFLAGS' in group:
        if 'CCFLAGS' in src_group:
558 559 560
            src_group['CCFLAGS'] = src_group['CCFLAGS'] + group['CCFLAGS']
        else:
            src_group['CCFLAGS'] = group['CCFLAGS']
561 562
    if 'CPPPATH' in group:
        if 'CPPPATH' in src_group:
563 564 565
            src_group['CPPPATH'] = src_group['CPPPATH'] + group['CPPPATH']
        else:
            src_group['CPPPATH'] = group['CPPPATH']
566 567
    if 'CPPDEFINES' in group:
        if 'CPPDEFINES' in src_group:
568 569 570
            src_group['CPPDEFINES'] = src_group['CPPDEFINES'] + group['CPPDEFINES']
        else:
            src_group['CPPDEFINES'] = group['CPPDEFINES']
571 572
    if 'ASFLAGS' in group:
        if 'ASFLAGS' in src_group:
573 574 575
            src_group['ASFLAGS'] = src_group['ASFLAGS'] + group['ASFLAGS']
        else:
            src_group['ASFLAGS'] = group['ASFLAGS']
576 577

    # for local CCFLAGS/CPPPATH/CPPDEFINES
578 579
    if 'LOCAL_CCFLAGS' in group:
        if 'LOCAL_CCFLAGS' in src_group:
580 581 582
            src_group['LOCAL_CCFLAGS'] = src_group['LOCAL_CCFLAGS'] + group['LOCAL_CCFLAGS']
        else:
            src_group['LOCAL_CCFLAGS'] = group['LOCAL_CCFLAGS']
583 584
    if 'LOCAL_CPPPATH' in group:
        if 'LOCAL_CPPPATH' in src_group:
585 586 587
            src_group['LOCAL_CPPPATH'] = src_group['LOCAL_CPPPATH'] + group['LOCAL_CPPPATH']
        else:
            src_group['LOCAL_CPPPATH'] = group['LOCAL_CPPPATH']
588 589
    if 'LOCAL_CPPDEFINES' in group:
        if 'LOCAL_CPPDEFINES' in src_group:
590 591 592 593
            src_group['LOCAL_CPPDEFINES'] = src_group['LOCAL_CPPDEFINES'] + group['LOCAL_CPPDEFINES']
        else:
            src_group['LOCAL_CPPDEFINES'] = group['LOCAL_CPPDEFINES']

594 595
    if 'LINKFLAGS' in group:
        if 'LINKFLAGS' in src_group:
596 597 598
            src_group['LINKFLAGS'] = src_group['LINKFLAGS'] + group['LINKFLAGS']
        else:
            src_group['LINKFLAGS'] = group['LINKFLAGS']
599 600
    if 'LIBS' in group:
        if 'LIBS' in src_group:
601
            src_group['LIBS'] = src_group['LIBS'] + group['LIBS']
602
        else:
603
            src_group['LIBS'] = group['LIBS']
604 605
    if 'LIBPATH' in group:
        if 'LIBPATH' in src_group:
606 607 608
            src_group['LIBPATH'] = src_group['LIBPATH'] + group['LIBPATH']
        else:
            src_group['LIBPATH'] = group['LIBPATH']
609 610
    if 'LOCAL_ASFLAGS' in group:
        if 'LOCAL_ASFLAGS' in src_group:
611 612 613
            src_group['LOCAL_ASFLAGS'] = src_group['LOCAL_ASFLAGS'] + group['LOCAL_ASFLAGS']
        else:
            src_group['LOCAL_ASFLAGS'] = group['LOCAL_ASFLAGS']
614

G
goprife@gmail.com 已提交
615 616 617 618 619
def DefineGroup(name, src, depend, **parameters):
    global Env
    if not GetDepend(depend):
        return []

620 621 622 623 624 625 626 627
    # 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 已提交
628 629
    group = parameters
    group['name'] = name
630
    group['path'] = group_path
631
    if type(src) == type([]):
G
goprife@gmail.com 已提交
632 633 634 635
        group['src'] = File(src)
    else:
        group['src'] = src

636
    if 'CCFLAGS' in group:
637
        Env.AppendUnique(CCFLAGS = group['CCFLAGS'])
638
    if 'CPPPATH' in group:
639 640 641 642
        paths = []
        for item in group['CPPPATH']:
            paths.append(os.path.abspath(item))
        group['CPPPATH'] = paths
643
        Env.AppendUnique(CPPPATH = group['CPPPATH'])
644
    if 'CPPDEFINES' in group:
645
        Env.AppendUnique(CPPDEFINES = group['CPPDEFINES'])
646
    if 'LINKFLAGS' in group:
647
        Env.AppendUnique(LINKFLAGS = group['LINKFLAGS'])
648
    if 'ASFLAGS' in group:
649
        Env.AppendUnique(ASFLAGS = group['ASFLAGS'])
650 651 652 653 654 655 656 657 658 659 660 661
    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 已提交
662

B
Bright Pan 已提交
663
    # check whether to clean up library
B
bernard 已提交
664
    if GetOption('cleanlib') and os.path.exists(os.path.join(group['path'], GroupLibFullName(name, Env))):
B
bernard 已提交
665
        if group['src'] != []:
666
            print ('Remove library:'+ GroupLibFullName(name, Env))
B
bernard 已提交
667 668 669
            fn = os.path.join(group['path'], GroupLibFullName(name, Env))
            if os.path.exists(fn):
                os.unlink(fn)
B
bernard 已提交
670

671
    if 'LIBS' in group:
672
        Env.AppendUnique(LIBS = group['LIBS'])
673
    if 'LIBPATH' in group:
674
        Env.AppendUnique(LIBPATH = group['LIBPATH'])
G
goprife@gmail.com 已提交
675

676
    # check whether to build group library
677
    if 'LIBRARY' in group:
678 679
        objs = Env.Library(name, group['src'])
    else:
680
        # only add source
681
        objs = group['src']
G
goprife@gmail.com 已提交
682

B
Bright Pan 已提交
683
    # merge group
684 685 686 687 688 689
    for g in Projects:
        if g['name'] == name:
            # merge to this group
            MergeGroup(g, group)
            return objs

X
xieyangrun 已提交
690 691 692
    def PriorityInsertGroup(groups, group):
        length = len(groups)
        for i in range(0, length):
X
xieyangrun 已提交
693
            if operator.gt(groups[i]['name'].lower(), group['name'].lower()):
X
xieyangrun 已提交
694 695 696 697
                groups.insert(i, group)
                return
        groups.append(group)

B
Bright Pan 已提交
698
    # add a new group
X
xieyangrun 已提交
699
    PriorityInsertGroup(Projects, group)
700

G
goprife@gmail.com 已提交
701 702 703 704 705 706 707 708 709
    return objs

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

710 711 712 713 714 715 716 717 718 719 720
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 已提交
721
def GroupLibName(name, env):
B
bernard 已提交
722 723 724 725 726 727 728 729 730 731
    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 已提交
732 733 734 735 736

def BuildLibInstallAction(target, source, env):
    lib_name = GetOption('buildlib')
    for Group in Projects:
        if Group['name'] == lib_name:
B
bernard 已提交
737
            lib_name = GroupLibFullName(Group['name'], env)
B
bernard 已提交
738
            dst_name = os.path.join(Group['path'], lib_name)
739
            print ('Copy '+lib_name+' => ' +dst_name)
B
bernard 已提交
740 741 742
            do_copy_file(lib_name, dst_name)
            break

743
def DoBuilding(target, objects):
744 745 746 747 748 749 750 751 752 753 754

    # 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

755 756
    # handle local group
    def local_group(group, objects):
757
        if 'LOCAL_CCFLAGS' in group or 'LOCAL_CPPPATH' in group or 'LOCAL_CPPDEFINES' in group or 'LOCAL_ASFLAGS' in group:
758 759 760
            CCFLAGS = Env.get('CCFLAGS', '') + group.get('LOCAL_CCFLAGS', '')
            CPPPATH = Env.get('CPPPATH', ['']) + group.get('LOCAL_CPPPATH', [''])
            CPPDEFINES = Env.get('CPPDEFINES', ['']) + group.get('LOCAL_CPPDEFINES', [''])
761
            ASFLAGS = Env.get('ASFLAGS', '') + group.get('LOCAL_ASFLAGS', '')
762 763

            for source in group['src']:
764
                objects.append(Env.Object(source, CCFLAGS = CCFLAGS, ASFLAGS = ASFLAGS,
765 766 767 768 769 770 771
                    CPPPATH = CPPPATH, CPPDEFINES = CPPDEFINES))

            return True

        return False

    objects = one_list(objects)
772

773 774 775 776
    program = None
    # check whether special buildlib option
    lib_name = GetOption('buildlib')
    if lib_name:
777
        objects = [] # remove all of objects
778 779 780
        # build library with special component
        for Group in Projects:
            if Group['name'] == lib_name:
B
bernard 已提交
781
                lib_name = GroupLibName(Group['name'], Env)
782 783 784
                if not local_group(Group, objects):
                    objects = Env.Object(Group['src'])

785
                program = Env.Library(lib_name, objects)
B
bernard 已提交
786 787 788 789

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

790 791
                break
    else:
792 793
        # remove source files with local flags setting
        for group in Projects:
794
            if 'LOCAL_CCFLAGS' in group or 'LOCAL_CPPPATH' in group or 'LOCAL_CPPDEFINES' in group:
795 796 797 798 799 800 801 802 803
                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)

804 805 806
        program = Env.Program(target, objects)

    EndBuilding(target, program)
807

808
def GenTargetProject(program = None):
G
goprife@gmail.com 已提交
809 810

    if GetOption('target') == 'mdk':
B
bernard 已提交
811 812
        from keil import MDKProject
        from keil import MDK4Project
B
Bright Pan 已提交
813
        from keil import MDK5Project
B
bernard 已提交
814

G
goprife@gmail.com 已提交
815 816 817 818 819 820 821 822
        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 已提交
823 824 825 826
                template = os.path.isfile('template.uvprojx')
                if template:
                    MDK5Project('project.uvprojx', Projects)
                else:
827
                    print ('No template project file found.')
B
Bright Pan 已提交
828

G
goprife@gmail.com 已提交
829
    if GetOption('target') == 'mdk4':
B
bernard 已提交
830
        from keil import MDK4Project
G
goprife@gmail.com 已提交
831 832
        MDK4Project('project.uvproj', Projects)

B
Bright Pan 已提交
833 834 835 836
    if GetOption('target') == 'mdk5':
        from keil import MDK5Project
        MDK5Project('project.uvprojx', Projects)

G
goprife@gmail.com 已提交
837
    if GetOption('target') == 'iar':
B
bernard 已提交
838
        from iar import IARProject
B
Bright Pan 已提交
839
        IARProject('project.ewp', Projects)
840

841
    if GetOption('target') == 'vs':
B
bernard 已提交
842
        from vs import VSProject
843
        VSProject('project.vcproj', Projects, program)
844

845
    if GetOption('target') == 'vs2012':
B
bernard 已提交
846
        from vs2012 import VS2012Project
847 848
        VS2012Project('project.vcxproj', Projects, program)

wuyangyong's avatar
wuyangyong 已提交
849
    if GetOption('target') == 'cb':
B
bernard 已提交
850
        from codeblocks import CBProject
wuyangyong's avatar
wuyangyong 已提交
851 852
        CBProject('project.cbp', Projects, program)

B
bernard 已提交
853 854 855
    if GetOption('target') == 'ua':
        from ua import PrepareUA
        PrepareUA(Projects, Rtt_Root, str(Dir('#')))
B
Bright Pan 已提交
856

857 858 859
    if GetOption('target') == 'vsc':
        from vsc import GenerateVSCode
        GenerateVSCode(Env)
860

861 862 863
    if GetOption('target') == 'cdk':
        from cdk import CDKProject
        CDKProject('project.cdkproj', Projects)
864

865 866 867 868
    if GetOption('target') == 'ses':
        from ses import SESProject
        SESProject(Env)

869 870 871 872
    if GetOption('target') == 'makefile':
        from makefile import TargetMakefile
        TargetMakefile(Env)

873 874
    if GetOption('target') == 'eclipse':
        from eclipse import TargetEclipse
875
        TargetEclipse(Env, GetOption('reset-project-config'), GetOption('project-name'))
M
mx 已提交
876 877 878 879
        
    if GetOption('target') == 'codelite':
        from codelite import TargetCodelite
        TargetCodelite(Projects, program)
880

881

882 883 884 885 886 887 888 889
def EndBuilding(target, program = None):
    import rtconfig

    need_exit = False

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

890 891 892
    if hasattr(rtconfig, 'BSP_LIBRARY_TYPE'):
        Env['bsp_lib_type'] = rtconfig.BSP_LIBRARY_TYPE

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

896 897 898 899 900 901 902 903 904
    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 已提交
905 906 907 908
    BSP_ROOT = Dir('#').abspath
    if GetOption('make-dist') and program != None:
        from mkdist import MkDist
        MkDist(program, BSP_ROOT, Rtt_Root, Env)
909 910 911
    if GetOption('make-dist-strip') and program != None:
        from mkdist import MkDist_Strip
        MkDist_Strip(program, BSP_ROOT, Rtt_Root, Env)
912
        need_exit = True
S
SummerGift 已提交
913 914
    if GetOption('make-dist-ide') and program != None:
        from mkdist import MkDist
915 916
        project_path = GetOption('project-path')
        project_name = GetOption('project-name')
917 918 919 920 921 922 923 924 925 926 927

        if not isinstance(project_path, str) or len(project_path) == 0 :
            print("\nwarning : --project-path=your_project_path parameter is required.")
            print("\nstop!")
            exit(0)

        if not isinstance(project_name, str) or len(project_name) == 0:
            print("\nwarning : --project-name=your_project_name parameter is required.")
            print("\nstop!")
            exit(0)

928
        rtt_ide = {'project_path' : project_path, 'project_name' : project_name}
S
SummerGift 已提交
929 930
        MkDist(program, BSP_ROOT, Rtt_Root, Env, rtt_ide)
        need_exit = True
931 932 933 934
    if GetOption('cscope'):
        from cscope import CscopeDatabase
        CscopeDatabase(Projects)

935 936
    if not GetOption('help') and not GetOption('target'):
        if not os.path.exists(rtconfig.EXEC_PATH):
937
            print ("Error: the toolchain path (" + rtconfig.EXEC_PATH + ") is not exist, please check 'EXEC_PATH' in path or rtconfig.py.")
938 939 940 941
            need_exit = True

    if need_exit:
        exit(0)
942

G
goprife@gmail.com 已提交
943
def SrcRemove(src, remove):
G
Grissiom 已提交
944 945 946
    if not src:
        return

X
xieyangrun 已提交
947
    src_bak = src[:]
948 949 950 951 952 953

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

X
xieyangrun 已提交
954
        for item in src_bak:
955 956 957 958
            if type(item) == type('str'):
                item_str = item
            else:
                item_str = item.rstr()
959

960 961 962
            if os.path.isabs(item_str):
                item_str = os.path.relpath(item_str, GetCurrentDir())
            item_str = os.path.normpath(item_str)
963 964

            if item_str == remove:
X
xieyangrun 已提交
965
                src.remove(item)
966 967 968 969 970 971 972
    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 已提交
973
            for item in src_bak:
974 975 976 977 978 979 980 981 982 983
                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 已提交
984
                    src.remove(item)
985 986 987 988 989 990 991

def GetVersion():
    import SCons.cpp
    import string

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

B
Bright Pan 已提交
992
    # parse rtdef.h to get RT-Thread version
993
    prepcessor = PatchedPreProcessor()
994
    f = open(rtdef, 'r')
995 996 997 998 999 1000 1001 1002
    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']))

1003
    if 'RT_REVISION' in def_ns:
1004 1005 1006 1007
        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)
1008

1009 1010 1011 1012
def GlobSubDir(sub_dir, ext_name):
    import os
    import glob

1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
    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
1028

1029 1030 1031 1032
def PackageSConscript(package):
    from package import BuildPackage

    return BuildPackage(package)