building.py 28 KB

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