building.py 33 KB

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