building.py 34 KB

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