building.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  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. penv = {}
  350. for key, value in env.iteritems():
  351. penv[key] = str(value)
  352. proc = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  353. stderr=subprocess.PIPE, startupinfo=startupinfo, shell = False, env=penv)
  354. data, err = proc.communicate()
  355. rv = proc.wait()
  356. if data:
  357. print data
  358. if err:
  359. print err
  360. if rv:
  361. return rv
  362. return 0
  363. def PrepareBuilding(env, root_directory, has_libcpu=False):
  364. import SCons.cpp
  365. import rtconfig
  366. global BuildOptions
  367. global Projects
  368. global Env
  369. global Rtt_Root
  370. Env = env
  371. Rtt_Root = root_directory
  372. # patch for win32 spawn
  373. if env['PLATFORM'] == 'win32' and rtconfig.PLATFORM == 'gcc':
  374. win32_spawn = Win32Spawn()
  375. win32_spawn.env = env
  376. env['SPAWN'] = win32_spawn.spawn
  377. # add program path
  378. env.PrependENVPath('PATH', rtconfig.EXEC_PATH)
  379. # parse rtconfig.h to get used component
  380. PreProcessor = SCons.cpp.PreProcessor()
  381. f = file('rtconfig.h', 'r')
  382. contents = f.read()
  383. f.close()
  384. PreProcessor.process_contents(contents)
  385. BuildOptions = PreProcessor.cpp_namespace
  386. # add target option
  387. AddOption('--target',
  388. dest='target',
  389. type='string',
  390. help='set target project: mdk')
  391. #{target_name:(CROSS_TOOL, PLATFORM)}
  392. tgt_dict = {'mdk':('keil', 'armcc'),
  393. 'mdk4':('keil', 'armcc'),
  394. 'iar':('iar', 'iar')}
  395. tgt_name = GetOption('target')
  396. if tgt_name:
  397. SetOption('no_exec', 1)
  398. try:
  399. rtconfig.CROSS_TOOL, rtconfig.PLATFORM = tgt_dict[tgt_name]
  400. except KeyError:
  401. print 'Unknow target: %s. Avaible targets: %s' % \
  402. (tgt_name, ', '.join(tgt_dict.keys()))
  403. sys.exit(1)
  404. elif (GetDepend('RT_USING_NEWLIB') == False and GetDepend('RT_USING_NOLIBC') == False) \
  405. and rtconfig.PLATFORM == 'gcc':
  406. AddDepend('RT_USING_MINILIBC')
  407. #env['CCCOMSTR'] = "CC $TARGET"
  408. #env['ASCOMSTR'] = "AS $TARGET"
  409. #env['LINKCOMSTR'] = "Link $TARGET"
  410. # board build script
  411. objs = SConscript('SConscript', variant_dir='build/bsp', duplicate=0)
  412. Repository(Rtt_Root)
  413. # include kernel
  414. objs.append(SConscript('src/SConscript', variant_dir='build/src', duplicate=0))
  415. # include libcpu
  416. if not has_libcpu:
  417. objs.append(SConscript('libcpu/SConscript', variant_dir='build/libcpu', duplicate=0))
  418. # include components
  419. objs.append(SConscript('components/SConscript', variant_dir='build/components', duplicate=0))
  420. return objs
  421. def PrepareModuleBuilding(env, root_directory):
  422. import SCons.cpp
  423. import rtconfig
  424. global BuildOptions
  425. global Projects
  426. global Env
  427. global Rtt_Root
  428. Env = env
  429. Rtt_Root = root_directory
  430. # add program path
  431. env.PrependENVPath('PATH', rtconfig.EXEC_PATH)
  432. def GetDepend(depend):
  433. building = True
  434. if type(depend) == type('str'):
  435. if not BuildOptions.has_key(depend) or BuildOptions[depend] == 0:
  436. building = False
  437. elif BuildOptions[depend] != '':
  438. return BuildOptions[depend]
  439. return building
  440. # for list type depend
  441. for item in depend:
  442. if item != '':
  443. if not BuildOptions.has_key(item) or BuildOptions[item] == 0:
  444. building = False
  445. return building
  446. def AddDepend(option):
  447. BuildOptions[option] = 1
  448. def MergeGroup(src_group, group):
  449. src_group['src'] = src_group['src'] + group['src']
  450. if group.has_key('CCFLAGS'):
  451. if src_group.has_key('CCFLAGS'):
  452. src_group['CCFLAGS'] = src_group['CCFLAGS'] + group['CCFLAGS']
  453. else:
  454. src_group['CCFLAGS'] = group['CCFLAGS']
  455. if group.has_key('CPPPATH'):
  456. if src_group.has_key('CPPPATH'):
  457. src_group['CPPPATH'] = src_group['CPPPATH'] + group['CPPPATH']
  458. else:
  459. src_group['CPPPATH'] = group['CPPPATH']
  460. if group.has_key('CPPDEFINES'):
  461. if src_group.has_key('CPPDEFINES'):
  462. src_group['CPPDEFINES'] = src_group['CPPDEFINES'] + group['CPPDEFINES']
  463. else:
  464. src_group['CPPDEFINES'] = group['CPPDEFINES']
  465. if group.has_key('LINKFLAGS'):
  466. if src_group.has_key('LINKFLAGS'):
  467. src_group['LINKFLAGS'] = src_group['LINKFLAGS'] + group['LINKFLAGS']
  468. else:
  469. src_group['LINKFLAGS'] = group['LINKFLAGS']
  470. if group.has_key('LIBRARY'):
  471. if src_group['LIBRARY'].has_key('LIBRARY'):
  472. src_group['LIBRARY'] = src_group['LIBRARY'] + group['LIBRARY']
  473. else:
  474. src_group['LIBRARY'] = group['LIBRARY']
  475. def DefineGroup(name, src, depend, **parameters):
  476. global Env
  477. if not GetDepend(depend):
  478. return []
  479. group = parameters
  480. group['name'] = name
  481. if type(src) == type(['src1', 'str2']):
  482. group['src'] = File(src)
  483. else:
  484. group['src'] = src
  485. if group.has_key('CCFLAGS'):
  486. Env.Append(CCFLAGS = group['CCFLAGS'])
  487. if group.has_key('CPPPATH'):
  488. Env.Append(CPPPATH = group['CPPPATH'])
  489. if group.has_key('CPPDEFINES'):
  490. Env.Append(CPPDEFINES = group['CPPDEFINES'])
  491. if group.has_key('LINKFLAGS'):
  492. Env.Append(LINKFLAGS = group['LINKFLAGS'])
  493. objs = Env.Object(group['src'])
  494. if group.has_key('LIBRARY'):
  495. objs = Env.Library(name, objs)
  496. # merge group
  497. for g in Projects:
  498. if g['name'] == name:
  499. # merge to this group
  500. MergeGroup(g, group)
  501. return objs
  502. # add a new group
  503. Projects.append(group)
  504. return objs
  505. def GetCurrentDir():
  506. conscript = File('SConscript')
  507. fn = conscript.rfile()
  508. name = fn.name
  509. path = os.path.dirname(fn.abspath)
  510. return path
  511. def EndBuilding(target):
  512. import rtconfig
  513. Env.AddPostAction(target, rtconfig.POST_ACTION)
  514. if GetOption('target') == 'mdk':
  515. template = os.path.isfile('template.Uv2')
  516. if template:
  517. MDKProject('project.Uv2', Projects)
  518. else:
  519. template = os.path.isfile('template.uvproj')
  520. if template:
  521. MDK4Project('project.uvproj', Projects)
  522. else:
  523. print 'No template project file found.'
  524. if GetOption('target') == 'mdk4':
  525. MDK4Project('project.uvproj', Projects)
  526. if GetOption('target') == 'iar':
  527. IARProject('project.ewp', Projects)
  528. def SrcRemove(src, remove):
  529. if type(src[0]) == type('str'):
  530. for item in src:
  531. if os.path.basename(item) in remove:
  532. src.remove(item)
  533. return
  534. for item in src:
  535. if os.path.basename(item.rstr()) in remove:
  536. src.remove(item)