nsdk_builder.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  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. if cmdsts:
  228. upload_sts = False
  229. with open(uploadlog, 'r') as uf:
  230. for line in uf.readlines():
  231. if "-ex" in line or "\\" in line:
  232. # strip extra newline and \
  233. uploader["cmd"] = uploader.get("cmd", "") + line.strip().strip("\\")
  234. if "On-Chip Debugger" in line:
  235. uploader["version"] = line.strip()
  236. if "A problem internal to GDB has been detected" in line:
  237. uploader["gdbstatus"] = "hang"
  238. if "Quit this debugging session?" in line:
  239. uploader["gdbstatus"] = "hang"
  240. if "Start address" in line:
  241. uploader["gdbstatus"] = "ok"
  242. upload_sts = True
  243. break
  244. # append openocd log to upload log
  245. openocd_log = os.path.join(appdir, "openocd.log")
  246. if os.path.isfile(openocd_log):
  247. with open(uploadlog, 'a') as uf:
  248. uf.write("\n=====OpenOCD log content dumped as below:=====\n")
  249. with open(openocd_log, "r") as of:
  250. for line in of.readlines():
  251. if "Error: Target not examined yet" in line:
  252. uploader["cpustatus"] = "hang"
  253. if "Examined RISC-V core" in line:
  254. uploader["cpustatus"] = "ok"
  255. uf.write(line)
  256. if upload_sts == False: # actually not upload successfully
  257. cmdsts = False
  258. if "app" in build_status:
  259. build_status["app"]["uploader"] = uploader
  260. if logfile is None:
  261. os.remove(uploadlog)
  262. print("Upload application %s status: %s" % (appdir, cmdsts))
  263. return cmdsts, build_status
  264. class MonitorThread(Thread):
  265. def __init__(self, port:str, baudrate:str, timeout:int, checks:dict, checktime=time.time(), sdk_check=False, logfile=None, show_output=False):
  266. super().__init__()
  267. self.port = port
  268. self.baudrate = baudrate
  269. self.timeout = timeout
  270. self.checks = checks
  271. self.checktime = checktime
  272. self.tty_iserr = False
  273. self.sdk_check = sdk_check
  274. self.logfile = logfile
  275. self.show_output = show_output
  276. self._exit_req = False
  277. self._check_sdk = False
  278. self._check_sdk_timeout = 10
  279. pass
  280. def get_result(self):
  281. try:
  282. return self.result
  283. except Exception:
  284. return None
  285. def get_tty_iserror(self):
  286. return self.tty_iserr
  287. def exit_request(self):
  288. self._exit_req = True
  289. pass
  290. def set_check_sdk_timeout(self, timeout=10):
  291. self._check_sdk_timestart = time.time()
  292. self._check_sdk_timeout = timeout
  293. self._check_sdk = True # start to check timeout monitor
  294. pass
  295. def run(self):
  296. start_time = time.time()
  297. serial_log = ""
  298. check_status = False
  299. pass_checks = self.checks.get("PASS", [])
  300. fail_checks = self.checks.get("FAIL", [])
  301. def test_in_check(string, checks):
  302. if type(checks) == list:
  303. for check in checks:
  304. if check in string:
  305. return True
  306. return False
  307. NSDK_CHECK_TAG = get_sdk_checktag()
  308. if get_sdk_verb_buildmsg:
  309. print("Read serial log from %s, baudrate %s" %(self.port, self.baudrate))
  310. print("Checker used: ", self.checks)
  311. print("SDK Checker Tag \"%s\", checker enable %s" % (NSDK_CHECK_TAG, self.sdk_check))
  312. check_finished = False
  313. try:
  314. ser = None
  315. ser = serial.Serial(self.port, self.baudrate, timeout=3)
  316. while (time.time() - start_time) < self.timeout:
  317. if self._exit_req:
  318. break
  319. # Remove '\r' in serial read line
  320. sline = ser.readline()
  321. line = str(try_decode_bytes(sline)).replace('\r', '')
  322. if self.sdk_check == True:
  323. if self.show_output:
  324. print("XXX Check " + line, end='')
  325. if self._check_sdk:
  326. chk_time_cost = time.time() - self._check_sdk_timestart
  327. if chk_time_cost > self._check_sdk_timeout:
  328. print("No SDK banner found in %s s, quit now!" % (self._check_sdk_timeout))
  329. break
  330. if NSDK_CHECK_TAG in line:
  331. timestr = line.split(NSDK_CHECK_TAG)[-1].strip()
  332. if "Download" in timestr:
  333. print("Warning: Download and SDK tag in same line which should not happen!")
  334. #timestr = timestr.split("Download")[0].strip()
  335. cur_time = time.mktime(time.strptime(timestr, "%b %d %Y, %H:%M:%S"))
  336. if int(cur_time) >= int(self.checktime):
  337. self.sdk_check = False
  338. line = NSDK_CHECK_TAG + " " + timestr + "\n"
  339. serial_log = serial_log + str(line)
  340. else:
  341. serial_log = serial_log + str(line)
  342. if self.show_output:
  343. print(line, end='')
  344. if check_finished == False:
  345. if test_in_check(line, fail_checks):
  346. check_status = False
  347. check_finished = True
  348. if test_in_check(line, pass_checks):
  349. check_status = True
  350. check_finished = True
  351. if check_finished:
  352. # record another 2 seconds by reset start_time and timeout to 2
  353. start_time = time.time()
  354. self.timeout = 2
  355. except serial.serialutil.SerialException:
  356. # https://stackoverflow.com/questions/21050671/how-to-check-if-device-is-connected-pyserial
  357. print("serial port %s might not exist or in use" % self.port)
  358. # set tty is error
  359. self.tty_iserr = True
  360. except Exception as exc:
  361. print("Some error happens during serial operations, %s" % (str(exc)))
  362. finally:
  363. if ser:
  364. ser.close()
  365. if self.logfile:
  366. with open(self.logfile, 'w') as lf:
  367. lf.write(serial_log)
  368. self.result = check_status
  369. return check_status
  370. class nsdk_runner(nsdk_builder):
  371. def __init__(self):
  372. super().__init__()
  373. self.hangup_action = None
  374. self.ttyerrcnt = 0
  375. self.fpgaprogramcnt = 0
  376. self.gdberrcnt = 0
  377. self.uploaderrcnt = 0
  378. pass
  379. @staticmethod
  380. def find_apps(rootdir):
  381. subdirectories = [x[0] for x in os.walk(rootdir)]
  382. appdirs = []
  383. for subdir in subdirectories:
  384. if nsdk_runner.is_app(subdir):
  385. appdirs.append(os.path.normpath(subdir))
  386. return appdirs
  387. def reset_counters(self):
  388. self.ttyerrcnt = 0
  389. self.uploaderrcnt = 0
  390. self.fpgaprogramcnt = 0
  391. self.gdberrcnt = 0
  392. pass
  393. def need_exit_now(self):
  394. if self.ttyerrcnt > get_sdk_ttyerr_maxcnt():
  395. return True
  396. if self.fpgaprogramcnt > get_sdk_fpgaprog_maxcnt():
  397. return True
  398. if self.gdberrcnt > get_sdk_gdberr_maxcnt():
  399. return True
  400. if self.uploaderrcnt > get_sdk_uploaderr_maxcnt():
  401. return True
  402. return False
  403. def show_counters(self):
  404. print("TTY Error counter %d, limit count %d" % (self.ttyerrcnt, get_sdk_ttyerr_maxcnt()))
  405. print("GDB Internal Error counter %d, limit count %d" % (self.gdberrcnt, get_sdk_gdberr_maxcnt()))
  406. print("Upload Error counter %d, limit count %d" % (self.uploaderrcnt, get_sdk_uploaderr_maxcnt()))
  407. print("FPGA Program Error counter %d, limit count %d" % (self.fpgaprogramcnt, get_sdk_fpgaprog_maxcnt()))
  408. pass
  409. def set_cpu_hangup_action(self, hangaction):
  410. self.hangup_action = hangaction
  411. pass
  412. def build_target_in_directory(self, rootdir, make_options="", target="", \
  413. show_output=True, logdir=None, stoponfail=False):
  414. appdirs = self.find_apps(rootdir)
  415. if len(appdirs) == 0:
  416. return False, None
  417. cmdsts = True
  418. build_status = dict()
  419. createlog = False
  420. if isinstance(logdir, str):
  421. createlog = True
  422. if os.path.isdir(logdir) == False:
  423. os.makedirs(logdir)
  424. for appdir in appdirs:
  425. appdir = appdir.replace("\\", "/") # Change windows \\ path to /
  426. applogfile = None
  427. if createlog:
  428. applogfile = get_logfile(appdir, rootdir, logdir, "build.log")
  429. appcmdsts, appsts = self.build_target(appdir, make_options, \
  430. target, show_output, logfile=applogfile)
  431. build_status[appdir] = appsts
  432. if appcmdsts == False:
  433. cmdsts = appcmdsts
  434. if stoponfail == True:
  435. print("Stop build directory due to fail on application %s" %(appdir))
  436. return cmdsts, build_status
  437. return cmdsts, build_status
  438. def analyze_runlog(self, logfile):
  439. result = {"type": "unknown", "value": {}}
  440. if os.path.isfile(logfile):
  441. result_lines = open(logfile).readlines()
  442. program_found, subtype, result_parsed = parse_benchmark_runlog(result_lines, lgf=logfile)
  443. if program_found != PROGRAM_UNKNOWN:
  444. result = {"type": program_found, "subtype": subtype, "value": result_parsed}
  445. return result
  446. def run_app_onhw(self, appdir, runcfg:dict(), show_output=True, logfile=None, uploadlog=None):
  447. app_runcfg = runcfg.get("run_config", dict())
  448. app_runchecks = runcfg.get("checks", dict())
  449. make_options = runcfg["misc"]["make_options"]
  450. checktime = runcfg["misc"]["build_time"]
  451. hwconfig = app_runcfg.get("hardware", None)
  452. serport = None
  453. timeout = 60
  454. baudrate = 115200
  455. fpgabit = None
  456. fpgaserial = None
  457. if hwconfig is not None:
  458. most_possible_serport = find_most_possible_serport()
  459. serport = hwconfig.get("serport", most_possible_serport)
  460. baudrate = hwconfig.get("baudrate", 115200)
  461. timeout = hwconfig.get("timeout", 60)
  462. fpgabit = hwconfig.get("fpgabit", None)
  463. fpgaserial = hwconfig.get("fpgaserial", None)
  464. ser_thread = None
  465. uploader = None
  466. sdk_check = get_sdk_check()
  467. banner_tmout = get_sdk_banner_tmout()
  468. retry_cnt = 0
  469. max_retrycnt = 1
  470. while True:
  471. try:
  472. if retry_cnt > max_retrycnt: # do retry
  473. break
  474. retry_cnt += 1
  475. print("Hardware configuration: serial port %s, baudrate %s, timeout %ds, retry counter %d" % (serport, baudrate, timeout, retry_cnt))
  476. if serport: # only monitor serial port when port found
  477. ser_thread = MonitorThread(serport, baudrate, timeout, app_runchecks, checktime, \
  478. sdk_check, logfile, show_output)
  479. ser_thread.start()
  480. else:
  481. print("Warning: No available serial port found, please check!")
  482. self.ttyerrcnt += 1
  483. cmdsts, upload_sts = self.upload_app(appdir, make_options, show_output, uploadlog)
  484. uploader = upload_sts.get("app", dict()).get("uploader", None)
  485. uploader["retried"] = retry_cnt
  486. status = True
  487. if ser_thread:
  488. if cmdsts == False:
  489. ser_thread.exit_request()
  490. else:
  491. ser_thread.set_check_sdk_timeout(banner_tmout)
  492. while ser_thread.is_alive():
  493. ser_thread.join(1)
  494. status = ser_thread.get_result()
  495. if ser_thread.get_tty_iserror(): # tty is in use or not exist
  496. print("tty serial port error count %d" % (self.ttyerrcnt))
  497. self.ttyerrcnt += 1
  498. del ser_thread
  499. if uploader.get("cpustatus", "") == "hang": # cpu hangs then call cpu hangup action and retry this application
  500. self.uploaderrcnt += 1
  501. if self.hangup_action is not None:
  502. print("Execute hangup action for hangup case!")
  503. if self.hangup_action() == True:
  504. print("hangup action success!")
  505. continue
  506. else:
  507. print("hangup action failed!")
  508. elif fpgabit and fpgaserial:
  509. print("Reprogram fpga bit %s on fpga board serial number %s, total fpga reprogam count %d" % (fpgabit, fpgaserial, self.fpgaprogramcnt))
  510. self.fpgaprogramcnt += 1
  511. if program_fpga(fpgabit, fpgaserial) == True:
  512. print("Reprogram fpga sucessfully!")
  513. continue
  514. else:
  515. print("Reprogram fpga failed!")
  516. else:
  517. print("No cpu hangup action found, just continue with other cases")
  518. if uploader.get("gdbstatus", "") == "hang": # gdb hangs with internal error retry upload this applicationa
  519. max_retrycnt = 2 # when gdb internal error happened, do retry twice
  520. print("GDB internal error happened, re-upload application, total re-upload count %d" % (self.gdberrcnt))
  521. continue
  522. # exit with upload status
  523. break
  524. except (KeyboardInterrupt, SystemExit):
  525. print("%s: Exit program due to CTRL - C pressed or SystemExit" % (sys._getframe().f_code.co_name))
  526. if ser_thread:
  527. ser_thread.exit_request()
  528. sys.exit(1)
  529. final_status = cmdsts and status
  530. return final_status, uploader
  531. def run_app_onqemu(self, appdir, runcfg:dict(), show_output=True, logfile=None):
  532. app_runcfg = runcfg.get("run_config", dict())
  533. app_runchecks = runcfg.get("checks", dict())
  534. build_info = runcfg["misc"]["build_info"]
  535. build_config = runcfg["misc"]["build_config"]
  536. build_objects = runcfg["misc"]["build_objects"]
  537. checktime = runcfg["misc"]["build_time"]
  538. hwconfig = app_runcfg.get("qemu", dict())
  539. timeout = 60
  540. qemu_exe = None
  541. qemu_extraopt = ""
  542. if hwconfig is not None:
  543. qemu32_exe = hwconfig.get("qemu32", "qemu-system-riscv32")
  544. qemu64_exe = hwconfig.get("qemu64", "qemu-system-riscv64")
  545. qemu_machine = hwconfig.get("qemu_machine", None)
  546. qemu_cpu = hwconfig.get("qemu_cpu", None)
  547. qemu_exe = qemu32_exe
  548. build_soc = build_info["SOC"]
  549. build_board = build_info["BOARD"]
  550. build_core = build_info["CORE"]
  551. build_download = build_info["DOWNLOAD"]
  552. build_smp = build_info.get("SMP", "")
  553. build_arch_ext = build_config.get("ARCH_EXT", "")
  554. if build_smp != "":
  555. qemu_extraopt = "%s -smp %s" % (qemu_extraopt, build_smp)
  556. if qemu_machine is None:
  557. if is_nuclei_demosoc(build_soc):
  558. machine = "nuclei_n"
  559. else:
  560. if build_board == "gd32vf103v_rvstar":
  561. machine = "gd32vf103_rvstar"
  562. elif build_board == "gd32vf103v_eval":
  563. machine = "gd32vf103_eval"
  564. else:
  565. machine = "nuclei_n"
  566. # machine combined with download
  567. machine = machine + ",download=%s" %(build_download.lower())
  568. else:
  569. machine = qemu_machine
  570. if qemu_cpu is None:
  571. qemu_sel_cpu = "nuclei-%s" % (build_core.lower())
  572. if build_arch_ext != "":
  573. qemu_sel_cpu = qemu_sel_cpu + ",ext=%s" %(build_arch_ext)
  574. else:
  575. qemu_sel_cpu = qemu_cpu
  576. if "rv64" in build_info["RISCV_ARCH"]:
  577. qemu_exe = qemu64_exe
  578. timeout = hwconfig.get("timeout", 60)
  579. runner = None
  580. cmdsts = False
  581. sdk_check = get_sdk_check()
  582. if qemu_exe:
  583. if os.path.isfile(build_objects["elf"]):
  584. vercmd = "%s --version" % (qemu_exe)
  585. verchk = "QEMU emulator version"
  586. ret, verstr = check_tool_version(vercmd, verchk)
  587. if ret:
  588. command = "%s %s -M %s -cpu %s -nodefaults -nographic -icount shift=0 -serial stdio -kernel %s" \
  589. % (qemu_exe, qemu_extraopt, machine, qemu_sel_cpu, build_objects["elf"])
  590. print("Run command: %s" %(command))
  591. runner = {"cmd": command, "version": verstr}
  592. cmdsts, _ = run_cmd_and_check(command, timeout, app_runchecks, checktime, \
  593. sdk_check, logfile, show_output)
  594. else:
  595. print("%s doesn't exist in PATH, please check!" % qemu_exe)
  596. else:
  597. print("ELF file %s doesn't exist, can't run on qemu" % (build_objects["elf"]))
  598. final_status = cmdsts
  599. return final_status, runner
  600. def run_app_onxlspike(self, appdir, runcfg:dict(), show_output=True, logfile=None):
  601. app_runcfg = runcfg.get("run_config", dict())
  602. app_runchecks = runcfg.get("checks", dict())
  603. build_info = runcfg["misc"]["build_info"]
  604. build_config = runcfg["misc"]["build_config"]
  605. build_objects = runcfg["misc"]["build_objects"]
  606. checktime = runcfg["misc"]["build_time"]
  607. hwconfig = app_runcfg.get("xlspike", dict())
  608. timeout = 60
  609. xlspike_exe = None
  610. xlspike_extraopt = ""
  611. if hwconfig is not None:
  612. xlspike_exe = hwconfig.get("xlspike", "xl_spike")
  613. build_soc = build_info["SOC"]
  614. build_board = build_info["BOARD"]
  615. riscv_arch = build_info["RISCV_ARCH"]
  616. # replace e with i for xlspike
  617. riscv_arch = riscv_arch.replace("e", "i")
  618. #build_arch_ext = build_config.get("ARCH_EXT", "")
  619. build_smp = build_info.get("SMP", "")
  620. if build_smp != "":
  621. xlspike_extraopt = "%s -p%s" % (xlspike_extraopt, build_smp)
  622. if not is_nuclei_demosoc(build_soc):
  623. xlspike_exe = None
  624. print("SOC=%s BOARD=%s is not supported by xlspike" % (build_soc, build_board))
  625. timeout = hwconfig.get("timeout", 60)
  626. runner = None
  627. cmdsts = False
  628. sdk_check = get_sdk_check()
  629. if xlspike_exe:
  630. if os.path.isfile(build_objects["elf"]):
  631. vercmd = "%s --help" % (xlspike_exe)
  632. verchk = "RISC-V ISA Simulator"
  633. ret, verstr = check_tool_version(vercmd, verchk)
  634. if ret:
  635. command = "%s %s --isa %s %s" % (xlspike_exe, xlspike_extraopt, riscv_arch, build_objects["elf"])
  636. print("Run command: %s" %(command))
  637. runner = {"cmd": command, "version": verstr}
  638. cmdsts, _ = run_cmd_and_check(command, timeout, app_runchecks, checktime, \
  639. sdk_check, logfile, show_output)
  640. else:
  641. print("%s doesn't exist in PATH, please check!" % xlspike_exe)
  642. else:
  643. print("ELF file %s doesn't exist, can't run on xlspike" % (build_objects["elf"]))
  644. else:
  645. print("Can't run on xlspike due to run config not exist or config not supported")
  646. final_status = cmdsts
  647. return final_status, runner
  648. def run_app_onncycm(self, appdir, runcfg:dict(), show_output=True, logfile=None):
  649. app_runcfg = runcfg.get("run_config", dict())
  650. app_runchecks = runcfg.get("checks", dict())
  651. build_info = runcfg["misc"]["build_info"]
  652. build_config = runcfg["misc"]["build_config"]
  653. build_objects = runcfg["misc"]["build_objects"]
  654. checktime = runcfg["misc"]["build_time"]
  655. hwconfig = app_runcfg.get("ncycm", dict())
  656. timeout = 60
  657. ncycm_exe = None
  658. if hwconfig is not None:
  659. ncycm_exe = hwconfig.get("ncycm", "ncycm")
  660. timeout = hwconfig.get("timeout", 600)
  661. runner = None
  662. cmdsts = False
  663. sdk_check = get_sdk_check()
  664. if ncycm_exe:
  665. if os.path.isfile(build_objects["elf"]):
  666. vercmd = "%s -v" % (ncycm_exe)
  667. verchk = "version:"
  668. ret, verstr = check_tool_version(vercmd, verchk)
  669. if ret == False:
  670. verstr = "v1"
  671. ret = check_tool_exist(ncycm_exe) or os.path.isfile(ncycm_exe)
  672. if ret:
  673. if (verstr == "v1"):
  674. ncycm_verilog = fix_demosoc_verilog_ncycm(build_objects["verilog"])
  675. if ncycm_verilog == "":
  676. command = ""
  677. else:
  678. command = "%s +TESTCASE=%s" % (ncycm_exe, ncycm_verilog)
  679. else:
  680. command = "%s %s" % (ncycm_exe, build_objects["elf"])
  681. if command != "":
  682. print("Run command: %s" %(command))
  683. runner = {"cmd": command, "version": verstr}
  684. cmdsts, _ = run_cmd_and_check(command, timeout, app_runchecks, checktime, \
  685. sdk_check, logfile, show_output, 480)
  686. else:
  687. print("Unable to run cycle model with %s" % (build_objects["elf"]))
  688. cmdsts = False
  689. else:
  690. print("%s doesn't exist in PATH, please check!" % ncycm_exe)
  691. else:
  692. print("ELF file %s doesn't exist, can't run on xlspike" % (build_objects["elf"]))
  693. else:
  694. print("Can't run on xlspike due to run config not exist or config not supported")
  695. final_status = cmdsts
  696. return final_status, runner
  697. def build_app_with_config(self, appdir, appconfig:dict, show_output=True, logfile=None):
  698. build_config = appconfig.get("build_config", None)
  699. target = appconfig.get("build_target", "all")
  700. parallel = appconfig.get("parallel", "")
  701. # Copy program objects if copy_objects is true
  702. copy_objects_required = appconfig.get("copy_objects", get_sdk_copyobjects_flag())
  703. make_options = ""
  704. if isinstance(build_config, dict):
  705. for key, value in build_config.items():
  706. value = str(value).strip()
  707. if " " in key:
  708. continue
  709. if " " in value:
  710. make_options += " %s=\"%s\""%(key, value)
  711. else:
  712. make_options += " %s=%s"%(key, value)
  713. appcmdsts, appsts = self.build_target(appdir, make_options, target, show_output, logfile, parallel)
  714. objs_copydir = os.path.dirname(logfile) # where objects are copied to
  715. # copy objects if copy_objects_required
  716. if copy_objects_required:
  717. nsdk_builder.copy_objects(appsts, objs_copydir)
  718. buildtime = appsts["time"]["build"]
  719. print("Build application %s with target %s, make options %s, time cost %s seconds, passed: %s" %(appdir, target, make_options, buildtime, appcmdsts))
  720. sys.stdout.flush()
  721. appsts["config"] = appconfig
  722. return appcmdsts, appsts
  723. def run_app_with_config(self, appdir, appconfig:dict, show_output=True, buildlog=None, runlog=None):
  724. appconfig["build_target"] = "clean dasm"
  725. # build application
  726. build_cktime = time.time()
  727. appcmdsts, appsts = self.build_app_with_config(appdir, appconfig, show_output, buildlog)
  728. # run application
  729. if appcmdsts == False:
  730. print("Failed to build application %s, so we can't run it!" % (appdir))
  731. return appcmdsts, appsts
  732. # get run config
  733. app_runcfg = appconfig.get("run_config", dict())
  734. app_runtarget = app_runcfg.get("target", "hardware")
  735. # get run checks
  736. DEFAULT_CHECKS = { "PASS": [ ], "FAIL": [ "MCAUSE:" ] }
  737. app_runchecks = appconfig.get("checks", DEFAULT_CHECKS)
  738. misc_config = {"make_options": appsts["app"]["make_options"], "build_config": appconfig["build_config"],\
  739. "build_info": appsts["info"], "build_objects": appsts["objects"], "build_time": build_cktime}
  740. runcfg = {"run_config": app_runcfg, "checks": app_runchecks, "misc": misc_config}
  741. print("Run application on %s" % app_runtarget)
  742. runstarttime = time.time()
  743. runstatus = False
  744. appsts["status_code"]["run"] = RUNSTATUS_NOTSTART
  745. if app_runtarget == "hardware":
  746. uploadlog = None
  747. if runlog:
  748. uploadlog = os.path.join(os.path.dirname(runlog), "upload.log")
  749. runstatus, uploader = self.run_app_onhw(appdir, runcfg, show_output, runlog, uploadlog)
  750. # If run successfully, then do log analyze
  751. if runlog and runstatus:
  752. appsts["result"] = self.analyze_runlog(runlog)
  753. appsts["logs"]["run"] = runlog
  754. appsts["logs"]["upload"] = uploadlog
  755. appsts["status_code"]["run"] = RUNSTATUS_OK if runstatus else RUNSTATUS_FAIL
  756. if uploader:
  757. appsts["app"]["uploader"] = uploader
  758. elif app_runtarget == "qemu":
  759. runstatus, runner = self.run_app_onqemu(appdir, runcfg, show_output, runlog)
  760. # If run successfully, then do log analyze
  761. if runlog and runstatus:
  762. appsts["result"] = self.analyze_runlog(runlog)
  763. appsts["logs"]["run"] = runlog
  764. appsts["status_code"]["run"] = RUNSTATUS_OK if runstatus else RUNSTATUS_FAIL
  765. if runner:
  766. appsts["app"]["qemu"] = runner
  767. elif app_runtarget == "xlspike":
  768. runstatus, runner = self.run_app_onxlspike(appdir, runcfg, show_output, runlog)
  769. # If run successfully, then do log analyze
  770. if runlog and runstatus:
  771. appsts["result"] = self.analyze_runlog(runlog)
  772. appsts["logs"]["run"] = runlog
  773. appsts["status_code"]["run"] = RUNSTATUS_OK if runstatus else RUNSTATUS_FAIL
  774. if runner:
  775. appsts["app"]["xlspike"] = runner
  776. elif app_runtarget == "ncycm":
  777. runstatus, runner = self.run_app_onncycm(appdir, runcfg, show_output, runlog)
  778. # If run successfully, then do log analyze
  779. if runlog and runstatus:
  780. appsts["result"] = self.analyze_runlog(runlog)
  781. appsts["logs"]["run"] = runlog
  782. appsts["status_code"]["run"] = RUNSTATUS_OK if runstatus else RUNSTATUS_FAIL
  783. if runner:
  784. appsts["app"]["ncycm"] = runner
  785. else:
  786. print("Unsupported run target %s" %(app_runtarget))
  787. runtime = round(time.time() - runstarttime, 2)
  788. print("Run application %s on %s, time cost %s seconds, passed: %s" %(appdir, app_runtarget, runtime, runstatus))
  789. sys.stdout.flush()
  790. appsts["status"]["run"] = runstatus
  791. appsts["time"]["run"] = runtime
  792. return runstatus, appsts
  793. def build_apps_with_config(self, config:dict, show_output=True, logdir=None, stoponfail=False):
  794. # Build all the applications, each application only has one configuration
  795. # "app" : { the_only_config }
  796. cmdsts = True
  797. build_status = dict()
  798. apps_config = copy.deepcopy(config)
  799. for appdir in apps_config:
  800. appconfig = apps_config[appdir]
  801. applogs = appconfig.get("logs", dict())
  802. applogfile = applogs.get("build", None)
  803. appcmdsts, appsts = self.build_app_with_config(appdir, appconfig, show_output, applogfile)
  804. build_status[appdir] = appsts
  805. if appcmdsts == False:
  806. cmdsts = appcmdsts
  807. if stoponfail == True:
  808. print("Stop build apps with config due to fail on application %s" %(appdir))
  809. return cmdsts, build_status
  810. return cmdsts, build_status
  811. def build_apps_with_configs(self, config:dict, show_output=True, logdir=None, stoponfail=False):
  812. # Build all the applications, each application has more than one configuration
  813. # "app" : {"configs": {"case1": case1_config}}
  814. cmdsts = True
  815. build_status = dict()
  816. apps_config = copy.deepcopy(config)
  817. for appdir in apps_config:
  818. appconfigs = apps_config[appdir]
  819. if "configs" not in appconfigs:
  820. continue
  821. build_status[appdir] = dict()
  822. app_allconfigs = appconfigs["configs"]
  823. for cfgname in app_allconfigs:
  824. appconfig = app_allconfigs[cfgname] # get configuration for each case for single app
  825. applogs = appconfig.get("logs", dict())
  826. applogfile = applogs.get("build", None)
  827. appcmdsts, appsts = self.build_app_with_config(appdir, appconfig, show_output, applogfile)
  828. build_status[appdir][cfgname] = appsts
  829. if appcmdsts == False:
  830. cmdsts = appcmdsts
  831. if stoponfail == True:
  832. print("Stop build apps with config due to fail on application %s" %(appdir))
  833. return cmdsts, build_status
  834. return cmdsts, build_status
  835. def run_apps_with_config(self, config:dict, show_output=True, stoponfail=False):
  836. # Run all the applications, each application only has one configuration
  837. # "app" : { the_only_config }
  838. cmdsts = True
  839. # reset error counters
  840. self.reset_counters()
  841. build_status = dict()
  842. apps_config = copy.deepcopy(config)
  843. for appdir in apps_config:
  844. appconfig = apps_config[appdir]
  845. applogs = appconfig.get("logs", dict())
  846. app_buildlogfile = applogs.get("build", None)
  847. app_runlogfile = applogs.get("run", None)
  848. appcmdsts, appsts = self.run_app_with_config(appdir, appconfig, show_output, app_buildlogfile, app_runlogfile)
  849. build_status[appdir] = appsts
  850. if appcmdsts == False:
  851. cmdsts = appcmdsts
  852. if stoponfail == True:
  853. print("ERROR: Stop run apps with config due to fail on application %s" %(appdir))
  854. return cmdsts, build_status
  855. # error exit check
  856. if self.need_exit_now():
  857. print("ERROR: Need to exit now due to error counter exceed limit!")
  858. self.show_counters()
  859. cmdsts = False
  860. return cmdsts, build_status
  861. return cmdsts, build_status
  862. def run_apps_with_configs(self, config:dict, show_output=True, stoponfail=False):
  863. # Run all the applications, each application has more than one configuration
  864. # "app" : {"configs": {"case1": case1_config}}
  865. cmdsts = True
  866. # reset error counters
  867. self.reset_counters()
  868. build_status = dict()
  869. apps_config = copy.deepcopy(config)
  870. for appdir in apps_config:
  871. appconfigs = apps_config[appdir]
  872. if "configs" not in appconfigs:
  873. continue
  874. build_status[appdir] = dict()
  875. app_allconfigs = appconfigs["configs"]
  876. for cfgname in app_allconfigs:
  877. appconfig = app_allconfigs[cfgname] # get configuration for each case for single app
  878. applogs = appconfig.get("logs", dict())
  879. app_buildlogfile = applogs.get("build", None)
  880. app_runlogfile = applogs.get("run", None)
  881. appcmdsts, appsts = self.run_app_with_config(appdir, appconfig, show_output, app_buildlogfile, app_runlogfile)
  882. build_status[appdir][cfgname] = appsts
  883. if appcmdsts == False:
  884. cmdsts = appcmdsts
  885. if stoponfail == True:
  886. print("ERROR: Stop run apps with config due to fail on application %s" %(appdir))
  887. return cmdsts, build_status
  888. # error exit check
  889. if self.need_exit_now():
  890. print("ERROR: Need to exit now due to error counter exceed limit!")
  891. self.show_counters()
  892. cmdsts = False
  893. return cmdsts, build_status
  894. return cmdsts, build_status