1
0

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