nsdk_utils.py 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516
  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 update_list_items(list1, list2):
  954. for i in range(0, len(list2)):
  955. if list2[i] not in list1:
  956. list1.append(list2[i])
  957. return list1
  958. def set_global_variables(config):
  959. global SDK_GLOBAL_VARIABLES
  960. if isinstance(config, dict) == False:
  961. return False
  962. if "global_variables" in config:
  963. dict_merge(SDK_GLOBAL_VARIABLES, config["global_variables"])
  964. print("Using global variables: %s" % SDK_GLOBAL_VARIABLES)
  965. return True
  966. def get_app_runresult(apprst):
  967. if not isinstance(apprst, dict):
  968. return "unknown", "-"
  969. if "type" not in apprst:
  970. return "unknown", "-"
  971. rsttype = apprst["type"]
  972. rstvaluedict = apprst.get("value", dict())
  973. if rstvaluedict and len(rstvaluedict) < 3:
  974. rstval = ""
  975. for key in rstvaluedict:
  976. rstval += "%s : %s;" %(key, rstvaluedict[key])
  977. rstval = rstval.rstrip(';')
  978. else:
  979. rstval = "-"
  980. return rsttype, rstval
  981. def save_execute_csv(result, csvfile):
  982. if isinstance(result, dict) == False:
  983. return False
  984. csvlines = ["App, buildstatus, runstatus, buildtime, runtime, type, value, total, text, data, bss"]
  985. for app in result:
  986. size = result[app]["size"]
  987. app_status = result[app]["status"]
  988. app_time = result[app]["time"]
  989. apprsttype, apprstval = get_app_runresult(result[app].get("result", dict()))
  990. csvline ="%s, %s, %s, %s, %s, %s, %s, %d, %d, %d, %d" % (app, app_status["build"], \
  991. app_status.get("run", False), app_time.get("build", "-"), app_time.get("run", "-"), \
  992. apprsttype, apprstval, size["total"], size["text"], size["data"], size["bss"])
  993. csvlines.append(csvline)
  994. display = get_sdk_verb_buildmsg()
  995. save_csv(csvfile, csvlines, display)
  996. return True
  997. def save_bench_csv(result, csvfile):
  998. if isinstance(result, dict) == False:
  999. return False
  1000. csvlines = ["App, case, buildstatus, runstatus, buildtime, runtime, type, value, total, text, data, bss"]
  1001. for app in result:
  1002. appresult = result[app]
  1003. for case in appresult:
  1004. size = appresult[case]["size"]
  1005. app_status = appresult[case]["status"]
  1006. app_time = appresult[case]["time"]
  1007. apprsttype, apprstval = get_app_runresult(appresult[case].get("result", dict()))
  1008. csvline = "%s, %s, %s, %s, %s, %s, %s, %s, %d, %d, %d, %d" % (app, case, app_status["build"], \
  1009. app_status.get("run", False), app_time.get("build", "-"), app_time.get("run", "-"), \
  1010. apprsttype, apprstval, size["total"], size["text"], size["data"], size["bss"])
  1011. csvlines.append(csvline)
  1012. # save csv file
  1013. display = get_sdk_verb_buildmsg()
  1014. save_csv(csvfile, csvlines, display)
  1015. return True
  1016. def find_local_appconfig(appdir, localcfgs):
  1017. if isinstance(appdir, str) and isinstance(localcfgs, dict):
  1018. if appdir in localcfgs:
  1019. return appdir
  1020. else:
  1021. foundcfg = None
  1022. for localcfg in localcfgs:
  1023. localcfgtp = localcfg.strip('/')
  1024. striped_dir = appdir.split(localcfgtp, 1)
  1025. if len(striped_dir) == 2:
  1026. striped_dir = striped_dir[1]
  1027. else:
  1028. striped_dir = appdir
  1029. if striped_dir != appdir:
  1030. if striped_dir.startswith('/'):
  1031. if foundcfg is None:
  1032. foundcfg = localcfg
  1033. else:
  1034. if len(foundcfg) < len(localcfg):
  1035. foundcfg = localcfg
  1036. return foundcfg
  1037. else:
  1038. return None
  1039. def fix_evalsoc_verilog_ncycm(verilog):
  1040. if os.path.isfile(verilog) == False:
  1041. return ""
  1042. vfct = ""
  1043. with open(verilog, "r", errors='ignore') as vf:
  1044. for line in vf.readlines():
  1045. line = line.replace("@80", "@00").replace("@90", "@08")
  1046. vfct += line
  1047. verilog_new = verilog + ".ncycm"
  1048. with open(verilog_new, "w") as vf:
  1049. vf.write(vfct)
  1050. return verilog_new
  1051. PROGRAM_UNKNOWN="unknown"
  1052. PROGRAM_BAREBENCH="barebench"
  1053. PROGRAM_COREMARK="coremark"
  1054. PROGRAM_DHRYSTONE="dhrystone"
  1055. PROGRAM_WHETSTONE="whetstone"
  1056. def parse_benchmark_compatiable(lines):
  1057. result = None
  1058. program_type = PROGRAM_UNKNOWN
  1059. subtype = PROGRAM_UNKNOWN
  1060. try:
  1061. for line in lines:
  1062. # Coremark
  1063. if "CoreMark" in line:
  1064. program_type = PROGRAM_BAREBENCH
  1065. subtype = PROGRAM_COREMARK
  1066. if "Iterations*1000000/total_ticks" in line:
  1067. value = line.split("=")[1].strip().split()[0]
  1068. result = dict()
  1069. result["CoreMark/MHz"] = strtofloat(value)
  1070. # Dhrystone
  1071. if "Dhrystone" in line:
  1072. program_type = PROGRAM_BAREBENCH
  1073. subtype = PROGRAM_DHRYSTONE
  1074. if "1000000/(User_Cycle/Number_Of_Runs)" in line:
  1075. value = line.split("=")[1].strip().split()[0]
  1076. result = dict()
  1077. result["DMIPS/MHz"] = strtofloat(value)
  1078. # Whetstone
  1079. if "Whetstone" in line:
  1080. program_type = PROGRAM_BAREBENCH
  1081. subtype = PROGRAM_WHETSTONE
  1082. if "MWIPS/MHz" in line:
  1083. value = line.split("MWIPS/MHz")[-1].strip().split()[0]
  1084. result = dict()
  1085. result["MWIPS/MHz"] = strtofloat(value)
  1086. except:
  1087. return program_type, subtype, result
  1088. return program_type, subtype, result
  1089. def parse_benchmark_baremetal(lines):
  1090. result = None
  1091. program_type = PROGRAM_UNKNOWN
  1092. subtype = PROGRAM_UNKNOWN
  1093. try:
  1094. unit = "unknown"
  1095. for line in lines:
  1096. stripline = line.strip()
  1097. if "csv," in stripline.lower():
  1098. csv_values = stripline.split(',')
  1099. if len(csv_values) >= 3:
  1100. key = csv_values[1].strip()
  1101. value = csv_values[-1].strip()
  1102. if key.lower() == "benchmark":
  1103. program_type = PROGRAM_BAREBENCH
  1104. unit = value
  1105. else:
  1106. subtype = key.lower()
  1107. result = dict()
  1108. result[unit] = strtofloat(value)
  1109. break
  1110. except:
  1111. return program_type, subtype, result
  1112. return program_type, subtype, result
  1113. def parse_benchmark_baremetal_csv(lines):
  1114. result = None
  1115. program_type = PROGRAM_UNKNOWN
  1116. try:
  1117. result = dict()
  1118. for line in lines:
  1119. stripline = line.strip()
  1120. if "csv," in stripline.lower():
  1121. csv_values = stripline.split(',')
  1122. if len(csv_values) >= 3:
  1123. key = csv_values[1].strip()
  1124. value = csv_values[-1].strip()
  1125. if "BENCH" not in key.upper():
  1126. result[key] = value
  1127. except:
  1128. return program_type, result
  1129. return program_type, result
  1130. def find_index(key, arr):
  1131. try:
  1132. index = arr.index(key)
  1133. except:
  1134. index = -1
  1135. return index
  1136. def parse_benchmark_runlog(lines, lgf=""):
  1137. if isinstance(lines, list) == False:
  1138. return PROGRAM_UNKNOWN, PROGRAM_UNKNOWN, None
  1139. if len(lines) == 0:
  1140. return PROGRAM_UNKNOWN, PROGRAM_UNKNOWN, None
  1141. subtype = ""
  1142. if lgf.strip() == "": # old style
  1143. program_type, subtype, result = parse_benchmark_compatiable(lines)
  1144. else:
  1145. lgf = lgf.replace("\\", "/")
  1146. appnormdirs = os.path.dirname(os.path.normpath(lgf)).replace('\\', '/').split('/')
  1147. if "baremetal/benchmark" in lgf:
  1148. # baremetal benchmark
  1149. program_type, subtype, result = parse_benchmark_baremetal(lines)
  1150. if program_type == PROGRAM_UNKNOWN:
  1151. # fallback to previous parser
  1152. program_type, subtype, result = parse_benchmark_compatiable(lines)
  1153. elif "baremetal/demo_dsp" in lgf:
  1154. program_type, result = parse_benchmark_baremetal_csv(lines)
  1155. program_type = "demo_dsp"
  1156. elif "DSP/Examples/RISCV" in lgf:
  1157. program_type, result = parse_benchmark_baremetal_csv(lines)
  1158. program_type = "nmsis_dsp_example"
  1159. index = find_index("RISCV", appnormdirs)
  1160. if index >= 0:
  1161. subtype = appnormdirs[index + 1]
  1162. elif "DSP/Test" in lgf:
  1163. program_type, result = parse_benchmark_baremetal_csv(lines)
  1164. program_type = "nmsis_dsp_tests"
  1165. index = find_index("Test", appnormdirs)
  1166. if index >= 0:
  1167. subtype = appnormdirs[index + 1]
  1168. elif "DSP/Benchmark" in lgf:
  1169. program_type, result = parse_benchmark_baremetal_csv(lines)
  1170. program_type = "nmsis_dsp_benchmark"
  1171. index = find_index("Benchmark", appnormdirs)
  1172. if index >= 0:
  1173. subtype = appnormdirs[index + 1]
  1174. elif "NN/Examples/RISCV" in lgf:
  1175. program_type, result = parse_benchmark_baremetal_csv(lines)
  1176. program_type = "nmsis_nn_example"
  1177. index = find_index("RISCV", appnormdirs)
  1178. if index >= 0:
  1179. subtype = appnormdirs[index + 1]
  1180. elif "NN/Tests" in lgf:
  1181. program_type, result = parse_benchmark_baremetal_csv(lines)
  1182. if "full" in appnormdirs:
  1183. program_type = "nmsis_nn_test_full"
  1184. subtype = "full"
  1185. else:
  1186. program_type = "nmsis_nn_test_percase"
  1187. index = find_index("percase", appnormdirs)
  1188. if index >= 0:
  1189. subtype = appnormdirs[index + 1]
  1190. elif "NN/Benchmark" in lgf:
  1191. program_type, result = parse_benchmark_baremetal_csv(lines)
  1192. program_type = "nmsis_nn_benchmark"
  1193. index = find_index("Benchmark", appnormdirs)
  1194. if index >= 0:
  1195. subtype = appnormdirs[index + 1]
  1196. else:
  1197. program_type, subtype, result = parse_benchmark_compatiable(lines)
  1198. return program_type, subtype, result
  1199. def parse_benchmark_use_pyscript(lines, lgf, pyscript):
  1200. if isinstance(lines, list) == False:
  1201. return PROGRAM_UNKNOWN, PROGRAM_UNKNOWN, None
  1202. if len(lines) == 0:
  1203. return PROGRAM_UNKNOWN, PROGRAM_UNKNOWN, None
  1204. # function should named parse_benchmark
  1205. # function argument and return like parse_benchmark_runlog
  1206. parsefunc = import_function("parse_benchmark", pyscript)
  1207. if parsefunc is None:
  1208. return PROGRAM_UNKNOWN, PROGRAM_UNKNOWN, None
  1209. try:
  1210. program_type, subtype, result = parsefunc(lines, lgf)
  1211. return program_type, subtype, result
  1212. except Exception as exc:
  1213. print("ERROR: Parse using %s script error: %s" %(pyscript, exc))
  1214. return PROGRAM_UNKNOWN, PROGRAM_UNKNOWN, None
  1215. def check_tool_exist(tool):
  1216. exist = False
  1217. if sys.platform == 'win32':
  1218. if os.system("where %s" % (tool)) == 0:
  1219. exist = True
  1220. else:
  1221. if os.system("which %s" % (tool)) == 0:
  1222. exist = True
  1223. return exist
  1224. def find_vivado_cmd():
  1225. for vivado_cmd in ("vivado", "vivado_lab"):
  1226. if sys.platform == 'win32':
  1227. if os.system("where %s" % (vivado_cmd)) == 0:
  1228. return vivado_cmd
  1229. else:
  1230. if os.system("which %s" % (vivado_cmd)) == 0:
  1231. return vivado_cmd
  1232. return None
  1233. def datetime_now():
  1234. return datetime.datetime.now().strftime(DATE_FORMATE)
  1235. def program_fpga(bit, target):
  1236. if os.path.isfile(bit) == False:
  1237. print("Can't find bitstream in %s" % (bit))
  1238. return False
  1239. print("Try to program fpga bitstream %s to target board %s" % (bit, target))
  1240. sys.stdout.flush()
  1241. FILE_LOCK = os.path.join(get_tmpdir(), FILE_LOCK_NAME)
  1242. # TODO: use portable filelock for win32
  1243. with open(FILE_LOCK, 'w+') as filelock:
  1244. if sys.platform != "win32":
  1245. print("%s, Wait another board's programing fpga to finished" %(datetime_now()))
  1246. fcntl.flock(filelock, fcntl.LOCK_EX)
  1247. # set to 666, in case that other user can't access this file causing exception
  1248. if os.stat(FILE_LOCK).st_uid == os.getuid():
  1249. os.chmod(FILE_LOCK, stat.S_IWGRP | stat.S_IRGRP | stat.S_IWUSR | stat.S_IRUSR | stat.S_IWOTH | stat.S_IROTH)
  1250. print("%s, Has acquired the chance to do fpga programing!" %(datetime_now()))
  1251. vivado_cmd = find_vivado_cmd()
  1252. # check vivado is found or not
  1253. if vivado_cmd == None:
  1254. print("vivado is not found in PATH, please check!")
  1255. return False
  1256. tcl = os.path.join(os.path.dirname(os.path.realpath(__file__)), "program_bit.tcl")
  1257. target = "*%s" % (target)
  1258. progcmd = "%s -mode batch -nolog -nojournal -source %s -tclargs %s %s" % (vivado_cmd, tcl, bit, target)
  1259. tmout = get_sdk_fpga_prog_tmout()
  1260. if sys.platform != 'win32' and tmout is not None and tmout.strip() != "":
  1261. print("Timeout %s do fpga program" % (tmout))
  1262. progcmd = "timeout --foreground -s SIGKILL %s %s" % (tmout, progcmd)
  1263. print("Do fpga program using command: %s" % (progcmd))
  1264. sys.stdout.flush()
  1265. ret = os.system(progcmd)
  1266. sys.stdout.flush()
  1267. if ret != 0:
  1268. print("Program fpga bit failed, error code %d" % ret)
  1269. return False
  1270. print("Program fpga bit successfully")
  1271. return True
  1272. def find_fpgas():
  1273. vivado_cmd = find_vivado_cmd()
  1274. if vivado_cmd == None:
  1275. print("vivado is not found in PATH, please check!")
  1276. return dict()
  1277. tcl = os.path.join(os.path.dirname(os.path.realpath(__file__)), "find_devices.tcl")
  1278. sys.stdout.flush()
  1279. tmp_log = tempfile.mktemp()
  1280. os.system("%s -mode batch -nolog -nojournal -source %s -notrace > %s" % (vivado_cmd, tcl, tmp_log))
  1281. sys.stdout.flush()
  1282. fpgadevices = dict()
  1283. with open(tmp_log, "r", errors='ignore') as tf:
  1284. for line in tf.readlines():
  1285. line = line.strip()
  1286. if line.startswith("CSV,") == False:
  1287. continue
  1288. splits = line.split(",")
  1289. if len(splits) != 3:
  1290. continue
  1291. fpga_serial = "/".join(splits[1].split("/")[2:])
  1292. fpgadevices[fpga_serial] = splits[2].strip()
  1293. return fpgadevices
  1294. def check_serial_port(serport):
  1295. if serport in find_possible_serports():
  1296. return True
  1297. return False
  1298. def modify_openocd_cfg(cfg, ftdi_serial):
  1299. cfg_bk = cfg + ".backup"
  1300. if (os.path.isfile(cfg)) == False:
  1301. return False
  1302. if os.path.isfile(cfg_bk) == True:
  1303. print("Restore openocd cfg %s" %(cfg))
  1304. shutil.copyfile(cfg_bk, cfg)
  1305. else:
  1306. print("Backup openocd cfg %s" %(cfg))
  1307. shutil.copyfile(cfg, cfg_bk)
  1308. found = False
  1309. contents = []
  1310. index = 0
  1311. with open(cfg, 'r', errors='ignore') as cf:
  1312. contents = cf.readlines()
  1313. for line in contents:
  1314. if line.strip().startswith("transport select"):
  1315. found = True
  1316. break
  1317. index += 1
  1318. if found == False:
  1319. return False
  1320. if sys.platform == 'win32':
  1321. ftdi_serial = "%sA" % (ftdi_serial)
  1322. contents.insert(index, "ftdi_serial %s\ntcl_port disabled\ntelnet_port disabled\n" %(ftdi_serial))
  1323. with open(cfg, 'w') as cf:
  1324. contents = "".join(contents)
  1325. cf.write(contents)
  1326. return True
  1327. GL_CPUCFGs = os.path.join(SCRIPT_DIR, "configs", "cpu")
  1328. def gen_runcfg(cpucfg, runcfg, buildconfig=dict()):
  1329. _, cpucfgdict = load_json(cpucfg)
  1330. _, runcfgdict = load_json(runcfg)
  1331. if cpucfgdict is None:
  1332. return { "build_configs": { "default": {} } }
  1333. if runcfgdict is None:
  1334. return cpucfgdict
  1335. matrixcfgs = runcfgdict.get("matrix", None)
  1336. expectedcfg = runcfgdict.get("expected", dict())
  1337. expectedscfg = runcfgdict.get("expecteds", dict())
  1338. appdirs_ignore = runcfgdict.get("appdirs_ignore", [])
  1339. finalruncfg = copy.deepcopy(cpucfgdict)
  1340. # merge buildconfig
  1341. finalruncfg["build_config"] = merge_two_config(finalruncfg.get("build_config", dict()), buildconfig)
  1342. finalruncfg["expected"] = merge_two_config(finalruncfg.get("expected", dict()), expectedcfg)
  1343. finalruncfg["expecteds"] = merge_two_config(finalruncfg.get("expecteds", dict()), expectedscfg)
  1344. # allow pass core related ignore cases
  1345. finalruncfg["appdirs_ignore"] = update_list_items(finalruncfg.get("appdirs_ignore", []), appdirs_ignore)
  1346. if matrixcfgs is None:
  1347. return finalruncfg
  1348. bcfgs = cpucfgdict.get("build_configs", dict())
  1349. newbcfgs = dict()
  1350. for bkey in bcfgs:
  1351. for key in matrixcfgs:
  1352. cfgkey = "%s-%s" % (bkey, key)
  1353. newbcfgs[cfgkey] = merge_two_config(bcfgs[bkey], matrixcfgs[key])
  1354. if len(newbcfgs) > 1:
  1355. finalruncfg["build_configs"] = newbcfgs
  1356. else:
  1357. finalruncfg["build_configs"] = bcfgs
  1358. return finalruncfg
  1359. def gen_coreruncfg(core, runcfg, choice="mini", buildconfig=dict(), casedir=None):
  1360. cpucfgsloc = os.path.join(GL_CPUCFGs, choice)
  1361. if casedir is not None:
  1362. tmp = os.path.join(casedir, choice)
  1363. if os.path.isdir(tmp) == True:
  1364. cpucfgsloc = os.path.realpath(tmp)
  1365. print("Use cpu configs in location %s directory" % (cpucfgsloc))
  1366. cpucfg = os.path.join(cpucfgsloc, "%s.json" % (core))
  1367. return gen_runcfg(cpucfg, runcfg, buildconfig)
  1368. def gen_coreruncfg_custom(core, runcfg, customcfgdir, buildconfig=dict()):
  1369. cpucfg = os.path.join(customcfgdir, "%s.json" % (core))
  1370. return gen_runcfg(cpucfg, runcfg, buildconfig)
  1371. def gen_runyaml(core, locs, fpga_serial, ftdi_serial, cycm, fpgabit, boardtype, ocdcfg, appcfg, hwcfg):
  1372. runyaml = { "runcfg": {"runner": "fpga"},
  1373. "fpga_runners": { core: {
  1374. "board_type": boardtype, "fpga_serial": fpga_serial,
  1375. "ftdi_serial": ftdi_serial, "serial_port": ""}
  1376. },
  1377. "ncycm_runners": { core: {
  1378. "model": cycm if cycm else "" }
  1379. },
  1380. "configs": { core: {
  1381. "fpga": boardtype, "bitstream": fpgabit,
  1382. "ncycm": core, "openocd_cfg": ocdcfg,
  1383. "appcfg": appcfg, "hwcfg": hwcfg }
  1384. },
  1385. "environment": {
  1386. "fpgaloc": locs.get("fpgaloc", ""),
  1387. "ncycmloc": locs.get("ncycmloc", ""),
  1388. "cfgloc": locs.get("cfgloc", "")
  1389. }
  1390. }
  1391. if cycm is not None:
  1392. runyaml["runcfg"]["runner"] = "ncycm"
  1393. return runyaml