awlsim-test 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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. sys.stdout.flush()
  106. nextScreenUpdate = 0.0
  107. lastDump = ""
  108. lastDumpNrLines = 0
  109. emptyLine = " " * 79
  110. def clearConsole():
  111. # Make cursor visible, clear console and
  112. # move cursor to homeposition.
  113. if osIsPosix:
  114. writeStdout("\x1B[?25h\x1B[2J\x1B[H")
  115. elif osIsWindows:
  116. os.system("cls")
  117. def emitCpuDump(dump):
  118. global lastDump
  119. global lastDumpNrLines
  120. # Pad lines
  121. dumpLines = list(line + (78 - len(line)) * ' ' + '|'
  122. for line in dump.splitlines())
  123. dumpNrLines = len(dumpLines)
  124. # Clear lines from previous dump.
  125. if dumpNrLines < lastDumpNrLines:
  126. dumpLines.extend([ emptyLine, ] * (lastDumpNrLines - dumpNrLines))
  127. dump = "\n".join(dumpLines)
  128. lastDumpNrLines = dumpNrLines
  129. lastDump = dump
  130. if osIsPosix:
  131. # Clear console, move home and print dump.
  132. writeStdout("\x1B[2J\x1B[H" + dump)
  133. else:
  134. # Clear console, move home and print dump.
  135. clearConsole()
  136. writeStdout(dump)
  137. def cpuBlockExitCallback(cpu):
  138. global nextScreenUpdate
  139. if cpu.now >= nextScreenUpdate:
  140. nextScreenUpdate = cpu.now + 0.3
  141. emitCpuDump(str(cpu))
  142. def assignCpuSpecs(cpuSpecs, projectCpuSpecs):
  143. cpuSpecs.assignFrom(projectCpuSpecs)
  144. if opt_nrAccus is not None:
  145. cpuSpecs.setNrAccus(opt_nrAccus)
  146. def assignCpuConf(cpuConf, projectCpuConf):
  147. cpuConf.assignFrom(projectCpuConf)
  148. if opt_mnemonics is not None:
  149. cpuConf.setConfiguredMnemonics(opt_mnemonics)
  150. if opt_clockMem is not None:
  151. cpuConf.setClockMemByte(opt_clockMem)
  152. if opt_cycletime is not None:
  153. cpuConf.setCycleTimeLimitUs(int(round(opt_cycletime * 1000000.0)))
  154. if opt_maxRuntime is not None:
  155. cpuConf.setRunTimeLimitUs(int(round(opt_maxRuntime * 1000000.0)))
  156. if opt_obtemp is not None:
  157. cpuConf.setOBStartinfoEn(opt_obtemp)
  158. if opt_extInsns is not None:
  159. cpuConf.setExtInsnsEn(opt_extInsns)
  160. def readInputFile(inputFile):
  161. if inputFile == "-":
  162. if isPy2Compat:
  163. dataBytes = sys.stdin.read()
  164. else:
  165. dataBytes = sys.stdin.buffer.read()
  166. project = Project.fromProjectOrRawAwlData(dataBytes)
  167. else:
  168. project = Project.fromProjectOrRawAwlFile(inputFile)
  169. return project
  170. def run(inputFile):
  171. insnMeas = None
  172. s = None
  173. try:
  174. if cython_helper.shouldUseCython():
  175. printInfo("*** Using accelerated CYTHON core "
  176. "(AWLSIM_CYTHON environment variable is set)")
  177. if opt_memReads or opt_memWrites:
  178. raise AwlSimError("awlsim-test --mem-read and --mem-write "
  179. "are not supported in non-server-mode.")
  180. project = readInputFile(inputFile)
  181. printInfo("Parsing code...")
  182. generatedAwlSrcs = []
  183. # Get mnemonics type
  184. mnemonics = project.getCpuConf().getConfiguredMnemonics()
  185. if opt_mnemonics is not None:
  186. mnemonics = opt_mnemonics
  187. # Parse FUP sources
  188. optSettCont = None
  189. if opt_optimizers == "off":
  190. optSettCont = AwlOptimizerSettingsContainer(globalEnable=False)
  191. elif opt_optimizers == "all":
  192. optSettCont = AwlOptimizerSettingsContainer(globalEnable=True,
  193. allEnable=True)
  194. for fupSrc in project.getFupSources():
  195. if not fupSrc.enabled:
  196. continue
  197. generatedAwlSrcs.append(FupCompiler().compile(
  198. fupSource=fupSrc,
  199. symTabSources=project.getSymTabSources(),
  200. mnemonics=mnemonics,
  201. optimizerSettingsContainer=optSettCont))
  202. # Parse KOP sources
  203. for kopSrc in project.getKopSources():
  204. if not kopSrc.enabled:
  205. continue
  206. pass#TODO
  207. # Parse AWL sources
  208. parseTrees = []
  209. for awlSrc in itertools.chain(project.getAwlSources(),
  210. generatedAwlSrcs):
  211. if not awlSrc.enabled:
  212. continue
  213. p = AwlParser()
  214. p.parseSource(awlSrc)
  215. parseTrees.append(p.getParseTree())
  216. # Parse symbol tables
  217. symTables = []
  218. for symTabSrc in project.getSymTabSources():
  219. if not symTabSrc.enabled:
  220. continue
  221. tab = SymTabParser.parseSource(symTabSrc,
  222. autodetectFormat = True,
  223. mnemonics = mnemonics)
  224. symTables.append(tab)
  225. printInfo("Initializing core...")
  226. s = AwlSim()
  227. s.reset()
  228. # Load hardware modules
  229. def loadMod(name, parameters):
  230. printInfo("Loading hardware module '%s'..." % name)
  231. hwClass = s.loadHardwareModule(name)
  232. s.registerHardwareClass(hwClass = hwClass,
  233. parameters = parameters)
  234. for modDesc in project.getHwmodSettings().getLoadedModules():
  235. loadMod(modDesc.getModuleName(),
  236. modDesc.getParameters())
  237. for name, parameters in opt_hwmods:
  238. loadMod(name, parameters)
  239. # Configure the CPU
  240. cpu = s.getCPU()
  241. assignCpuSpecs(cpu.getSpecs(), project.getCpuSpecs())
  242. assignCpuConf(cpu.getConf(), project.getCpuConf())
  243. if not opt_noCpuDump and opt_loglevel >= Logging.LOG_INFO:
  244. cpu.setBlockExitCallback(cpuBlockExitCallback, cpu)
  245. # Download the program
  246. printInfo("Initializing CPU...")
  247. for symTable in symTables:
  248. s.loadSymbolTable(symTable)
  249. for libSel in project.getLibSelections():
  250. s.loadLibraryBlock(libSel)
  251. for parseTree in parseTrees:
  252. s.load(parseTree)
  253. s.build()
  254. if opt_insnMeas:
  255. insnMeas = cpu.setupInsnMeas()
  256. # Run the program
  257. s.startup()
  258. printInfo("[Initialization finished - CPU is executing user code]")
  259. try:
  260. if not opt_noCpuDump:
  261. clearConsole()
  262. while 1:
  263. s.runCycle()
  264. finally:
  265. if not opt_noCpuDump and opt_loglevel >= Logging.LOG_INFO:
  266. clearConsole()
  267. writeStdout(lastDump + '\n')
  268. except (AwlParserError, AwlSimError) as e:
  269. printError(e.getReport())
  270. return ExitCodes.EXIT_ERR_SIM
  271. except KeyboardInterrupt as e:
  272. if insnMeas:
  273. if insnMeas.haveAnyMeasurements:
  274. if opt_insnMeas == "-":
  275. writeStdout(insnMeas.dump())
  276. else:
  277. with open(opt_insnMeas, "wb") as fd:
  278. fd.write(insnMeas.dumpCSV().encode("UTF-8"))
  279. else:
  280. printError("Instruction timing measurement: Not enough samples.")
  281. return ExitCodes.EXIT_ERR_OTHER
  282. except MaintenanceRequest as e:
  283. if e.requestType in (MaintenanceRequest.TYPE_SHUTDOWN,
  284. MaintenanceRequest.TYPE_STOP,
  285. MaintenanceRequest.TYPE_RTTIMEOUT):
  286. printInfo("Shutting down, as requested (%s)..." % str(e))
  287. else:
  288. printError("Received unknown maintenance request "
  289. "(%d: %s)..." % (e.requestType, str(e)))
  290. finally:
  291. if s:
  292. s.shutdown()
  293. return ExitCodes.EXIT_OK
  294. def runWithServerBackend(inputFile):
  295. client = None
  296. tunnel = None
  297. try:
  298. project = readInputFile(inputFile)
  299. linkSettings = project.getCoreLinkSettings()
  300. if opt_spawnBackend:
  301. host = AwlSimServer.DEFAULT_HOST
  302. port = range(AwlSimServer.DEFAULT_PORT,
  303. AwlSimServer.DEFAULT_PORT + 4096)
  304. else:
  305. host = linkSettings.getConnectHost()
  306. port = linkSettings.getConnectPort()
  307. if opt_connectTo:
  308. host, port = opt_connectTo
  309. # Establish SSH tunnel, if requested.
  310. if linkSettings.getTunnel() == linkSettings.TUNNEL_SSH and\
  311. not opt_spawnBackend:
  312. printInfo("Establishing SSH tunnel...")
  313. localPort = linkSettings.getTunnelLocalPort()
  314. if localPort == linkSettings.TUNNEL_LOCPORT_AUTO:
  315. localPort = None
  316. tunnel = SSHTunnel(
  317. remoteHost=host,
  318. remotePort=port,
  319. localPort=localPort,
  320. sshUser=linkSettings.getSSHUser(),
  321. sshPort=linkSettings.getSSHPort(),
  322. sshExecutable=linkSettings.getSSHExecutable(),
  323. )
  324. host, port = tunnel.connect()
  325. # Connect to the server
  326. client = TestAwlSimClient()
  327. if opt_spawnBackend:
  328. client.spawnServer(interpreter = opt_interpreter,
  329. listenHost = host,
  330. listenPort = port)
  331. port = client.serverProcessPort
  332. printInfo("Connecting to core server...")
  333. client.connectToServer(host=host, port=port, timeout=20.0)
  334. printInfo("Initializing core...")
  335. client.setLoglevel(opt_loglevel)
  336. client.setRunState(False)
  337. client.reset()
  338. # Load hardware modules
  339. client.loadHardwareModules(project.getHwmodSettings().getLoadedModules())
  340. for name, parameters in opt_hwmods:
  341. client.loadHardwareModule(HwmodDescriptor(name, parameters))
  342. # Configure the core
  343. if opt_noCpuDump:
  344. client.setPeriodicDumpInterval(0)
  345. else:
  346. client.setPeriodicDumpInterval(300)
  347. specs = client.getCpuSpecs()
  348. assignCpuSpecs(specs, project.getCpuSpecs())
  349. client.setCpuSpecs(specs)
  350. conf = client.getCpuConf()
  351. assignCpuConf(conf, project.getCpuConf())
  352. client.setCpuConf(conf)
  353. #TODO configure optimizers
  354. # Fire up the core
  355. printInfo("Initializing CPU...")
  356. client.loadProject(project, loadCpuSpecs=False,
  357. loadCpuConf=False,
  358. loadHwMods=False)
  359. client.setRunState(True)
  360. # Run the client-side event loop
  361. printInfo("[Initialization finished - Remote-CPU is executing user code]")
  362. try:
  363. if opt_memReads:
  364. client.setMemoryReadRequests(memAreas=opt_memReads,
  365. repetitionPeriod=0.001,
  366. sync=False)
  367. if not opt_noCpuDump:
  368. clearConsole()
  369. while True:
  370. client.processMessages(timeout=0.05)
  371. if opt_memWrites:
  372. client.writeMemory(memAreas=opt_memWrites,
  373. sync=True)
  374. finally:
  375. if not opt_noCpuDump and opt_loglevel >= Logging.LOG_INFO:
  376. clearConsole()
  377. writeStdout(lastDump + '\n')
  378. except AwlSimError as e:
  379. printError(e.getReport())
  380. return ExitCodes.EXIT_ERR_SIM
  381. except MaintenanceRequest as e:
  382. if e.requestType in (MaintenanceRequest.TYPE_SHUTDOWN,
  383. MaintenanceRequest.TYPE_STOP,
  384. MaintenanceRequest.TYPE_RTTIMEOUT):
  385. printInfo("Shutting down, as requested (%s)..." % str(e))
  386. else:
  387. printError("Received unknown maintenance request "
  388. "(%d: %s)..." % (e.requestType, str(e)))
  389. except KeyboardInterrupt as e:
  390. pass
  391. finally:
  392. if client:
  393. client.shutdown()
  394. if tunnel:
  395. tunnel.shutdown()
  396. return ExitCodes.EXIT_OK
  397. def __signalHandler(sig, frame):
  398. printInfo("Received signal %d" % sig)
  399. if sig == signal.SIGTERM:
  400. # Raise SIGINT. It will shut down everything.
  401. os.kill(os.getpid(), signal.SIGINT)
  402. def parseMemoryArea(memAreaStr, withData):
  403. try:
  404. def dataToBytes(value, length):
  405. if not (0 <= value <= ((1 << length) - 1)):
  406. raise ValueError
  407. return WordPacker.toBytes(byteBuffer=bytearray(length // 8),
  408. bitWidth=length,
  409. value=value)
  410. memAreaStr = memAreaStr.split(":")
  411. start = index = length = 0
  412. data = b''
  413. memType = {
  414. "E" : MemoryArea.TYPE_E,
  415. "A" : MemoryArea.TYPE_A,
  416. "M" : MemoryArea.TYPE_M,
  417. "L" : MemoryArea.TYPE_L,
  418. "DB" : MemoryArea.TYPE_DB,
  419. "T" : MemoryArea.TYPE_T,
  420. "Z" : MemoryArea.TYPE_Z,
  421. "STW" : MemoryArea.TYPE_STW,
  422. }[memAreaStr[0].upper().strip()]
  423. if memType in { MemoryArea.TYPE_E,
  424. MemoryArea.TYPE_A,
  425. MemoryArea.TYPE_M,
  426. MemoryArea.TYPE_L, }:
  427. start = int(memAreaStr[1])
  428. length = int(memAreaStr[2])
  429. if (not (0 <= start <= 0xFFFF) or
  430. length not in (8, 16, 32)):
  431. raise ValueError
  432. if withData:
  433. data = dataToBytes(int(memAreaStr[3]), length)
  434. elif memType == MemoryArea.TYPE_DB:
  435. index = int(memAreaStr[1])
  436. start = int(memAreaStr[2])
  437. length = int(memAreaStr[3])
  438. if (not (0 <= start <= 0xFFFF) or
  439. not (0 <= index <= 0xFFFF) or
  440. length not in (8, 16, 32)):
  441. raise ValueError
  442. if withData:
  443. data = dataToBytes(int(memAreaStr[4]), length)
  444. elif memType in { MemoryArea.TYPE_T,
  445. MemoryArea.TYPE_Z, }:
  446. index = int(memAreaStr[1])
  447. length = 16
  448. if not (0 <= index <= 0xFFFF):
  449. raise ValueError
  450. if withData:
  451. data = dataToBytes(int(memAreaStr[2]), 16)
  452. elif memType == MemoryArea.TYPE_STW:
  453. length = 16
  454. if withData:
  455. data = dataToBytes(int(memAreaStr[1]), 16)
  456. else:
  457. assert(0)
  458. return MemoryArea(memType=memType,
  459. flags=0,
  460. index=index,
  461. start=start,
  462. length=length // 8,
  463. data=data)
  464. except (ValueError, IndexError, KeyError, AwlSimError) as e:
  465. pass
  466. return None
  467. def main():
  468. global opt_cycletime
  469. global opt_maxRuntime
  470. global opt_noCpuDump
  471. global opt_nrAccus
  472. global opt_extInsns
  473. global opt_obtemp
  474. global opt_clockMem
  475. global opt_mnemonics
  476. global opt_optimizers
  477. global opt_insnMeas
  478. global opt_hwmods
  479. global opt_hwinfos
  480. global opt_loglevel
  481. global opt_connect
  482. global opt_connectTo
  483. global opt_spawnBackend
  484. global opt_interpreter
  485. global opt_memReads
  486. global opt_memWrites
  487. opt_cycletime = None
  488. opt_maxRuntime = None
  489. opt_noCpuDump = False
  490. opt_nrAccus = None
  491. opt_extInsns = None
  492. opt_obtemp = None
  493. opt_clockMem = None
  494. opt_mnemonics = None
  495. opt_optimizers = "default"
  496. opt_insnMeas = None
  497. opt_hwmods = []
  498. opt_hwinfos = []
  499. opt_loglevel = Logging.LOG_INFO
  500. opt_connect = None
  501. opt_connectTo = False
  502. opt_spawnBackend = False
  503. opt_interpreter = None
  504. opt_memReads = []
  505. opt_memWrites = []
  506. try:
  507. (opts, args) = getopt.getopt(sys.argv[1:],
  508. "hY:M:24qDxt:T:m:O:H:I:P:L:cC:bi:R:W:",
  509. [ "help", "cycle-limit=", "max-runtime=", "twoaccu", "fouraccu",
  510. "quiet", "no-cpu-dump", "extended-insns",
  511. "obtemp=", "clock-mem=", "mnemonics=", "optimizers=",
  512. "hardware=", "hardware-info=", "profile=",
  513. "loglevel=",
  514. "connect", "connect-to=", "spawn-backend", "interpreter=",
  515. "mem-read=", "mem-write=",
  516. "insn-meas=", ])
  517. except getopt.GetoptError as e:
  518. printError(str(e))
  519. usage()
  520. return ExitCodes.EXIT_ERR_CMDLINE
  521. for (o, v) in opts:
  522. if o in ("-h", "--help"):
  523. usage()
  524. return ExitCodes.EXIT_OK
  525. if o in ("-Y", "--cycle-limit"):
  526. try:
  527. opt_cycletime = float(v)
  528. except ValueError:
  529. printError("-Y|--cycle-limit: Invalid time format")
  530. sys.exit(1)
  531. if o in ("-M", "--max-runtime"):
  532. try:
  533. opt_maxRuntime = float(v)
  534. except ValueError:
  535. printError("-M|--max-runtime: Invalid time format")
  536. sys.exit(1)
  537. if o in ("-2", "--twoaccu"):
  538. opt_nrAccus = 2
  539. if o in ("-4", "--fouraccu"):
  540. opt_nrAccus = 4
  541. if o in ("-D", "--no-cpu-dump"):
  542. opt_noCpuDump = True
  543. if o in ("-x", "--extended-insns"):
  544. opt_extInsns = True
  545. if o in ("-t", "--obtemp"):
  546. opt_obtemp = str2bool(v)
  547. if o in ("-T", "--clock-mem"):
  548. try:
  549. opt_clockMem = int(v)
  550. if opt_clockMem < -1 or opt_clockMem > 0xFFFF:
  551. raise ValueError
  552. except ValueError:
  553. printError("-T|--clock-mem: Invalid byte address")
  554. sys.exit(1)
  555. if o in ("-m", "--mnemonics"):
  556. opt_mnemonics = v.lower()
  557. if opt_mnemonics not in ("en", "de", "auto"):
  558. printError("-m|--mnemonics: Invalid mnemonics type")
  559. sys.exit(1)
  560. if o in ("-O", "--optimizers"):
  561. try:
  562. modes = v.split(",")
  563. for mode in modes:
  564. mode = mode.lower()
  565. if mode in ("off", "all", "default"):
  566. opt_optimizers = mode
  567. else:
  568. printError("-O|--optimizers: Unknown optimizer: %s" % mode)
  569. sys.exit(1)
  570. except (ValueError, IndexError) as e:
  571. printError("-O|--optimizers: Invalid optimization mode")
  572. sys.exit(1)
  573. if o == "--insn-meas":
  574. opt_insnMeas = v
  575. if o in ("-H", "--hardware"):
  576. try:
  577. v = v.split(':')
  578. if not v:
  579. raise ValueError
  580. name = v[0]
  581. params = {}
  582. for pstr in v[1:]:
  583. if not pstr:
  584. continue
  585. i = pstr.find('=')
  586. if i < 0:
  587. raise ValueError
  588. pname = pstr[:i]
  589. pval = pstr[i+1:]
  590. if not pname or not pval:
  591. raise ValueError
  592. params[pname] = pval
  593. opt_hwmods.append( (name, params) )
  594. except (ValueError, IndexError) as e:
  595. printError("-H|--hardware: Invalid module name or parameters")
  596. sys.exit(1)
  597. if o in ("-I", "--hardware-info"):
  598. opt_hwinfos.append(v.split(':')[0])
  599. if o in ("-L", "--loglevel"):
  600. try:
  601. opt_loglevel = int(v)
  602. except ValueError:
  603. printError("-L|--loglevel: Invalid log level")
  604. sys.exit(1)
  605. if o in ("-c", "--connect"):
  606. opt_connect = True
  607. if o in ("-C", "--connect-to"):
  608. try:
  609. idx = v.rfind(":")
  610. if idx <= 0:
  611. raise ValueError
  612. opt_connectTo = (v[:idx], int(v[idx+1:]))
  613. except ValueError:
  614. printError("-c|--connect: Invalid host/port")
  615. sys.exit(1)
  616. if o in ("-b", "--spawn-backend"):
  617. opt_spawnBackend = True
  618. if o in ("-i", "--interpreter"):
  619. if isWinStandalone:
  620. printError("-i|--interpreter not supported on win-standalone")
  621. sys.exit(1)
  622. opt_interpreter = v
  623. if o in ("-R", "--mem-read"):
  624. memArea = parseMemoryArea(v, withData=False)
  625. if not memArea:
  626. printError("-R|--mem-read invalid arguments.")
  627. sys.exit(1)
  628. opt_memReads.append(memArea)
  629. if o in ("-W", "--mem-write"):
  630. memArea = parseMemoryArea(v, withData=True)
  631. if not memArea:
  632. printError("-W|--mem-write invalid arguments.")
  633. sys.exit(1)
  634. opt_memWrites.append(memArea)
  635. if len(args) != 1 and not opt_hwinfos:
  636. usage()
  637. return ExitCodes.EXIT_ERR_CMDLINE
  638. if args:
  639. inputFile = args[0]
  640. Logging.setLoglevel(opt_loglevel)
  641. opt_mnemonics = {
  642. None : None,
  643. "en" : S7CPUConfig.MNEMONICS_EN,
  644. "de" : S7CPUConfig.MNEMONICS_DE,
  645. "auto" : S7CPUConfig.MNEMONICS_AUTO,
  646. }[opt_mnemonics]
  647. try:
  648. if opt_hwinfos:
  649. # Just print the hardware-infos and exit.
  650. for name in opt_hwinfos:
  651. cls = AwlSim.loadHardwareModule(name)
  652. print(cls.getModuleInfo())
  653. return ExitCodes.EXIT_OK
  654. except (AwlParserError, AwlSimError) as e:
  655. printError(e.getReport())
  656. return ExitCodes.EXIT_ERR_SIM
  657. signal.signal(signal.SIGTERM, __signalHandler)
  658. if opt_interpreter and not opt_spawnBackend:
  659. printError("Selected an --interpreter, but no "
  660. "--spawn-backend was requested.")
  661. return ExitCodes.EXIT_ERR_CMDLINE
  662. if opt_spawnBackend or opt_connect or opt_connectTo:
  663. return runWithServerBackend(inputFile)
  664. return run(inputFile)
  665. if __name__ == "__main__":
  666. sys.exit(main())