Example #1
0
            public CodeSourcePreprocessorReader(CodeSource src)
            {
#if DEBUG
                if (src == null)
                {
                    throw new ArgumentNullException("src");
                }
#endif
                _src = src;

                _segIndex  = 0;
                _segOffset = 0;
                if (_src._segments.Count > 0)
                {
                    _seg       = _src._segments[_segIndex];
                    _pos       = _seg.startPos;
                    _segLength = _seg.length;
                }
                else
                {
                    _seg       = null;
                    _pos       = 0;
                    _segLength = 0;
                }
            }
Example #2
0
        /// <inheritdoc />
        public ISegmentReference SerializeMethodBody(MethodBodySerializationContext context, MethodDefinition method)
        {
            if (!(method.MethodBody is NativeMethodBody nativeMethodBody))
            {
                return(SegmentReference.Null);
            }

            var provider = context.SymbolsProvider;

            // Create new raw code segment containing the native code.
            var segment = new CodeSegment(provider.ImageBase, nativeMethodBody.Code);

            // Process fixups.
            for (int i = 0; i < nativeMethodBody.AddressFixups.Count; i++)
            {
                // Import symbol.
                var fixup  = nativeMethodBody.AddressFixups[i];
                var symbol = provider.ImportSymbol(fixup.Symbol);

                // Create new fixup with imported symbol.
                segment.AddressFixups.Add(new AddressFixup(fixup.Offset, fixup.Type, symbol));

                // Add base relocation when necessary.
                // TODO: keep architecture into account..
                if (fixup.Type == AddressFixupType.Absolute32BitAddress)
                {
                    var relocation = new BaseRelocation(RelocationType.HighLow,
                                                        new RelativeReference(segment, (int)fixup.Offset));
                    provider.RegisterBaseRelocation(relocation);
                }
            }

            return(new SegmentReference(segment));
        }
        /// <summary>
        /// Instruments method instruction, that has corresponging segment of source code
        /// </summary>
        /// <param name="instruction">instruction that should be preceded by counter invocation</param>
        /// <param name="segment"></param>
        /// <param name="context"></param>
        public override void VisitMethodPoint(Instruction instruction, CodeSegment segment, Context context)
        {
            if (!context.ShouldInstrumentCurrentMember)
            {
                return;
            }

            var counterMethodCall = context.MethodWorker.Create(OpCodes.Call, context.CounterMethodRef);
            var instrLoadModuleId = context.MethodWorker.Create(OpCodes.Ldstr, context.CurrentModuleId);
            var instrLoadPointId  = context.MethodWorker.Create(OpCodes.Ldc_I4, context.CurrentPointId);

            context.MethodWorker.InsertBefore(instruction, instrLoadModuleId);
            context.MethodWorker.InsertAfter(instrLoadModuleId, instrLoadPointId);
            context.MethodWorker.InsertAfter(instrLoadPointId, counterMethodCall);

            //Change references in operands from "instruction" to first counter invocation instruction (instrLoadModuleId)
            foreach (Instruction instr in context.MethodWorker.Body.Instructions)
            {
                SubstituteInstructionOperand(instr, instruction, instrLoadModuleId);
            }

            foreach (ExceptionHandler handler in context.MethodWorker.Body.ExceptionHandlers)
            {
                SubstituteExceptionBoundary(handler, instruction, instrLoadModuleId);
            }
        }
