nsdk_builder.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967
  1. #!/usr/bin/env python3
  2. import os
  3. import sys
  4. import time
  5. import copy
  6. import shutil
  7. import glob
  8. SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
  9. requirement_file = os.path.abspath(os.path.join(SCRIPT_DIR, "..", "requirements.txt"))
  10. try:
  11. import serial
  12. import tempfile
  13. import json
  14. import argparse
  15. from threading import Thread
  16. import subprocess
  17. except:
  18. print("Please install requried packages using: pip3 install -r %s" % (requirement_file))
  19. sys.exit(1)
  20. from nsdk_utils import *
  21. VALID_MAKEFILE_NAMES = ['Makefile', 'makefile', "GNUMakefile"]
  22. def is_nuclei_demosoc(soc):
  23. if soc == "hbird" or soc == "demosoc" or soc == "evalsoc" or soc == "xlspike":
  24. return True
  25. else:
  26. return False
  27. class nsdk_builder(object):
  28. def __init__(self):
  29. pass
  30. @staticmethod
  31. def is_app(appdir):
  32. if os.path.isdir(appdir) == False:
  33. return False
  34. appdir = os.path.realpath(appdir)
  35. for mkname in VALID_MAKEFILE_NAMES:
  36. mkfile_path = os.path.join(appdir, mkname)
  37. if os.path.isfile(mkfile_path):
  38. return True
  39. return False
  40. @staticmethod
  41. def copy_objects(appsts, copydir):
  42. if isinstance(appsts, dict) and "objects" in appsts:
  43. os.makedirs(copydir, exist_ok=True)
  44. objects = appsts["objects"]
  45. if "saved_objects" not in appsts:
  46. appsts["saved_objects"] = dict()
  47. cp_keys = get_sdk_copyobjects()
  48. if cp_keys != None:
  49. cp_keys = cp_keys.strip().split(",")
  50. for obj in objects:
  51. obj_file = objects[obj]
  52. if os.path.isfile(obj_file): # only copy when exist
  53. filename = os.path.basename(obj_file)
  54. filesuffix = os.path.splitext(filename)[-1].strip(".")
  55. newfile = os.path.join(copydir, filename)
  56. if cp_keys is None or filesuffix in cp_keys:
  57. shutil.copyfile(obj_file, newfile)
  58. appsts["saved_objects"][obj] = newfile
  59. pass
  60. @staticmethod
  61. def get_objects(appdir, target=None, timestamp=None):
  62. if nsdk_builder.is_app(appdir) == False:
  63. return None
  64. def find_app_object(pattern):
  65. files = find_files(appdir, pattern)
  66. found_file = ""
  67. latest_timestamp = 0
  68. for fl in files:
  69. flct = os.stat(fl).st_ctime
  70. if timestamp:
  71. if flct >= timestamp:
  72. found_file = fl
  73. break
  74. else:
  75. # find a latest file
  76. if flct > latest_timestamp:
  77. latest_timestamp = flct
  78. found_file = fl
  79. return found_file
  80. build_objects = dict()
  81. if target:
  82. build_objects["elf"] = find_app_object("*%s.elf" % (target))
  83. build_objects["map"] = find_app_object("*%s.map" % (target))
  84. build_objects["dump"] = find_app_object("*%s.dump" % (target) )
  85. build_objects["dasm"] = find_app_object("*%s.dasm" % (target))
  86. build_objects["verilog"] = find_app_object("*%s.verilog" % (target))
  87. else:
  88. build_objects["elf"] = find_app_object("*.elf")
  89. build_objects["map"] = find_app_object("*.map")
  90. build_objects["dump"] = find_app_object("*.dump")
  91. build_objects["dasm"] = find_app_object("*.dasm")
  92. build_objects["verilog"] = find_app_object("*.verilog")
  93. return build_objects
  94. def build_target_only(self, appdir, make_options="", target="clean", show_output=True, logfile=None, parallel=""):
  95. if self.is_app(appdir) == False:
  96. return COMMAND_NOTAPP, 0
  97. # Parallel must start with -j
  98. if isinstance(parallel, str):
  99. parallel = parallel.strip()
  100. if parallel != "" and parallel.startswith("-j") == False:
  101. parallel = ""
  102. else:
  103. parallel = ""
  104. if parallel != "": # need to split targets
  105. build_targets = target.strip().split()
  106. if get_sdk_verb_buildmsg():
  107. print("Target \"%s\" are split to seperated targets %s in parallel mode." %(target, build_targets))
  108. else:
  109. build_targets = [target]
  110. if os.path.isfile(logfile):
  111. os.remove(logfile)
  112. total_ticks = 0
  113. ignore_targets = ["info", "showtoolver", "showflags", "clean", "bin", "size"]
  114. for btg in build_targets:
  115. build_cmd = "make %s -C %s %s %s" % (parallel, appdir, make_options, btg)
  116. if get_sdk_verb_buildmsg() and (not ((show_output == False) and (btg in ignore_targets))):
  117. print("Build application %s, with target: %s" % (appdir, btg))
  118. print("Build command: %s" % (build_cmd))
  119. ret, ticks = run_command(build_cmd, show_output, logfile=logfile, append=True)
  120. if get_sdk_verb_buildmsg() and (not ((show_output == False) and (btg in ignore_targets))):
  121. print("Build command return value: %s" % (ret))
  122. total_ticks += ticks
  123. if ret != 0: # if one target failed, then stop
  124. break
  125. return ret, ticks
  126. def get_build_info(self, appdir, make_options=""):
  127. infolog = tempfile.mktemp()
  128. ret, _ = self.build_target_only(appdir, make_options, "info", False, infolog)
  129. build_info = dict()
  130. if ret != COMMAND_RUNOK:
  131. os.remove(infolog)
  132. return build_info
  133. build_info = dict()
  134. with open(infolog, "r") as inf:
  135. for line in inf.readlines():
  136. line = line.strip()
  137. INFO_TAG = "Current Configuration:"
  138. if line.startswith(INFO_TAG):
  139. infos = line.replace(INFO_TAG, "").strip().split()
  140. for info in infos:
  141. splits = info.split("=")
  142. if len(splits) == 2:
  143. build_info[splits[0]] = splits[1]
  144. os.remove(infolog)
  145. return build_info
  146. def get_build_flags(self, appdir, make_options=""):
  147. flagslog = tempfile.mktemp()
  148. ret, _ = self.build_target_only(appdir, make_options, "showflags", False, flagslog)
  149. build_flags = dict()
  150. if ret != COMMAND_RUNOK:
  151. os.remove(flagslog)
  152. return build_flags
  153. build_flags = dict()
  154. with open(flagslog, "r") as inf:
  155. for line in inf.readlines():
  156. line = line.strip()
  157. if ":" in line:
  158. splits = line.split(":")
  159. if len(splits) != 2:
  160. continue
  161. key, value = splits
  162. key = key.strip()
  163. value = value.strip()
  164. build_flags[key] = value
  165. os.remove(flagslog)
  166. return build_flags
  167. def get_build_toolver(self, appdir, make_options=""):
  168. log = tempfile.mktemp()
  169. ret, _ = self.build_target_only(appdir, make_options, "showtoolver", False, log)
  170. buildout = dict()
  171. if ret != COMMAND_RUNOK:
  172. os.remove(log)
  173. return buildout
  174. buildout = dict()
  175. toolname = ""
  176. with open(log, "r") as inf:
  177. for line in inf.readlines():
  178. line = line.strip()
  179. if line.startswith("Show"):
  180. toolname = line.split()[1].strip()
  181. buildout[toolname] = ""
  182. elif line.startswith("make:") == False:
  183. if toolname != "":
  184. buildout[toolname] += line + "\n"
  185. os.remove(log)
  186. return buildout
  187. def build_target(self, appdir, make_options="", target="clean", show_output=True, logfile=None, parallel=""):
  188. if self.is_app(appdir) == False:
  189. return False, None
  190. build_status = dict()
  191. ret, ticks = self.build_target_only(appdir, make_options, target, show_output, logfile, parallel)
  192. cmdsts = True
  193. if ret == COMMAND_INTERRUPTED:
  194. print("%s: Exit program due to CTRL - C pressed" % (sys._getframe().f_code.co_name))
  195. sys.exit(1)
  196. elif ret == COMMAND_RUNOK:
  197. cmdsts = True
  198. else:
  199. cmdsts = False
  200. build_status["app"] = { "path": appdir, \
  201. "make_options": make_options, \
  202. "target": target }
  203. build_status["status"] = {"build": cmdsts}
  204. build_status["status_code"] = {"build": ret}
  205. build_status["logs"] = {"build": logfile}
  206. build_status["time"] = {"build": round(ticks, 2)}
  207. build_status["info"] = self.get_build_info(appdir, make_options)
  208. build_status["toolver"] = self.get_build_toolver(appdir, make_options)
  209. build_status["flags"] = self.get_build_flags(appdir, make_options)
  210. apptarget = None
  211. if build_status["flags"]:
  212. apptarget = build_status["flags"].get("TARGET", None)
  213. build_status["objects"] = nsdk_builder.get_objects(appdir, apptarget)
  214. build_status["size"] = get_elfsize(build_status["objects"].get("elf", ""))
  215. return cmdsts, build_status
  216. def clean_app(self, appdir, make_options="", show_output=True, logfile=None):
  217. return self.build_target(appdir, make_options, "clean", show_output, logfile)
  218. def compile_app(self, appdir, make_options="", show_output=True, logfile=None, parallel=""):
  219. return self.build_target(appdir, make_options, "all", show_output, logfile, parallel)
  220. def upload_app(self, appdir, make_options="", show_output=True, logfile=None):
  221. if logfile is None:
  222. uploadlog = tempfile.mktemp()
  223. else:
  224. uploadlog = logfile
  225. cmdsts, build_status = self.build_target(appdir, make_options, "upload", show_output, uploadlog)
  226. uploader = dict()
  227. upload_sts = False
  228. with open(uploadlog, 'r') as uf:
  229. for line in uf.readlines():
  230. if "-ex" in line or "\\" in line:
  231. # strip extra newline and \
  232. uploader["cmd"] = uploader.get("cmd", "") + line.strip().strip("\\")
  233. if "On-Chip Debugger" in line:
  234. uploader["version"] = line.strip()
  235. if "A problem internal to GDB has been detected" in line:
  236. uploader["gdbstatus"] = "hang"
  237. if "Quit this debugging session?" in line:
  238. uploader["gdbstatus"] = "hang"
  239. if "Start address" in line:
  240. uploader["gdbstatus"] = "ok"
  241. upload_sts = True
  242. break
  243. # append openocd log to upload log
  244. openocd_log = os.path.join(appdir, "openocd.log")
  245. if os.path.isfile(openocd_log):
  246. with open(uploadlog, 'a') as uf:
  247. uf.write("\n=====OpenOCD log content dumped as below:=====\n")
  248. with open(openocd_log, "r") as of:
  249. for line in of.readlines():
  250. if "Error: Target not examined yet" in line:
  251. uploader["cpustatus"] = "hang"
  252. if "Examined RISC-V core" in line:
  253. uploader["cpustatus"] = "ok"
  254. uf.write(line)
  255. if upload_sts == False: # actually not upload successfully
  256. cmdsts = False
  257. if "app" in build_status:
  258. build_status["app"]["uploader"] = uploader
  259. if logfile is None:
  260. os.remove(uploadlog)
  261. print("Upload application %s status: %s" % (appdir, cmdsts))
  262. return cmdsts, build_status
  263. class MonitorThread(Thread):
  264. def __init__(self, port:str, baudrate:str, timeout:int, checks:dict, checktime=time.time(), sdk_check=False, logfile=None, show_output=False):
  265. super().__init__()
  266. self.port = port
  267. self.baudrate = baudrate
  268. self.timeout = timeout
  269. self.checks = checks
  270. self.checktime = checktime
  271. self.tty_iserr = False
  272. self.sdk_check = sdk_check
  273. self.logfile = logfile
  274. self.show_output = show_output
  275. self._exit_req = False
  276. self._check_sdk = False
  277. self._check_sdk_timeout = 10
  278. pass
  279. def get_result(self):
  280. try:
  281. return self.result
  282. except Exception:
  283. return None
  284. def get_tty_iserror(self):
  285. return self.tty_iserr
  286. def exit_request(self):
  287. self._exit_req = True
  288. pass
  289. def set_check_sdk_timeout(self, timeout=10):
  290. self._check_sdk_timestart = time.time()
  291. self._check_sdk_timeout = timeout
  292. self._check_sdk = True # start to check timeout monitor
  293. pass
  294. def run(self):
  295. start_time = time.time()
  296. serial_log = ""
  297. check_status = False
  298. pass_checks = self.checks.get("PASS", [])
  299. fail_checks = self.checks.get("FAIL", [])
  300. def test_in_check(string, checks):
  301. if type(checks) == list:
  302. for check in checks:
  303. if check in string:
  304. return True
  305. return False
  306. NSDK_CHECK_TAG = get_sdk_checktag()
  307. if get_sdk_verb_buildmsg():
  308. print("Read serial log from %s, baudrate %s" %(self.port, self.baudrate))
  309. print("Checker used: ", self.checks)
  310. print("SDK Checker Tag \"%s\", checker enable %s" % (NSDK_CHECK_TAG, self.sdk_check))
  311. check_finished = False
  312. try:
  313. ser = None
  314. ser = serial.Serial(self.port, self.baudrate, timeout=3)
  315. while (time.time() - start_time) < self.timeout:
  316. if self._exit_req:
  317. break
  318. # Remove '\r' in serial read line
  319. sline = ser.readline()
  320. line = str(try_decode_bytes(sline)).replace('\r', '')
  321. if self.sdk_check == True:
  322. if self.show_output:
  323. print("XXX Check " + line, end='')
  324. if self._check_sdk:
  325. chk_time_cost = time.time() - self._check_sdk_timestart
  326. if chk_time_cost > self._check_sdk_timeout:
  327. print("No SDK banner found in %s s, quit now!" % (self._check_sdk_timeout))
  328. break
  329. if NSDK_CHECK_TAG in line:
  330. timestr = line.split(NSDK_CHECK_TAG)[-1].strip()
  331. if "Download" in timestr:
  332. print("Warning: Download and SDK tag in same line which should not happen!")
  333. #timestr = timestr.split("Download")[0].strip()
  334. cur_time = time.mktime(time.strptime(timestr, "%b %d %Y, %H:%M:%S"))
  335. if int(cur_time) >= int(self.checktime):
  336. self.sdk_check = False
  337. line = NSDK_CHECK_TAG + " " + timestr + "\n"
  338. serial_log = serial_log + str(line)
  339. else:
  340. serial_log = serial_log + str(line)
  341. if self.show_output:
  342. print(line, end='')
  343. if check_finished == False:
  344. if test_in_check(line, fail_checks):
  345. check_status = False
  346. check_finished = True
  347. if test_in_check(line, pass_checks):
  348. check_status = True
  349. check_finished = True
  350. if check_finished:
  351. # record another 2 seconds by reset start_time and timeout to 2
  352. start_time = time.time()
  353. self.timeout = 2
  354. except serial.serialutil.SerialException:
  355. # https://stackoverflow.com/questions/21050671/how-to-check-if-device-is-connected-pyserial
  356. print("serial port %s might not exist or in use" % self.port)
  357. # set tty is error
  358. self.tty_iserr = True
  359. except Exception as exc:
  360. print("Some error happens during serial operations, %s" % (str(exc)))
  361. finally:
  362. if ser:
  363. ser.close()
  364. if self.logfile:
  365. with open(self.logfile, 'w') as lf:
  366. lf.write(serial_log)
  367. self.result = check_status
  368. return check_status
  369. class nsdk_runner(nsdk_builder):
  370. def __init__(self):
  371. super().__init__()
  372. self.hangup_action = None
  373. self.ttyerrcnt = 0
  374. self.fpgaprogramcnt = 0
  375. self.gdberrcnt = 0
  376. self.uploaderrcnt = 0
  377. pass
  378. @staticmethod
  379. def find_apps(rootdir):
  380. subdirectories = [x[0] for x in os.walk(rootdir)]
  381. appdirs = []
  382. for subdir in subdirectories:
  383. if nsdk_runner.is_app(subdir):
  384. appdirs.append(os.path.normpath(subdir))
  385. return appdirs
  386. def reset_counters(self):
  387. self.ttyerrcnt = 0
  388. self.uploaderrcnt = 0
  389. self.fpgaprogramcnt = 0
  390. self.gdberrcnt = 0
  391. pass
  392. def need_exit_now(self):
  393. if self.ttyerrcnt > get_sdk_ttyerr_maxcnt():
  394. return True
  395. if self.fpgaprogramcnt > get_sdk_fpgaprog_maxcnt():
  396. return True
  397. if self.gdberrcnt > get_sdk_gdberr_maxcnt():
  398. return True
  399. if self.uploaderrcnt > get_sdk_uploaderr_maxcnt():
  400. return True
  401. return False
  402. def show_counters(self):
  403. print("TTY Error counter %d, limit count %d" % (self.ttyerrcnt, get_sdk_ttyerr_maxcnt()))
  404. print("GDB Internal Error counter %d, limit count %d" % (self.gdberrcnt, get_sdk_gdberr_maxcnt()))
  405. print("Upload Error counter %d, limit count %d" % (self.uploaderrcnt, get_sdk_uploaderr_maxcnt()))
  406. print("FPGA Program Error counter %d, limit count %d" % (self.fpgaprogramcnt, get_sdk_fpgaprog_maxcnt()))
  407. pass
  408. def set_cpu_hangup_action(self, hangaction):
  409. self.hangup_action = hangaction
  410. pass
  411. def build_target_in_directory(self, rootdir, make_options="", target="", \
  412. show_output=True, logdir=None, stoponfail=False):
  413. appdirs = self.find_apps(rootdir)
  414. if len(appdirs) == 0:
  415. return False, None
  416. cmdsts = True
  417. build_status = dict()
  418. createlog = False
  419. if isinstance(logdir, str):
  420. createlog = True
  421. if os.path.isdir(logdir) == False:
  422. os.makedirs(logdir)
  423. for appdir in appdirs:
  424. appdir = appdir.replace("\\", "/") # Change windows \\ path to /
  425. applogfile = None
  426. if createlog:
  427. applogfile = get_logfile(appdir, rootdir, logdir, "build.log")
  428. appcmdsts, appsts = self.build_target(appdir, make_options, \
  429. target, show_output, logfile=applogfile)
  430. build_status[appdir] = appsts
  431. if appcmdsts == False:
  432. cmdsts = appcmdsts
  433. if stoponfail == True:
  434. print("Stop build directory due to fail on application %s" %(appdir))
  435. return cmdsts, build_status
  436. return cmdsts, build_status
  437. def analyze_runlog(self, logfile, parsescript=None):
  438. result = {"type": "unknown", "value": {}}
  439. if os.path.isfile(logfile):
  440. result_lines = open(logfile).readlines()
  441. program_found, subtype, result_parsed = parse_benchmark_runlog(result_lines, lgf=logfile)
  442. if program_found == PROGRAM_UNKNOWN:
  443. program_found, subtype, result_parsed = parse_benchmark_use_pyscript(result_lines, logfile, parsescript)
  444. if program_found != PROGRAM_UNKNOWN:
  445. result = {"type": program_found, "subtype": subtype, "value": result_parsed}
  446. return result
  447. def run_app_onhw(self, appdir, runcfg:dict(), show_output=True, logfile=None, uploadlog=None):
  448. app_runcfg = runcfg.get("run_config", dict())
  449. app_runchecks = runcfg.get("checks", dict())
  450. make_options = runcfg["misc"]["make_options"]
  451. checktime = runcfg["misc"]["build_time"]
  452. hwconfig = app_runcfg.get("hardware", None)
  453. serport = None
  454. timeout = 60
  455. baudrate = 115200
  456. fpgabit = None
  457. fpgaserial = None
  458. if hwconfig is not None:
  459. most_possible_serport = find_most_possible_serport()
  460. serport = hwconfig.get("serport", most_possible_serport)
  461. baudrate = hwconfig.get("baudrate", 115200)
  462. timeout = hwconfig.get("timeout", 60)
  463. fpgabit = hwconfig.get("fpgabit", None)
  464. fpgaserial = hwconfig.get("fpgaserial", None)
  465. ser_thread = None
  466. uploader = None
  467. sdk_check = get_sdk_check()
  468. banner_tmout = get_sdk_banner_tmout()
  469. retry_cnt = 0
  470. max_retrycnt = 1
  471. while True:
  472. try:
  473. if retry_cnt > max_retrycnt: # do retry
  474. break
  475. retry_cnt += 1
  476. print("Hardware configuration: serial port %s, baudrate %s, timeout %ds, retry counter %d" % (serport, baudrate, timeout, retry_cnt))
  477. if serport: # only monitor serial port when port found
  478. ser_thread = MonitorThread(serport, baudrate, timeout, app_runchecks, checktime, \
  479. sdk_check, logfile, show_output)
  480. ser_thread.start()
  481. else:
  482. print("Warning: No available serial port found, please check!")
  483. self.ttyerrcnt += 1
  484. cmdsts, upload_sts = self.upload_app(appdir, make_options, show_output, uploadlog)
  485. uploader = upload_sts.get("app", dict()).get("uploader", None)
  486. uploader["retried"] = retry_cnt
  487. status = True
  488. if ser_thread:
  489. if cmdsts == False:
  490. ser_thread.exit_request()
  491. else:
  492. ser_thread.set_check_sdk_timeout(banner_tmout)
  493. while ser_thread.is_alive():
  494. ser_thread.join(1)
  495. status = ser_thread.get_result()
  496. if ser_thread.get_tty_iserror(): # tty is in use or not exist
  497. print("tty serial port error count %d" % (self.ttyerrcnt))
  498. self.ttyerrcnt += 1
  499. del ser_thread
  500. if uploader.get("cpustatus", "") == "hang": # cpu hangs then call cpu hangup action and retry this application
  501. self.uploaderrcnt += 1
  502. if self.hangup_action is not None:
  503. print("Execute hangup action for hangup case!")
  504. if self.hangup_action() == True:
  505. print("hangup action success!")
  506. continue
  507. else:
  508. print("hangup action failed!")
  509. elif fpgabit and fpgaserial:
  510. print("Reprogram fpga bit %s on fpga board serial number %s, total fpga reprogam count %d" % (fpgabit, fpgaserial, self.fpgaprogramcnt))
  511. self.fpgaprogramcnt += 1
  512. if program_fpga(fpgabit, fpgaserial) == True:
  513. print("Reprogram fpga sucessfully!")
  514. continue
  515. else:
  516. print("Reprogram fpga failed!")
  517. else:
  518. print("No cpu hangup action found, just continue with other cases")
  519. if uploader.get("gdbstatus", "") == "hang": # gdb hangs with internal error retry upload this applicationa
  520. max_retrycnt = 2 # when gdb internal error happened, do retry twice
  521. print("GDB internal error happened, re-upload application, total re-upload count %d" % (self.gdberrcnt))
  522. continue
  523. # exit with upload status
  524. break
  525. except (KeyboardInterrupt, SystemExit):
  526. print("%s: Exit program due to CTRL - C pressed or SystemExit" % (sys._getframe().f_code.co_name))
  527. if ser_thread:
  528. ser_thread.exit_request()
  529. sys.exit(1)
  530. final_status = cmdsts and status
  531. return final_status, uploader
  532. def run_app_onqemu(self, appdir, runcfg:dict(), show_output=True, logfile=None):
  533. app_runcfg = runcfg.get("run_config", dict())
  534. app_runchecks = runcfg.get("checks", dict())
  535. build_info = runcfg["misc"]["build_info"]
  536. build_config = runcfg["misc"]["build_config"]
  537. build_objects = runcfg["misc"]["build_objects"]
  538. checktime = runcfg["misc"]["build_time"]
  539. hwconfig = app_runcfg.get("qemu", dict())
  540. timeout = 60
  541. qemu_exe = None
  542. qemu_extraopt = ""
  543. if hwconfig is not None:
  544. qemu32_exe = hwconfig.get("qemu32", "qemu-system-riscv32")
  545. qemu64_exe = hwconfig.get("qemu64", "qemu-system-riscv64")
  546. qemu_machine = hwconfig.get("qemu_machine", None)
  547. qemu_cpu = hwconfig.get("qemu_cpu", None)
  548. qemu_exe = qemu32_exe
  549. build_soc = build_info["SOC"]
  550. build_board = build_info["BOARD"]
  551. build_core = build_info["CORE"]
  552. build_download = build_info["DOWNLOAD"]
  553. build_smp = build_info.get("SMP", "")
  554. build_arch_ext = build_config.get("ARCH_EXT", "")
  555. if build_arch_ext == "":
  556. build_arch_ext = build_info.get("ARCH_EXT", "")
  557. if build_smp != "":
  558. qemu_extraopt = "%s -smp %s" % (qemu_extraopt, build_smp)
  559. if qemu_machine is None:
  560. if is_nuclei_demosoc(build_soc):
  561. machine = "nuclei_n"
  562. else:
  563. if build_board == "gd32vf103v_rvstar":
  564. machine = "gd32vf103_rvstar"
  565. elif build_board == "gd32vf103v_eval":
  566. machine = "gd32vf103_eval"
  567. else:
  568. machine = "nuclei_n"
  569. # machine combined with download
  570. machine = machine + ",download=%s" %(build_download.lower())
  571. else:
  572. machine = qemu_machine
  573. if qemu_cpu is None:
  574. qemu_sel_cpu = "nuclei-%s" % (build_core.lower())
  575. if build_arch_ext != "":
  576. qemu_sel_cpu = qemu_sel_cpu + ",ext=%s" %(build_arch_ext)
  577. else:
  578. qemu_sel_cpu = qemu_cpu
  579. if "rv64" in build_info["RISCV_ARCH"]:
  580. qemu_exe = qemu64_exe
  581. timeout = hwconfig.get("timeout", 60)
  582. runner = None
  583. cmdsts = False
  584. sdk_check = get_sdk_check()
  585. if qemu_exe:
  586. if os.path.isfile(build_objects["elf"]):
  587. vercmd = "%s --version" % (qemu_exe)
  588. verchk = "QEMU emulator version"
  589. ret, verstr = check_tool_version(vercmd, verchk)
  590. if ret:
  591. command = "%s %s -M %s -cpu %s -nodefaults -nographic -icount shift=0 -serial stdio -kernel %s" \
  592. % (qemu_exe, qemu_extraopt, machine, qemu_sel_cpu, build_objects["elf"])
  593. print("Run command: %s" %(command))
  594. runner = {"cmd": command, "version": verstr}
  595. cmdsts, _ = run_cmd_and_check(command, timeout, app_runchecks, checktime, \
  596. sdk_check, logfile, show_output)
  597. else:
  598. print("%s doesn't exist in PATH, please check!" % qemu_exe)
  599. else:
  600. print("ELF file %s doesn't exist, can't run on qemu" % (build_objects["elf"]))
  601. final_status = cmdsts
  602. return final_status, runner
  603. def run_app_onxlspike(self, appdir, runcfg:dict(), show_output=True, logfile=None):
  604. app_runcfg = runcfg.get("run_config", dict())
  605. app_runchecks = runcfg.get("checks", dict())
  606. build_info = runcfg["misc"]["build_info"]
  607. build_config = runcfg["misc"]["build_config"]
  608. build_objects = runcfg["misc"]["build_objects"]
  609. checktime = runcfg["misc"]["build_time"]
  610. hwconfig = app_runcfg.get("xlspike", dict())
  611. timeout = 60
  612. xlspike_exe = None
  613. xlspike_extraopt = ""
  614. if hwconfig is not None:
  615. xlspike_exe = hwconfig.get("xlspike", "xl_spike")
  616. build_soc = build_info["SOC"]
  617. build_board = build_info["BOARD"]
  618. riscv_arch = build_info["RISCV_ARCH"]
  619. # replace e with i for xlspike
  620. riscv_arch = riscv_arch.replace("e", "i")
  621. #build_arch_ext = build_info.get("ARCH_EXT", "")
  622. build_smp = build_info.get("SMP", "")
  623. if build_smp != "":
  624. xlspike_extraopt = "%s -p%s" % (xlspike_extraopt, build_smp)
  625. if not is_nuclei_demosoc(build_soc):
  626. xlspike_exe = None
  627. print("SOC=%s BOARD=%s is not supported by xlspike" % (build_soc, build_board))
  628. timeout = hwconfig.get("timeout", 60)
  629. runner = None
  630. cmdsts = False
  631. sdk_check = get_sdk_check()
  632. if xlspike_exe:
  633. if os.path.isfile(build_objects["elf"]):
  634. vercmd = "%s --help" % (xlspike_exe)
  635. verchk = "RISC-V ISA Simulator"
  636. ret, verstr = check_tool_version(vercmd, verchk)
  637. if ret:
  638. command = "%s %s --isa %s %s" % (xlspike_exe, xlspike_extraopt, riscv_arch, build_objects["elf"])
  639. print("Run command: %s" %(command))
  640. runner = {"cmd": command, "version": verstr}
  641. cmdsts, _ = run_cmd_and_check(command, timeout, app_runchecks, checktime, \
  642. sdk_check, logfile, show_output)
  643. else:
  644. print("%s doesn't exist in PATH, please check!" % xlspike_exe)
  645. else:
  646. print("ELF file %s doesn't exist, can't run on xlspike" % (build_objects["elf"]))
  647. else:
  648. print("Can't run on xlspike due to run config not exist or config not supported")
  649. final_status = cmdsts
  650. return final_status, runner
  651. def run_app_onncycm(self, appdir, runcfg:dict(), show_output=True, logfile=None):
  652. app_runcfg = runcfg.get("run_config", dict())
  653. app_runchecks = runcfg.get("checks", dict())
  654. build_info = runcfg["misc"]["build_info"]
  655. build_config = runcfg["misc"]["build_config"]
  656. build_objects = runcfg["misc"]["build_objects"]
  657. checktime = runcfg["misc"]["build_time"]
  658. hwconfig = app_runcfg.get("ncycm", dict())
  659. timeout = 60
  660. ncycm_exe = None
  661. if hwconfig is not None:
  662. ncycm_exe = hwconfig.get("ncycm", "ncycm")
  663. timeout = hwconfig.get("timeout", 600)
  664. runner = None
  665. cmdsts = False
  666. sdk_check = get_sdk_check()
  667. if ncycm_exe:
  668. if os.path.isfile(build_objects["elf"]):
  669. vercmd = "%s -v" % (ncycm_exe)
  670. verchk = "version:"
  671. ret, verstr = check_tool_version(vercmd, verchk)
  672. if ret == False:
  673. verstr = "v1"
  674. ret = check_tool_exist(ncycm_exe) or os.path.isfile(ncycm_exe)
  675. if ret:
  676. if (verstr == "v1"):
  677. ncycm_verilog = fix_demosoc_verilog_ncycm(build_objects["verilog"])
  678. if ncycm_verilog == "":
  679. command = ""
  680. else:
  681. command = "%s +TESTCASE=%s" % (ncycm_exe, ncycm_verilog)
  682. else:
  683. command = "%s %s" % (ncycm_exe, build_objects["elf"])
  684. if command != "":
  685. print("Run command: %s" %(command))
  686. runner = {"cmd": command, "version": verstr}
  687. cmdsts, _ = run_cmd_and_check(command, timeout, app_runchecks, checktime, \
  688. sdk_check, logfile, show_output, 480)
  689. else:
  690. print("Unable to run cycle model with %s" % (build_objects["elf"]))
  691. cmdsts = False
  692. else:
  693. print("%s doesn't exist in PATH, please check!" % ncycm_exe)
  694. else:
  695. print("ELF file %s doesn't exist, can't run on xlspike" % (build_objects["elf"]))
  696. else:
  697. print("Can't run on xlspike due to run config not exist or config not supported")
  698. final_status = cmdsts
  699. return final_status, runner
  700. def build_app_with_config(self, appdir, appconfig:dict, show_output=True, logfile=None):
  701. build_config = appconfig.get("build_config", None)
  702. target = appconfig.get("build_target", "all")
  703. parallel = appconfig.get("parallel", "")
  704. # Copy program objects if copy_objects is true
  705. copy_objects_required = appconfig.get("copy_objects", get_sdk_copyobjects_flag())
  706. make_options = ""
  707. if isinstance(build_config, dict):
  708. for key, value in build_config.items():
  709. value = str(value).strip()
  710. if " " in key:
  711. continue
  712. if " " in value:
  713. make_options += " %s=\"%s\""%(key, value)
  714. else:
  715. make_options += " %s=%s"%(key, value)
  716. appcmdsts, appsts = self.build_target(appdir, make_options, target, show_output, logfile, parallel)
  717. objs_copydir = os.path.dirname(logfile) # where objects are copied to
  718. # copy objects if copy_objects_required
  719. if copy_objects_required:
  720. nsdk_builder.copy_objects(appsts, objs_copydir)
  721. buildtime = appsts["time"]["build"]
  722. print("Build application %s with target %s, make options %s, time cost %s seconds, passed: %s" %(appdir, target, make_options, buildtime, appcmdsts))
  723. sys.stdout.flush()
  724. appsts["config"] = appconfig
  725. return appcmdsts, appsts
  726. def run_app_with_config(self, appdir, appconfig:dict, show_output=True, buildlog=None, runlog=None):
  727. appconfig["build_target"] = "clean dasm"
  728. # build application
  729. build_cktime = time.time()
  730. appcmdsts, appsts = self.build_app_with_config(appdir, appconfig, show_output, buildlog)
  731. # run application
  732. if appcmdsts == False:
  733. print("Failed to build application %s, so we can't run it!" % (appdir))
  734. return appcmdsts, appsts
  735. # get run config
  736. app_runcfg = appconfig.get("run_config", dict())
  737. app_runtarget = app_runcfg.get("target", "hardware")
  738. app_parsescript = app_runcfg.get("parsescript", None)
  739. if app_parsescript is not None:
  740. if os.path.isfile(app_parsescript) == False:
  741. app_parsescript = os.path.join(appdir, app_parsescript)
  742. # get run checks
  743. DEFAULT_CHECKS = { "PASS": [ ], "FAIL": [ "MCAUSE:" ] }
  744. app_runchecks = appconfig.get("checks", DEFAULT_CHECKS)
  745. misc_config = {"make_options": appsts["app"]["make_options"], "build_config": appconfig["build_config"],\
  746. "build_info": appsts["info"], "build_objects": appsts["objects"], "build_time": build_cktime}
  747. runcfg = {"run_config": app_runcfg, "checks": app_runchecks, "misc": misc_config}
  748. print("Run application on %s" % app_runtarget)
  749. runstarttime = time.time()
  750. runstatus = False
  751. appsts["status_code"]["run"] = RUNSTATUS_NOTSTART
  752. if app_runtarget == "hardware":
  753. uploadlog = None
  754. if runlog:
  755. uploadlog = os.path.join(os.path.dirname(runlog), "upload.log")
  756. runstatus, uploader = self.run_app_onhw(appdir, runcfg, show_output, runlog, uploadlog)
  757. # If run successfully, then do log analyze
  758. if runlog and runstatus:
  759. appsts["result"] = self.analyze_runlog(runlog, app_parsescript)
  760. appsts["logs"]["run"] = runlog
  761. appsts["logs"]["upload"] = uploadlog
  762. appsts["status_code"]["run"] = RUNSTATUS_OK if runstatus else RUNSTATUS_FAIL
  763. if uploader:
  764. appsts["app"]["uploader"] = uploader
  765. elif app_runtarget == "qemu":
  766. runstatus, runner = self.run_app_onqemu(appdir, runcfg, show_output, runlog)
  767. # If run successfully, then do log analyze
  768. if runlog and runstatus:
  769. appsts["result"] = self.analyze_runlog(runlog, app_parsescript)
  770. appsts["logs"]["run"] = runlog
  771. appsts["status_code"]["run"] = RUNSTATUS_OK if runstatus else RUNSTATUS_FAIL
  772. if runner:
  773. appsts["app"]["qemu"] = runner
  774. elif app_runtarget == "xlspike":
  775. runstatus, runner = self.run_app_onxlspike(appdir, runcfg, show_output, runlog)
  776. # If run successfully, then do log analyze
  777. if runlog and runstatus:
  778. appsts["result"] = self.analyze_runlog(runlog, app_parsescript)
  779. appsts["logs"]["run"] = runlog
  780. appsts["status_code"]["run"] = RUNSTATUS_OK if runstatus else RUNSTATUS_FAIL
  781. if runner:
  782. appsts["app"]["xlspike"] = runner
  783. elif app_runtarget == "ncycm":
  784. runstatus, runner = self.run_app_onncycm(appdir, runcfg, show_output, runlog)
  785. # If run successfully, then do log analyze
  786. if runlog and runstatus:
  787. appsts["result"] = self.analyze_runlog(runlog, app_parsescript)
  788. appsts["logs"]["run"] = runlog
  789. appsts["status_code"]["run"] = RUNSTATUS_OK if runstatus else RUNSTATUS_FAIL
  790. if runner:
  791. appsts["app"]["ncycm"] = runner
  792. else:
  793. print("Unsupported run target %s" %(app_runtarget))
  794. runtime = round(time.time() - runstarttime, 2)
  795. print("Run application %s on %s, time cost %s seconds, passed: %s" %(appdir, app_runtarget, runtime, runstatus))
  796. sys.stdout.flush()
  797. appsts["status"]["run"] = runstatus
  798. appsts["time"]["run"] = runtime
  799. return runstatus, appsts
  800. def build_apps_with_config(self, config:dict, show_output=True, logdir=None, stoponfail=False):
  801. # Build all the applications, each application only has one configuration
  802. # "app" : { the_only_config }
  803. cmdsts = True
  804. build_status = dict()
  805. apps_config = copy.deepcopy(config)
  806. for appdir in apps_config:
  807. appconfig = apps_config[appdir]
  808. applogs = appconfig.get("logs", dict())
  809. applogfile = applogs.get("build", None)
  810. appcmdsts, appsts = self.build_app_with_config(appdir, appconfig, show_output, applogfile)
  811. build_status[appdir] = appsts
  812. if appcmdsts == False:
  813. cmdsts = appcmdsts
  814. if stoponfail == True:
  815. print("Stop build apps with config due to fail on application %s" %(appdir))
  816. return cmdsts, build_status
  817. return cmdsts, build_status
  818. def build_apps_with_configs(self, config:dict, show_output=True, logdir=None, stoponfail=False):
  819. # Build all the applications, each application has more than one configuration
  820. # "app" : {"configs": {"case1": case1_config}}
  821. cmdsts = True
  822. build_status = dict()
  823. apps_config = copy.deepcopy(config)
  824. for appdir in apps_config:
  825. appconfigs = apps_config[appdir]
  826. if "configs" not in appconfigs:
  827. continue
  828. build_status[appdir] = dict()
  829. app_allconfigs = appconfigs["configs"]
  830. for cfgname in app_allconfigs:
  831. appconfig = app_allconfigs[cfgname] # get configuration for each case for single app
  832. applogs = appconfig.get("logs", dict())
  833. applogfile = applogs.get("build", None)
  834. appcmdsts, appsts = self.build_app_with_config(appdir, appconfig, show_output, applogfile)
  835. build_status[appdir][cfgname] = appsts
  836. if appcmdsts == False:
  837. cmdsts = appcmdsts
  838. if stoponfail == True:
  839. print("Stop build apps with config due to fail on application %s" %(appdir))
  840. return cmdsts, build_status
  841. return cmdsts, build_status
  842. def run_apps_with_config(self, config:dict, show_output=True, stoponfail=False):
  843. # Run all the applications, each application only has one configuration
  844. # "app" : { the_only_config }
  845. cmdsts = True
  846. # reset error counters
  847. self.reset_counters()
  848. build_status = dict()
  849. apps_config = copy.deepcopy(config)
  850. for appdir in apps_config:
  851. appconfig = apps_config[appdir]
  852. applogs = appconfig.get("logs", dict())
  853. app_buildlogfile = applogs.get("build", None)
  854. app_runlogfile = applogs.get("run", None)
  855. appcmdsts, appsts = self.run_app_with_config(appdir, appconfig, show_output, app_buildlogfile, app_runlogfile)
  856. build_status[appdir] = appsts
  857. if appcmdsts == False:
  858. cmdsts = appcmdsts
  859. if stoponfail == True:
  860. print("ERROR: Stop run apps with config due to fail on application %s" %(appdir))
  861. return cmdsts, build_status
  862. # error exit check
  863. if self.need_exit_now():
  864. print("ERROR: Need to exit now due to error counter exceed limit!")
  865. self.show_counters()
  866. cmdsts = False
  867. return cmdsts, build_status
  868. return cmdsts, build_status
  869. def run_apps_with_configs(self, config:dict, show_output=True, stoponfail=False):
  870. # Run all the applications, each application has more than one configuration
  871. # "app" : {"configs": {"case1": case1_config}}
  872. cmdsts = True
  873. # reset error counters
  874. self.reset_counters()
  875. build_status = dict()
  876. apps_config = copy.deepcopy(config)
  877. for appdir in apps_config:
  878. appconfigs = apps_config[appdir]
  879. if "configs" not in appconfigs:
  880. continue
  881. build_status[appdir] = dict()
  882. app_allconfigs = appconfigs["configs"]
  883. for cfgname in app_allconfigs:
  884. appconfig = app_allconfigs[cfgname] # get configuration for each case for single app
  885. applogs = appconfig.get("logs", dict())
  886. app_buildlogfile = applogs.get("build", None)
  887. app_runlogfile = applogs.get("run", None)
  888. appcmdsts, appsts = self.run_app_with_config(appdir, appconfig, show_output, app_buildlogfile, app_runlogfile)
  889. build_status[appdir][cfgname] = appsts
  890. if appcmdsts == False:
  891. cmdsts = appcmdsts
  892. if stoponfail == True:
  893. print("ERROR: Stop run apps with config due to fail on application %s" %(appdir))
  894. return cmdsts, build_status
  895. # error exit check
  896. if self.need_exit_now():
  897. print("ERROR: Need to exit now due to error counter exceed limit!")
  898. self.show_counters()
  899. cmdsts = False
  900. return cmdsts, build_status
  901. return cmdsts, build_status