building.py 37 KB

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