Example #4
0
        protected override StringBuilder Traducir(CodeSegment segment)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine(Registros.OpCode(NombreRegistroD));
            sb.AppendLine(Fuente.ToString());
            return(sb);
        }
        private static void ReplaceBodyWithNativeCode(IPEImage image, CodeSegment body, bool is32bit)
        {
            // Adjust image flags appropriately.
            image.DotNetDirectory.Flags &= ~DotNetDirectoryFlags.ILOnly;

            if (is32bit)
            {
                image.MachineType            = MachineType.I386;
                image.PEKind                 = OptionalHeaderMagic.Pe32;
                image.DotNetDirectory.Flags |= DotNetDirectoryFlags.Bit32Required;
            }
            else
            {
                image.MachineType = MachineType.Amd64;
                image.PEKind      = OptionalHeaderMagic.Pe32Plus;
            }

            // Access metadata.
            var metadata      = image.DotNetDirectory.Metadata;
            var stringsStream = metadata.GetStream <StringsStream>();
            var tablesStream  = metadata.GetStream <TablesStream>();
            var typeTable     = tablesStream.GetTable <TypeDefinitionRow>();
            var methodTable   = tablesStream.GetTable <MethodDefinitionRow>();

            // Find the method to replace its body of.
            int index = -1;

            for (int i = 0; i < methodTable.Count && index == -1; i++)
            {
                if (stringsStream.GetStringByIndex(methodTable[i].Name) == "GetTheAnswer")
                {
                    index = i;
                }
            }

            // Replace body.
            var methodRow = methodTable[index];

            methodTable[index] = new MethodDefinitionRow(
                new SegmentReference(body),
                methodRow.ImplAttributes | MethodImplAttributes.Native | MethodImplAttributes.Unmanaged
                | MethodImplAttributes.PreserveSig,
                methodRow.Attributes | MethodAttributes.PInvokeImpl,
                methodRow.Name,
                methodRow.Signature,
                methodRow.ParameterList);

            // Move to <Module>
            var typeRow = typeTable[1];

            typeTable[1] = new TypeDefinitionRow(
                typeRow.Attributes,
                typeRow.Name,
                typeRow.Namespace,
                typeRow.Extends,
                typeRow.FieldList,
                (uint)(index + 2));
        }
Example #6
0
        protected override StringBuilder Traducir(CodeSegment segment)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine(Registros.OpCode(NombreRegistroD))
            .AppendLine(Convert.ToString(this.Fuente.Decimal, 2)
                        .PadLeft(Alu.Palabra, '0'));
            return(sb);
        }
Example #7
0
        protected override StringBuilder Traducir(CodeSegment segment)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine($"100 ;{this.Tipo}");
            sb.AppendLine(Registros.OpCode(NombreRegistroD));
            sb.AppendLine(Registros.OpCode(NombreRegistroF));
            return(sb);
        }
Example #8
0
            private void PopState()
            {
                var state = _stack.Pop();

                _segIndex  = state.segIndex;
                _seg       = state.seg;
                _segOffset = state.segOffset;
                _pos       = state.pos;
                _segLength = state.segLength;
            }
Example #9
0
        public void Append(string text, string fileName, int fileStartPos, int fileEndPos, bool actualContent, bool primaryFile, bool disabled)
        {
            var lastSeg = _segments.LastOrDefault();

            if (lastSeg == null ||
                fileName != lastSeg.fileName ||
                fileStartPos != lastSeg.endPos ||
                actualContent != lastSeg.actualContent ||
                disabled != lastSeg.disabled)
            {
                Flush();
                lastSeg = new CodeSegment(fileName, _length, fileStartPos, fileEndPos, actualContent, primaryFile, disabled);

                if (primaryFile)
                {
                    var         primaryStartPos = fileStartPos;
                    CodeSegment seg;
                    for (int segIndex = _segments.Count - 1; segIndex >= 0; segIndex--)
                    {
                        seg = _segments[segIndex];
                        if (seg.nextPrimaryStartPos == -1)
                        {
                            seg.nextPrimaryStartPos = primaryStartPos;
                        }
                        else
                        {
                            break;
                        }
                    }
                }

                _segments.Add(lastSeg);
            }

            _writeBuf.Append(text);
            _length        += text.Length;
            lastSeg.length += text.Length;
            lastSeg.endPos  = fileEndPos;

#if DEBUG
            if (lastSeg.length != _writeBuf.Length + lastSeg.text.Length)
            {
                throw new InvalidOperationException("Segment length is incorrect during append.");
            }
#endif

            _text = null;

            //foreach (var ch in text)
            //{
            //	if (ch == '\n') _isEmptyLine = true;
            //	else if (!char.IsWhiteSpace(ch)) _isEmptyLine = false;
            //}
        }
