building.py 36 KB

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