keil.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. #
  2. # File : keil.py
  3. # This file is part of RT-Thread RTOS
  4. # COPYRIGHT (C) 2006 - 2015, RT-Thread Development Team
  5. #
  6. # This program is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation; either version 2 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License along
  17. # with this program; if not, write to the Free Software Foundation, Inc.,
  18. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  19. #
  20. # Change Logs:
  21. # Date Author Notes
  22. # 2015-01-20 Bernard Add copyright information
  23. #
  24. import os
  25. import sys
  26. import string
  27. import shutil
  28. import xml.etree.ElementTree as etree
  29. from xml.etree.ElementTree import SubElement
  30. from utils import _make_path_relative
  31. from utils import xml_indent
  32. fs_encoding = sys.getfilesystemencoding()
  33. def _get_filetype(fn):
  34. if fn.rfind('.cpp') != -1 or fn.rfind('.cxx') != -1:
  35. return 8
  36. if fn.rfind('.c') != -1 or fn.rfind('.C') != -1:
  37. return 1
  38. # assemble file type
  39. if fn.rfind('.s') != -1 or fn.rfind('.S') != -1:
  40. return 2
  41. # header type
  42. if fn.rfind('.h') != -1:
  43. return 5
  44. if fn.rfind('.lib') != -1:
  45. return 4
  46. if fn.rfind('.o') != -1:
  47. return 3
  48. # other filetype
  49. return 5
  50. def MDK4AddGroupForFN(ProjectFiles, parent, name, filename, project_path):
  51. group = SubElement(parent, 'Group')
  52. group_name = SubElement(group, 'GroupName')
  53. group_name.text = name
  54. name = os.path.basename(filename)
  55. path = os.path.dirname (filename)
  56. basename = os.path.basename(path)
  57. path = _make_path_relative(project_path, path)
  58. path = os.path.join(path, name)
  59. files = SubElement(group, 'Files')
  60. file = SubElement(files, 'File')
  61. file_name = SubElement(file, 'FileName')
  62. name = os.path.basename(path)
  63. if name.find('.cpp') != -1:
  64. obj_name = name.replace('.cpp', '.o')
  65. elif name.find('.c') != -1:
  66. obj_name = name.replace('.c', '.o')
  67. elif name.find('.s') != -1:
  68. obj_name = name.replace('.s', '.o')
  69. elif name.find('.S') != -1:
  70. obj_name = name.replace('.s', '.o')
  71. else:
  72. obj_name = name
  73. if ProjectFiles.count(obj_name):
  74. name = basename + '_' + name
  75. ProjectFiles.append(obj_name)
  76. try: # python 2
  77. file_name.text = name.decode(fs_encoding)
  78. except: # python 3
  79. file_name.text = name
  80. file_type = SubElement(file, 'FileType')
  81. file_type.text = '%d' % _get_filetype(name)
  82. file_path = SubElement(file, 'FilePath')
  83. try: # python 2
  84. file_path.text = path.decode(fs_encoding)
  85. except: # python 3
  86. file_path.text = path
  87. return group
  88. def MDK4AddLibToGroup(ProjectFiles, group, name, filename, project_path):
  89. name = os.path.basename(filename)
  90. path = os.path.dirname (filename)
  91. basename = os.path.basename(path)
  92. path = _make_path_relative(project_path, path)
  93. path = os.path.join(path, name)
  94. files = SubElement(group, 'Files')
  95. file = SubElement(files, 'File')
  96. file_name = SubElement(file, 'FileName')
  97. name = os.path.basename(path)
  98. if name.find('.cpp') != -1:
  99. obj_name = name.replace('.cpp', '.o')
  100. elif name.find('.c') != -1:
  101. obj_name = name.replace('.c', '.o')
  102. elif name.find('.s') != -1:
  103. obj_name = name.replace('.s', '.o')
  104. elif name.find('.S') != -1:
  105. obj_name = name.replace('.s', '.o')
  106. else:
  107. obj_name = name
  108. if ProjectFiles.count(obj_name):
  109. name = basename + '_' + name
  110. ProjectFiles.append(obj_name)
  111. try:
  112. file_name.text = name.decode(fs_encoding)
  113. except:
  114. file_name.text = name
  115. file_type = SubElement(file, 'FileType')
  116. file_type.text = '%d' % _get_filetype(name)
  117. file_path = SubElement(file, 'FilePath')
  118. try:
  119. file_path.text = path.decode(fs_encoding)
  120. except:
  121. file_path.text = path
  122. return group
  123. def MDK4AddGroup(ProjectFiles, parent, name, files, project_path, group_scons):
  124. # don't add an empty group
  125. if len(files) == 0:
  126. return
  127. group = SubElement(parent, 'Group')
  128. group_name = SubElement(group, 'GroupName')
  129. group_name.text = name
  130. for f in files:
  131. fn = f.rfile()
  132. name = fn.name
  133. path = os.path.dirname(fn.abspath)
  134. basename = os.path.basename(path)
  135. path = _make_path_relative(project_path, path)
  136. path = os.path.join(path, name)
  137. files = SubElement(group, 'Files')
  138. file = SubElement(files, 'File')
  139. file_name = SubElement(file, 'FileName')
  140. name = os.path.basename(path)
  141. if name.find('.cpp') != -1:
  142. obj_name = name.replace('.cpp', '.o')
  143. elif name.find('.c') != -1:
  144. obj_name = name.replace('.c', '.o')
  145. elif name.find('.s') != -1:
  146. obj_name = name.replace('.s', '.o')
  147. elif name.find('.S') != -1:
  148. obj_name = name.replace('.s', '.o')
  149. if ProjectFiles.count(obj_name):
  150. name = basename + '_' + name
  151. ProjectFiles.append(obj_name)
  152. file_name.text = name # name.decode(fs_encoding)
  153. file_type = SubElement(file, 'FileType')
  154. file_type.text = '%d' % _get_filetype(name)
  155. file_path = SubElement(file, 'FilePath')
  156. file_path.text = path # path.decode(fs_encoding)
  157. # for local LOCAL_CFLAGS/LOCAL_CXXFLAGS/LOCAL_CCFLAGS/LOCAL_CPPPATH/LOCAL_CPPDEFINES
  158. MiscControls_text = ' '
  159. if file_type.text == '1' and 'LOCAL_CFLAGS' in group_scons:
  160. MiscControls_text = MiscControls_text + group_scons['LOCAL_CFLAGS']
  161. elif file_type.text == '8' and 'LOCAL_CXXFLAGS' in group_scons:
  162. MiscControls_text = MiscControls_text + group_scons['LOCAL_CXXFLAGS']
  163. if 'LOCAL_CCFLAGS' in group_scons:
  164. MiscControls_text = MiscControls_text + group_scons['LOCAL_CCFLAGS']
  165. if MiscControls_text != ' ' or ('LOCAL_CPPDEFINES' in group_scons):
  166. FileOption = SubElement(file, 'FileOption')
  167. FileArmAds = SubElement(FileOption, 'FileArmAds')
  168. Cads = SubElement(FileArmAds, 'Cads')
  169. VariousControls = SubElement(Cads, 'VariousControls')
  170. MiscControls = SubElement(VariousControls, 'MiscControls')
  171. MiscControls.text = MiscControls_text
  172. Define = SubElement(VariousControls, 'Define')
  173. if 'LOCAL_CPPDEFINES' in group_scons:
  174. Define.text = ', '.join(set(group_scons['LOCAL_CPPDEFINES']))
  175. else:
  176. Define.text = ' '
  177. Undefine = SubElement(VariousControls, 'Undefine')
  178. Undefine.text = ' '
  179. IncludePath = SubElement(VariousControls, 'IncludePath')
  180. if 'LOCAL_CPPPATH' in group_scons:
  181. IncludePath.text = ';'.join([_make_path_relative(project_path, os.path.normpath(i)) for i in group_scons['LOCAL_CPPPATH']])
  182. else:
  183. IncludePath.text = ' '
  184. return group
  185. # The common part of making MDK4/5 project
  186. def MDK45Project(env, tree, target, script):
  187. project_path = os.path.dirname(os.path.abspath(target))
  188. root = tree.getroot()
  189. out = open(target, 'w')
  190. out.write('<?xml version="1.0" encoding="UTF-8" standalone="no" ?>\n')
  191. CPPPATH = []
  192. CPPDEFINES = env.get('CPPDEFINES', [])
  193. LINKFLAGS = ''
  194. CXXFLAGS = ''
  195. CCFLAGS = ''
  196. CFLAGS = ''
  197. ProjectFiles = []
  198. # add group
  199. groups = tree.find('Targets/Target/Groups')
  200. if groups is None:
  201. groups = SubElement(tree.find('Targets/Target'), 'Groups')
  202. groups.clear() # clean old groups
  203. for group in script:
  204. group_tree = MDK4AddGroup(ProjectFiles, groups, group['name'], group['src'], project_path, group)
  205. # get each include path
  206. if 'CPPPATH' in group and group['CPPPATH']:
  207. if CPPPATH:
  208. CPPPATH += group['CPPPATH']
  209. else:
  210. CPPPATH += group['CPPPATH']
  211. # get each group's link flags
  212. if 'LINKFLAGS' in group and group['LINKFLAGS']:
  213. if LINKFLAGS:
  214. LINKFLAGS += ' ' + group['LINKFLAGS']
  215. else:
  216. LINKFLAGS += group['LINKFLAGS']
  217. # get each group's CXXFLAGS flags
  218. if 'CXXFLAGS' in group and group['CXXFLAGS']:
  219. if CXXFLAGS:
  220. CXXFLAGS += ' ' + group['CXXFLAGS']
  221. else:
  222. CXXFLAGS += group['CXXFLAGS']
  223. # get each group's CCFLAGS flags
  224. if 'CCFLAGS' in group and group['CCFLAGS']:
  225. if CCFLAGS:
  226. CCFLAGS += ' ' + group['CCFLAGS']
  227. else:
  228. CCFLAGS += group['CCFLAGS']
  229. # get each group's CFLAGS flags
  230. if 'CFLAGS' in group and group['CFLAGS']:
  231. if CFLAGS:
  232. CFLAGS += ' ' + group['CFLAGS']
  233. else:
  234. CFLAGS += group['CFLAGS']
  235. # get each group's LIBS flags
  236. if 'LIBS' in group and group['LIBS']:
  237. for item in group['LIBPATH']:
  238. full_path = os.path.join(item, group['name'] + '.lib')
  239. if os.path.isfile(full_path): # has this library
  240. if group_tree != None:
  241. MDK4AddLibToGroup(ProjectFiles, group_tree, group['name'], full_path, project_path)
  242. else:
  243. group_tree = MDK4AddGroupForFN(ProjectFiles, groups, group['name'], full_path, project_path)
  244. # write include path, definitions and link flags
  245. IncludePath = tree.find('Targets/Target/TargetOption/TargetArmAds/Cads/VariousControls/IncludePath')
  246. IncludePath.text = ';'.join([_make_path_relative(project_path, os.path.normpath(i)) for i in set(CPPPATH)])
  247. Define = tree.find('Targets/Target/TargetOption/TargetArmAds/Cads/VariousControls/Define')
  248. Define.text = ', '.join(set(CPPDEFINES))
  249. if 'c99' in CXXFLAGS or 'c99' in CCFLAGS or 'c99' in CFLAGS:
  250. uC99 = tree.find('Targets/Target/TargetOption/TargetArmAds/Cads/uC99')
  251. uC99.text = '1'
  252. if 'gnu' in CXXFLAGS or 'gnu' in CCFLAGS or 'gnu' in CFLAGS:
  253. uGnu = tree.find('Targets/Target/TargetOption/TargetArmAds/Cads/uGnu')
  254. uGnu.text = '1'
  255. Misc = tree.find('Targets/Target/TargetOption/TargetArmAds/LDads/Misc')
  256. Misc.text = LINKFLAGS
  257. xml_indent(root)
  258. out.write(etree.tostring(root, encoding='utf-8').decode())
  259. out.close()
  260. def MDK4Project(env, target, script):
  261. if os.path.isfile('template.uvproj') is False:
  262. print ('Warning: The template project file [template.uvproj] not found!')
  263. return
  264. template_tree = etree.parse('template.uvproj')
  265. MDK45Project(env, template_tree, target, script)
  266. # remove project.uvopt file
  267. project_uvopt = os.path.abspath(target).replace('uvproj', 'uvopt')
  268. if os.path.isfile(project_uvopt):
  269. os.unlink(project_uvopt)
  270. # copy uvopt file
  271. if os.path.exists('template.uvopt'):
  272. import shutil
  273. shutil.copy2('template.uvopt', '{}.uvopt'.format(os.path.splitext(target)[0]))
  274. import threading
  275. import time
  276. def monitor_log_file(log_file_path):
  277. if not os.path.exists(log_file_path):
  278. open(log_file_path, 'w').close()
  279. empty_line_count = 0
  280. with open(log_file_path, 'r') as log_file:
  281. while True:
  282. line = log_file.readline()
  283. if line:
  284. print(line.strip())
  285. if 'Build Time Elapsed' in line:
  286. break
  287. empty_line_count = 0
  288. else:
  289. empty_line_count += 1
  290. time.sleep(1)
  291. if empty_line_count > 30:
  292. print("Timeout reached or too many empty lines, exiting log monitoring thread.")
  293. break
  294. def MDK5Project(env, target, script):
  295. if os.path.isfile('template.uvprojx') is False:
  296. print ('Warning: The template project file [template.uvprojx] not found!')
  297. return
  298. template_tree = etree.parse('template.uvprojx')
  299. MDK45Project(env, template_tree, target, script)
  300. # remove project.uvopt file
  301. project_uvopt = os.path.abspath(target).replace('uvprojx', 'uvoptx')
  302. if os.path.isfile(project_uvopt):
  303. os.unlink(project_uvopt)
  304. # copy uvopt file
  305. if os.path.exists('template.uvoptx'):
  306. import shutil
  307. shutil.copy2('template.uvoptx', '{}.uvoptx'.format(os.path.splitext(target)[0]))
  308. # build with UV4.exe
  309. if shutil.which('UV4.exe') is not None:
  310. target_name = template_tree.find('Targets/Target/TargetName')
  311. print('target_name:', target_name.text)
  312. log_file_path = 'keil.log'
  313. if os.path.exists(log_file_path):
  314. os.remove(log_file_path)
  315. log_thread = threading.Thread(target=monitor_log_file, args=(log_file_path,))
  316. log_thread.start()
  317. cmd = 'UV4.exe -b project.uvprojx -q -j0 -t '+ target_name.text +' -o '+log_file_path
  318. print('Start to build keil project')
  319. print(cmd)
  320. os.system(cmd)
  321. else:
  322. print('UV4.exe is not available, please check your keil installation')
  323. def MDK2Project(env, target, script):
  324. template = open(os.path.join(os.path.dirname(__file__), 'template.Uv2'), 'r')
  325. lines = template.readlines()
  326. project = open(target, "w")
  327. project_path = os.path.dirname(os.path.abspath(target))
  328. line_index = 5
  329. # write group
  330. for group in script:
  331. lines.insert(line_index, 'Group (%s)\r\n' % group['name'])
  332. line_index += 1
  333. lines.insert(line_index, '\r\n')
  334. line_index += 1
  335. # write file
  336. ProjectFiles = []
  337. CPPPATH = []
  338. CPPDEFINES = env.get('CPPDEFINES', [])
  339. LINKFLAGS = ''
  340. CFLAGS = ''
  341. # number of groups
  342. group_index = 1
  343. for group in script:
  344. # print group['name']
  345. # get each include path
  346. if 'CPPPATH' in group and group['CPPPATH']:
  347. if CPPPATH:
  348. CPPPATH += group['CPPPATH']
  349. else:
  350. CPPPATH += group['CPPPATH']
  351. # get each group's link flags
  352. if 'LINKFLAGS' in group and group['LINKFLAGS']:
  353. if LINKFLAGS:
  354. LINKFLAGS += ' ' + group['LINKFLAGS']
  355. else:
  356. LINKFLAGS += group['LINKFLAGS']
  357. # generate file items
  358. for node in group['src']:
  359. fn = node.rfile()
  360. name = fn.name
  361. path = os.path.dirname(fn.abspath)
  362. basename = os.path.basename(path)
  363. path = _make_path_relative(project_path, path)
  364. path = os.path.join(path, name)
  365. if ProjectFiles.count(name):
  366. name = basename + '_' + name
  367. ProjectFiles.append(name)
  368. lines.insert(line_index, 'File %d,%d,<%s><%s>\r\n'
  369. % (group_index, _get_filetype(name), path, name))
  370. line_index += 1
  371. group_index = group_index + 1
  372. lines.insert(line_index, '\r\n')
  373. line_index += 1
  374. # remove repeat path
  375. paths = set()
  376. for path in CPPPATH:
  377. inc = _make_path_relative(project_path, os.path.normpath(path))
  378. paths.add(inc) #.replace('\\', '/')
  379. paths = [i for i in paths]
  380. CPPPATH = string.join(paths, ';')
  381. definitions = [i for i in set(CPPDEFINES)]
  382. CPPDEFINES = string.join(definitions, ', ')
  383. while line_index < len(lines):
  384. if lines[line_index].startswith(' ADSCINCD '):
  385. lines[line_index] = ' ADSCINCD (' + CPPPATH + ')\r\n'
  386. if lines[line_index].startswith(' ADSLDMC ('):
  387. lines[line_index] = ' ADSLDMC (' + LINKFLAGS + ')\r\n'
  388. if lines[line_index].startswith(' ADSCDEFN ('):
  389. lines[line_index] = ' ADSCDEFN (' + CPPDEFINES + ')\r\n'
  390. line_index += 1
  391. # write project
  392. for line in lines:
  393. project.write(line)
  394. project.close()
  395. def ARMCC_Version():
  396. import rtconfig
  397. import subprocess
  398. import re
  399. path = rtconfig.EXEC_PATH
  400. if(rtconfig.PLATFORM == 'armcc'):
  401. path = os.path.join(path, 'armcc.exe')
  402. elif(rtconfig.PLATFORM == 'armclang'):
  403. path = os.path.join(path, 'armlink.exe')
  404. if os.path.exists(path):
  405. cmd = path
  406. else:
  407. return "0.0"
  408. child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  409. stdout, stderr = child.communicate()
  410. '''
  411. example stdout:
  412. Product: MDK Plus 5.24
  413. Component: ARM Compiler 5.06 update 5 (build 528)
  414. Tool: armcc [4d3621]
  415. return version: MDK Plus 5.24/ARM Compiler 5.06 update 5 (build 528)/armcc [4d3621]
  416. '''
  417. if not isinstance(stdout, str):
  418. stdout = str(stdout, 'utf8') # Patch for Python 3
  419. version_Product = re.search(r'Product: (.+)', stdout).group(1)
  420. version_Product = version_Product[:-1]
  421. version_Component = re.search(r'Component: (.*)', stdout).group(1)
  422. version_Component = version_Component[:-1]
  423. version_Tool = re.search(r'Tool: (.*)', stdout).group(1)
  424. version_Tool = version_Tool[:-1]
  425. version_str_format = '%s/%s/%s'
  426. version_str = version_str_format % (version_Product, version_Component, version_Tool)
  427. return version_str