building.py 35 KB

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