building.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. #
  2. # File : building.py
  3. # This file is part of RT-Thread RTOS
  4. # COPYRIGHT (C) 2006 - 2015, RT-Thread Development Team
  5. #
  6. # This program is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation; either version 2 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License along
  17. # with this program; if not, write to the Free Software Foundation, Inc.,
  18. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  19. #
  20. # Change Logs:
  21. # Date Author Notes
  22. # 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. import os
  27. import sys
  28. import string
  29. from SCons.Script import *
  30. from utils import _make_path_relative
  31. from mkdist import do_copy_file
  32. BuildOptions = {}
  33. Projects = []
  34. Rtt_Root = ''
  35. Env = None
  36. # SCons PreProcessor patch
  37. def start_handling_includes(self, t=None):
  38. """
  39. Causes the PreProcessor object to start processing #import,
  40. #include and #include_next lines.
  41. This method will be called when a #if, #ifdef, #ifndef or #elif
  42. evaluates True, or when we reach the #else in a #if, #ifdef,
  43. #ifndef or #elif block where a condition already evaluated
  44. False.
  45. """
  46. d = self.dispatch_table
  47. p = self.stack[-1] if self.stack else self.default_table
  48. for k in ('import', 'include', 'include_next', 'define'):
  49. d[k] = p[k]
  50. def stop_handling_includes(self, t=None):
  51. """
  52. Causes the PreProcessor object to stop processing #import,
  53. #include and #include_next lines.
  54. This method will be called when a #if, #ifdef, #ifndef or #elif
  55. evaluates False, or when we reach the #else in a #if, #ifdef,
  56. #ifndef or #elif block where a condition already evaluated True.
  57. """
  58. d = self.dispatch_table
  59. d['import'] = self.do_nothing
  60. d['include'] = self.do_nothing
  61. d['include_next'] = self.do_nothing
  62. d['define'] = self.do_nothing
  63. PatchedPreProcessor = SCons.cpp.PreProcessor
  64. PatchedPreProcessor.start_handling_includes = start_handling_includes
  65. PatchedPreProcessor.stop_handling_includes = stop_handling_includes
  66. class Win32Spawn:
  67. def spawn(self, sh, escape, cmd, args, env):
  68. # deal with the cmd build-in commands which cannot be used in
  69. # subprocess.Popen
  70. if cmd == 'del':
  71. for f in args[1:]:
  72. try:
  73. os.remove(f)
  74. except Exception as e:
  75. print 'Error removing file: %s' % e
  76. return -1
  77. return 0
  78. import subprocess
  79. newargs = string.join(args[1:], ' ')
  80. cmdline = cmd + " " + newargs
  81. # Make sure the env is constructed by strings
  82. _e = dict([(k, str(v)) for k, v in env.items()])
  83. # Windows(tm) CreateProcess does not use the env passed to it to find
  84. # the executables. So we have to modify our own PATH to make Popen
  85. # work.
  86. old_path = os.environ['PATH']
  87. os.environ['PATH'] = _e['PATH']
  88. try:
  89. proc = subprocess.Popen(cmdline, env=_e, shell=False)
  90. except Exception as e:
  91. print 'Error in calling:\n%s' % cmdline
  92. print 'Exception: %s: %s' % (e, os.strerror(e.errno))
  93. return e.errno
  94. finally:
  95. os.environ['PATH'] = old_path
  96. return proc.wait()
  97. def PrepareBuilding(env, root_directory, has_libcpu=False, remove_components = []):
  98. import SCons.cpp
  99. import rtconfig
  100. global BuildOptions
  101. global Projects
  102. global Env
  103. global Rtt_Root
  104. Env = env
  105. Rtt_Root = os.path.abspath(root_directory)
  106. # set RTT_ROOT in ENV
  107. Env['RTT_ROOT'] = Rtt_Root
  108. # set BSP_ROOT in ENV
  109. Env['BSP_ROOT'] = Dir('#').abspath
  110. sys.path = sys.path + [os.path.join(Rtt_Root, 'tools')]
  111. if not os.path.exists(rtconfig.EXEC_PATH):
  112. print "Error: Toolchain path (%s) is not exist, please check 'EXEC_PATH' in path or rtconfig.py." % rtconfig.EXEC_PATH
  113. sys.exit(1)
  114. # add compability with Keil MDK 4.6 which changes the directory of armcc.exe
  115. if rtconfig.PLATFORM == 'armcc':
  116. if not os.path.isfile(os.path.join(rtconfig.EXEC_PATH, 'armcc.exe')):
  117. if rtconfig.EXEC_PATH.find('bin40') > 0:
  118. rtconfig.EXEC_PATH = rtconfig.EXEC_PATH.replace('bin40', 'armcc/bin')
  119. Env['LINKFLAGS']=Env['LINKFLAGS'].replace('RV31', 'armcc')
  120. # reset AR command flags
  121. env['ARCOM'] = '$AR --create $TARGET $SOURCES'
  122. env['LIBPREFIX'] = ''
  123. env['LIBSUFFIX'] = '.lib'
  124. env['LIBLINKPREFIX'] = ''
  125. env['LIBLINKSUFFIX'] = '.lib'
  126. env['LIBDIRPREFIX'] = '--userlibpath '
  127. # patch for win32 spawn
  128. if env['PLATFORM'] == 'win32':
  129. win32_spawn = Win32Spawn()
  130. win32_spawn.env = env
  131. env['SPAWN'] = win32_spawn.spawn
  132. if env['PLATFORM'] == 'win32':
  133. os.environ['PATH'] = rtconfig.EXEC_PATH + ";" + os.environ['PATH']
  134. else:
  135. os.environ['PATH'] = rtconfig.EXEC_PATH + ":" + os.environ['PATH']
  136. # add program path
  137. env.PrependENVPath('PATH', rtconfig.EXEC_PATH)
  138. # add rtconfig.h path
  139. env.Append(CPPPATH = [str(Dir('#').abspath)])
  140. # add library build action
  141. act = SCons.Action.Action(BuildLibInstallAction, 'Install compiled library... $TARGET')
  142. bld = Builder(action = act)
  143. Env.Append(BUILDERS = {'BuildLib': bld})
  144. # parse rtconfig.h to get used component
  145. PreProcessor = PatchedPreProcessor()
  146. f = file('rtconfig.h', 'r')
  147. contents = f.read()
  148. f.close()
  149. PreProcessor.process_contents(contents)
  150. BuildOptions = PreProcessor.cpp_namespace
  151. if rtconfig.PLATFORM == 'gcc':
  152. contents = ''
  153. if not os.path.isfile('cconfig.h'):
  154. import gcc
  155. gcc.GenerateGCCConfig(rtconfig)
  156. # try again
  157. if os.path.isfile('cconfig.h'):
  158. f = file('cconfig.h', 'r')
  159. if f:
  160. contents = f.read()
  161. f.close();
  162. prep = PatchedPreProcessor()
  163. prep.process_contents(contents)
  164. options = prep.cpp_namespace
  165. BuildOptions.update(options)
  166. # add HAVE_CCONFIG_H definition
  167. env.AppendUnique(CPPDEFINES = ['HAVE_CCONFIG_H'])
  168. if str(env['LINKFLAGS']).find('nano.specs') != -1:
  169. env.AppendUnique(CPPDEFINES = ['_REENT_SMALL'])
  170. # add copy option
  171. AddOption('--copy',
  172. dest='copy',
  173. action='store_true',
  174. default=False,
  175. help='copy rt-thread directory to local.')
  176. AddOption('--copy-header',
  177. dest='copy-header',
  178. action='store_true',
  179. default=False,
  180. help='copy header of rt-thread directory to local.')
  181. AddOption('--dist',
  182. dest = 'make-dist',
  183. action = 'store_true',
  184. default=False,
  185. help = 'make distribution')
  186. AddOption('--cscope',
  187. dest='cscope',
  188. action='store_true',
  189. default=False,
  190. help='Build Cscope cross reference database. Requires cscope installed.')
  191. AddOption('--clang-analyzer',
  192. dest='clang-analyzer',
  193. action='store_true',
  194. default=False,
  195. help='Perform static analyze with Clang-analyzer. '+\
  196. 'Requires Clang installed.\n'+\
  197. 'It is recommended to use with scan-build like this:\n'+\
  198. '`scan-build scons --clang-analyzer`\n'+\
  199. 'If things goes well, scan-build will instruct you to invoke scan-view.')
  200. if GetOption('clang-analyzer'):
  201. # perform what scan-build does
  202. env.Replace(
  203. CC = 'ccc-analyzer',
  204. CXX = 'c++-analyzer',
  205. # skip as and link
  206. LINK = 'true',
  207. AS = 'true',)
  208. env["ENV"].update(x for x in os.environ.items() if x[0].startswith("CCC_"))
  209. # only check, don't compile. ccc-analyzer use CCC_CC as the CC.
  210. # fsyntax-only will give us some additional warning messages
  211. env['ENV']['CCC_CC'] = 'clang'
  212. env.Append(CFLAGS=['-fsyntax-only', '-Wall', '-Wno-invalid-source-encoding'])
  213. env['ENV']['CCC_CXX'] = 'clang++'
  214. env.Append(CXXFLAGS=['-fsyntax-only', '-Wall', '-Wno-invalid-source-encoding'])
  215. # remove the POST_ACTION as it will cause meaningless errors(file not
  216. # found or something like that).
  217. rtconfig.POST_ACTION = ''
  218. # add build library option
  219. AddOption('--buildlib',
  220. dest='buildlib',
  221. type='string',
  222. help='building library of a component')
  223. AddOption('--cleanlib',
  224. dest='cleanlib',
  225. action='store_true',
  226. default=False,
  227. help='clean up the library by --buildlib')
  228. # add target option
  229. AddOption('--target',
  230. dest='target',
  231. type='string',
  232. help='set target project: mdk/mdk4/mdk5/iar/vs/vsc/ua')
  233. #{target_name:(CROSS_TOOL, PLATFORM)}
  234. tgt_dict = {'mdk':('keil', 'armcc'),
  235. 'mdk4':('keil', 'armcc'),
  236. 'mdk5':('keil', 'armcc'),
  237. 'iar':('iar', 'iar'),
  238. 'vs':('msvc', 'cl'),
  239. 'vs2012':('msvc', 'cl'),
  240. 'vsc' : ('gcc', 'gcc'),
  241. 'cb':('keil', 'armcc'),
  242. 'ua':('gcc', 'gcc')}
  243. tgt_name = GetOption('target')
  244. if tgt_name:
  245. # --target will change the toolchain settings which clang-analyzer is
  246. # depend on
  247. if GetOption('clang-analyzer'):
  248. print '--clang-analyzer cannot be used with --target'
  249. sys.exit(1)
  250. SetOption('no_exec', 1)
  251. try:
  252. rtconfig.CROSS_TOOL, rtconfig.PLATFORM = tgt_dict[tgt_name]
  253. except KeyError:
  254. print 'Unknow target: %s. Avaible targets: %s' % \
  255. (tgt_name, ', '.join(tgt_dict.keys()))
  256. sys.exit(1)
  257. elif (GetDepend('RT_USING_NEWLIB') == False and GetDepend('RT_USING_NOLIBC') == False) \
  258. and rtconfig.PLATFORM == 'gcc':
  259. AddDepend('RT_USING_MINILIBC')
  260. AddOption('--genconfig',
  261. dest = 'genconfig',
  262. action = 'store_true',
  263. default = False,
  264. help = 'Generate .config from rtconfig.h')
  265. if GetOption('genconfig'):
  266. from genconf import genconfig
  267. genconfig()
  268. exit(0)
  269. if env['PLATFORM'] != 'win32':
  270. AddOption('--menuconfig',
  271. dest = 'menuconfig',
  272. action = 'store_true',
  273. default = False,
  274. help = 'make menuconfig for RT-Thread BSP')
  275. if GetOption('menuconfig'):
  276. from menuconfig import menuconfig
  277. menuconfig(Rtt_Root)
  278. exit(0)
  279. AddOption('--useconfig',
  280. dest = 'useconfig',
  281. type='string',
  282. help = 'make rtconfig.h from config file.')
  283. configfn = GetOption('useconfig')
  284. if configfn:
  285. from menuconfig import mk_rtconfig
  286. mk_rtconfig(configfn)
  287. exit(0)
  288. # add comstr option
  289. AddOption('--verbose',
  290. dest='verbose',
  291. action='store_true',
  292. default=False,
  293. help='print verbose information during build')
  294. if not GetOption('verbose'):
  295. # override the default verbose command string
  296. env.Replace(
  297. ARCOMSTR = 'AR $TARGET',
  298. ASCOMSTR = 'AS $TARGET',
  299. ASPPCOMSTR = 'AS $TARGET',
  300. CCCOMSTR = 'CC $TARGET',
  301. CXXCOMSTR = 'CXX $TARGET',
  302. LINKCOMSTR = 'LINK $TARGET'
  303. )
  304. # fix the linker for C++
  305. if GetDepend('RT_USING_CPLUSPLUS'):
  306. if env['LINK'].find('gcc') != -1:
  307. env['LINK'] = env['LINK'].replace('gcc', 'g++')
  308. # we need to seperate the variant_dir for BSPs and the kernels. BSPs could
  309. # have their own components etc. If they point to the same folder, SCons
  310. # would find the wrong source code to compile.
  311. bsp_vdir = 'build'
  312. kernel_vdir = 'build/kernel'
  313. # board build script
  314. objs = SConscript('SConscript', variant_dir=bsp_vdir, duplicate=0)
  315. # include kernel
  316. objs.extend(SConscript(Rtt_Root + '/src/SConscript', variant_dir=kernel_vdir + '/src', duplicate=0))
  317. # include libcpu
  318. if not has_libcpu:
  319. objs.extend(SConscript(Rtt_Root + '/libcpu/SConscript',
  320. variant_dir=kernel_vdir + '/libcpu', duplicate=0))
  321. # include components
  322. objs.extend(SConscript(Rtt_Root + '/components/SConscript',
  323. variant_dir=kernel_vdir + '/components',
  324. duplicate=0,
  325. exports='remove_components'))
  326. return objs
  327. def PrepareModuleBuilding(env, root_directory, bsp_directory):
  328. import rtconfig
  329. global BuildOptions
  330. global Env
  331. global Rtt_Root
  332. # patch for win32 spawn
  333. if env['PLATFORM'] == 'win32':
  334. win32_spawn = Win32Spawn()
  335. win32_spawn.env = env
  336. env['SPAWN'] = win32_spawn.spawn
  337. Env = env
  338. Rtt_Root = root_directory
  339. # parse bsp rtconfig.h to get used component
  340. PreProcessor = PatchedPreProcessor()
  341. f = file(bsp_directory + '/rtconfig.h', 'r')
  342. contents = f.read()
  343. f.close()
  344. PreProcessor.process_contents(contents)
  345. BuildOptions = PreProcessor.cpp_namespace
  346. # add build/clean library option for library checking
  347. AddOption('--buildlib',
  348. dest='buildlib',
  349. type='string',
  350. help='building library of a component')
  351. AddOption('--cleanlib',
  352. dest='cleanlib',
  353. action='store_true',
  354. default=False,
  355. help='clean up the library by --buildlib')
  356. # add program path
  357. env.PrependENVPath('PATH', rtconfig.EXEC_PATH)
  358. def GetConfigValue(name):
  359. assert type(name) == str, 'GetConfigValue: only string parameter is valid'
  360. try:
  361. return BuildOptions[name]
  362. except:
  363. return ''
  364. def GetDepend(depend):
  365. building = True
  366. if type(depend) == type('str'):
  367. if not BuildOptions.has_key(depend) or BuildOptions[depend] == 0:
  368. building = False
  369. elif BuildOptions[depend] != '':
  370. return BuildOptions[depend]
  371. return building
  372. # for list type depend
  373. for item in depend:
  374. if item != '':
  375. if not BuildOptions.has_key(item) or BuildOptions[item] == 0:
  376. building = False
  377. return building
  378. def LocalOptions(config_filename):
  379. from SCons.Script import SCons
  380. # parse wiced_config.h to get used component
  381. PreProcessor = SCons.cpp.PreProcessor()
  382. f = file(config_filename, 'r')
  383. contents = f.read()
  384. f.close()
  385. PreProcessor.process_contents(contents)
  386. local_options = PreProcessor.cpp_namespace
  387. return local_options
  388. def GetLocalDepend(options, depend):
  389. building = True
  390. if type(depend) == type('str'):
  391. if not options.has_key(depend) or options[depend] == 0:
  392. building = False
  393. elif options[depend] != '':
  394. return options[depend]
  395. return building
  396. # for list type depend
  397. for item in depend:
  398. if item != '':
  399. if not options.has_key(item) or options[item] == 0:
  400. building = False
  401. return building
  402. def AddDepend(option):
  403. BuildOptions[option] = 1
  404. def MergeGroup(src_group, group):
  405. src_group['src'] = src_group['src'] + group['src']
  406. if group.has_key('CCFLAGS'):
  407. if src_group.has_key('CCFLAGS'):
  408. src_group['CCFLAGS'] = src_group['CCFLAGS'] + group['CCFLAGS']
  409. else:
  410. src_group['CCFLAGS'] = group['CCFLAGS']
  411. if group.has_key('CPPPATH'):
  412. if src_group.has_key('CPPPATH'):
  413. src_group['CPPPATH'] = src_group['CPPPATH'] + group['CPPPATH']
  414. else:
  415. src_group['CPPPATH'] = group['CPPPATH']
  416. if group.has_key('CPPDEFINES'):
  417. if src_group.has_key('CPPDEFINES'):
  418. src_group['CPPDEFINES'] = src_group['CPPDEFINES'] + group['CPPDEFINES']
  419. else:
  420. src_group['CPPDEFINES'] = group['CPPDEFINES']
  421. if group.has_key('ASFLAGS'):
  422. if src_group.has_key('ASFLAGS'):
  423. src_group['ASFLAGS'] = src_group['ASFLAGS'] + group['ASFLAGS']
  424. else:
  425. src_group['ASFLAGS'] = group['ASFLAGS']
  426. # for local CCFLAGS/CPPPATH/CPPDEFINES
  427. if group.has_key('LOCAL_CCFLAGS'):
  428. if src_group.has_key('LOCAL_CCFLAGS'):
  429. src_group['LOCAL_CCFLAGS'] = src_group['LOCAL_CCFLAGS'] + group['LOCAL_CCFLAGS']
  430. else:
  431. src_group['LOCAL_CCFLAGS'] = group['LOCAL_CCFLAGS']
  432. if group.has_key('LOCAL_CPPPATH'):
  433. if src_group.has_key('LOCAL_CPPPATH'):
  434. src_group['LOCAL_CPPPATH'] = src_group['LOCAL_CPPPATH'] + group['LOCAL_CPPPATH']
  435. else:
  436. src_group['LOCAL_CPPPATH'] = group['LOCAL_CPPPATH']
  437. if group.has_key('LOCAL_CPPDEFINES'):
  438. if src_group.has_key('LOCAL_CPPDEFINES'):
  439. src_group['LOCAL_CPPDEFINES'] = src_group['LOCAL_CPPDEFINES'] + group['LOCAL_CPPDEFINES']
  440. else:
  441. src_group['LOCAL_CPPDEFINES'] = group['LOCAL_CPPDEFINES']
  442. if group.has_key('LINKFLAGS'):
  443. if src_group.has_key('LINKFLAGS'):
  444. src_group['LINKFLAGS'] = src_group['LINKFLAGS'] + group['LINKFLAGS']
  445. else:
  446. src_group['LINKFLAGS'] = group['LINKFLAGS']
  447. if group.has_key('LIBS'):
  448. if src_group.has_key('LIBS'):
  449. src_group['LIBS'] = src_group['LIBS'] + group['LIBS']
  450. else:
  451. src_group['LIBS'] = group['LIBS']
  452. if group.has_key('LIBPATH'):
  453. if src_group.has_key('LIBPATH'):
  454. src_group['LIBPATH'] = src_group['LIBPATH'] + group['LIBPATH']
  455. else:
  456. src_group['LIBPATH'] = group['LIBPATH']
  457. if group.has_key('LOCAL_ASFLAGS'):
  458. if src_group.has_key('LOCAL_ASFLAGS'):
  459. src_group['LOCAL_ASFLAGS'] = src_group['LOCAL_ASFLAGS'] + group['LOCAL_ASFLAGS']
  460. else:
  461. src_group['LOCAL_ASFLAGS'] = group['LOCAL_ASFLAGS']
  462. def DefineGroup(name, src, depend, **parameters):
  463. global Env
  464. if not GetDepend(depend):
  465. return []
  466. # find exist group and get path of group
  467. group_path = ''
  468. for g in Projects:
  469. if g['name'] == name:
  470. group_path = g['path']
  471. if group_path == '':
  472. group_path = GetCurrentDir()
  473. group = parameters
  474. group['name'] = name
  475. group['path'] = group_path
  476. if type(src) == type([]):
  477. group['src'] = File(src)
  478. else:
  479. group['src'] = src
  480. if group.has_key('CCFLAGS'):
  481. Env.AppendUnique(CCFLAGS = group['CCFLAGS'])
  482. if group.has_key('CPPPATH'):
  483. Env.AppendUnique(CPPPATH = group['CPPPATH'])
  484. if group.has_key('CPPDEFINES'):
  485. Env.AppendUnique(CPPDEFINES = group['CPPDEFINES'])
  486. if group.has_key('LINKFLAGS'):
  487. Env.AppendUnique(LINKFLAGS = group['LINKFLAGS'])
  488. if group.has_key('ASFLAGS'):
  489. Env.AppendUnique(ASFLAGS = group['ASFLAGS'])
  490. # check whether to clean up library
  491. if GetOption('cleanlib') and os.path.exists(os.path.join(group['path'], GroupLibFullName(name, Env))):
  492. if group['src'] != []:
  493. print 'Remove library:', GroupLibFullName(name, Env)
  494. fn = os.path.join(group['path'], GroupLibFullName(name, Env))
  495. if os.path.exists(fn):
  496. os.unlink(fn)
  497. # check whether exist group library
  498. if not GetOption('buildlib') and os.path.exists(os.path.join(group['path'], GroupLibFullName(name, Env))):
  499. group['src'] = []
  500. if group.has_key('LIBS'): group['LIBS'] = group['LIBS'] + [GroupLibName(name, Env)]
  501. else : group['LIBS'] = [GroupLibName(name, Env)]
  502. if group.has_key('LIBPATH'): group['LIBPATH'] = group['LIBPATH'] + [GetCurrentDir()]
  503. else : group['LIBPATH'] = [GetCurrentDir()]
  504. if group.has_key('LIBS'):
  505. Env.AppendUnique(LIBS = group['LIBS'])
  506. if group.has_key('LIBPATH'):
  507. Env.AppendUnique(LIBPATH = group['LIBPATH'])
  508. # check whether to build group library
  509. if group.has_key('LIBRARY'):
  510. objs = Env.Library(name, group['src'])
  511. else:
  512. # only add source
  513. objs = group['src']
  514. # merge group
  515. for g in Projects:
  516. if g['name'] == name:
  517. # merge to this group
  518. MergeGroup(g, group)
  519. return objs
  520. # add a new group
  521. Projects.append(group)
  522. return objs
  523. def GetCurrentDir():
  524. conscript = File('SConscript')
  525. fn = conscript.rfile()
  526. name = fn.name
  527. path = os.path.dirname(fn.abspath)
  528. return path
  529. PREBUILDING = []
  530. def RegisterPreBuildingAction(act):
  531. global PREBUILDING
  532. assert callable(act), 'Could only register callable objects. %s received' % repr(act)
  533. PREBUILDING.append(act)
  534. def PreBuilding():
  535. global PREBUILDING
  536. for a in PREBUILDING:
  537. a()
  538. def GroupLibName(name, env):
  539. import rtconfig
  540. if rtconfig.PLATFORM == 'armcc':
  541. return name + '_rvds'
  542. elif rtconfig.PLATFORM == 'gcc':
  543. return name + '_gcc'
  544. return name
  545. def GroupLibFullName(name, env):
  546. return env['LIBPREFIX'] + GroupLibName(name, env) + env['LIBSUFFIX']
  547. def BuildLibInstallAction(target, source, env):
  548. lib_name = GetOption('buildlib')
  549. for Group in Projects:
  550. if Group['name'] == lib_name:
  551. lib_name = GroupLibFullName(Group['name'], env)
  552. dst_name = os.path.join(Group['path'], lib_name)
  553. print 'Copy %s => %s' % (lib_name, dst_name)
  554. do_copy_file(lib_name, dst_name)
  555. break
  556. def DoBuilding(target, objects):
  557. # merge all objects into one list
  558. def one_list(l):
  559. lst = []
  560. for item in l:
  561. if type(item) == type([]):
  562. lst += one_list(item)
  563. else:
  564. lst.append(item)
  565. return lst
  566. # handle local group
  567. def local_group(group, objects):
  568. if group.has_key('LOCAL_CCFLAGS') or group.has_key('LOCAL_CPPPATH') or group.has_key('LOCAL_CPPDEFINES') or group.has_key('LOCAL_ASFLAGS'):
  569. CCFLAGS = Env.get('CCFLAGS', '') + group.get('LOCAL_CCFLAGS', '')
  570. CPPPATH = Env.get('CPPPATH', ['']) + group.get('LOCAL_CPPPATH', [''])
  571. CPPDEFINES = Env.get('CPPDEFINES', ['']) + group.get('LOCAL_CPPDEFINES', [''])
  572. ASFLAGS = Env.get('ASFLAGS', '') + group.get('LOCAL_ASFLAGS', '')
  573. for source in group['src']:
  574. objects.append(Env.Object(source, CCFLAGS = CCFLAGS, ASFLAGS = ASFLAGS,
  575. CPPPATH = CPPPATH, CPPDEFINES = CPPDEFINES))
  576. return True
  577. return False
  578. objects = one_list(objects)
  579. program = None
  580. # check whether special buildlib option
  581. lib_name = GetOption('buildlib')
  582. if lib_name:
  583. objects = [] # remove all of objects
  584. # build library with special component
  585. for Group in Projects:
  586. if Group['name'] == lib_name:
  587. lib_name = GroupLibName(Group['name'], Env)
  588. if not local_group(Group, objects):
  589. objects = Env.Object(Group['src'])
  590. program = Env.Library(lib_name, objects)
  591. # add library copy action
  592. Env.BuildLib(lib_name, program)
  593. break
  594. else:
  595. # remove source files with local flags setting
  596. for group in Projects:
  597. if group.has_key('LOCAL_CCFLAGS') or group.has_key('LOCAL_CPPPATH') or group.has_key('LOCAL_CPPDEFINES'):
  598. for source in group['src']:
  599. for obj in objects:
  600. if source.abspath == obj.abspath or (len(obj.sources) > 0 and source.abspath == obj.sources[0].abspath):
  601. objects.remove(obj)
  602. # re-add the source files to the objects
  603. for group in Projects:
  604. local_group(group, objects)
  605. program = Env.Program(target, objects)
  606. EndBuilding(target, program)
  607. def EndBuilding(target, program = None):
  608. import rtconfig
  609. Env['target'] = program
  610. Env['project'] = Projects
  611. Env.AddPostAction(target, rtconfig.POST_ACTION)
  612. # Add addition clean files
  613. Clean(target, 'cconfig.h')
  614. Clean(target, 'rtua.py')
  615. Clean(target, 'rtua.pyc')
  616. if GetOption('target') == 'mdk':
  617. from keil import MDKProject
  618. from keil import MDK4Project
  619. from keil import MDK5Project
  620. template = os.path.isfile('template.Uv2')
  621. if template:
  622. MDKProject('project.Uv2', Projects)
  623. else:
  624. template = os.path.isfile('template.uvproj')
  625. if template:
  626. MDK4Project('project.uvproj', Projects)
  627. else:
  628. template = os.path.isfile('template.uvprojx')
  629. if template:
  630. MDK5Project('project.uvprojx', Projects)
  631. else:
  632. print 'No template project file found.'
  633. if GetOption('target') == 'mdk4':
  634. from keil import MDK4Project
  635. MDK4Project('project.uvproj', Projects)
  636. if GetOption('target') == 'mdk5':
  637. from keil import MDK5Project
  638. MDK5Project('project.uvprojx', Projects)
  639. if GetOption('target') == 'iar':
  640. from iar import IARProject
  641. IARProject('project.ewp', Projects)
  642. if GetOption('target') == 'vs':
  643. from vs import VSProject
  644. VSProject('project.vcproj', Projects, program)
  645. if GetOption('target') == 'vs2012':
  646. from vs2012 import VS2012Project
  647. VS2012Project('project.vcxproj', Projects, program)
  648. if GetOption('target') == 'cb':
  649. from codeblocks import CBProject
  650. CBProject('project.cbp', Projects, program)
  651. if GetOption('target') == 'ua':
  652. from ua import PrepareUA
  653. PrepareUA(Projects, Rtt_Root, str(Dir('#')))
  654. if GetOption('target') == 'vsc':
  655. from vsc import GenerateVSCode
  656. GenerateVSCode(Env)
  657. BSP_ROOT = Dir('#').abspath
  658. if GetOption('copy') and program != None:
  659. from mkdist import MakeCopy
  660. MakeCopy(program, BSP_ROOT, Rtt_Root, Env)
  661. exit(0)
  662. if GetOption('copy-header') and program != None:
  663. from mkdist import MakeCopyHeader
  664. MakeCopyHeader(program, BSP_ROOT, Rtt_Root, Env)
  665. exit(0)
  666. if GetOption('make-dist') and program != None:
  667. from mkdist import MkDist
  668. MkDist(program, BSP_ROOT, Rtt_Root, Env)
  669. exit(0)
  670. if GetOption('cscope'):
  671. from cscope import CscopeDatabase
  672. CscopeDatabase(Projects)
  673. def SrcRemove(src, remove):
  674. if not src:
  675. return
  676. for item in src:
  677. if type(item) == type('str'):
  678. item_str = item
  679. else:
  680. item_str = item.rstr()
  681. if os.path.isabs(item_str):
  682. item_str = os.path.relpath(item_str, GetCurrentDir())
  683. if type(remove) == type('str'):
  684. if item_str == remove:
  685. src.remove(item)
  686. else:
  687. for remove_item in remove:
  688. if item_str == str(remove_item):
  689. src.remove(item)
  690. def GetVersion():
  691. import SCons.cpp
  692. import string
  693. rtdef = os.path.join(Rtt_Root, 'include', 'rtdef.h')
  694. # parse rtdef.h to get RT-Thread version
  695. prepcessor = PatchedPreProcessor()
  696. f = file(rtdef, 'r')
  697. contents = f.read()
  698. f.close()
  699. prepcessor.process_contents(contents)
  700. def_ns = prepcessor.cpp_namespace
  701. version = int(filter(lambda ch: ch in '0123456789.', def_ns['RT_VERSION']))
  702. subversion = int(filter(lambda ch: ch in '0123456789.', def_ns['RT_SUBVERSION']))
  703. if def_ns.has_key('RT_REVISION'):
  704. revision = int(filter(lambda ch: ch in '0123456789.', def_ns['RT_REVISION']))
  705. return '%d.%d.%d' % (version, subversion, revision)
  706. return '0.%d.%d' % (version, subversion)
  707. def GlobSubDir(sub_dir, ext_name):
  708. import os
  709. import glob
  710. def glob_source(sub_dir, ext_name):
  711. list = os.listdir(sub_dir)
  712. src = glob.glob(os.path.join(sub_dir, ext_name))
  713. for item in list:
  714. full_subdir = os.path.join(sub_dir, item)
  715. if os.path.isdir(full_subdir):
  716. src += glob_source(full_subdir, ext_name)
  717. return src
  718. dst = []
  719. src = glob_source(sub_dir, ext_name)
  720. for item in src:
  721. dst.append(os.path.relpath(item, sub_dir))
  722. return dst
  723. def PackageSConscript(package):
  724. from package import BuildPackage
  725. return BuildPackage(package)