building.py 34 KB

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