Example #10
0
        protected override StringBuilder Traducir(CodeSegment code)
        {
            StringBuilder sb = new StringBuilder();

            if (!code.Etiquetas.ContainsKey(this.Etiqueta))
            {
                //Kit.Services.CustomMessageBox.Current.Show($"No se definio la etiqueta: [{this.Etiqueta}]", "Alerta", Kit.Enums.CustomMessageBoxButton.OK, Kit.Enums.CustomMessageBoxImage.Error);
                return(sb.AppendLine(";ERROR"));
            }
            sb.AppendLine(code.Etiquetas[this.Etiqueta]);
            return(sb);
        }
        public void NativeBodyWithCall()
        {
            Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), NonWindowsPlatform);
            Skip.IfNot(Environment.Is64BitOperatingSystem, Non64BitPlatform);

            // Read image
            var image = PEImage.FromBytes(Properties.Resources.TheAnswer_NetFx);

            var module = new ImportedModule("api-ms-win-crt-stdio-l1-1-0.dll");

            image.Imports.Add(module);

            var function = new ImportedSymbol(0x4fc, "puts");

            module.Symbols.Add(function);

            var body = new CodeSegment(image.ImageBase, new byte[]
            {
                /* 00: */ 0x48, 0x83, 0xEC, 0x28,                     // sub rsp, 0x28
                /* 04: */ 0x48, 0x8D, 0x0D, 0x10, 0x00, 0x00, 0x00,   // lea rcx, qword [rel str]
                /* 0B: */ 0xFF, 0x15, 0x00, 0x00, 0x00, 0x00,         // call qword [rel puts]
                /* 11: */ 0xB8, 0x37, 0x13, 0x00, 0x00,               // mov eax, 0x1337
                /* 16: */ 0x48, 0x83, 0xC4, 0x28,                     // add rsp, 0x28
                /* 1A: */ 0xC3,                                       // ret

                // str:
                0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x66,   // "Hello f"
                0x72, 0x6f, 0x6d, 0x20, 0x74, 0x68, 0x65,   // "rom the"
                0x20, 0x75, 0x6e, 0x6d, 0x61, 0x6e, 0x61,   // " unmana"
                0x67, 0x65, 0x64, 0x20, 0x77, 0x6f, 0x72,   // "ged wor"
                0x6c, 0x64, 0x21, 0x00                      // "ld!"
            });

            // Fixup puts call.
            body.AddressFixups.Add(new AddressFixup(
                                       0xD, AddressFixupType.Relative32BitAddress, function
                                       ));

            // Replace body.
            ReplaceBodyWithNativeCode(image, body, false);

            // Rebuild
            var builder = new ManagedPEFileBuilder();
            var peFile  = builder.CreateFile(image);

            // Verify
            string expectedOutput = "Hello from the unmanaged world!\r\nThe answer to life, universe and everything is 4919\r\n";

            _fixture
            .GetRunner <FrameworkPERunner>()
            .RebuildAndRun(peFile, "TheAnswer", expectedOutput);
        }
Example #12
0
        /// <summary>
        /// Adds new sequence point to report
        /// </summary>
        public override void VisitMethodPoint(Instruction instruction, CodeSegment segment, Context context)
        {
            var pointEntry = new PointEntry(
                segment.StartLine,
                segment.StartColumn,
                segment.EndLine,
                segment.EndColumn,
                segment.Document,
                context.ShouldInstrumentCurrentMember
                );

            context.ReportBuilder.AddPoint(pointEntry);
        }
        public void NativeBodyWithCallX86()
        {
            Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), NonWindowsPlatform);

            // Read image
            var image = PEImage.FromBytes(Properties.Resources.TheAnswer_NetFx);

            var module = new ImportedModule("api-ms-win-crt-stdio-l1-1-0.dll");

            image.Imports.Add(module);

            var function = new ImportedSymbol(0x4fc, "puts");

            module.Symbols.Add(function);

            var body = new CodeSegment(image.ImageBase, new byte[]
            {
                /* 00: */ 0x55,                                  // push ebp
                /* 01: */ 0x89, 0xE5,                            // mov ebp,esp
                /* 03: */ 0x6A, 0x6F,                            // push byte +0x6f         ; H
                /* 05: */ 0x68, 0x48, 0x65, 0x6C, 0x6C,          // push dword 0x6c6c6548   ; ello
                /* 0A: */ 0x54,                                  // push esp
                /* 0B: */ 0xFF, 0x15, 0x00, 0x00, 0x00, 0x00,    // call [dword puts]
                /* 11: */ 0x83, 0xC4, 0x0C,                      // add esp,byte +0xc
                /* 14: */ 0xB8, 0x37, 0x13, 0x00, 0x00,          // mov eax,0x1337
                /* 19: */ 0x5D,                                  // pop ebp
                /* 1A: */ 0xC3,                                  // ret
            });

            // Fix up puts call.
            body.AddressFixups.Add(new AddressFixup(
                                       0xD, AddressFixupType.Absolute32BitAddress, function
                                       ));
            image.Relocations.Clear();
            image.Relocations.Add(new BaseRelocation(RelocationType.HighLow, new RelativeReference(body, 0xD)));

            // Replace body.
            ReplaceBodyWithNativeCode(image, body, true);

            // Rebuild
            var builder = new ManagedPEFileBuilder();
            var peFile  = builder.CreateFile(image);

            // Verify
            string expectedOutput = "Hello\r\nThe answer to life, universe and everything is 4919\r\n";

            _fixture
            .GetRunner <FrameworkPERunner>()
            .RebuildAndRun(peFile, "TheAnswer", expectedOutput);
        }
