building.py 28 KB

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