building.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  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. if isinstance(option, str):
  389. BuildOptions[option] = 1
  390. elif isinstance(option, list):
  391. for obj in option:
  392. if isinstance(obj, str):
  393. BuildOptions[obj] = 1
  394. else:
  395. print('AddDepend arguements are illegal!')
  396. else:
  397. print('AddDepend arguements are illegal!')
  398. def MergeGroup(src_group, group):
  399. src_group['src'] = src_group['src'] + group['src']
  400. src_group['src'].sort()
  401. if 'CFLAGS' in group:
  402. if 'CFLAGS' in src_group:
  403. src_group['CFLAGS'] = src_group['CFLAGS'] + group['CFLAGS']
  404. else:
  405. src_group['CFLAGS'] = group['CFLAGS']
  406. if 'CCFLAGS' in group:
  407. if 'CCFLAGS' in src_group:
  408. src_group['CCFLAGS'] = src_group['CCFLAGS'] + group['CCFLAGS']
  409. else:
  410. src_group['CCFLAGS'] = group['CCFLAGS']
  411. if 'CXXFLAGS' in group:
  412. if 'CXXFLAGS' in src_group:
  413. src_group['CXXFLAGS'] = src_group['CXXFLAGS'] + group['CXXFLAGS']
  414. else:
  415. src_group['CXXFLAGS'] = group['CXXFLAGS']
  416. if 'CPPPATH' in group:
  417. if 'CPPPATH' in src_group:
  418. src_group['CPPPATH'] = src_group['CPPPATH'] + group['CPPPATH']
  419. else:
  420. src_group['CPPPATH'] = group['CPPPATH']
  421. if 'CPPDEFINES' in group:
  422. if 'CPPDEFINES' in src_group:
  423. src_group['CPPDEFINES'] = src_group['CPPDEFINES'] + group['CPPDEFINES']
  424. else:
  425. src_group['CPPDEFINES'] = group['CPPDEFINES']
  426. if 'ASFLAGS' in group:
  427. if 'ASFLAGS' in src_group:
  428. src_group['ASFLAGS'] = src_group['ASFLAGS'] + group['ASFLAGS']
  429. else:
  430. src_group['ASFLAGS'] = group['ASFLAGS']
  431. # for local CCFLAGS/CPPPATH/CPPDEFINES
  432. if 'LOCAL_CFLAGS' in group:
  433. if 'LOCAL_CFLAGS' in src_group:
  434. src_group['LOCAL_CFLAGS'] = src_group['LOCAL_CFLAGS'] + group['LOCAL_CFLAGS']
  435. else:
  436. src_group['LOCAL_CFLAGS'] = group['LOCAL_CFLAGS']
  437. if 'LOCAL_CCFLAGS' in group:
  438. if 'LOCAL_CCFLAGS' in src_group:
  439. src_group['LOCAL_CCFLAGS'] = src_group['LOCAL_CCFLAGS'] + group['LOCAL_CCFLAGS']
  440. else:
  441. src_group['LOCAL_CCFLAGS'] = group['LOCAL_CCFLAGS']
  442. if 'LOCAL_CXXFLAGS' in group:
  443. if 'LOCAL_CXXFLAGS' in src_group:
  444. src_group['LOCAL_CXXFLAGS'] = src_group['LOCAL_CXXFLAGS'] + group['LOCAL_CXXFLAGS']
  445. else:
  446. src_group['LOCAL_CXXFLAGS'] = group['LOCAL_CXXFLAGS']
  447. if 'LOCAL_CPPPATH' in group:
  448. if 'LOCAL_CPPPATH' in src_group:
  449. src_group['LOCAL_CPPPATH'] = src_group['LOCAL_CPPPATH'] + group['LOCAL_CPPPATH']
  450. else:
  451. src_group['LOCAL_CPPPATH'] = group['LOCAL_CPPPATH']
  452. if 'LOCAL_CPPDEFINES' in group:
  453. if 'LOCAL_CPPDEFINES' in src_group:
  454. src_group['LOCAL_CPPDEFINES'] = src_group['LOCAL_CPPDEFINES'] + group['LOCAL_CPPDEFINES']
  455. else:
  456. src_group['LOCAL_CPPDEFINES'] = group['LOCAL_CPPDEFINES']
  457. if 'LINKFLAGS' in group:
  458. if 'LINKFLAGS' in src_group:
  459. src_group['LINKFLAGS'] = src_group['LINKFLAGS'] + group['LINKFLAGS']
  460. else:
  461. src_group['LINKFLAGS'] = group['LINKFLAGS']
  462. if 'LIBS' in group:
  463. if 'LIBS' in src_group:
  464. src_group['LIBS'] = src_group['LIBS'] + group['LIBS']
  465. else:
  466. src_group['LIBS'] = group['LIBS']
  467. if 'LIBPATH' in group:
  468. if 'LIBPATH' in src_group:
  469. src_group['LIBPATH'] = src_group['LIBPATH'] + group['LIBPATH']
  470. else:
  471. src_group['LIBPATH'] = group['LIBPATH']
  472. if 'LOCAL_ASFLAGS' in group:
  473. if 'LOCAL_ASFLAGS' in src_group:
  474. src_group['LOCAL_ASFLAGS'] = src_group['LOCAL_ASFLAGS'] + group['LOCAL_ASFLAGS']
  475. else:
  476. src_group['LOCAL_ASFLAGS'] = group['LOCAL_ASFLAGS']
  477. def _PretreatListParameters(target_list):
  478. while '' in target_list: # remove null strings
  479. target_list.remove('')
  480. while ' ' in target_list: # remove ' '
  481. target_list.remove(' ')
  482. if(len(target_list) == 0):
  483. return False # ignore this list, don't add this list to the parameter
  484. return True # permit to add this list to the parameter
  485. def DefineGroup(name, src, depend, **parameters):
  486. global Env
  487. if not GetDepend(depend):
  488. return []
  489. # find exist group and get path of group
  490. group_path = ''
  491. for g in Projects:
  492. if g['name'] == name:
  493. group_path = g['path']
  494. if group_path == '':
  495. group_path = GetCurrentDir()
  496. group = parameters
  497. group['name'] = name
  498. group['path'] = group_path
  499. if type(src) == type([]):
  500. # remove duplicate elements from list
  501. src = list(set(src))
  502. group['src'] = File(src)
  503. else:
  504. group['src'] = src
  505. if 'CFLAGS' in group:
  506. target = group['CFLAGS']
  507. if len(target) > 0:
  508. Env.AppendUnique(CFLAGS = target)
  509. if 'CCFLAGS' in group:
  510. target = group['CCFLAGS']
  511. if len(target) > 0:
  512. Env.AppendUnique(CCFLAGS = target)
  513. if 'CXXFLAGS' in group:
  514. target = group['CXXFLAGS']
  515. if len(target) > 0:
  516. Env.AppendUnique(CXXFLAGS = target)
  517. if 'CPPPATH' in group:
  518. target = group['CPPPATH']
  519. if _PretreatListParameters(target) == True:
  520. paths = []
  521. for item in target:
  522. paths.append(os.path.abspath(item))
  523. target = paths
  524. Env.AppendUnique(CPPPATH = target)
  525. if 'CPPDEFINES' in group:
  526. target = group['CPPDEFINES']
  527. if _PretreatListParameters(target) == True:
  528. Env.AppendUnique(CPPDEFINES = target)
  529. if 'LINKFLAGS' in group:
  530. target = group['LINKFLAGS']
  531. if len(target) > 0:
  532. Env.AppendUnique(LINKFLAGS = target)
  533. if 'ASFLAGS' in group:
  534. target = group['ASFLAGS']
  535. if len(target) > 0:
  536. Env.AppendUnique(ASFLAGS = target)
  537. if 'LOCAL_CPPPATH' in group:
  538. paths = []
  539. for item in group['LOCAL_CPPPATH']:
  540. paths.append(os.path.abspath(item))
  541. group['LOCAL_CPPPATH'] = paths
  542. if rtconfig.PLATFORM in ['gcc']:
  543. if 'CFLAGS' in group:
  544. group['CFLAGS'] = utils.GCCC99Patch(group['CFLAGS'])
  545. if 'CCFLAGS' in group:
  546. group['CCFLAGS'] = utils.GCCC99Patch(group['CCFLAGS'])
  547. if 'CXXFLAGS' in group:
  548. group['CXXFLAGS'] = utils.GCCC99Patch(group['CXXFLAGS'])
  549. if 'LOCAL_CCFLAGS' in group:
  550. group['LOCAL_CCFLAGS'] = utils.GCCC99Patch(group['LOCAL_CCFLAGS'])
  551. if 'LOCAL_CXXFLAGS' in group:
  552. group['LOCAL_CXXFLAGS'] = utils.GCCC99Patch(group['LOCAL_CXXFLAGS'])
  553. if 'LOCAL_CFLAGS' in group:
  554. group['LOCAL_CFLAGS'] = utils.GCCC99Patch(group['LOCAL_CFLAGS'])
  555. # check whether to clean up library
  556. if GetOption('cleanlib') and os.path.exists(os.path.join(group['path'], GroupLibFullName(name, Env))):
  557. if group['src'] != []:
  558. print('Remove library:'+ GroupLibFullName(name, Env))
  559. fn = os.path.join(group['path'], GroupLibFullName(name, Env))
  560. if os.path.exists(fn):
  561. os.unlink(fn)
  562. if 'LIBS' in group:
  563. target = group['LIBS']
  564. if _PretreatListParameters(target) == True:
  565. Env.AppendUnique(LIBS = target)
  566. if 'LIBPATH' in group:
  567. target = group['LIBPATH']
  568. if _PretreatListParameters(target) == True:
  569. Env.AppendUnique(LIBPATH = target)
  570. # check whether to build group library
  571. if 'LIBRARY' in group:
  572. objs = Env.Library(name, group['src'])
  573. else:
  574. # only add source
  575. objs = group['src']
  576. # merge group
  577. for g in Projects:
  578. if g['name'] == name:
  579. # merge to this group
  580. MergeGroup(g, group)
  581. return objs
  582. def PriorityInsertGroup(groups, group):
  583. length = len(groups)
  584. for i in range(0, length):
  585. if operator.gt(groups[i]['name'].lower(), group['name'].lower()):
  586. groups.insert(i, group)
  587. return
  588. groups.append(group)
  589. # add a new group
  590. PriorityInsertGroup(Projects, group)
  591. return objs
  592. def GetCurrentDir():
  593. conscript = File('SConscript')
  594. fn = conscript.rfile()
  595. name = fn.name
  596. path = os.path.dirname(fn.abspath)
  597. return path
  598. PREBUILDING = []
  599. def RegisterPreBuildingAction(act):
  600. global PREBUILDING
  601. assert callable(act), 'Could only register callable objects. %s received' % repr(act)
  602. PREBUILDING.append(act)
  603. def PreBuilding():
  604. global PREBUILDING
  605. for a in PREBUILDING:
  606. a()
  607. def GroupLibName(name, env):
  608. if rtconfig.PLATFORM in ['armcc']:
  609. return name + '_rvds'
  610. elif rtconfig.PLATFORM in ['gcc']:
  611. return name + '_gcc'
  612. return name
  613. def GroupLibFullName(name, env):
  614. return env['LIBPREFIX'] + GroupLibName(name, env) + env['LIBSUFFIX']
  615. def BuildLibInstallAction(target, source, env):
  616. lib_name = GetOption('buildlib')
  617. for Group in Projects:
  618. if Group['name'] == lib_name:
  619. lib_name = GroupLibFullName(Group['name'], env)
  620. dst_name = os.path.join(Group['path'], lib_name)
  621. print('Copy '+lib_name+' => ' + dst_name)
  622. do_copy_file(lib_name, dst_name)
  623. break
  624. def DoBuilding(target, objects):
  625. # merge all objects into one list
  626. def one_list(l):
  627. lst = []
  628. for item in l:
  629. if type(item) == type([]):
  630. lst += one_list(item)
  631. else:
  632. lst.append(item)
  633. return lst
  634. # handle local group
  635. def local_group(group, objects):
  636. 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:
  637. CFLAGS = Env.get('CFLAGS', '') + group.get('LOCAL_CFLAGS', '')
  638. CCFLAGS = Env.get('CCFLAGS', '') + group.get('LOCAL_CCFLAGS', '')
  639. CXXFLAGS = Env.get('CXXFLAGS', '') + group.get('LOCAL_CXXFLAGS', '')
  640. CPPPATH = Env.get('CPPPATH', ['']) + group.get('LOCAL_CPPPATH', [''])
  641. CPPDEFINES = Env.get('CPPDEFINES', ['']) + group.get('LOCAL_CPPDEFINES', [''])
  642. ASFLAGS = Env.get('ASFLAGS', '') + group.get('LOCAL_ASFLAGS', '')
  643. for source in group['src']:
  644. objects.append(Env.Object(source, CFLAGS = CFLAGS, CCFLAGS = CCFLAGS, CXXFLAGS = CXXFLAGS, ASFLAGS = ASFLAGS,
  645. CPPPATH = CPPPATH, CPPDEFINES = CPPDEFINES))
  646. return True
  647. return False
  648. objects = one_list(objects)
  649. program = None
  650. # check whether special buildlib option
  651. lib_name = GetOption('buildlib')
  652. if lib_name:
  653. objects = [] # remove all of objects
  654. # build library with special component
  655. for Group in Projects:
  656. if Group['name'] == lib_name:
  657. lib_name = GroupLibName(Group['name'], Env)
  658. if not local_group(Group, objects):
  659. objects = Env.Object(Group['src'])
  660. program = Env.Library(lib_name, objects)
  661. # add library copy action
  662. Env.BuildLib(lib_name, program)
  663. break
  664. else:
  665. # remove source files with local flags setting
  666. for group in Projects:
  667. 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:
  668. for source in group['src']:
  669. for obj in objects:
  670. if source.abspath == obj.abspath or (len(obj.sources) > 0 and source.abspath == obj.sources[0].abspath):
  671. objects.remove(obj)
  672. # re-add the source files to the objects
  673. objects_in_group = []
  674. for group in Projects:
  675. local_group(group, objects_in_group)
  676. # sort seperately, because the data type of
  677. # the members of the two lists are different
  678. objects_in_group = sorted(objects_in_group)
  679. objects = sorted(objects)
  680. objects.append(objects_in_group)
  681. program = Env.Program(target, objects)
  682. EndBuilding(target, program)
  683. def GenTargetProject(program = None):
  684. if GetOption('target') in ['mdk', 'mdk4', 'mdk5']:
  685. from keil import MDK2Project, MDK4Project, MDK5Project, ARMCC_Version
  686. if os.path.isfile('template.uvprojx') and GetOption('target') not in ['mdk4']: # Keil5
  687. MDK5Project(GetOption('project-name') + '.uvprojx', Projects)
  688. print("Keil5 project is generating...")
  689. elif os.path.isfile('template.uvproj') and GetOption('target') not in ['mdk5']: # Keil4
  690. MDK4Project(GetOption('project-name') + '.uvproj', Projects)
  691. print("Keil4 project is generating...")
  692. elif os.path.isfile('template.Uv2') and GetOption('target') not in ['mdk4', 'mdk5']: # Keil2
  693. MDK2Project(GetOption('project-name') + '.Uv2', Projects)
  694. print("Keil2 project is generating...")
  695. else:
  696. print ('No template project file found.')
  697. exit(1)
  698. print("Keil Version: " + ARMCC_Version())
  699. print("Keil-MDK project has generated successfully!")
  700. if GetOption('target') == 'iar':
  701. from iar import IARProject, IARVersion
  702. print("IAR Version: " + IARVersion())
  703. IARProject(GetOption('project-name') + '.ewp', Projects)
  704. print("IAR project has generated successfully!")
  705. if GetOption('target') == 'vs':
  706. from vs import VSProject
  707. VSProject(GetOption('project-name') + '.vcproj', Projects, program)
  708. if GetOption('target') == 'vs2012':
  709. from vs2012 import VS2012Project
  710. VS2012Project(GetOption('project-name') + '.vcxproj', Projects, program)
  711. if GetOption('target') == 'cb':
  712. from codeblocks import CBProject
  713. CBProject(GetOption('project-name') + '.cbp', Projects, program)
  714. if GetOption('target') == 'ua':
  715. from ua import PrepareUA
  716. PrepareUA(Projects, Rtt_Root, str(Dir('#')))
  717. if GetOption('target') == 'vsc':
  718. from vsc import GenerateVSCode
  719. GenerateVSCode(Env)
  720. if GetOption('target') == 'cdk':
  721. from cdk import CDKProject
  722. CDKProject(GetOption('project-name') + '.cdkproj', Projects)
  723. if GetOption('target') == 'ses':
  724. from ses import SESProject
  725. SESProject(Env)
  726. if GetOption('target') == 'makefile':
  727. from makefile import TargetMakefile
  728. TargetMakefile(Env)
  729. if GetOption('target') == 'eclipse':
  730. from eclipse import TargetEclipse
  731. TargetEclipse(Env, GetOption('reset-project-config'), GetOption('project-name'))
  732. if GetOption('target') == 'codelite':
  733. from codelite import TargetCodelite
  734. TargetCodelite(Projects, program)
  735. if GetOption('target') == 'cmake' or GetOption('target') == 'cmake-armclang':
  736. from cmake import CMakeProject
  737. CMakeProject(Env,Projects)
  738. if GetOption('target') == 'xmake':
  739. from xmake import XMakeProject
  740. XMakeProject(Env, Projects)
  741. if GetOption('target') == 'esp-idf':
  742. from esp_idf import ESPIDFProject
  743. ESPIDFProject(Env, Projects)
  744. def EndBuilding(target, program = None):
  745. need_exit = False
  746. Env['target'] = program
  747. Env['project'] = Projects
  748. if hasattr(rtconfig, 'BSP_LIBRARY_TYPE'):
  749. Env['bsp_lib_type'] = rtconfig.BSP_LIBRARY_TYPE
  750. if hasattr(rtconfig, 'dist_handle'):
  751. Env['dist_handle'] = rtconfig.dist_handle
  752. Env.AddPostAction(target, rtconfig.POST_ACTION)
  753. # Add addition clean files
  754. Clean(target, 'cconfig.h')
  755. Clean(target, 'rtua.py')
  756. Clean(target, 'rtua.pyc')
  757. Clean(target, '.sconsign.dblite')
  758. if GetOption('target'):
  759. GenTargetProject(program)
  760. need_exit = True
  761. BSP_ROOT = Dir('#').abspath
  762. if GetOption('make-dist') and program != None:
  763. from mkdist import MkDist
  764. MkDist(program, BSP_ROOT, Rtt_Root, Env)
  765. if GetOption('make-dist-strip') and program != None:
  766. from mkdist import MkDist_Strip
  767. MkDist_Strip(program, BSP_ROOT, Rtt_Root, Env)
  768. need_exit = True
  769. if GetOption('make-dist-ide') and program != None:
  770. from mkdist import MkDist
  771. project_path = GetOption('project-path')
  772. project_name = GetOption('project-name')
  773. if not isinstance(project_path, str) or len(project_path) == 0 :
  774. project_path = os.path.join(BSP_ROOT, 'rt-studio-project', project_name)
  775. print("\nwarning : --project-path not specified, use default path: {0}.".format(project_path))
  776. rtt_ide = {'project_path' : project_path, 'project_name' : project_name}
  777. MkDist(program, BSP_ROOT, Rtt_Root, Env, rtt_ide)
  778. need_exit = True
  779. if GetOption('cscope'):
  780. from cscope import CscopeDatabase
  781. CscopeDatabase(Projects)
  782. if not GetOption('help') and not GetOption('target'):
  783. if not os.path.exists(rtconfig.EXEC_PATH):
  784. print ("Error: the toolchain path (" + rtconfig.EXEC_PATH + ") is not exist, please check 'EXEC_PATH' in path or rtconfig.py.")
  785. need_exit = True
  786. if need_exit:
  787. exit(0)
  788. def SrcRemove(src, remove):
  789. if not src:
  790. return
  791. src_bak = src[:]
  792. if type(remove) == type('str'):
  793. if os.path.isabs(remove):
  794. remove = os.path.relpath(remove, GetCurrentDir())
  795. remove = os.path.normpath(remove)
  796. for item in src_bak:
  797. if type(item) == type('str'):
  798. item_str = item
  799. else:
  800. item_str = item.rstr()
  801. if os.path.isabs(item_str):
  802. item_str = os.path.relpath(item_str, GetCurrentDir())
  803. item_str = os.path.normpath(item_str)
  804. if item_str == remove:
  805. src.remove(item)
  806. else:
  807. for remove_item in remove:
  808. remove_str = str(remove_item)
  809. if os.path.isabs(remove_str):
  810. remove_str = os.path.relpath(remove_str, GetCurrentDir())
  811. remove_str = os.path.normpath(remove_str)
  812. for item in src_bak:
  813. if type(item) == type('str'):
  814. item_str = item
  815. else:
  816. item_str = item.rstr()
  817. if os.path.isabs(item_str):
  818. item_str = os.path.relpath(item_str, GetCurrentDir())
  819. item_str = os.path.normpath(item_str)
  820. if item_str == remove_str:
  821. src.remove(item)
  822. def GetVersion():
  823. import SCons.cpp
  824. import string
  825. rtdef = os.path.join(Rtt_Root, 'include', 'rtdef.h')
  826. # parse rtdef.h to get RT-Thread version
  827. prepcessor = PatchedPreProcessor()
  828. f = open(rtdef, 'r')
  829. contents = f.read()
  830. f.close()
  831. prepcessor.process_contents(contents)
  832. def_ns = prepcessor.cpp_namespace
  833. version = int([ch for ch in def_ns['RT_VERSION_MAJOR'] if ch in '0123456789.'])
  834. subversion = int([ch for ch in def_ns['RT_VERSION_MINOR'] if ch in '0123456789.'])
  835. if 'RT_VERSION_PATCH' in def_ns:
  836. revision = int([ch for ch in def_ns['RT_VERSION_PATCH'] if ch in '0123456789.'])
  837. return '%d.%d.%d' % (version, subversion, revision)
  838. return '0.%d.%d' % (version, subversion)
  839. def GlobSubDir(sub_dir, ext_name):
  840. import os
  841. import glob
  842. def glob_source(sub_dir, ext_name):
  843. list = os.listdir(sub_dir)
  844. src = glob.glob(os.path.join(sub_dir, ext_name))
  845. for item in list:
  846. full_subdir = os.path.join(sub_dir, item)
  847. if os.path.isdir(full_subdir):
  848. src += glob_source(full_subdir, ext_name)
  849. return src
  850. dst = []
  851. src = glob_source(sub_dir, ext_name)
  852. for item in src:
  853. dst.append(os.path.relpath(item, sub_dir))
  854. return dst
  855. def PackageSConscript(package):
  856. from package import BuildPackage
  857. return BuildPackage(package)