nsdk_builder.py 39 KB

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