1
0

building.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  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. def PrepareBuilding(env, root_directory, has_libcpu=False, remove_components = []):
  105. global BuildOptions
  106. global Projects
  107. global Env
  108. global Rtt_Root
  109. AddOptions()
  110. Env = env
  111. Rtt_Root = os.path.abspath(root_directory)
  112. # make an absolute root directory
  113. RTT_ROOT = Rtt_Root
  114. Export('RTT_ROOT')
  115. # set RTT_ROOT in ENV
  116. Env['RTT_ROOT'] = Rtt_Root
  117. # set BSP_ROOT in ENV
  118. Env['BSP_ROOT'] = Dir('#').abspath
  119. sys.path = sys.path + [os.path.join(Rtt_Root, 'tools')]
  120. # {target_name:(CROSS_TOOL, PLATFORM)}
  121. tgt_dict = {'mdk':('keil', 'armcc'),
  122. 'mdk4':('keil', 'armcc'),
  123. 'mdk5':('keil', 'armcc'),
  124. 'iar':('iar', 'iccarm'),
  125. 'vs':('msvc', 'cl'),
  126. 'vs2012':('msvc', 'cl'),
  127. 'vsc' : ('gcc', 'gcc'),
  128. 'cb':('keil', 'armcc'),
  129. 'ua':('gcc', 'gcc'),
  130. 'cdk':('gcc', 'gcc'),
  131. 'makefile':('gcc', 'gcc'),
  132. 'eclipse':('gcc', 'gcc'),
  133. 'ses' : ('gcc', 'gcc'),
  134. 'cmake':('gcc', 'gcc'),
  135. 'cmake-armclang':('keil', 'armclang'),
  136. 'xmake':('gcc', 'gcc'),
  137. 'codelite' : ('gcc', 'gcc'),
  138. 'esp-idf': ('gcc', 'gcc')}
  139. tgt_name = GetOption('target')
  140. if tgt_name:
  141. # --target will change the toolchain settings which clang-analyzer is
  142. # depend on
  143. if GetOption('clang-analyzer'):
  144. print ('--clang-analyzer cannot be used with --target')
  145. sys.exit(1)
  146. SetOption('no_exec', 1)
  147. try:
  148. rtconfig.CROSS_TOOL, rtconfig.PLATFORM = tgt_dict[tgt_name]
  149. # replace the 'RTT_CC' to 'CROSS_TOOL'
  150. os.environ['RTT_CC'] = rtconfig.CROSS_TOOL
  151. except KeyError:
  152. print('Unknow target: '+ tgt_name+'. Avaible targets: ' +', '.join(tgt_dict.keys()))
  153. sys.exit(1)
  154. exec_prefix = GetOption('exec-prefix')
  155. if exec_prefix:
  156. os.environ['RTT_CC_PREFIX'] = exec_prefix
  157. # auto change the 'RTT_EXEC_PATH' when 'rtconfig.EXEC_PATH' get failed
  158. if not os.path.exists(rtconfig.EXEC_PATH):
  159. if 'RTT_EXEC_PATH' in os.environ:
  160. # del the 'RTT_EXEC_PATH' and using the 'EXEC_PATH' setting on rtconfig.py
  161. del os.environ['RTT_EXEC_PATH']
  162. exec_path = GetOption('exec-path')
  163. if exec_path:
  164. os.environ['RTT_EXEC_PATH'] = exec_path
  165. utils.ReloadModule(rtconfig) # update environment variables to rtconfig.py
  166. # some env variables have loaded in Environment() of SConstruct before re-load rtconfig.py;
  167. # after update rtconfig.py's variables, those env variables need to synchronize
  168. if exec_prefix:
  169. env['CC'] = rtconfig.CC
  170. env['CXX'] = rtconfig.CXX
  171. env['AS'] = rtconfig.AS
  172. env['AR'] = rtconfig.AR
  173. env['LINK'] = rtconfig.LINK
  174. if exec_path:
  175. env.PrependENVPath('PATH', rtconfig.EXEC_PATH)
  176. if GetOption('strict-compiling'):
  177. STRICT_FLAGS = ''
  178. if rtconfig.PLATFORM in ['gcc']:
  179. STRICT_FLAGS += ' -Werror' #-Wextra
  180. env.Append(CFLAGS=STRICT_FLAGS, CXXFLAGS=STRICT_FLAGS)
  181. # add compability with Keil MDK 4.6 which changes the directory of armcc.exe
  182. if rtconfig.PLATFORM in ['armcc', 'armclang']:
  183. if rtconfig.PLATFORM == 'armcc' and not os.path.isfile(os.path.join(rtconfig.EXEC_PATH, 'armcc.exe')):
  184. if rtconfig.EXEC_PATH.find('bin40') > 0:
  185. rtconfig.EXEC_PATH = rtconfig.EXEC_PATH.replace('bin40', 'armcc/bin')
  186. Env['LINKFLAGS'] = Env['LINKFLAGS'].replace('RV31', 'armcc')
  187. # reset AR command flags
  188. env['ARCOM'] = '$AR --create $TARGET $SOURCES'
  189. env['LIBPREFIX'] = ''
  190. env['LIBSUFFIX'] = '.lib'
  191. env['LIBLINKPREFIX'] = ''
  192. env['LIBLINKSUFFIX'] = '.lib'
  193. env['LIBDIRPREFIX'] = '--userlibpath '
  194. elif rtconfig.PLATFORM == 'iccarm':
  195. env['LIBPREFIX'] = ''
  196. env['LIBSUFFIX'] = '.a'
  197. env['LIBLINKPREFIX'] = ''
  198. env['LIBLINKSUFFIX'] = '.a'
  199. env['LIBDIRPREFIX'] = '--search '
  200. # patch for win32 spawn
  201. if env['PLATFORM'] == 'win32':
  202. win32_spawn = Win32Spawn()
  203. win32_spawn.env = env
  204. env['SPAWN'] = win32_spawn.spawn
  205. if env['PLATFORM'] == 'win32':
  206. os.environ['PATH'] = rtconfig.EXEC_PATH + ";" + os.environ['PATH']
  207. else:
  208. os.environ['PATH'] = rtconfig.EXEC_PATH + ":" + os.environ['PATH']
  209. # add program path
  210. env.PrependENVPath('PATH', os.environ['PATH'])
  211. # add rtconfig.h/BSP path into Kernel group
  212. DefineGroup("Kernel", [], [], CPPPATH=[str(Dir('#').abspath)])
  213. # add library build action
  214. act = SCons.Action.Action(BuildLibInstallAction, 'Install compiled library... $TARGET')
  215. bld = Builder(action = act)
  216. Env.Append(BUILDERS = {'BuildLib': bld})
  217. # parse rtconfig.h to get used component
  218. PreProcessor = PatchedPreProcessor()
  219. f = open('rtconfig.h', 'r')
  220. contents = f.read()
  221. f.close()
  222. PreProcessor.process_contents(contents)
  223. BuildOptions = PreProcessor.cpp_namespace
  224. if GetOption('clang-analyzer'):
  225. # perform what scan-build does
  226. env.Replace(
  227. CC = 'ccc-analyzer',
  228. CXX = 'c++-analyzer',
  229. # skip as and link
  230. LINK = 'true',
  231. AS = 'true',)
  232. env["ENV"].update(x for x in os.environ.items() if x[0].startswith("CCC_"))
  233. # only check, don't compile. ccc-analyzer use CCC_CC as the CC.
  234. # fsyntax-only will give us some additional warning messages
  235. env['ENV']['CCC_CC'] = 'clang'
  236. env.Append(CFLAGS=['-fsyntax-only', '-Wall', '-Wno-invalid-source-encoding'])
  237. env['ENV']['CCC_CXX'] = 'clang++'
  238. env.Append(CXXFLAGS=['-fsyntax-only', '-Wall', '-Wno-invalid-source-encoding'])
  239. # remove the POST_ACTION as it will cause meaningless errors(file not
  240. # found or something like that).
  241. rtconfig.POST_ACTION = ''
  242. # auto append '_REENT_SMALL' when using newlib 'nano.specs' option
  243. if rtconfig.PLATFORM in ['gcc'] and str(env['LINKFLAGS']).find('nano.specs') != -1:
  244. env.AppendUnique(CPPDEFINES = ['_REENT_SMALL'])
  245. add_rtconfig = GetOption('add_rtconfig')
  246. if add_rtconfig:
  247. add_rtconfig = add_rtconfig.split(',')
  248. if isinstance(add_rtconfig, list):
  249. for config in add_rtconfig:
  250. if isinstance(config, str):
  251. AddDepend(add_rtconfig)
  252. env.Append(CFLAGS=' -D' + config, CXXFLAGS=' -D' + config, AFLAGS=' -D' + config)
  253. else:
  254. print('add_rtconfig arguements are illegal!')
  255. else:
  256. print('add_rtconfig arguements are illegal!')
  257. if GetOption('genconfig'):
  258. from genconf import genconfig
  259. genconfig()
  260. exit(0)
  261. if GetOption('stackanalysis'):
  262. from WCS import ThreadStackStaticAnalysis
  263. ThreadStackStaticAnalysis(Env)
  264. exit(0)
  265. if platform.system() != 'Windows':
  266. if GetOption('menuconfig'):
  267. from menuconfig import menuconfig
  268. menuconfig(Rtt_Root)
  269. exit(0)
  270. if GetOption('pyconfig_silent'):
  271. from menuconfig import guiconfig_silent
  272. guiconfig_silent(Rtt_Root)
  273. exit(0)
  274. elif GetOption('pyconfig'):
  275. from menuconfig import guiconfig
  276. guiconfig(Rtt_Root)
  277. exit(0)
  278. configfn = GetOption('useconfig')
  279. if configfn:
  280. from menuconfig import mk_rtconfig
  281. 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. if isinstance(option, str):
  396. BuildOptions[option] = 1
  397. elif isinstance(option, list):
  398. for obj in option:
  399. if isinstance(obj, str):
  400. BuildOptions[obj] = 1
  401. else:
  402. print('AddDepend arguements are illegal!')
  403. else:
  404. print('AddDepend arguements are illegal!')
  405. def Preprocessing(input, suffix, output = None, CPPPATH = None):
  406. if hasattr(rtconfig, "CPP") and hasattr(rtconfig, "CPPFLAGS"):
  407. if output == None:
  408. import re
  409. output = re.sub(r'[\.]+.*', suffix, input)
  410. inc = ' '
  411. cpppath = CPPPATH
  412. for cpppath_item in cpppath:
  413. inc += ' -I' + cpppath_item
  414. CPP = rtconfig.EXEC_PATH + '/' + rtconfig.CPP
  415. if not os.path.exists(CPP):
  416. CPP = rtconfig.CPP
  417. CPP += rtconfig.CPPFLAGS
  418. path = GetCurrentDir() + '/'
  419. os.system(CPP + inc + ' ' + path + input + ' -o ' + path + output)
  420. else:
  421. print('CPP tool or CPPFLAGS is undefined in rtconfig!')
  422. def MergeGroup(src_group, group):
  423. src_group['src'] = src_group['src'] + group['src']
  424. src_group['src'].sort()
  425. if 'CFLAGS' in group:
  426. if 'CFLAGS' in src_group:
  427. src_group['CFLAGS'] = src_group['CFLAGS'] + group['CFLAGS']
  428. else:
  429. src_group['CFLAGS'] = group['CFLAGS']
  430. if 'CCFLAGS' in group:
  431. if 'CCFLAGS' in src_group:
  432. src_group['CCFLAGS'] = src_group['CCFLAGS'] + group['CCFLAGS']
  433. else:
  434. src_group['CCFLAGS'] = group['CCFLAGS']
  435. if 'CXXFLAGS' in group:
  436. if 'CXXFLAGS' in src_group:
  437. src_group['CXXFLAGS'] = src_group['CXXFLAGS'] + group['CXXFLAGS']
  438. else:
  439. src_group['CXXFLAGS'] = group['CXXFLAGS']
  440. if 'CPPPATH' in group:
  441. if 'CPPPATH' in src_group:
  442. src_group['CPPPATH'] = src_group['CPPPATH'] + group['CPPPATH']
  443. else:
  444. src_group['CPPPATH'] = group['CPPPATH']
  445. if 'CPPDEFINES' in group:
  446. if 'CPPDEFINES' in src_group:
  447. src_group['CPPDEFINES'] = src_group['CPPDEFINES'] + group['CPPDEFINES']
  448. else:
  449. src_group['CPPDEFINES'] = group['CPPDEFINES']
  450. if 'ASFLAGS' in group:
  451. if 'ASFLAGS' in src_group:
  452. src_group['ASFLAGS'] = src_group['ASFLAGS'] + group['ASFLAGS']
  453. else:
  454. src_group['ASFLAGS'] = group['ASFLAGS']
  455. # for local CCFLAGS/CPPPATH/CPPDEFINES
  456. if 'LOCAL_CFLAGS' in group:
  457. if 'LOCAL_CFLAGS' in src_group:
  458. src_group['LOCAL_CFLAGS'] = src_group['LOCAL_CFLAGS'] + group['LOCAL_CFLAGS']
  459. else:
  460. src_group['LOCAL_CFLAGS'] = group['LOCAL_CFLAGS']
  461. if 'LOCAL_CCFLAGS' in group:
  462. if 'LOCAL_CCFLAGS' in src_group:
  463. src_group['LOCAL_CCFLAGS'] = src_group['LOCAL_CCFLAGS'] + group['LOCAL_CCFLAGS']
  464. else:
  465. src_group['LOCAL_CCFLAGS'] = group['LOCAL_CCFLAGS']
  466. if 'LOCAL_CXXFLAGS' in group:
  467. if 'LOCAL_CXXFLAGS' in src_group:
  468. src_group['LOCAL_CXXFLAGS'] = src_group['LOCAL_CXXFLAGS'] + group['LOCAL_CXXFLAGS']
  469. else:
  470. src_group['LOCAL_CXXFLAGS'] = group['LOCAL_CXXFLAGS']
  471. if 'LOCAL_CPPPATH' in group:
  472. if 'LOCAL_CPPPATH' in src_group:
  473. src_group['LOCAL_CPPPATH'] = src_group['LOCAL_CPPPATH'] + group['LOCAL_CPPPATH']
  474. else:
  475. src_group['LOCAL_CPPPATH'] = group['LOCAL_CPPPATH']
  476. if 'LOCAL_CPPDEFINES' in group:
  477. if 'LOCAL_CPPDEFINES' in src_group:
  478. src_group['LOCAL_CPPDEFINES'] = src_group['LOCAL_CPPDEFINES'] + group['LOCAL_CPPDEFINES']
  479. else:
  480. src_group['LOCAL_CPPDEFINES'] = group['LOCAL_CPPDEFINES']
  481. if 'LINKFLAGS' in group:
  482. if 'LINKFLAGS' in src_group:
  483. src_group['LINKFLAGS'] = src_group['LINKFLAGS'] + group['LINKFLAGS']
  484. else:
  485. src_group['LINKFLAGS'] = group['LINKFLAGS']
  486. if 'LIBS' in group:
  487. if 'LIBS' in src_group:
  488. src_group['LIBS'] = src_group['LIBS'] + group['LIBS']
  489. else:
  490. src_group['LIBS'] = group['LIBS']
  491. if 'LIBPATH' in group:
  492. if 'LIBPATH' in src_group:
  493. src_group['LIBPATH'] = src_group['LIBPATH'] + group['LIBPATH']
  494. else:
  495. src_group['LIBPATH'] = group['LIBPATH']
  496. if 'LOCAL_ASFLAGS' in group:
  497. if 'LOCAL_ASFLAGS' in src_group:
  498. src_group['LOCAL_ASFLAGS'] = src_group['LOCAL_ASFLAGS'] + group['LOCAL_ASFLAGS']
  499. else:
  500. src_group['LOCAL_ASFLAGS'] = group['LOCAL_ASFLAGS']
  501. def _PretreatListParameters(target_list):
  502. while '' in target_list: # remove null strings
  503. target_list.remove('')
  504. while ' ' in target_list: # remove ' '
  505. target_list.remove(' ')
  506. if(len(target_list) == 0):
  507. return False # ignore this list, don't add this list to the parameter
  508. return True # permit to add this list to the parameter
  509. def DefineGroup(name, src, depend, **parameters):
  510. global Env
  511. if not GetDepend(depend):
  512. return []
  513. # find exist group and get path of group
  514. group_path = ''
  515. for g in Projects:
  516. if g['name'] == name:
  517. group_path = g['path']
  518. if group_path == '':
  519. group_path = GetCurrentDir()
  520. group = parameters
  521. group['name'] = name
  522. group['path'] = group_path
  523. if type(src) == type([]):
  524. # remove duplicate elements from list
  525. src = list(set(src))
  526. group['src'] = File(src)
  527. else:
  528. group['src'] = src
  529. if 'CFLAGS' in group:
  530. target = group['CFLAGS']
  531. if len(target) > 0:
  532. Env.AppendUnique(CFLAGS = target)
  533. if 'CCFLAGS' in group:
  534. target = group['CCFLAGS']
  535. if len(target) > 0:
  536. Env.AppendUnique(CCFLAGS = target)
  537. if 'CXXFLAGS' in group:
  538. target = group['CXXFLAGS']
  539. if len(target) > 0:
  540. Env.AppendUnique(CXXFLAGS = target)
  541. if 'CPPPATH' in group:
  542. target = group['CPPPATH']
  543. if _PretreatListParameters(target) == True:
  544. paths = []
  545. for item in target:
  546. paths.append(os.path.abspath(item))
  547. target = paths
  548. Env.AppendUnique(CPPPATH = target)
  549. if 'CPPDEFINES' in group:
  550. target = group['CPPDEFINES']
  551. if _PretreatListParameters(target) == True:
  552. Env.AppendUnique(CPPDEFINES = target)
  553. if 'LINKFLAGS' in group:
  554. target = group['LINKFLAGS']
  555. if len(target) > 0:
  556. Env.AppendUnique(LINKFLAGS = target)
  557. if 'ASFLAGS' in group:
  558. target = group['ASFLAGS']
  559. if len(target) > 0:
  560. Env.AppendUnique(ASFLAGS = target)
  561. if 'LOCAL_CPPPATH' in group:
  562. paths = []
  563. for item in group['LOCAL_CPPPATH']:
  564. paths.append(os.path.abspath(item))
  565. group['LOCAL_CPPPATH'] = paths
  566. if rtconfig.PLATFORM in ['gcc']:
  567. if 'CFLAGS' in group:
  568. group['CFLAGS'] = utils.GCCC99Patch(group['CFLAGS'])
  569. if 'CCFLAGS' in group:
  570. group['CCFLAGS'] = utils.GCCC99Patch(group['CCFLAGS'])
  571. if 'CXXFLAGS' in group:
  572. group['CXXFLAGS'] = utils.GCCC99Patch(group['CXXFLAGS'])
  573. if 'LOCAL_CCFLAGS' in group:
  574. group['LOCAL_CCFLAGS'] = utils.GCCC99Patch(group['LOCAL_CCFLAGS'])
  575. if 'LOCAL_CXXFLAGS' in group:
  576. group['LOCAL_CXXFLAGS'] = utils.GCCC99Patch(group['LOCAL_CXXFLAGS'])
  577. if 'LOCAL_CFLAGS' in group:
  578. group['LOCAL_CFLAGS'] = utils.GCCC99Patch(group['LOCAL_CFLAGS'])
  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. target = group['LIBS']
  588. if _PretreatListParameters(target) == True:
  589. Env.AppendUnique(LIBS = target)
  590. if 'LIBPATH' in group:
  591. target = group['LIBPATH']
  592. if _PretreatListParameters(target) == True:
  593. Env.AppendUnique(LIBPATH = target)
  594. # check whether to build group library
  595. if 'LIBRARY' in group:
  596. objs = Env.Library(name, group['src'])
  597. else:
  598. # only add source
  599. objs = group['src']
  600. # merge group
  601. for g in Projects:
  602. if g['name'] == name:
  603. # merge to this group
  604. MergeGroup(g, group)
  605. return objs
  606. def PriorityInsertGroup(groups, group):
  607. length = len(groups)
  608. for i in range(0, length):
  609. if operator.gt(groups[i]['name'].lower(), group['name'].lower()):
  610. groups.insert(i, group)
  611. return
  612. groups.append(group)
  613. # add a new group
  614. PriorityInsertGroup(Projects, group)
  615. return objs
  616. def GetCurrentDir():
  617. conscript = File('SConscript')
  618. fn = conscript.rfile()
  619. name = fn.name
  620. path = os.path.dirname(fn.abspath)
  621. return path
  622. PREBUILDING = []
  623. def RegisterPreBuildingAction(act):
  624. global PREBUILDING
  625. assert callable(act), 'Could only register callable objects. %s received' % repr(act)
  626. PREBUILDING.append(act)
  627. def PreBuilding():
  628. global PREBUILDING
  629. for a in PREBUILDING:
  630. a()
  631. def GroupLibName(name, env):
  632. if rtconfig.PLATFORM in ['armcc']:
  633. return name + '_rvds'
  634. elif rtconfig.PLATFORM in ['gcc']:
  635. return name + '_gcc'
  636. return name
  637. def GroupLibFullName(name, env):
  638. return env['LIBPREFIX'] + GroupLibName(name, env) + env['LIBSUFFIX']
  639. def BuildLibInstallAction(target, source, env):
  640. lib_name = GetOption('buildlib')
  641. for Group in Projects:
  642. if Group['name'] == lib_name:
  643. lib_name = GroupLibFullName(Group['name'], env)
  644. dst_name = os.path.join(Group['path'], lib_name)
  645. print('Copy '+lib_name+' => ' + dst_name)
  646. do_copy_file(lib_name, dst_name)
  647. break
  648. def DoBuilding(target, objects):
  649. # merge all objects into one list
  650. def one_list(l):
  651. lst = []
  652. for item in l:
  653. if type(item) == type([]):
  654. lst += one_list(item)
  655. else:
  656. lst.append(item)
  657. return lst
  658. # handle local group
  659. def local_group(group, objects):
  660. 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:
  661. CFLAGS = Env.get('CFLAGS', '') + group.get('LOCAL_CFLAGS', '')
  662. CCFLAGS = Env.get('CCFLAGS', '') + group.get('LOCAL_CCFLAGS', '')
  663. CXXFLAGS = Env.get('CXXFLAGS', '') + group.get('LOCAL_CXXFLAGS', '')
  664. CPPPATH = list(Env.get('CPPPATH', [''])) + group.get('LOCAL_CPPPATH', [''])
  665. CPPDEFINES = list(Env.get('CPPDEFINES', [''])) + group.get('LOCAL_CPPDEFINES', [''])
  666. ASFLAGS = Env.get('ASFLAGS', '') + group.get('LOCAL_ASFLAGS', '')
  667. for source in group['src']:
  668. objects.append(Env.Object(source, CFLAGS = CFLAGS, CCFLAGS = CCFLAGS, CXXFLAGS = CXXFLAGS, ASFLAGS = ASFLAGS,
  669. CPPPATH = CPPPATH, CPPDEFINES = CPPDEFINES))
  670. return True
  671. return False
  672. objects = one_list(objects)
  673. program = None
  674. # check whether special buildlib option
  675. lib_name = GetOption('buildlib')
  676. if lib_name:
  677. objects = [] # remove all of objects
  678. # build library with special component
  679. for Group in Projects:
  680. if Group['name'] == lib_name:
  681. lib_name = GroupLibName(Group['name'], Env)
  682. if not local_group(Group, objects):
  683. objects = Env.Object(Group['src'])
  684. program = Env.Library(lib_name, objects)
  685. # add library copy action
  686. Env.BuildLib(lib_name, program)
  687. break
  688. else:
  689. # remove source files with local flags setting
  690. for group in Projects:
  691. 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:
  692. for source in group['src']:
  693. for obj in objects:
  694. if source.abspath == obj.abspath or (len(obj.sources) > 0 and source.abspath == obj.sources[0].abspath):
  695. objects.remove(obj)
  696. # re-add the source files to the objects
  697. objects_in_group = []
  698. for group in Projects:
  699. local_group(group, objects_in_group)
  700. # sort seperately, because the data type of
  701. # the members of the two lists are different
  702. objects_in_group = sorted(objects_in_group)
  703. objects = sorted(objects)
  704. objects.append(objects_in_group)
  705. program = Env.Program(target, objects)
  706. EndBuilding(target, program)
  707. def GenTargetProject(program = None):
  708. if GetOption('target') in ['mdk', 'mdk4', 'mdk5']:
  709. from keil import MDK2Project, MDK4Project, MDK5Project, ARMCC_Version
  710. if os.path.isfile('template.uvprojx') and GetOption('target') not in ['mdk4']: # Keil5
  711. MDK5Project(GetOption('project-name') + '.uvprojx', Projects)
  712. print("Keil5 project is generating...")
  713. elif os.path.isfile('template.uvproj') and GetOption('target') not in ['mdk5']: # Keil4
  714. MDK4Project(GetOption('project-name') + '.uvproj', Projects)
  715. print("Keil4 project is generating...")
  716. elif os.path.isfile('template.Uv2') and GetOption('target') not in ['mdk4', 'mdk5']: # Keil2
  717. MDK2Project(GetOption('project-name') + '.Uv2', Projects)
  718. print("Keil2 project is generating...")
  719. else:
  720. print ('No template project file found.')
  721. exit(1)
  722. print("Keil Version: " + ARMCC_Version())
  723. print("Keil-MDK project has generated successfully!")
  724. if GetOption('target') == 'iar':
  725. from iar import IARProject, IARVersion
  726. print("IAR Version: " + IARVersion())
  727. IARProject(GetOption('project-name') + '.ewp', Projects)
  728. print("IAR project has generated successfully!")
  729. if GetOption('target') == 'vs':
  730. from vs import VSProject
  731. VSProject(GetOption('project-name') + '.vcproj', Projects, program)
  732. if GetOption('target') == 'vs2012':
  733. from vs2012 import VS2012Project
  734. VS2012Project(GetOption('project-name') + '.vcxproj', Projects, program)
  735. if GetOption('target') == 'cb':
  736. from codeblocks import CBProject
  737. CBProject(GetOption('project-name') + '.cbp', Projects, program)
  738. if GetOption('target') == 'ua':
  739. from ua import PrepareUA
  740. PrepareUA(Projects, Rtt_Root, str(Dir('#')))
  741. if GetOption('target') == 'vsc':
  742. from vsc import GenerateVSCode
  743. GenerateVSCode(Env)
  744. if GetOption('cmsispack'):
  745. from vscpyocd import GenerateVSCodePyocdConfig
  746. GenerateVSCodePyocdConfig(GetOption('cmsispack'))
  747. if GetOption('target') == 'cdk':
  748. from cdk import CDKProject
  749. CDKProject(GetOption('project-name') + '.cdkproj', Projects)
  750. if GetOption('target') == 'ses':
  751. from ses import SESProject
  752. SESProject(Env)
  753. if GetOption('target') == 'makefile':
  754. from makefile import TargetMakefile
  755. TargetMakefile(Env)
  756. if GetOption('target') == 'eclipse':
  757. from eclipse import TargetEclipse
  758. TargetEclipse(Env, GetOption('reset-project-config'), GetOption('project-name'))
  759. if GetOption('target') == 'codelite':
  760. from codelite import TargetCodelite
  761. TargetCodelite(Projects, program)
  762. if GetOption('target') == 'cmake' or GetOption('target') == 'cmake-armclang':
  763. from cmake import CMakeProject
  764. CMakeProject(Env,Projects)
  765. if GetOption('target') == 'xmake':
  766. from xmake import XMakeProject
  767. XMakeProject(Env, Projects)
  768. if GetOption('target') == 'esp-idf':
  769. from esp_idf import ESPIDFProject
  770. ESPIDFProject(Env, Projects)
  771. def EndBuilding(target, program = None):
  772. from mkdist import MkDist
  773. need_exit = False
  774. Env['target'] = program
  775. Env['project'] = Projects
  776. if hasattr(rtconfig, 'BSP_LIBRARY_TYPE'):
  777. Env['bsp_lib_type'] = rtconfig.BSP_LIBRARY_TYPE
  778. if hasattr(rtconfig, 'dist_handle'):
  779. Env['dist_handle'] = rtconfig.dist_handle
  780. Env.AddPostAction(target, rtconfig.POST_ACTION)
  781. # Add addition clean files
  782. Clean(target, 'cconfig.h')
  783. Clean(target, 'rtua.py')
  784. Clean(target, 'rtua.pyc')
  785. Clean(target, '.sconsign.dblite')
  786. if GetOption('target'):
  787. GenTargetProject(program)
  788. need_exit = True
  789. BSP_ROOT = Dir('#').abspath
  790. project_name = GetOption('project-name')
  791. project_path = GetOption('project-path')
  792. if GetOption('make-dist') and program != None:
  793. MkDist(program, BSP_ROOT, Rtt_Root, Env, project_name, project_path)
  794. need_exit = True
  795. if GetOption('make-dist-ide') and program != None:
  796. import subprocess
  797. if not isinstance(project_path, str) or len(project_path) == 0 :
  798. project_path = os.path.join(BSP_ROOT, 'rt-studio-project')
  799. MkDist(program, BSP_ROOT, Rtt_Root, Env, project_name, project_path)
  800. child = subprocess.Popen('scons --target=eclipse --project-name="{}"'.format(project_name), cwd=project_path, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  801. stdout, stderr = child.communicate()
  802. need_exit = True
  803. if GetOption('cscope'):
  804. from cscope import CscopeDatabase
  805. CscopeDatabase(Projects)
  806. if not GetOption('help') and not GetOption('target'):
  807. if not os.path.exists(rtconfig.EXEC_PATH):
  808. print ("Error: the toolchain path (" + rtconfig.EXEC_PATH + ") is not exist, please check 'EXEC_PATH' in path or rtconfig.py.")
  809. need_exit = True
  810. if need_exit:
  811. exit(0)
  812. def SrcRemove(src, remove):
  813. if not src:
  814. return
  815. src_bak = src[:]
  816. if type(remove) == type('str'):
  817. if os.path.isabs(remove):
  818. remove = os.path.relpath(remove, GetCurrentDir())
  819. remove = os.path.normpath(remove)
  820. for item in src_bak:
  821. if type(item) == type('str'):
  822. item_str = item
  823. else:
  824. item_str = item.rstr()
  825. if os.path.isabs(item_str):
  826. item_str = os.path.relpath(item_str, GetCurrentDir())
  827. item_str = os.path.normpath(item_str)
  828. if item_str == remove:
  829. src.remove(item)
  830. else:
  831. for remove_item in remove:
  832. remove_str = str(remove_item)
  833. if os.path.isabs(remove_str):
  834. remove_str = os.path.relpath(remove_str, GetCurrentDir())
  835. remove_str = os.path.normpath(remove_str)
  836. for item in src_bak:
  837. if type(item) == type('str'):
  838. item_str = item
  839. else:
  840. item_str = item.rstr()
  841. if os.path.isabs(item_str):
  842. item_str = os.path.relpath(item_str, GetCurrentDir())
  843. item_str = os.path.normpath(item_str)
  844. if item_str == remove_str:
  845. src.remove(item)
  846. def GetVersion():
  847. import SCons.cpp
  848. import string
  849. rtdef = os.path.join(Rtt_Root, 'include', 'rtdef.h')
  850. # parse rtdef.h to get RT-Thread version
  851. prepcessor = PatchedPreProcessor()
  852. f = open(rtdef, 'r')
  853. contents = f.read()
  854. f.close()
  855. prepcessor.process_contents(contents)
  856. def_ns = prepcessor.cpp_namespace
  857. version = int([ch for ch in def_ns['RT_VERSION_MAJOR'] if ch in '0123456789.'])
  858. subversion = int([ch for ch in def_ns['RT_VERSION_MINOR'] if ch in '0123456789.'])
  859. if 'RT_VERSION_PATCH' in def_ns:
  860. revision = int([ch for ch in def_ns['RT_VERSION_PATCH'] if ch in '0123456789.'])
  861. return '%d.%d.%d' % (version, subversion, revision)
  862. return '0.%d.%d' % (version, subversion)
  863. def GlobSubDir(sub_dir, ext_name):
  864. import os
  865. import glob
  866. def glob_source(sub_dir, ext_name):
  867. list = os.listdir(sub_dir)
  868. src = glob.glob(os.path.join(sub_dir, ext_name))
  869. for item in list:
  870. full_subdir = os.path.join(sub_dir, item)
  871. if os.path.isdir(full_subdir):
  872. src += glob_source(full_subdir, ext_name)
  873. return src
  874. dst = []
  875. src = glob_source(sub_dir, ext_name)
  876. for item in src:
  877. dst.append(os.path.relpath(item, sub_dir))
  878. return dst
  879. def PackageSConscript(package):
  880. from package import BuildPackage
  881. return BuildPackage(package)