building.py 38 KB

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