building.py 37 KB

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