building.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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 xml_indent(elem, level=0):
  78. i = "\n" + level*" "
  79. if len(elem):
  80. if not elem.text or not elem.text.strip():
  81. elem.text = i + " "
  82. if not elem.tail or not elem.tail.strip():
  83. elem.tail = i
  84. for elem in elem:
  85. xml_indent(elem, level+1)
  86. if not elem.tail or not elem.tail.strip():
  87. elem.tail = i
  88. else:
  89. if level and (not elem.tail or not elem.tail.strip()):
  90. elem.tail = i
  91. def IARAddGroup(parent, name, files, project_path):
  92. group = SubElement(parent, 'group')
  93. group_name = SubElement(group, 'name')
  94. group_name.text = name
  95. for f in files:
  96. fn = f.rfile()
  97. name = fn.name
  98. path = os.path.dirname(fn.abspath)
  99. basename = os.path.basename(path)
  100. path = _make_path_relative(project_path, path)
  101. path = os.path.join(path, name)
  102. file = SubElement(group, 'file')
  103. file_name = SubElement(file, 'name')
  104. file_name.text = '$PROJ_DIR$\\' + path
  105. iar_workspace = '''<?xml version="1.0" encoding="iso-8859-1"?>
  106. <workspace>
  107. <project>
  108. <path>$WS_DIR$\%s</path>
  109. </project>
  110. <batchBuild/>
  111. </workspace>
  112. '''
  113. def IARWorkspace(target):
  114. # make an workspace
  115. workspace = target.replace('.ewp', '.eww')
  116. out = file(workspace, 'wb')
  117. xml = iar_workspace % target
  118. out.write(xml)
  119. out.close()
  120. def IARProject(target, script):
  121. project_path = os.path.dirname(os.path.abspath(target))
  122. tree = etree.parse('template.ewp')
  123. root = tree.getroot()
  124. out = file(target, 'wb')
  125. CPPPATH = []
  126. CPPDEFINES = []
  127. LINKFLAGS = ''
  128. CCFLAGS = ''
  129. # add group
  130. for group in script:
  131. IARAddGroup(root, group['name'], group['src'], project_path)
  132. # get each include path
  133. if group.has_key('CPPPATH') and group['CPPPATH']:
  134. CPPPATH += group['CPPPATH']
  135. # get each group's definitions
  136. if group.has_key('CPPDEFINES') and group['CPPDEFINES']:
  137. CPPDEFINES += group['CPPDEFINES']
  138. # get each group's link flags
  139. if group.has_key('LINKFLAGS') and group['LINKFLAGS']:
  140. LINKFLAGS += group['LINKFLAGS']
  141. # make relative path
  142. paths = set()
  143. for path in CPPPATH:
  144. inc = _make_path_relative(project_path, os.path.normpath(path))
  145. paths.add(inc) #.replace('\\', '/')
  146. # setting options
  147. options = tree.findall('configuration/settings/data/option')
  148. for option in options:
  149. # print option.text
  150. name = option.find('name')
  151. if name.text == 'CCIncludePath2':
  152. for path in paths:
  153. state = SubElement(option, 'state')
  154. state.text = '$PROJ_DIR$\\' + path
  155. if name.text == 'CCDefines':
  156. for define in CPPDEFINES:
  157. state = SubElement(option, 'state')
  158. state.text = define
  159. xml_indent(root)
  160. out.write(etree.tostring(root, encoding='utf-8'))
  161. out.close()
  162. IARWorkspace(target)
  163. def MDK4AddGroup(parent, name, files, project_path):
  164. group = SubElement(parent, 'Group')
  165. group_name = SubElement(group, 'GroupName')
  166. group_name.text = name
  167. for f in files:
  168. fn = f.rfile()
  169. name = fn.name
  170. path = os.path.dirname(fn.abspath)
  171. basename = os.path.basename(path)
  172. path = _make_path_relative(project_path, path)
  173. path = os.path.join(path, name)
  174. files = SubElement(group, 'Files')
  175. file = SubElement(files, 'File')
  176. file_name = SubElement(file, 'FileName')
  177. file_name.text = os.path.basename(path)
  178. file_type = SubElement(file, 'FileType')
  179. file_type.text = '%d' % _get_filetype(name)
  180. file_path = SubElement(file, 'FilePath')
  181. file_path.text = path
  182. def MDK4Project(target, script):
  183. project_path = os.path.dirname(os.path.abspath(target))
  184. tree = etree.parse('template.uvproj')
  185. root = tree.getroot()
  186. out = file(target, 'wb')
  187. out.write('<?xml version="1.0" encoding="UTF-8" standalone="no" ?>\n')
  188. CPPPATH = []
  189. CPPDEFINES = []
  190. LINKFLAGS = ''
  191. CCFLAGS = ''
  192. # add group
  193. groups = tree.find('Targets/Target/Groups')
  194. if not groups:
  195. groups = SubElement(tree.find('Targets/Target'), 'Groups')
  196. for group in script:
  197. group_xml = MDK4AddGroup(groups, group['name'], group['src'], project_path)
  198. # get each include path
  199. if group.has_key('CPPPATH') and group['CPPPATH']:
  200. if CPPPATH:
  201. CPPPATH += group['CPPPATH']
  202. else:
  203. CPPPATH += group['CPPPATH']
  204. # get each group's definitions
  205. if group.has_key('CPPDEFINES') and group['CPPDEFINES']:
  206. if CPPDEFINES:
  207. CPPDEFINES += ';' + group['CPPDEFINES']
  208. else:
  209. CPPDEFINES += group['CPPDEFINES']
  210. # get each group's link flags
  211. if group.has_key('LINKFLAGS') and group['LINKFLAGS']:
  212. if LINKFLAGS:
  213. LINKFLAGS += ' ' + group['LINKFLAGS']
  214. else:
  215. LINKFLAGS += group['LINKFLAGS']
  216. # remove repeat path
  217. paths = set()
  218. for path in CPPPATH:
  219. inc = _make_path_relative(project_path, os.path.normpath(path))
  220. paths.add(inc) #.replace('\\', '/')
  221. paths = [i for i in paths]
  222. CPPPATH = string.join(paths, ';')
  223. definitions = [i for i in set(CPPDEFINES)]
  224. CPPDEFINES = string.join(definitions, ', ')
  225. # write include path, definitions and link flags
  226. IncludePath = tree.find('Targets/Target/TargetOption/TargetArmAds/Cads/VariousControls/IncludePath')
  227. IncludePath.text = CPPPATH
  228. Define = tree.find('Targets/Target/TargetOption/TargetArmAds/Cads/VariousControls/Define')
  229. Define.text = CPPDEFINES
  230. Misc = tree.find('Targets/Target/TargetOption/TargetArmAds/LDads/Misc')
  231. Misc.text = LINKFLAGS
  232. xml_indent(root)
  233. out.write(etree.tostring(root, encoding='utf-8'))
  234. out.close()
  235. def MDKProject(target, script):
  236. template = file('template.Uv2', "rb")
  237. lines = template.readlines()
  238. project = file(target, "wb")
  239. project_path = os.path.dirname(os.path.abspath(target))
  240. line_index = 5
  241. # write group
  242. for group in script:
  243. lines.insert(line_index, 'Group (%s)\r\n' % group['name'])
  244. line_index += 1
  245. lines.insert(line_index, '\r\n')
  246. line_index += 1
  247. # write file
  248. ProjectFiles = []
  249. CPPPATH = []
  250. CPPDEFINES = []
  251. LINKFLAGS = ''
  252. CCFLAGS = ''
  253. # number of groups
  254. group_index = 1
  255. for group in script:
  256. # print group['name']
  257. # get each include path
  258. if group.has_key('CPPPATH') and group['CPPPATH']:
  259. if CPPPATH:
  260. CPPPATH += group['CPPPATH']
  261. else:
  262. CPPPATH += group['CPPPATH']
  263. # get each group's definitions
  264. if group.has_key('CPPDEFINES') and group['CPPDEFINES']:
  265. if CPPDEFINES:
  266. CPPDEFINES += ';' + group['CPPDEFINES']
  267. else:
  268. CPPDEFINES += group['CPPDEFINES']
  269. # get each group's link flags
  270. if group.has_key('LINKFLAGS') and group['LINKFLAGS']:
  271. if LINKFLAGS:
  272. LINKFLAGS += ' ' + group['LINKFLAGS']
  273. else:
  274. LINKFLAGS += group['LINKFLAGS']
  275. # generate file items
  276. for node in group['src']:
  277. fn = node.rfile()
  278. name = fn.name
  279. path = os.path.dirname(fn.abspath)
  280. basename = os.path.basename(path)
  281. path = _make_path_relative(project_path, path)
  282. path = os.path.join(path, name)
  283. if ProjectFiles.count(name):
  284. name = basename + '_' + name
  285. ProjectFiles.append(name)
  286. lines.insert(line_index, 'File %d,%d,<%s><%s>\r\n'
  287. % (group_index, _get_filetype(name), path, name))
  288. line_index += 1
  289. group_index = group_index + 1
  290. lines.insert(line_index, '\r\n')
  291. line_index += 1
  292. # remove repeat path
  293. paths = set()
  294. for path in CPPPATH:
  295. inc = _make_path_relative(project_path, os.path.normpath(path))
  296. paths.add(inc) #.replace('\\', '/')
  297. paths = [i for i in paths]
  298. CPPPATH = string.join(paths, ';')
  299. definitions = [i for i in set(CPPDEFINES)]
  300. CPPDEFINES = string.join(definitions, ', ')
  301. while line_index < len(lines):
  302. if lines[line_index].startswith(' ADSCINCD '):
  303. lines[line_index] = ' ADSCINCD (' + CPPPATH + ')\r\n'
  304. if lines[line_index].startswith(' ADSLDMC ('):
  305. lines[line_index] = ' ADSLDMC (' + LINKFLAGS + ')\r\n'
  306. if lines[line_index].startswith(' ADSCDEFN ('):
  307. lines[line_index] = ' ADSCDEFN (' + CPPDEFINES + ')\r\n'
  308. line_index += 1
  309. # write project
  310. for line in lines:
  311. project.write(line)
  312. project.close()
  313. def BuilderProject(target, script):
  314. project = file(target, "wb")
  315. project_path = os.path.dirname(os.path.abspath(target))
  316. # write file
  317. CPPPATH = []
  318. CPPDEFINES = []
  319. LINKFLAGS = ''
  320. CCFLAGS = ''
  321. # number of groups
  322. group_index = 1
  323. for group in script:
  324. # print group['name']
  325. # generate file items
  326. for node in group['src']:
  327. fn = node.rfile()
  328. name = fn.name
  329. path = os.path.dirname(fn.abspath)
  330. path = _make_path_relative(project_path, path)
  331. path = os.path.join(path, name)
  332. project.write('%s\r\n' % path)
  333. group_index = group_index + 1
  334. project.close()
  335. class Win32Spawn:
  336. def spawn(self, sh, escape, cmd, args, env):
  337. import subprocess
  338. newargs = string.join(args[1:], ' ')
  339. cmdline = cmd + " " + newargs
  340. startupinfo = subprocess.STARTUPINFO()
  341. # startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  342. proc = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  343. stderr=subprocess.PIPE, startupinfo=startupinfo, shell = False)
  344. data, err = proc.communicate()
  345. rv = proc.wait()
  346. if rv:
  347. print err
  348. return rv
  349. if data:
  350. print data
  351. return 0
  352. def PrepareBuilding(env, root_directory, has_libcpu=False):
  353. import SCons.cpp
  354. import rtconfig
  355. global BuildOptions
  356. global Projects
  357. global Env
  358. global Rtt_Root
  359. Env = env
  360. Rtt_Root = root_directory
  361. # patch for win32 spawn
  362. if env['PLATFORM'] == 'win32' and rtconfig.PLATFORM == 'gcc' and sys.version_info < (2, 6, 0):
  363. win32_spawn = Win32Spawn()
  364. win32_spawn.env = env
  365. env['SPAWN'] = win32_spawn.spawn
  366. # add program path
  367. env.PrependENVPath('PATH', rtconfig.EXEC_PATH)
  368. # parse rtconfig.h to get used component
  369. PreProcessor = SCons.cpp.PreProcessor()
  370. f = file('rtconfig.h', 'r')
  371. contents = f.read()
  372. f.close()
  373. PreProcessor.process_contents(contents)
  374. BuildOptions = PreProcessor.cpp_namespace
  375. if (GetDepend('RT_USING_NEWLIB') == False and GetDepend('RT_USING_NOLIBC') == False) and rtconfig.PLATFORM == 'gcc':
  376. AddDepend('RT_USING_MINILIBC')
  377. # add target option
  378. AddOption('--target',
  379. dest='target',
  380. type='string',
  381. help='set target project: mdk')
  382. if GetOption('target'):
  383. SetOption('no_exec', 1)
  384. #env['CCCOMSTR'] = "CC $TARGET"
  385. #env['ASCOMSTR'] = "AS $TARGET"
  386. #env['LINKCOMSTR'] = "Link $TARGET"
  387. # board build script
  388. objs = SConscript('SConscript', variant_dir='build/bsp', duplicate=0)
  389. Repository(Rtt_Root)
  390. # include kernel
  391. objs.append(SConscript('src/SConscript', variant_dir='build/src', duplicate=0))
  392. # include libcpu
  393. if not has_libcpu:
  394. objs.append(SConscript('libcpu/SConscript', variant_dir='build/libcpu', duplicate=0))
  395. # include components
  396. objs.append(SConscript('components/SConscript', variant_dir='build/components', duplicate=0))
  397. return objs
  398. def GetDepend(depend):
  399. building = True
  400. if type(depend) == type('str'):
  401. if not BuildOptions.has_key(depend):
  402. building = False
  403. return building
  404. # for list type depend
  405. for item in depend:
  406. if item != '':
  407. if not BuildOptions.has_key(item):
  408. building = False
  409. return building
  410. def AddDepend(option):
  411. BuildOptions[option] = 1
  412. def DefineGroup(name, src, depend, **parameters):
  413. global Env
  414. if not GetDepend(depend):
  415. return []
  416. group = parameters
  417. group['name'] = name
  418. if type(src) == type(['src1', 'str2']):
  419. group['src'] = File(src)
  420. else:
  421. group['src'] = src
  422. Projects.append(group)
  423. if group.has_key('CCFLAGS'):
  424. Env.Append(CCFLAGS = group['CCFLAGS'])
  425. if group.has_key('CPPPATH'):
  426. Env.Append(CPPPATH = group['CPPPATH'])
  427. if group.has_key('CPPDEFINES'):
  428. Env.Append(CPPDEFINES = group['CPPDEFINES'])
  429. if group.has_key('LINKFLAGS'):
  430. Env.Append(LINKFLAGS = group['LINKFLAGS'])
  431. objs = Env.Object(group['src'])
  432. if group.has_key('LIBRARY'):
  433. objs = Env.Library(name, objs)
  434. return objs
  435. def EndBuilding(target):
  436. import rtconfig
  437. Env.AddPostAction(target, rtconfig.POST_ACTION)
  438. if GetOption('target') == 'mdk':
  439. if rtconfig.CROSS_TOOL != 'keil':
  440. print 'Please use Keil MDK compiler in rtconfig.h'
  441. return
  442. MDKProject('project.Uv2', Projects)
  443. if GetOption('target') == 'mdk4':
  444. if rtconfig.CROSS_TOOL != 'keil':
  445. print 'Please use Keil MDK compiler in rtconfig.h'
  446. return
  447. MDK4Project('project.uvproj', Projects)
  448. if GetOption('target') == 'iar':
  449. if rtconfig.CROSS_TOOL != 'iar':
  450. print 'Please use IAR compiler in rtconfig.h'
  451. return
  452. IARProject('project.ewp', Projects)