private static ASMAddEquivalenceResult AddEquivalenceGeneric(Dictionary <string, string> eqvDict, string eqvName, string eqvValue) { ASMAddEquivalenceResult result = new ASMAddEquivalenceResult(); try { eqvName = ASMStringHelper.RemoveSpaces(eqvName); //.ToUpper(); if (!eqvDict.ContainsKey(eqvName)) { eqvDict.Add(eqvName, eqvValue); } else { eqvDict[eqvName] = eqvValue; } } catch { result.ErrorCode = 1; result.ErrorMessage = "Error adding equivalence " + eqvName + ": Equivalence already exists!\r\n"; return(result); } result.ErrorCode = 0; return(result); }
public string[] AddLabelLines(string[] lines) { List <string> resultLines = new List <string>(); foreach (string line in lines) { string modLine = ASMStringHelper.RemoveLeadingBracketBlock(line); string processLine = ASMStringHelper.RemoveLeadingSpaces(modLine); processLine = ASMStringHelper.RemoveComment(processLine); //if ((!processLine.StartsWith("#")) && (!processLine.StartsWith(";"))) if (processLine.Contains(":")) { string[] newResultLines = line.Split(':'); int newResultLinesLength = newResultLines.Length; for (int i = 0; i < newResultLinesLength; i++) { string newResultLine = newResultLines[i] + ((i < (newResultLinesLength - 1)) ? ":" : ""); resultLines.Add(newResultLine); } } else { resultLines.Add(line); } } return(resultLines.ToArray()); }
/* * public int LabelToUnsigned(string label) * { * string newLabel = ASMStringHelper.RemoveSpaces(label).ToUpper(); * ASMDebugHelper.assert(LabelDict.ContainsKey(newLabel), "Label not found: " + label); * return LabelDict[newLabel]; * } */ public uint GetAnyUnsignedValue(string val, bool skipLabelAssertion = false) { if ((val.StartsWith("0x")) || (val.StartsWith("-0x"))) { return(ASMValueHelper.HexToUnsigned_AnySign(val, 32)); } else if (ASMStringHelper.StringIsNumeric(val)) { return(Convert.ToUInt32(val)); } else if ((val.StartsWith("-")) && (val.Length > 1)) { string str_uvalue = val.Substring(1); if (ASMStringHelper.StringIsNumeric(str_uvalue)) { uint uvalue = Convert.ToUInt32(str_uvalue); if (uvalue == 0) { return(0); } else { return((uint)(0x100000000 - uvalue)); } } else { return(0); } } else { return(LabelToUnsigned(val, skipLabelAssertion)); } }
private ASMAddLabelResult ProcessLabelStatement(string[] parts) { if (!string.IsNullOrEmpty(parts[0])) { if (parts[0] == ".label") { try { string[] innerParts = parts[1].Split(','); if (!parts[1].Contains(",")) { ASMAddLabelResult errorResult = new ASMAddLabelResult(); errorResult.ErrorCode = 1; errorResult.ErrorMessage = "WARNING: Ignoring .label statement with bad argument list (no comma): \"" + parts[1] + "\"\r\n"; return(errorResult); } string label = ASMStringHelper.RemoveSpaces(innerParts[0]); uint pc = ASMValueHelper.FindUnsignedValueGeneric(ASMStringHelper.RemoveSpaces(innerParts[1])).Value; return(AddLabelGeneric(pc, label)); } catch (Exception ex) { ASMAddLabelResult errorResult = new ASMAddLabelResult(); errorResult.ErrorCode = 1; errorResult.ErrorMessage = "Error on .label statement: " + ex.Message + "\r\n"; return(errorResult); } } } return(null); }
private ASMAddLabelResult AddLabel(uint pc, string[] parts) { ASMAddLabelResult result = new ASMAddLabelResult(); if (ASMStringHelper.RemoveSpaces(parts[0]).EndsWith(":")) { string preLabel = ASMStringHelper.RemoveSpaces(parts[0]).ToUpper(); string label = preLabel.Substring(0, preLabel.Length - 1); result = AddLabelGeneric(pc, label); // Is there an ASM command on this line? If so, advance the PC if (!string.IsNullOrEmpty(parts[1])) { parts = ASMStringHelper.RemoveLabel(parts); // If this is an ASM command, advance the PC EncodingFormat curEncodingOrNull = FormatHelper.FindFormatByCommand(parts[0]); if (curEncodingOrNull != null) { pc += 4; } } } //result.ErrorCode = 0; result.PC = pc; return(result); }
private static ASMAddEquivalenceResult ProcessEquivalenceStatement(Dictionary <string, string> eqvDict, string[] parts) { if (!string.IsNullOrEmpty(parts[0])) { if (parts[0] == ".eqv") { try { string[] innerParts = parts[1].Split(','); if (!parts[1].Contains(",")) { ASMAddEquivalenceResult errorResult = new ASMAddEquivalenceResult(); errorResult.ErrorCode = 1; errorResult.ErrorMessage = "WARNING: Ignoring .eqv statement with bad argument list (no comma): \"" + parts[1] + "\"\r\n"; return(errorResult); } string eqvName = ASMStringHelper.RemoveSpaces(innerParts[0]); string eqvValue = ASMStringHelper.RemoveSpaces(innerParts[1]); return(AddEquivalenceGeneric(eqvDict, eqvName, eqvValue)); } catch (Exception ex) { ASMAddEquivalenceResult errorResult = new ASMAddEquivalenceResult(); errorResult.ErrorCode = 1; errorResult.ErrorMessage = "Error on .eqv statement: " + ex.Message + "\r\n"; return(errorResult); } } } return(null); }
private ASMAddLabelResult AddLabelGeneric(uint pc, string label) { ASMAddLabelResult result = new ASMAddLabelResult(); try { label = ASMStringHelper.RemoveSpaces(label).ToUpper(); if (!PersistentLabelDict.ContainsKey(label)) { LabelDict.Add(label, pc); if (label.StartsWith(PersistentLabelPrefix)) { PersistentLabelDict.Add(label, pc); } } else { PersistentLabelDict[label] = pc; LabelDict[label] = pc; } } catch { result.ErrorCode = 1; result.ErrorMessage = "Error adding label " + label + ": Label already exists!\r\n"; return(result); } result.ErrorCode = 0; result.PC = pc; return(result); }
// Translates pseudoinstructions public ASMTranslatePseudoResult TranslatePseudo(string[] lines, uint startPC, bool skipLabelAssertion = false) { _errorTextBuilder.Length = 0; ASMTranslatePseudoResult result = new ASMTranslatePseudoResult(); List <EncodeLine> resultLines = new List <EncodeLine>(); int index = 0; uint pc = startPC; foreach (string line in lines) { if (string.IsNullOrEmpty(line)) { continue; } string processLine = ASMStringHelper.RemoveLeadingBracketBlock(line); processLine = ASMStringHelper.RemoveLeadingSpaces(processLine); processLine = ASMStringHelper.RemoveComment(processLine).ToLower(); processLine = ASMStringHelper.ConvertBracketBlocks(processLine); string[] parts = ASMStringHelper.SplitLine(processLine); parts = ASMStringHelper.RemoveLabel(parts); //pc = ASMPCHelper.ProcessOrg(pc, parts); ASMProcessPCResult processPCResult = ASMPCHelper.ProcessOrg(pc, parts, false); pc = processPCResult.PC; _errorTextBuilder.Append(processPCResult.ErrorMessage); // If this is an ASM command, pass off line to translating routine EncodingFormat encodingOrNull = FormatHelper.FindFormatByCommand(parts[0]); if (encodingOrNull != null) { // DEBUG 1/16 try { EncodingFormat encoding = encodingOrNull; EncodeLine[] encodeLines = TranslatePseudoSingle(encoding, parts, index, pc, skipLabelAssertion); foreach (EncodeLine encodeLine in encodeLines) { resultLines.Add(encodeLine); pc += 4; } } catch (Exception ex) { //result.errorMessage = "Error translating pseudoinstruction: " + line; _errorTextBuilder.Append("Error translating pseudoinstruction: " + line + " (" + ex.Message + ")\r\n"); //result.lines = null; //return result; } index++; } } result.lines = resultLines.ToArray(); result.errorMessage = _errorTextBuilder.ToString(); return(result); }
private string[] GetASMLinesFromBytes(byte[] bytes, uint pc, bool littleEndian, bool useRegAliases) { string asmText = GetASMTextFromBytes(bytes, pc, littleEndian, useRegAliases); string[] lines = asmText.Split('\n'); lines = ASMStringHelper.RemoveFromLines(lines, "\r"); return(lines); }
public static ASMProcessPCResult ProcessOrg(uint pc, string[] parts, bool reportError = true) { if (!string.IsNullOrEmpty(parts[0])) { if (parts[0] == ".org") { string strArg = ASMStringHelper.RemoveSpaces(parts[1]); return(ProcessPC(pc, strArg, reportError)); } } //return pc; return(new ASMProcessPCResult(pc, "")); }
public static ASMProcessPCResult ProcessPC(uint pc, string strPC, bool reportError = true, bool blankAsZero = false) { ASMProcessPCResult errorResult = new ASMProcessPCResult(0, reportError ? "Starting address \"" + strPC + "\" is invalid; defaulting address to 0.\r\n" : ""); try { /* * if (!string.IsNullOrEmpty(strPC)) * { * if (strPC.StartsWith("0x")) * { * if (strPC.Length >= 10) * pc = ASMValueHelper.HexToUnsigned(strPC.Substring(3,strPC.Length-3)); * else * pc = ASMValueHelper.HexToUnsigned(strPC.Substring(2,strPC.Length-2)); * } * else * pc = Convert.ToUInt32(strPC); * } */ if (blankAsZero) { ASMProcessPCResult zeroResult = new ASMProcessPCResult(0, ""); if (string.IsNullOrEmpty(strPC)) { return(zeroResult); } else if (string.IsNullOrEmpty(ASMStringHelper.RemoveSpaces(strPC))) { return(zeroResult); } } Nullable <uint> uValue = ASMValueHelper.FindUnsignedValueGeneric(strPC); return((uValue == null) ? errorResult : new ASMProcessPCResult(uValue.Value, "")); //pc = ASMValueHelper.FindUnsignedValueGeneric(strPC); } catch { return(errorResult); //return 0; //txt_Messages.Text = "Starting address invalid."; } //return pc; //return new ASMProcessPCResult(pc, ""); }
public static ASMProcessEquivalencesResult ProcessEquivalences(string[] lines) { ASMProcessEquivalencesResult result = new ASMProcessEquivalencesResult(); result.ErrorCode = 0; StringBuilder errorTextBuilder = new StringBuilder(); Dictionary <string, string> eqvDict = new Dictionary <string, string>(); ASMFindEquivalencesResult findEquivalencesResult = FindEquivalences(eqvDict, lines); if (findEquivalencesResult != null) { if (findEquivalencesResult.ErrorCode > 0) { result.ErrorCode = 1; errorTextBuilder.Append(findEquivalencesResult.ErrorMessage); } } List <string> newLines = new List <string>(); foreach (string line in lines) { string processLine = ASMStringHelper.RemoveLeadingBracketBlock(line); processLine = ASMStringHelper.RemoveLeadingSpaces(processLine); processLine = ASMStringHelper.RemoveComment(processLine).ToLower(); string[] parts = ASMStringHelper.SplitLine(processLine); bool isEquivalence = ((!string.IsNullOrEmpty(parts[0])) && (parts[0].ToLower().Trim() == ".eqv")); string newLine = (string)line.Clone(); if (!isEquivalence) { foreach (KeyValuePair <string, string> eqv in eqvDict) { newLine = newLine.Replace(eqv.Key, eqv.Value); } } newLines.Add(newLine); } result.ErrorMessage = errorTextBuilder.ToString(); result.Lines = newLines.ToArray(); return(result); }
public static Nullable <uint> FindUnsignedValueGeneric(string val) { if (val.StartsWith("0x")) { //if (val.Length >= 10) // return HexToUnsigned(val.Substring(3,val.Length-3)); //else return(HexToUnsigned(val.Substring(2, val.Length - 2))); } else if (ASMStringHelper.StringIsNumeric(val)) { return(Convert.ToUInt32(val)); } else { return(null); } }
public static string[] RemoveLabel(string[] parts) { // Remove label portion, if it exists if (!string.IsNullOrEmpty(parts[0])) { if (parts[0].EndsWith(":")) { if (!string.IsNullOrEmpty(parts[1])) { string curLine = ASMStringHelper.RemoveLeadingSpaces(parts[1]); curLine = ASMStringHelper.RemoveComment(curLine); parts = ASMStringHelper.SplitLine(curLine); } } } return(parts); }
public uint LabelToUnsigned(string label, bool skipAssertion = false) { string newLabel = ASMStringHelper.RemoveSpaces(label).ToUpper(); string lowerLabel = newLabel.ToLower(); if (((lowerLabel.StartsWith("%hi(")) || (lowerLabel.StartsWith("%lo("))) && (lowerLabel.Substring(3).Contains(")"))) { string newValue = lowerLabel.Substring(4, lowerLabel.IndexOf(")") - 4).Trim(); uint uValue = GetAnyUnsignedValue(newValue, skipAssertion); return(lowerLabel.StartsWith("%hi(") ? ProcessHi(uValue) : ProcessLo(uValue)); } if (!skipAssertion) { ASMDebugHelper.assert(LabelDict.ContainsKey(newLabel), "Label not found: " + label); } return((uint)(LabelDict.ContainsKey(newLabel) ? LabelDict[newLabel] : 0)); }
public static uint ProcessStartPC(string asm, uint pc) { // If the ASM starts with a .org statement, use that address as the PC string[] lines = asm.Split('\n'); lines = ASMStringHelper.RemoveFromLines(lines, "\r"); foreach (string line in lines) { if (!string.IsNullOrEmpty(line)) { string processLine = ASMStringHelper.RemoveComment(line).ToLower(); string[] parts = ASMStringHelper.SplitLine(processLine); ASMProcessPCResult processPCResult = ASMPCHelper.ProcessOrg(pc, parts); pc = processPCResult.PC; break; } } return(pc); }
private string[] GetASMLines(string asm, uint pc, bool littleEndian, bool useRegAliases, bool reEncode = true) { string asmText = reEncode ? GetASMText(asm, pc, littleEndian, useRegAliases) : asm; string[] lines = asmText.Split('\n'); lines = ASMStringHelper.RemoveFromLines(lines, "\r"); if (!reEncode) { List <string> newLines = new List <string>(lines.Length); foreach (string line in lines) { string newLine = ASMStringHelper.RemoveLeadingBracketBlock(line); newLine = ASMStringHelper.RemoveLeadingSpaces(newLine); newLines.Add(newLine); } lines = newLines.ToArray(); } return(lines); }
private static ASMFindEquivalencesResult FindEquivalences(Dictionary <string, string> eqvDict, string[] lines) { ASMFindEquivalencesResult result = new ASMFindEquivalencesResult(); result.ErrorCode = 0; StringBuilder errorTextBuilder = new StringBuilder(); ClearEquivalenceDict(eqvDict); foreach (string line in lines) { if (string.IsNullOrEmpty(line)) { continue; } string processLine = ASMStringHelper.RemoveLeadingBracketBlock(line); processLine = ASMStringHelper.RemoveLeadingSpaces(processLine); processLine = ASMStringHelper.RemoveComment(processLine).ToLower(); string[] parts = ASMStringHelper.SplitLine(processLine); ASMAddEquivalenceResult processEquivalenceResult = ProcessEquivalenceStatement(eqvDict, parts); if (processEquivalenceResult != null) { if (processEquivalenceResult.ErrorCode > 0) { result.ErrorCode = 1; errorTextBuilder.Append(processEquivalenceResult.ErrorMessage); } } } result.ErrorMessage = errorTextBuilder.ToString(); return(result); }
private string DecodeVFPUPrefixImmediate(int immedValue, int prefixType) { //int iValue = (int)ASMValueHelper.BinaryToUnsigned(immedBinary); int iValue = immedValue; string result = ""; if (prefixType == ASMVFPUPrefix.Type.Destination) { int[] sat = new int[4]; sat[0] = iValue & 0x03; sat[1] = (iValue >> 2) & 0x03; sat[2] = (iValue >> 4) & 0x03; sat[3] = (iValue >> 6) & 0x03; int[] msk = new int[4]; msk[0] = (iValue >> 8) & 0x01; msk[1] = (iValue >> 9) & 0x01; msk[2] = (iValue >> 10) & 0x01; msk[3] = (iValue >> 11) & 0x01; string[] values = new string[4]; for (int i = 0; i < 4; i++) { if (msk[i] == 0) { switch (sat[i]) { case 0: values[i] = ASMVFPUPrefix.Elements[i].ToString(); break; case 1: values[i] = "0:1"; break; case 3: values[i] = "-1:1"; break; default: values[i] = ""; break; } } else { values[i] = "m"; } } result = ASMStringHelper.Concat("[", values[0], ",", values[1], ",", values[2], ",", values[3], "]"); } else if (prefixType == ASMVFPUPrefix.Type.Source) { int[] swz = new int[4]; swz[0] = iValue & 0x03; swz[1] = (iValue >> 2) & 0x03; swz[2] = (iValue >> 4) & 0x03; swz[3] = (iValue >> 6) & 0x03; bool[] abs = new bool[4]; abs[0] = (((iValue >> 8) & 0x01) > 0); abs[1] = (((iValue >> 9) & 0x01) > 0); abs[2] = (((iValue >> 10) & 0x01) > 0); abs[3] = (((iValue >> 11) & 0x01) > 0); bool[] cst = new bool[4]; cst[0] = (((iValue >> 12) & 0x01) > 0); cst[1] = (((iValue >> 13) & 0x01) > 0); cst[2] = (((iValue >> 14) & 0x01) > 0); cst[3] = (((iValue >> 15) & 0x01) > 0); bool[] neg = new bool[4]; neg[0] = (((iValue >> 16) & 0x01) > 0); neg[1] = (((iValue >> 17) & 0x01) > 0); neg[2] = (((iValue >> 18) & 0x01) > 0); neg[3] = (((iValue >> 19) & 0x01) > 0); string[] values = new string[4]; for (int i = 0; i < 4; i++) { if (cst[i]) { switch (swz[i]) { case 0: values[i] = abs[i] ? "3" : "0"; break; case 1: values[i] = abs[i] ? "1/3" : "1"; break; case 2: values[i] = abs[i] ? "1/4" : "2"; break; case 3: values[i] = abs[i] ? "1/6" : "1/2"; break; } } else { string val = ASMVFPUPrefix.Elements[swz[i]].ToString(); values[i] = abs[i] ? ("|" + val + "|") : val; } if (neg[i]) { values[i] = "-" + values[i]; } } result = ASMStringHelper.Concat("[", values[0], ",", values[1], ",", values[2], ",", values[3], "]"); } return(result); }
private string DecodeASMSingle(uint line, uint pc, bool useRegAliases) { _illegalFlag = false; // Find the binary line and format //string binaryLine = ASMValueHelper.HexToBinary_WithLength(line, 32); //uint uBinaryLine = ASMValueHelper.BinaryToUnsigned(binaryLine); EncodingFormat encFormat = FormatHelper.FindFormatByBinary(line); // If we couldn't find the command, it's some kind of mystery! Either not included in // the encoding file, or an illegal instruction. if (encFormat == null) { _errorTextBuilder.AppendLine("WARNING: Unknown command: " + ASMValueHelper.UnsignedToHex_WithLength(line, 8).ToUpper()); return("unknown"); } string newFormat = encFormat.ExpandedFormat; string syntax = encFormat.Syntax; string formatBinary = encFormat.Binary; string newSyntax = syntax; // Loop through syntax field and replace appropriate values int regIndex = 0; int immedIndex = 0; string argValue = ""; //string binaryValue = ""; //string prevBinaryValue = ""; int numericValue = 0; int prevNumericValue = 0; int syntaxLength = syntax.Length; int newIndex = 0; for (int i = 0; i < syntaxLength; i++) { char c = syntax[i]; // If this is a register or immediate, find value to replace in the syntax for the decoding if (char.IsLetter(c)) { int metaType = ASMFormatHelper.FindElementMetaType(c); if (metaType == ASMElementMetaType.Register) { char lookupChar = ASMStringHelper.CreateRegisterChar(regIndex); //int vfpuRegMode = (c == ASMElementTypeCharacter.VFPURegister ? encFormat.VFPURegisterTypes[regIndex] : 0); switch (c) { case ASMElementTypeCharacter.PartialVFPURegister: argValue = DecodePartialVFPURegister(encFormat, line, regIndex, lookupChar); break; case ASMElementTypeCharacter.InvertedSingleBitVFPURegister: numericValue = FindNumericArgValue(line, encFormat.RegisterPositions[regIndex], encFormat.RegisterIncludeMasks[regIndex]); argValue = DecodeInvertedSingleBitVFPURegister(numericValue, encFormat.VFPURegisterTypes[regIndex]); break; case ASMElementTypeCharacter.VFPURegister: numericValue = FindNumericArgValue(line, encFormat.RegisterPositions[regIndex], encFormat.RegisterIncludeMasks[regIndex]); argValue = DecodeRegister(numericValue, c, useRegAliases, encFormat.VFPURegisterTypes[regIndex]); break; default: //int binaryIndex = newFormat.IndexOf(lookupChar); //binaryValue = binaryLine.Substring(binaryIndex, ASMRegisterHelper.GetEncodingBitLength(c)); numericValue = FindNumericArgValue(line, encFormat.RegisterPositions[regIndex], encFormat.RegisterIncludeMasks[regIndex]); argValue = DecodeRegister(numericValue, c, useRegAliases, 0); break; } regIndex++; } else if (metaType == ASMElementMetaType.Immediate) { char lookupChar = ASMStringHelper.CreateImmediateChar(immedIndex); int binaryIndex = newFormat.IndexOf(lookupChar); //prevBinaryValue = binaryValue; prevNumericValue = numericValue; int immedLength = encFormat.ImmediateLengths[immedIndex]; int hexLength = (immedLength + 3) / 4; //binaryValue = binaryLine.Substring(binaryIndex, immedLength); //numericValue = FindNumericArgValue(line, encFormat.ImmediatePositions[immedIndex], ASMValueHelper.GetIncludeMask(encFormat.ImmediateLengths[immedIndex])); numericValue = FindNumericArgValue(line, encFormat.ImmediatePositions[immedIndex], encFormat.ImmediateIncludeMasks[immedIndex]); switch (c) { case ASMElementTypeCharacter.SignedImmediate: argValue = DecodeSignedImmediate(numericValue, hexLength); break; case ASMElementTypeCharacter.UnsignedImmediate: argValue = DecodeUnsignedImmediate(numericValue, hexLength); break; case ASMElementTypeCharacter.BranchImmediate: argValue = DecodeBranchImmediate(numericValue, pc); break; case ASMElementTypeCharacter.JumpImmediate: argValue = DecodeJumpImmediate(numericValue, pc); break; case ASMElementTypeCharacter.DecrementedImmediate: argValue = DecodeDecrementedImmediate(numericValue, hexLength); break; case ASMElementTypeCharacter.ModifiedImmediate: argValue = DecodeModifiedImmediate(numericValue, prevNumericValue, hexLength); break; case ASMElementTypeCharacter.ShiftedImmediate: argValue = DecodeShiftedImmediate(numericValue, encFormat.ShiftedImmediateAmounts[immedIndex], hexLength); break; case ASMElementTypeCharacter.VFPUPrefixImmediate: argValue = DecodeVFPUPrefixImmediate(numericValue, encFormat.VFPUPrefixType); break; default: break; } immedIndex++; } // Replace character in syntax with correct value newSyntax = ASMStringHelper.ReplaceCharAtIndex(newSyntax, newIndex, argValue); newIndex += argValue.Length - 1; } newIndex++; } string spacing = string.IsNullOrEmpty(newSyntax) ? "" : " "; string decoding = encFormat.Command + spacing + newSyntax; if (_illegalFlag) { decoding = "illegal"; _errorTextBuilder.AppendLine(ASMStringHelper.Concat("Illegal instruction: ", line.ToString("x"), ": ", encFormat.Command.ToUpper(), " (", _illegalMessage, ")")); } return(decoding); }
// Translates a single pseudoinstruction public EncodeLine[] TranslatePseudoSingle(EncodingFormat encoding, string[] parts, int index, uint pc, bool skipLabelAssertion = false) { List <EncodeLine> result = new List <EncodeLine>(); int startParenIndex = 0; int endParenIndex = 0; string strImmed = ""; string[] newParts; uint ivalue = 0; //long lvalue = 0; ushort ushortval = 0; //short shortval = 0; bool useNegativeOffset = false; string regS = ""; int argIndex0 = 0; int argIndex1 = 0; bool doesBranchIfEqual = false; bool isStore = false; bool useAT = false; // Find args string strArgs = ""; string[] args = null; if (!string.IsNullOrEmpty(parts[1])) { strArgs = ASMStringHelper.RemoveSpaces(parts[1]); args = strArgs.Split(','); } switch (encoding.Command) { case "jalr": if (args.Length == 1) { //parts[1] = args[0] + ",ra"; parts[1] = "ra," + args[0]; } result.Add(new EncodeLine(parts, index)); break; case "mul": case "div": case "rem": case "mod": if ((encoding.Command == "div") && (args.Length < 3)) { result.Add(new EncodeLine(parts, index)); break; } newParts = new string[2]; newParts[0] = (encoding.Command == "mul") ? "mult" : "div"; newParts[1] = args[1] + "," + args[2]; result.Add(new EncodeLine(newParts, index)); parts[0] = ((encoding.Command == "mul") || (encoding.Command == "div")) ? "mflo" : "mfhi"; parts[1] = args[0]; result.Add(new EncodeLine(parts, index)); break; case "add": case "addu": case "and": case "min": case "max": case "nor": case "or": case "rotrv": case "sllv": case "slt": case "sltu": case "srav": case "srlv": case "sub": case "subu": case "xor": if (args.Length == 2) { parts[1] = args[0] + "," + parts[1]; } result.Add(new EncodeLine(parts, index)); break; case "addi": case "addiu": case "andi": case "ori": case "rotr": case "sll": case "slti": case "sltiu": case "sra": case "srl": case "xori": if (args.Length == 2) { parts[1] = args[0] + "," + parts[1]; } result.Add(new EncodeLine(parts, index)); break; case "bgt": case "blt": case "bge": case "ble": argIndex0 = ((encoding.Command == "bgt") || (encoding.Command == "ble")) ? 1 : 0; argIndex1 = (argIndex0 > 0) ? 0 : 1; doesBranchIfEqual = ((encoding.Command == "bge") || (encoding.Command == "ble")); newParts = new string[2]; newParts[0] = "slt"; newParts[1] = "at," + args[argIndex0] + "," + args[argIndex1]; result.Add(new EncodeLine(newParts, index)); parts[0] = doesBranchIfEqual ? "beq" : "bne"; parts[1] = "at,zero," + args[2]; result.Add(new EncodeLine(parts, index)); break; case "lbu": case "lb": case "lhu": case "lh": case "lw": case "sb": case "sh": case "sw": bool isHiLo = ((args[1].ToLower().StartsWith("%hi")) || (args[1].ToLower().StartsWith("%lo"))); startParenIndex = args[1].IndexOf('(', (isHiLo ? 4 : 0)); // check -1 endParenIndex = args[1].IndexOf(')', (startParenIndex >= 0) ? startParenIndex : 0); isStore = encoding.Command.ToLower().StartsWith("s"); useAT = ((startParenIndex >= 0) || (isStore)); if (startParenIndex >= 0) { regS = args[1].Substring(startParenIndex + 1, endParenIndex - startParenIndex - 1); strImmed = args[1].Substring(0, startParenIndex); } else { strImmed = args[1]; } ivalue = ValueHelper.GetAnyUnsignedValue(strImmed, skipLabelAssertion); bool isLabel = !( ((strImmed.StartsWith("0x")) || (strImmed.StartsWith("-0x"))) || (ASMStringHelper.StringIsNumeric(strImmed)) || ((strImmed.StartsWith("-")) && (strImmed.Length > 1)) || (isHiLo) ); if (((ivalue > 0x7fff) && (strImmed[0] != '-') && (!isHiLo)) || isLabel) { ushortval = (ushort)(ivalue & 0xffff); if (ushortval >= 0x8000) { useNegativeOffset = true; ushortval = (ushort)(0x10000 - ushortval); } newParts = new string[2]; newParts[0] = "lui"; newParts[1] = (useAT ? "at" : args[0]) + "," + ((ivalue >> 16) + (useNegativeOffset ? 1 : 0)); result.Add(new EncodeLine(newParts, index)); if (startParenIndex >= 0) { newParts = new string[2]; newParts[0] = "addu"; newParts[1] = "at,at," + regS; result.Add(new EncodeLine(newParts, index)); } parts[1] = args[0] + "," + (useNegativeOffset ? "-" : "") + ushortval + "(" + (useAT ? "at" : args[0]) + ")"; result.Add(new EncodeLine(parts, index)); } else { result.Add(new EncodeLine(parts, index)); } break; // "la" always translates to two instructions, while "li" can translate to one. case "la": case "li": //ivalue = ValueHelper.GetAnyUnsignedValue(args[1]); /* * try * { * ivalue = ValueHelper.GetAnyUnsignedValue(args[1]); * //ivalue = ValueHelper.FindUnsignedValue(args[1]); * } * catch * { * ivalue = 0; * } */ ivalue = ValueHelper.GetAnyUnsignedValue(args[1], skipLabelAssertion); bool isLA = encoding.Command.Equals("la"); if (ivalue >= 0xffff8000) { parts[0] = "addiu"; parts[1] = args[0] + ",zero," + ((ushort)(ivalue & 0xffff)); result.Add(new EncodeLine(parts, index)); } else if ((ivalue > 0xffff) || isLA) { newParts = new string[2]; newParts[0] = "lui"; newParts[1] = args[0] + "," + (ivalue >> 16); result.Add(new EncodeLine(newParts, index)); ushortval = (ushort)(ivalue & 0xffff); if ((ushortval > 0) || (isLA)) { parts[0] = "ori"; parts[1] = args[0] + "," + args[0] + "," + ushortval; result.Add(new EncodeLine(parts, index)); } } else { if (!((args[1].StartsWith("0x") || ASMStringHelper.StringIsNumeric(args[1])))) { parts[1] = args[0] + "," + ValueHelper.LabelHelper.LabelToUnsigned(args[1], skipLabelAssertion); } result.Add(new EncodeLine(parts, index)); } break; default: result.Add(new EncodeLine(parts, index)); break; } return(result.ToArray()); }
private ASMSingleEncodeResult EncodeASMSingle(string[] parts, EncodingFormat encoding, uint pc, bool littleEndian) { // Initialize variables //string binary = ""; //string hex = ""; string strArgs = ""; string[] args = null; /* * if (!string.IsNullOrEmpty(parts[1])) * { * strArgs = ASMStringHelper.RemoveSpaces(parts[1]).Replace('(',',').Replace(")",""); * args = strArgs.Split(','); * } */ // Find encoding format and syntax string command = parts[0].ToLower(); EncodingFormat encodingFormat = FormatHelper.FindFormatByCommand(command); string formatBinary = encodingFormat.Binary; string syntax = encodingFormat.Syntax; string newFormat = formatBinary; if (!string.IsNullOrEmpty(parts[1])) { List <string> argsList = new List <string>(); strArgs = ASMStringHelper.RemoveSpaces(parts[1]); bool foundArg = false; int strArgCharIndex = 0; foreach (char currentChar in syntax) { if (Char.IsLetter(currentChar)) { foundArg = true; } else if (foundArg) { foundArg = false; bool isHiLo = ((strArgs.IndexOf("%hi(", strArgCharIndex) == strArgCharIndex) || (strArgs.IndexOf("%lo(", strArgCharIndex) == strArgCharIndex)); int separatorIndex = strArgs.IndexOf(currentChar, strArgCharIndex + (isHiLo ? 4 : 0)); argsList.Add(strArgs.Substring(strArgCharIndex, separatorIndex - strArgCharIndex)); strArgCharIndex = separatorIndex + 1; } } if (foundArg) { argsList.Add(strArgs.Substring(strArgCharIndex, strArgs.Length - strArgCharIndex)); } args = argsList.ToArray(); } // Create array for registers and immediates Nullable <uint>[] regValue = new Nullable <uint> [26]; Nullable <uint>[][] partialRegValue = new Nullable <uint> [26][]; uint[] immedValue = new uint[26]; int argsIndex = 0; int regIndex = 0; int immedIndex = 0; // Fill arrays based on order of arguments (syntax) foreach (char elementTypeChar in syntax) { bool incrementArgsIndex = true; switch (elementTypeChar) { case ASMElementTypeCharacter.GPRegister: regValue[regIndex++] = EncodeGPRegister(args[argsIndex]); break; case ASMElementTypeCharacter.GenericRegister: regValue[regIndex++] = EncodeGenericRegister(args[argsIndex]); break; case ASMElementTypeCharacter.FloatRegister: regValue[regIndex++] = EncodeFloatRegister(args[argsIndex]); break; case ASMElementTypeCharacter.VFPURegister: regValue[regIndex] = EncodeVFPURegister(args[argsIndex], encodingFormat.VFPURegisterTypes[regIndex]); regIndex++; break; case ASMElementTypeCharacter.PartialVFPURegister: partialRegValue[regIndex] = EncodePartialVFPURegister(args[argsIndex], encodingFormat.VFPURegisterTypes[regIndex], encodingFormat.PartialRegisterSizes, encodingFormat.PartialRegisterIncludeMasks[regIndex]); regIndex++; break; case ASMElementTypeCharacter.InvertedSingleBitVFPURegister: regValue[regIndex] = EncodeInvertedSingleBitVFPURegister(args[argsIndex], encodingFormat.VFPURegisterTypes[regIndex]); regIndex++; break; case ASMElementTypeCharacter.Cop0Register: regValue[regIndex] = EncodeCop0Register(args[argsIndex]); regIndex++; break; case ASMElementTypeCharacter.GTEControlRegister: regValue[regIndex] = EncodeGTEControlRegister(args[argsIndex]); regIndex++; break; case ASMElementTypeCharacter.GTEDataRegister: regValue[regIndex] = EncodeGTEDataRegister(args[argsIndex]); regIndex++; break; case ASMElementTypeCharacter.SignedImmediate: case ASMElementTypeCharacter.UnsignedImmediate: immedValue[immedIndex] = EncodeImmediate(args[argsIndex], encodingFormat.ImmediateLengths[immedIndex], (uint)encodingFormat.ImmediateIncludeMasks[immedIndex]); immedIndex++; break; case ASMElementTypeCharacter.BranchImmediate: immedValue[immedIndex] = EncodeBranchImmediate(args[argsIndex], pc, (uint)encodingFormat.ImmediateIncludeMasks[immedIndex]); immedIndex++; break; case ASMElementTypeCharacter.JumpImmediate: immedValue[immedIndex] = EncodeJumpImmediate(args[argsIndex], 26, pc); immedIndex++; break; case ASMElementTypeCharacter.DecrementedImmediate: immedValue[immedIndex] = EncodeDecrementedImmediate(args[argsIndex], encodingFormat.ImmediateLengths[immedIndex], (uint)encodingFormat.ImmediateIncludeMasks[immedIndex]); immedIndex++; break; case ASMElementTypeCharacter.ModifiedImmediate: immedValue[immedIndex] = EncodeModifiedImmediate(args[argsIndex], args[argsIndex - 1], encodingFormat.ImmediateLengths[immedIndex], (uint)encodingFormat.ImmediateIncludeMasks[immedIndex]); immedIndex++; break; case ASMElementTypeCharacter.ShiftedImmediate: immedValue[immedIndex] = EncodeShiftedImmediate(args[argsIndex], encodingFormat.ImmediateLengths[immedIndex], encodingFormat.ShiftedImmediateAmounts[immedIndex], (uint)encodingFormat.ImmediateIncludeMasks[immedIndex]); immedIndex++; break; case ASMElementTypeCharacter.VFPUPrefixImmediate: immedValue[immedIndex] = EncodeVFPUPrefixImmediate(args[argsIndex], encodingFormat.VFPUPrefixType, encodingFormat.ImmediateLengths[immedIndex]); immedIndex++; break; default: incrementArgsIndex = false; break; } if (incrementArgsIndex) { argsIndex++; } } /* * // Replace bracket blocks in format with appropriate values * for (int i = 0; i < regIndex; i++) * { * newFormat = newFormat.Replace("[" + encodingFormat.RegisterTypes[i] + (i + 1) + "]", regBinary[i]); * * if (partialRegBinary[i] != null) * { * newFormat = newFormat.Replace("[" + encodingFormat.RegisterTypes[i] + (i + 1) + "-1]", partialRegBinary[i][0]); * newFormat = newFormat.Replace("[" + encodingFormat.RegisterTypes[i] + (i + 1) + "-2]", partialRegBinary[i][1]); * } * } * for (int i = 0; i < immedIndex; i++) * { * newFormat = newFormat.Replace("[" + encodingFormat.ImmediateTypes[i] + (i + 1) + "]", immedBinary[i]); * } * * binary = newFormat; */ uint uEncodingValue = encodingFormat.BaseEncoding; for (int i = 0; i < regIndex; i++) { if (regValue[i] != null) { uEncodingValue |= (((uint)regValue[i]) << encodingFormat.RegisterPositions[i]); } else if (partialRegValue[i] != null) { uEncodingValue |= (((uint)partialRegValue[i][0]) << encodingFormat.PartialRegisterPositions[i][0]); uEncodingValue |= (((uint)partialRegValue[i][1]) << encodingFormat.PartialRegisterPositions[i][1]); } } for (int i = 0; i < immedIndex; i++) { uEncodingValue |= (immedValue[i] << encodingFormat.ImmediatePositions[i]); } //byte[] bytes = BitConverter.GetBytes(uEncodingValue); byte[] bytes = ASMValueHelper.ConvertUIntToBytes(uEncodingValue, littleEndian); if (littleEndian) { uEncodingValue = ASMValueHelper.ReverseBytes(uEncodingValue); } //else //{ // Array.Reverse(bytes); //} string hex = ASMValueHelper.UnsignedToHex_WithLength(uEncodingValue, 8).ToUpper(); return(new ASMSingleEncodeResult(hex, bytes)); }
public static ASMProcessEquivalencesResult ProcessEquivalences(string[] lines) { ASMProcessEquivalencesResult result = new ASMProcessEquivalencesResult(); result.ErrorCode = 0; StringBuilder errorTextBuilder = new StringBuilder(); Dictionary <string, string> eqvMap = new Dictionary <string, string>(); ASMFindEquivalencesResult findEquivalencesResult = FindEquivalences(eqvMap, lines); if (findEquivalencesResult != null) { if (findEquivalencesResult.ErrorCode > 0) { result.ErrorCode = 1; errorTextBuilder.Append(findEquivalencesResult.ErrorMessage); } } List <string> eqvKeys = new List <string>(eqvMap.Keys); eqvKeys.Sort((a, b) => a.Length.CompareTo(b.Length)); eqvKeys.Reverse(); List <string> newLines = new List <string>(); foreach (string line in lines) { string processLine = ASMStringHelper.RemoveLeadingBracketBlock(line); processLine = ASMStringHelper.RemoveLeadingSpaces(processLine); processLine = ASMStringHelper.RemoveComment(processLine).ToLower(); string[] parts = ASMStringHelper.SplitLine(processLine); bool isEquivalence = ((!string.IsNullOrEmpty(parts[0])) && (parts[0].ToLower().Trim() == ".eqv")); string newLine = (string)line.Clone(); if (!isEquivalence) { /* * foreach (KeyValuePair<string, string> eqv in eqvDict) * { * //newLine = newLine.Replace(eqv.Key, eqv.Value); * newLine = System.Text.RegularExpressions.Regex.Replace(newLine, System.Text.RegularExpressions.Regex.Escape(eqv.Key), eqv.Value.Replace("$", "$$"), * System.Text.RegularExpressions.RegexOptions.IgnoreCase); * } */ foreach (string eqvKey in eqvKeys) { newLine = System.Text.RegularExpressions.Regex.Replace(newLine, System.Text.RegularExpressions.Regex.Escape(eqvKey), eqvMap[eqvKey].Replace("$", "$$"), System.Text.RegularExpressions.RegexOptions.IgnoreCase); } } newLines.Add(newLine); } result.ErrorMessage = errorTextBuilder.ToString(); result.Lines = newLines.ToArray(); return(result); }
// Regs use uppercase letters, immediates use lowercase letters: [r1] becomes AAAAA, [i1] becomes aaa if length = 3, etc. public static string ExpandFormat(EncodingFormat format) { int numRegs = format.NumRegs; int numImmeds = format.NumImmeds; string newFormatBinary = format.Binary; for (int i = 0; i < numRegs; i++) { char elementTypeChar = format.RegisterTypes[i]; string strElementTypeChar = elementTypeChar.ToString(); int iPlusOne = i + 1; string strIPlusOne = iPlusOne.ToString(); newFormatBinary = newFormatBinary.Replace("[" + strElementTypeChar + strIPlusOne + "]", ASMStringHelper.CreateCharacterString(ASMStringHelper.CreateUpperLetterChar(i), ASMRegisterHelper.GetEncodingBitLength(elementTypeChar))); if (format.PartialRegisterSizes != null) { newFormatBinary = newFormatBinary.Replace("[" + strElementTypeChar + strIPlusOne + "-1]", ASMStringHelper.CreateCharacterString(ASMStringHelper.CreateUpperLetterChar(i), format.PartialRegisterSizes[0])); newFormatBinary = newFormatBinary.Replace("[" + strElementTypeChar + strIPlusOne + "-2]", ASMStringHelper.CreateCharacterString(ASMStringHelper.CreateUpperLetterChar(i), format.PartialRegisterSizes[1])); } } for (int i = 0; i < numImmeds; i++) { newFormatBinary = newFormatBinary.Replace("[" + format.ImmediateTypes[i] + (i + 1) + "]", ASMStringHelper.CreateCharacterString(ASMStringHelper.CreateLowerLetterChar(i), format.ImmediateLengths[i])); } return(newFormatBinary); }
public ASMCheckResult CheckASM(string[] lines, uint pc, bool littleEndian, bool useRegAliases, ICollection <ASMCheckCondition> conditions = null) { if (conditions == null) { conditions = standardCheckConditions; } bool isASM = (_errorTextBuilder.Length == 0); uint startPC = pc; string gprLoad = ""; int hiLoCountdown = 0; string hiLoCommand = ""; bool isLastCommandBranch = false; uint lastBranchAddress = 0; bool isLastCommandUnconditionalJump = false; bool isLastCommandUnconditionalJumpDelaySlot = false; foreach (string line in lines) { string[] parts = ASMStringHelper.SplitLine(line); if (parts.Length < 1) { continue; } string command = parts[0]; if (string.IsNullOrEmpty(command)) { continue; } string commandLower = command.ToLower().Trim(); bool isLoad = IsLoadCommand(command); bool isBranch = IsBranchCommand(command); bool isUnconditionalJump = IsUnconditionalJump(command); string strPC = "0x" + ASMValueHelper.UnsignedToHex_WithLength(pc, 8); string strArgs = parts[1]; if (!string.IsNullOrEmpty(strArgs)) { string[] args = strArgs.Split(','); if (conditions.Contains(ASMCheckCondition.LoadDelay)) { if (!isLastCommandUnconditionalJumpDelaySlot) { CheckLoadDelay(command, args, gprLoad, strPC); } } if (conditions.Contains(ASMCheckCondition.UnalignedOffset)) { int alignmentMultiple = GetAlignmentMultiple(command); if (alignmentMultiple > 1) { string strOffset = args[1].Substring(0, args[1].IndexOf("(")); uint offset = Encoder.ValueHelper.GetAnyUnsignedValue(strOffset); if ((offset % alignmentMultiple) != 0) { _errorTextBuilder.AppendLine("WARNING: Unaligned offset at address " + strPC); } } } if (conditions.Contains(ASMCheckCondition.MultCountdown)) { bool isMultiplication = ((commandLower == "mult") || (commandLower == "multu")); bool isDivision = ((commandLower == "div") || (commandLower == "divu")); if ((hiLoCountdown > 0) && ((isMultiplication) || (isDivision))) { string operation = isMultiplication ? "Multiplication" : "Division"; _errorTextBuilder.AppendLine("WARNING: " + operation + " within 2 commands of " + hiLoCommand + " at address " + strPC); } } if (isLoad) { gprLoad = args[0].Trim(); if (isLastCommandBranch) { if (conditions.Contains(ASMCheckCondition.LoadInBranchDelaySlot)) { _errorTextBuilder.AppendLine("WARNING: Load command in branch delay slot at address " + strPC); } // If there is a load in the branch delay slot, check if the branch target address tries to use the loaded value if (conditions.Contains(ASMCheckCondition.LoadDelay)) { uint endPC = startPC + ((uint)(lines.Length - 1) * 4); uint branchPC = lastBranchAddress; string strBranchPC = "0x" + ASMValueHelper.UnsignedToHex_WithLength(branchPC, 8); if ((startPC <= branchPC) && (branchPC <= endPC)) { int index = (int)((branchPC - startPC) / 4); string branchLine = lines[index]; string[] branchParts = ASMStringHelper.SplitLine(branchLine); if (branchParts.Length > 1) { string strBranchArgs = branchParts[1]; if (!string.IsNullOrEmpty(strBranchArgs)) { string[] branchArgs = strBranchArgs.Split(','); CheckLoadDelay(branchParts[0], branchArgs, gprLoad, strBranchPC); } } } } } } if (conditions.Contains(ASMCheckCondition.StackPointerOffset)) { if (IsAddImmediateCommand(command)) { string stackPointerRegName = Encoder.RegHelper.GetGPRegisterName(29, useRegAliases).ToLower().Trim(); if ((args[0].ToLower().Trim() == stackPointerRegName) && (args[1].ToLower().Trim() == stackPointerRegName)) { uint immed = Encoder.ValueHelper.GetAnyUnsignedValue(args[2].ToLower().Trim()); if (immed % 8 != 0) { _errorTextBuilder.AppendLine("WARNING: Stack pointer offset not a multiple of 8 at address " + strPC); } } } } if (isBranch) { lastBranchAddress = FindBranchTargetAddress(args); } } // Check if we're jumping into a hazard if (isLastCommandBranch) { uint endPC = startPC + ((uint)(lines.Length - 1) * 4); uint branchPC = lastBranchAddress; string strBranchPC = "0x" + ASMValueHelper.UnsignedToHex_WithLength(branchPC, 8); if ((startPC <= branchPC) && (branchPC <= endPC)) { int index = (int)((branchPC - startPC) / 4); string branchLine = lines[index]; string[] branchParts = ASMStringHelper.SplitLine(branchLine); if (branchParts.Length > 1) { string strCommand = branchParts[0]; string strBranchArgs = branchParts[1]; if (!string.IsNullOrEmpty(strBranchArgs)) { string[] branchArgs = strBranchArgs.Split(','); if (conditions.Contains(ASMCheckCondition.LoadDelay)) { if ((IsLoadCommand(strCommand)) && ((branchPC + 4) <= endPC)) { string secondBranchLine = lines[index + 1]; string[] secondBranchParts = ASMStringHelper.SplitLine(secondBranchLine); if (secondBranchParts.Length > 1) { string strSecondBranchArgs = secondBranchParts[1]; if (!string.IsNullOrEmpty(strSecondBranchArgs)) { string[] secondBranchArgs = strSecondBranchArgs.Split(','); string strSecondBranchPC = "0x" + ASMValueHelper.UnsignedToHex_WithLength(branchPC + 4, 8); string branchGprLoad = branchArgs[0].Trim(); CheckLoadDelay(secondBranchParts[0], secondBranchArgs, branchGprLoad, strSecondBranchPC); } } } } if (conditions.Contains(ASMCheckCondition.MultCountdown)) { string strCommandLower = strCommand.ToLower(); if ((strCommandLower == "mfhi") || (strCommandLower == "mflo")) { if (((branchPC + 4) <= endPC)) { string nextBranchLine = lines[index + 1]; string[] nextBranchParts = ASMStringHelper.SplitLine(nextBranchLine); if (nextBranchParts.Length > 0) { string nextBranchCommand = nextBranchParts[0].ToLower(); bool isMultiplication = ((nextBranchCommand == "mult") || (nextBranchCommand == "multu")); bool isDivision = ((nextBranchCommand == "div") || (nextBranchCommand == "divu")); if ((isMultiplication) || (isDivision)) { string operation = isMultiplication ? "Multiplication" : "Division"; string strNextPC = "0x" + ASMValueHelper.UnsignedToHex_WithLength(branchPC + 4, 8); _errorTextBuilder.AppendLine("WARNING: " + operation + " within 2 commands of " + strCommandLower + " at address " + strNextPC); } } } if (((branchPC + 8) <= endPC)) { string nextBranchLine = lines[index + 2]; string[] nextBranchParts = ASMStringHelper.SplitLine(nextBranchLine); if (nextBranchParts.Length > 0) { string nextBranchCommand = nextBranchParts[0].ToLower(); bool isMultiplication = ((nextBranchCommand == "mult") || (nextBranchCommand == "multu")); bool isDivision = ((nextBranchCommand == "div") || (nextBranchCommand == "divu")); if ((isMultiplication) || (isDivision)) { string operation = isMultiplication ? "Multiplication" : "Division"; string strNextPC = "0x" + ASMValueHelper.UnsignedToHex_WithLength(branchPC + 8, 8); _errorTextBuilder.AppendLine("WARNING: " + operation + " within 2 commands of " + strCommandLower + " at address " + strNextPC); } } } } } } } } } if (conditions.Contains(ASMCheckCondition.BranchInBranchDelaySlot)) { if (isBranch && isLastCommandBranch) { _errorTextBuilder.AppendLine("WARNING: Branch command in branch delay slot at address " + strPC); } } if (!isLoad) { gprLoad = ""; } if (isLastCommandUnconditionalJump) { hiLoCountdown = 0; } else if ((commandLower == "mfhi") || (commandLower == "mflo")) { hiLoCountdown = 2; hiLoCommand = commandLower; } else if (hiLoCountdown > 0) { hiLoCountdown--; } isLastCommandBranch = isBranch; isLastCommandUnconditionalJumpDelaySlot = isLastCommandUnconditionalJump; isLastCommandUnconditionalJump = isUnconditionalJump; pc += 4; } return(new ASMCheckResult { ErrorText = _errorTextBuilder.ToString(), IsASM = isASM }); }
public ASMEncoderResult EncodeASM(string asm, uint pc, string spacePadding, bool includeAddress, bool littleEndian, bool clearErrorText) { if (clearErrorText) { ClearErrorText(); } string[] lines = asm.Split('\n'); lines = ASMStringHelper.RemoveFromLines(lines, "\r"); string[] processLines = AddLabelLines(lines); string oldErrorText = _errorTextBuilder.ToString(); EncodeLine[] encodeLines = PreprocessLines(processLines, pc); int encodeLineIndex = 0; int lineIndex = 0; StringBuilder newTextASMBuilder = new StringBuilder(); StringBuilder newTextASMLineBuilder = new StringBuilder(); StringBuilder encodedASMBuilder = new StringBuilder(); List <byte> byteList = new List <byte>(); if (oldErrorText != _errorTextBuilder.ToString()) { return(new ASMEncoderResult(encodedASMBuilder.ToString(), byteList.ToArray(), asm, _errorTextBuilder.ToString())); } foreach (string line in lines) { if (string.IsNullOrEmpty(line)) { newTextASMBuilder.AppendLine(); continue; } newTextASMLineBuilder.Length = 0; string modLine = ASMStringHelper.RemoveLeadingBracketBlock(line); string processLine = ASMStringHelper.RemoveLeadingSpaces(modLine); processLine = ASMStringHelper.RemoveComment(processLine).ToLower(); string[] parts = ASMStringHelper.SplitLine(processLine); //pc = ASMPCHelper.ProcessOrg(pc, parts); ASMProcessPCResult processPCResult = ASMPCHelper.ProcessOrg(pc, parts); pc = processPCResult.PC; _errorTextBuilder.Append(processPCResult.ErrorMessage); parts = ASMStringHelper.RemoveLabel(parts); // If this is an ASM command, pass off line to encoding routine EncodingFormat encodingOrNull = FormatHelper.FindFormatByCommand(parts[0]); if (encodingOrNull != null) { if (includeAddress) { newTextASMLineBuilder.Append("[0x"); newTextASMLineBuilder.Append(ASMValueHelper.UnsignedToHex_WithLength(pc, 8)); newTextASMLineBuilder.Append("] "); } newTextASMLineBuilder.AppendLine(modLine); EncodeLine eLine = new EncodeLine(); if (encodeLines.Length > 0) { eLine = encodeLines[encodeLineIndex]; } while ((eLine.LineIndex == lineIndex) && (encodeLineIndex < encodeLines.Length)) { encodingOrNull = FormatHelper.FindFormatByCommand(eLine.LineParts[0]); EncodingFormat encoding = encodingOrNull; ASMSingleEncodeResult singleEncodeResult = TryEncodeSingle(eLine.LineParts, encoding, pc, modLine, littleEndian); encodedASMBuilder.Append(spacePadding); encodedASMBuilder.Append(singleEncodeResult.ASMText); encodedASMBuilder.AppendLine(); //encodedASMBuilder.Append("\r\n"); byteList.AddRange(singleEncodeResult.Bytes); encodeLineIndex++; pc += 4; if (encodeLineIndex < encodeLines.Length) { eLine = encodeLines[encodeLineIndex]; } } lineIndex++; } else { if (!string.IsNullOrEmpty(parts[0])) { if ((parts[0] != ".org") && (parts[0] != ".label") && (parts[0] != ".eqv") && (!parts[0].EndsWith(":"))) { _errorTextBuilder.AppendLine("WARNING: Ignoring unknown command \"" + parts[0] + "\"."); } } } if (string.IsNullOrEmpty(newTextASMLineBuilder.ToString())) { newTextASMLineBuilder.AppendLine(modLine); } newTextASMBuilder.Append(newTextASMLineBuilder.ToString()); } string newTextASM = newTextASMBuilder.ToString(); if (newTextASM.EndsWith("\r\n")) { newTextASMBuilder.Length -= 2; } else if (newTextASM.EndsWith("\n")) { newTextASMBuilder.Length -= 1; } newTextASM = newTextASMBuilder.ToString(); return(new ASMEncoderResult(encodedASMBuilder.ToString(), byteList.ToArray(), newTextASM, _errorTextBuilder.ToString())); }
// Translates pseudoinstructions public ASMTranslatePseudoResult TranslatePseudo(string[] lines, uint startPC, bool skipLabelAssertion = false) { _errorTextBuilder.Length = 0; bool reportErrors = !skipLabelAssertion; ASMTranslatePseudoResult result = new ASMTranslatePseudoResult(); List <EncodeLine> resultLines = new List <EncodeLine>(); int index = 0; uint pc = startPC; List <bool> isSkippingLine = new List <bool>() { false }; int ifNestLevel = 0; foreach (string line in lines) { if (string.IsNullOrEmpty(line)) { continue; } string processLine = ASMStringHelper.RemoveLeadingBracketBlock(line); processLine = ASMStringHelper.RemoveLeadingSpaces(processLine); processLine = ASMStringHelper.RemoveComment(processLine).ToLower(); processLine = ASMStringHelper.ConvertBracketBlocks(processLine); string[] parts = ASMStringHelper.SplitLine(processLine); parts = ASMStringHelper.RemoveLabel(parts); //pc = ASMPCHelper.ProcessOrg(pc, parts); ASMProcessPCResult processPCResult = ASMPCHelper.ProcessOrg(pc, parts, false); pc = processPCResult.PC; _errorTextBuilder.Append(processPCResult.ErrorMessage); string firstPart = parts[0].ToLower().Trim(); if (firstPart == ".endif") { if (ifNestLevel == 0) { if (reportErrors) { _errorTextBuilder.AppendLine("WARNING: No matching .if statement for .endif statement at address 0x" + ASMValueHelper.UnsignedToHex_WithLength(pc, 8)); } } else { isSkippingLine.RemoveAt(isSkippingLine.Count - 1); ifNestLevel--; } } else if (firstPart == ".else") { if (ifNestLevel == 0) { if (reportErrors) { _errorTextBuilder.AppendLine("WARNING: No matching .if statement for .else statement at address 0x" + ASMValueHelper.UnsignedToHex_WithLength(pc, 8)); } } else if (!isSkippingLine[ifNestLevel - 1]) { isSkippingLine[ifNestLevel] = !isSkippingLine[ifNestLevel]; } } else if (firstPart == ".if") { try { string[] innerParts = parts[1].Split(','); if (!parts[1].Contains(",")) { if (reportErrors) { _errorTextBuilder.AppendLine("WARNING: Unreachable code at address 0x" + ASMValueHelper.UnsignedToHex_WithLength(pc, 8) + " inside .if statement with bad argument list (no commas): \"" + parts[1] + "\""); } isSkippingLine.Add(true); ifNestLevel++; } else if (innerParts.Length < 2) { if (reportErrors) { _errorTextBuilder.AppendLine("WARNING: Unreachable code at address 0x" + ASMValueHelper.UnsignedToHex_WithLength(pc, 8) + " inside .if statement with bad argument list (less than 2 arguments): \"" + parts[1] + "\""); } isSkippingLine.Add(true); ifNestLevel++; } else if (isSkippingLine[ifNestLevel]) { isSkippingLine.Add(true); ifNestLevel++; } else { string operation = string.Empty; string eqvKey, eqvValue; if (innerParts.Length >= 3) { operation = ASMStringHelper.RemoveSpaces(innerParts[0]); eqvKey = ASMStringHelper.RemoveSpaces(innerParts[1]); eqvValue = ASMStringHelper.RemoveSpaces(innerParts[2]); } else { operation = "="; eqvKey = ASMStringHelper.RemoveSpaces(innerParts[0]); eqvValue = ASMStringHelper.RemoveSpaces(innerParts[1]); } int intKey = 0; int intValue = 0; bool isKeyInt = int.TryParse(eqvKey, out intKey); bool isValueInt = int.TryParse(eqvValue, out intValue); bool isIntCompare = isKeyInt && isValueInt; bool isPass = false; switch (operation) { case "=": case "==": isPass = eqvKey.Equals(eqvValue); break; case "!=": case "<>": isPass = !eqvKey.Equals(eqvValue); break; case "<": isPass = isIntCompare && (intKey < intValue); break; case ">": isPass = isIntCompare && (intKey > intValue); break; case "<=": isPass = isIntCompare && (intKey <= intValue); break; case ">=": isPass = isIntCompare && (intKey >= intValue); break; default: break; } isSkippingLine.Add(!isPass); ifNestLevel++; } } catch (Exception ex) { if (reportErrors) { _errorTextBuilder.AppendLine("Error on .if statement: " + ex.Message + "\r\n"); } } } else { // If this is an ASM command, pass off line to translating routine EncodingFormat encodingOrNull = FormatHelper.FindFormatByCommand(parts[0]); if (encodingOrNull != null) { try { if (!isSkippingLine[ifNestLevel]) { EncodingFormat encoding = encodingOrNull; EncodeLine[] encodeLines = TranslatePseudoSingle(encoding, parts, index, pc, skipLabelAssertion); foreach (EncodeLine encodeLine in encodeLines) { resultLines.Add(encodeLine); pc += 4; } //index++; } } catch (Exception ex) { if (reportErrors) { //result.errorMessage = "Error translating pseudoinstruction: " + line; _errorTextBuilder.Append("Error translating pseudoinstruction: " + line + " (" + ex.Message + ")\r\n"); } //result.lines = null; //return result; //index++; } index++; } } } result.lines = resultLines.ToArray(); result.errorMessage = _errorTextBuilder.ToString(); return(result); }
public ASMFindLabelsResult FindLabels(string[] lines, EncodeLine[] encodeLines, uint pc) { ASMFindLabelsResult result = new ASMFindLabelsResult(); result.ErrorCode = 0; _errorTextBuilder.Length = 0; //LabelDict.Clear(); ClearLabelDict(); //int pc = ProcessPC(0, txt_StartPC.Text); int lineIndex = 0; int encodeLineIndex = 0; foreach (string line in lines) { if (string.IsNullOrEmpty(line)) { continue; } string processLine = ASMStringHelper.RemoveLeadingBracketBlock(line); processLine = ASMStringHelper.RemoveLeadingSpaces(processLine); processLine = ASMStringHelper.RemoveComment(processLine).ToLower(); string[] parts = ASMStringHelper.SplitLine(processLine); //pc = ASMPCHelper.ProcessOrg(pc, parts); ASMProcessPCResult processPCResult = ASMPCHelper.ProcessOrg(pc, parts, false); pc = processPCResult.PC; _errorTextBuilder.Append(processPCResult.ErrorMessage); ASMAddLabelResult processLabelResult = ProcessLabelStatement(parts); if (processLabelResult != null) { if (processLabelResult.ErrorCode > 0) { result.ErrorCode = 1; _errorTextBuilder.Append(processLabelResult.ErrorMessage); } } EncodingFormat encodingOrNull = FormatHelper.FindFormatByCommand(parts[0]); if (encodingOrNull != null) { EncodeLine eLine = new EncodeLine(); if ((encodeLines.Length > 0) && (encodeLineIndex < encodeLines.Length)) { eLine = encodeLines[encodeLineIndex]; } while ((eLine.LineIndex == lineIndex) && (encodeLineIndex < encodeLines.Length)) { pc += 4; encodeLineIndex++; if (encodeLineIndex < encodeLines.Length) { eLine = encodeLines[encodeLineIndex]; } } lineIndex++; } else { ASMAddLabelResult addLabelResult = AddLabel(pc, parts); if (addLabelResult.ErrorCode == 0) { pc = addLabelResult.PC; } else { _errorTextBuilder.Append(addLabelResult.ErrorMessage); result.ErrorCode = 1; } } } result.ErrorMessage = _errorTextBuilder.ToString(); return(result); }
// For reading encoding files public void ReadEncodeList(string filepath) { StreamReader reader = new StreamReader(filepath); try { while (reader.Peek() != -1) { string line = reader.ReadLine(); if (!string.IsNullOrEmpty(line)) { line = ASMStringHelper.RemoveSpaces(line); string[] lineArray = line.Split(':'); EncodingFormat encoding = new EncodingFormat(); encoding.Command = lineArray[0].ToLower(); encoding.Binary = lineArray[1]; encoding.Syntax = lineArray[2]; if (lineArray.Length > 3) { encoding.ImmediateLengths = ASMStringHelper.CreateIntList(lineArray[3]); } if (lineArray.Length > 4) { encoding.VFPURegisterTypes = ASMStringHelper.CreateIntList(lineArray[4]); } if (lineArray.Length > 5) { encoding.PartialRegisterSizes = ASMStringHelper.CreateIntList(lineArray[5]); } if (lineArray.Length > 6) { encoding.ShiftedImmediateAmounts = ASMStringHelper.CreateIntList(lineArray[6]); } if (lineArray.Length > 7) { encoding.VFPUPrefixType = int.Parse(lineArray[7]); } encoding = FindFormatDetails(encoding); string expFormat = ExpandFormat(encoding); encoding.ExpandedFormat = expFormat; encoding = FindFormatBaseValues(encoding); encoding = FindParameterIndexes(encoding); EncodeList.Add(encoding); EncodeDict.Add(encoding.Command, encoding); AddToDecodeLists(expFormat, encoding); } } } catch (Exception ex) { } finally { reader.Close(); } }