building.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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. def _get_filetype(fn):
  12. if fn.rfind('.c') != -1 or fn.rfind('.C') != -1 or fn.rfind('.cpp') != -1:
  13. return 1
  14. # assimble file type
  15. if fn.rfind('.s') != -1 or fn.rfind('.S') != -1:
  16. return 2
  17. # header type
  18. if fn.rfind('.h') != -1:
  19. return 5
  20. # other filetype
  21. return 5
  22. def splitall(loc):
  23. """
  24. Return a list of the path components in loc. (Used by relpath_).
  25. The first item in the list will be either ``os.curdir``, ``os.pardir``, empty,
  26. or the root directory of loc (for example, ``/`` or ``C:\\).
  27. The other items in the list will be strings.
  28. Adapted from *path.py* by Jason Orendorff.
  29. """
  30. parts = []
  31. while loc != os.curdir and loc != os.pardir:
  32. prev = loc
  33. loc, child = os.path.split(prev)
  34. if loc == prev:
  35. break
  36. parts.append(child)
  37. parts.append(loc)
  38. parts.reverse()
  39. return parts
  40. def _make_path_relative(origin, dest):
  41. """
  42. Return the relative path between origin and dest.
  43. If it's not possible return dest.
  44. If they are identical return ``os.curdir``
  45. Adapted from `path.py <http://www.jorendorff.com/articles/python/path/>`_ by Jason Orendorff.
  46. """
  47. origin = os.path.abspath(origin).replace('\\', '/')
  48. dest = os.path.abspath(dest).replace('\\', '/')
  49. #
  50. orig_list = splitall(os.path.normcase(origin))
  51. # Don't normcase dest! We want to preserve the case.
  52. dest_list = splitall(dest)
  53. #
  54. if orig_list[0] != os.path.normcase(dest_list[0]):
  55. # Can't get here from there.
  56. return dest
  57. #
  58. # Find the location where the two paths start to differ.
  59. i = 0
  60. for start_seg, dest_seg in zip(orig_list, dest_list):
  61. if start_seg != os.path.normcase(dest_seg):
  62. break
  63. i += 1
  64. #
  65. # Now i is the point where the two paths diverge.
  66. # Need a certain number of "os.pardir"s to work up
  67. # from the origin to the point of divergence.
  68. segments = [os.pardir] * (len(orig_list) - i)
  69. # Need to add the diverging part of dest_list.
  70. segments += dest_list[i:]
  71. if len(segments) == 0:
  72. # If they happen to be identical, use os.curdir.
  73. return os.curdir
  74. else:
  75. # return os.path.join(*segments).replace('\\', '/')
  76. return os.path.join(*segments)
  77. def IARProject(target, script):
  78. project = file(target, "wb")
  79. project_path = os.path.dirname(os.path.abspath(target))
  80. tree = etree.parse('template.ewp')
  81. tree.write('project.ewp')
  82. def xml_indent(elem, level=0):
  83. i = "\n" + level*" "
  84. if len(elem):
  85. if not elem.text or not elem.text.strip():
  86. elem.text = i + " "
  87. if not elem.tail or not elem.tail.strip():
  88. elem.tail = i
  89. for elem in elem:
  90. xml_indent(elem, level+1)
  91. if not elem.tail or not elem.tail.strip():
  92. elem.tail = i
  93. else:
  94. if level and (not elem.tail or not elem.tail.strip()):
  95. elem.tail = i
  96. def MDK4AddGroup(parent, name, files, project_path):
  97. group = SubElement(parent, 'Group')
  98. group_name = SubElement(group, 'GroupName')
  99. group_name.text = name
  100. for f in files:
  101. fn = f.rfile()
  102. name = fn.name
  103. path = os.path.dirname(fn.abspath)
  104. basename = os.path.basename(path)
  105. path = _make_path_relative(project_path, path)
  106. path = os.path.join(path, name)
  107. files = SubElement(group, 'Files')
  108. file = SubElement(files, 'File')
  109. file_name = SubElement(file, 'FileName')
  110. file_name.text = os.path.basename(path)
  111. file_type = SubElement(file, 'FileType')
  112. file_type.text = '%d' % _get_filetype(name)
  113. file_path = SubElement(file, 'FilePath')
  114. file_path.text = path
  115. def MDK4Project(target, script):
  116. project_path = os.path.dirname(os.path.abspath(target))
  117. tree = etree.parse('template.uvproj')
  118. root = tree.getroot()
  119. out = file(target, 'wb')
  120. out.write('<?xml version="1.0" encoding="UTF-8" standalone="no" ?>\n')
  121. CPPPATH = []
  122. CPPDEFINES = []
  123. LINKFLAGS = ''
  124. CCFLAGS = ''
  125. # add group
  126. groups = tree.find('Targets/Target/Groups')
  127. if not groups:
  128. groups = SubElement(tree.find('Targets/Target'), 'Groups')
  129. for group in script:
  130. group_xml = MDK4AddGroup(groups, group['name'], group['src'], project_path)
  131. # get each include path
  132. if group.has_key('CPPPATH') and group['CPPPATH']:
  133. if CPPPATH:
  134. CPPPATH += group['CPPPATH']
  135. else:
  136. CPPPATH += group['CPPPATH']
  137. # get each group's definitions
  138. if group.has_key('CPPDEFINES') and group['CPPDEFINES']:
  139. if CPPDEFINES:
  140. CPPDEFINES += ';' + group['CPPDEFINES']
  141. else:
  142. CPPDEFINES += group['CPPDEFINES']
  143. # get each group's link flags
  144. if group.has_key('LINKFLAGS') and group['LINKFLAGS']:
  145. if LINKFLAGS:
  146. LINKFLAGS += ' ' + group['LINKFLAGS']
  147. else:
  148. LINKFLAGS += group['LINKFLAGS']
  149. # remove repeat path
  150. paths = set()
  151. for path in CPPPATH:
  152. inc = _make_path_relative(project_path, os.path.normpath(path))
  153. paths.add(inc) #.replace('\\', '/')
  154. paths = [i for i in paths]
  155. CPPPATH = string.join(paths, ';')
  156. definitions = [i for i in set(CPPDEFINES)]
  157. CPPDEFINES = string.join(definitions, ', ')
  158. # write include path, definitions and link flags
  159. IncludePath = tree.find('Targets/Target/TargetOption/TargetArmAds/Cads/VariousControls/IncludePath')
  160. IncludePath.text = CPPPATH
  161. Define = tree.find('Targets/Target/TargetOption/TargetArmAds/Cads/VariousControls/Define')
  162. Define.text = CPPDEFINES
  163. Misc = tree.find('Targets/Target/TargetOption/TargetArmAds/LDads/Misc')
  164. Misc.text = LINKFLAGS
  165. xml_indent(root)
  166. out.write(etree.tostring(root, encoding='utf-8'))
  167. out.close()
  168. def MDKProject(target, script):
  169. template = file('template.Uv2', "rb")
  170. lines = template.readlines()
  171. project = file(target, "wb")
  172. project_path = os.path.dirname(os.path.abspath(target))
  173. line_index = 5
  174. # write group
  175. for group in script:
  176. lines.insert(line_index, 'Group (%s)\r\n' % group['name'])
  177. line_index += 1
  178. lines.insert(line_index, '\r\n')
  179. line_index += 1
  180. # write file
  181. ProjectFiles = []
  182. CPPPATH = []
  183. CPPDEFINES = []
  184. LINKFLAGS = ''
  185. CCFLAGS = ''
  186. # number of groups
  187. group_index = 1
  188. for group in script:
  189. # print group['name']
  190. # get each include path
  191. if group.has_key('CPPPATH') and group['CPPPATH']:
  192. if CPPPATH:
  193. CPPPATH += group['CPPPATH']
  194. else:
  195. CPPPATH += group['CPPPATH']
  196. # get each group's definitions
  197. if group.has_key('CPPDEFINES') and group['CPPDEFINES']:
  198. if CPPDEFINES:
  199. CPPDEFINES += ';' + group['CPPDEFINES']
  200. else:
  201. CPPDEFINES += group['CPPDEFINES']
  202. # get each group's link flags
  203. if group.has_key('LINKFLAGS') and group['LINKFLAGS']:
  204. if LINKFLAGS:
  205. LINKFLAGS += ' ' + group['LINKFLAGS']
  206. else:
  207. LINKFLAGS += group['LINKFLAGS']
  208. # generate file items
  209. for node in group['src']:
  210. fn = node.rfile()
  211. name = fn.name
  212. path = os.path.dirname(fn.abspath)
  213. basename = os.path.basename(path)
  214. path = _make_path_relative(project_path, path)
  215. path = os.path.join(path, name)
  216. if ProjectFiles.count(name):
  217. name = basename + '_' + name
  218. ProjectFiles.append(name)
  219. lines.insert(line_index, 'File %d,%d,<%s><%s>\r\n'
  220. % (group_index, _get_filetype(name), path, name))
  221. line_index += 1
  222. group_index = group_index + 1
  223. lines.insert(line_index, '\r\n')
  224. line_index += 1
  225. # remove repeat path
  226. paths = set()
  227. for path in CPPPATH:
  228. inc = _make_path_relative(project_path, os.path.normpath(path))
  229. paths.add(inc) #.replace('\\', '/')
  230. paths = [i for i in paths]
  231. CPPPATH = string.join(paths, ';')
  232. definitions = [i for i in set(CPPDEFINES)]
  233. CPPDEFINES = string.join(definitions, ', ')
  234. while line_index < len(lines):
  235. if lines[line_index].startswith(' ADSCINCD '):
  236. lines[line_index] = ' ADSCINCD (' + CPPPATH + ')\r\n'
  237. if lines[line_index].startswith(' ADSLDMC ('):
  238. lines[line_index] = ' ADSLDMC (' + LINKFLAGS + ')\r\n'
  239. if lines[line_index].startswith(' ADSCDEFN ('):
  240. lines[line_index] = ' ADSCDEFN (' + CPPDEFINES + ')\r\n'
  241. line_index += 1
  242. # write project
  243. for line in lines:
  244. project.write(line)
  245. project.close()
  246. def BuilderProject(target, script):
  247. project = file(target, "wb")
  248. project_path = os.path.dirname(os.path.abspath(target))
  249. # write file
  250. CPPPATH = []
  251. CPPDEFINES = []
  252. LINKFLAGS = ''
  253. CCFLAGS = ''
  254. # number of groups
  255. group_index = 1
  256. for group in script:
  257. # print group['name']
  258. # generate file items
  259. for node in group['src']:
  260. fn = node.rfile()
  261. name = fn.name
  262. path = os.path.dirname(fn.abspath)
  263. path = _make_path_relative(project_path, path)
  264. path = os.path.join(path, name)
  265. project.write('%s\r\n' % path)
  266. group_index = group_index + 1
  267. project.close()
  268. class Win32Spawn:
  269. def spawn(self, sh, escape, cmd, args, env):
  270. import subprocess
  271. newargs = string.join(args[1:], ' ')
  272. cmdline = cmd + " " + newargs
  273. startupinfo = subprocess.STARTUPINFO()
  274. # startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  275. proc = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  276. stderr=subprocess.PIPE, startupinfo=startupinfo, shell = False)
  277. data, err = proc.communicate()
  278. rv = proc.wait()
  279. if rv:
  280. print err
  281. return rv
  282. if data:
  283. print data
  284. return 0
  285. def PrepareBuilding(env, root_directory, has_libcpu=False):
  286. import SCons.cpp
  287. import rtconfig
  288. global BuildOptions
  289. global Projects
  290. global Env
  291. global Rtt_Root
  292. Env = env
  293. Rtt_Root = root_directory
  294. # patch for win32 spawn
  295. if env['PLATFORM'] == 'win32' and rtconfig.PLATFORM == 'gcc' and sys.version_info < (2, 6, 0):
  296. win32_spawn = Win32Spawn()
  297. win32_spawn.env = env
  298. env['SPAWN'] = win32_spawn.spawn
  299. # add program path
  300. env.PrependENVPath('PATH', rtconfig.EXEC_PATH)
  301. # parse rtconfig.h to get used component
  302. PreProcessor = SCons.cpp.PreProcessor()
  303. f = file('rtconfig.h', 'r')
  304. contents = f.read()
  305. f.close()
  306. PreProcessor.process_contents(contents)
  307. BuildOptions = PreProcessor.cpp_namespace
  308. if (GetDepend('RT_USING_NEWLIB') == False and GetDepend('RT_USING_NOLIBC') == False) and rtconfig.PLATFORM == 'gcc':
  309. AddDepend('RT_USING_MINILIBC')
  310. # add target option
  311. AddOption('--target',
  312. dest='target',
  313. type='string',
  314. help='set target project: mdk')
  315. if GetOption('target'):
  316. SetOption('no_exec', 1)
  317. #env['CCCOMSTR'] = "CC $TARGET"
  318. #env['ASCOMSTR'] = "AS $TARGET"
  319. #env['LINKCOMSTR'] = "Link $TARGET"
  320. # board build script
  321. objs = SConscript('SConscript', variant_dir='build/bsp', duplicate=0)
  322. Repository(Rtt_Root)
  323. # include kernel
  324. objs.append(SConscript('src/SConscript', variant_dir='build/src', duplicate=0))
  325. # include libcpu
  326. if not has_libcpu:
  327. objs.append(SConscript('libcpu/SConscript', variant_dir='build/libcpu', duplicate=0))
  328. # include components
  329. objs.append(SConscript('components/SConscript', variant_dir='build/components', duplicate=0))
  330. return objs
  331. def GetDepend(depend):
  332. building = True
  333. if type(depend) == type('str'):
  334. if not BuildOptions.has_key(depend):
  335. building = False
  336. return building
  337. # for list type depend
  338. for item in depend:
  339. if item != '':
  340. if not BuildOptions.has_key(item):
  341. building = False
  342. return building
  343. def AddDepend(option):
  344. BuildOptions[option] = 1
  345. def DefineGroup(name, src, depend, **parameters):
  346. global Env
  347. if not GetDepend(depend):
  348. return []
  349. group = parameters
  350. group['name'] = name
  351. if type(src) == type(['src1', 'str2']):
  352. group['src'] = File(src)
  353. else:
  354. group['src'] = src
  355. Projects.append(group)
  356. if group.has_key('CCFLAGS'):
  357. Env.Append(CCFLAGS = group['CCFLAGS'])
  358. if group.has_key('CPPPATH'):
  359. Env.Append(CPPPATH = group['CPPPATH'])
  360. if group.has_key('CPPDEFINES'):
  361. Env.Append(CPPDEFINES = group['CPPDEFINES'])
  362. if group.has_key('LINKFLAGS'):
  363. Env.Append(LINKFLAGS = group['LINKFLAGS'])
  364. objs = Env.Object(group['src'])
  365. if group.has_key('LIBRARY'):
  366. objs = Env.Library(name, objs)
  367. return objs
  368. def EndBuilding(target):
  369. import rtconfig
  370. Env.AddPostAction(target, rtconfig.POST_ACTION)
  371. if GetOption('target') == 'iar':
  372. IARProject('project.ewp', Projects)
  373. if GetOption('target') == 'mdk':
  374. MDKProject('project.Uv2', Projects)
  375. if GetOption('target') == 'mdk4':
  376. MDK4Project('project.uvproj', Projects)