building.py 37 KB

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