building.py 38 KB

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