building.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  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/ses')
  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. 'ses' : ('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. utils.ReloadModule(rtconfig)
  211. except KeyError:
  212. print ('Unknow target: '+ tgt_name+'. Avaible targets: ' +', '.join(tgt_dict.keys()))
  213. sys.exit(1)
  214. elif (GetDepend('RT_USING_NEWLIB') == False and GetDepend('RT_USING_NOLIBC') == False) \
  215. and rtconfig.PLATFORM == 'gcc':
  216. AddDepend('RT_USING_MINILIBC')
  217. # auto change the 'RTT_EXEC_PATH' when 'rtconfig.EXEC_PATH' get failed
  218. if not os.path.exists(rtconfig.EXEC_PATH):
  219. if 'RTT_EXEC_PATH' in os.environ:
  220. # del the 'RTT_EXEC_PATH' and using the 'EXEC_PATH' setting on rtconfig.py
  221. del os.environ['RTT_EXEC_PATH']
  222. utils.ReloadModule(rtconfig)
  223. # add compability with Keil MDK 4.6 which changes the directory of armcc.exe
  224. if rtconfig.PLATFORM == 'armcc':
  225. if not os.path.isfile(os.path.join(rtconfig.EXEC_PATH, 'armcc.exe')):
  226. if rtconfig.EXEC_PATH.find('bin40') > 0:
  227. rtconfig.EXEC_PATH = rtconfig.EXEC_PATH.replace('bin40', 'armcc/bin')
  228. Env['LINKFLAGS'] = Env['LINKFLAGS'].replace('RV31', 'armcc')
  229. # reset AR command flags
  230. env['ARCOM'] = '$AR --create $TARGET $SOURCES'
  231. env['LIBPREFIX'] = ''
  232. env['LIBSUFFIX'] = '.lib'
  233. env['LIBLINKPREFIX'] = ''
  234. env['LIBLINKSUFFIX'] = '.lib'
  235. env['LIBDIRPREFIX'] = '--userlibpath '
  236. # patch for win32 spawn
  237. if env['PLATFORM'] == 'win32':
  238. win32_spawn = Win32Spawn()
  239. win32_spawn.env = env
  240. env['SPAWN'] = win32_spawn.spawn
  241. if env['PLATFORM'] == 'win32':
  242. os.environ['PATH'] = rtconfig.EXEC_PATH + ";" + os.environ['PATH']
  243. else:
  244. os.environ['PATH'] = rtconfig.EXEC_PATH + ":" + os.environ['PATH']
  245. # add program path
  246. env.PrependENVPath('PATH', rtconfig.EXEC_PATH)
  247. # add rtconfig.h path
  248. env.Append(CPPPATH = [str(Dir('#').abspath)])
  249. # add library build action
  250. act = SCons.Action.Action(BuildLibInstallAction, 'Install compiled library... $TARGET')
  251. bld = Builder(action = act)
  252. Env.Append(BUILDERS = {'BuildLib': bld})
  253. # parse rtconfig.h to get used component
  254. PreProcessor = PatchedPreProcessor()
  255. f = open('rtconfig.h', 'r')
  256. contents = f.read()
  257. f.close()
  258. PreProcessor.process_contents(contents)
  259. BuildOptions = PreProcessor.cpp_namespace
  260. if GetOption('clang-analyzer'):
  261. # perform what scan-build does
  262. env.Replace(
  263. CC = 'ccc-analyzer',
  264. CXX = 'c++-analyzer',
  265. # skip as and link
  266. LINK = 'true',
  267. AS = 'true',)
  268. env["ENV"].update(x for x in os.environ.items() if x[0].startswith("CCC_"))
  269. # only check, don't compile. ccc-analyzer use CCC_CC as the CC.
  270. # fsyntax-only will give us some additional warning messages
  271. env['ENV']['CCC_CC'] = 'clang'
  272. env.Append(CFLAGS=['-fsyntax-only', '-Wall', '-Wno-invalid-source-encoding'])
  273. env['ENV']['CCC_CXX'] = 'clang++'
  274. env.Append(CXXFLAGS=['-fsyntax-only', '-Wall', '-Wno-invalid-source-encoding'])
  275. # remove the POST_ACTION as it will cause meaningless errors(file not
  276. # found or something like that).
  277. rtconfig.POST_ACTION = ''
  278. # generate cconfig.h file
  279. GenCconfigFile(env, BuildOptions)
  280. # auto append '_REENT_SMALL' when using newlib 'nano.specs' option
  281. if rtconfig.PLATFORM == 'gcc' and str(env['LINKFLAGS']).find('nano.specs') != -1:
  282. env.AppendUnique(CPPDEFINES = ['_REENT_SMALL'])
  283. if GetOption('genconfig'):
  284. from genconf import genconfig
  285. genconfig()
  286. exit(0)
  287. if env['PLATFORM'] != 'win32':
  288. AddOption('--menuconfig',
  289. dest = 'menuconfig',
  290. action = 'store_true',
  291. default = False,
  292. help = 'make menuconfig for RT-Thread BSP')
  293. if GetOption('menuconfig'):
  294. from menuconfig import menuconfig
  295. menuconfig(Rtt_Root)
  296. exit(0)
  297. AddOption('--pyconfig',
  298. dest = 'pyconfig',
  299. action = 'store_true',
  300. default = False,
  301. help = 'make menuconfig for RT-Thread BSP')
  302. if GetOption('pyconfig'):
  303. from menuconfig import pyconfig
  304. pyconfig(Rtt_Root)
  305. exit(0)
  306. configfn = GetOption('useconfig')
  307. if configfn:
  308. from menuconfig import mk_rtconfig
  309. mk_rtconfig(configfn)
  310. exit(0)
  311. if not GetOption('verbose'):
  312. # override the default verbose command string
  313. env.Replace(
  314. ARCOMSTR = 'AR $TARGET',
  315. ASCOMSTR = 'AS $TARGET',
  316. ASPPCOMSTR = 'AS $TARGET',
  317. CCCOMSTR = 'CC $TARGET',
  318. CXXCOMSTR = 'CXX $TARGET',
  319. LINKCOMSTR = 'LINK $TARGET'
  320. )
  321. # fix the linker for C++
  322. if GetDepend('RT_USING_CPLUSPLUS'):
  323. if env['LINK'].find('gcc') != -1:
  324. env['LINK'] = env['LINK'].replace('gcc', 'g++')
  325. # we need to seperate the variant_dir for BSPs and the kernels. BSPs could
  326. # have their own components etc. If they point to the same folder, SCons
  327. # would find the wrong source code to compile.
  328. bsp_vdir = 'build'
  329. kernel_vdir = 'build/kernel'
  330. # board build script
  331. objs = SConscript('SConscript', variant_dir=bsp_vdir, duplicate=0)
  332. # include kernel
  333. objs.extend(SConscript(Rtt_Root + '/src/SConscript', variant_dir=kernel_vdir + '/src', duplicate=0))
  334. # include libcpu
  335. if not has_libcpu:
  336. objs.extend(SConscript(Rtt_Root + '/libcpu/SConscript',
  337. variant_dir=kernel_vdir + '/libcpu', duplicate=0))
  338. # include components
  339. objs.extend(SConscript(Rtt_Root + '/components/SConscript',
  340. variant_dir=kernel_vdir + '/components',
  341. duplicate=0,
  342. exports='remove_components'))
  343. return objs
  344. def PrepareModuleBuilding(env, root_directory, bsp_directory):
  345. import rtconfig
  346. global BuildOptions
  347. global Env
  348. global Rtt_Root
  349. # patch for win32 spawn
  350. if env['PLATFORM'] == 'win32':
  351. win32_spawn = Win32Spawn()
  352. win32_spawn.env = env
  353. env['SPAWN'] = win32_spawn.spawn
  354. Env = env
  355. Rtt_Root = root_directory
  356. # parse bsp rtconfig.h to get used component
  357. PreProcessor = PatchedPreProcessor()
  358. f = open(bsp_directory + '/rtconfig.h', 'r')
  359. contents = f.read()
  360. f.close()
  361. PreProcessor.process_contents(contents)
  362. BuildOptions = PreProcessor.cpp_namespace
  363. # add build/clean library option for library checking
  364. AddOption('--buildlib',
  365. dest='buildlib',
  366. type='string',
  367. help='building library of a component')
  368. AddOption('--cleanlib',
  369. dest='cleanlib',
  370. action='store_true',
  371. default=False,
  372. help='clean up the library by --buildlib')
  373. # add program path
  374. env.PrependENVPath('PATH', rtconfig.EXEC_PATH)
  375. def GetConfigValue(name):
  376. assert type(name) == str, 'GetConfigValue: only string parameter is valid'
  377. try:
  378. return BuildOptions[name]
  379. except:
  380. return ''
  381. def GetDepend(depend):
  382. building = True
  383. if type(depend) == type('str'):
  384. if not depend in BuildOptions or BuildOptions[depend] == 0:
  385. building = False
  386. elif BuildOptions[depend] != '':
  387. return BuildOptions[depend]
  388. return building
  389. # for list type depend
  390. for item in depend:
  391. if item != '':
  392. if not item in BuildOptions or BuildOptions[item] == 0:
  393. building = False
  394. return building
  395. def LocalOptions(config_filename):
  396. from SCons.Script import SCons
  397. # parse wiced_config.h to get used component
  398. PreProcessor = SCons.cpp.PreProcessor()
  399. f = open(config_filename, 'r')
  400. contents = f.read()
  401. f.close()
  402. PreProcessor.process_contents(contents)
  403. local_options = PreProcessor.cpp_namespace
  404. return local_options
  405. def GetLocalDepend(options, depend):
  406. building = True
  407. if type(depend) == type('str'):
  408. if not depend in options or options[depend] == 0:
  409. building = False
  410. elif options[depend] != '':
  411. return options[depend]
  412. return building
  413. # for list type depend
  414. for item in depend:
  415. if item != '':
  416. if not item in options or options[item] == 0:
  417. building = False
  418. return building
  419. def AddDepend(option):
  420. BuildOptions[option] = 1
  421. def MergeGroup(src_group, group):
  422. src_group['src'] = src_group['src'] + group['src']
  423. if 'CCFLAGS' in group:
  424. if 'CCFLAGS' in src_group:
  425. src_group['CCFLAGS'] = src_group['CCFLAGS'] + group['CCFLAGS']
  426. else:
  427. src_group['CCFLAGS'] = group['CCFLAGS']
  428. if 'CPPPATH' in group:
  429. if 'CPPPATH' in src_group:
  430. src_group['CPPPATH'] = src_group['CPPPATH'] + group['CPPPATH']
  431. else:
  432. src_group['CPPPATH'] = group['CPPPATH']
  433. if 'CPPDEFINES' in group:
  434. if 'CPPDEFINES' in src_group:
  435. src_group['CPPDEFINES'] = src_group['CPPDEFINES'] + group['CPPDEFINES']
  436. else:
  437. src_group['CPPDEFINES'] = group['CPPDEFINES']
  438. if 'ASFLAGS' in group:
  439. if 'ASFLAGS' in src_group:
  440. src_group['ASFLAGS'] = src_group['ASFLAGS'] + group['ASFLAGS']
  441. else:
  442. src_group['ASFLAGS'] = group['ASFLAGS']
  443. # for local CCFLAGS/CPPPATH/CPPDEFINES
  444. if 'LOCAL_CCFLAGS' in group:
  445. if 'LOCAL_CCFLAGS' in src_group:
  446. src_group['LOCAL_CCFLAGS'] = src_group['LOCAL_CCFLAGS'] + group['LOCAL_CCFLAGS']
  447. else:
  448. src_group['LOCAL_CCFLAGS'] = group['LOCAL_CCFLAGS']
  449. if 'LOCAL_CPPPATH' in group:
  450. if 'LOCAL_CPPPATH' in src_group:
  451. src_group['LOCAL_CPPPATH'] = src_group['LOCAL_CPPPATH'] + group['LOCAL_CPPPATH']
  452. else:
  453. src_group['LOCAL_CPPPATH'] = group['LOCAL_CPPPATH']
  454. if 'LOCAL_CPPDEFINES' in group:
  455. if 'LOCAL_CPPDEFINES' in src_group:
  456. src_group['LOCAL_CPPDEFINES'] = src_group['LOCAL_CPPDEFINES'] + group['LOCAL_CPPDEFINES']
  457. else:
  458. src_group['LOCAL_CPPDEFINES'] = group['LOCAL_CPPDEFINES']
  459. if 'LINKFLAGS' in group:
  460. if 'LINKFLAGS' in src_group:
  461. src_group['LINKFLAGS'] = src_group['LINKFLAGS'] + group['LINKFLAGS']
  462. else:
  463. src_group['LINKFLAGS'] = group['LINKFLAGS']
  464. if 'LIBS' in group:
  465. if 'LIBS' in src_group:
  466. src_group['LIBS'] = src_group['LIBS'] + group['LIBS']
  467. else:
  468. src_group['LIBS'] = group['LIBS']
  469. if 'LIBPATH' in group:
  470. if 'LIBPATH' in src_group:
  471. src_group['LIBPATH'] = src_group['LIBPATH'] + group['LIBPATH']
  472. else:
  473. src_group['LIBPATH'] = group['LIBPATH']
  474. if 'LOCAL_ASFLAGS' in group:
  475. if 'LOCAL_ASFLAGS' in src_group:
  476. src_group['LOCAL_ASFLAGS'] = src_group['LOCAL_ASFLAGS'] + group['LOCAL_ASFLAGS']
  477. else:
  478. src_group['LOCAL_ASFLAGS'] = group['LOCAL_ASFLAGS']
  479. def DefineGroup(name, src, depend, **parameters):
  480. global Env
  481. if not GetDepend(depend):
  482. return []
  483. # find exist group and get path of group
  484. group_path = ''
  485. for g in Projects:
  486. if g['name'] == name:
  487. group_path = g['path']
  488. if group_path == '':
  489. group_path = GetCurrentDir()
  490. group = parameters
  491. group['name'] = name
  492. group['path'] = group_path
  493. if type(src) == type([]):
  494. group['src'] = File(src)
  495. else:
  496. group['src'] = src
  497. if 'CCFLAGS' in group:
  498. Env.AppendUnique(CCFLAGS = group['CCFLAGS'])
  499. if 'CPPPATH' in group:
  500. paths = []
  501. for item in group['CPPPATH']:
  502. paths.append(os.path.abspath(item))
  503. group['CPPPATH'] = paths
  504. Env.AppendUnique(CPPPATH = group['CPPPATH'])
  505. if 'CPPDEFINES' in group:
  506. Env.AppendUnique(CPPDEFINES = group['CPPDEFINES'])
  507. if 'LINKFLAGS' in group:
  508. Env.AppendUnique(LINKFLAGS = group['LINKFLAGS'])
  509. if 'ASFLAGS' in group:
  510. Env.AppendUnique(ASFLAGS = group['ASFLAGS'])
  511. if 'LOCAL_CPPPATH' in group:
  512. paths = []
  513. for item in group['LOCAL_CPPPATH']:
  514. paths.append(os.path.abspath(item))
  515. group['LOCAL_CPPPATH'] = paths
  516. import rtconfig
  517. if rtconfig.PLATFORM == 'gcc':
  518. if 'CCFLAGS' in group:
  519. group['CCFLAGS'] = utils.GCCC99Patch(group['CCFLAGS'])
  520. if 'LOCAL_CCFLAGS' in group:
  521. group['LOCAL_CCFLAGS'] = utils.GCCC99Patch(group['LOCAL_CCFLAGS'])
  522. # check whether to clean up library
  523. if GetOption('cleanlib') and os.path.exists(os.path.join(group['path'], GroupLibFullName(name, Env))):
  524. if group['src'] != []:
  525. print ('Remove library:'+ GroupLibFullName(name, Env))
  526. fn = os.path.join(group['path'], GroupLibFullName(name, Env))
  527. if os.path.exists(fn):
  528. os.unlink(fn)
  529. if 'LIBS' in group:
  530. Env.AppendUnique(LIBS = group['LIBS'])
  531. if 'LIBPATH' in group:
  532. Env.AppendUnique(LIBPATH = group['LIBPATH'])
  533. # check whether to build group library
  534. if 'LIBRARY' in group:
  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 '+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 'LOCAL_CCFLAGS' in group or 'LOCAL_CPPPATH' in group or 'LOCAL_CPPDEFINES' in group or 'LOCAL_ASFLAGS' in group:
  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 'LOCAL_CCFLAGS' in group or 'LOCAL_CPPPATH' in group or 'LOCAL_CPPDEFINES' in group:
  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. if GetOption('target') == 'ses':
  678. from ses import SESProject
  679. SESProject(Env)
  680. def EndBuilding(target, program = None):
  681. import rtconfig
  682. need_exit = False
  683. Env['target'] = program
  684. Env['project'] = Projects
  685. if hasattr(rtconfig, 'BSP_LIBRARY_TYPE'):
  686. Env['bsp_lib_type'] = rtconfig.BSP_LIBRARY_TYPE
  687. Env.AddPostAction(target, rtconfig.POST_ACTION)
  688. # Add addition clean files
  689. Clean(target, 'cconfig.h')
  690. Clean(target, 'rtua.py')
  691. Clean(target, 'rtua.pyc')
  692. if GetOption('target'):
  693. GenTargetProject(program)
  694. BSP_ROOT = Dir('#').abspath
  695. if GetOption('make-dist') and program != None:
  696. from mkdist import MkDist
  697. MkDist(program, BSP_ROOT, Rtt_Root, Env)
  698. if GetOption('make-dist-strip') and program != None:
  699. from mkdist import MkDist_Strip
  700. MkDist_Strip(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 (" + rtconfig.EXEC_PATH + ") is not exist, please check 'EXEC_PATH' in path or rtconfig.py.")
  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 = open(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 'RT_REVISION' in def_ns:
  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)