building.py 30 KB

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