building.py 35 KB

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