building.py 38 KB

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