building.py 38 KB

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