building.py 36 KB

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