public SimpleSimulator() { Memory = new Memory(); Registers = new Registers(); Machine = new Machine(Memory, Registers); Assembler = new Assembler(); }
private static int Main(string[] args) { try { if (args.Length != 1) throw new Ufer(AppDomain.CurrentDomain.FriendlyName + " <xxx.asm>"); var fpatIn = args[0]; if (!fpatIn.EndsWith(".asm", StringComparison.InvariantCultureIgnoreCase)) throw new Ufer("Not an asm file"); var src = File.ReadAllText(fpatIn); var fpatOut = fpatIn.Substring(0, fpatIn.Length - 4) + ".hack"; var assembler = new Assembler(); File.WriteAllLines(fpatOut, assembler.Assemble(src)); return 0; } catch (Exception er) { Console.WriteLine(er.UstMessage()); return 1; } }
IEnumerator Start() { assember = Assembler.GetInstance(); assember.OnFinishLoading += HandleOnFinishLoading; yield return new WaitForSeconds(3); string avatar = "zs"; //AssemblerInfo info1 = new AssemblerInfo(0, avatar, avatar + "_head_0000", avatar + "_body_0000", "", "weapon0001", "", "wing", "zs_wing_0001"); //AssemblerInfo info1 = new AssemblerInfo(0, avatar, avatar + "_head_0000", avatar + "_body_0000", "", "", "", "", ""); //AssemblerInfo info2 = new AssemblerInfo(1, avatar, avatar + "_head_0001", avatar + "_body_0001", "", "weapon0001", "", "wing", "zs_wing_0001"); //_id = assember.Create(info1, this); // assember.Create(info2); for(int i = 0; i < 20; ++i) { AssemblerInfo info1 = new AssemblerInfo(0, avatar, avatar + "_head_0000", avatar + "_body_0000", "", "", "", "", ""); assember.Create(info1, this); yield return Random.Range(0, 30); } }
public override void AssembleNew(Assembler.Assembler aAssembler, object aMethodInfo) { // $this ebp+8 new Mov { DestinationReg = Registers.EAX, SourceReg = Registers.EBP, SourceIsIndirect = true, SourceDisplacement = 8 }; new Mov { DestinationReg = Registers.EAX, SourceReg = Registers.EAX, SourceIsIndirect = true }; new Push { DestinationIsIndirect = true, DestinationReg = Registers.EAX, DestinationDisplacement = 8 }; }
public void SetUp() { var arch = new IntelArchitecture(ProcessorMode.Real); prog = new Program() { Architecture = arch }; asm = new X86TextAssembler(arch); configFile = null; }
private void assemble() { txtErrorsAndWarnings.Text = string.Empty; var assembler = new Assembler(); var lines = txtInput.Text.Split('\n'); try { var gekkoAssembly = assembler.AssembleAllLines(lines); ICodeWriter writer; if (cmbType.SelectedItem.ToString() == "Gecko") { writer = new GeckoWriter(); } else if (cmbType.SelectedItem.ToString() == "Action Replay") { writer = new ActionReplayWriter(); } else { writer = new ByteCodeWriter(); } var code = writer.WriteCode(gekkoAssembly); txtOutput.Text = string.Join(Environment.NewLine, code.Lines); txtErrorsAndWarnings.Text = string.Join(Environment.NewLine, code.Errors.Select(x => $"Error: {x}").Concat(code.Warnings.Select(x => $"Warning: {x}"))); } catch (Exception ex) { txtErrorsAndWarnings.Text = $"Error: {ex.Message}"; } }
public static Assembler.Assembler Optimize(Assembler.Assembler asmb) { return asmb; //Assembler asmblr = asmb; //List<Instruction> instr = asmb.Instructions; ////List<DataMember> dmbrs = asmb.DataMembers; //SortedDictionary<string, Instruction> labels = new SortedDictionary<string, Instruction>(); //List<Instruction> comments = new List<Instruction>(); //List<String> usedLabels = new List<string>(); //usedLabels.Add("KernelStart"); //foreach (Instruction ins in instr) { // if (ins is Label) { // if (((Label)ins).IsGlobal) { // usedLabels.Add(((Label)ins).QualifiedName); // } // labels.Add(((Label)ins).QualifiedName, ins); // } else if (ins is x86.JumpToSegment) { // if (((x86.JumpToSegment)ins).DestinationRef != null) { // usedLabels.Add(((x86.JumpToSegment)ins).DestinationRef.Name); // } else { // usedLabels.Add(((x86.JumpToSegment)ins).DestinationLabel); // } // } else if (ins is x86.JumpBase) { // usedLabels.Add(((x86.JumpBase)ins).DestinationLabel); // } else if (ins is x86.Call) { // usedLabels.Add(((x86.Call)ins).DestinationLabel); // } else if (ins is x86.Push) { // if (((x86.Push)ins).DestinationRef != null) { // usedLabels.Add(((x86.Push)ins).DestinationRef.Name); // } // } else if (ins is x86.Mov) { // if (((x86.Mov)ins).SourceRef != null) { // usedLabels.Add(((x86.Mov)ins).SourceRef.Name); // } // } //} //foreach (string s in usedLabels) { // labels.Remove(s); //} //usedLabels = null; //instr.RemoveAll( // delegate(Instruction inst) { // if (inst is Comment) // return true; // else if (inst is Label) { // if (labels.ContainsKey(((Label)inst).QualifiedName)) // return true; // return false; // } // return false; // } //); //labels = null; //comments = null; //asmblr.Instructions = instr; ////asmblr.DataMembers = dmbrs; //return asmblr; }
public override void AssembleNew(Assembler.Assembler aAssembler, object aMethodInfo) { // $this ebp+8 XS.Set(XSRegisters.EAX, XSRegisters.EBP, sourceDisplacement: 8); XS.Set(XSRegisters.EAX, XSRegisters.EAX, sourceDisplacement: 8, sourceIsIndirect: true); // element count XS.Push(XSRegisters.EAX); }
public static void Assembler(string fpatAsm, string fpatHack) { var stAsm = U.StFromResource(typeof (Tests), fpatAsm); var stHackExpected = U.StFromResource(typeof (Tests), fpatHack); var stHackOut = new Assembler().Assemble(stAsm).StJoin("\r\n") + "\r\n"; Console.WriteLine(stHackOut); Assert.AreEqual(stHackExpected, stHackOut); }
public void SetUp() { var arch = new X86ArchitectureReal(); program = new Program() { Architecture = arch }; sc = new ServiceContainer(); sc.AddService<IFileSystemService>(new FileSystemServiceImpl()); asm = new X86TextAssembler(sc, arch); configFile = null; }
public static Assembler GetInstance() { if (s_Instance == null) { GameObject go = GameObject.Find("__Assembler"); if (go != null)s_Instance = go.GetComponent<Assembler>(); } return s_Instance; }
public Repl(ProgrammingModel model, Memory memory) { registry = new InstructionRegistry(); this.model = model; this.memory = memory; assembler = new Assembler(registry.All); fetcher = new Fetcher(model, memory); decoder = new Decoder(registry.All); executor = new Executor(registry.All, model, memory); coreLoop = new CoreLoop(fetcher, decoder, executor); }
public override void WriteText(Assembler aAssembler, TextWriter aOutput) { if (DestinationValue == 0) { aOutput.WriteLine("Ret"); } else { aOutput.WriteLine("Ret 0x" + DestinationValue.ToString("X")); } }
public static void saveRegisters(int threadNum, int tBase, ref int[] register, ref Assembler asm) { const int THREAD_MEM_SIZE = 1000; int stackPointer = tBase - 4;//Make room to store something if (threadNum != 0) stackPointer = tBase - (THREAD_MEM_SIZE * threadNum); //Iterate through registers for (int i = 0; i < register.Length; i++) { asm.storeData(register[i], stackPointer); stackPointer -= 4; } }
public static void loadRegisters(int threadNum, int tBase, ref int[] register, ref Assembler asm) { const int THREAD_MEM_SIZE = 1000; int stackPointer = tBase - 4; if (threadNum != 0) stackPointer = tBase - (THREAD_MEM_SIZE * threadNum); //Iterate through registers for (int i = 0; i < register.Length; i++) { register[i] = asm.getData(stackPointer); stackPointer -= 4; } }
/*public static void BlockCopy( * Array src, [ebp + 24] * int srcOffset, [ebp + 20] * Array dst, [ebp + 16] * int dstOffset, [ebp + 12] * int count); [ebp + 8] */ public override void AssembleNew(Assembler.Assembler aAssembler, object aMethodInfo) { new CPUx86.Mov { DestinationReg = CPUx86.Registers.ESI, SourceReg = CPUx86.Registers.EBP, SourceIsIndirect = true, SourceDisplacement = 24 }; new CPUx86.Add { DestinationReg = CPUx86.Registers.ESI, SourceValue = 16 }; new CPUx86.Mov { DestinationReg = CPUx86.Registers.EAX, SourceReg = CPUx86.Registers.EBP, SourceIsIndirect = true, SourceDisplacement = 20 }; new CPUx86.Add { DestinationReg = CPUx86.Registers.ESI, SourceReg = CPUx86.Registers.EAX }; new CPUx86.Mov { DestinationReg = CPUx86.Registers.EDI, SourceReg = CPUx86.Registers.EBP, SourceIsIndirect = true, SourceDisplacement = 16 }; new CPUx86.Add { DestinationReg = CPUx86.Registers.EDI, SourceValue = 16 }; new CPUx86.Mov { DestinationReg = CPUx86.Registers.EAX, SourceReg = CPUx86.Registers.EBP, SourceIsIndirect = true, SourceDisplacement = 12 }; new CPUx86.Add { DestinationReg = CPUx86.Registers.EDI, SourceReg = CPUx86.Registers.EAX }; new CPUx86.Mov { DestinationReg = CPUx86.Registers.ECX, SourceReg = CPUx86.Registers.EBP, SourceIsIndirect = true, SourceDisplacement = 8 }; new CPUx86.Movs { Size = 8, Prefixes = CPUx86.InstructionPrefixes.Repeat }; }
public override void AssembleNew(Assembler.Assembler aAssembler, object aMethodInfo) { XS.ClearDirectionFlag(); XS.Set(XSRegisters.EDI, XSRegisters.EBP, sourceDisplacement: 0xC); //address XS.Set(XSRegisters.ECX, XSRegisters.EBP, sourceDisplacement: 0x8); //length // set EAX to value of fill (zero) XS.Xor(XSRegisters.EAX, XSRegisters.EAX); XS.ShiftRight(XSRegisters.ECX, 1); XS.Jump(Assembler.x86.ConditionalTestEnum.NotBelow, ".step2"); XS.StoreByteInString(); XS.Label(".step2"); XS.ShiftRight(XSRegisters.ECX, 1); XS.Jump(Assembler.x86.ConditionalTestEnum.NotBelow, ".step3"); XS.StoreWordInString(); XS.Label(".step3"); new Assembler.x86.Stos {Size = 32, Prefixes = Assembler.x86.InstructionPrefixes.Repeat}; }
private void Test(string input, string output, string message) { var inputLines = input.Replace("\r", "").Split('\n'); var outputLines = output.Replace("\r", "").Split('\n'); var assembler = new Assembler(); var gekkoAssembly = assembler.AssembleAllLines(inputLines); var writer = new ActionReplayWriter(); var code = writer.WriteCode(gekkoAssembly); var actualLines = code.Lines; for (var i = 0; i < Math.Min(outputLines.Length, actualLines.Count); ++i) { Assert.AreEqual(outputLines[i], actualLines[i], $"Line {i + 1}: {message}"); } }
private static void RunProgram(string assemblyCode) { Assembler assembler = new Assembler(); Instruction[] instructions = assembler.Assemble(assemblyCode); Memory memory = new Memory(); memory.LoadInstructions(instructions); Registers registers = new Registers(); registers.ValueWrittenToOutputRegister += System.Console.Write; Machine machine = new Machine(memory, registers); machine.Run(25); System.Console.ReadLine(); }
public static unsafe void Main() { int prot = 0x1 | 0x2 | 0x4; //PROT_READ | PROT_WRITE | PROT_EXEC int flags = 0x1000 | 0x0002; //MAP_ANON | MAP_PRIVATE var res = mmap (IntPtr.Zero, (IntPtr)4096, prot , flags, 0); var mem = new UnmanagedMemoryStream ((byte*)res, 4096, 4096, FileAccess.ReadWrite); var asm = new Assembler (mem); asm.Push (EBP); asm.Mov (EBP, ESP); asm.Mov (EAX, 10); asm.Leave (); asm.Ret (); NoArgsReturnInt dele = (NoArgsReturnInt)Marshal.GetDelegateForFunctionPointer (res, typeof (NoArgsReturnInt)); Console.WriteLine (dele ()); }
private IntPtr CreateMethodStub(MethodCompiler methodCompiler) { if (methodCompiler == null) throw new ArgumentNullException("methodCompiler"); _unmanagedDelegates.Add(methodCompiler); IntPtr methodPtr = Marshal.GetFunctionPointerForDelegate(methodCompiler); Assembler assembler = new Assembler(); Label label = assembler.DefineLabel(); assembler.Call(label); assembler.MarkLabel(label); assembler.Sub(Mem.sysint_ptr(Register.nsp), 5); assembler.Call(methodPtr); assembler.Add(Register.nsp, IntPtr.Size); assembler.Jmp(Register.nax); return assembler.Make(); }
public IoTransport(String host, int port, ConnectionDelegate conndel) { CreateSocket(host, port); Sender = new IoSender(this, QUEUE_SIZE, TIMEOUT); Receiver = new IoReceiver(Stream, Socket.ReceiveBufferSize * 2, TIMEOUT); Assembler assembler = new Assembler(); InputHandler inputHandler = new InputHandler(InputHandler.State.PROTO_HDR); Connection = new Connection(assembler, new Disassembler(Sender, 64 * 1024 - 1), conndel); // Input handler listen to Receiver events Receiver.Received += inputHandler.On_ReceivedBuffer; // Assembler listen to inputhandler events inputHandler.ReceivedEvent += assembler.On_ReceivedEvent; // Connection listen to asembler protocol event Receiver.Closed += Connection.On_ReceivedClosed; assembler.Closed += Connection.On_ReceivedClosed; Receiver.Exception += Connection.On_ReceivedException; inputHandler.ExceptionProcessing += Connection.On_ReceivedException; assembler.ReceivedEvent += Connection.On_ReceivedEvent; }
public bool Assemble(string file, Assembler asm, DecompilerHost host) { var ldr = Services.RequireService<ILoader>(); this.Decompiler = CreateDecompiler(ldr, host); var svc = Services.RequireService<IWorkerDialogService>(); svc.StartBackgroundWork("Loading program", delegate() { Decompiler.Assemble(file, asm); }); if (Decompiler.Project == null) return false; var browserSvc = Services.RequireService<IProjectBrowserService>(); browserSvc.Load(Decompiler.Project); if (Decompiler.Project.Programs.Count > 0) { var memSvc = Services.RequireService<ILowLevelViewService>(); memSvc.ViewImage(Decompiler.Project.Programs.First()); } return false; }
/*public static void BlockCopy( * Array src, [ebp + 24] * int srcOffset, [ebp + 20] * Array dst, [ebp + 16] * int dstOffset, [ebp + 12] * int count); [ebp + 8] */ public override void AssembleNew(Assembler.Assembler aAssembler, object aMethodInfo) { XS.Comment("Source array"); XS.Set(XSRegisters.ESI, XSRegisters.EBP, sourceDisplacement: SourceArrayDisplacement); XS.Add(XSRegisters.ESI, ObjectInfo.FieldDataOffset + 4); XS.Comment("Source index"); XS.Set(XSRegisters.EAX, XSRegisters.EBP, sourceDisplacement: SourceIndexDisplacement); XS.Add(XSRegisters.ESI, XSRegisters.EAX); XS.Comment("Destination array"); XS.Set(XSRegisters.EDI, XSRegisters.EBP, sourceDisplacement: DestinationArrayDisplacement); XS.Add(XSRegisters.EDI, ObjectInfo.FieldDataOffset + 4); XS.Comment("Destination index"); XS.Set(XSRegisters.EAX, XSRegisters.EBP, sourceDisplacement: DestinationIndexDisplacement); XS.Add(XSRegisters.EDI, XSRegisters.EAX); XS.Comment("Count"); XS.Set(XSRegisters.ECX, XSRegisters.EBP, sourceDisplacement: CountDisplacement); new CPUx86.Movs { Size = 8, Prefixes = CPUx86.InstructionPrefixes.Repeat }; }
private static IntPtr CreateCompilerLaunchPad() { Console.Error.WriteLine("Creating the compiler launch pad:"); Console.Error.WriteLine(); MethodCompiler methodCompiler = CreateMethod; _unmanagedDelegates.Add(methodCompiler); IntPtr methodPtr = Marshal.GetFunctionPointerForDelegate(methodCompiler); Assembler assembler = new Assembler(); assembler.Logger = new FileLogger(Console.Error); assembler.Push(Register.nbp); assembler.Mov(Register.nbp, Register.nsp); if (IntPtr.Size == 4) { assembler.Push(Mem.dword_ptr(Register.nbp, 4)); assembler.Sub(Mem.dword_ptr(Register.nsp), 5); } else { assembler.Push(Register.ncx); assembler.Mov(Register.ncx, Mem.qword_ptr(Register.nbp, 8)); assembler.Sub(Register.ncx, 5); } assembler.Call(methodPtr); if (IntPtr.Size == 4) { assembler.Add(Register.nsp, 4); } else { assembler.Pop(Register.ncx); } assembler.Pop(Register.nbp); assembler.Ret(); return assembler.Make(); }
public override void Generate(out IntPtr destination, Assembler assembler) { if (assembler == null) throw new ArgumentNullException("assembler"); Contract.EndContractBlock(); // Disallow empty code generation. long codeSize = assembler.CodeSize; if (codeSize == 0) { destination = IntPtr.Zero; throw new AssemblerException("The assembler has no code to generate."); } // Switch to global memory manager if not provided. MemoryManager memmgr = MemoryManager ?? MemoryManager.Global; IntPtr p = memmgr.Alloc(codeSize, AllocType); if (p == IntPtr.Zero) { destination = IntPtr.Zero; throw new JitException("Out of virtual memory."); } // Relocate the code. IntPtr relocatedSize = assembler.RelocCode(p); // Return unused memory to memory manager. if (relocatedSize.ToInt64() < codeSize) { memmgr.Shrink(p, relocatedSize); } // Mark memory if (_memoryMarker != null) _memoryMarker.Mark(p, relocatedSize); // Return the code. destination = p; }
/* void Copy( * Array sourceArray, ebp + 36 * int sourceIndex, ebp + 28 * Array destinationArray, ebp + 24 * int destinationIndex, ebp + 16 * int length, ebp + 12 * bool reliable); ebp + 8 */ public override void AssembleNew(Assembler.Assembler aAssembler, object aMethodInfo) { XS.Comment("Source"); XS.Comment("Element size"); XS.Set(EAX, EBP, sourceDisplacement: SourceArrayDisplacement); XS.Add(EAX, ObjectInfo.FieldDataOffset); XS.Set(EAX, EAX, sourceIsIndirect: true); // element size XS.Comment("Source ptr"); XS.Set(EBX, EBP, sourceDisplacement: SourceIndexDisplacement); XS.Multiply(EBX); XS.Add(EAX, ObjectInfo.FieldDataOffset + 4); // first element XS.Set(ESI, EBP, sourceDisplacement: SourceArrayDisplacement); XS.Add(ESI, EAX); // source ptr XS.Comment("Destination"); XS.Comment("Element size"); XS.Set(EAX, EBP, sourceDisplacement: DestinationArrayDisplacement); XS.Add(EAX, ObjectInfo.FieldDataOffset); XS.Set(EAX, EAX, sourceIsIndirect: true); // element size XS.Comment("Destination ptr"); XS.Set(ECX, EBP, sourceDisplacement: DestinationIndexDisplacement); XS.Multiply(ECX); XS.Add(EAX, ObjectInfo.FieldDataOffset + 4); // first element XS.Set(EDI, EBP, sourceDisplacement: DestinationArrayDisplacement); XS.Add(EDI, EAX); // destination ptr XS.Comment("Copy byte count"); XS.Comment("Element size"); XS.Set(EAX, EBP, sourceDisplacement: DestinationArrayDisplacement); XS.Add(EAX, ObjectInfo.FieldDataOffset); XS.Set(EAX, EAX, sourceIsIndirect: true); // element size XS.Comment("Count"); XS.Set(EDX, EBP, sourceDisplacement: LengthDisplacement); XS.Multiply(EDX); XS.Set(ECX, EAX); new CPUx86.Movs { Size = 8, Prefixes = CPUx86.InstructionPrefixes.Repeat }; }
/* void Copy(Array sourceArray, ebp + 0x1C * int sourceIndex, ebp + 0x18 * Array destinationArray, ebp + 0x14 * int destinationIndex, ebp + 0x10 * int length, ebp + 0xC * bool reliable); ebp + 0x8 */ public override void AssembleNew(Assembler.Assembler aAssembler, object aMethodInfo) { new CPUx86.Mov { DestinationReg = CPUx86.Registers.EAX, SourceReg = CPUx86.Registers.EBP, SourceIsIndirect = true, SourceDisplacement = SourceArrayDisplacement }; new CPUx86.Mov { DestinationReg = CPUx86.Registers.EAX, SourceReg = CPUx86.Registers.EAX, SourceIsIndirect = true }; // dereference memory handle to pointer new CPUx86.Push { DestinationReg = CPUx86.Registers.EAX }; new CPUx86.Add { DestinationReg = CPUx86.Registers.ESP, DestinationIsIndirect = true, SourceValue = 12, Size = 32 }; // pointer is at the element size new CPUx86.Pop { DestinationReg = CPUx86.Registers.EAX }; new CPUx86.Mov { DestinationReg = CPUx86.Registers.EAX, SourceReg = CPUx86.Registers.EAX, SourceIsIndirect = true }; // element size new CPUx86.Mov { DestinationReg = CPUx86.Registers.EBX, SourceReg = CPUx86.Registers.EBP, SourceIsIndirect = true, SourceDisplacement = SourceIndexDisplacement }; new CPUx86.Multiply { DestinationReg = CPUx86.Registers.EBX }; new CPUx86.Add { DestinationReg = CPUx86.Registers.EAX, SourceValue = 16 }; new CPUx86.Mov { DestinationReg = CPUx86.Registers.ESI, SourceReg = CPUx86.Registers.EBP, SourceIsIndirect = true, SourceDisplacement = SourceArrayDisplacement }; new CPUx86.Mov { DestinationReg = CPUx86.Registers.ESI, SourceReg = CPUx86.Registers.ESI, SourceIsIndirect = true }; // dereference memory handle to pointer new CPUx86.Add { DestinationReg = CPUx86.Registers.ESI, SourceReg = CPUx86.Registers.EAX }; // source ptr new CPUx86.Mov { DestinationReg = CPUx86.Registers.EDX, SourceReg = CPUx86.Registers.EBP, SourceIsIndirect = true, SourceDisplacement = DestinationArrayDisplacement }; new CPUx86.Mov { DestinationReg = CPUx86.Registers.EDX, SourceReg = CPUx86.Registers.EDX, SourceIsIndirect = true }; // dereference memory handle to pointer new CPUx86.Push { DestinationReg = CPUx86.Registers.EDX }; new CPUx86.Add { DestinationReg = CPUx86.Registers.ESP, DestinationIsIndirect = true, SourceValue = 12, Size = 32 }; // pointer is at element size new CPUx86.Pop { DestinationReg = CPUx86.Registers.EAX }; new CPUx86.Mov { DestinationReg = CPUx86.Registers.EAX, SourceReg = CPUx86.Registers.EAX, SourceIsIndirect = true }; // dereference handle to pointer new CPUx86.Mov { DestinationReg = CPUx86.Registers.ECX, SourceReg = CPUx86.Registers.EBP, SourceIsIndirect = true, SourceDisplacement = DestinationIndexDisplacement }; new CPUx86.Multiply { DestinationReg = CPUx86.Registers.ECX }; new CPUx86.Add { DestinationReg = CPUx86.Registers.EAX, SourceValue = 16 }; new CPUx86.Mov { DestinationReg = CPUx86.Registers.EDI, SourceReg = CPUx86.Registers.EBP, SourceIsIndirect = true, SourceDisplacement = DestinationArrayDisplacement }; new CPUx86.Mov { DestinationReg = CPUx86.Registers.EDI, SourceReg = CPUx86.Registers.EDI, SourceIsIndirect = true }; // dereference handle to pointer new CPUx86.Add { DestinationReg = CPUx86.Registers.EDI, SourceReg = CPUx86.Registers.EAX }; // calculate byte count to copy new CPUx86.Mov { DestinationReg = CPUx86.Registers.EAX, SourceReg = CPUx86.Registers.EBP, SourceIsIndirect = true, SourceDisplacement = DestinationArrayDisplacement }; new CPUx86.Mov { DestinationReg = CPUx86.Registers.EAX, SourceReg = CPUx86.Registers.EAX, SourceIsIndirect = true }; // dereference memory handle to pointer new CPUx86.Add { DestinationReg = CPUx86.Registers.EAX, SourceValue = 12 }; new CPUx86.Mov { DestinationReg = CPUx86.Registers.EAX, SourceReg = CPUx86.Registers.EAX, SourceIsIndirect = true }; new CPUx86.Mov { DestinationReg = CPUx86.Registers.EDX, SourceReg = CPUx86.Registers.EBP, SourceIsIndirect = true, SourceDisplacement = LengthDisplacement }; new CPUx86.Multiply { DestinationReg = CPUx86.Registers.EDX }; new CPUx86.Mov { DestinationReg = CPUx86.Registers.ECX, SourceReg = CPUx86.Registers.EAX }; new CPUx86.Movs { Size = 8, Prefixes = CPUx86.InstructionPrefixes.Repeat }; }
/* void Copy(Array sourceArray, ebp + 0x1C * int sourceIndex, ebp + 0x18 * Array destinationArray, ebp + 0x14 * int destinationIndex, ebp + 0x10 * int length, ebp + 0xC * bool reliable); ebp + 0x8 */ public override void AssembleNew(Assembler.Assembler aAssembler, object aMethodInfo) { XS.Set(XSRegisters.EAX, XSRegisters.EBP, sourceDisplacement: SourceArrayDisplacement); XS.Set(XSRegisters.EAX, XSRegisters.EAX, sourceIsIndirect: true); // dereference memory handle to pointer XS.Push(XSRegisters.EAX); new CPUx86.Add { DestinationReg = CPUx86.RegistersEnum.ESP, DestinationIsIndirect = true, SourceValue = 12, Size = 32 }; // pointer is at the element size XS.Pop(XSRegisters.EAX); XS.Set(XSRegisters.EAX, XSRegisters.EAX, sourceIsIndirect: true); // element size XS.Set(XSRegisters.EBX, XSRegisters.EBP, sourceDisplacement: SourceIndexDisplacement); XS.Multiply(XSRegisters.EBX); XS.Add(XSRegisters.EAX, 16); XS.Set(XSRegisters.ESI, XSRegisters.EBP, sourceDisplacement: SourceArrayDisplacement); XS.Set(XSRegisters.ESI, XSRegisters.ESI, sourceIsIndirect: true); // dereference memory handle to pointer XS.Add(XSRegisters.ESI, XSRegisters.EAX); // source ptr XS.Set(XSRegisters.EDX, XSRegisters.EBP, sourceDisplacement: DestinationArrayDisplacement); XS.Set(XSRegisters.EDX, XSRegisters.EDX, sourceIsIndirect: true); // dereference memory handle to pointer XS.Push(XSRegisters.EDX); new CPUx86.Add { DestinationReg = CPUx86.RegistersEnum.ESP, DestinationIsIndirect = true, SourceValue = 12, Size = 32 }; // pointer is at element size XS.Pop(XSRegisters.EAX); XS.Set(XSRegisters.EAX, XSRegisters.EAX, sourceIsIndirect: true); // dereference handle to pointer XS.Set(XSRegisters.ECX, XSRegisters.EBP, sourceDisplacement: DestinationIndexDisplacement); XS.Multiply(XSRegisters.ECX); XS.Add(XSRegisters.EAX, 16); XS.Set(XSRegisters.EDI, XSRegisters.EBP, sourceDisplacement: DestinationArrayDisplacement); XS.Set(XSRegisters.EDI, XSRegisters.EDI, sourceIsIndirect: true); // dereference handle to pointer XS.Add(XSRegisters.EDI, XSRegisters.EAX); // calculate byte count to copy XS.Set(XSRegisters.EAX, XSRegisters.EBP, sourceDisplacement: DestinationArrayDisplacement); XS.Set(XSRegisters.EAX, XSRegisters.EAX, sourceIsIndirect: true); // dereference memory handle to pointer XS.Add(XSRegisters.EAX, 12); XS.Set(XSRegisters.EAX, XSRegisters.EAX, sourceIsIndirect: true); XS.Set(XSRegisters.EDX, XSRegisters.EBP, sourceDisplacement: LengthDisplacement); XS.Multiply(XSRegisters.EDX); XS.Set(XSRegisters.ECX, XSRegisters.EAX); new CPUx86.Movs { Size = 8, Prefixes = CPUx86.InstructionPrefixes.Repeat }; }
public async Task SetUp() { RxApp.MainThreadScheduler = Scheduler.CurrentThread; this.thingDialogNavigationService = new Mock <IThingDialogNavigationService>(); this.panelNavigationService = new Mock <IPanelNavigationService>(); this.dialogNavigationService = new Mock <IDialogNavigationService>(); this.assembler = new Assembler(this.uri); this.session = new Mock <ISession>(); this.session.Setup(x => x.Assembler).Returns(this.assembler); this.outputTerminal = new OutputTerminal(); this.scriptViewModel = new Mock <IScriptPanelViewModel>(); this.scriptViewModel.SetupGet(x => x.OutputTerminal).Returns(() => this.outputTerminal); this.scriptViewModel.SetupProperty(x => x.SelectedSession, session.Object); this.scriptingProxy = new ScriptingProxy(this.thingDialogNavigationService.Object, this.panelNavigationService.Object, this.dialogNavigationService.Object); this.scriptingProxy.ScriptingPanelViewModel = this.scriptViewModel.Object; // Creation of the elements that can be searched using a script this.engineeringModelSetup = new EngineeringModelSetup(Guid.NewGuid(), this.assembler.Cache, null) { Name = "model", ShortName = "Train" }; this.engineerModel = new EngineeringModel(Guid.NewGuid(), this.assembler.Cache, null) { EngineeringModelSetup = engineeringModelSetup }; this.engineerModel.EngineeringModelSetup = this.engineeringModelSetup; this.iterationSetup = new IterationSetup(Guid.NewGuid(), this.assembler.Cache, this.uri); this.iteration = new Iteration(Guid.NewGuid(), this.assembler.Cache, null) { IterationSetup = this.iterationSetup }; this.iteration.IterationSetup = this.iterationSetup; this.elementDefinition = new ElementDefinition(Guid.NewGuid(), this.assembler.Cache, this.uri) { Name = "element", ShortName = "Transformator" }; this.mass = new SimpleQuantityKind(Guid.NewGuid(), null, this.uri) { Name = "parameter", ShortName = "mass" }; this.parameter = new Parameter(Guid.NewGuid(), this.assembler.Cache, null) { ParameterType = this.mass }; this.parameterValueSet = new ParameterValueSet(Guid.NewGuid(), this.assembler.Cache, null) { Reference = new ValueArray <string>(new List <string> { "100" }), Computed = new ValueArray <string>(new List <string> { "-" }), Formula = new ValueArray <string>(new List <string> { "-" }), ValueSwitch = ParameterSwitchKind.REFERENCE }; this.engineerModel.Iteration.Add(this.iteration); this.iteration.Element.Add(this.elementDefinition); this.elementDefinition.Parameter.Add(this.parameter); this.parameter.ValueSet.Add(this.parameterValueSet); // Inclusion of the engineering model in the cache var testThing = new Lazy <Thing>(() => this.engineerModel); testThing.Value.Cache.TryAdd(new CacheKey(testThing.Value.Iid, null), testThing); }
/// <summary> /// Helper method to invoke <see cref="Assembler.ForExistingComposite{T}(CompositeModelType)"/> method with <see cref="CompositeModelType.PLAIN"/> as parameter. /// </summary> /// <typeparam name="TCompositeDeclaration">The type of composite declaration.</typeparam> /// <param name="assembler">The <see cref="Assembler"/>.</param> /// <returns>The return value of <see cref="Assembler.ForExistingComposite{T}(CompositeModelType)"/>.</returns> public static TCompositeDeclaration ForExistingPlainComposite <TCompositeDeclaration>(this Assembler assembler) where TCompositeDeclaration : PlainCompositeAssemblyDeclaration { return(assembler.ForExistingComposite <TCompositeDeclaration>(CompositeModelType.PLAIN)); }
public static void DoExecute(Assembler Assembler, _MethodInfo aMethod, MethodBase aTargetMethod, uint aTargetMethodUID, ILOpCode aOp, bool debugEnabled) { string xCurrentMethodLabel = GetLabel(aMethod, aOp.Position); Type xPopType = aOp.StackPopTypes.Last(); string xNormalAddress = ""; if (aTargetMethod.IsStatic || !aTargetMethod.IsVirtual || aTargetMethod.IsFinal) { xNormalAddress = LabelName.Get(aTargetMethod); } uint xReturnSize = 0; var xMethodInfo = aTargetMethod as MethodInfo; if (xMethodInfo != null) { xReturnSize = Align(SizeOfType(xMethodInfo.ReturnType), 4); } uint xExtraStackSize = Call.GetStackSizeToReservate(aTargetMethod, xPopType); uint xThisOffset = 0; var xParameters = aTargetMethod.GetParameters(); foreach (var xItem in xParameters) { xThisOffset += Align(SizeOfType(xItem.ParameterType), 4); } // This is finding offset to self? It looks like we dont need offsets of other // arguments, but only self. If so can calculate without calculating all fields // Might have to go to old data structure for the offset... // Can we add this method info somehow to the data passed in? // mThisOffset = mTargetMethodInfo.Arguments[0].Offset; XS.Comment("ThisOffset = " + xThisOffset); if (IsReferenceType(xPopType)) { DoNullReferenceCheck(Assembler, debugEnabled, (int)xThisOffset + 4); } else { DoNullReferenceCheck(Assembler, debugEnabled, (int)xThisOffset); } if (!String.IsNullOrEmpty(xNormalAddress)) { if (xExtraStackSize > 0) { XS.Sub(ESP, xExtraStackSize); } XS.Call(xNormalAddress); } else { /* * On the stack now: * $esp Params * $esp + mThisOffset This */ if ((xPopType.IsPointer) || (xPopType.IsByRef)) { xPopType = xPopType.GetElementType(); string xTypeId = GetTypeIDLabel(xPopType); XS.Push(xTypeId, isIndirect: true); } else { XS.Set(EAX, ESP, sourceDisplacement: (int)xThisOffset + 4); XS.Push(EAX, isIndirect: true); } XS.Push(aTargetMethodUID); XS.Call(LabelName.Get(VTablesImplRefs.GetMethodAddressForTypeRef)); if (xExtraStackSize > 0) { xThisOffset -= xExtraStackSize; } /* * On the stack now: * $esp Params * $esp + mThisOffset This */ XS.Pop(ECX); XS.Label(xCurrentMethodLabel + ".AfterAddressCheck"); if (IsReferenceType(xPopType)) { /* * On the stack now: * $esp + 0 Params * $esp + mThisOffset This */ // we need to see if $this is a boxed object, and if so, we need to box it XS.Set(EAX, ESP, sourceDisplacement: (int)xThisOffset + 4); XS.Compare(EAX, (int)ObjectUtils.InstanceTypeEnum.BoxedValueType, destinationIsIndirect: true, destinationDisplacement: 4, size: RegisterSize.Int32); /* * On the stack now: * $esp Params * $esp + mThisOffset This * * ECX contains the method to call * EAX contains the type pointer (not the handle!!) */ XS.Jump(CPU.ConditionalTestEnum.NotEqual, xCurrentMethodLabel + ".NotBoxedThis"); /* * On the stack now: * $esp Params * $esp + mThisOffset This * * ECX contains the method to call * EAX contains the type pointer (not the handle!!) */ XS.Add(EAX, (uint)ObjectUtils.FieldDataOffset); XS.Set(ESP, EAX, destinationDisplacement: (int)xThisOffset + 4); /* * On the stack now: * $esp Params * $esp + mThisOffset Pointer to address inside box * * ECX contains the method to call */ } XS.Label(xCurrentMethodLabel + ".NotBoxedThis"); if (xExtraStackSize > 0) { XS.Sub(ESP, xExtraStackSize); } XS.Call(ECX); XS.Label(xCurrentMethodLabel + ".AfterNotBoxedThis"); } EmitExceptionLogic(Assembler, aMethod, aOp, true, delegate { var xStackOffsetBefore = aOp.StackOffsetBeforeExecution.Value; uint xPopSize = 0; foreach (var type in aOp.StackPopTypes) { xPopSize += Align(SizeOfType(type), 4); } var xResultSize = xReturnSize; if (xResultSize % 4 != 0) { xResultSize += 4 - (xResultSize % 4); } EmitExceptionCleanupAfterCall(Assembler, xResultSize, xStackOffsetBefore, xPopSize); }); XS.Label(xCurrentMethodLabel + ".NoExceptionAfterCall"); XS.Comment("Argument Count = " + xParameters.Length); }
public static GMFile /* errors: different return type? */ ReadFile(string baseDir, JsonData projFile) { var f = new GMFile(); // OBJT: depends on SPRT, obj<->id map // ROOM: depends on OBJT, BGND // SCPT: depends on CODE if (projFile.Has("chunkorder") && projFile["chunkorder"].IsArray) { f.ChunkOrder = DeserializeArray(projFile["chunkorder"], jd => SectionHeadersExtensions.FromChunkName((string)jd)); } else { Console.Error.WriteLine("Warning: Project file doesn't have a chunk order. You should export with a newer Altar.NET version."); f.ChunkOrder = new SectionHeaders[] { SectionHeaders.General, SectionHeaders.Options, SectionHeaders.Language, SectionHeaders.Extensions, SectionHeaders.Sounds, SectionHeaders.AudioGroup, SectionHeaders.Sprites, SectionHeaders.Backgrounds, SectionHeaders.Paths, SectionHeaders.Scripts, SectionHeaders.Globals, SectionHeaders.Shaders, SectionHeaders.Fonts, SectionHeaders.Timelines, SectionHeaders.Objects, SectionHeaders.Rooms, SectionHeaders.DataFiles, SectionHeaders.TexturePage, SectionHeaders.Code, SectionHeaders.Variables, SectionHeaders.Functions, SectionHeaders.Strings, SectionHeaders.Textures, SectionHeaders.Audio, SectionHeaders.EmbedImage, }; } if (projFile.Has("general")) { Console.WriteLine("Loading general..."); try { f.General = DeserializeGeneral(LoadJson(baseDir, (string)(projFile["general"]))); if (f.General.Version >= new Version(2, 0)) { Console.Error.WriteLine("Warning: GM:S 2.0 support is incomplete!"); } } catch (Exception) { Console.Error.WriteLine("Error loading general"); throw; } } if (projFile.Has("options")) { Console.WriteLine("Loading options..."); try { f.Options = DeserializeOptions(LoadJson(baseDir, (string)(projFile["options"]))); } catch (Exception) { Console.Error.WriteLine("Error loading options"); throw; } } if (projFile.Has("strings")) { Console.WriteLine("Loading strings..."); try { f.Strings = DeserializeArray(LoadJson(baseDir, (string)(projFile["strings"])), jd => (string)jd); } catch (Exception) { Console.Error.WriteLine("Error loading strings"); throw; } } var variables = new ReferenceDef[0]; var functions = new ReferenceDef[0]; if (projFile.Has("variables")) { Console.WriteLine("Loading variables..."); try { var vardata = LoadJson(baseDir, (string)(projFile["variables"])); variables = DeserializeArray(vardata.IsArray ? vardata : vardata["variables"], DeserializeReferenceDef); if (vardata.Has("extra")) { f.VariableExtra = DeserializeArray(vardata["extra"], jd => (uint)jd); } } catch (Exception) { Console.Error.WriteLine("Error loading variables"); throw; } } if (projFile.Has("functions")) { Console.WriteLine("Loading functions..."); try { var funcdata = LoadJson(baseDir, (string)(projFile["functions"])); functions = DeserializeArray(funcdata.IsArray ? funcdata : funcdata["functions"], DeserializeReferenceDef); if (funcdata.Has("locals")) { f.FunctionLocals = DeserializeArray(funcdata["locals"], DeserializeFuncLocals); } } catch (Exception) { Console.Error.WriteLine("Error loading functions"); throw; } } f.RefData = new RefData { Variables = variables, Functions = functions }; if (projFile.Has("textures")) { Console.WriteLine("Loading textures..."); var textures = projFile["textures"].ToArray(); var ts = new TextureInfo[textures.Length]; for (int i = 0; i < textures.Length; i++) { try { var texinfo = new TextureInfo { PngData = File.ReadAllBytes(Path.Combine(baseDir, (string)(textures[i]))) }; var bp = new UniquePtr(texinfo.PngData); unsafe { var png = (PngHeader *)bp.BPtr; texinfo.Width = Utils.SwapEnd32(png->IHDR.Width); texinfo.Height = Utils.SwapEnd32(png->IHDR.Height); } ts[i] = texinfo; } catch (Exception) { Console.Error.WriteLine($"Error loading {textures[i]}"); throw; } } f.Textures = ts; } if (projFile.Has("tpags")) { Console.Write("Loading texture pages... "); var cl = Console.CursorLeft; var ct = Console.CursorTop; var tpags = projFile["tpags"].ToArray(); var tps = new TexturePageInfo[tpags.Length]; for (int i = 0; i < tpags.Length; i++) { Console.SetCursorPosition(cl, ct); Console.WriteLine(O_PAREN + (i + 1) + SLASH + tpags.Length + C_PAREN); try { tps[i] = DeserializeTPag(LoadJson(baseDir, (string)(tpags[i]))); } catch (Exception) { Console.Error.WriteLine($"Error loading {tpags[i]}"); throw; } } f.TexturePages = tps; } if (projFile.Has("audio")) { Console.WriteLine("Loading audio..."); var audio = projFile["audio"].ToArray(); var ais = new AudioInfo[audio.Length]; for (int i = 0; i < audio.Length; i++) { try { var audioinfo = new AudioInfo { Wave = File.ReadAllBytes(Path.Combine(baseDir, (string)(audio[i]))) }; ais[i] = audioinfo; } catch (Exception) { Console.Error.WriteLine($"Error loading {audio[i]}"); throw; } } f.Audio = ais; } if (projFile.Has("sprites")) { Console.Write("Loading sprites... "); var cl = Console.CursorLeft; var ct = Console.CursorTop; var sprites = projFile["sprites"].ToArray(); var ss = new SpriteInfo[sprites.Length]; for (int i = 0; i < sprites.Length; i++) { Console.SetCursorPosition(cl, ct); Console.WriteLine(O_PAREN + (i + 1) + SLASH + sprites.Length + C_PAREN); try { ss[i] = DeserializeSprite(LoadJson(baseDir, (string)(sprites[i]))); ss[i].Name = Path.GetFileNameWithoutExtension((string)(sprites[i])); } catch (Exception) { Console.Error.WriteLine($"Error loading {sprites[i]}"); throw; } } f.Sprites = ss; } if (projFile.Has("objs")) { Console.Write("Loading objects... "); var cl = Console.CursorLeft; var ct = Console.CursorTop; var objs = projFile["objs"].ToArray(); var objNames = objs.Select(o => Path.GetFileNameWithoutExtension((string)o)).ToArray(); var os = new ObjectInfo[objs.Length]; for (int i = 0; i < objs.Length; i++) { Console.SetCursorPosition(cl, ct); Console.WriteLine(O_PAREN + (i + 1) + SLASH + objs.Length + C_PAREN); try { os[i] = DeserializeObj( LoadJson(baseDir, (string)(objs[i])), f.Sprites, s => (uint)Array.IndexOf(objNames, s)); os[i].Name = objNames[i]; } catch (Exception) { Console.Error.WriteLine($"Error loading {objs[i]}"); throw; } } f.Objects = os; } if (projFile.Has("code")) { Console.WriteLine("Loading code..."); var code = projFile["code"].ToArray(); var cs = new CodeInfo[code.Length]; var strings = new StringsListBuilder(); strings.AddStrings(f.Strings); IDictionary <string, uint> objectIndices = new Dictionary <string, uint>(f.Objects.Length); for (uint i = 0; i < f.Objects.Length; i++) { objectIndices[f.Objects[i].Name] = i; } for (int i = 0; i < code.Length; i++) { Console.WriteLine((string)(code[i])); try { cs[i] = Assembler.DeserializeCodeFromFile(Path.Combine(baseDir, (string)(code[i])), f.General.BytecodeVersion, strings, objectIndices); cs[i].Name = Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension((string)(code[i]))); cs[i].ArgumentCount = 1; if (f.FunctionLocals != null) { for (int j = 0; j < f.FunctionLocals.Length; j++) { int fastIndex = (j + i) % f.FunctionLocals.Length; if (f.FunctionLocals[fastIndex].FunctionName == cs[i].Name) { cs[i].ArgumentCount = f.FunctionLocals[fastIndex].LocalNames.Length; break; } } } } catch (Exception) { Console.Error.WriteLine($"Error loading {code[i]}"); throw; } } f.Code = cs; f.Strings = strings.GetStrings(); } if (projFile.Has("sounds")) { Console.WriteLine("Loading sounds..."); var sounds = projFile["sounds"].ToArray(); var ss = new SoundInfo[sounds.Length]; for (int i = 0; i < sounds.Length; i++) { try { ss[i] = DeserializeSound(LoadJson(baseDir, (string)(sounds[i]))); ss[i].Name = Path.GetFileNameWithoutExtension((string)(sounds[i])); } catch (Exception) { Console.Error.WriteLine($"Error loading {sounds[i]}"); throw; } } f.Sound = ss; } if (projFile.Has("bg")) { Console.WriteLine("Loading backgrounds..."); var bg = projFile["bg"].ToArray(); var bs = new BackgroundInfo[bg.Length]; for (int i = 0; i < bg.Length; i++) { try { bs[i] = DeserializeBg(LoadJson(baseDir, (string)(bg[i]))); bs[i].Name = Path.GetFileNameWithoutExtension((string)(bg[i])); } catch (Exception) { Console.Error.WriteLine($"Error loading {bg[i]}"); throw; } } f.Backgrounds = bs; } if (projFile.Has("paths")) { Console.WriteLine("Loading paths..."); var paths = projFile["paths"].ToArray(); var ps = new PathInfo[paths.Length]; for (int i = 0; i < paths.Length; i++) { try { ps[i] = DeserializePath(LoadJson(baseDir, (string)(paths[i]))); ps[i].Name = Path.GetFileNameWithoutExtension((string)(paths[i])); } catch (Exception) { Console.Error.WriteLine($"Error loading {paths[i]}"); throw; } } f.Paths = ps; } if (projFile.Has("scripts")) { Console.WriteLine("Loading scripts..."); var scripts = projFile["scripts"].ToArray(); var ss = new ScriptInfo[scripts.Length]; for (int i = 0; i < scripts.Length; i++) { try { ss[i] = DeserializeScript(LoadJson(baseDir, (string)(scripts[i])), f.Code); ss[i].Name = Path.GetFileNameWithoutExtension((string)(scripts[i])); } catch (Exception) { Console.Error.WriteLine($"Error loading {scripts[i]}"); throw; } } f.Scripts = ss; } if (projFile.Has("fonts")) { Console.WriteLine("Loading fonts..."); var fonts = projFile["fonts"].ToArray(); var fs = new FontInfo[fonts.Length]; for (int i = 0; i < fonts.Length; i++) { try { fs[i] = DeserializeFont(LoadJson(baseDir, (string)(fonts[i]))); fs[i].CodeName = Path.GetFileNameWithoutExtension((string)(fonts[i])); } catch (Exception) { Console.Error.WriteLine($"Error loading {fonts[i]}"); throw; } } f.Fonts = fs; } if (projFile.Has("rooms")) { Console.Write("Loading rooms... "); var cl = Console.CursorLeft; var ct = Console.CursorTop; var rooms = projFile["rooms"].ToArray(); var rs = new RoomInfo[rooms.Length]; for (int i = 0; i < rooms.Length; i++) { Console.SetCursorPosition(cl, ct); Console.WriteLine(O_PAREN + (i + 1) + SLASH + rooms.Length + C_PAREN); try { rs[i] = DeserializeRoom(LoadJson(baseDir, (string)(rooms[i])), f.Backgrounds, f.Objects); rs[i].Name = Path.GetFileNameWithoutExtension((string)(rooms[i])); } catch (Exception) { Console.Error.WriteLine($"Error loading {rooms[i]}"); throw; } } f.Rooms = rs; } if (projFile.Has("audiogroups")) { Console.WriteLine("Loading audio groups..."); try { f.AudioGroups = DeserializeArray(LoadJson(baseDir, (string)(projFile["audiogroups"])), jd => (string)jd); } catch (Exception) { Console.Error.WriteLine("Error loading audio groups"); throw; } } if (projFile.Has("shaders")) { Console.WriteLine("Loading shaders..."); var shaders = projFile["shaders"].ToArray(); var ss = new ShaderInfo[shaders.Length]; for (int i = 0; i < shaders.Length; i++) { try { ss[i] = DeserializeShader(LoadJson(baseDir, (string)(shaders[i]))); ss[i].Name = Path.GetFileNameWithoutExtension((string)(shaders[i])); } catch (Exception) { Console.Error.WriteLine($"Error loading {shaders[i]}"); throw; } } f.Shaders = ss; } return(f); }
public Newobj(Assembler aAsmblr) : base(aAsmblr) { }
public static void Invoke(Mobile from, Point3D start, Point3D end, string[] args, List <Container> packs, bool outline, bool mapAvg) { StringBuilder sb = new(); sb.AppendFormat("{0} {1} building ", from.AccessLevel, CommandLogging.Format(from)); if (start == end) { sb.AppendFormat("at {0} in {1}", start, from.Map); } else { sb.AppendFormat("from {0} to {1} in {2}", start, end, from.Map); } sb.Append(":"); for (int i = 0; i < args.Length; ++i) { sb.AppendFormat(" \"{0}\"", args[i]); } CommandLogging.WriteLine(from, sb.ToString()); string name = args[0]; FixArgs(ref args); string[,] props = null; for (int i = 0; i < args.Length; ++i) { if (Insensitive.Equals(args[i], "set")) { int remains = args.Length - i - 1; if (remains >= 2) { props = new string[remains / 2, 2]; remains /= 2; for (int j = 0; j < remains; ++j) { props[j, 0] = args[i + (j * 2) + 1]; props[j, 1] = args[i + (j * 2) + 2]; } FixSetString(ref args, i); } break; } } Type type = Assembler.FindTypeByName(name); if (!IsEntity(type)) { from.SendMessage("No type with that name was found."); return; } DateTime time = DateTime.UtcNow; int built = BuildObjects(from, type, start, end, args, props, packs, outline, mapAvg); if (built > 0) { from.SendMessage("{0} object{1} generated in {2:F1} seconds.", built, built != 1 ? "s" : "", (DateTime.UtcNow - time).TotalSeconds); } else { SendUsage(type, from); } }
public static void Assemble(Assembler aAssembler, uint aElementSize, bool isSigned, _MethodInfo aMethod, ILOpCode aOpCode, bool debugEnabled) { // stack = index // stack + 2 = array DoNullReferenceCheck(aAssembler, debugEnabled, 8); // calculate element offset into array memory (including header) XS.Pop(EAX); XS.Set(EDX, aElementSize); XS.Multiply(EDX); XS.Add(EAX, ObjectUtils.FieldDataOffset + 4); if (aElementSize > 4) { // we start copying the last bytes XS.Add(EAX, aElementSize - 4); } // pop the array now XS.Add(ESP, 4); XS.Pop(EDX); XS.Add(EDX, EAX); var xSizeLeft = aElementSize; while (xSizeLeft > 0) { var xCurrentStep = Math.Min(xSizeLeft, 4); if (xSizeLeft % 4 != 0) { xCurrentStep = xSizeLeft % 4; } xSizeLeft = xSizeLeft - xCurrentStep; switch (xCurrentStep) { case 1: if (isSigned) { XS.MoveSignExtend(ECX, EDX, sourceIsIndirect: true, size: RegisterSize.Byte8); } else { XS.MoveZeroExtend(ECX, EDX, sourceIsIndirect: true, size: RegisterSize.Byte8); } XS.Push(ECX); break; case 2: if (isSigned) { XS.MoveSignExtend(ECX, EDX, sourceIsIndirect: true, size: RegisterSize.Short16); } else { XS.MoveZeroExtend(ECX, EDX, sourceIsIndirect: true, size: RegisterSize.Short16); } XS.Push(ECX); break; case 4: // copy a full dword XS.Push(EDX, true); XS.Sub(EDX, 4); // move to previous 4 bytes break; //case 8: // new CPUx86.Push {DestinationReg = CPUx86.Registers.EDX, DestinationDisplacement = 4, DestinationIsIndirect = true}; // XS.Push(XSRegisters.EDX, isIndirect: true); // break; } } }
public Ldelem_Ref(Assembler aAsmblr) : base(aAsmblr) { }
public Localloc(Assembler aAsmblr) : base(aAsmblr) { }
public void Setup() { RxApp.MainThreadScheduler = Scheduler.CurrentThread; this.session = new Mock <ISession>(); this.assembler = new Assembler(this.uri); this.cache = this.assembler.Cache; this.permissionService = new Mock <IPermissionService>(); this.permissionService.Setup(x => x.CanRead(It.IsAny <Thing>())).Returns(true); this.permissionService.Setup(x => x.CanWrite(It.IsAny <Thing>())).Returns(true); this.permissionService.Setup(x => x.CanWrite(It.IsAny <ClassKind>(), It.IsAny <Thing>())).Returns(true); this.session = new Mock <ISession>(); this.person = new Person(Guid.NewGuid(), this.cache, this.uri) { ShortName = "test" }; this.participant = new Participant(Guid.NewGuid(), this.cache, this.uri) { SelectedDomain = null, Person = this.person }; this.model = new EngineeringModel(Guid.NewGuid(), this.cache, this.uri); this.modelSetup = new EngineeringModelSetup(Guid.NewGuid(), this.cache, this.uri) { Name = "model" }; this.iteration = new Iteration(Guid.NewGuid(), this.cache, this.uri); this.elementDefinition = new ElementDefinition(Guid.NewGuid(), this.cache, this.uri); this.option = new Option(Guid.NewGuid(), this.cache, this.uri); this.iterationSetup = new IterationSetup(Guid.NewGuid(), this.cache, this.uri); this.reqSpec = new RequirementsSpecification(Guid.NewGuid(), this.cache, this.uri); this.reqGroup = new RequirementsGroup(Guid.NewGuid(), this.cache, this.uri); this.modelSetup.IterationSetup.Add(this.iterationSetup); this.modelSetup.Participant.Add(this.participant); this.panelNavigation = new Mock <IPanelNavigationService>(); this.dialogNavigation = new Mock <IThingDialogNavigationService>(); this.domain = new DomainOfExpertise(Guid.NewGuid(), this.cache, this.uri) { Name = "test", ShortName = "test" }; this.reqSpec.Owner = this.domain; this.participant.Domain.Add(this.domain); this.iteration.RequirementsSpecification.Add(this.reqSpec); this.iteration.Option.Add(this.option); this.iteration.DefaultOption = this.option; this.iteration.IterationSetup = this.iterationSetup; this.iteration.Element.Add(this.elementDefinition); this.iteration.TopElement = this.elementDefinition; this.model.EngineeringModelSetup = this.modelSetup; this.model.Iteration.Add(this.iteration); this.reqSpec.Group.Add(this.reqGroup); this.session.Setup(x => x.DataSourceUri).Returns(this.uri.ToString()); this.session.Setup(x => x.ActivePerson).Returns(this.person); this.session.Setup(x => x.PermissionService).Returns(this.permissionService.Object); this.session.Setup(x => x.OpenIterations).Returns(new Dictionary <Iteration, Tuple <DomainOfExpertise, Participant> > { { this.iteration, new Tuple <DomainOfExpertise, Participant>(this.domain, this.participant) } }); this.session.Setup(x => x.QuerySelectedDomainOfExpertise(this.iteration)).Returns(this.domain); }
/// <summary> /// Helper method to invoke <see cref="Assembler.NewComposite{T}(CompositeModelType)"/> method with <see cref="CompositeModelType.PLAIN"/> as parameter. /// </summary> /// <param name="assembler">The <see cref="Assembler"/>.</param> /// <returns>The return value of <see cref="Assembler.NewComposite{T}(CompositeModelType)"/> casted to <see cref="PlainCompositeAssemblyDeclaration"/>.</returns> public static PlainCompositeAssemblyDeclaration NewPlainComposite(this Assembler assembler) { return(assembler.NewComposite <PlainCompositeAssemblyDeclaration>(CompositeModelType.PLAIN)); }
/// <summary> /// Helper method to invoke <see cref="Assembler.ForNewOrExistingComposite{T}(CompositeModelType,IEnumerable{System.Type},out T)"/> method with <see cref="CompositeModelType.PLAIN"/> as parameter. /// </summary> /// <typeparam name="TCompositeDeclaration">The type of composite declaration.</typeparam> /// <param name="assembler">The <see cref="Assembler"/>.</param> /// <param name="types">The composite types.</param> /// <param name="result">This parameter will hold the resulting composite declaration.</param> /// <returns>The return value of <see cref="Assembler.ForNewOrExistingComposite{T}(CompositeModelType,IEnumerable{System.Type},out T)"/>.</returns> public static Boolean ForNewOrExistingPlainComposite <TCompositeDeclaration>(this Assembler assembler, IEnumerable <Type> types, out TCompositeDeclaration result) where TCompositeDeclaration : PlainCompositeAssemblyDeclaration { return(assembler.ForNewOrExistingComposite <TCompositeDeclaration>(CompositeModelType.PLAIN, types, out result)); }
public Ldloc(Assembler aAsmblr) : base(aAsmblr) { }
public override void AssembleNew(Assembler aAssembler, object aMethodInfo) { new XSharp.Assembler.x86.Push { DestinationRef = ElementReference.New("MultiBootInfo_Structure"), DestinationIsIndirect = true }; }
/// <summary> /// Helper method to invoke <see cref="Assembler.ForNewOrExistingComposite{T}(CompositeModelType,IEnumerable{System.Type},out T)"/> method with <see cref="CompositeModelType.SERVICE"/> as parameter. /// </summary> /// <typeparam name="TServiceDeclaration">The type of composite declaration.</typeparam> /// <param name="assembler">The <see cref="Assembler"/>.</param> /// <param name="types">The composite types.</param> /// <param name="result">This parameter will hold the resulting composite declaration.</param> /// <returns>The return value of <see cref="Assembler.ForNewOrExistingComposite{T}(CompositeModelType,IEnumerable{System.Type},out T)"/>.</returns> public static Boolean ForNewOrExistingService <TServiceDeclaration>(this Assembler assembler, IEnumerable <Type> types, out TServiceDeclaration result) where TServiceDeclaration : ServiceCompositeAssemblyDeclaration { return(assembler.ForNewOrExistingComposite <TServiceDeclaration>(CompositeModelType.SERVICE, types, out result)); }
/// <summary> /// Helper method to invoke <see cref="Assembler.ForExistingComposite{T}(CompositeModelType)"/> method with <see cref="CompositeModelType.SERVICE"/> as parameter. /// </summary> /// <typeparam name="TServiceDeclaration">The type of composite declaration.</typeparam> /// <param name="assembler">The <see cref="Assembler"/>.</param> /// <returns>The return value of <see cref="Assembler.ForExistingComposite{T}(CompositeModelType)"/>.</returns> public static TServiceDeclaration ForExistingService <TServiceDeclaration>(this Assembler assembler) where TServiceDeclaration : ServiceCompositeAssemblyDeclaration { return(assembler.ForExistingComposite <TServiceDeclaration>(CompositeModelType.SERVICE)); }
// TODO implementing value composite model type should be done via extension //public static CompositeAssemblyDeclaration NewValue( this Assembler assembler ) //{ // return assembler.NewComposite<CompositeAssemblyDeclaration>( CompositeModelType.VALUE ); //} //public static TCompositeDeclaration NewValue<TCompositeDeclaration>( this Assembler assembler ) // where TCompositeDeclaration : CompositeAssemblyDeclaration //{ // return assembler.NewComposite<TCompositeDeclaration>( CompositeModelType.VALUE ); //} /// <summary> /// Helper method to invoke <see cref="Assembler.NewComposite{T}(CompositeModelType)"/> method with <see cref="CompositeModelType.SERVICE"/> as parameter. /// </summary> /// <param name="assembler">The <see cref="Assembler"/>.</param> /// <returns>The return value of <see cref="Assembler.NewComposite{T}(CompositeModelType)"/> casted to <see cref="ServiceCompositeAssemblyDeclaration"/>.</returns> public static ServiceCompositeAssemblyDeclaration NewService(this Assembler assembler) { return(assembler.NewComposite <ServiceCompositeAssemblyDeclaration>(CompositeModelType.SERVICE)); }
public static void Assemble(Assembler aAssembler, _MethodInfo aMethod, OpMethod xMethod, string currentLabel, Type objectType, MethodBase constructor, bool debugEnabled) { // call cctor: if (aMethod != null) { var xCctor = (objectType.GetConstructors(BindingFlags.Static | BindingFlags.NonPublic) ?? Array.Empty <ConstructorInfo>()).SingleOrDefault(); if (xCctor != null) { XS.Call(LabelName.Get(xCctor)); EmitExceptionLogic(aAssembler, aMethod, xMethod, true, null, ".AfterCCTorExceptionCheck"); XS.Label(".AfterCCTorExceptionCheck"); } } if (objectType.IsValueType) { #region Valuetypes XS.Comment("ValueType"); XS.Comment("Type: " + objectType); /* * Current sitation on stack: * $ESP Arg * $ESP+.. other items * * What should happen: * + The stack should be increased to allow space to contain: * + .ctor arguments * + struct _pointer_ (ref to start of emptied space) * + empty space for struct * + arguments should be copied to the new place * + old place where arguments were should be cleared * + pointer should be set * + call .ctor */ // Size of return value - we need to make room for this on the stack. var xStorageSize = Align(SizeOfType(objectType), 4); XS.Comment("StorageSize: " + xStorageSize); if (xStorageSize == 0) { throw new Exception("ValueType storage size cannot be 0."); } uint xArgSize = 0; var xParameterList = constructor.GetParameters(); foreach (var xParam in xParameterList) { xArgSize = xArgSize + Align(SizeOfType(xParam.ParameterType), 4); } XS.Comment("ArgSize: " + xArgSize); // set source of args copy XS.Set(ESI, ESP); // allocate space for struct XS.Sub(ESP, xStorageSize + 4); // set destination and count of args copy XS.Set(EDI, ESP); XS.Set(ECX, xArgSize / 4); // move the args to their new location new CPUx86.Movs { Size = 32, Prefixes = CPUx86.InstructionPrefixes.Repeat }; // set struct ptr XS.Set(EAX, ESP); XS.Add(EAX, xArgSize + 4); XS.Set(ESP, EAX, destinationDisplacement: (int)xArgSize); XS.Push(EAX); var xOpType = new OpType(xMethod.OpCode, xMethod.Position, xMethod.NextPosition, xMethod.Value.DeclaringType, xMethod.CurrentExceptionRegion); new Initobj(aAssembler).Execute(aMethod, xOpType, true); new Call(aAssembler).Execute(aMethod, xMethod); // Need to put these *after* the call because the Call pops the args from the stack // and we have mucked about on the stack, so this makes it right before the next // op. #endregion Valuetypes } else { // If not ValueType, then we need gc var xParams = constructor.GetParameters(); // array length + 8 var xHasCalcSize = false; #region Special string handling // try calculating size: if (constructor.DeclaringType == typeof(string)) { if (xParams.Length == 1 && xParams[0].ParameterType == typeof(char[])) { xHasCalcSize = true; XS.Set(EAX, ESP, sourceDisplacement: 4, sourceIsIndirect: true); // address XS.Set(EAX, EAX, sourceDisplacement: 8, sourceIsIndirect: true); // element count XS.Set(EDX, 2); // element size XS.Multiply(EDX); XS.Push(EAX); } else if (xParams.Length == 3 && (xParams[0].ParameterType == typeof(char[]) || xParams[0].ParameterType == typeof(char *)) && xParams[1].ParameterType == typeof(int) && xParams[2].ParameterType == typeof(int)) { xHasCalcSize = true; XS.Set(EAX, ESP, sourceIsIndirect: true); XS.ShiftLeft(EAX, 1); XS.Push(EAX); } else if (xParams.Length == 2 && xParams[0].ParameterType == typeof(char) && xParams[1].ParameterType == typeof(int)) { xHasCalcSize = true; XS.Set(EAX, ESP, sourceIsIndirect: true); XS.ShiftLeft(EAX, 1); XS.Push(EAX); } /* * TODO see if something is needed in stack / register to make them really work */ else if (xParams.Length == 3 && (xParams[0].ParameterType == typeof(sbyte *) && xParams[1].ParameterType == typeof(int) && xParams[2].ParameterType == typeof(int))) { xHasCalcSize = true; XS.Push(ESP, isIndirect: true); } else if (xParams.Length == 1 && (xParams[0].ParameterType == typeof(sbyte *))) { xHasCalcSize = true; /* xParams[0] contains a C / ASCII Z string the following ASM is de facto the C strlen() function */ var xSByteCountLabel = currentLabel + ".SByteCount"; XS.Set(EAX, ESP, sourceIsIndirect: true); XS.Or(ECX, 0xFFFFFFFF); XS.Label(xSByteCountLabel); XS.Increment(EAX); XS.Increment(ECX); XS.Compare(EAX, 0, destinationIsIndirect: true); XS.Jump(CPUx86.ConditionalTestEnum.NotEqual, xSByteCountLabel); XS.Push(ECX); } else if (xParams.Length == 1 && (xParams[0].ParameterType == typeof(char *))) { xHasCalcSize = true; /* xParams[0] contains a C / ASCII Z string the following ASM is de facto the C strlen() function */ // todo: does this actually work for empty strings? var xSByteCountLabel = currentLabel + ".SByteCount"; XS.Set(EAX, ESP, sourceIsIndirect: true); XS.Or(ECX, 0xFFFFFFFF); XS.Label(xSByteCountLabel); XS.Increment(EAX); // a char is two bytes XS.Increment(EAX); XS.Increment(ECX); XS.Set(EBX, EAX, sourceIsIndirect: true); XS.And(EBX, 0xFF); // Only compare the char XS.Compare(EBX, 0); XS.Jump(CPUx86.ConditionalTestEnum.NotEqual, xSByteCountLabel); XS.ShiftLeft(ECX, 1); // every character needs two bytes XS.Push(ECX); } else if (xParams.Length == 1 && xParams[0].ParameterType == typeof(ReadOnlySpan <char>)) { xHasCalcSize = true; // push the lenght of the span as well // ReadOnlySpan<char> in memory is a Pointer and Length, simply dup the length and multiply by 2 to get the length to allocate XS.Set(EAX, ESP, sourceIsIndirect: true, sourceDisplacement: 4); XS.ShiftLeft(EAX, 1); XS.Push(EAX); } else { // You actually have to do something to implement a new ctor. For every ctor, newobj has to calculate the size of the string being allocated so that the GC can give enough space. // If this is not done, it will seem to work until a new object is allocated in the space after the string overwriting the string data. This may only happen for long enough strings i.e. // strings with more than one character throw new NotImplementedException(); } } #endregion Special string handling var xMemSize = GetStorageSize(objectType); var xExtraSize = 12; // additional size for set values after alloc XS.Push((uint)(xMemSize + xExtraSize)); if (xHasCalcSize) { XS.Pop(EAX); XS.Add(ESP, EAX, destinationIsIndirect: true); } // todo: probably we want to check for exceptions after calling Alloc XS.Call(LabelName.Get(GCImplementationRefs.AllocNewObjectRef)); XS.Label(".AfterAlloc"); XS.Push(ESP, isIndirect: true); XS.Push(ESP, isIndirect: true); // it's on the stack now 3 times. Once from the Alloc return value, twice from the pushes var strTypeId = GetTypeIDLabel(constructor.DeclaringType); XS.Pop(EAX); XS.Set(EBX, strTypeId, sourceIsIndirect: true); XS.Set(EAX, EBX, destinationIsIndirect: true); XS.Set(EAX, (uint)ObjectUtils.InstanceTypeEnum.NormalObject, destinationDisplacement: 4, destinationIsIndirect: true, size: RegisterSize.Int32); XS.Set(EAX, xMemSize, destinationDisplacement: 8, destinationIsIndirect: true, size: RegisterSize.Int32); var xSize = (uint)(from item in xParams let xQSize = Align(SizeOfType(item.ParameterType), 4) select(int) xQSize).Take(xParams.Length).Sum(); XS.Push(0); foreach (var xParam in xParams) { var xParamSize = Align(SizeOfType(xParam.ParameterType), 4); XS.Comment($"Arg {xParam.Name}: {xParamSize}"); for (var i = 0; i < xParamSize; i += 4) { XS.Push(ESP, isIndirect: true, displacement: (int)(xSize + 8)); } } XS.Call(LabelName.Get(constructor)); // should the complete error handling happen by ILOp.EmitExceptionLogic? if (aMethod != null) { // todo: only happening for real methods now, not for ctor's ? XS.Test(ECX, 2); var xNoErrorLabel = currentLabel + ".NoError" + LabelName.LabelCount.ToString(); XS.Jump(CPUx86.ConditionalTestEnum.Equal, xNoErrorLabel); PushAlignedParameterSize(constructor); // an exception occurred, we need to cleanup the stack, and jump to the exit XS.Add(ESP, 4); new Comment(aAssembler, "[ Newobj.Execute cleanup end ]"); Jump_Exception(aMethod); XS.Label(xNoErrorLabel); } XS.Pop(EAX); PushAlignedParameterSize(constructor); XS.Push(EAX); XS.Push(0); } }
private void ProcessLine() { if (lexer.PeekAndDiscard(TokenType.EOL)) { return; } if (lexer.PeekAndDiscard(TokenType._Page)) { return; } if (lexer.Peek().Type == TokenType.Id) { var id = (string)lexer.Expect(TokenType.Id); if (lexer.PeekAndDiscard(TokenType.Eq)) { var exp = ParseExpression(); Assembler.Equate(id, exp); lexer.PeekAndDiscard(TokenType.EOL); return; } else if (lexer.PeekAndDiscard(TokenType.Colon)) { Assembler.Label(id); } else { lexer.Unexpected(lexer.Get()); } } switch (lexer.Peek().Type) { case TokenType.EOL: lexer.Get(); return; case TokenType._Word: lexer.Get(); ProcessWords(PrimitiveType.Word16); break; case TokenType._Dot: lexer.Get(); lexer.Expect(TokenType.Eq); lexer.Expect(TokenType._Dot); lexer.Expect(TokenType.Plus); var delta = (int)ParseExpression(); emitter.Reserve(delta); break; case TokenType.ASR: ProcessSingleOperand(Assembler.Asr); break; case TokenType.CLR: ProcessSingleOperand(Assembler.Clr); break; case TokenType.CLRB: ProcessSingleOperand(Assembler.Clrb); break; case TokenType.BEQ: ProcessBranch(Assembler.Beq); break; case TokenType.DEC: ProcessSingleOperand(Assembler.Dec); break; case TokenType.INC: ProcessSingleOperand(Assembler.Inc); break; case TokenType.JSR: lexer.Get(); Assembler.Jsr(ParseOperands()); break; case TokenType.MOV: ProcessDoubleOperand(Assembler.Mov); break; case TokenType.MOVB: ProcessDoubleOperand(Assembler.Movb); break; case TokenType.RESET: lexer.Get(); Assembler.Reset(); break; case TokenType.SUB: ProcessDoubleOperand(Assembler.Sub); break; default: lexer.Unexpected(lexer.Get()); break; } }
public Callvirt(Assembler aAsmblr) : base(aAsmblr) { }
public override void RunCommand(CalledCommand calledCommand) { string pathDataDir; if (!GetPathOrDefault(calledCommand, out pathDataDir)) { FailCommand("Invalid parameter value: path."); } switch (calledCommand.Name) { case "load": { switch (calledCommand.MandatoryParametersValues[0]) { case "graph": Loader.LoadGraphFromInternet(pathDataDir); break; case "sales": Loader.LoadSalesFromInternet(pathDataDir); break; } break; } case "clean": { switch (calledCommand.MandatoryParametersValues[0]) { case "graph": Cleaner.CleanGraphData(pathDataDir); Cleaner.CleanKey(pathDataDir); break; case "sales": Cleaner.CleanSalesData(pathDataDir); break; } break; } case "filter": { switch (calledCommand.MandatoryParametersValues[0]) { case "graph_links": Linker.FilterLinks(pathDataDir); break; } break; } case "link": { switch (calledCommand.MandatoryParametersValues[0]) { case "graph": Linker.LinkGraphData(pathDataDir); break; case "sales": Linker.LinkGraphWithSales(pathDataDir); break; } break; } case "asm": { switch (calledCommand.MandatoryParametersValues[0]) { case "graph": Assembler.AssembleGraphData(pathDataDir); break; case "sales": Assembler.AssembleSalesData(pathDataDir); break; } break; } case "sample": { SetType trainingSetType = SamplingHelper.GetSetTypeOrDefault(calledCommand.MandatoryParametersValues[0]); int trainingSetSize; if (!IsValidSetSize(calledCommand.MandatoryParametersValues[1], out trainingSetSize)) { FailCommand("Invalid parameter value: training set size."); } SetType testingSetType = SamplingHelper.GetSetTypeOrDefault(calledCommand.MandatoryParametersValues[2]); int testingSetSize; if (!IsValidSetSize(calledCommand.MandatoryParametersValues[3], out testingSetSize)) { FailCommand("Invalid parameter value: testing set size."); } int testingDataAmount = 100; if (calledCommand.OptionalParametersValues.Count > 0) { if (!IsValidPercentage(calledCommand.OptionalParametersValues[0], out testingDataAmount)) { FailCommand("Invalid parameter value: testing set size."); } } DataSampler.CreateTrainingAndTestSets(pathDataDir, trainingSetType, testingSetType, trainingSetSize, testingSetSize, testingDataAmount); break; } case "test": { switch (calledCommand.MandatoryParametersValues[0]) { case "graph_linkage": TestManager.TestLinkageGraph(pathDataDir); break; case "graph_mapping": TestManager.TestMapping(pathDataDir); break; case "graph_id": TestManager.TestID(pathDataDir); break; } break; } case "stat": { switch (calledCommand.MandatoryParametersValues[0]) { case "graph": TestManager.GetStatisticsGraph(pathDataDir); break; case "connectivity": StatisticsCollector.GetConnectivityStatistics(pathDataDir); break; } break; } default: { FailCommand("Cannot recognize the input commands."); break; } } }
// TODO implementing value composite model type should be done via extension //public static CompositeAssemblyDeclaration ForExistingValue( this Assembler assembler ) //{ // return assembler.ForExistingComposite<CompositeAssemblyDeclaration>( CompositeModelType.VALUE ); //} //public static TCompositeDeclaration ForExistingValue<TCompositeDeclaration>( this Assembler assembler ) // where TCompositeDeclaration : CompositeAssemblyDeclaration //{ // return assembler.ForExistingComposite<TCompositeDeclaration>( CompositeModelType.VALUE ); //} /// <summary> /// Helper method to invoke <see cref="Assembler.ForExistingComposite{T}(CompositeModelType)"/> method with <see cref="CompositeModelType.SERVICE"/> as parameter. /// </summary> /// <param name="assembler">The <see cref="Assembler"/>.</param> /// <returns>The return value of <see cref="Assembler.ForExistingComposite{T}(CompositeModelType)"/> casted to <see cref="ServiceCompositeAssemblyDeclaration"/>.</returns> public static ServiceCompositeAssemblyDeclaration ForExistingService(this Assembler assembler) { return(assembler.ForExistingComposite <ServiceCompositeAssemblyDeclaration>(CompositeModelType.SERVICE)); }
public void SetUp() { this.revision = typeof(Thing).GetProperty("RevisionNumber"); RxApp.MainThreadScheduler = Scheduler.CurrentThread; this.serviceLocator = new Mock <IServiceLocator>(); ServiceLocator.SetLocatorProvider(() => this.serviceLocator.Object); this.session = new Mock <ISession>(); this.permissionService = new Mock <IPermissionService>(); this.thingDialogNavigationService = new Mock <IThingDialogNavigationService>(); this.panelNavigationService = new Mock <IPanelNavigationService>(); this.dialogNavigationService = new Mock <IDialogNavigationService>(); this.pluginSettingsService = new Mock <IPluginSettingsService>(); this.assembler = new Assembler(this.uri); this.cache = this.assembler.Cache; this.serviceLocator.Setup(x => x.GetInstance <IPermissionService>()).Returns(this.permissionService.Object); this.serviceLocator.Setup(x => x.GetInstance <IThingDialogNavigationService>()).Returns(this.thingDialogNavigationService.Object); this.serviceLocator.Setup(x => x.GetInstance <IPanelNavigationService>()).Returns(this.panelNavigationService.Object); this.serviceLocator.Setup(x => x.GetInstance <IDialogNavigationService>()).Returns(this.dialogNavigationService.Object); this.serviceLocator.Setup(x => x.GetInstance <IPluginSettingsService>()).Returns(this.pluginSettingsService.Object); this.sitedir = new SiteDirectory(Guid.NewGuid(), this.cache, this.uri); this.modelsetup = new EngineeringModelSetup(Guid.NewGuid(), this.cache, this.uri) { Name = "model" }; this.iterationsetup = new IterationSetup(Guid.NewGuid(), this.cache, this.uri); this.person = new Person(Guid.NewGuid(), this.cache, this.uri); this.domain = new DomainOfExpertise(Guid.NewGuid(), this.cache, this.uri) { Name = "domain" }; this.participant = new Participant(Guid.NewGuid(), this.cache, this.uri) { Person = this.person, SelectedDomain = this.domain }; this.sitedir.Model.Add(this.modelsetup); this.sitedir.Person.Add(this.person); this.sitedir.Domain.Add(this.domain); this.modelsetup.IterationSetup.Add(this.iterationsetup); this.modelsetup.Participant.Add(this.participant); this.model = new EngineeringModel(Guid.NewGuid(), this.cache, this.uri) { EngineeringModelSetup = this.modelsetup }; this.iteration = new Iteration(Guid.NewGuid(), this.cache, this.uri) { IterationSetup = this.iterationsetup }; this.model.Iteration.Add(this.iteration); this.session.Setup(x => x.RetrieveSiteDirectory()).Returns(this.sitedir); this.session.Setup(x => x.ActivePerson).Returns(this.person); this.session.Setup(x => x.DataSourceUri).Returns(this.uri.ToString); this.session.Setup(x => x.Assembler).Returns(this.assembler); this.session.Setup(x => x.IsVersionSupported(It.IsAny <Version>())).Returns(true); this.session.Setup(x => x.PermissionService).Returns(this.permissionService.Object); this.cache.TryAdd(new CacheKey(this.iteration.Iid, null), new Lazy <Thing>(() => this.iteration)); this.permissionService.Setup(x => x.CanRead(It.IsAny <Thing>())).Returns(true); this.permissionService.Setup(x => x.CanWrite(It.IsAny <Thing>())).Returns(true); this.permissionService.Setup(x => x.CanWrite(It.IsAny <ClassKind>(), It.IsAny <Thing>())).Returns(true); }
/// <summary> /// Helper method to invoke <see cref="Assembler.ForExistingComposite{T}(CompositeModelType)"/> method with <see cref="CompositeModelType.PLAIN"/> as parameter. /// </summary> /// <param name="assembler">The <see cref="Assembler"/>.</param> /// <returns>The return value of <see cref="Assembler.ForExistingComposite{T}(CompositeModelType)"/> casted to <see cref="PlainCompositeAssemblyDeclaration"/>.</returns> public static PlainCompositeAssemblyDeclaration ForExistingPlainComposite(this Assembler assembler) { return(assembler.ForExistingComposite <PlainCompositeAssemblyDeclaration>(CompositeModelType.PLAIN)); }
private void BuildSiteDirData() { this.session = new Mock <ISession>(); this.permissionService = new Mock <IPermissionService>(); this.session.Setup(x => x.PermissionService).Returns(this.permissionService.Object); this.assembler = new Assembler(this.uri); this.session.Setup(x => x.Assembler).Returns(this.assembler); this.siteDir = new SiteDirectory(Guid.NewGuid(), this.assembler.Cache, this.uri); this.modelsetup1 = new EngineeringModelSetup(Guid.NewGuid(), this.assembler.Cache, this.uri); this.modelsetup2 = new EngineeringModelSetup(Guid.NewGuid(), this.assembler.Cache, this.uri); this.iterationSetup1 = new IterationSetup(Guid.NewGuid(), this.assembler.Cache, this.uri); this.iterationSetup2 = new IterationSetup(Guid.NewGuid(), this.assembler.Cache, this.uri); this.person = new Person(Guid.NewGuid(), this.assembler.Cache, this.uri); this.participant1 = new Participant(Guid.NewGuid(), this.assembler.Cache, this.uri); this.participant2 = new Participant(Guid.NewGuid(), this.assembler.Cache, this.uri); this.domain1 = new DomainOfExpertise(Guid.NewGuid(), this.assembler.Cache, this.uri); this.domain2 = new DomainOfExpertise(Guid.NewGuid(), this.assembler.Cache, this.uri); this.domain3 = new DomainOfExpertise(Guid.NewGuid(), this.assembler.Cache, this.uri); this.srdl1 = new SiteReferenceDataLibrary(Guid.NewGuid(), this.assembler.Cache, this.uri); this.srdl2 = new SiteReferenceDataLibrary(Guid.NewGuid(), this.assembler.Cache, this.uri); this.mrdl1 = new ModelReferenceDataLibrary(Guid.NewGuid(), this.assembler.Cache, this.uri); this.mrdl2 = new ModelReferenceDataLibrary(Guid.NewGuid(), this.assembler.Cache, this.uri); this.category = new Category(Guid.NewGuid(), this.assembler.Cache, this.uri); this.booleanPt = new BooleanParameterType(Guid.NewGuid(), this.assembler.Cache, this.uri); this.srdl2.RequiredRdl = this.srdl1; this.mrdl1.RequiredRdl = this.srdl2; this.mrdl2.RequiredRdl = this.srdl1; this.participant1.Person = this.person; this.participant2.Person = this.person; this.modelsetup1.ActiveDomain.Add(this.domain1); this.modelsetup1.ActiveDomain.Add(this.domain2); this.modelsetup1.ActiveDomain.Add(this.domain3); this.modelsetup2.ActiveDomain.Add(this.domain1); this.modelsetup2.ActiveDomain.Add(this.domain2); this.srdl1.ParameterType.Add(this.booleanPt); this.srdl2.DefinedCategory.Add(this.category); this.siteDir.Model.Add(this.modelsetup1); this.siteDir.Model.Add(this.modelsetup2); this.siteDir.Person.Add(this.person); this.siteDir.Domain.Add(this.domain1); this.siteDir.Domain.Add(this.domain2); this.siteDir.Domain.Add(this.domain3); this.siteDir.SiteReferenceDataLibrary.Add(this.srdl1); this.siteDir.SiteReferenceDataLibrary.Add(this.srdl2); this.modelsetup1.IterationSetup.Add(this.iterationSetup1); this.modelsetup2.IterationSetup.Add(this.iterationSetup2); this.modelsetup1.Participant.Add(this.participant1); this.modelsetup2.Participant.Add(this.participant2); this.modelsetup1.RequiredRdl.Add(this.mrdl1); this.modelsetup2.RequiredRdl.Add(this.mrdl2); this.session.Setup(x => x.ActivePerson).Returns(this.person); this.session.Setup(x => x.ActivePersonParticipants) .Returns(new List <Participant> { this.participant1, this.participant2 }); }
public void Setup() { RxApp.MainThreadScheduler = Scheduler.CurrentThread; this.serviceLocator = new Mock <IServiceLocator>(); ServiceLocator.SetLocatorProvider(() => this.serviceLocator.Object); this.nestedElementTreeService = new Mock <INestedElementTreeService>(); this.nestedElementTreeService.Setup(x => x.GetNestedParameterPath(It.IsAny <ParameterBase>(), It.IsAny <Option>())).Returns(this.nestedParameterPath); this.serviceLocator.Setup(x => x.GetInstance <INestedElementTreeService>()).Returns(this.nestedElementTreeService.Object); this.permissionService = new Mock <IPermissionService>(); this.panelNavigationService = new Mock <IPanelNavigationService>(); this.thingDialogNavigationService = new Mock <IThingDialogNavigationService>(); this.dialogNavigationService = new Mock <IDialogNavigationService>(); this.session = new Mock <ISession>(); this.assembler = new Assembler(this.uri); this.session.Setup(x => x.ActivePerson).Returns(this.person); this.session.Setup(x => x.Assembler).Returns(this.assembler); this.siteDir = new SiteDirectory(Guid.NewGuid(), this.assembler.Cache, this.uri); this.person = new Person(Guid.NewGuid(), this.assembler.Cache, this.uri) { GivenName = "John", Surname = "Doe" }; this.model = new EngineeringModel(Guid.NewGuid(), this.assembler.Cache, this.uri); this.modelSetup = new EngineeringModelSetup(Guid.NewGuid(), this.assembler.Cache, this.uri); this.modelSetup.Name = "model name"; this.modelSetup.ShortName = "modelshortname"; this.iteration = new Iteration(Guid.NewGuid(), this.assembler.Cache, this.uri); this.iterationSetup = new IterationSetup(Guid.NewGuid(), this.assembler.Cache, this.uri); this.participant = new Participant(Guid.NewGuid(), this.assembler.Cache, this.uri); this.option = new Option(Guid.NewGuid(), this.assembler.Cache, this.uri) { Name = "option name", ShortName = "optionshortname" }; this.elementDef = new ElementDefinition(Guid.NewGuid(), this.assembler.Cache, this.uri); this.domain = new DomainOfExpertise(Guid.NewGuid(), this.assembler.Cache, this.uri) { Name = "domain", ShortName = "domainshortname" }; this.siteDir.Person.Add(this.person); this.siteDir.Model.Add(this.modelSetup); this.modelSetup.IterationSetup.Add(this.iterationSetup); this.modelSetup.Participant.Add(this.participant); this.participant.Person = this.person; this.model.Iteration.Add(this.iteration); this.model.EngineeringModelSetup = this.modelSetup; this.iteration.IterationSetup = this.iterationSetup; this.iteration.Option.Add(this.option); this.iteration.Element.Add(this.elementDef); this.iteration.TopElement = this.elementDef; this.dialogNavigationService.Setup(x => x.NavigateModal(It.IsAny <IDialogViewModel>())).Returns(new BaseDialogResult(true)); this.permissionService.Setup(x => x.CanWrite(It.IsAny <ClassKind>(), It.IsAny <Thing>())).Returns(true); this.permissionService.Setup(x => x.CanWrite(It.IsAny <Thing>())).Returns(true); this.session.Setup(x => x.ActivePerson).Returns(this.person); this.session.Setup(x => x.DataSourceUri).Returns(this.uri.ToString); this.session.Setup(x => x.PermissionService).Returns(this.permissionService.Object); this.session.Setup(x => x.QuerySelectedDomainOfExpertise(this.iteration)).Returns(this.domain); this.session.Setup(x => x.OpenIterations).Returns( new Dictionary <Iteration, Tuple <DomainOfExpertise, Participant> > { { this.iteration, new Tuple <DomainOfExpertise, Participant>(this.domain, null) } }); }
public Ldobj(Assembler aAsmblr) : base(aAsmblr) { }
public override void AssembleNew(Assembler aAssembler, object aMethodInfo) { XS.Rdtsc(); XS.Push(EDX); XS.Push(EAX); }
public override void AssembleNew(Assembler aAssembler, object aMethodInfo) { XS.Exchange(XSRegisters.BX, XSRegisters.BX); }
public Isinst(Assembler.Assembler aAsmblr) : base(aAsmblr) { }
/// <summary> /// Enables remote code execution by hooking into the HrFunctionCall xbdm function. /// </summary> private void EnableRemoteCodeExecution() { // TODO: proper class for in-memory representation of this stuff const int debugMonitorCustomHeaderSize = 0x40; var scriptBuffer = Module.GetSection(".reloc").Base + debugMonitorCustomHeaderSize; string[] cave = { "use32", $"org {scriptBuffer}", // function prolog "push ebp", "mov ebp, esp", "sub esp, 10h", "push edi", // check for thread id "lea eax, [ebp-4]", // thread id address "push eax", "push strThread", "push dword [ebp+8]", // command $"mov eax, {FGetDwParam}", "call eax", "test eax, eax", "jz immediateCall", // call original code if thread id exists "push dword [ebp-4]", $"mov eax, {DmSetupFunctionCall}", "call eax", "jmp lblDone", // thread argument doesn't exist, must be an immediate call instead "immediateCall:", // get the call address "lea eax, [ebp-8]", // argument value address "push eax", "push strAddr", "push dword [ebp+8]", // command $"mov eax, {FGetDwParam}", "call eax", "test eax, eax", "jz lblError", // ensure constructed argument name is null-terminated "mov dword [ebp-0Ch], 0", // push arguments (leave it up to caller to reverse argument order and supply the correct amount) "xor edi, edi", // argument counter "nextArg:", // get argument name "push edi", // argument index "push argNameFormat", // format string address "lea eax, [ebp-10h]", // argument name address "push eax", $"mov eax, {_xbox.Kernel.Exports.sprintf}", "call eax", "add esp, 0Ch", // check if it's included in the command "lea eax, [ebp-4]", // argument value address "push eax", "lea eax, [ebp-10h]", // argument name address "push eax", "push dword [ebp+8]", // command $"mov eax, {FGetDwParam}", "call eax", "test eax, eax", "jz noMoreArgs", // push it on the stack "push dword [ebp-4]", "inc edi", // move on to the next argument "jmp nextArg", "noMoreArgs:", // TODO: set fastcall register context (ecx, edx, xmm0-xmm2) // perform the call "call dword [ebp-8]", // print response message "push dword [ebp+14h]", // use pdmcc as connection id "fst dword [ebp-4]", "push dword [ebp-4]", // floating-point return value "push eax", // integer return value "push returnValuesFormat", // format string address "push dword [ebp+0Ch]", // response address $"mov eax, {_xbox.Kernel.Exports.sprintf}", "call eax", "add esp, 14h", // return codes "mov eax, 02DB0000h", // success "jmp lblDone", "lblError:", "mov eax, 82DB0000h", // error "lblDone:", // function epilog "pop edi", "leave", "retn 10h", // variables "strAddr db 'addr', 0", "strThread db 'thread', 0", "argNameFormat db 'arg%01d', 0", "returnValuesFormat db 'eax=0x%X st0=0x%X cid=0x%X', 0" }; // write the cave byte[] caveBytes = Assembler.Assemble(cave, scriptBuffer); _xbox.Memory.WriteBytes(scriptBuffer, caveBytes); // write the hook byte[] hookBytes = Assembler.Assemble(new[] { $"push {scriptBuffer}", "retn" }); _xbox.Memory.WriteBytes(HrFunctionCall, hookBytes); }