building.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  1. #
  2. # File : building.py
  3. # This file is part of RT-Thread RTOS
  4. # COPYRIGHT (C) 2006 - 2015, RT-Thread Development Team
  5. #
  6. # This program is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation; either version 2 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License along
  17. # with this program; if not, write to the Free Software Foundation, Inc.,
  18. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  19. #
  20. # Change Logs:
  21. # Date Author Notes
  22. # 2015-01-20 Bernard Add copyright information
  23. # 2015-07-25 Bernard Add LOCAL_CCFLAGS/LOCAL_CPPPATH/LOCAL_CPPDEFINES for
  24. # group definition.
  25. #
  26. import os
  27. import sys
  28. import string
  29. import utils
  30. import operator
  31. import rtconfig
  32. import platform
  33. from SCons.Script import *
  34. from utils import _make_path_relative
  35. from mkdist import do_copy_file
  36. from options import AddOptions
  37. BuildOptions = {}
  38. Projects = []
  39. Rtt_Root = ''
  40. Env = None
  41. # SCons PreProcessor patch
  42. def start_handling_includes(self, t=None):
  43. """
  44. Causes the PreProcessor object to start processing #import,
  45. #include and #include_next lines.
  46. This method will be called when a #if, #ifdef, #ifndef or #elif
  47. evaluates True, or when we reach the #else in a #if, #ifdef,
  48. #ifndef or #elif block where a condition already evaluated
  49. False.
  50. """
  51. d = self.dispatch_table
  52. p = self.stack[-1] if self.stack else self.default_table
  53. for k in ('import', 'include', 'include_next', 'define'):
  54. d[k] = p[k]
  55. def stop_handling_includes(self, t=None):
  56. """
  57. Causes the PreProcessor object to stop processing #import,
  58. #include and #include_next lines.
  59. This method will be called when a #if, #ifdef, #ifndef or #elif
  60. evaluates False, or when we reach the #else in a #if, #ifdef,
  61. #ifndef or #elif block where a condition already evaluated True.
  62. """
  63. d = self.dispatch_table
  64. d['import'] = self.do_nothing
  65. d['include'] = self.do_nothing
  66. d['include_next'] = self.do_nothing
  67. d['define'] = self.do_nothing
  68. PatchedPreProcessor = SCons.cpp.PreProcessor
  69. PatchedPreProcessor.start_handling_includes = start_handling_includes
  70. PatchedPreProcessor.stop_handling_includes = stop_handling_includes
  71. class Win32Spawn:
  72. def spawn(self, sh, escape, cmd, args, env):
  73. # deal with the cmd build-in commands which cannot be used in
  74. # subprocess.Popen
  75. if cmd == 'del':
  76. for f in args[1:]:
  77. try:
  78. os.remove(f)
  79. except Exception as e:
  80. print('Error removing file: ' + e)
  81. return -1
  82. return 0
  83. import subprocess
  84. newargs = ' '.join(args[1:])
  85. cmdline = cmd + " " + newargs
  86. # Make sure the env is constructed by strings
  87. _e = dict([(k, str(v)) for k, v in env.items()])
  88. # Windows(tm) CreateProcess does not use the env passed to it to find
  89. # the executables. So we have to modify our own PATH to make Popen
  90. # work.
  91. old_path = os.environ['PATH']
  92. os.environ['PATH'] = _e['PATH']
  93. try:
  94. proc = subprocess.Popen(cmdline, env=_e, shell=False)
  95. except Exception as e:
  96. print('Error in calling command:' + cmdline.split(' ')[0])
  97. print('Exception: ' + os.strerror(e.errno))
  98. if (os.strerror(e.errno) == "No such file or directory"):
  99. print ("\nPlease check Toolchains PATH setting.\n")
  100. return e.errno
  101. finally:
  102. os.environ['PATH'] = old_path
  103. return proc.wait()
  104. def PrepareBuilding(env, root_directory, has_libcpu=False, remove_components = []):
  105. global BuildOptions
  106. global Projects
  107. global Env
  108. global Rtt_Root
  109. AddOptions()
  110. Env = env
  111. Rtt_Root = os.path.abspath(root_directory)
  112. # make an absolute root directory
  113. RTT_ROOT = Rtt_Root
  114. Export('RTT_ROOT')
  115. # set RTT_ROOT in ENV
  116. Env['RTT_ROOT'] = Rtt_Root
  117. os.environ["RTT_DIR"] = Rtt_Root
  118. # set BSP_ROOT in ENV
  119. Env['BSP_ROOT'] = Dir('#').abspath
  120. os.environ["BSP_DIR"] = Dir('#').abspath
  121. # set PKGS_ROOT in ENV
  122. if not "PKGS_DIR" in os.environ:
  123. if "ENV_ROOT" in os.environ:
  124. os.environ["PKGS_DIR"] = os.path.join(os.environ["ENV_ROOT"], "packages")
  125. elif sys.platform == "win32":
  126. os.environ["PKGS_DIR"] = os.path.join(os.environ["USERPROFILE"], ".env/packages")
  127. else:
  128. os.environ["PKGS_DIR"] = os.path.join(os.environ["HOME"], ".env/packages")
  129. sys.path = sys.path + [os.path.join(Rtt_Root, 'tools'), os.path.join(Rtt_Root, 'tools/kconfiglib')]
  130. # {target_name:(CROSS_TOOL, PLATFORM)}
  131. tgt_dict = {'mdk':('keil', 'armcc'),
  132. 'mdk4':('keil', 'armcc'),
  133. 'mdk5':('keil', 'armcc'),
  134. 'iar':('iar', 'iccarm'),
  135. 'vs':('msvc', 'cl'),
  136. 'vs2012':('msvc', 'cl'),
  137. 'vsc' : ('gcc', 'gcc'),
  138. 'cb':('keil', 'armcc'),
  139. 'ua':('gcc', 'gcc'),
  140. 'cdk':('gcc', 'gcc'),
  141. 'makefile':('gcc', 'gcc'),
  142. 'eclipse':('gcc', 'gcc'),
  143. 'ses' : ('gcc', 'gcc'),
  144. 'cmake':('gcc', 'gcc'),
  145. 'cmake-armclang':('keil', 'armclang'),
  146. 'xmake':('gcc', 'gcc'),
  147. 'codelite' : ('gcc', 'gcc'),
  148. 'esp-idf': ('gcc', 'gcc')}
  149. tgt_name = GetOption('target')
  150. if tgt_name:
  151. # --target will change the toolchain settings which clang-analyzer is
  152. # depend on
  153. if GetOption('clang-analyzer'):
  154. print ('--clang-analyzer cannot be used with --target')
  155. sys.exit(1)
  156. SetOption('no_exec', 1)
  157. try:
  158. rtconfig.CROSS_TOOL, rtconfig.PLATFORM = tgt_dict[tgt_name]
  159. # replace the 'RTT_CC' to 'CROSS_TOOL'
  160. os.environ['RTT_CC'] = rtconfig.CROSS_TOOL
  161. except KeyError:
  162. print('Unknow target: '+ tgt_name+'. Avaible targets: ' +', '.join(tgt_dict.keys()))
  163. sys.exit(1)
  164. exec_prefix = GetOption('exec-prefix')
  165. if exec_prefix:
  166. os.environ['RTT_CC_PREFIX'] = exec_prefix
  167. # auto change the 'RTT_EXEC_PATH' when 'rtconfig.EXEC_PATH' get failed
  168. if not os.path.exists(rtconfig.EXEC_PATH):
  169. if 'RTT_EXEC_PATH' in os.environ:
  170. # del the 'RTT_EXEC_PATH' and using the 'EXEC_PATH' setting on rtconfig.py
  171. del os.environ['RTT_EXEC_PATH']
  172. exec_path = GetOption('exec-path')
  173. if exec_path:
  174. os.environ['RTT_EXEC_PATH'] = exec_path
  175. utils.ReloadModule(rtconfig) # update environment variables to rtconfig.py
  176. # some env variables have loaded in Environment() of SConstruct before re-load rtconfig.py;
  177. # after update rtconfig.py's variables, those env variables need to synchronize
  178. if exec_prefix:
  179. env['CC'] = rtconfig.CC
  180. env['CXX'] = rtconfig.CXX
  181. env['AS'] = rtconfig.AS
  182. env['AR'] = rtconfig.AR
  183. env['LINK'] = rtconfig.LINK
  184. if exec_path:
  185. env.PrependENVPath('PATH', rtconfig.EXEC_PATH)
  186. env['ASCOM']= env['ASPPCOM']
  187. if GetOption('strict-compiling'):
  188. STRICT_FLAGS = ''
  189. if rtconfig.PLATFORM in ['gcc']:
  190. STRICT_FLAGS += ' -Werror' #-Wextra
  191. env.Append(CFLAGS=STRICT_FLAGS, CXXFLAGS=STRICT_FLAGS)
  192. # add compability with Keil MDK 4.6 which changes the directory of armcc.exe
  193. if rtconfig.PLATFORM in ['armcc', 'armclang']:
  194. if rtconfig.PLATFORM == 'armcc' and not os.path.isfile(os.path.join(rtconfig.EXEC_PATH, 'armcc.exe')):
  195. if rtconfig.EXEC_PATH.find('bin40') > 0:
  196. rtconfig.EXEC_PATH = rtconfig.EXEC_PATH.replace('bin40', 'armcc/bin')
  197. Env['LINKFLAGS'] = Env['LINKFLAGS'].replace('RV31', 'armcc')
  198. # reset AR command flags
  199. env['ARCOM'] = '$AR --create $TARGET $SOURCES'
  200. env['LIBPREFIX'] = ''
  201. env['LIBSUFFIX'] = '.lib'
  202. env['LIBLINKPREFIX'] = ''
  203. env['LIBLINKSUFFIX'] = '.lib'
  204. env['LIBDIRPREFIX'] = '--userlibpath '
  205. elif rtconfig.PLATFORM == 'iccarm':
  206. env['LIBPREFIX'] = ''
  207. env['LIBSUFFIX'] = '.a'
  208. env['LIBLINKPREFIX'] = ''
  209. env['LIBLINKSUFFIX'] = '.a'
  210. env['LIBDIRPREFIX'] = '--search '
  211. # patch for win32 spawn
  212. if env['PLATFORM'] == 'win32':
  213. win32_spawn = Win32Spawn()
  214. win32_spawn.env = env
  215. env['SPAWN'] = win32_spawn.spawn
  216. if env['PLATFORM'] == 'win32':
  217. os.environ['PATH'] = rtconfig.EXEC_PATH + ";" + os.environ['PATH']
  218. else:
  219. os.environ['PATH'] = rtconfig.EXEC_PATH + ":" + os.environ['PATH']
  220. # add program path
  221. env.PrependENVPath('PATH', os.environ['PATH'])
  222. # add rtconfig.h/BSP path into Kernel group
  223. DefineGroup("Kernel", [], [], CPPPATH=[str(Dir('#').abspath)])
  224. # add library build action
  225. act = SCons.Action.Action(BuildLibInstallAction, 'Install compiled library... $TARGET')
  226. bld = Builder(action = act)
  227. Env.Append(BUILDERS = {'BuildLib': bld})
  228. # parse rtconfig.h to get used component
  229. PreProcessor = PatchedPreProcessor()
  230. f = open('rtconfig.h', 'r')
  231. contents = f.read()
  232. f.close()
  233. PreProcessor.process_contents(contents)
  234. BuildOptions = PreProcessor.cpp_namespace
  235. if GetOption('clang-analyzer'):
  236. # perform what scan-build does
  237. env.Replace(
  238. CC = 'ccc-analyzer',
  239. CXX = 'c++-analyzer',
  240. # skip as and link
  241. LINK = 'true',
  242. AS = 'true',)
  243. env["ENV"].update(x for x in os.environ.items() if x[0].startswith("CCC_"))
  244. # only check, don't compile. ccc-analyzer use CCC_CC as the CC.
  245. # fsyntax-only will give us some additional warning messages
  246. env['ENV']['CCC_CC'] = 'clang'
  247. env.Append(CFLAGS=['-fsyntax-only', '-Wall', '-Wno-invalid-source-encoding'])
  248. env['ENV']['CCC_CXX'] = 'clang++'
  249. env.Append(CXXFLAGS=['-fsyntax-only', '-Wall', '-Wno-invalid-source-encoding'])
  250. # remove the POST_ACTION as it will cause meaningless errors(file not
  251. # found or something like that).
  252. rtconfig.POST_ACTION = ''
  253. # auto append '_REENT_SMALL' when using newlib 'nano.specs' option
  254. if rtconfig.PLATFORM in ['gcc'] and str(env['LINKFLAGS']).find('nano.specs') != -1:
  255. env.AppendUnique(CPPDEFINES = ['_REENT_SMALL'])
  256. attach_global_macros = GetOption('global-macros')
  257. if attach_global_macros:
  258. attach_global_macros = attach_global_macros.split(',')
  259. if isinstance(attach_global_macros, list):
  260. for config in attach_global_macros:
  261. if isinstance(config, str):
  262. AddDepend(attach_global_macros)
  263. env.Append(CFLAGS=' -D' + config, CXXFLAGS=' -D' + config, AFLAGS=' -D' + config)
  264. else:
  265. print('--global-macros arguments are illegal!')
  266. else:
  267. print('--global-macros arguments are illegal!')
  268. if GetOption('genconfig'):
  269. from menukconfig import genconfig
  270. genconfig()
  271. exit(0)
  272. if GetOption('stackanalysis'):
  273. from WCS import ThreadStackStaticAnalysis
  274. ThreadStackStaticAnalysis(Env)
  275. exit(0)
  276. if GetOption('menuconfig'):
  277. from menukconfig import menuconfig
  278. menuconfig(Rtt_Root)
  279. exit(0)
  280. if GetOption('pyconfig-silent'):
  281. from menukconfig import guiconfig_silent
  282. guiconfig_silent(Rtt_Root)
  283. exit(0)
  284. elif GetOption('pyconfig'):
  285. from menukconfig import guiconfig
  286. guiconfig(Rtt_Root)
  287. exit(0)
  288. configfn = GetOption('useconfig')
  289. if configfn:
  290. from menukconfig 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 Preprocessing(input, suffix, output = None, CPPPATH = None):
  416. if hasattr(rtconfig, "CPP") and hasattr(rtconfig, "CPPFLAGS"):
  417. if output == None:
  418. import re
  419. output = re.sub(r'[\.]+.*', suffix, input)
  420. inc = ' '
  421. cpppath = CPPPATH
  422. for cpppath_item in cpppath:
  423. inc += ' -I' + cpppath_item
  424. CPP = rtconfig.EXEC_PATH + '/' + rtconfig.CPP
  425. if not os.path.exists(CPP):
  426. CPP = rtconfig.CPP
  427. CPP += rtconfig.CPPFLAGS
  428. path = GetCurrentDir() + '/'
  429. os.system(CPP + inc + ' ' + path + input + ' -o ' + path + output)
  430. else:
  431. print('CPP tool or CPPFLAGS is undefined in rtconfig!')
  432. def MergeGroup(src_group, group):
  433. src_group['src'] = src_group['src'] + group['src']
  434. src_group['src'].sort()
  435. if 'CFLAGS' in group:
  436. if 'CFLAGS' in src_group:
  437. src_group['CFLAGS'] = src_group['CFLAGS'] + group['CFLAGS']
  438. else:
  439. src_group['CFLAGS'] = group['CFLAGS']
  440. if 'CCFLAGS' in group:
  441. if 'CCFLAGS' in src_group:
  442. src_group['CCFLAGS'] = src_group['CCFLAGS'] + group['CCFLAGS']
  443. else:
  444. src_group['CCFLAGS'] = group['CCFLAGS']
  445. if 'CXXFLAGS' in group:
  446. if 'CXXFLAGS' in src_group:
  447. src_group['CXXFLAGS'] = src_group['CXXFLAGS'] + group['CXXFLAGS']
  448. else:
  449. src_group['CXXFLAGS'] = group['CXXFLAGS']
  450. if 'CPPPATH' in group:
  451. if 'CPPPATH' in src_group:
  452. src_group['CPPPATH'] = src_group['CPPPATH'] + group['CPPPATH']
  453. else:
  454. src_group['CPPPATH'] = group['CPPPATH']
  455. if 'CPPDEFINES' in group:
  456. if 'CPPDEFINES' in src_group:
  457. src_group['CPPDEFINES'] = src_group['CPPDEFINES'] + group['CPPDEFINES']
  458. else:
  459. src_group['CPPDEFINES'] = group['CPPDEFINES']
  460. if 'ASFLAGS' in group:
  461. if 'ASFLAGS' in src_group:
  462. src_group['ASFLAGS'] = src_group['ASFLAGS'] + group['ASFLAGS']
  463. else:
  464. src_group['ASFLAGS'] = group['ASFLAGS']
  465. # for local CCFLAGS/CPPPATH/CPPDEFINES
  466. if 'LOCAL_CFLAGS' in group:
  467. if 'LOCAL_CFLAGS' in src_group:
  468. src_group['LOCAL_CFLAGS'] = src_group['LOCAL_CFLAGS'] + group['LOCAL_CFLAGS']
  469. else:
  470. src_group['LOCAL_CFLAGS'] = group['LOCAL_CFLAGS']
  471. if 'LOCAL_CCFLAGS' in group:
  472. if 'LOCAL_CCFLAGS' in src_group:
  473. src_group['LOCAL_CCFLAGS'] = src_group['LOCAL_CCFLAGS'] + group['LOCAL_CCFLAGS']
  474. else:
  475. src_group['LOCAL_CCFLAGS'] = group['LOCAL_CCFLAGS']
  476. if 'LOCAL_CXXFLAGS' in group:
  477. if 'LOCAL_CXXFLAGS' in src_group:
  478. src_group['LOCAL_CXXFLAGS'] = src_group['LOCAL_CXXFLAGS'] + group['LOCAL_CXXFLAGS']
  479. else:
  480. src_group['LOCAL_CXXFLAGS'] = group['LOCAL_CXXFLAGS']
  481. if 'LOCAL_CPPPATH' in group:
  482. if 'LOCAL_CPPPATH' in src_group:
  483. src_group['LOCAL_CPPPATH'] = src_group['LOCAL_CPPPATH'] + group['LOCAL_CPPPATH']
  484. else:
  485. src_group['LOCAL_CPPPATH'] = group['LOCAL_CPPPATH']
  486. if 'LOCAL_CPPDEFINES' in group:
  487. if 'LOCAL_CPPDEFINES' in src_group:
  488. src_group['LOCAL_CPPDEFINES'] = src_group['LOCAL_CPPDEFINES'] + group['LOCAL_CPPDEFINES']
  489. else:
  490. src_group['LOCAL_CPPDEFINES'] = group['LOCAL_CPPDEFINES']
  491. if 'LINKFLAGS' in group:
  492. if 'LINKFLAGS' in src_group:
  493. src_group['LINKFLAGS'] = src_group['LINKFLAGS'] + group['LINKFLAGS']
  494. else:
  495. src_group['LINKFLAGS'] = group['LINKFLAGS']
  496. if 'LIBS' in group:
  497. if 'LIBS' in src_group:
  498. src_group['LIBS'] = src_group['LIBS'] + group['LIBS']
  499. else:
  500. src_group['LIBS'] = group['LIBS']
  501. if 'LIBPATH' in group:
  502. if 'LIBPATH' in src_group:
  503. src_group['LIBPATH'] = src_group['LIBPATH'] + group['LIBPATH']
  504. else:
  505. src_group['LIBPATH'] = group['LIBPATH']
  506. if 'LOCAL_ASFLAGS' in group:
  507. if 'LOCAL_ASFLAGS' in src_group:
  508. src_group['LOCAL_ASFLAGS'] = src_group['LOCAL_ASFLAGS'] + group['LOCAL_ASFLAGS']
  509. else:
  510. src_group['LOCAL_ASFLAGS'] = group['LOCAL_ASFLAGS']
  511. def _PretreatListParameters(target_list):
  512. while '' in target_list: # remove null strings
  513. target_list.remove('')
  514. while ' ' in target_list: # remove ' '
  515. target_list.remove(' ')
  516. if(len(target_list) == 0):
  517. return False # ignore this list, don't add this list to the parameter
  518. return True # permit to add this list to the parameter
  519. def DefineGroup(name, src, depend, **parameters):
  520. global Env
  521. if not GetDepend(depend):
  522. return []
  523. # find exist group and get path of group
  524. group_path = ''
  525. for g in Projects:
  526. if g['name'] == name:
  527. group_path = g['path']
  528. if group_path == '':
  529. group_path = GetCurrentDir()
  530. group = parameters
  531. group['name'] = name
  532. group['path'] = group_path
  533. if type(src) == type([]):
  534. # remove duplicate elements from list
  535. src = list(set(src))
  536. group['src'] = File(src)
  537. else:
  538. group['src'] = src
  539. if 'CFLAGS' in group:
  540. target = group['CFLAGS']
  541. if len(target) > 0:
  542. Env.AppendUnique(CFLAGS = target)
  543. if 'CCFLAGS' in group:
  544. target = group['CCFLAGS']
  545. if len(target) > 0:
  546. Env.AppendUnique(CCFLAGS = target)
  547. if 'CXXFLAGS' in group:
  548. target = group['CXXFLAGS']
  549. if len(target) > 0:
  550. Env.AppendUnique(CXXFLAGS = target)
  551. if 'CPPPATH' in group:
  552. target = group['CPPPATH']
  553. if _PretreatListParameters(target) == True:
  554. paths = []
  555. for item in target:
  556. paths.append(os.path.abspath(item))
  557. target = paths
  558. Env.AppendUnique(CPPPATH = target)
  559. if 'CPPDEFINES' in group:
  560. target = group['CPPDEFINES']
  561. if _PretreatListParameters(target) == True:
  562. Env.AppendUnique(CPPDEFINES = target)
  563. if 'LINKFLAGS' in group:
  564. target = group['LINKFLAGS']
  565. if len(target) > 0:
  566. Env.AppendUnique(LINKFLAGS = target)
  567. if 'ASFLAGS' in group:
  568. target = group['ASFLAGS']
  569. if len(target) > 0:
  570. Env.AppendUnique(ASFLAGS = target)
  571. if 'LOCAL_CPPPATH' in group:
  572. paths = []
  573. for item in group['LOCAL_CPPPATH']:
  574. paths.append(os.path.abspath(item))
  575. group['LOCAL_CPPPATH'] = paths
  576. if rtconfig.PLATFORM in ['gcc']:
  577. if 'CFLAGS' in group:
  578. group['CFLAGS'] = utils.GCCC99Patch(group['CFLAGS'])
  579. if 'CCFLAGS' in group:
  580. group['CCFLAGS'] = utils.GCCC99Patch(group['CCFLAGS'])
  581. if 'CXXFLAGS' in group:
  582. group['CXXFLAGS'] = utils.GCCC99Patch(group['CXXFLAGS'])
  583. if 'LOCAL_CCFLAGS' in group:
  584. group['LOCAL_CCFLAGS'] = utils.GCCC99Patch(group['LOCAL_CCFLAGS'])
  585. if 'LOCAL_CXXFLAGS' in group:
  586. group['LOCAL_CXXFLAGS'] = utils.GCCC99Patch(group['LOCAL_CXXFLAGS'])
  587. if 'LOCAL_CFLAGS' in group:
  588. group['LOCAL_CFLAGS'] = utils.GCCC99Patch(group['LOCAL_CFLAGS'])
  589. # check whether to clean up library
  590. if GetOption('cleanlib') and os.path.exists(os.path.join(group['path'], GroupLibFullName(name, Env))):
  591. if group['src'] != []:
  592. print('Remove library:'+ GroupLibFullName(name, Env))
  593. fn = os.path.join(group['path'], GroupLibFullName(name, Env))
  594. if os.path.exists(fn):
  595. os.unlink(fn)
  596. if 'LIBS' in group:
  597. target = group['LIBS']
  598. if _PretreatListParameters(target) == True:
  599. Env.AppendUnique(LIBS = target)
  600. if 'LIBPATH' in group:
  601. target = group['LIBPATH']
  602. if _PretreatListParameters(target) == True:
  603. Env.AppendUnique(LIBPATH = target)
  604. # check whether to build group library
  605. if 'LIBRARY' in group:
  606. objs = Env.Library(name, group['src'])
  607. else:
  608. # only add source
  609. objs = group['src']
  610. # merge group
  611. for g in Projects:
  612. if g['name'] == name:
  613. # merge to this group
  614. MergeGroup(g, group)
  615. return objs
  616. def PriorityInsertGroup(groups, group):
  617. length = len(groups)
  618. for i in range(0, length):
  619. if operator.gt(groups[i]['name'].lower(), group['name'].lower()):
  620. groups.insert(i, group)
  621. return
  622. groups.append(group)
  623. # add a new group
  624. PriorityInsertGroup(Projects, group)
  625. return objs
  626. def GetCurrentDir():
  627. conscript = File('SConscript')
  628. fn = conscript.rfile()
  629. name = fn.name
  630. path = os.path.dirname(fn.abspath)
  631. return path
  632. PREBUILDING = []
  633. def RegisterPreBuildingAction(act):
  634. global PREBUILDING
  635. assert callable(act), 'Could only register callable objects. %s received' % repr(act)
  636. PREBUILDING.append(act)
  637. def PreBuilding():
  638. global PREBUILDING
  639. for a in PREBUILDING:
  640. a()
  641. def GroupLibName(name, env):
  642. if rtconfig.PLATFORM in ['armcc']:
  643. return name + '_rvds'
  644. elif rtconfig.PLATFORM in ['gcc']:
  645. return name + '_gcc'
  646. return name
  647. def GroupLibFullName(name, env):
  648. return env['LIBPREFIX'] + GroupLibName(name, env) + env['LIBSUFFIX']
  649. def BuildLibInstallAction(target, source, env):
  650. lib_name = GetOption('buildlib')
  651. for Group in Projects:
  652. if Group['name'] == lib_name:
  653. lib_name = GroupLibFullName(Group['name'], env)
  654. dst_name = os.path.join(Group['path'], lib_name)
  655. print('Copy '+lib_name+' => ' + dst_name)
  656. do_copy_file(lib_name, dst_name)
  657. break
  658. def DoBuilding(target, objects):
  659. # merge all objects into one list
  660. def one_list(l):
  661. lst = []
  662. for item in l:
  663. if type(item) == type([]):
  664. lst += one_list(item)
  665. else:
  666. lst.append(item)
  667. return lst
  668. # handle local group
  669. def local_group(group, objects):
  670. 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:
  671. CFLAGS = Env.get('CFLAGS', '') + group.get('LOCAL_CFLAGS', '')
  672. CCFLAGS = Env.get('CCFLAGS', '') + group.get('LOCAL_CCFLAGS', '')
  673. CXXFLAGS = Env.get('CXXFLAGS', '') + group.get('LOCAL_CXXFLAGS', '')
  674. CPPPATH = list(Env.get('CPPPATH', [''])) + group.get('LOCAL_CPPPATH', [''])
  675. CPPDEFINES = list(Env.get('CPPDEFINES', [''])) + group.get('LOCAL_CPPDEFINES', [''])
  676. ASFLAGS = Env.get('ASFLAGS', '') + group.get('LOCAL_ASFLAGS', '')
  677. for source in group['src']:
  678. objects.append(Env.Object(source, CFLAGS = CFLAGS, CCFLAGS = CCFLAGS, CXXFLAGS = CXXFLAGS, ASFLAGS = ASFLAGS,
  679. CPPPATH = CPPPATH, CPPDEFINES = CPPDEFINES))
  680. return True
  681. return False
  682. PreBuilding()
  683. objects = one_list(objects)
  684. program = None
  685. # check whether special buildlib option
  686. lib_name = GetOption('buildlib')
  687. if lib_name:
  688. objects = [] # remove all of objects
  689. # build library with special component
  690. for Group in Projects:
  691. if Group['name'] == lib_name:
  692. lib_name = GroupLibName(Group['name'], Env)
  693. if not local_group(Group, objects):
  694. objects = Env.Object(Group['src'])
  695. program = Env.Library(lib_name, objects)
  696. # add library copy action
  697. Env.BuildLib(lib_name, program)
  698. break
  699. else:
  700. # remove source files with local flags setting
  701. for group in Projects:
  702. 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:
  703. for source in group['src']:
  704. for obj in objects:
  705. if source.abspath == obj.abspath or (len(obj.sources) > 0 and source.abspath == obj.sources[0].abspath):
  706. objects.remove(obj)
  707. # re-add the source files to the objects
  708. objects_in_group = []
  709. for group in Projects:
  710. local_group(group, objects_in_group)
  711. # sort seperately, because the data type of
  712. # the members of the two lists are different
  713. objects_in_group = sorted(objects_in_group)
  714. objects = sorted(objects)
  715. objects.append(objects_in_group)
  716. program = Env.Program(target, objects)
  717. EndBuilding(target, program)
  718. def GenTargetProject(program = None):
  719. if GetOption('target') in ['mdk', 'mdk4', 'mdk5']:
  720. from keil import MDK2Project, MDK4Project, MDK5Project, ARMCC_Version
  721. if os.path.isfile('template.uvprojx') and GetOption('target') not in ['mdk4']: # Keil5
  722. MDK5Project(GetOption('project-name') + '.uvprojx', Projects)
  723. print("Keil5 project is generating...")
  724. elif os.path.isfile('template.uvproj') and GetOption('target') not in ['mdk5']: # Keil4
  725. MDK4Project(GetOption('project-name') + '.uvproj', Projects)
  726. print("Keil4 project is generating...")
  727. elif os.path.isfile('template.Uv2') and GetOption('target') not in ['mdk4', 'mdk5']: # Keil2
  728. MDK2Project(GetOption('project-name') + '.Uv2', Projects)
  729. print("Keil2 project is generating...")
  730. else:
  731. print ('No template project file found.')
  732. exit(1)
  733. print("Keil Version: " + ARMCC_Version())
  734. print("Keil-MDK project has generated successfully!")
  735. if GetOption('target') == 'iar':
  736. from iar import IARProject, IARVersion
  737. print("IAR Version: " + IARVersion())
  738. IARProject(GetOption('project-name') + '.ewp', Projects)
  739. print("IAR project has generated successfully!")
  740. if GetOption('target') == 'vs':
  741. from vs import VSProject
  742. VSProject(GetOption('project-name') + '.vcproj', Projects, program)
  743. if GetOption('target') == 'vs2012':
  744. from vs2012 import VS2012Project
  745. VS2012Project(GetOption('project-name') + '.vcxproj', Projects, program)
  746. if GetOption('target') == 'cb':
  747. from codeblocks import CBProject
  748. CBProject(GetOption('project-name') + '.cbp', Projects, program)
  749. if GetOption('target') == 'ua':
  750. from ua import PrepareUA
  751. PrepareUA(Projects, Rtt_Root, str(Dir('#')))
  752. if GetOption('target') == 'vsc':
  753. from vsc import GenerateVSCode
  754. GenerateVSCode(Env)
  755. if GetOption('cmsispack'):
  756. from vscpyocd import GenerateVSCodePyocdConfig
  757. GenerateVSCodePyocdConfig(GetOption('cmsispack'))
  758. if GetOption('target') == 'cdk':
  759. from cdk import CDKProject
  760. CDKProject(GetOption('project-name') + '.cdkproj', Projects)
  761. if GetOption('target') == 'ses':
  762. from ses import SESProject
  763. SESProject(Env)
  764. if GetOption('target') == 'makefile':
  765. from makefile import TargetMakefile
  766. TargetMakefile(Env)
  767. if GetOption('target') == 'eclipse':
  768. from eclipse import TargetEclipse
  769. TargetEclipse(Env, GetOption('reset-project-config'), GetOption('project-name'))
  770. if GetOption('target') == 'codelite':
  771. from codelite import TargetCodelite
  772. TargetCodelite(Projects, program)
  773. if GetOption('target') == 'cmake' or GetOption('target') == 'cmake-armclang':
  774. from cmake import CMakeProject
  775. CMakeProject(Env,Projects)
  776. if GetOption('target') == 'xmake':
  777. from xmake import XMakeProject
  778. XMakeProject(Env, Projects)
  779. if GetOption('target') == 'esp-idf':
  780. from esp_idf import ESPIDFProject
  781. ESPIDFProject(Env, Projects)
  782. def EndBuilding(target, program = None):
  783. from mkdist import MkDist
  784. need_exit = False
  785. Env['target'] = program
  786. Env['project'] = Projects
  787. if hasattr(rtconfig, 'BSP_LIBRARY_TYPE'):
  788. Env['bsp_lib_type'] = rtconfig.BSP_LIBRARY_TYPE
  789. if hasattr(rtconfig, 'dist_handle'):
  790. Env['dist_handle'] = rtconfig.dist_handle
  791. Env.AddPostAction(target, rtconfig.POST_ACTION)
  792. # Add addition clean files
  793. Clean(target, 'cconfig.h')
  794. Clean(target, 'rtua.py')
  795. Clean(target, 'rtua.pyc')
  796. Clean(target, '.sconsign.dblite')
  797. if GetOption('target'):
  798. GenTargetProject(program)
  799. need_exit = True
  800. BSP_ROOT = Dir('#').abspath
  801. project_name = GetOption('project-name')
  802. project_path = GetOption('project-path')
  803. if GetOption('make-dist') and program != None:
  804. MkDist(program, BSP_ROOT, Rtt_Root, Env, project_name, project_path)
  805. need_exit = True
  806. if GetOption('make-dist-ide') and program != None:
  807. import subprocess
  808. if not isinstance(project_path, str) or len(project_path) == 0 :
  809. project_path = os.path.join(BSP_ROOT, 'rt-studio-project')
  810. MkDist(program, BSP_ROOT, Rtt_Root, Env, project_name, project_path)
  811. child = subprocess.Popen('scons --target=eclipse --project-name="{}"'.format(project_name), cwd=project_path, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  812. stdout, stderr = child.communicate()
  813. need_exit = True
  814. if GetOption('cscope'):
  815. from cscope import CscopeDatabase
  816. CscopeDatabase(Projects)
  817. if not GetOption('help') and not GetOption('target'):
  818. if not os.path.exists(rtconfig.EXEC_PATH):
  819. print ("Error: the toolchain path (" + rtconfig.EXEC_PATH + ") is not exist, please check 'EXEC_PATH' in path or rtconfig.py.")
  820. need_exit = True
  821. if need_exit:
  822. exit(0)
  823. def SrcRemove(src, remove):
  824. if not src:
  825. return
  826. src_bak = src[:]
  827. if type(remove) == type('str'):
  828. if os.path.isabs(remove):
  829. remove = os.path.relpath(remove, GetCurrentDir())
  830. remove = os.path.normpath(remove)
  831. for item in src_bak:
  832. if type(item) == type('str'):
  833. item_str = item
  834. else:
  835. item_str = item.rstr()
  836. if os.path.isabs(item_str):
  837. item_str = os.path.relpath(item_str, GetCurrentDir())
  838. item_str = os.path.normpath(item_str)
  839. if item_str == remove:
  840. src.remove(item)
  841. else:
  842. for remove_item in remove:
  843. remove_str = str(remove_item)
  844. if os.path.isabs(remove_str):
  845. remove_str = os.path.relpath(remove_str, GetCurrentDir())
  846. remove_str = os.path.normpath(remove_str)
  847. for item in src_bak:
  848. if type(item) == type('str'):
  849. item_str = item
  850. else:
  851. item_str = item.rstr()
  852. if os.path.isabs(item_str):
  853. item_str = os.path.relpath(item_str, GetCurrentDir())
  854. item_str = os.path.normpath(item_str)
  855. if item_str == remove_str:
  856. src.remove(item)
  857. def GetVersion():
  858. import SCons.cpp
  859. import string
  860. rtdef = os.path.join(Rtt_Root, 'include', 'rtdef.h')
  861. # parse rtdef.h to get RT-Thread version
  862. prepcessor = PatchedPreProcessor()
  863. f = open(rtdef, 'r')
  864. contents = f.read()
  865. f.close()
  866. prepcessor.process_contents(contents)
  867. def_ns = prepcessor.cpp_namespace
  868. version = int([ch for ch in def_ns['RT_VERSION_MAJOR'] if ch in '0123456789.'])
  869. subversion = int([ch for ch in def_ns['RT_VERSION_MINOR'] if ch in '0123456789.'])
  870. if 'RT_VERSION_PATCH' in def_ns:
  871. revision = int([ch for ch in def_ns['RT_VERSION_PATCH'] if ch in '0123456789.'])
  872. return '%d.%d.%d' % (version, subversion, revision)
  873. return '0.%d.%d' % (version, subversion)
  874. def GlobSubDir(sub_dir, ext_name):
  875. import os
  876. import glob
  877. def glob_source(sub_dir, ext_name):
  878. list = os.listdir(sub_dir)
  879. src = glob.glob(os.path.join(sub_dir, ext_name))
  880. for item in list:
  881. full_subdir = os.path.join(sub_dir, item)
  882. if os.path.isdir(full_subdir):
  883. src += glob_source(full_subdir, ext_name)
  884. return src
  885. dst = []
  886. src = glob_source(sub_dir, ext_name)
  887. for item in src:
  888. dst.append(os.path.relpath(item, sub_dir))
  889. return dst
  890. def PackageSConscript(package):
  891. from package import BuildPackage
  892. return BuildPackage(package)