building.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  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. # 2024-04-21 Bernard Add toolchain detection in sdk packages
  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(os.path.join(rtconfig.EXEC_PATH, rtconfig.CC)):
  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. try:
  173. # try to detect toolchains in env
  174. envm = utils.ImportModule('env')
  175. # from env import GetSDKPath
  176. exec_path = envm.GetSDKPath(rtconfig.CC)
  177. if 'gcc' in rtconfig.CC:
  178. exec_path = os.path.join(exec_path, 'bin')
  179. if os.path.exists(exec_path):
  180. print('set CC to ' + exec_path)
  181. rtconfig.EXEC_PATH = exec_path
  182. os.environ['RTT_EXEC_PATH'] = exec_path
  183. except Exception as e:
  184. # detect failed, ignore
  185. pass
  186. exec_path = GetOption('exec-path')
  187. if exec_path:
  188. os.environ['RTT_EXEC_PATH'] = exec_path
  189. utils.ReloadModule(rtconfig) # update environment variables to rtconfig.py
  190. # some env variables have loaded in Environment() of SConstruct before re-load rtconfig.py;
  191. # after update rtconfig.py's variables, those env variables need to synchronize
  192. if exec_prefix:
  193. env['CC'] = rtconfig.CC
  194. env['CXX'] = rtconfig.CXX
  195. env['AS'] = rtconfig.AS
  196. env['AR'] = rtconfig.AR
  197. env['LINK'] = rtconfig.LINK
  198. if exec_path:
  199. env.PrependENVPath('PATH', rtconfig.EXEC_PATH)
  200. env['ASCOM']= env['ASPPCOM']
  201. if GetOption('strict-compiling'):
  202. STRICT_FLAGS = ''
  203. if rtconfig.PLATFORM in ['gcc']:
  204. STRICT_FLAGS += ' -Werror' #-Wextra
  205. env.Append(CFLAGS=STRICT_FLAGS, CXXFLAGS=STRICT_FLAGS)
  206. # add compability with Keil MDK 4.6 which changes the directory of armcc.exe
  207. if rtconfig.PLATFORM in ['armcc', 'armclang']:
  208. if rtconfig.PLATFORM == 'armcc' and not os.path.isfile(os.path.join(rtconfig.EXEC_PATH, 'armcc.exe')):
  209. if rtconfig.EXEC_PATH.find('bin40') > 0:
  210. rtconfig.EXEC_PATH = rtconfig.EXEC_PATH.replace('bin40', 'armcc/bin')
  211. Env['LINKFLAGS'] = Env['LINKFLAGS'].replace('RV31', 'armcc')
  212. # reset AR command flags
  213. env['ARCOM'] = '$AR --create $TARGET $SOURCES'
  214. env['LIBPREFIX'] = ''
  215. env['LIBSUFFIX'] = '.lib'
  216. env['LIBLINKPREFIX'] = ''
  217. env['LIBLINKSUFFIX'] = '.lib'
  218. env['LIBDIRPREFIX'] = '--userlibpath '
  219. elif rtconfig.PLATFORM == 'iccarm':
  220. env['LIBPREFIX'] = ''
  221. env['LIBSUFFIX'] = '.a'
  222. env['LIBLINKPREFIX'] = ''
  223. env['LIBLINKSUFFIX'] = '.a'
  224. env['LIBDIRPREFIX'] = '--search '
  225. # patch for win32 spawn
  226. if env['PLATFORM'] == 'win32':
  227. win32_spawn = Win32Spawn()
  228. win32_spawn.env = env
  229. env['SPAWN'] = win32_spawn.spawn
  230. if env['PLATFORM'] == 'win32':
  231. os.environ['PATH'] = rtconfig.EXEC_PATH + ";" + os.environ['PATH']
  232. else:
  233. os.environ['PATH'] = rtconfig.EXEC_PATH + ":" + os.environ['PATH']
  234. # add program path
  235. env.PrependENVPath('PATH', os.environ['PATH'])
  236. # add rtconfig.h/BSP path into Kernel group
  237. DefineGroup("Kernel", [], [], CPPPATH=[str(Dir('#').abspath)])
  238. # add library build action
  239. act = SCons.Action.Action(BuildLibInstallAction, 'Install compiled library... $TARGET')
  240. bld = Builder(action = act)
  241. Env.Append(BUILDERS = {'BuildLib': bld})
  242. # parse rtconfig.h to get used component
  243. PreProcessor = PatchedPreProcessor()
  244. f = open('rtconfig.h', 'r')
  245. contents = f.read()
  246. f.close()
  247. PreProcessor.process_contents(contents)
  248. BuildOptions = PreProcessor.cpp_namespace
  249. if GetOption('clang-analyzer'):
  250. # perform what scan-build does
  251. env.Replace(
  252. CC = 'ccc-analyzer',
  253. CXX = 'c++-analyzer',
  254. # skip as and link
  255. LINK = 'true',
  256. AS = 'true',)
  257. env["ENV"].update(x for x in os.environ.items() if x[0].startswith("CCC_"))
  258. # only check, don't compile. ccc-analyzer use CCC_CC as the CC.
  259. # fsyntax-only will give us some additional warning messages
  260. env['ENV']['CCC_CC'] = 'clang'
  261. env.Append(CFLAGS=['-fsyntax-only', '-Wall', '-Wno-invalid-source-encoding'])
  262. env['ENV']['CCC_CXX'] = 'clang++'
  263. env.Append(CXXFLAGS=['-fsyntax-only', '-Wall', '-Wno-invalid-source-encoding'])
  264. # remove the POST_ACTION as it will cause meaningless errors(file not
  265. # found or something like that).
  266. rtconfig.POST_ACTION = ''
  267. # auto append '_REENT_SMALL' when using newlib 'nano.specs' option
  268. if rtconfig.PLATFORM in ['gcc'] and str(env['LINKFLAGS']).find('nano.specs') != -1:
  269. env.AppendUnique(CPPDEFINES = ['_REENT_SMALL'])
  270. attach_global_macros = GetOption('global-macros')
  271. if attach_global_macros:
  272. attach_global_macros = attach_global_macros.split(',')
  273. if isinstance(attach_global_macros, list):
  274. for config in attach_global_macros:
  275. if isinstance(config, str):
  276. AddDepend(attach_global_macros)
  277. env.Append(CFLAGS=' -D' + config, CXXFLAGS=' -D' + config, AFLAGS=' -D' + config)
  278. else:
  279. print('--global-macros arguments are illegal!')
  280. else:
  281. print('--global-macros arguments are illegal!')
  282. if GetOption('genconfig'):
  283. from menukconfig import genconfig
  284. genconfig()
  285. exit(0)
  286. if GetOption('stackanalysis'):
  287. from WCS import ThreadStackStaticAnalysis
  288. ThreadStackStaticAnalysis(Env)
  289. exit(0)
  290. if GetOption('menuconfig'):
  291. from menukconfig import menuconfig
  292. menuconfig(Rtt_Root)
  293. exit(0)
  294. if GetOption('pyconfig-silent'):
  295. from menukconfig import guiconfig_silent
  296. guiconfig_silent(Rtt_Root)
  297. exit(0)
  298. elif GetOption('pyconfig'):
  299. from menukconfig import guiconfig
  300. guiconfig(Rtt_Root)
  301. exit(0)
  302. configfn = GetOption('useconfig')
  303. if configfn:
  304. from menukconfig 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. PreBuilding()
  697. objects = one_list(objects)
  698. program = None
  699. # check whether special buildlib option
  700. lib_name = GetOption('buildlib')
  701. if lib_name:
  702. objects = [] # remove all of objects
  703. # build library with special component
  704. for Group in Projects:
  705. if Group['name'] == lib_name:
  706. lib_name = GroupLibName(Group['name'], Env)
  707. if not local_group(Group, objects):
  708. objects = Env.Object(Group['src'])
  709. program = Env.Library(lib_name, objects)
  710. # add library copy action
  711. Env.BuildLib(lib_name, program)
  712. break
  713. else:
  714. # remove source files with local flags setting
  715. for group in Projects:
  716. 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:
  717. for source in group['src']:
  718. for obj in objects:
  719. if source.abspath == obj.abspath or (len(obj.sources) > 0 and source.abspath == obj.sources[0].abspath):
  720. objects.remove(obj)
  721. # re-add the source files to the objects
  722. objects_in_group = []
  723. for group in Projects:
  724. local_group(group, objects_in_group)
  725. # sort seperately, because the data type of
  726. # the members of the two lists are different
  727. objects_in_group = sorted(objects_in_group)
  728. objects = sorted(objects)
  729. objects.append(objects_in_group)
  730. program = Env.Program(target, objects)
  731. EndBuilding(target, program)
  732. def GenTargetProject(program = None):
  733. if GetOption('target') in ['mdk', 'mdk4', 'mdk5']:
  734. from keil import MDK2Project, MDK4Project, MDK5Project, ARMCC_Version
  735. if os.path.isfile('template.uvprojx') and GetOption('target') not in ['mdk4']: # Keil5
  736. MDK5Project(GetOption('project-name') + '.uvprojx', Projects)
  737. print("Keil5 project is generating...")
  738. elif os.path.isfile('template.uvproj') and GetOption('target') not in ['mdk5']: # Keil4
  739. MDK4Project(GetOption('project-name') + '.uvproj', Projects)
  740. print("Keil4 project is generating...")
  741. elif os.path.isfile('template.Uv2') and GetOption('target') not in ['mdk4', 'mdk5']: # Keil2
  742. MDK2Project(GetOption('project-name') + '.Uv2', Projects)
  743. print("Keil2 project is generating...")
  744. else:
  745. print ('No template project file found.')
  746. exit(1)
  747. print("Keil Version: " + ARMCC_Version())
  748. print("Keil-MDK project has generated successfully!")
  749. if GetOption('target') == 'iar':
  750. from iar import IARProject, IARVersion
  751. print("IAR Version: " + IARVersion())
  752. IARProject(GetOption('project-name') + '.ewp', Projects)
  753. print("IAR project has generated successfully!")
  754. if GetOption('target') == 'vs':
  755. from vs import VSProject
  756. VSProject(GetOption('project-name') + '.vcproj', Projects, program)
  757. if GetOption('target') == 'vs2012':
  758. from vs2012 import VS2012Project
  759. VS2012Project(GetOption('project-name') + '.vcxproj', Projects, program)
  760. if GetOption('target') == 'cb':
  761. from codeblocks import CBProject
  762. CBProject(GetOption('project-name') + '.cbp', Projects, program)
  763. if GetOption('target') == 'ua':
  764. from ua import PrepareUA
  765. PrepareUA(Projects, Rtt_Root, str(Dir('#')))
  766. if GetOption('target') == 'vsc':
  767. from vsc import GenerateVSCode
  768. GenerateVSCode(Env)
  769. if GetOption('cmsispack'):
  770. from vscpyocd import GenerateVSCodePyocdConfig
  771. GenerateVSCodePyocdConfig(GetOption('cmsispack'))
  772. if GetOption('target') == 'cdk':
  773. from cdk import CDKProject
  774. CDKProject(GetOption('project-name') + '.cdkproj', Projects)
  775. if GetOption('target') == 'ses':
  776. from ses import SESProject
  777. SESProject(Env)
  778. if GetOption('target') == 'makefile':
  779. from makefile import TargetMakefile
  780. TargetMakefile(Env)
  781. if GetOption('target') == 'eclipse':
  782. from eclipse import TargetEclipse
  783. TargetEclipse(Env, GetOption('reset-project-config'), GetOption('project-name'))
  784. if GetOption('target') == 'codelite':
  785. from codelite import TargetCodelite
  786. TargetCodelite(Projects, program)
  787. if GetOption('target') == 'cmake' or GetOption('target') == 'cmake-armclang':
  788. from cmake import CMakeProject
  789. CMakeProject(Env,Projects)
  790. if GetOption('target') == 'xmake':
  791. from xmake import XMakeProject
  792. XMakeProject(Env, Projects)
  793. if GetOption('target') == 'esp-idf':
  794. from esp_idf import ESPIDFProject
  795. ESPIDFProject(Env, Projects)
  796. def EndBuilding(target, program = None):
  797. from mkdist import MkDist
  798. need_exit = False
  799. Env['target'] = program
  800. Env['project'] = Projects
  801. if hasattr(rtconfig, 'BSP_LIBRARY_TYPE'):
  802. Env['bsp_lib_type'] = rtconfig.BSP_LIBRARY_TYPE
  803. if hasattr(rtconfig, 'dist_handle'):
  804. Env['dist_handle'] = rtconfig.dist_handle
  805. Env.AddPostAction(target, rtconfig.POST_ACTION)
  806. # Add addition clean files
  807. Clean(target, 'cconfig.h')
  808. Clean(target, 'rtua.py')
  809. Clean(target, 'rtua.pyc')
  810. Clean(target, '.sconsign.dblite')
  811. if GetOption('target'):
  812. GenTargetProject(program)
  813. need_exit = True
  814. BSP_ROOT = Dir('#').abspath
  815. project_name = GetOption('project-name')
  816. project_path = GetOption('project-path')
  817. if GetOption('make-dist') and program != None:
  818. MkDist(program, BSP_ROOT, Rtt_Root, Env, project_name, project_path)
  819. need_exit = True
  820. if GetOption('make-dist-ide') and program != None:
  821. import subprocess
  822. if not isinstance(project_path, str) or len(project_path) == 0 :
  823. project_path = os.path.join(BSP_ROOT, 'rt-studio-project')
  824. MkDist(program, BSP_ROOT, Rtt_Root, Env, project_name, project_path)
  825. child = subprocess.Popen('scons --target=eclipse --project-name="{}"'.format(project_name), cwd=project_path, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  826. stdout, stderr = child.communicate()
  827. need_exit = True
  828. if GetOption('cscope'):
  829. from cscope import CscopeDatabase
  830. CscopeDatabase(Projects)
  831. if not GetOption('help') and not GetOption('target'):
  832. if not os.path.exists(rtconfig.EXEC_PATH):
  833. print ("Error: the toolchain path (" + rtconfig.EXEC_PATH + ") is not exist, please check 'EXEC_PATH' in path or rtconfig.py.")
  834. need_exit = True
  835. if need_exit:
  836. exit(0)
  837. def SrcRemove(src, remove):
  838. if not src:
  839. return
  840. src_bak = src[:]
  841. if type(remove) == type('str'):
  842. if os.path.isabs(remove):
  843. remove = os.path.relpath(remove, GetCurrentDir())
  844. remove = os.path.normpath(remove)
  845. for item in src_bak:
  846. if type(item) == type('str'):
  847. item_str = item
  848. else:
  849. item_str = item.rstr()
  850. if os.path.isabs(item_str):
  851. item_str = os.path.relpath(item_str, GetCurrentDir())
  852. item_str = os.path.normpath(item_str)
  853. if item_str == remove:
  854. src.remove(item)
  855. else:
  856. for remove_item in remove:
  857. remove_str = str(remove_item)
  858. if os.path.isabs(remove_str):
  859. remove_str = os.path.relpath(remove_str, GetCurrentDir())
  860. remove_str = os.path.normpath(remove_str)
  861. for item in src_bak:
  862. if type(item) == type('str'):
  863. item_str = item
  864. else:
  865. item_str = item.rstr()
  866. if os.path.isabs(item_str):
  867. item_str = os.path.relpath(item_str, GetCurrentDir())
  868. item_str = os.path.normpath(item_str)
  869. if item_str == remove_str:
  870. src.remove(item)
  871. def GetVersion():
  872. import SCons.cpp
  873. import string
  874. rtdef = os.path.join(Rtt_Root, 'include', 'rtdef.h')
  875. # parse rtdef.h to get RT-Thread version
  876. prepcessor = PatchedPreProcessor()
  877. f = open(rtdef, 'r')
  878. contents = f.read()
  879. f.close()
  880. prepcessor.process_contents(contents)
  881. def_ns = prepcessor.cpp_namespace
  882. version = int([ch for ch in def_ns['RT_VERSION_MAJOR'] if ch in '0123456789.'])
  883. subversion = int([ch for ch in def_ns['RT_VERSION_MINOR'] if ch in '0123456789.'])
  884. if 'RT_VERSION_PATCH' in def_ns:
  885. revision = int([ch for ch in def_ns['RT_VERSION_PATCH'] if ch in '0123456789.'])
  886. return '%d.%d.%d' % (version, subversion, revision)
  887. return '0.%d.%d' % (version, subversion)
  888. def GlobSubDir(sub_dir, ext_name):
  889. import os
  890. import glob
  891. def glob_source(sub_dir, ext_name):
  892. list = os.listdir(sub_dir)
  893. src = glob.glob(os.path.join(sub_dir, ext_name))
  894. for item in list:
  895. full_subdir = os.path.join(sub_dir, item)
  896. if os.path.isdir(full_subdir):
  897. src += glob_source(full_subdir, ext_name)
  898. return src
  899. dst = []
  900. src = glob_source(sub_dir, ext_name)
  901. for item in src:
  902. dst.append(os.path.relpath(item, sub_dir))
  903. return dst
  904. def PackageSConscript(package):
  905. from package import BuildPackage
  906. return BuildPackage(package)