building.py 34 KB

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