1 //
2 // Copyright (c) 2010-2023 Antmicro
3 // Copyright (c) 2011-2015 Realtime Embedded
4 //
5 // This file is licensed under the MIT License.
6 // Full license text is available in 'licenses/MIT.txt'.
7 //
8 using System;
9 using Antmicro.Renode.Core;
10 using Antmicro.Renode.Logging;
11 using Antmicro.Renode.Peripherals.CPU;
12 using Antmicro.Renode.Exceptions;
13 using Microsoft.Scripting.Hosting;
14 using Antmicro.Migrant.Hooks;
15 using Antmicro.Migrant;
16 
17 namespace Antmicro.Renode.Hooks
18 {
19     public sealed class BlockPythonEngine : PythonEngine
20     {
BlockPythonEngine(IMachine mach, ICPUWithHooks cpu, string script)21         public BlockPythonEngine(IMachine mach, ICPUWithHooks cpu, string script)
22         {
23             Script = script;
24             CPU = cpu;
25             Machine = mach;
26 
27             InnerInit();
28 
29             Hook = (_, pc) =>
30             {
31                 Scope.SetVariable("pc", pc);
32                 Execute(code, error =>
33                 {
34                     CPU.Log(LogLevel.Error, "Python runtime error: {0}", error);
35                 });
36             };
37 
38             HookWithSize = (pc, size) =>
39             {
40                 Scope.SetVariable("pc", pc);
41                 Scope.SetVariable("size", size);
42                 Execute(code, error =>
43                 {
44                     CPU.Log(LogLevel.Error, "Python runtime error: {0}", error);
45                 });
46             };
47         }
48 
49         [PostDeserialization]
InnerInit()50         private void InnerInit()
51         {
52             Scope.SetVariable(Core.Machine.MachineKeyword, Machine);
53             Scope.SetVariable("cpu", CPU);
54             Scope.SetVariable("self", CPU);
55             var source = Engine.CreateScriptSourceFromString(Script);
56             code = Compile(source);
57         }
58 
59         public Action<ICpuSupportingGdb, ulong> Hook { get; private set; }
60 
61         public Action<ulong, uint> HookWithSize { get; private set; }
62 
63         [Transient]
64         private CompiledCode code;
65 
66         private readonly string Script;
67         private readonly ICPUWithHooks CPU;
68         private readonly IMachine Machine;
69     }
70 }
71