building.py 30 KB

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