building.py 33 KB

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