Example #14
0
        protected override StringBuilder Traducir(CodeSegment code)
        {
            StringBuilder sb = new StringBuilder();

            foreach (Numero numero in this.Valores)
            {
                string bin = ConversorBinario.StrDecimal(numero.Decimal);
                for (int i = 0; i < Alu.Byte; i++)
                {
                    sb.Append('0');
                }
                sb.AppendLine(bin);
            }
            return(sb);
        }
Example #15
0
            private bool MoveNextSegment()
            {
                _segIndex++;
                if (_segIndex >= _src._segments.Count)
                {
                    _seg       = null;
                    _segLength = 0;
                    _segOffset = 0;
                    return(false);
                }

                _seg       = _src._segments[_segIndex];
                _segOffset = 0;
                _pos       = _seg.startPos;
                _segLength = _seg.length;
                return(true);
            }
        public void GeneratePartialCodeSegmentIfStop()
        {
            var input    = "1,9,10,3,2,3,11,0,99,30,40,50";
            var expected = new CodeSegment
            {
                Index          = 8,
                OpCode         = OpCodes.Stop,
                Arguments      = (-1, -1),
                UpdatePosition = -1
            };
            var intProcessor = new IntCodeProcessor(input);

            CodeSegment actual = intProcessor.GenerateCodeSegment(8);

            actual.Index.ShouldBe(expected.Index);
            actual.OpCode.ShouldBe(expected.OpCode);
            actual.Arguments.ShouldBe(expected.Arguments);
            actual.UpdatePosition.ShouldBe(expected.UpdatePosition);
        }
Example #17
0
        public StringBuilder CodigoMaquina(CodeSegment code)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(Convert.ToString((int)this.Tipo, 2).PadLeft(28, '0'))
            .Append(Modificador()).AppendLine();
            //.Append("; ").Append(this.Tipo.ToString()).Append(" - ").AppendLine(this.GetType().Name);


            StringBuilder complemento = Traducir(code).TrimEnd();

            if (complemento.Length > 0)
            {
                sb.Append(complemento);
            }

            sb.TrimEnd().AppendLine();
            return(sb);
        }
        public void GenerateCodeSegment()
        {
            var input    = "1,9,10,3,2,3,11,0,99,30,40,50";
            var expected = new CodeSegment
            {
                Index          = 0,
                OpCode         = OpCodes.Addition,
                Arguments      = (30, 40),
                UpdatePosition = 3
            };
            var intProcessor = new IntCodeProcessor(input);

            CodeSegment actual = intProcessor.GenerateCodeSegment(0);

            actual.Index.ShouldBe(expected.Index);
            actual.OpCode.ShouldBe(expected.OpCode);
            actual.Arguments.ShouldBe(expected.Arguments);
            actual.UpdatePosition.ShouldBe(expected.UpdatePosition);
        }
Example #19
0
 public Sintesis(AnalizadorSintactico Semantico, TextDocument Documento, ResultadosCompilacion Errores) : base(Documento, Errores)
 {
     this.CodeSegment = Semantico.CodeSegment;
 }
Example #20
0
            private void ILProcEnd(QuadTuple qt)
            {
                var tplt = "{0} endp";

                CodeSegment.Add(string.Format(tplt, qt.LValue.ID));
            }
Example #21
0
 public CodigoMaquina(Sintesis sintetizado)
 {
     this.Codigo      = new StringBuilder();
     this.CodeSegment = sintetizado.CodeSegment;
 }
