building.py 34 KB

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