building.py 36 KB

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