building.py 37 KB

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