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 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);
        }
Beispiel #3
0
        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);
        }
        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);
        }
Beispiel #5
0
        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);
        }
Beispiel #6
0
        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, ""));
        }
Beispiel #7
0
        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 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));
        }
Beispiel #9
0
        // 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());
        }
Beispiel #10
0
        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));
        }
Beispiel #11
0
        // 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);
        }
Beispiel #12
0
        // 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();
            }
        }