building.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. import os
  2. import sys
  3. import string
  4. import xml.etree.ElementTree as etree
  5. from xml.etree.ElementTree import SubElement
  6. from SCons.Script import *
  7. BuildOptions = {}
  8. Projects = []
  9. Rtt_Root = ''
  10. Env = None
  11. fs_encoding = sys.getfilesystemencoding()
  12. def _get_filetype(fn):
  13. if fn.rfind('.c') != -1 or fn.rfind('.C') != -1 or fn.rfind('.cpp') != -1:
  14. return 1
  15. # assemble file type
  16. if fn.rfind('.s') != -1 or fn.rfind('.S') != -1:
  17. return 2
  18. # header type
  19. if fn.rfind('.h') != -1:
  20. return 5
  21. # other filetype
  22. return 5
  23. def splitall(loc):
  24. """
  25. Return a list of the path components in loc. (Used by relpath_).
  26. The first item in the list will be either ``os.curdir``, ``os.pardir``, empty,
  27. or the root directory of loc (for example, ``/`` or ``C:\\).
  28. The other items in the list will be strings.
  29. Adapted from *path.py* by Jason Orendorff.
  30. """
  31. parts = []
  32. while loc != os.curdir and loc != os.pardir:
  33. prev = loc
  34. loc, child = os.path.split(prev)
  35. if loc == prev:
  36. break
  37. parts.append(child)
  38. parts.append(loc)
  39. parts.reverse()
  40. return parts
  41. def _make_path_relative(origin, dest):
  42. """
  43. Return the relative path between origin and dest.
  44. If it's not possible return dest.
  45. If they are identical return ``os.curdir``
  46. Adapted from `path.py <http://www.jorendorff.com/articles/python/path/>`_ by Jason Orendorff.
  47. """
  48. origin = os.path.abspath(origin).replace('\\', '/')
  49. dest = os.path.abspath(dest).replace('\\', '/')
  50. #
  51. orig_list = splitall(os.path.normcase(origin))
  52. # Don't normcase dest! We want to preserve the case.
  53. dest_list = splitall(dest)
  54. #
  55. if orig_list[0] != os.path.normcase(dest_list[0]):
  56. # Can't get here from there.
  57. return dest
  58. #
  59. # Find the location where the two paths start to differ.
  60. i = 0
  61. for start_seg, dest_seg in zip(orig_list, dest_list):
  62. if start_seg != os.path.normcase(dest_seg):
  63. break
  64. i += 1
  65. #
  66. # Now i is the point where the two paths diverge.
  67. # Need a certain number of "os.pardir"s to work up
  68. # from the origin to the point of divergence.
  69. segments = [os.pardir] * (len(orig_list) - i)
  70. # Need to add the diverging part of dest_list.
  71. segments += dest_list[i:]
  72. if len(segments) == 0:
  73. # If they happen to be identical, use os.curdir.
  74. return os.curdir
  75. else:
  76. # return os.path.join(*segments).replace('\\', '/')
  77. return os.path.join(*segments)
  78. def xml_indent(elem, level=0):
  79. i = "\n" + level*" "
  80. if len(elem):
  81. if not elem.text or not elem.text.strip():
  82. elem.text = i + " "
  83. if not elem.tail or not elem.tail.strip():
  84. elem.tail = i
  85. for elem in elem:
  86. xml_indent(elem, level+1)
  87. if not elem.tail or not elem.tail.strip():
  88. elem.tail = i
  89. else:
  90. if level and (not elem.tail or not elem.tail.strip()):
  91. elem.tail = i
  92. def IARAddGroup(parent, name, files, project_path):
  93. group = SubElement(parent, 'group')
  94. group_name = SubElement(group, 'name')
  95. group_name.text = name
  96. for f in files:
  97. fn = f.rfile()
  98. name = fn.name
  99. path = os.path.dirname(fn.abspath)
  100. basename = os.path.basename(path)
  101. path = _make_path_relative(project_path, path)
  102. path = os.path.join(path, name)
  103. file = SubElement(group, 'file')
  104. file_name = SubElement(file, 'name')
  105. file_name.text = ('$PROJ_DIR$\\' + path).decode(fs_encoding)
  106. iar_workspace = '''<?xml version="1.0" encoding="iso-8859-1"?>
  107. <workspace>
  108. <project>
  109. <path>$WS_DIR$\%s</path>
  110. </project>
  111. <batchBuild/>
  112. </workspace>
  113. '''
  114. def IARWorkspace(target):
  115. # make an workspace
  116. workspace = target.replace('.ewp', '.eww')
  117. out = file(workspace, 'wb')
  118. xml = iar_workspace % target
  119. out.write(xml)
  120. out.close()
  121. def IARProject(target, script):
  122. project_path = os.path.dirname(os.path.abspath(target))
  123. tree = etree.parse('template.ewp')
  124. root = tree.getroot()
  125. out = file(target, 'wb')
  126. CPPPATH = []
  127. CPPDEFINES = []
  128. LINKFLAGS = ''
  129. CCFLAGS = ''
  130. # add group
  131. for group in script:
  132. IARAddGroup(root, group['name'], group['src'], project_path)
  133. # get each include path
  134. if group.has_key('CPPPATH') and group['CPPPATH']:
  135. CPPPATH += group['CPPPATH']
  136. # get each group's definitions
  137. if group.has_key('CPPDEFINES') and group['CPPDEFINES']:
  138. CPPDEFINES += group['CPPDEFINES']
  139. # get each group's link flags
  140. if group.has_key('LINKFLAGS') and group['LINKFLAGS']:
  141. LINKFLAGS += group['LINKFLAGS']
  142. # make relative path
  143. paths = set()
  144. for path in CPPPATH:
  145. inc = _make_path_relative(project_path, os.path.normpath(path))
  146. paths.add(inc) #.replace('\\', '/')
  147. # setting options
  148. options = tree.findall('configuration/settings/data/option')
  149. for option in options:
  150. # print option.text
  151. name = option.find('name')
  152. if name.text == 'CCIncludePath2':
  153. for path in paths:
  154. state = SubElement(option, 'state')
  155. state.text = '$PROJ_DIR$\\' + path
  156. if name.text == 'CCDefines':
  157. for define in CPPDEFINES:
  158. state = SubElement(option, 'state')
  159. state.text = define
  160. xml_indent(root)
  161. out.write(etree.tostring(root, encoding='utf-8'))
  162. out.close()
  163. IARWorkspace(target)
  164. def MDK4AddGroup(ProjectFiles, parent, name, files, project_path):
  165. group = SubElement(parent, 'Group')
  166. group_name = SubElement(group, 'GroupName')
  167. group_name.text = name
  168. for f in files:
  169. fn = f.rfile()
  170. name = fn.name
  171. path = os.path.dirname(fn.abspath)
  172. basename = os.path.basename(path)
  173. path = _make_path_relative(project_path, path)
  174. path = os.path.join(path, name)
  175. files = SubElement(group, 'Files')
  176. file = SubElement(files, 'File')
  177. file_name = SubElement(file, 'FileName')
  178. name = os.path.basename(path)
  179. if ProjectFiles.count(name):
  180. name = basename + '_' + name
  181. ProjectFiles.append(name)
  182. file_name.text = name.decode(fs_encoding)
  183. file_type = SubElement(file, 'FileType')
  184. file_type.text = '%d' % _get_filetype(name)
  185. file_path = SubElement(file, 'FilePath')
  186. file_path.text = path.decode(fs_encoding)
  187. def MDK4Project(target, script):
  188. project_path = os.path.dirname(os.path.abspath(target))
  189. tree = etree.parse('template.uvproj')
  190. root = tree.getroot()
  191. out = file(target, 'wb')
  192. out.write('<?xml version="1.0" encoding="UTF-8" standalone="no" ?>\n')
  193. CPPPATH = []
  194. CPPDEFINES = []
  195. LINKFLAGS = ''
  196. CCFLAGS = ''
  197. ProjectFiles = []
  198. # add group
  199. groups = tree.find('Targets/Target/Groups')
  200. if not groups:
  201. groups = SubElement(tree.find('Targets/Target'), 'Groups')
  202. for group in script:
  203. group_xml = MDK4AddGroup(ProjectFiles, groups, group['name'], group['src'], project_path)
  204. # get each include path
  205. if group.has_key('CPPPATH') and group['CPPPATH']:
  206. if CPPPATH:
  207. CPPPATH += group['CPPPATH']
  208. else:
  209. CPPPATH += group['CPPPATH']
  210. # get each group's definitions
  211. if group.has_key('CPPDEFINES') and group['CPPDEFINES']:
  212. if CPPDEFINES:
  213. CPPDEFINES += group['CPPDEFINES']
  214. else:
  215. CPPDEFINES += group['CPPDEFINES']
  216. # get each group's link flags
  217. if group.has_key('LINKFLAGS') and group['LINKFLAGS']:
  218. if LINKFLAGS:
  219. LINKFLAGS += ' ' + group['LINKFLAGS']
  220. else:
  221. LINKFLAGS += group['LINKFLAGS']
  222. # remove repeat path
  223. paths = set()
  224. for path in CPPPATH:
  225. inc = _make_path_relative(project_path, os.path.normpath(path))
  226. paths.add(inc) #.replace('\\', '/')
  227. paths = [i for i in paths]
  228. paths.sort()
  229. CPPPATH = string.join(paths, ';')
  230. definitions = [i for i in set(CPPDEFINES)]
  231. CPPDEFINES = string.join(definitions, ', ')
  232. # write include path, definitions and link flags
  233. IncludePath = tree.find('Targets/Target/TargetOption/TargetArmAds/Cads/VariousControls/IncludePath')
  234. IncludePath.text = CPPPATH
  235. Define = tree.find('Targets/Target/TargetOption/TargetArmAds/Cads/VariousControls/Define')
  236. Define.text = CPPDEFINES
  237. Misc = tree.find('Targets/Target/TargetOption/TargetArmAds/LDads/Misc')
  238. Misc.text = LINKFLAGS
  239. xml_indent(root)
  240. out.write(etree.tostring(root, encoding='utf-8'))
  241. out.close()
  242. def MDKProject(target, script):
  243. template = file('template.Uv2', "rb")
  244. lines = template.readlines()
  245. project = file(target, "wb")
  246. project_path = os.path.dirname(os.path.abspath(target))
  247. line_index = 5
  248. # write group
  249. for group in script:
  250. lines.insert(line_index, 'Group (%s)\r\n' % group['name'])
  251. line_index += 1
  252. lines.insert(line_index, '\r\n')
  253. line_index += 1
  254. # write file
  255. ProjectFiles = []
  256. CPPPATH = []
  257. CPPDEFINES = []
  258. LINKFLAGS = ''
  259. CCFLAGS = ''
  260. # number of groups
  261. group_index = 1
  262. for group in script:
  263. # print group['name']
  264. # get each include path
  265. if group.has_key('CPPPATH') and group['CPPPATH']:
  266. if CPPPATH:
  267. CPPPATH += group['CPPPATH']
  268. else:
  269. CPPPATH += group['CPPPATH']
  270. # get each group's definitions
  271. if group.has_key('CPPDEFINES') and group['CPPDEFINES']:
  272. if CPPDEFINES:
  273. CPPDEFINES += ';' + group['CPPDEFINES']
  274. else:
  275. CPPDEFINES += group['CPPDEFINES']
  276. # get each group's link flags
  277. if group.has_key('LINKFLAGS') and group['LINKFLAGS']:
  278. if LINKFLAGS:
  279. LINKFLAGS += ' ' + group['LINKFLAGS']
  280. else:
  281. LINKFLAGS += group['LINKFLAGS']
  282. # generate file items
  283. for node in group['src']:
  284. fn = node.rfile()
  285. name = fn.name
  286. path = os.path.dirname(fn.abspath)
  287. basename = os.path.basename(path)
  288. path = _make_path_relative(project_path, path)
  289. path = os.path.join(path, name)
  290. if ProjectFiles.count(name):
  291. name = basename + '_' + name
  292. ProjectFiles.append(name)
  293. lines.insert(line_index, 'File %d,%d,<%s><%s>\r\n'
  294. % (group_index, _get_filetype(name), path, name))
  295. line_index += 1
  296. group_index = group_index + 1
  297. lines.insert(line_index, '\r\n')
  298. line_index += 1
  299. # remove repeat path
  300. paths = set()
  301. for path in CPPPATH:
  302. inc = _make_path_relative(project_path, os.path.normpath(path))
  303. paths.add(inc) #.replace('\\', '/')
  304. paths = [i for i in paths]
  305. CPPPATH = string.join(paths, ';')
  306. definitions = [i for i in set(CPPDEFINES)]
  307. CPPDEFINES = string.join(definitions, ', ')
  308. while line_index < len(lines):
  309. if lines[line_index].startswith(' ADSCINCD '):
  310. lines[line_index] = ' ADSCINCD (' + CPPPATH + ')\r\n'
  311. if lines[line_index].startswith(' ADSLDMC ('):
  312. lines[line_index] = ' ADSLDMC (' + LINKFLAGS + ')\r\n'
  313. if lines[line_index].startswith(' ADSCDEFN ('):
  314. lines[line_index] = ' ADSCDEFN (' + CPPDEFINES + ')\r\n'
  315. line_index += 1
  316. # write project
  317. for line in lines:
  318. project.write(line)
  319. project.close()
  320. def BuilderProject(target, script):
  321. project = file(target, "wb")
  322. project_path = os.path.dirname(os.path.abspath(target))
  323. # write file
  324. CPPPATH = []
  325. CPPDEFINES = []
  326. LINKFLAGS = ''
  327. CCFLAGS = ''
  328. # number of groups
  329. group_index = 1
  330. for group in script:
  331. # print group['name']
  332. # generate file items
  333. for node in group['src']:
  334. fn = node.rfile()
  335. name = fn.name
  336. path = os.path.dirname(fn.abspath)
  337. path = _make_path_relative(project_path, path)
  338. path = os.path.join(path, name)
  339. project.write('%s\r\n' % path)
  340. group_index = group_index + 1
  341. project.close()
  342. class Win32Spawn:
  343. def spawn(self, sh, escape, cmd, args, env):
  344. import subprocess
  345. newargs = string.join(args[1:], ' ')
  346. cmdline = cmd + " " + newargs
  347. startupinfo = subprocess.STARTUPINFO()
  348. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  349. proc = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  350. stderr=subprocess.PIPE, startupinfo=startupinfo, shell = False)
  351. data, err = proc.communicate()
  352. rv = proc.wait()
  353. if err:
  354. print err
  355. if rv:
  356. return rv
  357. if data:
  358. print data
  359. return 0
  360. def PrepareBuilding(env, root_directory, has_libcpu=False):
  361. import SCons.cpp
  362. import rtconfig
  363. global BuildOptions
  364. global Projects
  365. global Env
  366. global Rtt_Root
  367. Env = env
  368. Rtt_Root = root_directory
  369. # patch for win32 spawn
  370. if env['PLATFORM'] == 'win32' and rtconfig.PLATFORM == 'gcc':
  371. win32_spawn = Win32Spawn()
  372. win32_spawn.env = env
  373. env['SPAWN'] = win32_spawn.spawn
  374. # add program path
  375. env.PrependENVPath('PATH', rtconfig.EXEC_PATH)
  376. # parse rtconfig.h to get used component
  377. PreProcessor = SCons.cpp.PreProcessor()
  378. f = file('rtconfig.h', 'r')
  379. contents = f.read()
  380. f.close()
  381. PreProcessor.process_contents(contents)
  382. BuildOptions = PreProcessor.cpp_namespace
  383. # add target option
  384. AddOption('--target',
  385. dest='target',
  386. type='string',
  387. help='set target project: mdk')
  388. #{target_name:(CROSS_TOOL, PLATFORM)}
  389. tgt_dict = {'mdk':('keil', 'armcc'),
  390. 'mdk4':('keil', 'armcc'),
  391. 'iar':('iar', 'iar')}
  392. tgt_name = GetOption('target')
  393. if tgt_name:
  394. SetOption('no_exec', 1)
  395. try:
  396. rtconfig.CROSS_TOOL, rtconfig.PLATFORM = tgt_dict[tgt_name]
  397. except KeyError:
  398. print 'Unknow target: %s. Avaible targets: %s' % \
  399. (tgt_name, ', '.join(tgt_dict.keys()))
  400. sys.exit(1)
  401. elif (GetDepend('RT_USING_NEWLIB') == False and GetDepend('RT_USING_NOLIBC') == False) \
  402. and rtconfig.PLATFORM == 'gcc':
  403. AddDepend('RT_USING_MINILIBC')
  404. #env['CCCOMSTR'] = "CC $TARGET"
  405. #env['ASCOMSTR'] = "AS $TARGET"
  406. #env['LINKCOMSTR'] = "Link $TARGET"
  407. # board build script
  408. objs = SConscript('SConscript', variant_dir='build/bsp', duplicate=0)
  409. Repository(Rtt_Root)
  410. # include kernel
  411. objs.append(SConscript('src/SConscript', variant_dir='build/src', duplicate=0))
  412. # include libcpu
  413. if not has_libcpu:
  414. objs.append(SConscript('libcpu/SConscript', variant_dir='build/libcpu', duplicate=0))
  415. # include components
  416. objs.append(SConscript('components/SConscript', variant_dir='build/components', duplicate=0))
  417. return objs
  418. def PrepareModuleBuilding(env, root_directory):
  419. import SCons.cpp
  420. import rtconfig
  421. global BuildOptions
  422. global Projects
  423. global Env
  424. global Rtt_Root
  425. Env = env
  426. Rtt_Root = root_directory
  427. # add program path
  428. env.PrependENVPath('PATH', rtconfig.EXEC_PATH)
  429. def GetDepend(depend):
  430. building = True
  431. if type(depend) == type('str'):
  432. if not BuildOptions.has_key(depend) or BuildOptions[depend] == 0:
  433. building = False
  434. elif BuildOptions[depend] != '':
  435. return BuildOptions[depend]
  436. return building
  437. # for list type depend
  438. for item in depend:
  439. if item != '':
  440. if not BuildOptions.has_key(item) or BuildOptions[item] == 0:
  441. building = False
  442. return building
  443. def AddDepend(option):
  444. BuildOptions[option] = 1
  445. def MergeGroup(src_group, group):
  446. src_group['src'] = src_group['src'] + group['src']
  447. if group.has_key('CCFLAGS'):
  448. if src_group.has_key('CCFLAGS'):
  449. src_group['CCFLAGS'] = src_group['CCFLAGS'] + group['CCFLAGS']
  450. else:
  451. src_group['CCFLAGS'] = group['CCFLAGS']
  452. if group.has_key('CPPPATH'):
  453. if src_group.has_key('CPPPATH'):
  454. src_group['CPPPATH'] = src_group['CPPPATH'] + group['CPPPATH']
  455. else:
  456. src_group['CPPPATH'] = group['CPPPATH']
  457. if group.has_key('CPPDEFINES'):
  458. if src_group.has_key('CPPDEFINES'):
  459. src_group['CPPDEFINES'] = src_group['CPPDEFINES'] + group['CPPDEFINES']
  460. else:
  461. src_group['CPPDEFINES'] = group['CPPDEFINES']
  462. if group.has_key('LINKFLAGS'):
  463. if src_group.has_key('LINKFLAGS'):
  464. src_group['LINKFLAGS'] = src_group['LINKFLAGS'] + group['LINKFLAGS']
  465. else:
  466. src_group['LINKFLAGS'] = group['LINKFLAGS']
  467. if group.has_key('LIBRARY'):
  468. if src_group['LIBRARY'].has_key('LIBRARY'):
  469. src_group['LIBRARY'] = src_group['LIBRARY'] + group['LIBRARY']
  470. else:
  471. src_group['LIBRARY'] = group['LIBRARY']
  472. def DefineGroup(name, src, depend, **parameters):
  473. global Env
  474. if not GetDepend(depend):
  475. return []
  476. group = parameters
  477. group['name'] = name
  478. if type(src) == type(['src1', 'str2']):
  479. group['src'] = File(src)
  480. else:
  481. group['src'] = src
  482. if group.has_key('CCFLAGS'):
  483. Env.Append(CCFLAGS = group['CCFLAGS'])
  484. if group.has_key('CPPPATH'):
  485. Env.Append(CPPPATH = group['CPPPATH'])
  486. if group.has_key('CPPDEFINES'):
  487. Env.Append(CPPDEFINES = group['CPPDEFINES'])
  488. if group.has_key('LINKFLAGS'):
  489. Env.Append(LINKFLAGS = group['LINKFLAGS'])
  490. objs = Env.Object(group['src'])
  491. if group.has_key('LIBRARY'):
  492. objs = Env.Library(name, objs)
  493. # merge group
  494. for g in Projects:
  495. if g['name'] == name:
  496. # merge to this group
  497. MergeGroup(g, group)
  498. return objs
  499. # add a new group
  500. Projects.append(group)
  501. return objs
  502. def GetCurrentDir():
  503. conscript = File('SConscript')
  504. fn = conscript.rfile()
  505. name = fn.name
  506. path = os.path.dirname(fn.abspath)
  507. return path
  508. def EndBuilding(target):
  509. import rtconfig
  510. Env.AddPostAction(target, rtconfig.POST_ACTION)
  511. if GetOption('target') == 'mdk':
  512. template = os.path.isfile('template.Uv2')
  513. if template:
  514. MDKProject('project.Uv2', Projects)
  515. else:
  516. template = os.path.isfile('template.uvproj')
  517. if template:
  518. MDK4Project('project.uvproj', Projects)
  519. else:
  520. print 'No template project file found.'
  521. if GetOption('target') == 'mdk4':
  522. MDK4Project('project.uvproj', Projects)
  523. if GetOption('target') == 'iar':
  524. IARProject('project.ewp', Projects)
  525. def SrcRemove(src, remove):
  526. if type(src[0]) == type('str'):
  527. for item in src:
  528. if os.path.basename(item) in remove:
  529. src.remove(item)
  530. return
  531. for item in src:
  532. if os.path.basename(item.rstr()) in remove:
  533. src.remove(item)