building.py 31 KB

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