building.py 35 KB

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