1
0

building.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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(ProjectFiles, 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. name = os.path.basename(path)
  178. if ProjectFiles.count(name):
  179. name = basename + '_' + name
  180. ProjectFiles.append(name)
  181. file_name.text = name
  182. file_type = SubElement(file, 'FileType')
  183. file_type.text = '%d' % _get_filetype(name)
  184. file_path = SubElement(file, 'FilePath')
  185. file_path.text = path
  186. def MDK4Project(target, script):
  187. project_path = os.path.dirname(os.path.abspath(target))
  188. tree = etree.parse('template.uvproj')
  189. root = tree.getroot()
  190. out = file(target, 'wb')
  191. out.write('<?xml version="1.0" encoding="UTF-8" standalone="no" ?>\n')
  192. CPPPATH = []
  193. CPPDEFINES = []
  194. LINKFLAGS = ''
  195. CCFLAGS = ''
  196. ProjectFiles = []
  197. # add group
  198. groups = tree.find('Targets/Target/Groups')
  199. if not groups:
  200. groups = SubElement(tree.find('Targets/Target'), 'Groups')
  201. for group in script:
  202. group_xml = MDK4AddGroup(ProjectFiles, groups, group['name'], group['src'], project_path)
  203. # get each include path
  204. if group.has_key('CPPPATH') and group['CPPPATH']:
  205. if CPPPATH:
  206. CPPPATH += group['CPPPATH']
  207. else:
  208. CPPPATH += group['CPPPATH']
  209. # get each group's definitions
  210. if group.has_key('CPPDEFINES') and group['CPPDEFINES']:
  211. if CPPDEFINES:
  212. CPPDEFINES += ';' + group['CPPDEFINES']
  213. else:
  214. CPPDEFINES += group['CPPDEFINES']
  215. # get each group's link flags
  216. if group.has_key('LINKFLAGS') and group['LINKFLAGS']:
  217. if LINKFLAGS:
  218. LINKFLAGS += ' ' + group['LINKFLAGS']
  219. else:
  220. LINKFLAGS += group['LINKFLAGS']
  221. # remove repeat path
  222. paths = set()
  223. for path in CPPPATH:
  224. inc = _make_path_relative(project_path, os.path.normpath(path))
  225. paths.add(inc) #.replace('\\', '/')
  226. paths = [i for i in paths]
  227. CPPPATH = string.join(paths, ';')
  228. definitions = [i for i in set(CPPDEFINES)]
  229. CPPDEFINES = string.join(definitions, ', ')
  230. # write include path, definitions and link flags
  231. IncludePath = tree.find('Targets/Target/TargetOption/TargetArmAds/Cads/VariousControls/IncludePath')
  232. IncludePath.text = CPPPATH
  233. Define = tree.find('Targets/Target/TargetOption/TargetArmAds/Cads/VariousControls/Define')
  234. Define.text = CPPDEFINES
  235. Misc = tree.find('Targets/Target/TargetOption/TargetArmAds/LDads/Misc')
  236. Misc.text = LINKFLAGS
  237. xml_indent(root)
  238. out.write(etree.tostring(root, encoding='utf-8'))
  239. out.close()
  240. def MDKProject(target, script):
  241. template = file('template.Uv2', "rb")
  242. lines = template.readlines()
  243. project = file(target, "wb")
  244. project_path = os.path.dirname(os.path.abspath(target))
  245. line_index = 5
  246. # write group
  247. for group in script:
  248. lines.insert(line_index, 'Group (%s)\r\n' % group['name'])
  249. line_index += 1
  250. lines.insert(line_index, '\r\n')
  251. line_index += 1
  252. # write file
  253. ProjectFiles = []
  254. CPPPATH = []
  255. CPPDEFINES = []
  256. LINKFLAGS = ''
  257. CCFLAGS = ''
  258. # number of groups
  259. group_index = 1
  260. for group in script:
  261. # print group['name']
  262. # get each include path
  263. if group.has_key('CPPPATH') and group['CPPPATH']:
  264. if CPPPATH:
  265. CPPPATH += group['CPPPATH']
  266. else:
  267. CPPPATH += group['CPPPATH']
  268. # get each group's definitions
  269. if group.has_key('CPPDEFINES') and group['CPPDEFINES']:
  270. if CPPDEFINES:
  271. CPPDEFINES += ';' + group['CPPDEFINES']
  272. else:
  273. CPPDEFINES += group['CPPDEFINES']
  274. # get each group's link flags
  275. if group.has_key('LINKFLAGS') and group['LINKFLAGS']:
  276. if LINKFLAGS:
  277. LINKFLAGS += ' ' + group['LINKFLAGS']
  278. else:
  279. LINKFLAGS += group['LINKFLAGS']
  280. # generate file items
  281. for node in group['src']:
  282. fn = node.rfile()
  283. name = fn.name
  284. path = os.path.dirname(fn.abspath)
  285. basename = os.path.basename(path)
  286. path = _make_path_relative(project_path, path)
  287. path = os.path.join(path, name)
  288. if ProjectFiles.count(name):
  289. name = basename + '_' + name
  290. ProjectFiles.append(name)
  291. lines.insert(line_index, 'File %d,%d,<%s><%s>\r\n'
  292. % (group_index, _get_filetype(name), path, name))
  293. line_index += 1
  294. group_index = group_index + 1
  295. lines.insert(line_index, '\r\n')
  296. line_index += 1
  297. # remove repeat path
  298. paths = set()
  299. for path in CPPPATH:
  300. inc = _make_path_relative(project_path, os.path.normpath(path))
  301. paths.add(inc) #.replace('\\', '/')
  302. paths = [i for i in paths]
  303. CPPPATH = string.join(paths, ';')
  304. definitions = [i for i in set(CPPDEFINES)]
  305. CPPDEFINES = string.join(definitions, ', ')
  306. while line_index < len(lines):
  307. if lines[line_index].startswith(' ADSCINCD '):
  308. lines[line_index] = ' ADSCINCD (' + CPPPATH + ')\r\n'
  309. if lines[line_index].startswith(' ADSLDMC ('):
  310. lines[line_index] = ' ADSLDMC (' + LINKFLAGS + ')\r\n'
  311. if lines[line_index].startswith(' ADSCDEFN ('):
  312. lines[line_index] = ' ADSCDEFN (' + CPPDEFINES + ')\r\n'
  313. line_index += 1
  314. # write project
  315. for line in lines:
  316. project.write(line)
  317. project.close()
  318. def BuilderProject(target, script):
  319. project = file(target, "wb")
  320. project_path = os.path.dirname(os.path.abspath(target))
  321. # write file
  322. CPPPATH = []
  323. CPPDEFINES = []
  324. LINKFLAGS = ''
  325. CCFLAGS = ''
  326. # number of groups
  327. group_index = 1
  328. for group in script:
  329. # print group['name']
  330. # generate file items
  331. for node in group['src']:
  332. fn = node.rfile()
  333. name = fn.name
  334. path = os.path.dirname(fn.abspath)
  335. path = _make_path_relative(project_path, path)
  336. path = os.path.join(path, name)
  337. project.write('%s\r\n' % path)
  338. group_index = group_index + 1
  339. project.close()
  340. class Win32Spawn:
  341. def spawn(self, sh, escape, cmd, args, env):
  342. import subprocess
  343. newargs = string.join(args[1:], ' ')
  344. cmdline = cmd + " " + newargs
  345. startupinfo = subprocess.STARTUPINFO()
  346. # startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  347. proc = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  348. stderr=subprocess.PIPE, startupinfo=startupinfo, shell = False)
  349. data, err = proc.communicate()
  350. rv = proc.wait()
  351. if rv:
  352. print err
  353. return rv
  354. if data:
  355. print data
  356. return 0
  357. def PrepareBuilding(env, root_directory, has_libcpu=False):
  358. import SCons.cpp
  359. import rtconfig
  360. global BuildOptions
  361. global Projects
  362. global Env
  363. global Rtt_Root
  364. Env = env
  365. Rtt_Root = root_directory
  366. # patch for win32 spawn
  367. if env['PLATFORM'] == 'win32' and rtconfig.PLATFORM == 'gcc':
  368. win32_spawn = Win32Spawn()
  369. win32_spawn.env = env
  370. env['SPAWN'] = win32_spawn.spawn
  371. # add program path
  372. env.PrependENVPath('PATH', rtconfig.EXEC_PATH)
  373. # parse rtconfig.h to get used component
  374. PreProcessor = SCons.cpp.PreProcessor()
  375. f = file('rtconfig.h', 'r')
  376. contents = f.read()
  377. f.close()
  378. PreProcessor.process_contents(contents)
  379. BuildOptions = PreProcessor.cpp_namespace
  380. if (GetDepend('RT_USING_NEWLIB') == False and GetDepend('RT_USING_NOLIBC') == False) and rtconfig.PLATFORM == 'gcc':
  381. AddDepend('RT_USING_MINILIBC')
  382. # add target option
  383. AddOption('--target',
  384. dest='target',
  385. type='string',
  386. help='set target project: mdk')
  387. if GetOption('target'):
  388. SetOption('no_exec', 1)
  389. #env['CCCOMSTR'] = "CC $TARGET"
  390. #env['ASCOMSTR'] = "AS $TARGET"
  391. #env['LINKCOMSTR'] = "Link $TARGET"
  392. # board build script
  393. objs = SConscript('SConscript', variant_dir='build/bsp', duplicate=0)
  394. Repository(Rtt_Root)
  395. # include kernel
  396. objs.append(SConscript('src/SConscript', variant_dir='build/src', duplicate=0))
  397. # include libcpu
  398. if not has_libcpu:
  399. objs.append(SConscript('libcpu/SConscript', variant_dir='build/libcpu', duplicate=0))
  400. # include components
  401. objs.append(SConscript('components/SConscript', variant_dir='build/components', duplicate=0))
  402. return objs
  403. def PrepareModuleBuilding(env, root_directory):
  404. import SCons.cpp
  405. import rtconfig
  406. global BuildOptions
  407. global Projects
  408. global Env
  409. global Rtt_Root
  410. Env = env
  411. Rtt_Root = root_directory
  412. # add program path
  413. env.PrependENVPath('PATH', rtconfig.EXEC_PATH)
  414. def GetDepend(depend):
  415. building = True
  416. if type(depend) == type('str'):
  417. if not BuildOptions.has_key(depend) or BuildOptions[depend] == 0:
  418. building = False
  419. elif BuildOptions[depend] != '':
  420. return BuildOptions[depend]
  421. return building
  422. # for list type depend
  423. for item in depend:
  424. if item != '':
  425. if not BuildOptions.has_key(item) or BuildOptions[item] == 0:
  426. building = False
  427. return building
  428. def AddDepend(option):
  429. BuildOptions[option] = 1
  430. def DefineGroup(name, src, depend, **parameters):
  431. global Env
  432. if not GetDepend(depend):
  433. return []
  434. group = parameters
  435. group['name'] = name
  436. if type(src) == type(['src1', 'str2']):
  437. group['src'] = File(src)
  438. else:
  439. group['src'] = src
  440. Projects.append(group)
  441. if group.has_key('CCFLAGS'):
  442. Env.Append(CCFLAGS = group['CCFLAGS'])
  443. if group.has_key('CPPPATH'):
  444. Env.Append(CPPPATH = group['CPPPATH'])
  445. if group.has_key('CPPDEFINES'):
  446. Env.Append(CPPDEFINES = group['CPPDEFINES'])
  447. if group.has_key('LINKFLAGS'):
  448. Env.Append(LINKFLAGS = group['LINKFLAGS'])
  449. objs = Env.Object(group['src'])
  450. if group.has_key('LIBRARY'):
  451. objs = Env.Library(name, objs)
  452. return objs
  453. def GetCurrentDir():
  454. conscript = File('SConscript')
  455. fn = conscript.rfile()
  456. name = fn.name
  457. path = os.path.dirname(fn.abspath)
  458. return path
  459. def EndBuilding(target):
  460. import rtconfig
  461. Env.AddPostAction(target, rtconfig.POST_ACTION)
  462. if GetOption('target') == 'mdk':
  463. template = os.path.isfile('template.Uv2')
  464. if rtconfig.CROSS_TOOL != 'keil':
  465. print 'Please use Keil MDK compiler in rtconfig.py'
  466. return
  467. if template:
  468. MDKProject('project.Uv2', Projects)
  469. else:
  470. template = os.path.isfile('template.uvproj')
  471. if template:
  472. MDK4Project('project.uvproj', Projects)
  473. else:
  474. print 'No template project file found.'
  475. if GetOption('target') == 'mdk4':
  476. if rtconfig.CROSS_TOOL != 'keil':
  477. print 'Please use Keil MDK compiler in rtconfig.py'
  478. return
  479. MDK4Project('project.uvproj', Projects)
  480. if GetOption('target') == 'iar':
  481. if rtconfig.CROSS_TOOL != 'iar':
  482. print 'Please use IAR compiler in rtconfig.py'
  483. return
  484. IARProject('project.ewp', Projects)