building.py 34 KB

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