building.py 31 KB

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