building.py 28 KB

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