building.py 38 KB

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