building.py 33 KB

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