building.py 34 KB

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