building.py 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  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 command:' + cmdline.split(' ')[0])
  93. print ('Exception: ' + os.strerror(e.errno))
  94. if (os.strerror(e.errno) == "No such file or directory"):
  95. print ("\nPlease check Toolchains PATH setting.\n")
  96. return e.errno
  97. finally:
  98. os.environ['PATH'] = old_path
  99. return proc.wait()
  100. # generate cconfig.h file
  101. def GenCconfigFile(env, BuildOptions):
  102. import rtconfig
  103. if rtconfig.PLATFORM == 'gcc':
  104. contents = ''
  105. if not os.path.isfile('cconfig.h'):
  106. import gcc
  107. gcc.GenerateGCCConfig(rtconfig)
  108. # try again
  109. if os.path.isfile('cconfig.h'):
  110. f = open('cconfig.h', 'r')
  111. if f:
  112. contents = f.read()
  113. f.close()
  114. prep = PatchedPreProcessor()
  115. prep.process_contents(contents)
  116. options = prep.cpp_namespace
  117. BuildOptions.update(options)
  118. # add HAVE_CCONFIG_H definition
  119. env.AppendUnique(CPPDEFINES = ['HAVE_CCONFIG_H'])
  120. def PrepareBuilding(env, root_directory, has_libcpu=False, remove_components = []):
  121. import rtconfig
  122. global BuildOptions
  123. global Projects
  124. global Env
  125. global Rtt_Root
  126. # ===== Add option to SCons =====
  127. AddOption('--dist',
  128. dest = 'make-dist',
  129. action = 'store_true',
  130. default = False,
  131. help = 'make distribution')
  132. AddOption('--dist-strip',
  133. dest = 'make-dist-strip',
  134. action = 'store_true',
  135. default = False,
  136. help = 'make distribution and strip useless files')
  137. AddOption('--dist-ide',
  138. dest = 'make-dist-ide',
  139. action = 'store_true',
  140. default = False,
  141. help = 'make distribution for RT-Thread Studio IDE')
  142. AddOption('--project-path',
  143. dest = 'project-path',
  144. type = 'string',
  145. default = False,
  146. help = 'set dist-ide project output path')
  147. AddOption('--project-name',
  148. dest = 'project-name',
  149. type = 'string',
  150. default = False,
  151. help = 'set project name')
  152. AddOption('--reset-project-config',
  153. dest = 'reset-project-config',
  154. action = 'store_true',
  155. default = False,
  156. help = 'reset the project configurations to default')
  157. AddOption('--mcu-type',
  158. dest = 'mcu-type',
  159. type = 'string',
  160. default = False,
  161. help = 'set mcu type name')
  162. AddOption('--cscope',
  163. dest = 'cscope',
  164. action = 'store_true',
  165. default = False,
  166. help = 'Build Cscope cross reference database. Requires cscope installed.')
  167. AddOption('--clang-analyzer',
  168. dest = 'clang-analyzer',
  169. action = 'store_true',
  170. default = False,
  171. help = 'Perform static analyze with Clang-analyzer. ' + \
  172. 'Requires Clang installed.\n' + \
  173. 'It is recommended to use with scan-build like this:\n' + \
  174. '`scan-build scons --clang-analyzer`\n' + \
  175. 'If things goes well, scan-build will instruct you to invoke scan-view.')
  176. AddOption('--buildlib',
  177. dest = 'buildlib',
  178. type = 'string',
  179. help = 'building library of a component')
  180. AddOption('--cleanlib',
  181. dest = 'cleanlib',
  182. action = 'store_true',
  183. default = False,
  184. help = 'clean up the library by --buildlib')
  185. AddOption('--target',
  186. dest = 'target',
  187. type = 'string',
  188. help = 'set target project: mdk/mdk4/mdk5/iar/vs/vsc/ua/cdk/ses/makefile/eclipse')
  189. AddOption('--genconfig',
  190. dest = 'genconfig',
  191. action = 'store_true',
  192. default = False,
  193. help = 'Generate .config from rtconfig.h')
  194. AddOption('--useconfig',
  195. dest = 'useconfig',
  196. type = 'string',
  197. help = 'make rtconfig.h from config file.')
  198. AddOption('--verbose',
  199. dest = 'verbose',
  200. action = 'store_true',
  201. default = False,
  202. help = 'print verbose information during build')
  203. Env = env
  204. Rtt_Root = os.path.abspath(root_directory)
  205. # make an absolute root directory
  206. RTT_ROOT = Rtt_Root
  207. Export('RTT_ROOT')
  208. # set RTT_ROOT in ENV
  209. Env['RTT_ROOT'] = Rtt_Root
  210. # set BSP_ROOT in ENV
  211. Env['BSP_ROOT'] = Dir('#').abspath
  212. sys.path = sys.path + [os.path.join(Rtt_Root, 'tools')]
  213. # {target_name:(CROSS_TOOL, PLATFORM)}
  214. tgt_dict = {'mdk':('keil', 'armcc'),
  215. 'mdk4':('keil', 'armcc'),
  216. 'mdk5':('keil', 'armcc'),
  217. 'iar':('iar', 'iar'),
  218. 'vs':('msvc', 'cl'),
  219. 'vs2012':('msvc', 'cl'),
  220. 'vsc' : ('gcc', 'gcc'),
  221. 'cb':('keil', 'armcc'),
  222. 'ua':('gcc', 'gcc'),
  223. 'cdk':('gcc', 'gcc'),
  224. 'makefile':('gcc', 'gcc'),
  225. 'eclipse':('gcc', 'gcc'),
  226. 'ses' : ('gcc', 'gcc')}
  227. tgt_name = GetOption('target')
  228. if tgt_name:
  229. # --target will change the toolchain settings which clang-analyzer is
  230. # depend on
  231. if GetOption('clang-analyzer'):
  232. print ('--clang-analyzer cannot be used with --target')
  233. sys.exit(1)
  234. SetOption('no_exec', 1)
  235. try:
  236. rtconfig.CROSS_TOOL, rtconfig.PLATFORM = tgt_dict[tgt_name]
  237. # replace the 'RTT_CC' to 'CROSS_TOOL'
  238. os.environ['RTT_CC'] = rtconfig.CROSS_TOOL
  239. utils.ReloadModule(rtconfig)
  240. except KeyError:
  241. print ('Unknow target: '+ tgt_name+'. Avaible targets: ' +', '.join(tgt_dict.keys()))
  242. sys.exit(1)
  243. elif (GetDepend('RT_USING_NEWLIB') == False and GetDepend('RT_USING_NOLIBC') == False) \
  244. and rtconfig.PLATFORM == 'gcc':
  245. AddDepend('RT_USING_MINILIBC')
  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 env['PLATFORM'] != 'win32':
  323. AddOption('--menuconfig',
  324. dest = 'menuconfig',
  325. action = 'store_true',
  326. default = False,
  327. help = 'make menuconfig for RT-Thread BSP')
  328. if GetOption('menuconfig'):
  329. from menuconfig import menuconfig
  330. menuconfig(Rtt_Root)
  331. exit(0)
  332. AddOption('--pyconfig',
  333. dest = 'pyconfig',
  334. action = 'store_true',
  335. default = False,
  336. help = 'Python GUI menuconfig for RT-Thread BSP')
  337. AddOption('--pyconfig-silent',
  338. dest = 'pyconfig_silent',
  339. action = 'store_true',
  340. default = False,
  341. help = 'Don`t show pyconfig window')
  342. if GetOption('pyconfig_silent'):
  343. from menuconfig import guiconfig_silent
  344. guiconfig_silent(Rtt_Root)
  345. exit(0)
  346. elif GetOption('pyconfig'):
  347. from menuconfig import guiconfig
  348. guiconfig(Rtt_Root)
  349. exit(0)
  350. configfn = GetOption('useconfig')
  351. if configfn:
  352. from menuconfig import mk_rtconfig
  353. mk_rtconfig(configfn)
  354. exit(0)
  355. if not GetOption('verbose'):
  356. # override the default verbose command string
  357. env.Replace(
  358. ARCOMSTR = 'AR $TARGET',
  359. ASCOMSTR = 'AS $TARGET',
  360. ASPPCOMSTR = 'AS $TARGET',
  361. CCCOMSTR = 'CC $TARGET',
  362. CXXCOMSTR = 'CXX $TARGET',
  363. LINKCOMSTR = 'LINK $TARGET'
  364. )
  365. # fix the linker for C++
  366. if GetDepend('RT_USING_CPLUSPLUS'):
  367. if env['LINK'].find('gcc') != -1:
  368. env['LINK'] = env['LINK'].replace('gcc', 'g++')
  369. # we need to seperate the variant_dir for BSPs and the kernels. BSPs could
  370. # have their own components etc. If they point to the same folder, SCons
  371. # would find the wrong source code to compile.
  372. bsp_vdir = 'build'
  373. kernel_vdir = 'build/kernel'
  374. # board build script
  375. objs = SConscript('SConscript', variant_dir=bsp_vdir, duplicate=0)
  376. # include kernel
  377. objs.extend(SConscript(Rtt_Root + '/src/SConscript', variant_dir=kernel_vdir + '/src', duplicate=0))
  378. # include libcpu
  379. if not has_libcpu:
  380. objs.extend(SConscript(Rtt_Root + '/libcpu/SConscript',
  381. variant_dir=kernel_vdir + '/libcpu', duplicate=0))
  382. # include components
  383. objs.extend(SConscript(Rtt_Root + '/components/SConscript',
  384. variant_dir=kernel_vdir + '/components',
  385. duplicate=0,
  386. exports='remove_components'))
  387. return objs
  388. def PrepareModuleBuilding(env, root_directory, bsp_directory):
  389. import rtconfig
  390. global BuildOptions
  391. global Env
  392. global Rtt_Root
  393. # patch for win32 spawn
  394. if env['PLATFORM'] == 'win32':
  395. win32_spawn = Win32Spawn()
  396. win32_spawn.env = env
  397. env['SPAWN'] = win32_spawn.spawn
  398. Env = env
  399. Rtt_Root = root_directory
  400. # parse bsp rtconfig.h to get used component
  401. PreProcessor = PatchedPreProcessor()
  402. f = open(bsp_directory + '/rtconfig.h', 'r')
  403. contents = f.read()
  404. f.close()
  405. PreProcessor.process_contents(contents)
  406. BuildOptions = PreProcessor.cpp_namespace
  407. # add build/clean library option for library checking
  408. AddOption('--buildlib',
  409. dest='buildlib',
  410. type='string',
  411. help='building library of a component')
  412. AddOption('--cleanlib',
  413. dest='cleanlib',
  414. action='store_true',
  415. default=False,
  416. help='clean up the library by --buildlib')
  417. # add program path
  418. env.PrependENVPath('PATH', rtconfig.EXEC_PATH)
  419. def GetConfigValue(name):
  420. assert type(name) == str, 'GetConfigValue: only string parameter is valid'
  421. try:
  422. return BuildOptions[name]
  423. except:
  424. return ''
  425. def GetDepend(depend):
  426. building = True
  427. if type(depend) == type('str'):
  428. if not depend in BuildOptions or BuildOptions[depend] == 0:
  429. building = False
  430. elif BuildOptions[depend] != '':
  431. return BuildOptions[depend]
  432. return building
  433. # for list type depend
  434. for item in depend:
  435. if item != '':
  436. if not item in BuildOptions or BuildOptions[item] == 0:
  437. building = False
  438. return building
  439. def LocalOptions(config_filename):
  440. from SCons.Script import SCons
  441. # parse wiced_config.h to get used component
  442. PreProcessor = SCons.cpp.PreProcessor()
  443. f = open(config_filename, 'r')
  444. contents = f.read()
  445. f.close()
  446. PreProcessor.process_contents(contents)
  447. local_options = PreProcessor.cpp_namespace
  448. return local_options
  449. def GetLocalDepend(options, depend):
  450. building = True
  451. if type(depend) == type('str'):
  452. if not depend in options or options[depend] == 0:
  453. building = False
  454. elif options[depend] != '':
  455. return options[depend]
  456. return building
  457. # for list type depend
  458. for item in depend:
  459. if item != '':
  460. if not item in options or options[item] == 0:
  461. building = False
  462. return building
  463. def AddDepend(option):
  464. BuildOptions[option] = 1
  465. def MergeGroup(src_group, group):
  466. src_group['src'] = src_group['src'] + group['src']
  467. if 'CCFLAGS' in group:
  468. if 'CCFLAGS' in src_group:
  469. src_group['CCFLAGS'] = src_group['CCFLAGS'] + group['CCFLAGS']
  470. else:
  471. src_group['CCFLAGS'] = group['CCFLAGS']
  472. if 'CPPPATH' in group:
  473. if 'CPPPATH' in src_group:
  474. src_group['CPPPATH'] = src_group['CPPPATH'] + group['CPPPATH']
  475. else:
  476. src_group['CPPPATH'] = group['CPPPATH']
  477. if 'CPPDEFINES' in group:
  478. if 'CPPDEFINES' in src_group:
  479. src_group['CPPDEFINES'] = src_group['CPPDEFINES'] + group['CPPDEFINES']
  480. else:
  481. src_group['CPPDEFINES'] = group['CPPDEFINES']
  482. if 'ASFLAGS' in group:
  483. if 'ASFLAGS' in src_group:
  484. src_group['ASFLAGS'] = src_group['ASFLAGS'] + group['ASFLAGS']
  485. else:
  486. src_group['ASFLAGS'] = group['ASFLAGS']
  487. # for local CCFLAGS/CPPPATH/CPPDEFINES
  488. if 'LOCAL_CCFLAGS' in group:
  489. if 'LOCAL_CCFLAGS' in src_group:
  490. src_group['LOCAL_CCFLAGS'] = src_group['LOCAL_CCFLAGS'] + group['LOCAL_CCFLAGS']
  491. else:
  492. src_group['LOCAL_CCFLAGS'] = group['LOCAL_CCFLAGS']
  493. if 'LOCAL_CPPPATH' in group:
  494. if 'LOCAL_CPPPATH' in src_group:
  495. src_group['LOCAL_CPPPATH'] = src_group['LOCAL_CPPPATH'] + group['LOCAL_CPPPATH']
  496. else:
  497. src_group['LOCAL_CPPPATH'] = group['LOCAL_CPPPATH']
  498. if 'LOCAL_CPPDEFINES' in group:
  499. if 'LOCAL_CPPDEFINES' in src_group:
  500. src_group['LOCAL_CPPDEFINES'] = src_group['LOCAL_CPPDEFINES'] + group['LOCAL_CPPDEFINES']
  501. else:
  502. src_group['LOCAL_CPPDEFINES'] = group['LOCAL_CPPDEFINES']
  503. if 'LINKFLAGS' in group:
  504. if 'LINKFLAGS' in src_group:
  505. src_group['LINKFLAGS'] = src_group['LINKFLAGS'] + group['LINKFLAGS']
  506. else:
  507. src_group['LINKFLAGS'] = group['LINKFLAGS']
  508. if 'LIBS' in group:
  509. if 'LIBS' in src_group:
  510. src_group['LIBS'] = src_group['LIBS'] + group['LIBS']
  511. else:
  512. src_group['LIBS'] = group['LIBS']
  513. if 'LIBPATH' in group:
  514. if 'LIBPATH' in src_group:
  515. src_group['LIBPATH'] = src_group['LIBPATH'] + group['LIBPATH']
  516. else:
  517. src_group['LIBPATH'] = group['LIBPATH']
  518. if 'LOCAL_ASFLAGS' in group:
  519. if 'LOCAL_ASFLAGS' in src_group:
  520. src_group['LOCAL_ASFLAGS'] = src_group['LOCAL_ASFLAGS'] + group['LOCAL_ASFLAGS']
  521. else:
  522. src_group['LOCAL_ASFLAGS'] = group['LOCAL_ASFLAGS']
  523. def DefineGroup(name, src, depend, **parameters):
  524. global Env
  525. if not GetDepend(depend):
  526. return []
  527. # find exist group and get path of group
  528. group_path = ''
  529. for g in Projects:
  530. if g['name'] == name:
  531. group_path = g['path']
  532. if group_path == '':
  533. group_path = GetCurrentDir()
  534. group = parameters
  535. group['name'] = name
  536. group['path'] = group_path
  537. if type(src) == type([]):
  538. group['src'] = File(src)
  539. else:
  540. group['src'] = src
  541. if 'CCFLAGS' in group:
  542. Env.AppendUnique(CCFLAGS = group['CCFLAGS'])
  543. if 'CPPPATH' in group:
  544. paths = []
  545. for item in group['CPPPATH']:
  546. paths.append(os.path.abspath(item))
  547. group['CPPPATH'] = paths
  548. Env.AppendUnique(CPPPATH = group['CPPPATH'])
  549. if 'CPPDEFINES' in group:
  550. Env.AppendUnique(CPPDEFINES = group['CPPDEFINES'])
  551. if 'LINKFLAGS' in group:
  552. Env.AppendUnique(LINKFLAGS = group['LINKFLAGS'])
  553. if 'ASFLAGS' in group:
  554. Env.AppendUnique(ASFLAGS = group['ASFLAGS'])
  555. if 'LOCAL_CPPPATH' in group:
  556. paths = []
  557. for item in group['LOCAL_CPPPATH']:
  558. paths.append(os.path.abspath(item))
  559. group['LOCAL_CPPPATH'] = paths
  560. import rtconfig
  561. if rtconfig.PLATFORM == 'gcc':
  562. if 'CCFLAGS' in group:
  563. group['CCFLAGS'] = utils.GCCC99Patch(group['CCFLAGS'])
  564. if 'LOCAL_CCFLAGS' in group:
  565. group['LOCAL_CCFLAGS'] = utils.GCCC99Patch(group['LOCAL_CCFLAGS'])
  566. # check whether to clean up library
  567. if GetOption('cleanlib') and os.path.exists(os.path.join(group['path'], GroupLibFullName(name, Env))):
  568. if group['src'] != []:
  569. print ('Remove library:'+ GroupLibFullName(name, Env))
  570. fn = os.path.join(group['path'], GroupLibFullName(name, Env))
  571. if os.path.exists(fn):
  572. os.unlink(fn)
  573. if 'LIBS' in group:
  574. Env.AppendUnique(LIBS = group['LIBS'])
  575. if 'LIBPATH' in group:
  576. Env.AppendUnique(LIBPATH = group['LIBPATH'])
  577. # check whether to build group library
  578. if 'LIBRARY' in group:
  579. objs = Env.Library(name, group['src'])
  580. else:
  581. # only add source
  582. objs = group['src']
  583. # merge group
  584. for g in Projects:
  585. if g['name'] == name:
  586. # merge to this group
  587. MergeGroup(g, group)
  588. return objs
  589. # add a new group
  590. Projects.append(group)
  591. return objs
  592. def GetCurrentDir():
  593. conscript = File('SConscript')
  594. fn = conscript.rfile()
  595. name = fn.name
  596. path = os.path.dirname(fn.abspath)
  597. return path
  598. PREBUILDING = []
  599. def RegisterPreBuildingAction(act):
  600. global PREBUILDING
  601. assert callable(act), 'Could only register callable objects. %s received' % repr(act)
  602. PREBUILDING.append(act)
  603. def PreBuilding():
  604. global PREBUILDING
  605. for a in PREBUILDING:
  606. a()
  607. def GroupLibName(name, env):
  608. import rtconfig
  609. if rtconfig.PLATFORM == 'armcc':
  610. return name + '_rvds'
  611. elif rtconfig.PLATFORM == 'gcc':
  612. return name + '_gcc'
  613. return name
  614. def GroupLibFullName(name, env):
  615. return env['LIBPREFIX'] + GroupLibName(name, env) + env['LIBSUFFIX']
  616. def BuildLibInstallAction(target, source, env):
  617. lib_name = GetOption('buildlib')
  618. for Group in Projects:
  619. if Group['name'] == lib_name:
  620. lib_name = GroupLibFullName(Group['name'], env)
  621. dst_name = os.path.join(Group['path'], lib_name)
  622. print ('Copy '+lib_name+' => ' +dst_name)
  623. do_copy_file(lib_name, dst_name)
  624. break
  625. def DoBuilding(target, objects):
  626. # merge all objects into one list
  627. def one_list(l):
  628. lst = []
  629. for item in l:
  630. if type(item) == type([]):
  631. lst += one_list(item)
  632. else:
  633. lst.append(item)
  634. return lst
  635. # handle local group
  636. def local_group(group, objects):
  637. if 'LOCAL_CCFLAGS' in group or 'LOCAL_CPPPATH' in group or 'LOCAL_CPPDEFINES' in group or 'LOCAL_ASFLAGS' in group:
  638. CCFLAGS = Env.get('CCFLAGS', '') + group.get('LOCAL_CCFLAGS', '')
  639. CPPPATH = Env.get('CPPPATH', ['']) + group.get('LOCAL_CPPPATH', [''])
  640. CPPDEFINES = Env.get('CPPDEFINES', ['']) + group.get('LOCAL_CPPDEFINES', [''])
  641. ASFLAGS = Env.get('ASFLAGS', '') + group.get('LOCAL_ASFLAGS', '')
  642. for source in group['src']:
  643. objects.append(Env.Object(source, CCFLAGS = CCFLAGS, ASFLAGS = ASFLAGS,
  644. CPPPATH = CPPPATH, CPPDEFINES = CPPDEFINES))
  645. return True
  646. return False
  647. objects = one_list(objects)
  648. program = None
  649. # check whether special buildlib option
  650. lib_name = GetOption('buildlib')
  651. if lib_name:
  652. objects = [] # remove all of objects
  653. # build library with special component
  654. for Group in Projects:
  655. if Group['name'] == lib_name:
  656. lib_name = GroupLibName(Group['name'], Env)
  657. if not local_group(Group, objects):
  658. objects = Env.Object(Group['src'])
  659. program = Env.Library(lib_name, objects)
  660. # add library copy action
  661. Env.BuildLib(lib_name, program)
  662. break
  663. else:
  664. # remove source files with local flags setting
  665. for group in Projects:
  666. if 'LOCAL_CCFLAGS' in group or 'LOCAL_CPPPATH' in group or 'LOCAL_CPPDEFINES' in group:
  667. for source in group['src']:
  668. for obj in objects:
  669. if source.abspath == obj.abspath or (len(obj.sources) > 0 and source.abspath == obj.sources[0].abspath):
  670. objects.remove(obj)
  671. # re-add the source files to the objects
  672. for group in Projects:
  673. local_group(group, objects)
  674. program = Env.Program(target, objects)
  675. EndBuilding(target, program)
  676. def GenTargetProject(program = None):
  677. if GetOption('target') == 'mdk':
  678. from keil import MDKProject
  679. from keil import MDK4Project
  680. from keil import MDK5Project
  681. template = os.path.isfile('template.Uv2')
  682. if template:
  683. MDKProject('project.Uv2', Projects)
  684. else:
  685. template = os.path.isfile('template.uvproj')
  686. if template:
  687. MDK4Project('project.uvproj', Projects)
  688. else:
  689. template = os.path.isfile('template.uvprojx')
  690. if template:
  691. MDK5Project('project.uvprojx', Projects)
  692. else:
  693. print ('No template project file found.')
  694. if GetOption('target') == 'mdk4':
  695. from keil import MDK4Project
  696. MDK4Project('project.uvproj', Projects)
  697. if GetOption('target') == 'mdk5':
  698. from keil import MDK5Project
  699. MDK5Project('project.uvprojx', Projects)
  700. if GetOption('target') == 'iar':
  701. from iar import IARProject
  702. IARProject('project.ewp', Projects)
  703. if GetOption('target') == 'vs':
  704. from vs import VSProject
  705. VSProject('project.vcproj', Projects, program)
  706. if GetOption('target') == 'vs2012':
  707. from vs2012 import VS2012Project
  708. VS2012Project('project.vcxproj', Projects, program)
  709. if GetOption('target') == 'cb':
  710. from codeblocks import CBProject
  711. CBProject('project.cbp', Projects, program)
  712. if GetOption('target') == 'ua':
  713. from ua import PrepareUA
  714. PrepareUA(Projects, Rtt_Root, str(Dir('#')))
  715. if GetOption('target') == 'vsc':
  716. from vsc import GenerateVSCode
  717. GenerateVSCode(Env)
  718. if GetOption('target') == 'cdk':
  719. from cdk import CDKProject
  720. CDKProject('project.cdkproj', Projects)
  721. if GetOption('target') == 'ses':
  722. from ses import SESProject
  723. SESProject(Env)
  724. if GetOption('target') == 'makefile':
  725. from makefile import TargetMakefile
  726. TargetMakefile(Env)
  727. if GetOption('target') == 'eclipse':
  728. from eclipse import TargetEclipse
  729. TargetEclipse(Env, GetOption('reset-project-config'), GetOption('project-name'), GetOption('mcu-type'))
  730. def EndBuilding(target, program = None):
  731. import rtconfig
  732. need_exit = False
  733. Env['target'] = program
  734. Env['project'] = Projects
  735. if hasattr(rtconfig, 'BSP_LIBRARY_TYPE'):
  736. Env['bsp_lib_type'] = rtconfig.BSP_LIBRARY_TYPE
  737. if hasattr(rtconfig, 'dist_handle'):
  738. Env['dist_handle'] = rtconfig.dist_handle
  739. Env.AddPostAction(target, rtconfig.POST_ACTION)
  740. # Add addition clean files
  741. Clean(target, 'cconfig.h')
  742. Clean(target, 'rtua.py')
  743. Clean(target, 'rtua.pyc')
  744. if GetOption('target'):
  745. GenTargetProject(program)
  746. BSP_ROOT = Dir('#').abspath
  747. if GetOption('make-dist') and program != None:
  748. from mkdist import MkDist
  749. MkDist(program, BSP_ROOT, Rtt_Root, Env)
  750. if GetOption('make-dist-strip') and program != None:
  751. from mkdist import MkDist_Strip
  752. MkDist_Strip(program, BSP_ROOT, Rtt_Root, Env)
  753. need_exit = True
  754. if GetOption('make-dist-ide') and program != None:
  755. from mkdist import MkDist
  756. project_path = GetOption('project-path')
  757. project_name = GetOption('project-name')
  758. if not isinstance(project_path, str) or len(project_path) == 0 :
  759. print("\nwarning : --project-path=your_project_path parameter is required.")
  760. print("\nstop!")
  761. exit(0)
  762. if not isinstance(project_name, str) or len(project_name) == 0:
  763. print("\nwarning : --project-name=your_project_name parameter is required.")
  764. print("\nstop!")
  765. exit(0)
  766. rtt_ide = {'project_path' : project_path, 'project_name' : project_name}
  767. MkDist(program, BSP_ROOT, Rtt_Root, Env, rtt_ide)
  768. need_exit = True
  769. if GetOption('cscope'):
  770. from cscope import CscopeDatabase
  771. CscopeDatabase(Projects)
  772. if not GetOption('help') and not GetOption('target'):
  773. if not os.path.exists(rtconfig.EXEC_PATH):
  774. print ("Error: the toolchain path (" + rtconfig.EXEC_PATH + ") is not exist, please check 'EXEC_PATH' in path or rtconfig.py.")
  775. need_exit = True
  776. if need_exit:
  777. exit(0)
  778. def SrcRemove(src, remove):
  779. if not src:
  780. return
  781. src_bak = src[:]
  782. if type(remove) == type('str'):
  783. if os.path.isabs(remove):
  784. remove = os.path.relpath(remove, GetCurrentDir())
  785. remove = os.path.normpath(remove)
  786. for item in src_bak:
  787. if type(item) == type('str'):
  788. item_str = item
  789. else:
  790. item_str = item.rstr()
  791. if os.path.isabs(item_str):
  792. item_str = os.path.relpath(item_str, GetCurrentDir())
  793. item_str = os.path.normpath(item_str)
  794. if item_str == remove:
  795. src.remove(item)
  796. else:
  797. for remove_item in remove:
  798. remove_str = str(remove_item)
  799. if os.path.isabs(remove_str):
  800. remove_str = os.path.relpath(remove_str, GetCurrentDir())
  801. remove_str = os.path.normpath(remove_str)
  802. for item in src_bak:
  803. if type(item) == type('str'):
  804. item_str = item
  805. else:
  806. item_str = item.rstr()
  807. if os.path.isabs(item_str):
  808. item_str = os.path.relpath(item_str, GetCurrentDir())
  809. item_str = os.path.normpath(item_str)
  810. if item_str == remove_str:
  811. src.remove(item)
  812. def GetVersion():
  813. import SCons.cpp
  814. import string
  815. rtdef = os.path.join(Rtt_Root, 'include', 'rtdef.h')
  816. # parse rtdef.h to get RT-Thread version
  817. prepcessor = PatchedPreProcessor()
  818. f = open(rtdef, 'r')
  819. contents = f.read()
  820. f.close()
  821. prepcessor.process_contents(contents)
  822. def_ns = prepcessor.cpp_namespace
  823. version = int(filter(lambda ch: ch in '0123456789.', def_ns['RT_VERSION']))
  824. subversion = int(filter(lambda ch: ch in '0123456789.', def_ns['RT_SUBVERSION']))
  825. if 'RT_REVISION' in def_ns:
  826. revision = int(filter(lambda ch: ch in '0123456789.', def_ns['RT_REVISION']))
  827. return '%d.%d.%d' % (version, subversion, revision)
  828. return '0.%d.%d' % (version, subversion)
  829. def GlobSubDir(sub_dir, ext_name):
  830. import os
  831. import glob
  832. def glob_source(sub_dir, ext_name):
  833. list = os.listdir(sub_dir)
  834. src = glob.glob(os.path.join(sub_dir, ext_name))
  835. for item in list:
  836. full_subdir = os.path.join(sub_dir, item)
  837. if os.path.isdir(full_subdir):
  838. src += glob_source(full_subdir, ext_name)
  839. return src
  840. dst = []
  841. src = glob_source(sub_dir, ext_name)
  842. for item in src:
  843. dst.append(os.path.relpath(item, sub_dir))
  844. return dst
  845. def PackageSConscript(package):
  846. from package import BuildPackage
  847. return BuildPackage(package)