building.py 32 KB

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