Example #22
0
 public AnalizadorSintactico(AnalizadorLexico Lexica, TextDocument Documento, ResultadosCompilacion Errores) : base(Documento, Errores)
 {
     this.Lexica      = Lexica;
     this.CodeSegment = new CodeSegment();
 }
Example #23
0
 protected override StringBuilder Traducir(CodeSegment code)
 {
     throw new NotImplementedException();
 }
Example #24
0
 protected abstract StringBuilder Traducir(CodeSegment code);
Example #25
0
            public void Run(string path)
            {
                Console.WriteLine("Generating Asssembly....");
                AssemblyCode.Add(".model flat,stdcall");
                AssemblyCode.Add("option casemap:none");
                AssemblyCode.Add("include msvcrt.inc");
                AssemblyCode.Add("includelib msvcrt.lib");
                foreach (var item in ILCode)
                {
                    switch (item.Operator)
                    {
                    case ILOperator.Module:
                        ILDivMod(item, "edx");
                        break;

                    case ILOperator.Add:
                        ILSimpleBinary(item, "add");
                        break;

                    case ILOperator.ArrayAccess:
                        ILArrayAccess(item);
                        break;

                    case ILOperator.ArrayAssign:
                        ILArrayAssign(item);
                        break;

                    case ILOperator.ArrayDefine:
                        ILArrayDefine(item);
                        break;

                    case ILOperator.Assign:
                        ILAssign(item);
                        break;

                    case ILOperator.Call:
                        ILCall(item);
                        break;

                    case ILOperator.DataBegin:
                        ILDataBegin(item);
                        break;

                    case ILOperator.DataEnd:
                        ILDataEnd(item);
                        break;

                    case ILOperator.Decrease:
                        ILDecrease(item);
                        break;

                    case ILOperator.Division:
                        ILDivMod(item, "eax");
                        break;

                    case ILOperator.Je:
                        ILJc(item, "je");
                        break;

                    case ILOperator.Jne:
                        ILJc(item, "jne");
                        break;

                    case ILOperator.Jg:
                        ILJc(item, "jg");
                        break;

                    case ILOperator.Jge:
                        ILJc(item, "jge");
                        break;

                    case ILOperator.Increase:
                        ILIncrease(item);
                        break;

                    case ILOperator.Jmp:
                        ILJmp(item);
                        break;

                    case ILOperator.JmpTarget:
                        ILJmpTarget(item);
                        break;

                    case ILOperator.Jl:
                        ILJc(item, "jl");
                        break;

                    case ILOperator.Jle:
                        ILJc(item, "jle");
                        break;

                    case ILOperator.LoadAddress:
                        ILLoadAddress(item);
                        break;

                    case ILOperator.Multiply:
                        ILMultiply(item);
                        break;

                    case ILOperator.Jnz:
                        ILJc(item, "jnz");
                        break;

                    case ILOperator.Param:
                        ILParam(item);
                        break;

                    case ILOperator.ProcBegin:
                        LSymbols = new Dictionary <string, string>();
                        isLocal  = true;
                        ILProcBegin(item);
                        ProcSegment = new List <string>();
                        break;

                    case ILOperator.ProcEnd:
                        isLocal = false;
                        CodeSegment.AddRange(ProcSegment);
                        ILProcEnd(item);
                        break;

                    case ILOperator.Push:
                        ILPush(item);
                        break;

                    case ILOperator.Return:
                        ILReturn(item);
                        break;

                    case ILOperator.Subtract:
                        ILSimpleBinary(item, "sub");
                        break;

                    case ILOperator.VarDefine:
                        ILVarDefine(item);
                        break;

                    default:
                        break;
                    }
                }
                AssemblyCode.AddRange(DataSegment);
                AssemblyCode.AddRange(CodeSegment);
                AssemblyCode.Add("end main");
                WriteToFile(path);
            }
Example #26
0
        //protected override StringBuilder Traduccion(CodeSegment code)
        //{
        //    return new StringBuilder().AppendLine("11111000 ;RETURN CONTROL");
        //}

        protected override StringBuilder Traducir(CodeSegment code)
        {
            return(new StringBuilder());
        }
Example #27
0
            private void ILProcBegin(QuadTuple qt)
            {
                var tplt = "{0} proc stdcall ";

                CodeSegment.Add(string.Format(tplt, qt.LValue.ID));
            }