awlsim-test 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. #
  4. # AWL simulator - Commandline testing interface
  5. #
  6. # Copyright 2012-2018 Michael Buesch <m@bues.ch>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation; either version 2 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License along
  19. # with this program; if not, write to the Free Software Foundation, Inc.,
  20. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. #
  22. from __future__ import division, absolute_import, print_function, unicode_literals
  23. import sys
  24. import os
  25. import getopt
  26. import traceback
  27. import signal
  28. from awlsim_loader.common import *
  29. from awlsim_loader.core import *
  30. from awlsim_loader.coreclient import *
  31. from awlsim_loader.awlcompiler import *
  32. from awlsim_loader.fupcompiler import *
  33. import awlsim_loader.cython_helper as cython_helper
  34. class TestAwlSimClient(AwlSimClient):
  35. def handle_CPUDUMP(self, dumpText):
  36. emitCpuDump(dumpText)
  37. def handle_MEMORY(self, memAreas):
  38. for memArea in memAreas:
  39. if memArea.flags & (memArea.FLG_ERR_READ |
  40. memArea.FLG_ERR_WRITE):
  41. raise AwlSimError("awlsim-test: "
  42. "Failed to access memory: %s" % (
  43. str(memArea)))
  44. def usage():
  45. print("awlsim version %s" % VERSION_STRING)
  46. print("")
  47. print("Usage: awlsim-test [OPTIONS] <AWL-source or awlsim-project file>")
  48. print("")
  49. print("Options:")
  50. print(" -Y|--cycle-limit SEC Cycle time limit, in seconds (default 1.0)")
  51. print(" -M|--max-runtime SEC CPU will be stopped after SEC seconds (default: off)")
  52. print(" -2|--twoaccu Force 2-accu mode")
  53. print(" -4|--fouraccu Force 4-accu mode")
  54. print(" -D|--no-cpu-dump Do not show CPU status while running")
  55. print(" -x|--extended-insns Enable extended instructions")
  56. print(" -t|--obtemp 1/0 Enable/disable writing of OB-temp variables (Default: off)")
  57. print(" -T|--clock-mem ADDR Force clock memory address (Default: off)")
  58. print(" -m|--mnemonics auto Force mnemonics type: en, de, auto")
  59. print(" -O|--optimizers OPT Sets the optimization mode.")
  60. print(" OPT may be one of:")
  61. print(" default: Keep project settings (default)")
  62. print(" all: Enable all optimizers")
  63. print(" off: Disable all optimizers")
  64. print(" --insn-meas OUTFILE Detailed instruction timing measurements")
  65. print(" -L|--loglevel LVL Set the log level:")
  66. print(" 0: Log nothing")
  67. print(" 1: Log errors")
  68. print(" 2: Log errors and warnings")
  69. print(" 3: Log errors, warnings and info messages (default)")
  70. print(" 4: Verbose logging")
  71. print(" 5: Extremely verbose logging")
  72. print("")
  73. print("Server backend related options:")
  74. print(" -c|--connect Connect to server backend")
  75. print(" -C|--connect-to IP:PORT Connect to server backend")
  76. print(" -b|--spawn-backend Spawn a new backend server and connect to it")
  77. if not isWinStandalone:
  78. print(" -i|--interpreter EXE Set the backend interpreter executable")
  79. print(" -R|--mem-read AREA:OFFS:BITWIDTH Memory read access.")
  80. print(" -W|--mem-write AREA:OFFS:BITWIDTH:VAL Memory write access.")
  81. print("")
  82. print("Loading hardware modules:")
  83. print(" -H|--hardware NAME:PARAM=VAL:PARAM=VAL...")
  84. print("Print module information:")
  85. print(" -I|--hardware-info NAME")
  86. print("")
  87. print(" Where NAME is the name of the hardware module.")
  88. print(" PARAM=VAL are optional hardware specific parameters.")
  89. print("")
  90. print("Environment variables:")
  91. print(" AWLSIM_PROFILE =0 Disable profiling (default)")
  92. print(" =1 Enable core cycle profiling")
  93. print(" =2 Enable full core profiling (including startup)")
  94. print("")
  95. print(" AWLSIM_CYTHON =0 Do not attempt to use Cython core (default)")
  96. print(" =1 Attempt to use Cython core, but fall back to Python")
  97. print(" =2 Enforce Cython core")
  98. print("")
  99. print(" AWLSIM_AFFINITY =0,2,... Comma separated list of host CPU cores")
  100. print(" to run on. Default: all cores.")
  101. print(" AWLSIM_COVERAGE =DATAFILE Enable code coverage tracing.")
  102. def writeStdout(message):
  103. if Logging.loglevel >= Logging.LOG_INFO:
  104. sys.stdout.write(message)
  105. if not isMicroPython:
  106. sys.stdout.flush()
  107. nextScreenUpdate = 0.0
  108. lastDump = ""
  109. lastDumpNrLines = 0
  110. emptyLine = " " * 79
  111. def clearConsole():
  112. # Make cursor visible, clear console and
  113. # move cursor to homeposition.
  114. if osIsPosix:
  115. writeStdout("\x1B[?25h\x1B[2J\x1B[H")
  116. elif osIsWindows:
  117. os.system("cls")
  118. def emitCpuDump(dump):
  119. global lastDump
  120. global lastDumpNrLines
  121. # Pad lines
  122. dumpLines = list(line + (78 - len(line)) * ' ' + '|'
  123. for line in dump.splitlines())
  124. dumpNrLines = len(dumpLines)
  125. # Clear lines from previous dump.
  126. if dumpNrLines < lastDumpNrLines:
  127. dumpLines.extend([ emptyLine, ] * (lastDumpNrLines - dumpNrLines))
  128. dump = "\n".join(dumpLines)
  129. lastDumpNrLines = dumpNrLines
  130. lastDump = dump
  131. if osIsPosix:
  132. # Clear console, move home and print dump.
  133. writeStdout("\x1B[2J\x1B[H" + dump)
  134. else:
  135. # Clear console, move home and print dump.
  136. clearConsole()
  137. writeStdout(dump)
  138. def cpuBlockExitCallback(cpu):
  139. global nextScreenUpdate
  140. if cpu.now >= nextScreenUpdate:
  141. nextScreenUpdate = cpu.now + 0.3
  142. emitCpuDump(str(cpu))
  143. def assignCpuSpecs(cpuSpecs, projectCpuSpecs):
  144. cpuSpecs.assignFrom(projectCpuSpecs)
  145. if opt_nrAccus is not None:
  146. cpuSpecs.setNrAccus(opt_nrAccus)
  147. def assignCpuConf(cpuConf, projectCpuConf):
  148. cpuConf.assignFrom(projectCpuConf)
  149. if opt_mnemonics is not None:
  150. cpuConf.setConfiguredMnemonics(opt_mnemonics)
  151. if opt_clockMem is not None:
  152. cpuConf.setClockMemByte(opt_clockMem)
  153. if opt_cycletime is not None:
  154. cpuConf.setCycleTimeLimitUs(int(round(opt_cycletime * 1000000.0)))
  155. if opt_maxRuntime is not None:
  156. cpuConf.setRunTimeLimitUs(int(round(opt_maxRuntime * 1000000.0)))
  157. if opt_obtemp is not None:
  158. cpuConf.setOBStartinfoEn(opt_obtemp)
  159. if opt_extInsns is not None:
  160. cpuConf.setExtInsnsEn(opt_extInsns)
  161. def readInputFile(inputFile):
  162. if inputFile == "-":
  163. if isPy2Compat:
  164. dataBytes = sys.stdin.read()
  165. else:
  166. dataBytes = sys.stdin.buffer.read()
  167. project = Project.fromProjectOrRawAwlData(dataBytes)
  168. else:
  169. project = Project.fromProjectOrRawAwlFile(inputFile)
  170. return project
  171. def run(inputFile):
  172. insnMeas = None
  173. s = None
  174. try:
  175. if cython_helper.shouldUseCython():
  176. printInfo("*** Using accelerated CYTHON core "
  177. "(AWLSIM_CYTHON environment variable is set)")
  178. if opt_memReads or opt_memWrites:
  179. raise AwlSimError("awlsim-test --mem-read and --mem-write "
  180. "are not supported in non-server-mode.")
  181. project = readInputFile(inputFile)
  182. printInfo("Parsing code...")
  183. generatedAwlSrcs = []
  184. # Get mnemonics type
  185. mnemonics = project.getCpuConf().getConfiguredMnemonics()
  186. if opt_mnemonics is not None:
  187. mnemonics = opt_mnemonics
  188. # Parse FUP sources
  189. optSettCont = None
  190. if opt_optimizers == "off":
  191. optSettCont = AwlOptimizerSettingsContainer(globalEnable=False)
  192. elif opt_optimizers == "all":
  193. optSettCont = AwlOptimizerSettingsContainer(globalEnable=True,
  194. allEnable=True)
  195. for fupSrc in project.getFupSources():
  196. if not fupSrc.enabled:
  197. continue
  198. generatedAwlSrcs.append(FupCompiler().compile(
  199. fupSource=fupSrc,
  200. symTabSources=project.getSymTabSources(),
  201. mnemonics=mnemonics,
  202. optimizerSettingsContainer=optSettCont))
  203. # Parse KOP sources
  204. for kopSrc in project.getKopSources():
  205. if not kopSrc.enabled:
  206. continue
  207. pass#TODO
  208. # Parse AWL sources
  209. parseTrees = []
  210. for awlSrc in itertools.chain(project.getAwlSources(),
  211. generatedAwlSrcs):
  212. if not awlSrc.enabled:
  213. continue
  214. p = AwlParser()
  215. p.parseSource(awlSrc)
  216. parseTrees.append(p.getParseTree())
  217. # Parse symbol tables
  218. symTables = []
  219. for symTabSrc in project.getSymTabSources():
  220. if not symTabSrc.enabled:
  221. continue
  222. tab = SymTabParser.parseSource(symTabSrc,
  223. autodetectFormat = True,
  224. mnemonics = mnemonics)
  225. symTables.append(tab)
  226. printInfo("Initializing core...")
  227. s = AwlSim()
  228. s.reset()
  229. # Load hardware modules
  230. def loadMod(name, parameters):
  231. printInfo("Loading hardware module '%s'..." % name)
  232. hwClass = s.loadHardwareModule(name)
  233. s.registerHardwareClass(hwClass = hwClass,
  234. parameters = parameters)
  235. for modDesc in project.getHwmodSettings().getLoadedModules():
  236. loadMod(modDesc.getModuleName(),
  237. modDesc.getParameters())
  238. for name, parameters in opt_hwmods:
  239. loadMod(name, parameters)
  240. # Configure the CPU
  241. cpu = s.getCPU()
  242. assignCpuSpecs(cpu.getSpecs(), project.getCpuSpecs())
  243. assignCpuConf(cpu.getConf(), project.getCpuConf())
  244. if not opt_noCpuDump and opt_loglevel >= Logging.LOG_INFO:
  245. cpu.setBlockExitCallback(cpuBlockExitCallback, cpu)
  246. # Download the program
  247. printInfo("Initializing CPU...")
  248. for symTable in symTables:
  249. s.loadSymbolTable(symTable)
  250. for libSel in project.getLibSelections():
  251. s.loadLibraryBlock(libSel)
  252. for parseTree in parseTrees:
  253. s.load(parseTree)
  254. s.build()
  255. if opt_insnMeas:
  256. insnMeas = cpu.setupInsnMeas()
  257. # Run the program
  258. s.startup()
  259. printInfo("[Initialization finished - CPU is executing user code]")
  260. try:
  261. if not opt_noCpuDump:
  262. clearConsole()
  263. while 1:
  264. s.runCycle()
  265. finally:
  266. if not opt_noCpuDump and opt_loglevel >= Logging.LOG_INFO:
  267. clearConsole()
  268. writeStdout(lastDump + '\n')
  269. except (AwlParserError, AwlSimError) as e:
  270. printError(e.getReport())
  271. return ExitCodes.EXIT_ERR_SIM
  272. except KeyboardInterrupt as e:
  273. if insnMeas:
  274. if insnMeas.haveAnyMeasurements:
  275. if opt_insnMeas == "-":
  276. writeStdout(insnMeas.dump())
  277. else:
  278. with open(opt_insnMeas, "wb") as fd:
  279. fd.write(insnMeas.dumpCSV().encode("UTF-8"))
  280. else:
  281. printError("Instruction timing measurement: Not enough samples.")
  282. return ExitCodes.EXIT_ERR_OTHER
  283. except MaintenanceRequest as e:
  284. if e.requestType in (MaintenanceRequest.TYPE_SHUTDOWN,
  285. MaintenanceRequest.TYPE_STOP,
  286. MaintenanceRequest.TYPE_RTTIMEOUT):
  287. printInfo("Shutting down, as requested (%s)..." % str(e))
  288. else:
  289. printError("Received unknown maintenance request "
  290. "(%d: %s)..." % (e.requestType, str(e)))
  291. finally:
  292. if s:
  293. s.shutdown()
  294. return ExitCodes.EXIT_OK
  295. def runWithServerBackend(inputFile):
  296. client = None
  297. tunnel = None
  298. try:
  299. project = readInputFile(inputFile)
  300. linkSettings = project.getCoreLinkSettings()
  301. if opt_spawnBackend:
  302. host = AwlSimServer.DEFAULT_HOST
  303. port = range(AwlSimServer.DEFAULT_PORT,
  304. AwlSimServer.DEFAULT_PORT + 4096)
  305. else:
  306. host = linkSettings.getConnectHost()
  307. port = linkSettings.getConnectPort()
  308. if opt_connectTo:
  309. host, port = opt_connectTo
  310. # Establish SSH tunnel, if requested.
  311. if linkSettings.getTunnel() == linkSettings.TUNNEL_SSH and\
  312. not opt_spawnBackend:
  313. printInfo("Establishing SSH tunnel...")
  314. localPort = linkSettings.getTunnelLocalPort()
  315. if localPort == linkSettings.TUNNEL_LOCPORT_AUTO:
  316. localPort = None
  317. tunnel = SSHTunnel(
  318. remoteHost=host,
  319. remotePort=port,
  320. localPort=localPort,
  321. sshUser=linkSettings.getSSHUser(),
  322. sshPort=linkSettings.getSSHPort(),
  323. sshExecutable=linkSettings.getSSHExecutable(),
  324. )
  325. host, port = tunnel.connect()
  326. # Connect to the server
  327. client = TestAwlSimClient()
  328. if opt_spawnBackend:
  329. client.spawnServer(interpreter = opt_interpreter,
  330. listenHost = host,
  331. listenPort = port)
  332. port = client.serverProcessPort
  333. printInfo("Connecting to core server...")
  334. client.connectToServer(host=host, port=port, timeout=20.0)
  335. printInfo("Initializing core...")
  336. client.setLoglevel(opt_loglevel)
  337. client.setRunState(False)
  338. client.reset()
  339. # Load hardware modules
  340. client.loadHardwareModules(project.getHwmodSettings().getLoadedModules())
  341. for name, parameters in opt_hwmods:
  342. client.loadHardwareModule(HwmodDescriptor(name, parameters))
  343. # Configure the core
  344. if opt_noCpuDump:
  345. client.setPeriodicDumpInterval(0)
  346. else:
  347. client.setPeriodicDumpInterval(300)
  348. specs = client.getCpuSpecs()
  349. assignCpuSpecs(specs, project.getCpuSpecs())
  350. client.setCpuSpecs(specs)
  351. conf = client.getCpuConf()
  352. assignCpuConf(conf, project.getCpuConf())
  353. client.setCpuConf(conf)
  354. #TODO configure optimizers
  355. # Fire up the core
  356. printInfo("Initializing CPU...")
  357. client.loadProject(project, loadCpuSpecs=False,
  358. loadCpuConf=False,
  359. loadHwMods=False)
  360. client.setRunState(True)
  361. # Run the client-side event loop
  362. printInfo("[Initialization finished - Remote-CPU is executing user code]")
  363. try:
  364. if opt_memReads:
  365. client.setMemoryReadRequests(memAreas=opt_memReads,
  366. repetitionPeriod=0.001,
  367. sync=False)
  368. if not opt_noCpuDump:
  369. clearConsole()
  370. while True:
  371. client.processMessages(timeout=0.05)
  372. if opt_memWrites:
  373. client.writeMemory(memAreas=opt_memWrites,
  374. sync=True)
  375. finally:
  376. if not opt_noCpuDump and opt_loglevel >= Logging.LOG_INFO:
  377. clearConsole()
  378. writeStdout(lastDump + '\n')
  379. except AwlSimError as e:
  380. printError(e.getReport())
  381. return ExitCodes.EXIT_ERR_SIM
  382. except MaintenanceRequest as e:
  383. if e.requestType in (MaintenanceRequest.TYPE_SHUTDOWN,
  384. MaintenanceRequest.TYPE_STOP,
  385. MaintenanceRequest.TYPE_RTTIMEOUT):
  386. printInfo("Shutting down, as requested (%s)..." % str(e))
  387. else:
  388. printError("Received unknown maintenance request "
  389. "(%d: %s)..." % (e.requestType, str(e)))
  390. except KeyboardInterrupt as e:
  391. pass
  392. finally:
  393. if client:
  394. client.shutdown()
  395. if tunnel:
  396. tunnel.shutdown()
  397. return ExitCodes.EXIT_OK
  398. def __signalHandler(sig, frame):
  399. printInfo("Received signal %d" % sig)
  400. if sig == signal.SIGTERM:
  401. # Raise SIGINT. It will shut down everything.
  402. os.kill(os.getpid(), signal.SIGINT)
  403. def parseMemoryArea(memAreaStr, withData):
  404. try:
  405. def dataToBytes(value, length):
  406. if not (0 <= value <= ((1 << length) - 1)):
  407. raise ValueError
  408. return WordPacker.toBytes(byteBuffer=bytearray(length // 8),
  409. bitWidth=length,
  410. value=value)
  411. memAreaStr = memAreaStr.split(":")
  412. start = index = length = 0
  413. data = b''
  414. memType = {
  415. "E" : MemoryArea.TYPE_E,
  416. "A" : MemoryArea.TYPE_A,
  417. "M" : MemoryArea.TYPE_M,
  418. "L" : MemoryArea.TYPE_L,
  419. "DB" : MemoryArea.TYPE_DB,
  420. "T" : MemoryArea.TYPE_T,
  421. "Z" : MemoryArea.TYPE_Z,
  422. "STW" : MemoryArea.TYPE_STW,
  423. }[memAreaStr[0].upper().strip()]
  424. if memType in { MemoryArea.TYPE_E,
  425. MemoryArea.TYPE_A,
  426. MemoryArea.TYPE_M,
  427. MemoryArea.TYPE_L, }:
  428. start = int(memAreaStr[1])
  429. length = int(memAreaStr[2])
  430. if (not (0 <= start <= 0xFFFF) or
  431. length not in (8, 16, 32)):
  432. raise ValueError
  433. if withData:
  434. data = dataToBytes(int(memAreaStr[3]), length)
  435. elif memType == MemoryArea.TYPE_DB:
  436. index = int(memAreaStr[1])
  437. start = int(memAreaStr[2])
  438. length = int(memAreaStr[3])
  439. if (not (0 <= start <= 0xFFFF) or
  440. not (0 <= index <= 0xFFFF) or
  441. length not in (8, 16, 32)):
  442. raise ValueError
  443. if withData:
  444. data = dataToBytes(int(memAreaStr[4]), length)
  445. elif memType in { MemoryArea.TYPE_T,
  446. MemoryArea.TYPE_Z, }:
  447. index = int(memAreaStr[1])
  448. length = 16
  449. if not (0 <= index <= 0xFFFF):
  450. raise ValueError
  451. if withData:
  452. data = dataToBytes(int(memAreaStr[2]), 16)
  453. elif memType == MemoryArea.TYPE_STW:
  454. length = 16
  455. if withData:
  456. data = dataToBytes(int(memAreaStr[1]), 16)
  457. else:
  458. assert(0)
  459. return MemoryArea(memType=memType,
  460. flags=0,
  461. index=index,
  462. start=start,
  463. length=length // 8,
  464. data=data)
  465. except (ValueError, IndexError, KeyError, AwlSimError) as e:
  466. pass
  467. return None
  468. def main():
  469. global opt_cycletime
  470. global opt_maxRuntime
  471. global opt_noCpuDump
  472. global opt_nrAccus
  473. global opt_extInsns
  474. global opt_obtemp
  475. global opt_clockMem
  476. global opt_mnemonics
  477. global opt_optimizers
  478. global opt_insnMeas
  479. global opt_hwmods
  480. global opt_hwinfos
  481. global opt_loglevel
  482. global opt_connect
  483. global opt_connectTo
  484. global opt_spawnBackend
  485. global opt_interpreter
  486. global opt_memReads
  487. global opt_memWrites
  488. opt_cycletime = None
  489. opt_maxRuntime = None
  490. opt_noCpuDump = False
  491. opt_nrAccus = None
  492. opt_extInsns = None
  493. opt_obtemp = None
  494. opt_clockMem = None
  495. opt_mnemonics = None
  496. opt_optimizers = "default"
  497. opt_insnMeas = None
  498. opt_hwmods = []
  499. opt_hwinfos = []
  500. opt_loglevel = Logging.LOG_INFO
  501. opt_connect = None
  502. opt_connectTo = False
  503. opt_spawnBackend = False
  504. opt_interpreter = None
  505. opt_memReads = []
  506. opt_memWrites = []
  507. try:
  508. (opts, args) = getopt.getopt(sys.argv[1:],
  509. "hY:M:24qDxt:T:m:O:H:I:P:L:cC:bi:R:W:",
  510. [ "help", "cycle-limit=", "max-runtime=", "twoaccu", "fouraccu",
  511. "quiet", "no-cpu-dump", "extended-insns",
  512. "obtemp=", "clock-mem=", "mnemonics=", "optimizers=",
  513. "hardware=", "hardware-info=", "profile=",
  514. "loglevel=",
  515. "connect", "connect-to=", "spawn-backend", "interpreter=",
  516. "mem-read=", "mem-write=",
  517. "insn-meas=", ])
  518. except getopt.GetoptError as e:
  519. printError(str(e))
  520. usage()
  521. return ExitCodes.EXIT_ERR_CMDLINE
  522. for (o, v) in opts:
  523. if o in ("-h", "--help"):
  524. usage()
  525. return ExitCodes.EXIT_OK
  526. if o in ("-Y", "--cycle-limit"):
  527. try:
  528. opt_cycletime = float(v)
  529. except ValueError:
  530. printError("-Y|--cycle-limit: Invalid time format")
  531. sys.exit(1)
  532. if o in ("-M", "--max-runtime"):
  533. try:
  534. opt_maxRuntime = float(v)
  535. except ValueError:
  536. printError("-M|--max-runtime: Invalid time format")
  537. sys.exit(1)
  538. if o in ("-2", "--twoaccu"):
  539. opt_nrAccus = 2
  540. if o in ("-4", "--fouraccu"):
  541. opt_nrAccus = 4
  542. if o in ("-D", "--no-cpu-dump"):
  543. opt_noCpuDump = True
  544. if o in ("-x", "--extended-insns"):
  545. opt_extInsns = True
  546. if o in ("-t", "--obtemp"):
  547. opt_obtemp = str2bool(v)
  548. if o in ("-T", "--clock-mem"):
  549. try:
  550. opt_clockMem = int(v)
  551. if opt_clockMem < -1 or opt_clockMem > 0xFFFF:
  552. raise ValueError
  553. except ValueError:
  554. printError("-T|--clock-mem: Invalid byte address")
  555. sys.exit(1)
  556. if o in ("-m", "--mnemonics"):
  557. opt_mnemonics = v.lower()
  558. if opt_mnemonics not in ("en", "de", "auto"):
  559. printError("-m|--mnemonics: Invalid mnemonics type")
  560. sys.exit(1)
  561. if o in ("-O", "--optimizers"):
  562. try:
  563. modes = v.split(",")
  564. for mode in modes:
  565. mode = mode.lower()
  566. if mode in ("off", "all", "default"):
  567. opt_optimizers = mode
  568. else:
  569. printError("-O|--optimizers: Unknown optimizer: %s" % mode)
  570. sys.exit(1)
  571. except (ValueError, IndexError) as e:
  572. printError("-O|--optimizers: Invalid optimization mode")
  573. sys.exit(1)
  574. if o == "--insn-meas":
  575. opt_insnMeas = v
  576. if o in ("-H", "--hardware"):
  577. try:
  578. v = v.split(':')
  579. if not v:
  580. raise ValueError
  581. name = v[0]
  582. params = {}
  583. for pstr in v[1:]:
  584. if not pstr:
  585. continue
  586. i = pstr.find('=')
  587. if i < 0:
  588. raise ValueError
  589. pname = pstr[:i]
  590. pval = pstr[i+1:]
  591. if not pname or not pval:
  592. raise ValueError
  593. params[pname] = pval
  594. opt_hwmods.append( (name, params) )
  595. except (ValueError, IndexError) as e:
  596. printError("-H|--hardware: Invalid module name or parameters")
  597. sys.exit(1)
  598. if o in ("-I", "--hardware-info"):
  599. opt_hwinfos.append(v.split(':')[0])
  600. if o in ("-L", "--loglevel"):
  601. try:
  602. opt_loglevel = int(v)
  603. except ValueError:
  604. printError("-L|--loglevel: Invalid log level")
  605. sys.exit(1)
  606. if o in ("-c", "--connect"):
  607. opt_connect = True
  608. if o in ("-C", "--connect-to"):
  609. try:
  610. idx = v.rfind(":")
  611. if idx <= 0:
  612. raise ValueError
  613. opt_connectTo = (v[:idx], int(v[idx+1:]))
  614. except ValueError:
  615. printError("-c|--connect: Invalid host/port")
  616. sys.exit(1)
  617. if o in ("-b", "--spawn-backend"):
  618. opt_spawnBackend = True
  619. if o in ("-i", "--interpreter"):
  620. if isWinStandalone:
  621. printError("-i|--interpreter not supported on win-standalone")
  622. sys.exit(1)
  623. opt_interpreter = v
  624. if o in ("-R", "--mem-read"):
  625. memArea = parseMemoryArea(v, withData=False)
  626. if not memArea:
  627. printError("-R|--mem-read invalid arguments.")
  628. sys.exit(1)
  629. opt_memReads.append(memArea)
  630. if o in ("-W", "--mem-write"):
  631. memArea = parseMemoryArea(v, withData=True)
  632. if not memArea:
  633. printError("-W|--mem-write invalid arguments.")
  634. sys.exit(1)
  635. opt_memWrites.append(memArea)
  636. if len(args) != 1 and not opt_hwinfos:
  637. usage()
  638. return ExitCodes.EXIT_ERR_CMDLINE
  639. if args:
  640. inputFile = args[0]
  641. Logging.setLoglevel(opt_loglevel)
  642. opt_mnemonics = {
  643. None : None,
  644. "en" : S7CPUConfig.MNEMONICS_EN,
  645. "de" : S7CPUConfig.MNEMONICS_DE,
  646. "auto" : S7CPUConfig.MNEMONICS_AUTO,
  647. }[opt_mnemonics]
  648. try:
  649. if opt_hwinfos:
  650. # Just print the hardware-infos and exit.
  651. for name in opt_hwinfos:
  652. cls = AwlSim.loadHardwareModule(name)
  653. print(cls.getModuleInfo())
  654. return ExitCodes.EXIT_OK
  655. except (AwlParserError, AwlSimError) as e:
  656. printError(e.getReport())
  657. return ExitCodes.EXIT_ERR_SIM
  658. signal.signal(signal.SIGTERM, __signalHandler)
  659. if opt_interpreter and not opt_spawnBackend:
  660. printError("Selected an --interpreter, but no "
  661. "--spawn-backend was requested.")
  662. return ExitCodes.EXIT_ERR_CMDLINE
  663. if opt_spawnBackend or opt_connect or opt_connectTo:
  664. return runWithServerBackend(inputFile)
  665. return run(inputFile)
  666. if __name__ == "__main__":
  667. sys.exit(main())