building.py 30 KB

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