public Expression GetExpression(InstructionInfo info, IExpressionLibraryRegistry expressionLibraries) { String opcode = info.Prefix + info.Opcode.ToString("X2"); if (!_enabledOpcodes.Contains(opcode) && IsFilterEnabled) return null; return GetExpressionImpl(info, expressionLibraries); }
public Expression GetExpression(InstructionInfo info, IExpressionLibraryRegistry expressionLibraries) { var instructionSize = 0; switch (info.ParameterMode) { case InstructionParameterMode.None: instructionSize = 1; break; case InstructionParameterMode.Byte: instructionSize = 2; break; case InstructionParameterMode.Word: instructionSize = 3; break; case InstructionParameterMode.Index: instructionSize = 2; break; case InstructionParameterMode.Address: instructionSize = 3; break; case InstructionParameterMode.IndexAndByte: instructionSize = 3; break; default: break; } if (info.Prefix == "DDCB" || info.Prefix == "FDCB") { instructionSize++; } if (!String.IsNullOrEmpty(info.Prefix)) instructionSize += info.Prefix.Length / 2; var progExpr = expressionLibraries.GetLibrary<IProgramControlExpressionLibrary>(); return Expression.Call(Expression.Constant(this), _enqueMethod, Expression.New(_historyItemConsturctor, Expression.Constant(info.Mnemonic), Expression.Subtract(progExpr.ProgramCounterRegister, Expression.Constant(instructionSize)), progExpr.ParameterByte1, progExpr.ParameterByte2) ); }
public static List<AstNodeExpr> ParseParameters(InstructionInfo InstructionInfo, Scope<string, AstLocal> Scope) { var Parameters = new List<AstNodeExpr>(); new Regex(@"%\w+").Replace(InstructionInfo.Format, (Match) => { switch (Match.ToString()) { case "%addr": Parameters.Add(ast.Cast<ushort>(ast.Local(Scope.Get("nnn")))); break; case "%vx": Parameters.Add(ast.Cast<byte>(ast.Local(Scope.Get("x")))); break; case "%vy": Parameters.Add(ast.Cast<byte>(ast.Local(Scope.Get("y")))); break; case "%byte": Parameters.Add(ast.Cast<byte>(ast.Local(Scope.Get("nn")))); break; case "%nibble": Parameters.Add(ast.Cast<byte>(ast.Local(Scope.Get("n")))); break; default: throw (new Exception(Match.ToString())); } return ""; }); return Parameters; }
protected override Expression GetExpressionImpl(InstructionInfo info, IExpressionLibraryRegistry expressionLibraries) { var dataExpLib = expressionLibraries.GetLibrary<IDataAccessExpressionLibrary>(); var progLib = expressionLibraries.GetLibrary<IProgramControlExpressionLibrary>(); return Expression.Call(Expression.Constant(this), _instructionRanEvent, Expression.New(_eventArgsConstructor, dataExpLib.RegisterA, dataExpLib.RegisterB, dataExpLib.RegisterC, dataExpLib.RegisterD, dataExpLib.RegisterE, dataExpLib.RegisterH, dataExpLib.RegisterL, dataExpLib.FlagsRegister, progLib.ProgramCounterRegister, dataExpLib.StackPointerRegister, progLib.CycleCounter, Expression.Constant(info), ((DataAccessExpressionLibrary)dataExpLib).SystemBusParameter ) ); }
public SchedulingGenome(SchedulingGenomePopulation population) { this.population = population; this.scheduler = population.Scheduler; int maxSchedulingSteps = InstructionNodes.Count; schedule = new InstructionNode[ maxSchedulingSteps, MachineDescription.ExecutionUnits]; instructionInfos = new Hashtable(InstructionNodes.Count); foreach (InstructionNode iNode in InstructionNodes) instructionInfos[iNode] = new InstructionInfo(); valueInfos = new Hashtable(RegisterValues.Count); foreach (ValueNode vNode in RegisterValues) valueInfos[vNode] = new ValueInfo(); isValid = false; generationOfBirth = population.GA.Generation; }
void Format_Misc(int index, InstructionInfo info, string formattedString) => FormatBase(index, info, formattedString, FormatterFactory.Create());
/// <summary> /// Decrypt the data /// </summary> /// <param name="Data">The data to decrypt</param>l /// <param name="Offset">The index where the data starts</param> /// <param name="Length">The length to decrypt</param> public void Decrypt(byte[] Data, int Offset, int Length) { lock (DecState) { int OrgLen = Length; Length += Offset; for (int round = 0; round < Rounds; round++) { using (PayloadWriter pw = new PayloadWriter(new System.IO.MemoryStream(Data))) { ulong temp_Value = DecState.IV[EncMode == WopEncMode.Simple ? 0 : DecState.IV_Pos]; //is being used for CBC Mode (Block-Cipher-Chaining Mode) for (int i = Offset, k = 0; i < Length; k++) { pw.vStream.Position = i; int usedsize = 0; ulong value = 0; ulong OrgReadValue = 0; if (i + 8 < Length) { OrgReadValue = BitConverter.ToUInt64(Data, i); usedsize = 8; value = Decrypt_Core_Big(OrgReadValue ^ temp_Value, OrgLen, k); pw.WriteULong(value); } else { OrgReadValue = Data[i]; usedsize = 1; value = Decrypt_Core_Small((byte)OrgReadValue, OrgLen, k); pw.WriteByte((byte)value); } temp_Value += OrgReadValue; DecState.Seed += (int)value; i += usedsize; if (EncMode != WopEncMode.Simple) { DecState.Key_Pos += 1; DecState.Salt_Pos += 1; } } } } DecState.IV_Pos = (DecState.IV_Pos + 1) % DecState.IV.Length; switch (EncMode) { case WopEncMode.GenerateNewAlgorithm: { InstructionInfo tempEncCode = null; InstructionInfo tempDecCode = null; FastRandom fastRand = new FastRandom(DecState.Seed); for (int i = 0; i < DecState.Instructions.Length; i++) { GetNextRandomInstruction(fastRand, ref tempEncCode, ref tempDecCode); DecState.Instructions[i] = tempDecCode; } if (UseDynamicCompiler) { DecState.Compile(); } break; } case WopEncMode.ShuffleInstructions: { ShuffleInstructions(DecState.Instructions, DecState.Seed); if (UseDynamicCompiler) { DecState.Compile(); } break; } } } }
protected void FormatBase(int index, InstructionInfo info, string formattedString, FastFormatter formatter) => FormatterTestUtils.FormatTest(info.Bitness, info.HexBytes, info.Code, info.Options, formattedString, formatter);
private void ApplyOperand(string str) { InstructionInfo II = (InstructionInfo)instructionEditor.DragItem; switch (currentPOT) { case PickOperandType.Byte: Byte resultByte; if (Byte.TryParse(str, out resultByte)) { II.NewInstruction.Operand = resultByte; } break; case PickOperandType.SByte: SByte resultSByte; if (SByte.TryParse(str, out resultSByte)) { II.NewInstruction.Operand = resultSByte; } break; case PickOperandType.Int32: Int32 resultInt32; if (Int32.TryParse(str, out resultInt32)) { II.NewInstruction.Operand = resultInt32; } break; case PickOperandType.Int64: Int64 resultInt64; if (Int64.TryParse(str, out resultInt64)) { II.NewInstruction.Operand = resultInt64; } break; case PickOperandType.Single: Single resultSingle; if (Single.TryParse(str, out resultSingle)) { II.NewInstruction.Operand = resultSingle; } break; case PickOperandType.Double: Double resultDouble; if (Double.TryParse(str, out resultDouble)) { II.NewInstruction.Operand = resultDouble; } break; case PickOperandType.String: II.NewInstruction.Operand = str; break; default: Log.Write(Log.Level.Warning, $"OperandType \"{currentPOT}\" cannot be processed with a textbox"); break; } RedrawBoth(); }
public CpuEventArgs(Int32 registerA, Int32 registerB, Int32 registerC, Int32 registerD, Int32 registerE, Int32 registerH, Int32 registerL, Int32 flagsRegister, Int32 programCounterRegsiter, Int32 stackPointerRegsiter, Int32 cycleCounter, InstructionInfo info, ISystemBus systemBus ) { RegisterA = registerA; RegisterB = registerB; RegisterC = registerC; RegisterD = registerD; RegisterE = registerE; RegisterH = registerH; RegisterL = registerL; FlagsRegister = flagsRegister; ProgramCounterRegister = programCounterRegsiter; StackPointerRegister = stackPointerRegsiter; CycleCounter = cycleCounter; Instruction = info; SystemBus = systemBus; }
private void FinishFile(int address, List <FunctionEnumerationResult> files, ref FunctionEnumerationResult currentFunction, ref FunctionEnumerationResult currentFile, InstructionInfo newFileInstruction) { if (newFileInstruction == null || (newFileInstruction.word1 >= 0 && newFileInstruction.word1 < ainFile.Filenames.Count)) { if (newFileInstruction != null) { currentFile.name = ainFile.Filenames[newFileInstruction.word1]; currentFile.id = newFileInstruction.word1; } FinishFunction(address, ref currentFunction, currentFile); currentFile.lastAddress = address; files.Add(currentFile); currentFile = new FunctionEnumerationResult(); currentFile.children = new List <FunctionEnumerationResult>(); currentFile.address = address; } }
/// <summary> /// 计算路径以及转向逻辑 /// </summary> /// <param name="insInfo"></param> /// <param name="path1"></param> /// <param name="path2"></param> /// <param name="rackItem"></param> private void ComputePath(InstructionInfo insInfo, string path1, string path2 = null, RackInfo rackItem = null) { string[] path1Arr = path1.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); int path1Length = path1Arr.Length; for (int i = 0; i < path1Length; i++) { string path = path1Arr[i]; if (i == 0 && !string.IsNullOrEmpty(lastRoute)) //如果取/卸货仓位是紧邻的仓位,则指令需要跳过下一位置 { var rackInfo = rackList.Where(a => a.RouteCode == path).FirstOrDefault(); if (rackInfo != null) { var lastInfo = rackList.Where(a => a.RouteCode == lastRoute).FirstOrDefault(); if (lastInfo != null) { continue; } } } lastRoute = path; var item = routelist.Where(a => a.Routecode == path1Arr[i]).FirstOrDefault(); if (i + 1 < path1Length) //还有下一节点 { string next = path1Arr[i + 1]; var nextItem = routelist.Where(a => a.Routecode == next).FirstOrDefault(); int xsub = item.X - nextItem.X; int ysub = item.Y - nextItem.Y; if (xsub == 0) { if (ysub > 0) //向南 { insInfo.AddItem(path, insInfo.getWay(direction, DirectionWay.South)); direction = DirectionWay.South; } else //向北 { insInfo.AddItem(path, insInfo.getWay(direction, DirectionWay.North)); direction = DirectionWay.North; } } else if (ysub == 0) { if (xsub > 0) //向西 { insInfo.AddItem(path, insInfo.getWay(direction, DirectionWay.West)); direction = DirectionWay.West; } else //向东 { insInfo.AddItem(path, insInfo.getWay(direction, DirectionWay.Easet)); direction = DirectionWay.Easet; } } } else if (!string.IsNullOrEmpty(path2)) //一期默认货架在右侧,即X正,Y负 { setRouteByRack(insInfo, path2, path, item, rackItem); } } }
void testALS() { prepare(); //joinIrc1(); var absolute = PathHelper.AssemblyDirectory.Uri.AbsoluteUri; var absoluteWithoutFile = absolute.Substring(8); var pathParts = new List <string>(absoluteWithoutFile.Split(new char[] { '/' })); var pathPartsWithoutSpecific = pathParts; for (;;) { string lastPathPart = pathPartsWithoutSpecific[pathPartsWithoutSpecific.Count - 1]; if (lastPathPart == "bin") { break; } pathPartsWithoutSpecific.RemoveAt(pathPartsWithoutSpecific.Count - 1); } pathPartsWithoutSpecific.RemoveAt(pathPartsWithoutSpecific.Count - 1); pathPartsWithoutSpecific.RemoveAt(pathPartsWithoutSpecific.Count - 1); pathPartsWithoutSpecific.AddRange(new string[] { "MetaNixCore", "functionalSrc", "problems" }); string directoryPath = string.Join("\\", pathPartsWithoutSpecific.ToArray()); string[] problemsFilenames = Directory.GetFiles(directoryPath); PatternSymbolContext patternSymbolContext = new PatternSymbolContext(); patternSymbolContext.lookupOrCreateSymbolIdAndUniqueIdForName("null"); // must have 0 as uniqueId patternSymbolContext.lookupOrCreateSymbolIdAndUniqueIdForName("true"); // must have 1 as uniqueId patternSymbolContext.lookupOrCreateSymbolIdAndUniqueIdForName("false"); // must have 2 as uniqueId Scheduler scheduler = new Scheduler(); AdvancedAdaptiveLevinSearchProgramDatabase levinSearchProblemDatabase = new AdvancedAdaptiveLevinSearchProgramDatabase(); SparseArrayProgramDistribution sparseArrayProgramDistribution = new SparseArrayProgramDistribution(); AdvancedAdaptiveLevinSearchTaskProvider levinSearchTaskProvider = new AdvancedAdaptiveLevinSearchTaskProvider(scheduler, sparseArrayProgramDistribution, levinSearchProblemDatabase, logger); // overwrite for testing problemsFilenames = new string[] { @"C:\Users\r0b3\github\AGI-X0\code\c#\MetaNixCore\functionalSrc\problems\Induction_array_verticalAddition.txt", @"C:\Users\r0b3\github\AGI-X0\code\c#\MetaNixCore\functionalSrc\problems\level1\Induction_array_integer_exists.txt", /* * * * @"C:\Users\r0b3\github\AGI-X0\code\c#\MetaNixCore\functionalSrc\problems\Induction_linkedlist_next.txt", * @"C:\Users\r0b3\github\AGI-X0\code\c#\MetaNixCore\functionalSrc\problems\Induction_linkedlist_append.txt", * @"C:\Users\r0b3\github\AGI-X0\code\c#\MetaNixCore\functionalSrc\problems\Induction_array_appendBeginningAndEnding.txt", * @"C:\Users\r0b3\github\AGI-X0\code\c#\MetaNixCore\functionalSrc\problems\Induction_array_removeEqual.txt", * @"C:\Users\r0b3\github\AGI-X0\code\c#\MetaNixCore\functionalSrc\problems\Induction_array_subReg0.txt", * @"C:\Users\r0b3\github\AGI-X0\code\c#\MetaNixCore\functionalSrc\problems\Induction_array_multiplication.txt", * @"C:\Users\r0b3\github\AGI-X0\code\c#\MetaNixCore\functionalSrc\problems\induction_array_binaryNegation.txt", * @"C:\Users\r0b3\github\AGI-X0\code\c#\MetaNixCore\functionalSrc\problems\Induction_array_negation.txt", */ }; foreach (string iterationPath in problemsFilenames) { string fileContent = File.ReadAllText(iterationPath); Lexer lexer = new Lexer(); lexer.setSource(fileContent); Functional2LexerAndParser parser = new Functional2LexerAndParser(patternSymbolContext); parser.lexer = lexer; parser.parse(); Pattern <Decoration> problemRootElement = parser.rootPattern; MetaNix.framework.pattern.Interpreter.vmAssert(problemRootElement.isBranch, false, "Must be branch!"); MetaNix.framework.pattern.Interpreter.vmAssert(problemRootElement.decoration == null, false, "Must be pure branch!"); Pattern <Decoration> configurationPattern = problemRootElement.referenced[0]; AdvancedAdaptiveLevinSearchProblem levinSearchProblem = new AdvancedAdaptiveLevinSearchProblem(); var iterationPathParts = new List <string>(iterationPath.Split(new char[] { '\\' })); string taskname = iterationPathParts[iterationPathParts.Count - 1].Substring(0, iterationPathParts[iterationPathParts.Count - 1].Length - 4); levinSearchProblem.humanReadableTaskname = taskname; //levinSearchProblem.enumerationMaxProgramLength = 5; levinSearchProblem.instructionsetCount = InstructionInfo.getNumberOfInstructions() - 16; /*because no call*/ levinSearchProblem.maxNumberOfRetiredInstructions = Conversion.convertToUint(configurationPattern.referenced[1]); // TODO< derive by propability with some formula from schmidhuber > // read hints for indirect call candidates Pattern <Decoration> hintIndirectCallCandidatesPattern = configurationPattern.referenced[2]; foreach (var iHintPattern in hintIndirectCallCandidatesPattern.referenced) { string iHint = Conversion.convertPatternToString(iHintPattern); levinSearchProblem.humanReadableIndirectlyCallableProgramNames.Add(iHint); } //levinSearchProblem.localInitialInterpreterState = new LocalInterpreterState(); //levinSearchProblem.localInitialInterpreterState.registers = new int[3]; //levinSearchProblem.initialInterpreterState.debugExecution = false; levinSearchProblem.enumerationMaxProgramLength = Conversion.convertToUint(configurationPattern.referenced[0]); for (int trainingSampleI = 1; trainingSampleI < problemRootElement.referenced.Length; trainingSampleI++) { var trainingSamplePattern = problemRootElement.referenced[trainingSampleI]; MetaNix.framework.pattern.Interpreter.vmAssert(trainingSamplePattern.isBranch, false, "Must be branch!"); MetaNix.framework.pattern.Interpreter.vmAssert(trainingSamplePattern.decoration == null, false, "Must be pure branch!"); Pattern <Decoration> questionArrayPattern = trainingSamplePattern.referenced[0], questionRegistersPattern = trainingSamplePattern.referenced[1], answerArrayPattern = trainingSamplePattern.referenced[3], answerRegistersPattern = trainingSamplePattern.referenced[4]; // append TrainingSample createdTrainingSample = new TrainingSample(); createdTrainingSample.questionArray = new List <int>(Conversion.convertToIntArray(questionArrayPattern)); createdTrainingSample.questionRegisters = Conversion.convertToOptionalIntArray(questionRegistersPattern); createdTrainingSample.questionArrayIndex = Conversion.convertToOptionalInt(trainingSamplePattern.referenced[2]); createdTrainingSample.answerRegisters = Conversion.convertToOptionalIntArray(answerRegistersPattern); createdTrainingSample.answerArray = new List <int>(Conversion.convertToIntArray(answerArrayPattern)); createdTrainingSample.answerArrayIndex = Conversion.convertToOptionalInt(trainingSamplePattern.referenced[5]); levinSearchProblem.trainingSamples.Add(createdTrainingSample); } levinSearchTaskProvider.problems.Add(levinSearchProblem); } levinSearchTaskProvider.submitFirstTask(); for (; ;) { scheduler.process(); } }
/// <summary> /// 计算仓位的转向逻辑 /// </summary> /// <param name="insInfo"></param> /// <param name="nextPathArray"></param> /// <param name="lastPath"></param> /// <param name="item"></param> /// <param name="rackItem"></param> private void setRouteByRack(InstructionInfo insInfo, string nextPathArray, string lastPath, RouteInfo item, RackInfo rackItem) { string[] path2Arr = nextPathArray.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); string next = path2Arr[0]; var nextItem = routelist.Where(a => a.Routecode == next).FirstOrDefault(); int xsub = item.X - nextItem.X; int ysub = item.Y - nextItem.Y; int xrack = 0; int yrack = 0; if (rackItem != null) { xrack = item.X - rackItem.X; yrack = item.Y - rackItem.Y; } if (xsub == 0) { if (ysub > 0) //向南 { if (lastPath == inpackroute || lastPath == outpackroute) { if (direction == DirectionWay.South) { if (xrack > 0) //右手 { insInfo.AddItem(lastPath, TurnWay.Left); insInfo.AddItem(lastPath, TurnWay.Right); } else { insInfo.AddItem(lastPath, TurnWay.Right); insInfo.AddItem(lastPath, TurnWay.Left); } } else if (direction == DirectionWay.North) { if (xrack > 0) //左手 { insInfo.AddItem(lastPath, TurnWay.Right); insInfo.AddItem(lastPath, TurnWay.Right); } else { insInfo.AddItem(lastPath, TurnWay.Left); insInfo.AddItem(lastPath, TurnWay.Left); } } else if (direction == DirectionWay.West) { insInfo.AddItem(lastPath, TurnWay.Left); //insInfo.AddItem(lastPath, TurnWay.Next); } else { insInfo.AddItem(lastPath, TurnWay.Right); //insInfo.AddItem(lastPath, TurnWay.Next); } } direction = DirectionWay.South; } else //向北 { if (lastPath == inpackroute || lastPath == outpackroute) { if (direction == DirectionWay.South) { if (xrack > 0) //右手 { insInfo.AddItem(lastPath, TurnWay.Left); insInfo.AddItem(lastPath, TurnWay.Left); } else { insInfo.AddItem(lastPath, TurnWay.Right); insInfo.AddItem(lastPath, TurnWay.Right); } } else if (direction == DirectionWay.North) { if (xrack > 0) //左手 { insInfo.AddItem(lastPath, TurnWay.Right); insInfo.AddItem(lastPath, TurnWay.Left); } else { insInfo.AddItem(lastPath, TurnWay.Left); insInfo.AddItem(lastPath, TurnWay.Right); } } else if (direction == DirectionWay.Easet) { insInfo.AddItem(lastPath, TurnWay.Left); //insInfo.AddItem(lastPath, TurnWay.Next); } else { insInfo.AddItem(lastPath, TurnWay.Right); //insInfo.AddItem(lastPath, TurnWay.Next); } } direction = DirectionWay.North; } } else if (ysub == 0) { if (xsub > 0) //向西 { if (lastPath == inpackroute || lastPath == outpackroute) { if (direction == DirectionWay.South) { insInfo.AddItem(lastPath, TurnWay.Right); //insInfo.AddItem(lastPath, TurnWay.Back); //insInfo.AddItem(lastPath, TurnWay.Left); } else if (direction == DirectionWay.Easet) { if (yrack > 0) //右手 { insInfo.AddItem(lastPath, TurnWay.Left); insInfo.AddItem(lastPath, TurnWay.Left); } else { insInfo.AddItem(lastPath, TurnWay.Right); insInfo.AddItem(lastPath, TurnWay.Right); } } else if (direction == DirectionWay.West) { if (yrack > 0) //左手 { insInfo.AddItem(lastPath, TurnWay.Right); insInfo.AddItem(lastPath, TurnWay.Left); } else { insInfo.AddItem(lastPath, TurnWay.Left); insInfo.AddItem(lastPath, TurnWay.Right); } } else { insInfo.AddItem(lastPath, TurnWay.Left); //insInfo.AddItem(lastPath, TurnWay.Back); //insInfo.AddItem(lastPath, TurnWay.Right); } } direction = DirectionWay.West; } else //向东 { if (lastPath == inpackroute || lastPath == outpackroute) { if (direction == DirectionWay.South) { insInfo.AddItem(lastPath, TurnWay.Left); //insInfo.AddItem(lastPath, TurnWay.Back); //insInfo.AddItem(lastPath, TurnWay.Right); } else if (direction == DirectionWay.Easet) { if (yrack > 0) //右手 { insInfo.AddItem(lastPath, TurnWay.Left); insInfo.AddItem(lastPath, TurnWay.Right); } else { insInfo.AddItem(lastPath, TurnWay.Right); insInfo.AddItem(lastPath, TurnWay.Left); } } else if (direction == DirectionWay.West) { if (yrack > 0) //左手 { insInfo.AddItem(lastPath, TurnWay.Right); insInfo.AddItem(lastPath, TurnWay.Right); } else { insInfo.AddItem(lastPath, TurnWay.Left); insInfo.AddItem(lastPath, TurnWay.Left); } } else { insInfo.AddItem(lastPath, TurnWay.Right); //insInfo.AddItem(lastPath, TurnWay.Back); //insInfo.AddItem(lastPath, TurnWay.Left); } } direction = DirectionWay.Easet; } } }
protected abstract Expression GetExpressionImpl(InstructionInfo info, IExpressionLibraryRegistry expressionLibraries);
public virtual void Copy( SchedulingGenome other, IDictionary instructionMap, IDictionary valueMap) { population = other.population; scheduler = other.scheduler; schedule = new InstructionNode[ other.schedule.GetLength(0), other.schedule.GetLength(1)]; for (int i = 0; i < schedule.GetLength(0); i++) { for (int j = 0; j < schedule.GetLength(1); j++) { InstructionNode iNode = other.schedule[i, j]; if (iNode != null) { schedule[i, j] = (InstructionNode) instructionMap[other.schedule[i, j]]; } else { schedule[i, j] = null; } } } valueInfos = new Hashtable(); foreach (ValueNode vNode in other.ValueInfos.Keys) { ValueInfo info = new ValueInfo(); ValueInfo otherInfo = other.GetValueInfo(vNode); info.Register = otherInfo.Register; info.Production = otherInfo.Production; info.LastUsage = otherInfo.LastUsage; valueInfos[valueMap[vNode]] = info; } instructionInfos = new Hashtable(); foreach (InstructionNode iNode in other.InstructionInfos.Keys) { InstructionInfo info = new InstructionInfo(); InstructionInfo otherInfo = other.GetInstructionInfo(iNode); info.SchedulingStep = otherInfo.SchedulingStep; instructionInfos[instructionMap[iNode]] = info; } isValid = other.isValid; scheduleLength = other.scheduleLength; violatedSchedulingConstraints = other.violatedSchedulingConstraints; violatedRegisterConstraints = other.violatedRegisterConstraints; generationOfBirth = other.generationOfBirth; }
public virtual void Copy(IGenome otherGenome) { SchedulingGenome other = (SchedulingGenome) otherGenome; population = other.population; scheduler = other.scheduler; schedule = new InstructionNode[ other.schedule.GetLength(0), other.schedule.GetLength(1)]; for (int i = 0; i < schedule.GetLength(0); i++) for (int j = 0; j < schedule.GetLength(1); j++) schedule[i, j] = other.schedule[i, j]; valueInfos = new Hashtable(); foreach (ValueNode vNode in other.ValueInfos.Keys) { ValueInfo info = new ValueInfo(); ValueInfo otherInfo = other.GetValueInfo(vNode); info.Register = otherInfo.Register; info.Production = otherInfo.Production; info.LastUsage = otherInfo.LastUsage; valueInfos[vNode] = info; } instructionInfos = new Hashtable(); foreach (InstructionNode iNode in other.InstructionInfos.Keys) { InstructionInfo info = new InstructionInfo(); InstructionInfo otherInfo = other.GetInstructionInfo(iNode); info.SchedulingStep = otherInfo.SchedulingStep; instructionInfos[iNode] = info; } isValid = other.isValid; scheduleLength = other.scheduleLength; violatedSchedulingConstraints = other.violatedSchedulingConstraints; violatedRegisterConstraints = other.violatedRegisterConstraints; generationOfBirth = other.generationOfBirth; }
/// <summary> /// Initializes a new instance of the <see cref="ExecutedBlock" /> class. /// </summary> /// <param name="info">The information.</param> /// <param name="call">The call.</param> internal ExecutedBlock(InstructionInfo info, CallContext call) { Info = info; Call = call; }
HashSet <Function> GetCalls2(Function startFunction) { HashSet <Function> calls = new HashSet <Function>(); int address = startFunction.Address; int lastAddress = ainFile.Code.Length; InstructionInfo previousInstructionInfo = default(InstructionInfo); if (address < lastAddress) { previousInstructionInfo = Decompiler.Peek(ainFile.Code, address); } while (address < lastAddress) { int functionIndex = -1; var instructionInfo = Decompiler.Peek(ainFile.Code, address); if (instructionInfo.instruction == Instruction.FUNC || instructionInfo.instruction == Instruction.ENDFUNC) { break; } if (instructionInfo.instruction == Instruction.CALLFUNC || instructionInfo.instruction == Instruction.CALLMETHOD) { functionIndex = instructionInfo.word1; } if (instructionInfo.instruction == Instruction.CALLONJUMP) { if (previousInstructionInfo.instruction == Instruction.S_PUSH) { int stringIndex = previousInstructionInfo.word1; if (stringIndex >= 0 && stringIndex < ainFile.Strings.Count) { string str = ainFile.Strings[stringIndex]; if (ainFile.FunctionNameToIndex.ContainsKey(str)) { functionIndex = ainFile.FunctionNameToIndex[str]; } } } } if (instructionInfo.instruction == Instruction.FT_ASSIGNS) { if (previousInstructionInfo.instruction == Instruction.PUSH) { int functionTypeNumber = previousInstructionInfo.word1; if (functionTypeNumber >= 0 && functionTypeNumber < ainFile.FunctionTypes.Count) { var stringInstructionInfo = Decompiler.Peek(ainFile.Code, previousInstructionInfo.CurrentAddress - 6); if (stringInstructionInfo.instruction == Instruction.S_PUSH) { int stringNumber = stringInstructionInfo.word1; if (stringNumber >= 0 && stringNumber < ainFile.Strings.Count) { string functionName = ainFile.Strings[stringNumber]; if (ainFile.FunctionNameToIndex.ContainsKey(functionName)) { var function = ainFile.Functions[ainFile.FunctionNameToIndex[functionName]]; functionIndex = function.Index; } } } } } } if (functionIndex >= 0 && functionIndex < ainFile.Functions.Count) { var function = ainFile.Functions[functionIndex]; if (!calls.Contains(function)) { calls.Add(function); } functionIndex = -1; } address = instructionInfo.nextAddress; previousInstructionInfo = instructionInfo; } return(calls); }
private IEnumerable <Group> GroupInstruction() { var code = this._Function.Code; if (_Index >= code.Count) { yield break; } var instruction = code[_Index++]; IEnumerable <Group> enumerable; var chainCount = InstructionInfo.GetChainCount(instruction.Opcode); if (chainCount >= 0) { enumerable = GroupBasicInstruction(chainCount); } else if (instruction.Opcode == Opcode.Constructor) { var(parameterCount, _) = (Constructor)instruction.Argument; enumerable = GroupBasicInstruction(parameterCount); } else if (instruction.Opcode == Opcode.FinalFunc) { var(_, _, function) = (FinalFunc)instruction.Argument; var parameterCount = function.Parameters.Count; parameterCount++; // EndCall enumerable = GroupBasicInstruction(parameterCount); } else if (instruction.Opcode == Opcode.VirtualFunc) { // TODO(gibbed): dodgy af /*var (_, _, name) = ((short, ushort, string))instruction.Argument; * var candidates = this._Cache.Definitions.Where(d => d.Name == name).ToArray(); * if (candidates.Length != 1) * { * enumerable = GroupBasicInstruction(1); * } * else * { * var function = (FunctionDefinition)candidates[0]; * var parameterCount = function.Parameters.Count; * parameterCount++; // EndCall * enumerable = GroupBasicInstruction(parameterCount); * }*/ enumerable = GroupCallNameInstruction(); } else if (instruction.Opcode == Opcode.Switch) { enumerable = GroupSwitchInstruction(); } else if (instruction.Opcode == Opcode.SwitchLabel) { enumerable = GroupSwitchCaseInstruction(); } else if (instruction.Opcode == Opcode.SwitchDefault) { enumerable = GroupSwitchDefaultInstruction(); } else { throw new NotImplementedException(); } var group = new Group(instruction); foreach (var child in enumerable) { group.Children.Add(child); } yield return(group); }
void EnumerateGenericInstruction(InstructionInfo instructionInfo, ArgumentKind overrideKind, ArgumentKind kindToFind, Action <int> addAction) { if (instructionInfo.totalArguments > 0) { if (ArgumentKinds.InstructionArgumentKinds.ContainsKey((int)instructionInfo.instruction)) { var argumentKinds = ArgumentKinds.InstructionArgumentKinds[(int)instructionInfo.instruction]; for (int i = 0; i < instructionInfo.totalArguments; i++) { var argumentKind = argumentKinds[i]; if (overrideKind != 0) { argumentKind = overrideKind; } int word = instructionInfo.words[i]; switch (argumentKind) { case ArgumentKind.AssignInt: argumentKind = ArgumentKind.Int; break; case ArgumentKind.Function: if (word >= 0 && word < ainFile.Functions.Count) { var func = ainFile.Functions[word]; previousStructType = currentStructType; currentStructType = func.StructType; } break; case ArgumentKind.Global: if (word >= 0 && word < ainFile.Globals.Count) { var global = ainFile.Globals[word]; previousStructType = currentStructType; currentStructType = global.StructType; } break; case ArgumentKind.Library: libraryNumber = word; break; case ArgumentKind.LibraryFunction: currentStructType = -1; break; case ArgumentKind.Local: if (word >= 0 && word < locals.Count) { var local = locals[word]; previousStructType = currentStructType; currentStructType = local.StructType; } break; case ArgumentKind.LocalMember: argumentKind = ArgumentKind.Member; currentStructType = currentClass; if (currentStructType >= 0 && currentStructType < ainFile.Structs.Count) { var structInfo = ainFile.Structs[currentStructType]; if (word >= 0 && word < structInfo.Members.Count) { var member = structInfo.Members[word]; previousStructType = currentStructType; currentStructType = member.StructType; } } break; case ArgumentKind.Member: if (currentStructType >= 0 && currentStructType < ainFile.Structs.Count) { var structInfo = ainFile.Structs[currentStructType]; if (word >= 0 && word < structInfo.Members.Count) { var member = structInfo.Members[word]; previousStructType = currentStructType; currentStructType = member.StructType; } } break; case ArgumentKind.StructType: currentStructType = word; break; case ArgumentKind.SystemCall: currentStructType = -1; break; } if (argumentKind == kindToFind) { addAction(word); } } } } }
public FunctionEnumerationResult[] GetFilesAndFunctions() { if (ainFile.Version == 0) { return(GetFilesAndFunctionsVersion0()); } int address = 0; int codeLength = ainFile.Code.Length; HashSet <int> fileNumberSeen = new HashSet <int>(); List <FunctionEnumerationResult> files = new List <FunctionEnumerationResult>(); FunctionEnumerationResult currentFunction = null; FunctionEnumerationResult currentFile = new FunctionEnumerationResult(); currentFile.children = new List <FunctionEnumerationResult>(); currentFile.address = 0; bool wantNewFile = false; InstructionInfo newFileInstruction = null; bool haveFunction = false; while (address < codeLength) { var info = Decompiler.Peek(ainFile.Code, address); if (info.instruction == Instruction.EOF) { if (!fileNumberSeen.Contains(info.word1)) { fileNumberSeen.Add(info.word1); if (wantNewFile) { FinishFile(address, files, ref currentFunction, ref currentFile, newFileInstruction); wantNewFile = false; newFileInstruction = null; } wantNewFile = true; newFileInstruction = info; } } if (info.instruction == Instruction.FUNC) { if (wantNewFile) { FinishFile(address, files, ref currentFunction, ref currentFile, newFileInstruction); wantNewFile = false; newFileInstruction = null; } FinishFunction(address, ref currentFunction, currentFile); if (info.word1 >= 0 && info.word1 < ainFile.Functions.Count) { currentFunction = new FunctionEnumerationResult(); currentFunction.id = info.word1; currentFunction.name = ainFile.Functions[info.word1].Name; currentFunction.address = address; } } //if (info.instruction == Instruction.ENDFUNC) //{ // FinishFunction(address, ref currentFunction, currentFile); //} address = info.nextAddress; } if (currentFile.children.Count > 0) { if (String.IsNullOrEmpty(currentFile.name)) { currentFile.name = "remaining.jaf"; } FinishFile(address, files, ref currentFunction, ref currentFile, newFileInstruction); //files.Add(currentFile); } return(files.ToArray()); }
public static InstructionInfo GetInstructionInfo(string FormID) { InstructionInfo info = null; SqlParameter[] parameters = new SqlParameter[] { new SqlParameter("@FormID", System.Data.SqlDbType.NVarChar, 100), }; parameters[0].Value = FormID; DataTable dataTable = DBHelper.ExecutedProcedure("Biz.ERP_Instruction_Get", parameters); ///给实体赋值 if (dataTable != null && dataTable.Rows.Count > 0) { info = new InstructionInfo(); if (dataTable.Rows[0]["FormId"] != null && dataTable.Rows[0]["FormId"].ToString() != "") { info.FormId = dataTable.Rows[0]["FormId"].ToString(); } if (dataTable.Rows[0]["IsReport"] != null && dataTable.Rows[0]["IsReport"].ToString() != "") { info.IsReport = int.Parse(dataTable.Rows[0]["IsReport"].ToString()); } if (dataTable.Rows[0]["ErpFormId"] != null && dataTable.Rows[0]["ErpFormId"].ToString() != "") { info.ErpFormId = dataTable.Rows[0]["ErpFormId"].ToString(); } if (dataTable.Rows[0]["ErpFormType"] != null && dataTable.Rows[0]["ErpFormType"].ToString() != "") { info.ErpFormType = dataTable.Rows[0]["ErpFormType"].ToString(); } if (dataTable.Rows[0]["StartDeptId"] != null && dataTable.Rows[0]["StartDeptId"].ToString() != "") { info.StartDeptId = dataTable.Rows[0]["StartDeptId"].ToString(); } if (dataTable.Rows[0]["DeptName"] != null && dataTable.Rows[0]["DeptName"].ToString() != "") { info.ErpFormId = dataTable.Rows[0]["DeptName"].ToString(); } if (dataTable.Rows[0]["UserName"] != null && dataTable.Rows[0]["UserName"].ToString() != "") { info.StartDeptId = dataTable.Rows[0]["UserName"].ToString(); } if (dataTable.Rows[0]["CreateTime"] != null && dataTable.Rows[0]["CreateTime"].ToString() != "") { info.CreateTime = DateTime.Parse(dataTable.Rows[0]["CreateTime"].ToString()); } if (dataTable.Rows[0]["LeadersSelected"] != null && dataTable.Rows[0]["LeadersSelected"].ToString() != "") { info.ErpFormType = dataTable.Rows[0]["LeadersSelected"].ToString(); } if (dataTable.Rows[0]["ApproveResult"] != null && dataTable.Rows[0]["ApproveResult"].ToString() != "") { info.ApproveResult = dataTable.Rows[0]["ApproveResult"].ToString(); } if (dataTable.Rows[0]["IsCheckedChairman"] != null && dataTable.Rows[0]["IsCheckedChairman"].ToString() != "") { info.IsReport = int.Parse(dataTable.Rows[0]["IsCheckedChairman"].ToString()); } } return(info); }
public Expression GetExpression(InstructionInfo info, IExpressionLibraryRegistry expressionLibraries) { var programControl = expressionLibraries.GetLibrary<IProgramControlExpressionLibrary>(); List<Expression> expressions = new List<Expression>(); expressions.Add(Expression.Call(debugWriteMethod, Expression.Constant("PC: "))); switch (info.ParameterMode) { case InstructionParameterMode.None: expressions.Add(Expression.Call(debugWriteMethod, Expression.TypeAs(Expression.Subtract(programControl.ProgramCounterRegister, Expression.Constant(1)), typeof(Object)))); break; case InstructionParameterMode.Byte: expressions.Add(Expression.Call(debugWriteMethod, Expression.TypeAs(Expression.Subtract(programControl.ProgramCounterRegister, Expression.Constant(2)), typeof(Object)))); break; case InstructionParameterMode.Word: expressions.Add(Expression.Call(debugWriteMethod, Expression.TypeAs(Expression.Subtract(programControl.ProgramCounterRegister, Expression.Constant(3)), typeof(Object)))); break; case InstructionParameterMode.Index: expressions.Add(Expression.Call(debugWriteMethod, Expression.TypeAs(Expression.Subtract(programControl.ProgramCounterRegister, Expression.Constant(2)), typeof(Object)))); break; case InstructionParameterMode.Address: expressions.Add(Expression.Call(debugWriteMethod, Expression.TypeAs(Expression.Subtract(programControl.ProgramCounterRegister, Expression.Constant(3)), typeof(Object)))); break; case InstructionParameterMode.IndexAndByte: expressions.Add(Expression.Call(debugWriteMethod, Expression.TypeAs(Expression.Subtract(programControl.ProgramCounterRegister, Expression.Constant(3)), typeof(Object)))); break; default: break; } expressions.Add(Expression.Call(debugWriteMethod, Expression.Constant("\t"))); expressions.Add(Expression.Call(debugWriteMethod, Expression.Constant(String.Format("0x{0:X2}", info.Opcode)))); expressions.Add(Expression.Call(debugWriteMethod, Expression.Constant("\t"))); expressions.Add(Expression.Call(debugWriteMethod, Expression.Constant(info.Mnemonic.PadRight(15)))); switch (info.ParameterMode) { case InstructionParameterMode.None: break; case InstructionParameterMode.Byte: expressions.Add(Expression.Call(debugWriteMethod, Expression.Constant("\tn = "))); expressions.Add(Expression.Call(debugWriteMethod, Expression.TypeAs(programControl.ParameterByte1, typeof(Object)))); break; case InstructionParameterMode.Word: expressions.Add(Expression.Call(debugWriteMethod, Expression.Constant("\tnn = "))); expressions.Add(Expression.Call(debugWriteMethod, Expression.TypeAs(programControl.ParameterWord, typeof(Object)))); break; case InstructionParameterMode.Index: expressions.Add(Expression.Call(debugWriteMethod, Expression.Constant("\td = "))); expressions.Add(Expression.Call(debugWriteMethod, Expression.TypeAs(programControl.ParameterByte1, typeof(Object)))); break; case InstructionParameterMode.Address: expressions.Add(Expression.Call(debugWriteMethod, Expression.Constant("\taddress = "))); expressions.Add(Expression.Call(debugWriteMethod, Expression.TypeAs(programControl.ParameterWord, typeof(Object)))); break; case InstructionParameterMode.IndexAndByte: expressions.Add(Expression.Call(debugWriteMethod, Expression.Constant("\tindex = "))); expressions.Add(Expression.Call(debugWriteMethod, Expression.TypeAs(programControl.ParameterByte2, typeof(Object)))); expressions.Add(Expression.Call(debugWriteMethod, Expression.Constant("\tn = "))); expressions.Add(Expression.Call(debugWriteMethod, Expression.TypeAs(programControl.ParameterByte1, typeof(Object)))); break; default: break; } expressions.Add(Expression.Call(debugWriteMethod, Expression.Constant(Environment.NewLine))); return Expression.Block(expressions); //return Expression.PostIncrementAssign(programControl.ParameterByte1); }
private void ParseLine(Scanner s) { tokStream = s.Tokens; var lblText = string.Empty; if (tokStream.First().Type == TokenType.LABEL) { lblText = tokStream.First().Text; if (lblText.Length == 2 && char.IsDigit(lblText[0]) && lblText[1] == 'H') // This is a local symbol { var n = byte.Parse(lblText[0].ToString()); if (localSymbs.ContainsKey(n)) { localSymbs[n] = localSymbs[n] + 1; } else { localSymbs.Add(n, 1); } lblText = "|" + n + "-" + localSymbs[n] + "|"; } if (tokStream.Skip(1).ToArray().Length > 0) { symbolTable.Add(lblText, new MIXWord(locCounter)); tokStream = tokStream.Skip(1); } else { errors.Add(new ErrorInfo { Column = tokStream.First().ColumnNumber, Line = LineNumber, Text = "LINE: Unexpected end of line, expected: KEYWORD or PSEUDO" }); } } // Parse the rest of the sentence switch (tokStream.First().Type) { case TokenType.KEYWORD: var instrList = from i in MIXMachine.INSTRUCTION_LIST where i.Name == tokStream.First().Text select i; InstructionInfo instr = instrList.First(); tokStream = tokStream.Skip(1); MIXWord a = Address(); MIXWord index = Index(); MIXWord f = Field(); if (f == -1) { f = instr.DefaultField; } MIXWord word = new MIXWord(); if (a != null) { word[0, 2] = a; word[3] = index; word[4] = f; word[5] = instr.OpCode; assembly.Add(new MemoryCell { SourceLocation = LineNumber, Location = locCounter, Contents = word }); } else { futureRefs.Add(new FutureReference { Symbol = FRefSymb, Field = f, Index = index, Location = locCounter, OpCode = instr.OpCode, SourceLocation = LineNumber }); } locCounter++; break; case TokenType.ORIG: tokStream = tokStream.Skip(1); locCounter = WordValue(); break; case TokenType.CON: tokStream = tokStream.Skip(1); assembly.Add(new MemoryCell { SourceLocation = LineNumber, Location = locCounter, Contents = WordValue() }); locCounter++; break; case TokenType.EQU: tokStream = tokStream.Skip(1); var val = WordValue(); if (!string.IsNullOrEmpty(lblText)) { symbolTable[lblText] = val; } break; case TokenType.ALF: tokStream = tokStream.Skip(1); if (tokStream.First().Type != TokenType.STRING) { errors.Add(new ErrorInfo { Line = LineNumber, Column = tokStream.First().ColumnNumber, Text = "LINE: Expected: STRING CONSTANT." }); } else { string sc = tokStream.First().Text; MIXWord w = new MIXWord(); for (byte i = 0; i < 5; i++) { w[(byte)(i + 1)] = MIXMachine.CHAR_TABLE[sc[i]]; } assembly.Add(new MemoryCell { SourceLocation = LineNumber, Location = locCounter, Contents = w }); locCounter++; tokStream = tokStream.Skip(1); } break; case TokenType.END: if (null != StartLoc) { warnings.Add(new ErrorInfo { Line = LineNumber, Column = tokStream.First().ColumnNumber, Text = "LINE: Multiple appearances of the END directive." }); } tokStream = tokStream.Skip(1); StartLoc = WordValue(); insertionPoint = locCounter; break; default: errors.Add(new ErrorInfo { Line = LineNumber, Column = tokStream.First().ColumnNumber, Text = string.Format("LINE: Parser panic! Don't know what to do with token {0}['{1}']", tokStream.First().Type, tokStream.First().Text) }); break; } }
/// <summary> /// Create new instruction info for block starting with next emitted instruction. /// </summary> /// <returns>Created instruction info.</returns> public override InstructionInfo StartNewInfoBlock() { _currentBlockInfo = new InstructionInfo(_currentGroupID); return(_currentBlockInfo); }
// \param indirectCall is not -1 if the instruction is an indirect call to another function public static void dispatch( GlobalInterpreterState globalState, LocalInterpreterState localState, Instruction instr, out bool success, out int indirectCall ) { indirectCall = -1; uint instructionWithoutRelative; int relative; decodeInstruction(instr.code, out instructionWithoutRelative, out relative); switch (instructionWithoutRelative) { case INSTRUCTION_RET: Operations.@return(localState, out success); return; case 1: ArrayOperations.macroArrayAdvanceOrExit(globalState, localState, relative, out success); return; case 2: ArrayOperations.macroArrayNotEndOrExit(globalState, localState, relative, out success); return; case 3: Operations.jump(localState, relative); success = true; return; case 4: Operations.jumpIfNotFlag(localState, relative); success = true; return; case 5: Operations.call(localState, relative); success = true; return; case 6: ArrayOperationsTwoArgumentWrapper.arrayMove(globalState, localState, -1, int.MaxValue, out success); return; case 7: ArrayOperationsTwoArgumentWrapper.arrayMove(globalState, localState, 1, int.MaxValue, out success); return; case 8: ArrayOperationsTwoArgumentWrapper.arrayRemove(globalState, localState, int.MaxValue, int.MaxValue, out success); return; case 9: ArrayOperationsTwoArgumentWrapper.arrayCompareWithRegister(globalState, localState, 0, int.MaxValue, out success); return; case 10: ArrayOperationsTwoArgumentWrapper.arrayCompareWithRegister(globalState, localState, 1, int.MaxValue, out success); return; case 11: ArrayOperations.insert(globalState, localState, /*reg*/ 0, out success); return; case 12: ArrayOperations.insert(globalState, localState, /*reg*/ 1, out success); return; case 13: ArrayOperations.insert(globalState, localState, /*reg*/ 2, out success); return; case 14: ArrayOperations.setIdxRelative(globalState, localState, 0, 0, out success); return; case 15: ArrayOperations.setIdxRelative(globalState, localState, 0, -1, out success); return; // -1 is end of array case 16: ArrayOperations.idxFlag(globalState, localState, 0, 1, out success); return; // TODO< should be an intrinsic command which gets added by default > case 17: ArrayOperations.valid(globalState, localState, /*array*/ 0, out success); return; case 18: ArrayOperations.read(globalState, localState, /*array*/ 0, /*register*/ 0, out success); return; case 19: ArrayOperations.idx2Reg(globalState, localState, /*array*/ 0, /*register*/ 0, out success); return; case 20: Operations.movImmediate(localState, /*register*/ 0, 0, out success); return; case 21: Operations.movImmediate(localState, /*register*/ 0, 1, out success); return; case 22: Operations.movImmediate(localState, /*register*/ 0, 3, out success); return; case 23: ArrayOperations.arrayMovToArray(globalState, localState, /*array*/ 0, /*register*/ 0, out success); return; case 24: Operations.mulRegisterImmediate(localState, /*register*/ 0, -1); success = true; return; case 25: Operations.binaryNegate(globalState, localState, /*register*/ 0); success = true; return; case 26: ArrayOperations.macroArrayAdvanceOrExit(globalState, localState, -4, out success); return; case 27: Operations.movImmediate(localState, /*register*/ 1, 0, out success); return; case 28: Operations.movImmediate(localState, /*register*/ 1, 1, out success); return; case 29: Operations.movImmediate(localState, /*register*/ 1, 3, out success); return; case 30: ArrayOperations.read(globalState, localState, /*array*/ 0, /*register*/ 1, out success); return; case 31: Operations.mulRegisterRegister(localState, 0, 1); success = true; return; case 32: Operations.addRegisterRegister(localState, 0, 1); success = true; return; case 33: ArrayOperations.arrayMovToArray(globalState, localState, /*array*/ 0, /*register*/ 1, out success); return; case 34: Operations.subRegisterRegister(localState, 1, 0); success = true; return; case 35: ArrayOperations.read(globalState, localState, /*array*/ 0, /*register*/ 1, out success); return; case 36: ArrayOperations.reg2idx(globalState, localState, /*register*/ 0, /*array*/ 0, out success); return; case 37: Operations.compareRegister(localState, /*register*/ 0, /*register*/ 1, /*type*/ -1); success = true; return; // TODO< maybe using relative value as immediate > case 38: Operations.random(globalState, localState, 0, 0, out success); return; case 39: ArrayOperations.length(globalState, localState, /*destRegister*/ 0, out success); return; } // if we are here we have instrution with hardcoded parameters uint baseInstruction = InstructionInfo.getNumberOfHardcodedSingleInstructions(); Debug.Assert(instructionWithoutRelative >= baseInstruction); int currentBaseInstruction = (int)baseInstruction; // add register constant if (instructionWithoutRelative <= currentBaseInstruction + 3) { int subInstruction = (int)instructionWithoutRelative - currentBaseInstruction; // which instruction do we choose from the pool if (subInstruction == 0) { Operations.add(localState, /*register*/ 0, -1); success = true; } else if (subInstruction == 1) { Operations.add(localState, /*register*/ 0, 2); success = true; } else if (subInstruction == 2) { Operations.add(localState, /*register*/ 1, -1); success = true; } } currentBaseInstruction += 3; // addFlag reg0 constant if (instructionWithoutRelative <= currentBaseInstruction + 1) { // currently just compare reg0 with zero Operations.addFlag(localState, /*register*/ 0, 1); success = true; return; } currentBaseInstruction += 1; // indirect table call if (instructionWithoutRelative <= currentBaseInstruction + 1) { // currently just compare reg0 with zero indirectCall = 0; success = true; return; } currentBaseInstruction += 1; // additional instructions GlobalInterpreterState.AdditionalOperationsDelegateType additionalOperationDelegate; if (globalState.additionalOperations.TryGetValue(instructionWithoutRelative, out additionalOperationDelegate)) { additionalOperationDelegate(globalState, localState, out success); return; } // unknown instruction success = false; }
private void lbxAllInstruct_MouseDoubleClick(object sender, MouseEventArgs e) { InstructionInfo II = ((InstructionInfo)lbxAllInstruct.SelectedElement); lbxSwitchInstruct.AddItem(new InstructElement(II.NewInstruction, II.NewInstructionNum)); }
List <Instruction> GetInstructions(SbAddress sbAddress, uint numInstructions, bool withSource) { _lineEntryCache.Clear(); var instructions = new List <Instruction>(); // If we need source information, we look at the previous instruction to find out // if it is on the same line and/or in the same file. var position = SourcePosition.Empty; if (withSource) { // Find previous instruction and initialize lineAddress and lastLine here. SbAddress previousSbAddress = _target.ResolveLoadAddress(sbAddress.GetLoadAddress(_target) - 1); if (previousSbAddress != null) { position = GetPositionForAddress(previousSbAddress); } } uint numInstructionsRead = 0; List <InstructionInfo> cachedInstructions = _target.ReadInstructionInfos(sbAddress, numInstructions, _flavor); for (int i = 0; i < cachedInstructions.Count; i++) { Instruction currentInstruction = new Instruction(); if (numInstructionsRead >= numInstructions) { break; } numInstructionsRead++; InstructionInfo instruction = cachedInstructions[i]; _lineEntryCache.Add(instruction.Address, instruction.LineEntry); currentInstruction.Address = instruction.Address; // Since Visual Studio doesn't do a good job formatting opcode and operands, in // addition to not providing a field to show instruction comments, do all the // formatting ourselves and put the entire string in the opcode field. string operands = instruction.Operands; string comment = instruction.Comment; string instructionString = $"{instruction.Mnemonic,-10}"; if (string.IsNullOrEmpty(comment)) { instructionString += $" {operands}"; } else { instructionString += $" {operands,-30} # {comment}"; } currentInstruction.Text = instructionString; if (!string.IsNullOrEmpty(instruction.SymbolName)) { currentInstruction.Symbol = instruction.SymbolName; } // If we so far believe we should get source position, let us get it here. if (withSource) { SourcePosition lastPosition = position; position = GetPositionFor(instruction.LineEntry); WritePositionToInstruction(lastPosition, position, i == 0, ref currentInstruction); } instructions.Add(currentInstruction); } return(instructions); }
void Format(int index, InstructionInfo info, string formattedString) => FormatBase(index, info, formattedString, GasFormatterFactory.Create_NoSuffix());
public int Seek(enum_SEEK_START seekStart, IDebugCodeContext2 codeContext, ulong codeLocationId, long numInstructions) { if (seekStart == enum_SEEK_START.SEEK_START_CODECONTEXT) { _address = codeContext.GetAddress(); } else if (seekStart == enum_SEEK_START.SEEK_START_CODELOCID) { _address = codeLocationId; } SbAddress sbAddress = _target.ResolveLoadAddress(_address); if (sbAddress == null) { return(VSConstants.E_FAIL); } if (numInstructions > 0) { // seek forward numInstructions++; List <InstructionInfo> instructions = _target.ReadInstructionInfos(sbAddress, (uint)numInstructions, _flavor); if (instructions.Count > 0) { numInstructions = Math.Min(numInstructions, instructions.Count); _address = instructions[(int)numInstructions - 1].Address; } } else if (numInstructions < 0) { // TODO: Get opcode sizes from LLDB. // Hard-code the opcode sizes for x86_64. Currently LLDB doesn't expose this // information, and this is the only architecture we support. uint minOpcodeSize = 1; uint maxOpcodeSize = 15; // When seeking backwards we don't know the exact address since x86_64 is a variable // size instruction architecture. Instead we figure out the max range to fit a // specific number of instructions. uint maxRangeForInstructions = (uint)Math.Abs(numInstructions) * maxOpcodeSize; // Since x86_64 is a variable size instruction architecture we don't know the exact // number of instructions in a specific address range. Assume the smallest opcode // size and that will be the number of instructions we need to read. uint maxNumberInstructions = maxRangeForInstructions / minOpcodeSize; // Using the start address and the max possible range, we can determine the lower // bound for where we should start reading instructions from. ulong endAddress = _address - maxRangeForInstructions; // The instruction where we should start the seek. List <InstructionInfo> startInstructionList = _target.ReadInstructionInfos(sbAddress, 1, _flavor); if (startInstructionList.Count == 0) { Trace.WriteLine( "Failed to seek backwards. Unable to read " + $"instruction at 0x{_address:X} so we have no start point for the seek"); return(VSConstants.E_FAIL); } InstructionInfo startInstruction = startInstructionList[0]; // We know there is an instruction around the |endAddress| but we don't know exactly // where it starts (because variable size instructions). LLDB will stop reading if // it runs into a bad instruction. We use that to our advantage and start reading // instructions from the |endAddress| + offset until LLDB returns us the number of // instructions we requested. We can then be fairly certain |endAddress| + offset is // the address to a valid instruction. int startIndex = -1; List <InstructionInfo> validInstructions = null; for (ulong i = 0; i < maxOpcodeSize; i++) { ulong seekAddress = endAddress + i; SbAddress seekSbAddress = _target.ResolveLoadAddress(seekAddress); List <InstructionInfo> instructions = _target.ReadInstructionInfos( seekSbAddress, maxNumberInstructions + 1, _flavor); // Shortcut: Continue if we did not get enough instructions. if (instructions == null || instructions.Count < Math.Abs(numInstructions)) { continue; } // Only accept the instructions if our start instruction is there. try { startIndex = instructions.BinarySearch(startInstruction, new InstructionComparator()); if (startIndex >= 0) { validInstructions = instructions; break; } } catch (InvalidOperationException e) { Trace.WriteLine(e); } } if (startIndex < 0) { Trace.WriteLine( "Failed to seek backwards. Unable to find an instruction with " + $"address 0x{_address:X} so we have no start point for the seek"); return(VSConstants.E_FAIL); } // Add the |startIndex| and the negative |numInstructions| to get the index of the // instruction to which we want to seek. int seekIndex = startIndex + (int)numInstructions; if (validInstructions == null || seekIndex < 0 || seekIndex >= validInstructions.Count) { Trace.WriteLine($"Failed to seek backwards. Seek index {seekIndex} is out " + "of range"); return(VSConstants.E_FAIL); } _address = validInstructions[seekIndex].Address; } return(VSConstants.S_OK); }
private static void GetNextRandomInstruction(FastRandom rnd, ref InstructionInfo EncInstruction, ref InstructionInfo DecInstruction) { lock (RndInstLock) { Instruction[] InstructionList = new Instruction[] { //Instruction.BitLeft, //unstable do not use Instruction.Minus, Instruction.Plus, //Instruction.ForLoop_PlusMinus, //Instruction.RotateLeft_Big, //Instruction.RotateLeft_Small, Instruction.SwapBits, Instruction.XOR }; Instruction inst = InstructionList[rnd.Next(0, InstructionList.Length)]; switch (inst) { case Instruction.BitLeft: { int bitSize = rnd.Next(1, 3); //maybe needs to be higher ? EncInstruction = new InstructionInfo(inst, bitSize); DecInstruction = new InstructionInfo(Instruction.BitRight, bitSize); break; } case Instruction.Minus: { byte[] TempDate = new byte[32]; rnd.NextBytes(TempDate); EncInstruction = new InstructionInfo(inst, new BigInteger(TempDate)); DecInstruction = new InstructionInfo(Instruction.Plus, new BigInteger(TempDate)); break; } case Instruction.Plus: { byte[] TempDate = new byte[32]; rnd.NextBytes(TempDate); EncInstruction = new InstructionInfo(inst, new BigInteger(TempDate)); DecInstruction = new InstructionInfo(Instruction.Minus, new BigInteger(TempDate)); break; } case Instruction.ForLoop_PlusMinus: { int size = rnd.Next(); int size2 = rnd.Next(); int loops = rnd.Next(2, 255); EncInstruction = new InstructionInfo(inst, (uint)size, (uint)size2, loops); DecInstruction = new InstructionInfo(inst, (uint)size, (uint)size2, loops); break; } case Instruction.RotateLeft_Big: { byte bitSize = (byte)rnd.Next(1, 60); EncInstruction = new InstructionInfo(inst, (uint)bitSize); DecInstruction = new InstructionInfo(Instruction.RotateRight_Big, (uint)bitSize); break; } case Instruction.RotateLeft_Small: { byte bitSize = (byte)rnd.Next(1, 30); EncInstruction = new InstructionInfo(inst, (uint)bitSize); DecInstruction = new InstructionInfo(Instruction.RotateRight_Small, (uint)bitSize); break; } case Instruction.SwapBits: { EncInstruction = new InstructionInfo(inst, 0); DecInstruction = new InstructionInfo(inst, 0); break; } case Instruction.XOR: { byte[] TempDate = new byte[32]; rnd.NextBytes(TempDate); EncInstruction = new InstructionInfo(inst, new BigInteger(TempDate)); DecInstruction = new InstructionInfo(inst, new BigInteger(TempDate)); break; } default: { break; } } } }
private static void AddInstruction(InstructionSyntaxType type, string name, uint functionOrOpcode, string help) { Instructions[name] = new InstructionInfo(type, functionOrOpcode, help); }
void Format(int index, InstructionInfo info, string formattedString) => FormatBase(index, info, formattedString, MasmFormatterFactory.Create_NoMemSize());
public List <InstructionInfo> ReadInstructionInfos(SbAddress address, uint count, string flavor) { SbProcess process = _sbTarget.GetProcess(); var instructions = new List <InstructionInfo>(); while (instructions.Count < count) { SbMemoryRegionInfo memoryRegion = null; SbError error = process.GetMemoryRegionInfo(address.GetLoadAddress(_sbTarget), out memoryRegion); if (error.Fail()) { Trace.WriteLine("Unable to retrieve memory region info."); return(new List <InstructionInfo>()); } // If the address we are given is not mapped we should not try to disassemble it. if (!memoryRegion.IsMapped()) { uint instructionsLeft = count - (uint)instructions.Count; ulong nextAddress = AddUnmappedInstructions(address, instructionsLeft, memoryRegion, instructions); address = _sbTarget.ResolveLoadAddress(nextAddress); // Continue in case we still need more instructions continue; } List <SbInstruction> sbInstructions = _sbTarget.ReadInstructions(address, count - (uint)instructions.Count, flavor); foreach (SbInstruction sbInstruction in sbInstructions) { SbAddress sbAddress = sbInstruction.GetAddress(); if (sbAddress == null) { // It should never happen that we cannot get an address for an instruction Trace.WriteLine("Unable to retrieve address."); return(new List <InstructionInfo>()); } ulong instructionAddress = sbAddress.GetLoadAddress(_sbTarget); SbSymbol symbol = sbAddress.GetSymbol(); string symbolName = null; // Only set symbolName if it is the start of a function SbAddress startAddress = symbol?.GetStartAddress(); if (startAddress != null && startAddress.GetLoadAddress(_sbTarget) == instructionAddress) { symbolName = symbol.GetName(); } SbLineEntry lineEntry = sbAddress.GetLineEntry(); LineEntryInfo lineEntryInfo = null; if (lineEntry != null) { lineEntryInfo = new LineEntryInfo { FileName = lineEntry.GetFileName(), Directory = lineEntry.GetDirectory(), Line = lineEntry.GetLine(), Column = lineEntry.GetColumn(), }; } // Create a new instruction and fill in the values var instruction = new InstructionInfo { Address = instructionAddress, Operands = sbInstruction.GetOperands(_sbTarget), Comment = sbInstruction.GetComment(_sbTarget), Mnemonic = sbInstruction.GetMnemonic(_sbTarget), SymbolName = symbolName, LineEntry = lineEntryInfo, }; instructions.Add(instruction); } // If we haven't managed to retrieve all the instructions we wanted, add // an invalid instruction and keep going from the next address. if (instructions.Count < count) { ulong nextAddress = AddInvalidInstruction(address, sbInstructions, instructions); // Set the address to the next address after the invalid instruction address = _sbTarget.ResolveLoadAddress(nextAddress); } } return(instructions); }
public InstructionDynarecInfo(InstructionInfo InstructionInfo, uint[] Params) { this.InstructionInfo = InstructionInfo; this.Params = Params; //this.GenerateDynarecCode = GenerateDynarecCode; }
protected override Expression GetExpressionImpl(InstructionInfo info, IExpressionLibraryRegistry expressionLibraries) { throw new NotImplementedException(); }