1 //
2 // Copyright (c) 2010-2022 Antmicro
3 //
4 //  This file is licensed under the MIT License.
5 //  Full license text is available in 'licenses/MIT.txt'.
6 //
7 using System;
8 using Antmicro.Migrant;
9 using Antmicro.Migrant.Hooks;
10 using Antmicro.Renode.Core;
11 using Antmicro.Renode.Logging;
12 using Antmicro.Renode.Peripherals.CPU;
13 using Antmicro.Renode.Exceptions;
14 using Microsoft.Scripting.Hosting;
15 
16 namespace Antmicro.Renode.Hooks
17 {
18     public class InterruptPythonEngine : PythonEngine
19     {
InterruptPythonEngine(IMachine machine, ICPUWithHooks cpu, string script)20         public InterruptPythonEngine(IMachine machine, ICPUWithHooks cpu, string script)
21         {
22             this.script = script;
23             this.machine = machine;
24             this.cpu = cpu;
25 
26             InnerInit();
27 
28             HookWithExceptionIndex = exceptionIndex =>
29             {
30                 Scope.SetVariable("exceptionIndex", exceptionIndex);
31                 Execute(code, error =>
32                 {
33                     this.cpu.Log(LogLevel.Error, "Python runtime error: {0}", error);
34                     throw new CpuAbortException($"Python runtime error: {error}");
35                 });
36             };
37         }
38 
39         [PostDeserialization]
InnerInit()40         private void InnerInit()
41         {
42             Scope.SetVariable(Machine.MachineKeyword, machine);
43             Scope.SetVariable("self", cpu);
44             var source = Engine.CreateScriptSourceFromString(script);
45             code = Compile(source);
46         }
47 
48         public Action<ulong> HookWithExceptionIndex { get; private set; }
49 
50         [Transient]
51         private CompiledCode code;
52         private readonly string script;
53         private readonly ICPUWithHooks cpu;
54         private readonly IMachine machine;
55     }
56 }
57