building.py 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  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/codelite/cmake')
  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. 'cmake':('gcc', 'gcc'),
  229. 'codelite' : ('gcc', 'gcc')}
  230. tgt_name = GetOption('target')
  231. if tgt_name:
  232. # --target will change the toolchain settings which clang-analyzer is
  233. # depend on
  234. if GetOption('clang-analyzer'):
  235. print ('--clang-analyzer cannot be used with --target')
  236. sys.exit(1)
  237. SetOption('no_exec', 1)
  238. try:
  239. rtconfig.CROSS_TOOL, rtconfig.PLATFORM = tgt_dict[tgt_name]
  240. # replace the 'RTT_CC' to 'CROSS_TOOL'
  241. os.environ['RTT_CC'] = rtconfig.CROSS_TOOL
  242. utils.ReloadModule(rtconfig)
  243. except KeyError:
  244. print('Unknow target: '+ tgt_name+'. Avaible targets: ' +', '.join(tgt_dict.keys()))
  245. sys.exit(1)
  246. # auto change the 'RTT_EXEC_PATH' when 'rtconfig.EXEC_PATH' get failed
  247. if not os.path.exists(rtconfig.EXEC_PATH):
  248. if 'RTT_EXEC_PATH' in os.environ:
  249. # del the 'RTT_EXEC_PATH' and using the 'EXEC_PATH' setting on rtconfig.py
  250. del os.environ['RTT_EXEC_PATH']
  251. utils.ReloadModule(rtconfig)
  252. # add compability with Keil MDK 4.6 which changes the directory of armcc.exe
  253. if rtconfig.PLATFORM == 'armcc' or rtconfig.PLATFORM == 'armclang':
  254. if rtconfig.PLATFORM == 'armcc' and not os.path.isfile(os.path.join(rtconfig.EXEC_PATH, 'armcc.exe')):
  255. if rtconfig.EXEC_PATH.find('bin40') > 0:
  256. rtconfig.EXEC_PATH = rtconfig.EXEC_PATH.replace('bin40', 'armcc/bin')
  257. Env['LINKFLAGS'] = Env['LINKFLAGS'].replace('RV31', 'armcc')
  258. # reset AR command flags
  259. env['ARCOM'] = '$AR --create $TARGET $SOURCES'
  260. env['LIBPREFIX'] = ''
  261. env['LIBSUFFIX'] = '.lib'
  262. env['LIBLINKPREFIX'] = ''
  263. env['LIBLINKSUFFIX'] = '.lib'
  264. env['LIBDIRPREFIX'] = '--userlibpath '
  265. elif rtconfig.PLATFORM == 'iar':
  266. env['LIBPREFIX'] = ''
  267. env['LIBSUFFIX'] = '.a'
  268. env['LIBLINKPREFIX'] = ''
  269. env['LIBLINKSUFFIX'] = '.a'
  270. env['LIBDIRPREFIX'] = '--search '
  271. # patch for win32 spawn
  272. if env['PLATFORM'] == 'win32':
  273. win32_spawn = Win32Spawn()
  274. win32_spawn.env = env
  275. env['SPAWN'] = win32_spawn.spawn
  276. if env['PLATFORM'] == 'win32':
  277. os.environ['PATH'] = rtconfig.EXEC_PATH + ";" + os.environ['PATH']
  278. else:
  279. os.environ['PATH'] = rtconfig.EXEC_PATH + ":" + os.environ['PATH']
  280. # add program path
  281. env.PrependENVPath('PATH', os.environ['PATH'])
  282. # add rtconfig.h/BSP path into Kernel group
  283. DefineGroup("Kernel", [], [], CPPPATH=[str(Dir('#').abspath)])
  284. # add library build action
  285. act = SCons.Action.Action(BuildLibInstallAction, 'Install compiled library... $TARGET')
  286. bld = Builder(action = act)
  287. Env.Append(BUILDERS = {'BuildLib': bld})
  288. # parse rtconfig.h to get used component
  289. PreProcessor = PatchedPreProcessor()
  290. f = open('rtconfig.h', 'r')
  291. contents = f.read()
  292. f.close()
  293. PreProcessor.process_contents(contents)
  294. BuildOptions = PreProcessor.cpp_namespace
  295. if GetOption('clang-analyzer'):
  296. # perform what scan-build does
  297. env.Replace(
  298. CC = 'ccc-analyzer',
  299. CXX = 'c++-analyzer',
  300. # skip as and link
  301. LINK = 'true',
  302. AS = 'true',)
  303. env["ENV"].update(x for x in os.environ.items() if x[0].startswith("CCC_"))
  304. # only check, don't compile. ccc-analyzer use CCC_CC as the CC.
  305. # fsyntax-only will give us some additional warning messages
  306. env['ENV']['CCC_CC'] = 'clang'
  307. env.Append(CFLAGS=['-fsyntax-only', '-Wall', '-Wno-invalid-source-encoding'])
  308. env['ENV']['CCC_CXX'] = 'clang++'
  309. env.Append(CXXFLAGS=['-fsyntax-only', '-Wall', '-Wno-invalid-source-encoding'])
  310. # remove the POST_ACTION as it will cause meaningless errors(file not
  311. # found or something like that).
  312. rtconfig.POST_ACTION = ''
  313. # generate cconfig.h file
  314. GenCconfigFile(env, BuildOptions)
  315. # auto append '_REENT_SMALL' when using newlib 'nano.specs' option
  316. if rtconfig.PLATFORM == 'gcc' and str(env['LINKFLAGS']).find('nano.specs') != -1:
  317. env.AppendUnique(CPPDEFINES = ['_REENT_SMALL'])
  318. if GetOption('genconfig'):
  319. from genconf import genconfig
  320. genconfig()
  321. exit(0)
  322. if GetOption('stackanalysis'):
  323. from WCS import ThreadStackStaticAnalysis
  324. ThreadStackStaticAnalysis(Env)
  325. exit(0)
  326. if env['PLATFORM'] != 'win32':
  327. AddOption('--menuconfig',
  328. dest = 'menuconfig',
  329. action = 'store_true',
  330. default = False,
  331. help = 'make menuconfig for RT-Thread BSP')
  332. if GetOption('menuconfig'):
  333. from menuconfig import menuconfig
  334. menuconfig(Rtt_Root)
  335. exit(0)
  336. AddOption('--pyconfig',
  337. dest = 'pyconfig',
  338. action = 'store_true',
  339. default = False,
  340. help = 'Python GUI menuconfig for RT-Thread BSP')
  341. AddOption('--pyconfig-silent',
  342. dest = 'pyconfig_silent',
  343. action = 'store_true',
  344. default = False,
  345. help = 'Don`t show pyconfig window')
  346. if GetOption('pyconfig_silent'):
  347. from menuconfig import guiconfig_silent
  348. guiconfig_silent(Rtt_Root)
  349. exit(0)
  350. elif GetOption('pyconfig'):
  351. from menuconfig import guiconfig
  352. guiconfig(Rtt_Root)
  353. exit(0)
  354. configfn = GetOption('useconfig')
  355. if configfn:
  356. from menuconfig import mk_rtconfig
  357. mk_rtconfig(configfn)
  358. exit(0)
  359. if not GetOption('verbose'):
  360. # override the default verbose command string
  361. env.Replace(
  362. ARCOMSTR = 'AR $TARGET',
  363. ASCOMSTR = 'AS $TARGET',
  364. ASPPCOMSTR = 'AS $TARGET',
  365. CCCOMSTR = 'CC $TARGET',
  366. CXXCOMSTR = 'CXX $TARGET',
  367. LINKCOMSTR = 'LINK $TARGET'
  368. )
  369. # fix the linker for C++
  370. if GetDepend('RT_USING_CPLUSPLUS'):
  371. if env['LINK'].find('gcc') != -1:
  372. env['LINK'] = env['LINK'].replace('gcc', 'g++')
  373. # we need to seperate the variant_dir for BSPs and the kernels. BSPs could
  374. # have their own components etc. If they point to the same folder, SCons
  375. # would find the wrong source code to compile.
  376. bsp_vdir = 'build'
  377. kernel_vdir = 'build/kernel'
  378. # board build script
  379. objs = SConscript('SConscript', variant_dir=bsp_vdir, duplicate=0)
  380. # include kernel
  381. objs.extend(SConscript(Rtt_Root + '/src/SConscript', variant_dir=kernel_vdir + '/src', duplicate=0))
  382. # include libcpu
  383. if not has_libcpu:
  384. objs.extend(SConscript(Rtt_Root + '/libcpu/SConscript',
  385. variant_dir=kernel_vdir + '/libcpu', duplicate=0))
  386. # include components
  387. objs.extend(SConscript(Rtt_Root + '/components/SConscript',
  388. variant_dir=kernel_vdir + '/components',
  389. duplicate=0,
  390. exports='remove_components'))
  391. return objs
  392. def PrepareModuleBuilding(env, root_directory, bsp_directory):
  393. import rtconfig
  394. global BuildOptions
  395. global Env
  396. global Rtt_Root
  397. # patch for win32 spawn
  398. if env['PLATFORM'] == 'win32':
  399. win32_spawn = Win32Spawn()
  400. win32_spawn.env = env
  401. env['SPAWN'] = win32_spawn.spawn
  402. Env = env
  403. Rtt_Root = root_directory
  404. # parse bsp rtconfig.h to get used component
  405. PreProcessor = PatchedPreProcessor()
  406. f = open(bsp_directory + '/rtconfig.h', 'r')
  407. contents = f.read()
  408. f.close()
  409. PreProcessor.process_contents(contents)
  410. BuildOptions = PreProcessor.cpp_namespace
  411. # add build/clean library option for library checking
  412. AddOption('--buildlib',
  413. dest='buildlib',
  414. type='string',
  415. help='building library of a component')
  416. AddOption('--cleanlib',
  417. dest='cleanlib',
  418. action='store_true',
  419. default=False,
  420. help='clean up the library by --buildlib')
  421. # add program path
  422. env.PrependENVPath('PATH', rtconfig.EXEC_PATH)
  423. def GetConfigValue(name):
  424. assert type(name) == str, 'GetConfigValue: only string parameter is valid'
  425. try:
  426. return BuildOptions[name]
  427. except:
  428. return ''
  429. def GetDepend(depend):
  430. building = True
  431. if type(depend) == type('str'):
  432. if not depend in BuildOptions or BuildOptions[depend] == 0:
  433. building = False
  434. elif BuildOptions[depend] != '':
  435. return BuildOptions[depend]
  436. return building
  437. # for list type depend
  438. for item in depend:
  439. if item != '':
  440. if not item in BuildOptions or BuildOptions[item] == 0:
  441. building = False
  442. return building
  443. def LocalOptions(config_filename):
  444. from SCons.Script import SCons
  445. # parse wiced_config.h to get used component
  446. PreProcessor = SCons.cpp.PreProcessor()
  447. f = open(config_filename, 'r')
  448. contents = f.read()
  449. f.close()
  450. PreProcessor.process_contents(contents)
  451. local_options = PreProcessor.cpp_namespace
  452. return local_options
  453. def GetLocalDepend(options, depend):
  454. building = True
  455. if type(depend) == type('str'):
  456. if not depend in options or options[depend] == 0:
  457. building = False
  458. elif options[depend] != '':
  459. return options[depend]
  460. return building
  461. # for list type depend
  462. for item in depend:
  463. if item != '':
  464. if not item in options or options[item] == 0:
  465. building = False
  466. return building
  467. def AddDepend(option):
  468. BuildOptions[option] = 1
  469. def MergeGroup(src_group, group):
  470. src_group['src'] = src_group['src'] + group['src']
  471. if 'CCFLAGS' in group:
  472. if 'CCFLAGS' in src_group:
  473. src_group['CCFLAGS'] = src_group['CCFLAGS'] + group['CCFLAGS']
  474. else:
  475. src_group['CCFLAGS'] = group['CCFLAGS']
  476. if 'CPPPATH' in group:
  477. if 'CPPPATH' in src_group:
  478. src_group['CPPPATH'] = src_group['CPPPATH'] + group['CPPPATH']
  479. else:
  480. src_group['CPPPATH'] = group['CPPPATH']
  481. if 'CPPDEFINES' in group:
  482. if 'CPPDEFINES' in src_group:
  483. src_group['CPPDEFINES'] = src_group['CPPDEFINES'] + group['CPPDEFINES']
  484. else:
  485. src_group['CPPDEFINES'] = group['CPPDEFINES']
  486. if 'ASFLAGS' in group:
  487. if 'ASFLAGS' in src_group:
  488. src_group['ASFLAGS'] = src_group['ASFLAGS'] + group['ASFLAGS']
  489. else:
  490. src_group['ASFLAGS'] = group['ASFLAGS']
  491. # for local CCFLAGS/CPPPATH/CPPDEFINES
  492. if 'LOCAL_CCFLAGS' in group:
  493. if 'LOCAL_CCFLAGS' in src_group:
  494. src_group['LOCAL_CCFLAGS'] = src_group['LOCAL_CCFLAGS'] + group['LOCAL_CCFLAGS']
  495. else:
  496. src_group['LOCAL_CCFLAGS'] = group['LOCAL_CCFLAGS']
  497. if 'LOCAL_CPPPATH' in group:
  498. if 'LOCAL_CPPPATH' in src_group:
  499. src_group['LOCAL_CPPPATH'] = src_group['LOCAL_CPPPATH'] + group['LOCAL_CPPPATH']
  500. else:
  501. src_group['LOCAL_CPPPATH'] = group['LOCAL_CPPPATH']
  502. if 'LOCAL_CPPDEFINES' in group:
  503. if 'LOCAL_CPPDEFINES' in src_group:
  504. src_group['LOCAL_CPPDEFINES'] = src_group['LOCAL_CPPDEFINES'] + group['LOCAL_CPPDEFINES']
  505. else:
  506. src_group['LOCAL_CPPDEFINES'] = group['LOCAL_CPPDEFINES']
  507. if 'LINKFLAGS' in group:
  508. if 'LINKFLAGS' in src_group:
  509. src_group['LINKFLAGS'] = src_group['LINKFLAGS'] + group['LINKFLAGS']
  510. else:
  511. src_group['LINKFLAGS'] = group['LINKFLAGS']
  512. if 'LIBS' in group:
  513. if 'LIBS' in src_group:
  514. src_group['LIBS'] = src_group['LIBS'] + group['LIBS']
  515. else:
  516. src_group['LIBS'] = group['LIBS']
  517. if 'LIBPATH' in group:
  518. if 'LIBPATH' in src_group:
  519. src_group['LIBPATH'] = src_group['LIBPATH'] + group['LIBPATH']
  520. else:
  521. src_group['LIBPATH'] = group['LIBPATH']
  522. if 'LOCAL_ASFLAGS' in group:
  523. if 'LOCAL_ASFLAGS' in src_group:
  524. src_group['LOCAL_ASFLAGS'] = src_group['LOCAL_ASFLAGS'] + group['LOCAL_ASFLAGS']
  525. else:
  526. src_group['LOCAL_ASFLAGS'] = group['LOCAL_ASFLAGS']
  527. def DefineGroup(name, src, depend, **parameters):
  528. global Env
  529. if not GetDepend(depend):
  530. return []
  531. # find exist group and get path of group
  532. group_path = ''
  533. for g in Projects:
  534. if g['name'] == name:
  535. group_path = g['path']
  536. if group_path == '':
  537. group_path = GetCurrentDir()
  538. group = parameters
  539. group['name'] = name
  540. group['path'] = group_path
  541. if type(src) == type([]):
  542. # remove duplicate elements from list
  543. src = list(set(src))
  544. group['src'] = File(src)
  545. else:
  546. group['src'] = src
  547. if 'CCFLAGS' in group:
  548. Env.AppendUnique(CCFLAGS = group['CCFLAGS'])
  549. if 'CPPPATH' in group:
  550. paths = []
  551. for item in group['CPPPATH']:
  552. paths.append(os.path.abspath(item))
  553. group['CPPPATH'] = paths
  554. Env.AppendUnique(CPPPATH = group['CPPPATH'])
  555. if 'CPPDEFINES' in group:
  556. Env.AppendUnique(CPPDEFINES = group['CPPDEFINES'])
  557. if 'LINKFLAGS' in group:
  558. Env.AppendUnique(LINKFLAGS = group['LINKFLAGS'])
  559. if 'ASFLAGS' in group:
  560. Env.AppendUnique(ASFLAGS = group['ASFLAGS'])
  561. if 'LOCAL_CPPPATH' in group:
  562. paths = []
  563. for item in group['LOCAL_CPPPATH']:
  564. paths.append(os.path.abspath(item))
  565. group['LOCAL_CPPPATH'] = paths
  566. import rtconfig
  567. if rtconfig.PLATFORM == 'gcc':
  568. if 'CCFLAGS' in group:
  569. group['CCFLAGS'] = utils.GCCC99Patch(group['CCFLAGS'])
  570. if 'LOCAL_CCFLAGS' in group:
  571. group['LOCAL_CCFLAGS'] = utils.GCCC99Patch(group['LOCAL_CCFLAGS'])
  572. # check whether to clean up library
  573. if GetOption('cleanlib') and os.path.exists(os.path.join(group['path'], GroupLibFullName(name, Env))):
  574. if group['src'] != []:
  575. print('Remove library:'+ GroupLibFullName(name, Env))
  576. fn = os.path.join(group['path'], GroupLibFullName(name, Env))
  577. if os.path.exists(fn):
  578. os.unlink(fn)
  579. if 'LIBS' in group:
  580. Env.AppendUnique(LIBS = group['LIBS'])
  581. if 'LIBPATH' in group:
  582. Env.AppendUnique(LIBPATH = group['LIBPATH'])
  583. # check whether to build group library
  584. if 'LIBRARY' in group:
  585. objs = Env.Library(name, group['src'])
  586. else:
  587. # only add source
  588. objs = group['src']
  589. # merge group
  590. for g in Projects:
  591. if g['name'] == name:
  592. # merge to this group
  593. MergeGroup(g, group)
  594. return objs
  595. def PriorityInsertGroup(groups, group):
  596. length = len(groups)
  597. for i in range(0, length):
  598. if operator.gt(groups[i]['name'].lower(), group['name'].lower()):
  599. groups.insert(i, group)
  600. return
  601. groups.append(group)
  602. # add a new group
  603. PriorityInsertGroup(Projects, group)
  604. return objs
  605. def GetCurrentDir():
  606. conscript = File('SConscript')
  607. fn = conscript.rfile()
  608. name = fn.name
  609. path = os.path.dirname(fn.abspath)
  610. return path
  611. PREBUILDING = []
  612. def RegisterPreBuildingAction(act):
  613. global PREBUILDING
  614. assert callable(act), 'Could only register callable objects. %s received' % repr(act)
  615. PREBUILDING.append(act)
  616. def PreBuilding():
  617. global PREBUILDING
  618. for a in PREBUILDING:
  619. a()
  620. def GroupLibName(name, env):
  621. import rtconfig
  622. if rtconfig.PLATFORM == 'armcc':
  623. return name + '_rvds'
  624. elif rtconfig.PLATFORM == 'gcc':
  625. return name + '_gcc'
  626. return name
  627. def GroupLibFullName(name, env):
  628. return env['LIBPREFIX'] + GroupLibName(name, env) + env['LIBSUFFIX']
  629. def BuildLibInstallAction(target, source, env):
  630. lib_name = GetOption('buildlib')
  631. for Group in Projects:
  632. if Group['name'] == lib_name:
  633. lib_name = GroupLibFullName(Group['name'], env)
  634. dst_name = os.path.join(Group['path'], lib_name)
  635. print('Copy '+lib_name+' => ' + dst_name)
  636. do_copy_file(lib_name, dst_name)
  637. break
  638. def DoBuilding(target, objects):
  639. # merge all objects into one list
  640. def one_list(l):
  641. lst = []
  642. for item in l:
  643. if type(item) == type([]):
  644. lst += one_list(item)
  645. else:
  646. lst.append(item)
  647. return lst
  648. # handle local group
  649. def local_group(group, objects):
  650. if 'LOCAL_CCFLAGS' in group or 'LOCAL_CPPPATH' in group or 'LOCAL_CPPDEFINES' in group or 'LOCAL_ASFLAGS' in group:
  651. CCFLAGS = Env.get('CCFLAGS', '') + group.get('LOCAL_CCFLAGS', '')
  652. CPPPATH = Env.get('CPPPATH', ['']) + group.get('LOCAL_CPPPATH', [''])
  653. CPPDEFINES = Env.get('CPPDEFINES', ['']) + group.get('LOCAL_CPPDEFINES', [''])
  654. ASFLAGS = Env.get('ASFLAGS', '') + group.get('LOCAL_ASFLAGS', '')
  655. for source in group['src']:
  656. objects.append(Env.Object(source, CCFLAGS = CCFLAGS, ASFLAGS = ASFLAGS,
  657. CPPPATH = CPPPATH, CPPDEFINES = CPPDEFINES))
  658. return True
  659. return False
  660. objects = one_list(objects)
  661. program = None
  662. # check whether special buildlib option
  663. lib_name = GetOption('buildlib')
  664. if lib_name:
  665. objects = [] # remove all of objects
  666. # build library with special component
  667. for Group in Projects:
  668. if Group['name'] == lib_name:
  669. lib_name = GroupLibName(Group['name'], Env)
  670. if not local_group(Group, objects):
  671. objects = Env.Object(Group['src'])
  672. program = Env.Library(lib_name, objects)
  673. # add library copy action
  674. Env.BuildLib(lib_name, program)
  675. break
  676. else:
  677. # remove source files with local flags setting
  678. for group in Projects:
  679. if 'LOCAL_CCFLAGS' in group or 'LOCAL_CPPPATH' in group or 'LOCAL_CPPDEFINES' in group:
  680. for source in group['src']:
  681. for obj in objects:
  682. if source.abspath == obj.abspath or (len(obj.sources) > 0 and source.abspath == obj.sources[0].abspath):
  683. objects.remove(obj)
  684. # re-add the source files to the objects
  685. for group in Projects:
  686. local_group(group, objects)
  687. program = Env.Program(target, objects)
  688. EndBuilding(target, program)
  689. def GenTargetProject(program = None):
  690. if GetOption('target') == 'mdk':
  691. from keil import MDKProject
  692. from keil import MDK4Project
  693. from keil import MDK5Project
  694. template = os.path.isfile('template.Uv2')
  695. if template:
  696. MDKProject('project.Uv2', Projects)
  697. else:
  698. template = os.path.isfile('template.uvproj')
  699. if template:
  700. MDK4Project('project.uvproj', Projects)
  701. else:
  702. template = os.path.isfile('template.uvprojx')
  703. if template:
  704. MDK5Project('project.uvprojx', Projects)
  705. else:
  706. print ('No template project file found.')
  707. if GetOption('target') == 'mdk4':
  708. from keil import MDK4Project
  709. MDK4Project('project.uvproj', Projects)
  710. if GetOption('target') == 'mdk5':
  711. from keil import MDK5Project
  712. MDK5Project('project.uvprojx', Projects)
  713. if GetOption('target') == 'iar':
  714. from iar import IARProject
  715. IARProject('project.ewp', Projects)
  716. if GetOption('target') == 'vs':
  717. from vs import VSProject
  718. VSProject('project.vcproj', Projects, program)
  719. if GetOption('target') == 'vs2012':
  720. from vs2012 import VS2012Project
  721. VS2012Project('project.vcxproj', Projects, program)
  722. if GetOption('target') == 'cb':
  723. from codeblocks import CBProject
  724. CBProject('project.cbp', Projects, program)
  725. if GetOption('target') == 'ua':
  726. from ua import PrepareUA
  727. PrepareUA(Projects, Rtt_Root, str(Dir('#')))
  728. if GetOption('target') == 'vsc':
  729. from vsc import GenerateVSCode
  730. GenerateVSCode(Env)
  731. if GetOption('target') == 'cdk':
  732. from cdk import CDKProject
  733. CDKProject('project.cdkproj', Projects)
  734. if GetOption('target') == 'ses':
  735. from ses import SESProject
  736. SESProject(Env)
  737. if GetOption('target') == 'makefile':
  738. from makefile import TargetMakefile
  739. TargetMakefile(Env)
  740. if GetOption('target') == 'eclipse':
  741. from eclipse import TargetEclipse
  742. TargetEclipse(Env, GetOption('reset-project-config'), GetOption('project-name'))
  743. if GetOption('target') == 'codelite':
  744. from codelite import TargetCodelite
  745. TargetCodelite(Projects, program)
  746. if GetOption('target') == 'cmake':
  747. from cmake import CMakeProject
  748. CMakeProject(Env,Projects)
  749. def EndBuilding(target, program = None):
  750. import rtconfig
  751. need_exit = False
  752. Env['target'] = program
  753. Env['project'] = Projects
  754. if hasattr(rtconfig, 'BSP_LIBRARY_TYPE'):
  755. Env['bsp_lib_type'] = rtconfig.BSP_LIBRARY_TYPE
  756. if hasattr(rtconfig, 'dist_handle'):
  757. Env['dist_handle'] = rtconfig.dist_handle
  758. Env.AddPostAction(target, rtconfig.POST_ACTION)
  759. # Add addition clean files
  760. Clean(target, 'cconfig.h')
  761. Clean(target, 'rtua.py')
  762. Clean(target, 'rtua.pyc')
  763. if GetOption('target'):
  764. GenTargetProject(program)
  765. BSP_ROOT = Dir('#').abspath
  766. if GetOption('make-dist') and program != None:
  767. from mkdist import MkDist
  768. MkDist(program, BSP_ROOT, Rtt_Root, Env)
  769. if GetOption('make-dist-strip') and program != None:
  770. from mkdist import MkDist_Strip
  771. MkDist_Strip(program, BSP_ROOT, Rtt_Root, Env)
  772. need_exit = True
  773. if GetOption('make-dist-ide') and program != None:
  774. from mkdist import MkDist
  775. project_path = GetOption('project-path')
  776. project_name = GetOption('project-name')
  777. if not isinstance(project_path, str) or len(project_path) == 0 :
  778. print("\nwarning : --project-path=your_project_path parameter is required.")
  779. print("\nstop!")
  780. exit(0)
  781. if not isinstance(project_name, str) or len(project_name) == 0:
  782. print("\nwarning : --project-name=your_project_name parameter is required.")
  783. print("\nstop!")
  784. exit(0)
  785. rtt_ide = {'project_path' : project_path, 'project_name' : project_name}
  786. MkDist(program, BSP_ROOT, Rtt_Root, Env, rtt_ide)
  787. need_exit = True
  788. if GetOption('cscope'):
  789. from cscope import CscopeDatabase
  790. CscopeDatabase(Projects)
  791. if not GetOption('help') and not GetOption('target'):
  792. if not os.path.exists(rtconfig.EXEC_PATH):
  793. print ("Error: the toolchain path (" + rtconfig.EXEC_PATH + ") is not exist, please check 'EXEC_PATH' in path or rtconfig.py.")
  794. need_exit = True
  795. if need_exit:
  796. exit(0)
  797. def SrcRemove(src, remove):
  798. if not src:
  799. return
  800. src_bak = src[:]
  801. if type(remove) == type('str'):
  802. if os.path.isabs(remove):
  803. remove = os.path.relpath(remove, GetCurrentDir())
  804. remove = os.path.normpath(remove)
  805. for item in src_bak:
  806. if type(item) == type('str'):
  807. item_str = item
  808. else:
  809. item_str = item.rstr()
  810. if os.path.isabs(item_str):
  811. item_str = os.path.relpath(item_str, GetCurrentDir())
  812. item_str = os.path.normpath(item_str)
  813. if item_str == remove:
  814. src.remove(item)
  815. else:
  816. for remove_item in remove:
  817. remove_str = str(remove_item)
  818. if os.path.isabs(remove_str):
  819. remove_str = os.path.relpath(remove_str, GetCurrentDir())
  820. remove_str = os.path.normpath(remove_str)
  821. for item in src_bak:
  822. if type(item) == type('str'):
  823. item_str = item
  824. else:
  825. item_str = item.rstr()
  826. if os.path.isabs(item_str):
  827. item_str = os.path.relpath(item_str, GetCurrentDir())
  828. item_str = os.path.normpath(item_str)
  829. if item_str == remove_str:
  830. src.remove(item)
  831. def GetVersion():
  832. import SCons.cpp
  833. import string
  834. rtdef = os.path.join(Rtt_Root, 'include', 'rtdef.h')
  835. # parse rtdef.h to get RT-Thread version
  836. prepcessor = PatchedPreProcessor()
  837. f = open(rtdef, 'r')
  838. contents = f.read()
  839. f.close()
  840. prepcessor.process_contents(contents)
  841. def_ns = prepcessor.cpp_namespace
  842. version = int([ch for ch in def_ns['RT_VERSION'] if ch in '0123456789.'])
  843. subversion = int([ch for ch in def_ns['RT_SUBVERSION'] if ch in '0123456789.'])
  844. if 'RT_REVISION' in def_ns:
  845. revision = int([ch for ch in def_ns['RT_REVISION'] if ch in '0123456789.'])
  846. return '%d.%d.%d' % (version, subversion, revision)
  847. return '0.%d.%d' % (version, subversion)
  848. def GlobSubDir(sub_dir, ext_name):
  849. import os
  850. import glob
  851. def glob_source(sub_dir, ext_name):
  852. list = os.listdir(sub_dir)
  853. src = glob.glob(os.path.join(sub_dir, ext_name))
  854. for item in list:
  855. full_subdir = os.path.join(sub_dir, item)
  856. if os.path.isdir(full_subdir):
  857. src += glob_source(full_subdir, ext_name)
  858. return src
  859. dst = []
  860. src = glob_source(sub_dir, ext_name)
  861. for item in src:
  862. dst.append(os.path.relpath(item, sub_dir))
  863. return dst
  864. def PackageSConscript(package):
  865. from package import BuildPackage
  866. return BuildPackage(package)