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