building.py 36 KB

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