building.py 38 KB

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