building.py 35 KB

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