nsdk_utils.py 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495
  1. #!/usr/bin/env python3
  2. import os
  3. import sys
  4. SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
  5. requirement_file = os.path.abspath(os.path.join(SCRIPT_DIR, "..", "requirements.txt"))
  6. try:
  7. import time
  8. import datetime
  9. import random
  10. import shutil
  11. import signal
  12. import psutil
  13. import re
  14. import copy
  15. import serial
  16. import serial.tools.list_ports
  17. import tempfile
  18. import collections
  19. from collections import OrderedDict
  20. from threading import Thread
  21. import subprocess
  22. import asyncio
  23. import glob
  24. import json
  25. import yaml
  26. import importlib.util
  27. if sys.platform != "win32":
  28. import fcntl
  29. import stat
  30. except Exception as exc:
  31. print("Import Error: %s" % (exc))
  32. print("Please install requried packages using: pip3 install -r %s" % (requirement_file))
  33. sys.exit(1)
  34. try:
  35. from collections.abc import Mapping
  36. except ImportError: # Python 2.7 compatibility
  37. from collections import Mapping
  38. SDK_GLOBAL_VARIABLES = {
  39. "sdk_checktag": "Nuclei SDK Build Time:",
  40. "sdk_check": True,
  41. "sdk_banner_tmout": 15,
  42. "sdk_copy_objects": "elf,map",
  43. "sdk_copy_objects_flag": False,
  44. "sdk_ttyerr_maxcnt": 3,
  45. "sdk_fpgaprog_maxcnt": 3,
  46. "sdk_gdberr_maxcnt": 10,
  47. "sdk_uploaderr_maxcnt": 10,
  48. "sdk_bannertmout_maxcnt": 100,
  49. "sdk_verb_buildmsg": True,
  50. "sdk_copy_failobj": True
  51. }
  52. INVAILD_SERNO = "xxxxx"
  53. BANNER_TMOUT = "banner_timeout"
  54. TTY_OP_ERR = "tty_operate_error"
  55. TTY_UNKNOWN_ERR = "tty_unknown_error"
  56. FILE_LOCK_NAME = "fpga_program.lock"
  57. DATE_FORMATE = "%Y-%m-%d %H:%M:%S"
  58. def get_tmpdir():
  59. tempdir = tempfile.gettempdir()
  60. if sys.platform == "win32":
  61. wintempdir = "C:\\Users\\Public\\Temp"
  62. if os.path.isdir(wintempdir) == False:
  63. os.makedirs(wintempdir)
  64. tempdir = wintempdir
  65. return tempdir
  66. # get ci url information
  67. def get_ci_info():
  68. cijoburl = os.environ.get("CI_JOB_URL")
  69. cipipelineurl = os.environ.get("CI_PIPELINE_URL")
  70. if cijoburl and cipipelineurl:
  71. return {"joburl": cijoburl, "pipelineurl": cipipelineurl}
  72. else:
  73. return {}
  74. def get_global_variables():
  75. return SDK_GLOBAL_VARIABLES
  76. def get_sdk_checktag():
  77. checktag = os.environ.get("SDK_CHECKTAG")
  78. if checktag is None:
  79. checktag = SDK_GLOBAL_VARIABLES.get("sdk_checktag")
  80. return checktag
  81. def get_sdk_copyobjects():
  82. cpobjs = os.environ.get("SDK_COPY_OBJECTS")
  83. if cpobjs is None:
  84. cpobjs = SDK_GLOBAL_VARIABLES.get("sdk_copy_objects")
  85. return cpobjs
  86. def get_env_flag(envar, deft=None):
  87. flag = os.environ.get(envar)
  88. if flag is None:
  89. return deft
  90. return flag.lower() in ('true', '1', 't')
  91. def get_sdk_check():
  92. check = get_env_flag("SDK_CHECK")
  93. if check is None:
  94. check = SDK_GLOBAL_VARIABLES.get("sdk_check")
  95. return check
  96. def get_sdk_verb_buildmsg():
  97. check = get_env_flag("SDK_VERB_BUILDMSG")
  98. if check is None:
  99. check = SDK_GLOBAL_VARIABLES.get("sdk_verb_buildmsg")
  100. return check
  101. def get_sdk_copyobjects_flag():
  102. cpflag = get_env_flag("SDK_COPY_OBJECTS_FLAG")
  103. if cpflag is None:
  104. cpflag = SDK_GLOBAL_VARIABLES.get("sdk_copy_objects_flag")
  105. return cpflag
  106. def get_sdk_need_copyobjects(appconfig):
  107. try:
  108. needed = appconfig.get("copy_objects")
  109. except:
  110. needed = False
  111. if needed != True:
  112. # use global flag
  113. needed = get_sdk_copyobjects_flag()
  114. return needed
  115. def get_sdk_copy_failobj():
  116. cpflag = get_env_flag("SDK_COPY_FAILOBJ")
  117. if cpflag is None:
  118. cpflag = SDK_GLOBAL_VARIABLES.get("sdk_copy_failobj")
  119. return cpflag
  120. def get_sdk_banner_tmout():
  121. tmout = os.environ.get("SDK_BANNER_TMOUT")
  122. if tmout is not None:
  123. tmout = int(tmout)
  124. else:
  125. tmout = SDK_GLOBAL_VARIABLES.get("sdk_banner_tmout")
  126. return tmout
  127. # some case may run more than default timeout in app.json
  128. def get_sdk_run_tmout():
  129. tmout = os.environ.get("SDK_RUN_TMOUT")
  130. if tmout is not None:
  131. tmout = int(tmout)
  132. return tmout
  133. def get_sdk_fpga_prog_tmout():
  134. tmout = os.environ.get("FPGA_PROG_TMOUT")
  135. return tmout
  136. def get_sdk_ttyerr_maxcnt():
  137. num = os.environ.get("SDK_TTYERR_MAXCNT")
  138. if num is not None:
  139. num = int(num)
  140. else:
  141. num = SDK_GLOBAL_VARIABLES.get("sdk_ttyerr_maxcnt")
  142. return num
  143. def get_sdk_fpgaprog_maxcnt():
  144. num = os.environ.get("SDK_FPGAPROG_MAXCNT")
  145. if num is not None:
  146. num = int(num)
  147. else:
  148. num = SDK_GLOBAL_VARIABLES.get("sdk_fpgaprog_maxcnt")
  149. return num
  150. def get_sdk_gdberr_maxcnt():
  151. num = os.environ.get("SDK_GDBERR_MAXCNT")
  152. if num is not None:
  153. num = int(num)
  154. else:
  155. num = SDK_GLOBAL_VARIABLES.get("sdk_gdberr_maxcnt")
  156. return num
  157. def get_sdk_bannertmout_maxcnt():
  158. num = os.environ.get("SDK_BANNERTMOUT_MAXCNT")
  159. if num is not None:
  160. num = int(num)
  161. else:
  162. num = SDK_GLOBAL_VARIABLES.get("sdk_bannertmout_maxcnt")
  163. return num
  164. def get_sdk_uploaderr_maxcnt():
  165. num = os.environ.get("SDK_UPLOADERR_MAXCNT")
  166. if num is not None:
  167. num = int(num)
  168. else:
  169. num = SDK_GLOBAL_VARIABLES.get("sdk_uploaderr_maxcnt")
  170. return num
  171. def parse_riscv_arch(arch_str):
  172. """Parse RISC-V architecture string to standardized format"""
  173. if not arch_str:
  174. return None
  175. arch_str = arch_str.lower()
  176. if not arch_str.startswith('rv32') and not arch_str.startswith('rv64'):
  177. return None
  178. features = {
  179. 'xlen': arch_str[:4],
  180. 'base': '',
  181. 'exts': set()
  182. }
  183. # Parse standard ISA string
  184. std_isa = arch_str[4:].split('_')[0]
  185. for c in std_isa:
  186. if c in 'iemafdcbpkv':
  187. # don't add b k p into base architecture
  188. if c == 'b':
  189. # for nuclei b extension contains zba/zbb/zbc/zbs
  190. features['exts'].add('zba')
  191. features['exts'].add('zbb')
  192. features['exts'].add('zbc')
  193. features['exts'].add('zbs')
  194. elif c == 'k':
  195. # for nuclei k extension contains zba/zbb/zbc/zbs
  196. features['exts'].add('zk') # zk -> zkn zkr zkt
  197. features['exts'].add('zks') # zks -> zbkb-sc zbkc-sc zbkx-sc zksed zksh
  198. features['exts'].add('zkn') # zkn -> zbkb-sc zbkc-sc zbkx-sc zkne zknd zknh
  199. features['exts'].add('zkr')
  200. features['exts'].add('zkt')
  201. features['exts'].add('zkne')
  202. features['exts'].add('zknd')
  203. features['exts'].add('zknh')
  204. features['exts'].add('zksed')
  205. features['exts'].add('zksh')
  206. features['exts'].add('zbkb-sc')
  207. features['exts'].add('zbkc-sc')
  208. features['exts'].add('zbkx-sc')
  209. elif c == 'v':
  210. features['exts'].add('zve64d')
  211. features['exts'].add('zvl128b')
  212. features['base'] += 'v'
  213. elif c == 'p':
  214. features['exts'].add('xxldsp')
  215. else:
  216. features['base'] += c
  217. # when base architecture has i extension, then e extension is implied
  218. if 'i' in features['base']:
  219. features['base'] += 'e'
  220. # Parse extensions
  221. if '_' in arch_str:
  222. exts = arch_str.split('_')[1:]
  223. for ext in exts:
  224. ext = ext.strip()
  225. if ext == "":
  226. continue
  227. if ext in ('zvl128', 'zvl256', 'zvl512', 'zvl1024'):
  228. ext = ext + 'b'
  229. elif ext in ('zvb', 'zvk', 'zc'):
  230. ext = ext + '*'
  231. elif ext in ('dsp'):
  232. ext = 'xxl' + ext
  233. elif ext in ('dspn1', 'dspn2', 'dspn3'):
  234. ext = 'xxl' + ext + 'x'
  235. features['exts'].add(ext)
  236. # For nuclei zc* can also configured as c extension via mmisc_ctl csr ZCMT_ZCMP_EN bit
  237. if 'zc*' in features['exts']:
  238. features['base'] += 'c'
  239. # For nuclei cpu, zifencei and zicsr are implied
  240. features['exts'].add('zicsr')
  241. features['exts'].add('zifencei')
  242. # zve64d imply zve64f, zve64f imply zve64x and zve32f
  243. # zve64x imply zve32x, zve32f imply zve32x
  244. if 'zve64d' in features['exts']:
  245. features['exts'].add('zve64f')
  246. if 'zve64f' in features['exts']:
  247. features['exts'].add('zve32f')
  248. features['exts'].add('zve64x')
  249. if 'zve64x' in features['exts']:
  250. features['exts'].add('zve32x')
  251. if 'zve32f' in features['exts']:
  252. features['exts'].add('zve32x')
  253. if 'xxldspn3x' in features['exts']:
  254. features['exts'].add('xxldspn2x')
  255. if 'xxldspn2x' in features['exts']:
  256. features['exts'].add('xxldspn1x')
  257. if 'xxldspn1x' in features['exts']:
  258. features['exts'].add('xxldsp')
  259. if 'zvl1024b' in features['exts']:
  260. features['exts'].add('zvl512b')
  261. if 'zvl512b' in features['exts']:
  262. features['exts'].add('zvl256b')
  263. if 'zvl256b' in features['exts']:
  264. features['exts'].add('zvl128b')
  265. if 'zve64d' in features['exts'] and 'zvl128b' in features['exts']:
  266. features['base'] += 'v'
  267. return features
  268. def get_nuclei_sdk_root():
  269. sdk_root = os.environ.get("NUCLEI_SDK_ROOT")
  270. if not sdk_root:
  271. sdk_root = os.path.abspath(os.path.join(SCRIPT_DIR, "..", "..", ".."))
  272. return sdk_root
  273. def parse_makefile_core():
  274. sdk_root = get_nuclei_sdk_root()
  275. makefile_core = os.path.join(sdk_root, "Build", "Makefile.core")
  276. core_archs = {}
  277. if not os.path.exists(makefile_core):
  278. return core_archs
  279. with open(makefile_core, 'r') as f:
  280. for line in f:
  281. line = line.strip()
  282. if not line or line.startswith('#'):
  283. continue
  284. if '_CORE_ARCH_ABI' in line:
  285. parts = line.split('=')
  286. if len(parts) == 2:
  287. core_name = parts[0].split('_CORE_ARCH_ABI')[0].lower()
  288. arch_parts = parts[1].strip().split()
  289. if len(arch_parts) >= 2:
  290. core_archs[core_name] = arch_parts[0]
  291. return core_archs
  292. def check_arch_compatibility(core_arch, arch_ext, supported_arch):
  293. """Check if core architecture with extensions is compatible with supported architecture"""
  294. if not supported_arch:
  295. return True
  296. supported = parse_riscv_arch(supported_arch)
  297. if not supported:
  298. return True
  299. # Combine core_arch with arch_ext
  300. full_arch = core_arch
  301. if arch_ext:
  302. full_arch += arch_ext
  303. current = parse_riscv_arch(full_arch)
  304. if not current:
  305. return False
  306. # Check XLEN compatibility
  307. if current['xlen'] != supported['xlen']:
  308. return False
  309. # Check base ISA compatibility
  310. for c in current['base']:
  311. if c not in supported['base']:
  312. return False
  313. # Check extensions compatibility
  314. # For current['exts'] containing extensions (no * suffix)
  315. # For supported['exts'] containing extensions (may have * suffix)
  316. # Extension matching should handle wildcards (*) in supported extensions
  317. for ext in current['exts']:
  318. found_match = False
  319. for supported_ext in supported['exts']:
  320. if supported_ext.endswith('*'):
  321. # Handle wildcard matching
  322. if ext.startswith(supported_ext[:-1]):
  323. found_match = True
  324. break
  325. elif ext == supported_ext:
  326. # Handle exact matching
  327. found_match = True
  328. break
  329. if not found_match:
  330. return False
  331. return True
  332. def filter_app_config(appconfig):
  333. """
  334. Filter application configurations based on architecture and extension compatibility.
  335. This function examines the build configuration of an application and determines if it should
  336. be filtered out based on architecture support and extension compatibility.
  337. Parameters:
  338. appconfig (dict): A dictionary containing application configuration.
  339. Expected to have a 'build_config' key with CORE, ARCH_EXT details.
  340. Returns:
  341. tuple: A pair of (bool, str) where:
  342. - bool: True if the configuration should be filtered out, False otherwise
  343. - str: A message explaining why the configuration was filtered (empty if not filtered)
  344. Environment Variables Used:
  345. - SDK_SUPPORT_ARCH: Supported architecture specifications
  346. - SDK_IGNORED_EXTS: Underscore-separated list of extensions to ignore
  347. Example:
  348. >>> config = {
  349. ... "build_config": {
  350. ... "CORE": "n307",
  351. ... "ARCH_EXT": "p_zfh"
  352. ... }
  353. ... }
  354. >>> filter_app_config(config)
  355. (False, "")
  356. Notes:
  357. - The function handles both single-letter and multi-letter extensions
  358. - Architecture extensions can be specified with or without leading underscore
  359. - Returns (False, "") if any required configuration is missing or in case of errors
  360. """
  361. if not isinstance(appconfig, dict):
  362. return False, ""
  363. try:
  364. build_config = appconfig.get("build_config", None)
  365. if build_config is None or len(build_config) == 0:
  366. return False, ""
  367. # Check SDK_SUPPORT_ARCH compatibility
  368. core = build_config.get("CORE", "").lower()
  369. arch_ext = build_config.get("ARCH_EXT", "")
  370. supported_arch = os.environ.get("SDK_SUPPORT_ARCH")
  371. if core and supported_arch:
  372. core_archs = parse_makefile_core()
  373. if core in core_archs:
  374. core_arch = core_archs[core]
  375. if not check_arch_compatibility(core_arch, arch_ext, supported_arch):
  376. return True, f"Core {core} with extensions {arch_ext} not supported by {supported_arch}"
  377. # Continue with existing extension filtering
  378. archext = build_config.get("ARCH_EXT", None)
  379. if archext is None or archext.strip() == "":
  380. return False, ""
  381. first_part = None
  382. rest_part = None
  383. if archext.startswith("_") == False:
  384. if "_" in archext:
  385. first_part, rest_part = archext.split("_", 1)
  386. else:
  387. if archext.startswith("z"):
  388. rest_part = archext
  389. else:
  390. first_part = archext
  391. else:
  392. rest_part = archext
  393. ignored_exts = os.environ.get("SDK_IGNORED_EXTS")
  394. if ignored_exts is None:
  395. return False, ""
  396. unique_exts = list(
  397. OrderedDict.fromkeys(part.strip() for part in ignored_exts.split('_'))
  398. )
  399. if len(unique_exts) == 1 and unique_exts[0] == "":
  400. return False, ""
  401. for ext in unique_exts:
  402. if len(ext) == 0:
  403. continue
  404. if len(ext) == 1:
  405. # handle single letter
  406. if first_part and ext in first_part:
  407. return True, "Filtered by %s extension" %(ext)
  408. else:
  409. # handle multi letter
  410. if rest_part and ext in rest_part:
  411. return True, "Filtered by %s extension" % (ext)
  412. except:
  413. pass
  414. return False, ""
  415. class NThread(Thread):
  416. def __init__(self, func, args):
  417. super(NThread, self).__init__()
  418. self.func = func
  419. self.args = args
  420. def run(self):
  421. self.result = self.func(*self.args)
  422. def get_result(self):
  423. try:
  424. return self.result
  425. except Exception:
  426. return None
  427. YAML_OK=0
  428. YAML_NOFILE=1
  429. YAML_INVAILD=2
  430. def load_yaml(file):
  431. if isinstance(file, str) == False or os.path.isfile(file) == False:
  432. return YAML_NOFILE, None
  433. try:
  434. data = yaml.load(open(file, 'r'), Loader=yaml.FullLoader)
  435. return YAML_OK, data
  436. except:
  437. print("Error: %s is an invalid yaml file!" % (file))
  438. return YAML_INVAILD, None
  439. def save_yaml(file, data):
  440. if isinstance(file, str) == False:
  441. return False
  442. try:
  443. with open(file, "w") as cf:
  444. yaml.dump(data, cf, indent=4)
  445. return True
  446. except:
  447. print("Error: Data can't be serialized to yaml file!")
  448. return False
  449. def get_specific_key_value(dictdata:dict, key):
  450. if not dictdata:
  451. print("Error: dictdata doesn't exist!")
  452. return None
  453. value = dictdata.get(key, None)
  454. if not value:
  455. print("Error, key %s has no value!" % (key))
  456. return None
  457. return value
  458. JSON_OK=0
  459. JSON_NOFILE=1
  460. JSON_INVAILD=2
  461. def load_json(file):
  462. if isinstance(file, str) == False or os.path.isfile(file) == False:
  463. return JSON_NOFILE, None
  464. try:
  465. data = json.load(open(file, 'r'))
  466. return JSON_OK, data
  467. except:
  468. print("Error: %s is an invalid json file!" % (file))
  469. return JSON_INVAILD, None
  470. def save_json(file, data):
  471. if isinstance(file, str) == False:
  472. return False
  473. try:
  474. with open(file, "w") as cf:
  475. json.dump(data, cf, indent=4)
  476. return True
  477. except:
  478. print("Error: Data can't be serialized to json file!")
  479. return False
  480. def save_csv(file, csvlines, display=True):
  481. if isinstance(csvlines, list) == False:
  482. return False
  483. # Flush stdout buffer
  484. sys.stdout.flush()
  485. try:
  486. with open(file, "w") as cf:
  487. for line in csvlines:
  488. csvline = line + "\n"
  489. cf.write(csvline)
  490. cf.flush()
  491. if display:
  492. try:
  493. # sometimes facing issue BlockingIOError: [Errno 11] write could not complete without blocking here
  494. # maybe related to https://bugs.python.org/issue40634 since we are using async in this tool
  495. sys.stdout.flush()
  496. print("CSV, %s" % line)
  497. except:
  498. pass
  499. return True
  500. except:
  501. print("Error: Data can't be saved to file!")
  502. return False
  503. # Return possible serports, return a list of possible serports
  504. def find_possible_serports():
  505. comports = serial.tools.list_ports.comports()
  506. serports = [ port.device for port in comports ]
  507. return serports
  508. def find_serport_by_no(serno):
  509. comports = serial.tools.list_ports.comports()
  510. serport = None
  511. for port in comports:
  512. cur_serno = port.serial_number
  513. cur_dev = port.device
  514. cur_loc = port.location
  515. if cur_serno is None:
  516. continue
  517. if sys.platform == "win32":
  518. if (serno + 'B') == cur_serno:
  519. serport = cur_dev
  520. break
  521. else:
  522. if serno != cur_serno:
  523. continue
  524. # serial is the second device of the composite device
  525. if cur_loc.endswith(".1"):
  526. serport = cur_dev
  527. break
  528. # serport founded
  529. return serport
  530. def find_most_possible_serport():
  531. serports = find_possible_serports()
  532. if len(serports) > 0:
  533. # sort the ports
  534. serports.sort()
  535. # get the biggest port
  536. # for /dev/ttyUSB0, /dev/ttyUSB1, get /dev/ttyUSB1
  537. # for COM16, COM17, get COM17
  538. return serports[-1]
  539. else:
  540. return None
  541. # get from https://gist.github.com/angstwad/bf22d1822c38a92ec0a9
  542. def dict_merge(dct, merge_dct):
  543. """ Recursive dict merge. Inspired by :meth:``dict.update()``, instead of
  544. updating only top-level keys, dict_merge recurses down into dicts nested
  545. to an arbitrary depth, updating keys. The ``merge_dct`` is merged into
  546. ``dct``.
  547. :param dct: dict onto which the merge is executed
  548. :param merge_dct: dct merged into dct
  549. :return: None
  550. """
  551. for k, v in merge_dct.items():
  552. if (k in dct and isinstance(dct[k], dict)
  553. and isinstance(merge_dct[k], Mapping)):
  554. dict_merge(dct[k], merge_dct[k])
  555. else:
  556. dct[k] = merge_dct[k]
  557. def get_make_csv(app, config):
  558. make_options = " "
  559. SUPPORT_KEYS = ["SOC", "BOARD", "CORE", "DOWNLOAD", "VARIANT", \
  560. "BENCH_UNIT", "BENCH_FLAGS", "ARCH_EXT", "STDCLIB", "SILENT", "V"]
  561. csv_print = "CSV, APP=%s" % (app)
  562. if isinstance(config, dict):
  563. for key in config:
  564. if key not in SUPPORT_KEYS:
  565. continue
  566. option = "%s=%s"%(key, config[key])
  567. make_options = " %s %s " % (make_options, option)
  568. csv_print = "%s, %s" % (csv_print, option)
  569. return make_options, csv_print
  570. def try_decode_bytes(bytes):
  571. ENCODING_LIST = ['utf-8', 'gbk', 'gb18030']
  572. destr = ""
  573. for encoding in ENCODING_LIST:
  574. try:
  575. destr = bytes.decode(encoding)
  576. break
  577. except:
  578. continue
  579. return destr
  580. def kill_async_subprocess(proc):
  581. startticks = time.time()
  582. if proc is not None:
  583. try:
  584. kill_sig = signal.SIGTERM
  585. if sys.platform != "win32":
  586. kill_sig = signal.SIGKILL
  587. print("Try to Kill process id %d now" %(proc.pid))
  588. parent_proc = psutil.Process(proc.pid)
  589. try:
  590. # This might cause PermissionError: [Errno 1] Operation not permitted: '/proc/1/stat' issue
  591. child_procs = parent_proc.children(recursive=True)
  592. for child_proc in child_procs:
  593. print("Kill child process %s, pid %d" %(child_proc.name(), child_proc.pid))
  594. try:
  595. os.kill(child_proc.pid, kill_sig) # kill child process
  596. except:
  597. continue
  598. except Exception as exc:
  599. print("Warning: kill child process failed with %s" %(exc))
  600. if parent_proc.is_running():
  601. print("Kill parent process %s, pid %d" %(parent_proc.name(), parent_proc.pid))
  602. if sys.platform != "win32":
  603. try:
  604. os.killpg(parent_proc.pid, kill_sig) # kill parent process
  605. except:
  606. os.kill(parent_proc.pid, kill_sig) # kill parent process
  607. else:
  608. os.kill(parent_proc.pid, kill_sig) # kill parent process
  609. # kill using process.kill again
  610. if parent_proc.is_running():
  611. proc.kill()
  612. except psutil.NoSuchProcess:
  613. pass
  614. except Exception as exc:
  615. print("Warning: kill process failed with %s" %(exc))
  616. # show time cost for kill process
  617. print("kill process used %.2f seconds" %((time.time() - startticks)))
  618. sys.stdout.flush()
  619. pass
  620. def kill_subprocess(proc):
  621. try:
  622. if proc.poll() is None: # process is still running
  623. kill_async_subprocess(proc)
  624. except:
  625. pass
  626. pass
  627. def import_module(module_name, file_path):
  628. if file_path is None or os.path.isfile(file_path) == False:
  629. return None
  630. try:
  631. spec = importlib.util.spec_from_file_location(module_name, file_path)
  632. module = importlib.util.module_from_spec(spec)
  633. spec.loader.exec_module(module)
  634. except:
  635. module = None
  636. return module
  637. def import_function(func_name, file_path):
  638. module_name = "tempmodule_%s" % (random.randint(0, 10000))
  639. tmpmodule = import_module(module_name, file_path)
  640. if tmpmodule is None:
  641. return None
  642. if func_name not in dir(tmpmodule):
  643. return None
  644. return getattr(tmpmodule, func_name)
  645. COMMAND_RUNOK=0
  646. COMMAND_INVALID=1
  647. COMMAND_FAIL=2
  648. COMMAND_INTERRUPTED=3
  649. COMMAND_EXCEPTION=4
  650. COMMAND_NOTAPP=5
  651. COMMAND_TIMEOUT=6
  652. COMMAND_TIMEOUT_READ=7
  653. RUNSTATUS_OK=0
  654. RUNSTATUS_FAIL=1
  655. RUNSTATUS_NOTSTART=2
  656. def run_command(command, show_output=True, logfile=None, append=False):
  657. logfh = None
  658. ret = COMMAND_RUNOK
  659. cmd_elapsed_ticks = 0
  660. if isinstance(command, str) == False:
  661. return COMMAND_INVALID, cmd_elapsed_ticks
  662. startticks = time.time()
  663. process = None
  664. try:
  665. if isinstance(logfile, str):
  666. if append:
  667. logfh = open(logfile, "ab")
  668. else:
  669. logfh = open(logfile, "wb")
  670. if logfh:
  671. # record command run in log file
  672. logfh.write(("Execute Command %s\n" % (command)).encode())
  673. process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, \
  674. stderr=subprocess.STDOUT)
  675. while True:
  676. line = process.stdout.readline()
  677. if (not line) and process.poll() is not None:
  678. break
  679. if show_output:
  680. print(try_decode_bytes(line), end="")
  681. if logfh:
  682. logfh.write(line)
  683. time.sleep(0.01)
  684. process.communicate(30)
  685. if process.returncode != 0:
  686. ret = COMMAND_FAIL
  687. except (KeyboardInterrupt):
  688. print("Key CTRL-C pressed, command executing stopped!")
  689. ret = COMMAND_INTERRUPTED
  690. except subprocess.TimeoutExpired:
  691. ret = COMMAND_TIMEOUT
  692. except Exception as exc:
  693. print("Unexpected exception happened: %s" %(str(exc)))
  694. ret = COMMAND_EXCEPTION
  695. finally:
  696. kill_subprocess(process)
  697. if process:
  698. del process
  699. if logfh:
  700. logfh.close()
  701. cmd_elapsed_ticks = time.time() - startticks
  702. return ret, cmd_elapsed_ticks
  703. async def run_cmd_and_check_async(command, timeout:int, checks:dict, checktime=time.time(), sdk_check=False, logfile=None, show_output=False, banner_timeout=3):
  704. logfh = None
  705. ret = COMMAND_FAIL
  706. cmd_elapsed_ticks = 0
  707. if isinstance(command, str) == False:
  708. return COMMAND_INVALID, cmd_elapsed_ticks
  709. startticks = time.time()
  710. process = None
  711. check_status = False
  712. pass_checks = checks.get("PASS", [])
  713. fail_checks = checks.get("FAIL", [])
  714. def test_in_check(string, checks):
  715. if type(checks) == list:
  716. for check in checks:
  717. if check in string:
  718. return True
  719. return False
  720. NSDK_CHECK_TAG = get_sdk_checktag()
  721. if get_sdk_verb_buildmsg():
  722. print("Checker used: ", checks)
  723. print("SDK Checker Tag \"%s\", checker enable %s" % (NSDK_CHECK_TAG, sdk_check))
  724. print("SDK run timeout %s, banner timeout %s" % (timeout, banner_timeout))
  725. check_finished = False
  726. start_time = time.time()
  727. serial_log = ""
  728. nsdk_check_timeout = banner_timeout
  729. sdk_checkstarttime = time.time()
  730. try:
  731. if isinstance(logfile, str):
  732. logfh = open(logfile, "wb")
  733. if sys.platform != "win32":
  734. # add exec to running command to avoid create a process called /bin/sh -c
  735. # and if you kill that process it will kill this sh process not the really
  736. # command process you want to kill
  737. process = await asyncio.create_subprocess_shell("exec " + command, \
  738. stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT)
  739. else:
  740. process = await asyncio.create_subprocess_shell(command, \
  741. stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT)
  742. while (time.time() - start_time) < timeout:
  743. try:
  744. linebytes = await asyncio.wait_for(process.stdout.readline(), 1)
  745. except asyncio.TimeoutError:
  746. if sdk_check == True:
  747. linebytes = None
  748. else:
  749. continue
  750. except KeyboardInterrupt:
  751. print("Key CTRL-C pressed, command executing stopped!")
  752. break
  753. except:
  754. break
  755. if linebytes:
  756. line = str(try_decode_bytes(linebytes)).replace('\r', '')
  757. else:
  758. line = ""
  759. if sdk_check == True:
  760. if (time.time() - sdk_checkstarttime) > nsdk_check_timeout:
  761. print("No SDK banner found in %s s, quit now!" % (nsdk_check_timeout))
  762. ret = COMMAND_TIMEOUT
  763. check_status = False
  764. break
  765. if line == "":
  766. continue
  767. if show_output:
  768. print("XXX Check " + line, end='')
  769. if NSDK_CHECK_TAG in line:
  770. timestr = line.split(NSDK_CHECK_TAG)[-1].strip()
  771. cur_time = time.mktime(time.strptime(timestr, "%b %d %Y, %H:%M:%S"))
  772. if int(cur_time) >= int(checktime):
  773. sdk_check = False
  774. line = NSDK_CHECK_TAG + " " + timestr + "\n"
  775. serial_log = serial_log + str(line)
  776. else:
  777. serial_log = serial_log + str(line)
  778. if show_output:
  779. print(line, end='')
  780. if check_finished == False:
  781. if test_in_check(line, fail_checks):
  782. check_status = False
  783. check_finished = True
  784. if test_in_check(line, pass_checks):
  785. check_status = True
  786. check_finished = True
  787. if check_finished:
  788. ret = COMMAND_RUNOK
  789. # record another 2 seconds by reset start_time and timeout to 2
  790. start_time = time.time()
  791. timeout = 1
  792. if logfh and linebytes:
  793. logfh.write(linebytes)
  794. time.sleep(0.01)
  795. except (KeyboardInterrupt):
  796. print("Key CTRL-C pressed, command executing stopped!")
  797. ret = COMMAND_INTERRUPTED
  798. except Exception as exc:
  799. print("Unexpected exception happened: %s" %(str(exc)))
  800. ret = COMMAND_EXCEPTION
  801. finally:
  802. # kill this process
  803. kill_async_subprocess(process)
  804. if logfh:
  805. logfh.close()
  806. cmd_elapsed_ticks = time.time() - startticks
  807. return check_status, cmd_elapsed_ticks
  808. def run_cmd_and_check(command, timeout:int, checks:dict, checktime=time.time(), sdk_check=False, logfile=None, show_output=False, banner_timeout=30):
  809. loop = asyncio.get_event_loop()
  810. try:
  811. ret, cmd_elapsed_ticks = loop.run_until_complete( \
  812. run_cmd_and_check_async(command, timeout, checks, checktime, sdk_check, logfile, show_output, banner_timeout))
  813. except KeyboardInterrupt:
  814. print("Key CTRL-C pressed, command executing stopped!")
  815. ret, cmd_elapsed_ticks = False, 0
  816. finally:
  817. if sys.platform != "win32":
  818. os.system("stty echo 2> /dev/null")
  819. return ret, cmd_elapsed_ticks
  820. def find_files(fndir, pattern, recursive=False):
  821. fndir = os.path.normpath(fndir)
  822. files = glob.glob(os.path.join(fndir, pattern), recursive=recursive)
  823. return files
  824. def get_logfile(appdir, startdir, logdir, logname):
  825. relpath = os.path.relpath(appdir, startdir)
  826. _, startdir_basename = os.path.splitdrive(startdir)
  827. applogdir = os.path.join(os.path.relpath(logdir + os.sep + startdir_basename), relpath)
  828. applog = os.path.relpath(os.path.join(applogdir, logname))
  829. applogdir = os.path.dirname(applog)
  830. if os.path.isdir(applogdir) == False:
  831. os.makedirs(applogdir)
  832. return applog
  833. def strtofloat(value):
  834. fval = 0.0
  835. try:
  836. match = re.search(r'[+-]?\d*\.?\d+([Ee][+-]?\d+)?', value.strip())
  837. if match:
  838. fval = float(match.group())
  839. except:
  840. pass
  841. return fval
  842. def check_tool_version(ver_cmd, ver_check):
  843. vercmd_log = tempfile.mktemp()
  844. ret, _ = run_command(ver_cmd, show_output=False, logfile=vercmd_log)
  845. check_sts = False
  846. verstr = None
  847. if ret == COMMAND_RUNOK:
  848. with open(vercmd_log, 'r', errors='ignore') as vlf:
  849. for line in vlf.readlines():
  850. if ver_check in line:
  851. verstr = line.strip()
  852. check_sts = True
  853. break
  854. os.remove(vercmd_log)
  855. return check_sts, verstr
  856. def get_elfsize(elf):
  857. sizeinfo = {"text": -1, "data": -1, "bss": -1, "total": -1}
  858. if os.path.isfile(elf) == False:
  859. return sizeinfo
  860. for sizetool in [ "riscv-nuclei-elf-size", "riscv64-unknown-elf-size", "size" ]:
  861. sizecmd = "%s %s" % (sizetool, elf)
  862. sizelog = tempfile.mktemp()
  863. ret, _ = run_command(sizecmd, show_output=False, logfile=sizelog)
  864. if ret == COMMAND_RUNOK:
  865. with open(sizelog, "r", errors='ignore') as sf:
  866. lines = sf.readlines()
  867. datas = lines[-1].strip().split()
  868. sizeinfo["text"] = int(datas[0])
  869. sizeinfo["data"] = int(datas[1])
  870. sizeinfo["bss"] = int(datas[2])
  871. sizeinfo["total"] = int(datas[3])
  872. os.remove(sizelog)
  873. break
  874. else:
  875. os.remove(sizelog)
  876. return sizeinfo
  877. def merge_config_with_makeopts(config, make_options):
  878. opt_splits=make_options.strip().split()
  879. passed_buildcfg = dict()
  880. for opt in opt_splits:
  881. if "=" in opt:
  882. values = opt.split("=")
  883. # Make new build config
  884. if (len(values) == 2):
  885. passed_buildcfg[values[0]] = values[1]
  886. build_cfg = config.get("build_config", None)
  887. if build_cfg is None:
  888. config["build_config"] = passed_buildcfg
  889. else:
  890. # update build_config using parsed config via values specified in make_options
  891. config["build_config"].update(passed_buildcfg)
  892. return config
  893. # merge config dict and args dict
  894. # args will overwrite config
  895. def merge_config_with_args(config, args_dict):
  896. if isinstance(config, dict) == False:
  897. return None
  898. if isinstance(args_dict, dict) == False:
  899. return config
  900. serport = args_dict.get("serport", None)
  901. baudrate = args_dict.get("baudrate", None)
  902. make_options = args_dict.get("make_options", None)
  903. parallel = args_dict.get("parallel", None)
  904. build_target = args_dict.get("build_target", None)
  905. run_target = args_dict.get("run_target", None)
  906. timeout = args_dict.get("timeout", None)
  907. ncycm = args_dict.get("ncycm", None)
  908. if isinstance(config, dict) == False:
  909. return None
  910. new_config = copy.deepcopy(config)
  911. if serport or baudrate or run_target:
  912. run_cfg = new_config.get("run_config", None)
  913. if run_cfg is None:
  914. new_config["run_config"] = {"hardware":{}}
  915. elif "hardware" not in run_cfg:
  916. new_config["run_config"]["hardware"] = {}
  917. if serport:
  918. new_config["run_config"]["hardware"]["serport"] = str(serport)
  919. if baudrate:
  920. new_config["run_config"]["hardware"]["serport"] = int(baudrate)
  921. if run_target:
  922. new_config["run_config"]["target"] = str(run_target)
  923. run_target = new_config["run_config"].get("target", "hardware")
  924. if run_target not in new_config["run_config"]:
  925. new_config["run_config"][run_target] = dict()
  926. if ncycm:
  927. if "ncycm" not in new_config["run_config"]:
  928. new_config["run_config"]["ncycm"] = dict()
  929. new_config["run_config"]["ncycm"]["ncycm"] = os.path.abspath(ncycm)
  930. if timeout: # set timeout
  931. try:
  932. timeout = int(timeout)
  933. except:
  934. timeout = 60
  935. new_config["run_config"][run_target]["timeout"] = timeout
  936. if build_target is not None:
  937. new_config["build_target"] = build_target
  938. if parallel is not None:
  939. new_config["parallel"] = parallel
  940. if make_options:
  941. new_config = merge_config_with_makeopts(new_config, make_options)
  942. return new_config
  943. # merge two config, now is appcfg, another is hwcfg
  944. # hwcfg will overwrite configuration in appcfg
  945. def merge_two_config(appcfg, hwcfg):
  946. if isinstance(appcfg, dict) == True and isinstance(hwcfg, dict) == False:
  947. return appcfg
  948. if isinstance(appcfg, dict) == False and isinstance(hwcfg, dict) == True:
  949. return hwcfg
  950. merged_appcfg = copy.deepcopy(appcfg)
  951. dict_merge(merged_appcfg, hwcfg)
  952. return merged_appcfg
  953. def set_global_variables(config):
  954. global SDK_GLOBAL_VARIABLES
  955. if isinstance(config, dict) == False:
  956. return False
  957. if "global_variables" in config:
  958. dict_merge(SDK_GLOBAL_VARIABLES, config["global_variables"])
  959. print("Using global variables: %s" % SDK_GLOBAL_VARIABLES)
  960. return True
  961. def get_app_runresult(apprst):
  962. if not isinstance(apprst, dict):
  963. return "unknown", "-"
  964. if "type" not in apprst:
  965. return "unknown", "-"
  966. rsttype = apprst["type"]
  967. rstvaluedict = apprst.get("value", dict())
  968. if rstvaluedict and len(rstvaluedict) < 3:
  969. rstval = ""
  970. for key in rstvaluedict:
  971. rstval += "%s : %s;" %(key, rstvaluedict[key])
  972. rstval = rstval.rstrip(';')
  973. else:
  974. rstval = "-"
  975. return rsttype, rstval
  976. def save_execute_csv(result, csvfile):
  977. if isinstance(result, dict) == False:
  978. return False
  979. csvlines = ["App, buildstatus, runstatus, buildtime, runtime, type, value, total, text, data, bss"]
  980. for app in result:
  981. size = result[app]["size"]
  982. app_status = result[app]["status"]
  983. app_time = result[app]["time"]
  984. apprsttype, apprstval = get_app_runresult(result[app].get("result", dict()))
  985. csvline ="%s, %s, %s, %s, %s, %s, %s, %d, %d, %d, %d" % (app, app_status["build"], \
  986. app_status.get("run", False), app_time.get("build", "-"), app_time.get("run", "-"), \
  987. apprsttype, apprstval, size["total"], size["text"], size["data"], size["bss"])
  988. csvlines.append(csvline)
  989. display = get_sdk_verb_buildmsg()
  990. save_csv(csvfile, csvlines, display)
  991. return True
  992. def save_bench_csv(result, csvfile):
  993. if isinstance(result, dict) == False:
  994. return False
  995. csvlines = ["App, case, buildstatus, runstatus, buildtime, runtime, type, value, total, text, data, bss"]
  996. for app in result:
  997. appresult = result[app]
  998. for case in appresult:
  999. size = appresult[case]["size"]
  1000. app_status = appresult[case]["status"]
  1001. app_time = appresult[case]["time"]
  1002. apprsttype, apprstval = get_app_runresult(appresult[case].get("result", dict()))
  1003. csvline = "%s, %s, %s, %s, %s, %s, %s, %s, %d, %d, %d, %d" % (app, case, app_status["build"], \
  1004. app_status.get("run", False), app_time.get("build", "-"), app_time.get("run", "-"), \
  1005. apprsttype, apprstval, size["total"], size["text"], size["data"], size["bss"])
  1006. csvlines.append(csvline)
  1007. # save csv file
  1008. display = get_sdk_verb_buildmsg()
  1009. save_csv(csvfile, csvlines, display)
  1010. return True
  1011. def find_local_appconfig(appdir, localcfgs):
  1012. if isinstance(appdir, str) and isinstance(localcfgs, dict):
  1013. if appdir in localcfgs:
  1014. return appdir
  1015. else:
  1016. foundcfg = None
  1017. for localcfg in localcfgs:
  1018. localcfgtp = localcfg.strip('/')
  1019. striped_dir = appdir.split(localcfgtp, 1)
  1020. if len(striped_dir) == 2:
  1021. striped_dir = striped_dir[1]
  1022. else:
  1023. striped_dir = appdir
  1024. if striped_dir != appdir:
  1025. if striped_dir.startswith('/'):
  1026. if foundcfg is None:
  1027. foundcfg = localcfg
  1028. else:
  1029. if len(foundcfg) < len(localcfg):
  1030. foundcfg = localcfg
  1031. return foundcfg
  1032. else:
  1033. return None
  1034. def fix_evalsoc_verilog_ncycm(verilog):
  1035. if os.path.isfile(verilog) == False:
  1036. return ""
  1037. vfct = ""
  1038. with open(verilog, "r", errors='ignore') as vf:
  1039. for line in vf.readlines():
  1040. line = line.replace("@80", "@00").replace("@90", "@08")
  1041. vfct += line
  1042. verilog_new = verilog + ".ncycm"
  1043. with open(verilog_new, "w") as vf:
  1044. vf.write(vfct)
  1045. return verilog_new
  1046. PROGRAM_UNKNOWN="unknown"
  1047. PROGRAM_BAREBENCH="barebench"
  1048. PROGRAM_COREMARK="coremark"
  1049. PROGRAM_DHRYSTONE="dhrystone"
  1050. PROGRAM_WHETSTONE="whetstone"
  1051. def parse_benchmark_compatiable(lines):
  1052. result = None
  1053. program_type = PROGRAM_UNKNOWN
  1054. subtype = PROGRAM_UNKNOWN
  1055. try:
  1056. for line in lines:
  1057. # Coremark
  1058. if "CoreMark" in line:
  1059. program_type = PROGRAM_BAREBENCH
  1060. subtype = PROGRAM_COREMARK
  1061. if "Iterations*1000000/total_ticks" in line:
  1062. value = line.split("=")[1].strip().split()[0]
  1063. result = dict()
  1064. result["CoreMark/MHz"] = strtofloat(value)
  1065. # Dhrystone
  1066. if "Dhrystone" in line:
  1067. program_type = PROGRAM_BAREBENCH
  1068. subtype = PROGRAM_DHRYSTONE
  1069. if "1000000/(User_Cycle/Number_Of_Runs)" in line:
  1070. value = line.split("=")[1].strip().split()[0]
  1071. result = dict()
  1072. result["DMIPS/MHz"] = strtofloat(value)
  1073. # Whetstone
  1074. if "Whetstone" in line:
  1075. program_type = PROGRAM_BAREBENCH
  1076. subtype = PROGRAM_WHETSTONE
  1077. if "MWIPS/MHz" in line:
  1078. value = line.split("MWIPS/MHz")[-1].strip().split()[0]
  1079. result = dict()
  1080. result["MWIPS/MHz"] = strtofloat(value)
  1081. except:
  1082. return program_type, subtype, result
  1083. return program_type, subtype, result
  1084. def parse_benchmark_baremetal(lines):
  1085. result = None
  1086. program_type = PROGRAM_UNKNOWN
  1087. subtype = PROGRAM_UNKNOWN
  1088. try:
  1089. unit = "unknown"
  1090. for line in lines:
  1091. stripline = line.strip()
  1092. if "csv," in stripline.lower():
  1093. csv_values = stripline.split(',')
  1094. if len(csv_values) >= 3:
  1095. key = csv_values[1].strip()
  1096. value = csv_values[-1].strip()
  1097. if key.lower() == "benchmark":
  1098. program_type = PROGRAM_BAREBENCH
  1099. unit = value
  1100. else:
  1101. subtype = key.lower()
  1102. result = dict()
  1103. result[unit] = strtofloat(value)
  1104. break
  1105. except:
  1106. return program_type, subtype, result
  1107. return program_type, subtype, result
  1108. def parse_benchmark_baremetal_csv(lines):
  1109. result = None
  1110. program_type = PROGRAM_UNKNOWN
  1111. try:
  1112. result = dict()
  1113. for line in lines:
  1114. stripline = line.strip()
  1115. if "csv," in stripline.lower():
  1116. csv_values = stripline.split(',')
  1117. if len(csv_values) >= 3:
  1118. key = csv_values[1].strip()
  1119. value = csv_values[-1].strip()
  1120. if "BENCH" not in key.upper():
  1121. result[key] = value
  1122. except:
  1123. return program_type, result
  1124. return program_type, result
  1125. def find_index(key, arr):
  1126. try:
  1127. index = arr.index(key)
  1128. except:
  1129. index = -1
  1130. return index
  1131. def parse_benchmark_runlog(lines, lgf=""):
  1132. if isinstance(lines, list) == False:
  1133. return PROGRAM_UNKNOWN, PROGRAM_UNKNOWN, None
  1134. if len(lines) == 0:
  1135. return PROGRAM_UNKNOWN, PROGRAM_UNKNOWN, None
  1136. subtype = ""
  1137. if lgf.strip() == "": # old style
  1138. program_type, subtype, result = parse_benchmark_compatiable(lines)
  1139. else:
  1140. lgf = lgf.replace("\\", "/")
  1141. appnormdirs = os.path.dirname(os.path.normpath(lgf)).replace('\\', '/').split('/')
  1142. if "baremetal/benchmark" in lgf:
  1143. # baremetal benchmark
  1144. program_type, subtype, result = parse_benchmark_baremetal(lines)
  1145. if program_type == PROGRAM_UNKNOWN:
  1146. # fallback to previous parser
  1147. program_type, subtype, result = parse_benchmark_compatiable(lines)
  1148. elif "baremetal/demo_dsp" in lgf:
  1149. program_type, result = parse_benchmark_baremetal_csv(lines)
  1150. program_type = "demo_dsp"
  1151. elif "DSP/Examples/RISCV" in lgf:
  1152. program_type, result = parse_benchmark_baremetal_csv(lines)
  1153. program_type = "nmsis_dsp_example"
  1154. index = find_index("RISCV", appnormdirs)
  1155. if index >= 0:
  1156. subtype = appnormdirs[index + 1]
  1157. elif "DSP/Test" in lgf:
  1158. program_type, result = parse_benchmark_baremetal_csv(lines)
  1159. program_type = "nmsis_dsp_tests"
  1160. index = find_index("Test", appnormdirs)
  1161. if index >= 0:
  1162. subtype = appnormdirs[index + 1]
  1163. elif "NN/Examples/RISCV" in lgf:
  1164. program_type, result = parse_benchmark_baremetal_csv(lines)
  1165. program_type = "nmsis_nn_example"
  1166. index = find_index("RISCV", appnormdirs)
  1167. if index >= 0:
  1168. subtype = appnormdirs[index + 1]
  1169. elif "NN/Tests" in lgf:
  1170. program_type, result = parse_benchmark_baremetal_csv(lines)
  1171. if "full" in appnormdirs:
  1172. program_type = "nmsis_nn_test_full"
  1173. subtype = "full"
  1174. else:
  1175. program_type = "nmsis_nn_test_percase"
  1176. index = find_index("percase", appnormdirs)
  1177. if index >= 0:
  1178. subtype = appnormdirs[index + 1]
  1179. else:
  1180. program_type, subtype, result = parse_benchmark_compatiable(lines)
  1181. return program_type, subtype, result
  1182. def parse_benchmark_use_pyscript(lines, lgf, pyscript):
  1183. if isinstance(lines, list) == False:
  1184. return PROGRAM_UNKNOWN, PROGRAM_UNKNOWN, None
  1185. if len(lines) == 0:
  1186. return PROGRAM_UNKNOWN, PROGRAM_UNKNOWN, None
  1187. # function should named parse_benchmark
  1188. # function argument and return like parse_benchmark_runlog
  1189. parsefunc = import_function("parse_benchmark", pyscript)
  1190. if parsefunc is None:
  1191. return PROGRAM_UNKNOWN, PROGRAM_UNKNOWN, None
  1192. try:
  1193. program_type, subtype, result = parsefunc(lines, lgf)
  1194. return program_type, subtype, result
  1195. except Exception as exc:
  1196. print("ERROR: Parse using %s script error: %s" %(pyscript, exc))
  1197. return PROGRAM_UNKNOWN, PROGRAM_UNKNOWN, None
  1198. def check_tool_exist(tool):
  1199. exist = False
  1200. if sys.platform == 'win32':
  1201. if os.system("where %s" % (tool)) == 0:
  1202. exist = True
  1203. else:
  1204. if os.system("which %s" % (tool)) == 0:
  1205. exist = True
  1206. return exist
  1207. def find_vivado_cmd():
  1208. for vivado_cmd in ("vivado", "vivado_lab"):
  1209. if sys.platform == 'win32':
  1210. if os.system("where %s" % (vivado_cmd)) == 0:
  1211. return vivado_cmd
  1212. else:
  1213. if os.system("which %s" % (vivado_cmd)) == 0:
  1214. return vivado_cmd
  1215. return None
  1216. def datetime_now():
  1217. return datetime.datetime.now().strftime(DATE_FORMATE)
  1218. def program_fpga(bit, target):
  1219. if os.path.isfile(bit) == False:
  1220. print("Can't find bitstream in %s" % (bit))
  1221. return False
  1222. print("Try to program fpga bitstream %s to target board %s" % (bit, target))
  1223. sys.stdout.flush()
  1224. FILE_LOCK = os.path.join(get_tmpdir(), FILE_LOCK_NAME)
  1225. # TODO: use portable filelock for win32
  1226. with open(FILE_LOCK, 'w+') as filelock:
  1227. if sys.platform != "win32":
  1228. print("%s, Wait another board's programing fpga to finished" %(datetime_now()))
  1229. fcntl.flock(filelock, fcntl.LOCK_EX)
  1230. # set to 666, in case that other user can't access this file causing exception
  1231. if os.stat(FILE_LOCK).st_uid == os.getuid():
  1232. os.chmod(FILE_LOCK, stat.S_IWGRP | stat.S_IRGRP | stat.S_IWUSR | stat.S_IRUSR | stat.S_IWOTH | stat.S_IROTH)
  1233. print("%s, Has acquired the chance to do fpga programing!" %(datetime_now()))
  1234. vivado_cmd = find_vivado_cmd()
  1235. # check vivado is found or not
  1236. if vivado_cmd == None:
  1237. print("vivado is not found in PATH, please check!")
  1238. return False
  1239. tcl = os.path.join(os.path.dirname(os.path.realpath(__file__)), "program_bit.tcl")
  1240. target = "*%s" % (target)
  1241. progcmd = "%s -mode batch -nolog -nojournal -source %s -tclargs %s %s" % (vivado_cmd, tcl, bit, target)
  1242. tmout = get_sdk_fpga_prog_tmout()
  1243. if sys.platform != 'win32' and tmout is not None and tmout.strip() != "":
  1244. print("Timeout %s do fpga program" % (tmout))
  1245. progcmd = "timeout --foreground -s SIGKILL %s %s" % (tmout, progcmd)
  1246. print("Do fpga program using command: %s" % (progcmd))
  1247. sys.stdout.flush()
  1248. ret = os.system(progcmd)
  1249. sys.stdout.flush()
  1250. if ret != 0:
  1251. print("Program fpga bit failed, error code %d" % ret)
  1252. return False
  1253. print("Program fpga bit successfully")
  1254. return True
  1255. def find_fpgas():
  1256. vivado_cmd = find_vivado_cmd()
  1257. if vivado_cmd == None:
  1258. print("vivado is not found in PATH, please check!")
  1259. return dict()
  1260. tcl = os.path.join(os.path.dirname(os.path.realpath(__file__)), "find_devices.tcl")
  1261. sys.stdout.flush()
  1262. tmp_log = tempfile.mktemp()
  1263. os.system("%s -mode batch -nolog -nojournal -source %s -notrace > %s" % (vivado_cmd, tcl, tmp_log))
  1264. sys.stdout.flush()
  1265. fpgadevices = dict()
  1266. with open(tmp_log, "r", errors='ignore') as tf:
  1267. for line in tf.readlines():
  1268. line = line.strip()
  1269. if line.startswith("CSV,") == False:
  1270. continue
  1271. splits = line.split(",")
  1272. if len(splits) != 3:
  1273. continue
  1274. fpga_serial = "/".join(splits[1].split("/")[2:])
  1275. fpgadevices[fpga_serial] = splits[2].strip()
  1276. return fpgadevices
  1277. def check_serial_port(serport):
  1278. if serport in find_possible_serports():
  1279. return True
  1280. return False
  1281. def modify_openocd_cfg(cfg, ftdi_serial):
  1282. cfg_bk = cfg + ".backup"
  1283. if (os.path.isfile(cfg)) == False:
  1284. return False
  1285. if os.path.isfile(cfg_bk) == True:
  1286. print("Restore openocd cfg %s" %(cfg))
  1287. shutil.copyfile(cfg_bk, cfg)
  1288. else:
  1289. print("Backup openocd cfg %s" %(cfg))
  1290. shutil.copyfile(cfg, cfg_bk)
  1291. found = False
  1292. contents = []
  1293. index = 0
  1294. with open(cfg, 'r', errors='ignore') as cf:
  1295. contents = cf.readlines()
  1296. for line in contents:
  1297. if line.strip().startswith("transport select"):
  1298. found = True
  1299. break
  1300. index += 1
  1301. if found == False:
  1302. return False
  1303. if sys.platform == 'win32':
  1304. ftdi_serial = "%sA" % (ftdi_serial)
  1305. contents.insert(index, "ftdi_serial %s\ntcl_port disabled\ntelnet_port disabled\n" %(ftdi_serial))
  1306. with open(cfg, 'w') as cf:
  1307. contents = "".join(contents)
  1308. cf.write(contents)
  1309. return True
  1310. GL_CPUCFGs = os.path.join(SCRIPT_DIR, "configs", "cpu")
  1311. def gen_runcfg(cpucfg, runcfg, buildconfig=dict()):
  1312. _, cpucfgdict = load_json(cpucfg)
  1313. _, runcfgdict = load_json(runcfg)
  1314. if cpucfgdict is None:
  1315. return { "build_configs": { "default": {} } }
  1316. if runcfgdict is None:
  1317. return cpucfgdict
  1318. matrixcfgs = runcfgdict.get("matrix", None)
  1319. expectedcfg = runcfgdict.get("expected", dict())
  1320. expectedscfg = runcfgdict.get("expecteds", dict())
  1321. finalruncfg = copy.deepcopy(cpucfgdict)
  1322. # merge buildconfig
  1323. finalruncfg["build_config"] = merge_two_config(finalruncfg.get("build_config", dict()), buildconfig)
  1324. finalruncfg["expected"] = merge_two_config(finalruncfg.get("expected", dict()), expectedcfg)
  1325. finalruncfg["expecteds"] = merge_two_config(finalruncfg.get("expecteds", dict()), expectedscfg)
  1326. if matrixcfgs is None:
  1327. return finalruncfg
  1328. bcfgs = cpucfgdict.get("build_configs", dict())
  1329. newbcfgs = dict()
  1330. for bkey in bcfgs:
  1331. for key in matrixcfgs:
  1332. cfgkey = "%s-%s" % (bkey, key)
  1333. newbcfgs[cfgkey] = merge_two_config(bcfgs[bkey], matrixcfgs[key])
  1334. if len(newbcfgs) > 1:
  1335. finalruncfg["build_configs"] = newbcfgs
  1336. else:
  1337. finalruncfg["build_configs"] = bcfgs
  1338. return finalruncfg
  1339. def gen_coreruncfg(core, runcfg, choice="mini", buildconfig=dict(), casedir=None):
  1340. cpucfgsloc = os.path.join(GL_CPUCFGs, choice)
  1341. if casedir is not None:
  1342. tmp = os.path.join(casedir, choice)
  1343. if os.path.isdir(tmp) == True:
  1344. cpucfgsloc = os.path.realpath(tmp)
  1345. print("Use cpu configs in location %s directory" % (cpucfgsloc))
  1346. cpucfg = os.path.join(cpucfgsloc, "%s.json" % (core))
  1347. return gen_runcfg(cpucfg, runcfg, buildconfig)
  1348. def gen_coreruncfg_custom(core, runcfg, customcfgdir, buildconfig=dict()):
  1349. cpucfg = os.path.join(customcfgdir, "%s.json" % (core))
  1350. return gen_runcfg(cpucfg, runcfg, buildconfig)
  1351. def gen_runyaml(core, locs, fpga_serial, ftdi_serial, cycm, fpgabit, boardtype, ocdcfg, appcfg, hwcfg):
  1352. runyaml = { "runcfg": {"runner": "fpga"},
  1353. "fpga_runners": { core: {
  1354. "board_type": boardtype, "fpga_serial": fpga_serial,
  1355. "ftdi_serial": ftdi_serial, "serial_port": ""}
  1356. },
  1357. "ncycm_runners": { core: {
  1358. "model": cycm if cycm else "" }
  1359. },
  1360. "configs": { core: {
  1361. "fpga": boardtype, "bitstream": fpgabit,
  1362. "ncycm": core, "openocd_cfg": ocdcfg,
  1363. "appcfg": appcfg, "hwcfg": hwcfg }
  1364. },
  1365. "environment": {
  1366. "fpgaloc": locs.get("fpgaloc", ""),
  1367. "ncycmloc": locs.get("ncycmloc", ""),
  1368. "cfgloc": locs.get("cfgloc", "")
  1369. }
  1370. }
  1371. if cycm is not None:
  1372. runyaml["runcfg"]["runner"] = "ncycm"
  1373. return runyaml