Exemplo n.º 1
0
        /// <summary>
        /// Load a Basic PRG.
        /// </summary>
        /// <param name="imageBytes"></param>
        /// <returns></returns>
        private static Program LoadPrg(IServiceProvider services, byte[] imageBytes)
        {
            var    stm = new MemoryStream();
            ushort preferredAddress = MemoryArea.ReadLeUInt16(imageBytes, 0);
            ushort alignedAddress   = (ushort)(preferredAddress & ~0xF);
            int    pad = preferredAddress - alignedAddress;

            while (pad-- > 0)
            {
                stm.WriteByte(0);
            }
            stm.Write(imageBytes, 2, imageBytes.Length - 2);
            var loadedBytes = stm.ToArray();
            var image       = new MemoryArea(
                Address.Ptr16(alignedAddress),
                loadedBytes);
            var rdr      = new C64BasicReader(image, 0x0801);
            var lines    = rdr.ToSortedList(line => (ushort)line.Address.ToLinear(), line => line);
            var cfgSvc   = services.RequireService <IConfigurationService>();
            var arch6502 = new Mos6502Architecture(services, "m6502");
            var arch     = new C64Basic(services, lines);
            var platform = cfgSvc.GetEnvironment("c64").Load(services, arch);
            var segMap   = platform.CreateAbsoluteMemoryMap();

            segMap.AddSegment(image, "code", AccessMode.ReadWriteExecute);
            var program = new Program(segMap, arch, platform);

            program.Architectures.Add(arch6502.Name, arch6502);
            var addrBasic = Address.Ptr16(lines.Keys[0]);
            var sym       = ImageSymbol.Procedure(arch, addrBasic, state: arch.CreateProcessorState());

            program.EntryPoints.Add(sym.Address, sym);
            return(program);
        }
Exemplo n.º 2
0
        private void BuildTest(Address addrBase, IPlatform platform, Action <X86Assembler> asmProg)
        {
            var sc            = new ServiceContainer();
            var eventListener = new FakeDecompilerEventListener();

            sc.AddService <DecompilerEventListener>(eventListener);
            sc.AddService <IDecompiledFileService>(new FakeDecompiledFileService());
            sc.AddService <IFileSystemService>(new FileSystemServiceImpl());
            var entryPoints = new List <ImageSymbol>();
            var asm         = new X86Assembler(arch, addrBase, entryPoints);

            asmProg(asm);

            program          = asm.GetImage();
            program.Platform = platform;
            var project = new Project {
                Programs = { program }
            };

            scanner = new Scanner(
                program,
                new DynamicLinker(project, program, eventListener),
                sc);
            scanner.EnqueueImageSymbol(ImageSymbol.Procedure(arch, addrBase), true);
            scanner.ScanImage();
        }
Exemplo n.º 3
0
        private ImageSymbol?LoadProgramEntryPoint(Program program, SortedList <Address, ImageSymbol> symbols)
        {
            if (!aux.HasValue)
            {
                return(null);
            }
            var entry = aux.Value.o_entry;

            if (entry == 0 || entry == ~0u)
            {
                return(null);
            }
            var arch = program.Architecture;
            var rdr  = program.CreateImageReader(arch, Address.Ptr32(entry));

            // o_entry actually points to a function descriptor (think of it as a closure)
            // consisting of a pointer to the actual code and a pointer to the TOC.
            if (TryReadFunctionDescriptor(rdr, out Address addrEntry, out Constant ptrToc))
            {
                if (!symbols.TryGetValue(addrEntry, out var symEntry))
                {
                    symEntry = ImageSymbol.Procedure(arch, addrEntry);
                    symbols.Add(addrEntry, symEntry);
                }
                symEntry.ProcessorState = arch.CreateProcessorState();
                symEntry.ProcessorState.SetRegister(arch.GetRegister("r2") !, ptrToc);
                return(symEntry);
            }
            return(null);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Create symbols for the driver routines.
        /// </summary>
        private void AddDriverMethods(SortedList <Address, ImageSymbol> symbols, ByteMemoryArea memSeg)
        {
            void MakeSymbol(ByteMemoryArea mem, string prefix, string routineName, uint offset)
            {
                var name = $"{prefix}_{routineName}";
                var sym  = ImageSymbol.Procedure(this.arch, mem.BaseAddress + offset + 4, name);

                symbols.Add(sym.Address, sym);
            }

            var rdr          = memSeg.CreateBeReader(4 + 8);
            var offsetOpen   = rdr.ReadBeUInt16();
            var offsetPrime  = rdr.ReadBeUInt16();
            var offsetCtl    = rdr.ReadBeUInt16();
            var offsetStatus = rdr.ReadBeUInt16();
            var offsetClose  = rdr.ReadBeUInt16();
            var cbName       = rdr.ReadByte();
            var abName       = rdr.ReadBytes(cbName);
            var driverName   = Encoding.UTF8.GetString(abName);
            var driverPrefix = NamingPolicy.SanitizeIdentifierName(driverName);

            MakeSymbol(memSeg, driverPrefix, "Open", offsetOpen);
            MakeSymbol(memSeg, driverPrefix, "Prime", offsetPrime);
            MakeSymbol(memSeg, driverPrefix, "Ctl", offsetCtl);
            MakeSymbol(memSeg, driverPrefix, "Status", offsetStatus);
            MakeSymbol(memSeg, driverPrefix, "Close", offsetClose);
        }
Exemplo n.º 5
0
        private void RunFileTestx86_32(string relativePath, string outputFile)
        {
            Program program;
            var     sc    = new ServiceContainer();
            var     fsSvc = new FileSystemServiceImpl();
            var     el    = new FakeDecompilerEventListener();

            sc.AddService <IFileSystemService>(fsSvc);
            sc.AddService <DecompilerEventListener>(el);
            var arch = new X86ArchitectureFlat32(sc, "x86-protected-32");
            var asm  = new X86TextAssembler(arch);

            using (var rdr = new StreamReader(FileUnitTester.MapTestPath(relativePath)))
            {
                var platform = new DefaultPlatform(sc, arch);
                program          = asm.Assemble(Address.Ptr32(0x10000000), rdr);
                program.Platform = platform;
            }
            var scanner = new Scanner(program, null, sc);

            scanner.EnqueueImageSymbol(ImageSymbol.Procedure(arch, program.ImageMap.BaseAddress), true);
            scanner.ScanImage();
            using (var fut = new FileUnitTester(outputFile))
            {
                foreach (var proc in program.Procedures.Values)
                {
                    proc.Write(false, fut.TextWriter);
                }
                fut.AssertFilesEqual();
            }
        }
Exemplo n.º 6
0
        public override Program Load(Address addrLoad, IProcessorArchitecture arch, IPlatform platform)
        {
            var    stm = new MemoryStream();
            ushort preferredAddress = ByteMemoryArea.ReadLeUInt16(RawImage, 0);
            ushort alignedAddress   = (ushort)(preferredAddress & ~0xF);
            int    pad = preferredAddress - alignedAddress;

            while (pad-- > 0)
            {
                stm.WriteByte(0);
            }
            stm.Write(RawImage, 2, RawImage.Length - 2);
            var loadedBytes = stm.ToArray();
            var image       = new ByteMemoryArea(
                Address.Ptr16(alignedAddress),
                loadedBytes);
            var rdr    = new C64BasicReader(image, 0x0801);
            var lines  = rdr.ToSortedList(line => line.LineNumber, line => line);
            var cfgSvc = Services.RequireService <IConfigurationService>();

            arch     = new C64Basic(Services, lines);
            platform = cfgSvc.GetEnvironment("c64").Load(Services, arch);
            var        arch6502 = cfgSvc.GetArchitecture("m6502");
            SegmentMap segMap   = CreateSegmentMap(platform, image, lines);
            var        program  = new Program(segMap, arch, platform);

            program.Architectures.Add(arch6502.Name, arch6502);
            var addrBasic = lines.Values[0].Address;
            var sym       = ImageSymbol.Procedure(arch, addrBasic, state: arch.CreateProcessorState());

            program.EntryPoints.Add(sym.Address, sym);
            AddLineNumberSymbols(lines, program);
            return(program);
        }
Exemplo n.º 7
0
        protected void RunHexTest(string hexFile, string outputFile)
        {
            var svc           = new ServiceContainer();
            var cfg           = new FakeDecompilerConfiguration();
            var eventListener = new FakeDecompilerEventListener();

            svc.AddService <IConfigurationService>(cfg);
            svc.AddService <DecompilerEventListener>(eventListener);
            svc.AddService <DecompilerHost>(new FakeDecompilerHost());
            ILoader ldr       = new Loader(svc);
            var     imgLoader = new DchexLoader(FileUnitTester.MapTestPath(hexFile), svc, null);
            var     program   = imgLoader.Load(null);
            var     project   = new Project {
                Programs = { program }
            };
            var ep             = ImageSymbol.Procedure(program.Architecture, program.ImageMap.BaseAddress);
            var importResolver = new ImportResolver(project, program, eventListener);
            var scan           = new Scanner(program, importResolver, svc);

            scan.EnqueueImageSymbol(ep, true);
            scan.ScanImage();

            var dfa = new DataFlowAnalysis(program, null, eventListener);

            dfa.AnalyzeProgram();
            RunTest(program, outputFile);
        }
Exemplo n.º 8
0
 public override RelocationResults Relocate(Program program, Address addrLoad)
 {
     entryPoints.Add(ImageSymbol.Procedure(program.Architecture, addrEntry));
     return new RelocationResults(
         entryPoints,
         imageSymbols);
 }
Exemplo n.º 9
0
        public override Program LoadProgram(Address?addrLoad)
        {
            addrLoad ??= PreferredBaseAddress;
            var cfgSvc = Services.RequireService <IConfigurationService>();

            this.arch     = cfgSvc.GetArchitecture("x86-protected-32") !;
            this.platform = cfgSvc.GetEnvironment("ms-dos-386")
                            .Load(Services, arch);
            var rdr        = new LeImageReader(RawImage, FileHeaderOffset);
            var fileHeader = rdr.ReadStruct <FileHeader>();
            var image      = new ByteMemoryArea(Address.Ptr32(fileHeader.base_load_offset), new byte[fileHeader.memory_requirements]);

            if ((fileHeader.flags & FlagImagePacked) != 0)
            {
                UnpackImage(fileHeader, image);
            }
            var loadseg = new ImageSegment("DOSX_PROG", image, AccessMode.ReadWriteExecute);

            this.segmentMap = new SegmentMap(addrLoad);
            var seg = this.segmentMap.AddSegment(loadseg);

            this.program = new Program(this.segmentMap, this.arch, platform);
            var ep = ImageSymbol.Procedure(
                this.arch,
                Address.Ptr32(fileHeader.initial_EIP),
                "_start");

            this.program.EntryPoints.Add(ep.Address, ep);
            return(program);
        }
Exemplo n.º 10
0
        private static void Rewrite(Program program, IAssembler asm, string configFile)
        {
            var fakeDiagnosticsService = new FakeDiagnosticsService();
            var fakeConfigService      = new FakeDecompilerConfiguration();
            var eventListener          = new FakeDecompilerEventListener();
            var sc = new ServiceContainer();

            sc.AddService <IDiagnosticsService>(fakeDiagnosticsService);
            sc.AddService <IConfigurationService>(fakeConfigService);
            sc.AddService <DecompilerEventListener>(eventListener);
            sc.AddService <IDecompiledFileService>(new FakeDecompiledFileService());
            sc.AddService <IFileSystemService>(new FileSystemServiceImpl());
            var loader  = new Loader(sc);
            var project = string.IsNullOrEmpty(configFile)
                ? new Project()
                : new ProjectLoader(sc, loader, eventListener).LoadProject(FileUnitTester.MapTestPath(configFile));
            var scan = new Scanner(
                program,
                new DynamicLinker(project, program, eventListener),
                sc);

            scan.EnqueueImageSymbol(ImageSymbol.Procedure(program.Architecture, asm.StartAddress), true);
            foreach (var f in project.Programs)
            {
                foreach (var sp in f.User.Procedures.Values)
                {
                    scan.EnqueueUserProcedure(program.Architecture, sp);
                }
            }
            scan.ScanImage();
        }
Exemplo n.º 11
0
 public override RelocationResults Relocate(Program program, Address addrLoad)
 {
     return(new RelocationResults(
                new List <ImageSymbol>
     {
         ImageSymbol.Procedure(program.Architecture, addrEntry !),
     },
Exemplo n.º 12
0
        /// <summary>
        /// Builds the MacOS A5World, based on the contents of the jump table in CODE#0.
        /// </summary>
        /// <param name="jt"></param>
        /// <param name="addr"></param>
        /// <param name="codeSegs"></param>
        /// <returns></returns>
        public ImageSegment LoadA5World(
            JumpTable jt,
            Address addr,
            Dictionary <int, ImageSegment> codeSegs,
            SortedList <Address, ImageSymbol> symbols)
        {
            var size = jt.BelowA5Size + jt.AboveA5Size;
            var mem  = new ByteMemoryArea(addr, new byte[size]);
            var w    = new BeImageWriter(mem, jt.BelowA5Size + jt.JumpTableOffset);
            int i    = 0;

            foreach (var entry in jt.Entries)
            {
                w.WriteBeUInt16(entry.RoutineOffsetFromSegmentStart);
                int iSeg      = (ushort)entry.Instruction;
                var targetSeg = codeSegs[iSeg];
                var addrDst   = targetSeg.Address + entry.RoutineOffsetFromSegmentStart;
                if (!symbols.ContainsKey(addrDst))
                {
                    symbols.Add(addrDst, ImageSymbol.Procedure(arch, addrDst));
                }
                w.WriteBeUInt16(0x4EF9);            // jmp (xxxxxxxxx).L
                w.WriteBeUInt32(addrDst.ToUInt32());
                ++i;
            }
            return(new ImageSegment("A5World", mem, AccessMode.ReadWriteExecute));
        }
Exemplo n.º 13
0
        // Fix up the relocations.

        public override RelocationResults Relocate(Program program, Address addrLoad)
        {
            // Seed the scanner with the start location.

            var sym = ImageSymbol.Procedure(
                program.Architecture,
                Address.SegPtr((ushort)(lzCs + addrLoad.Selector !), lzIp),
                state: arch.CreateProcessorState());

            var imageSymbols = new SortedList <Address, ImageSymbol> {
                { sym.Address, sym }
            };
            List <ImageSymbol> entryPoints = new List <ImageSymbol>()
            {
                sym
            };

            if (isLz91)
            {
                Relocate91(RawImage, addrLoad.Selector !.Value, imgLoaded);
            }
            else
            {
                Relocate90(RawImage, addrLoad.Selector !.Value, imgLoaded);
            }
            return(new RelocationResults(entryPoints, imageSymbols));
        }
Exemplo n.º 14
0
 void ParseSymtabCommand(IProcessorArchitecture arch)
 {
     if (rdr.TryReadUInt32(out uint symoff) &&
         rdr.TryReadUInt32(out uint nsyms) &&
         rdr.TryReadUInt32(out uint stroff) &&
         rdr.TryReadUInt32(out uint strsize))
     {
         Debug.Print("    Found a symbol table with {0} entries at {1:X8}.", nsyms, symoff);
         var strs     = rdr.CreateNew(this.ldr.RawImage, stroff);
         var strBytes = strs.ReadBytes(strsize);
         var syms     = rdr.CreateNew(this.ldr.RawImage, symoff);
         for (uint i = 0; i < nsyms; ++i)
         {
             var(msym, addr) = ReadSymbol(strBytes, syms, i);
             if (msym != null)
             {
                 ldr.machoSymbols.Add(msym);
                 if (addr.ToLinear() != 0 &&
                     msym.Name != "radr://5614542")      // Ignore Apple's hack for radar bug 5614542
                 {
                     ldr.imageSymbols[addr] = ImageSymbol.Procedure(arch, addr, msym.Name);
                 }
             }
         }
     }
Exemplo n.º 15
0
 public List <ImageSymbol> GetAllSymbols()
 {
     return(new List <ImageSymbol>
     {
         ImageSymbol.Procedure(
             arch.Object,
             Address.Ptr64(0x12340000),
             "MyFunction",
             signature: new SerializedSignature
         {
             Arguments = new Argument_v1[]
             {
                 new Argument_v1("arg1", PrimitiveType_v1.Int32(), new StackVariable_v1(), false),
                 new Argument_v1("arg2", new PointerType_v1(PrimitiveType_v1.Char8())
                 {
                     PointerSize = 4
                 }, new StackVariable_v1(), false),
             },
             ReturnValue = new Argument_v1
             {
                 Type = PrimitiveType_v1.Int32()
             }
         })
     });
 }
Exemplo n.º 16
0
        public override Program Load(Address addrLoad)
        {
            var cfgSvc   = Services.RequireService <IConfigurationService>();
            var arch     = cfgSvc.GetArchitecture("ppc-be-64");
            var platform = cfgSvc.GetEnvironment("xbox360").Load(Services, arch);

            LoadHeaders();
            LoadImageData();
            LoadPEImage();

            PopulateImports();

            addrLoad = new Address32(xexData.exe_address);
            var segmentMap = new SegmentMap(addrLoad, segments.ToArray());

            var entryPointAddress = new Address32(xexData.exe_entry_point);
            var entryPoint        = ImageSymbol.Procedure(arch, entryPointAddress);

            var program = new Program(
                segmentMap,
                arch,
                platform
                )
            {
                ImageSymbols = { { entryPointAddress, entryPoint } },
                EntryPoints  = { { entryPointAddress, entryPoint } },
            };

            foreach (var import in imports)
            {
                program.ImportReferences.Add(import.Key, import.Value);
            }

            return(program);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Load a Basic PRG.
        /// </summary>
        /// <param name="imageBytes"></param>
        /// <returns></returns>
        private Program LoadPrg(byte[] imageBytes)
        {
            var    stm = new MemoryStream();
            ushort preferredAddress = MemoryArea.ReadLeUInt16(imageBytes, 0);
            ushort alignedAddress   = (ushort)(preferredAddress & ~0xF);
            int    pad = preferredAddress - alignedAddress;

            while (pad-- > 0)
            {
                stm.WriteByte(0);
            }
            stm.Write(imageBytes, 2, imageBytes.Length - 2);
            var loadedBytes = stm.ToArray();
            var image       = new MemoryArea(
                Address.Ptr16(alignedAddress),
                loadedBytes);
            var rdr  = new C64BasicReader(image, 0x0801);
            var prog = rdr.ToSortedList(line => (ushort)line.Address.ToLinear(), line => line);
            var arch = new C64Basic(prog);

            image = new MemoryArea(
                Address.Ptr16(prog.Keys[0]),
                new byte[0xFFFF]);
            var program = new Program(
                new SegmentMap(
                    image.BaseAddress,
                    new ImageSegment("code", image, AccessMode.ReadWriteExecute)),
                arch,
                new C64Platform(Services, null));
            var sym = ImageSymbol.Procedure(arch, image.BaseAddress, state: arch.CreateProcessorState());

            program.EntryPoints.Add(sym.Address, sym);
            return(program);
        }
Exemplo n.º 18
0
        private void DoRewriteCore()
        {
            var cfgSvc        = new Mock <IConfigurationService>();
            var env           = new Mock <PlatformDefinition>();
            var tlSvc         = new Mock <ITypeLibraryLoaderService>();
            var eventListener = new FakeDecompilerEventListener();

            cfgSvc.Setup(c => c.GetEnvironment("ms-dos")).Returns(env.Object);
            env.Setup(e => e.TypeLibraries).Returns(new List <TypeLibraryDefinition>());
            env.Setup(e => e.CharacteristicsLibraries).Returns(new List <TypeLibraryDefinition>());
            sc.AddService <IDecompiledFileService>(new FakeDecompiledFileService());
            sc.AddService <DecompilerEventListener>(eventListener);
            sc.AddService <IConfigurationService>(cfgSvc.Object);
            sc.AddService <ITypeLibraryLoaderService>(tlSvc.Object);

            Project project = LoadProject();

            project.Programs.Add(this.program);
            scanner = new Scanner(
                this.program,
                project.LoadedMetadata,
                new DynamicLinker(project, this.program, eventListener),
                sc);
            var ep = ImageSymbol.Procedure(this.program.Architecture, baseAddress);

            this.program.EntryPoints.Add(ep.Address, ep);
            var program = project.Programs[0];

            foreach (var sp in program.User.Procedures.Values)
            {
                scanner.EnqueueUserProcedure(program.Architecture, sp);
            }
            scanner.ScanImage();
        }
Exemplo n.º 19
0
        public override Program LoadProgram(Address?addrLoad)
        {
            if (!ParseDMKHeader())
            {
                throw new BadImageFormatException("Unable to read DMK header.");
            }

            addrLoad ??= PreferredBaseAddress;
            var tracks = BuildTrackList(TrackLength);
            var bytes  = tracks.SelectMany(t => t.Sectors)
                         .SelectMany(s => s.GetData())
                         .ToArray();
            var mem        = new ByteMemoryArea(addrLoad, bytes);
            var cfgSvc     = Services.RequireService <IConfigurationService>();
            var arch       = cfgSvc.GetArchitecture("z80") !;
            var platform   = cfgSvc.GetEnvironment("trs80").Load(Services, arch);
            var segmentMap = CreateMemoryMap(platform, mem);

            //        return new RelocationResults(
            //new List<ImageSymbol> {
            //
            //},
            //BuildSymbols(program));
            var program = new Program
            {
                Architecture = arch,
                Platform     = platform,
                SegmentMap   = segmentMap
            };

            program.ImageSymbols.Add(addrLoad, ImageSymbol.Procedure(program.Architecture, addrLoad));
            return(program);
        }
Exemplo n.º 20
0
 public override RelocationResults Relocate(Program program, Address addrLoad)
 {
     return(new RelocationResults(
                new List <ImageSymbol> {
         ImageSymbol.Procedure(program.Architecture, entryPoint)
     },
                new SortedList <Address, ImageSymbol>()));
 }
Exemplo n.º 21
0
        public void Relocate(Program program, Address addrLoad)
        {
            var header     = CreateSavHeader(program.Architecture);
            var uaddrEntry = ByteMemoryArea.ReadLeUInt16(RawImage, 0x20);
            var entry      = ImageSymbol.Procedure(program.Architecture, Address.Ptr16(uaddrEntry));

            program.EntryPoints[entry.Address]   = entry;
            program.ImageSymbols[header.Address] = header;
        }
Exemplo n.º 22
0
        public void Scanner_Interprocedural_CloneBlocks()
        {
            var scan = CreateScanner(0x1000, 0x2000);

            Given_Trace(new RtlTrace(0x1000)
            {
                m => { m.Assign(reg1, m.Word32(0)); },
                m => { m.Assign(m.Mem32(m.Word32(0x1800)), reg1); },
                m => { m.Return(0, 0); }
            });
            Given_Trace(new RtlTrace(0x1004)
            {
                m => { m.Assign(m.Mem32(m.Word32(0x1800)), reg1); },
                m => { m.Return(0, 0); }
            });
            Given_Trace(new RtlTrace(0x1100)
            {
                m => { m.Assign(reg1, m.Word32(1)); },
                m => { m.Goto(Address.Ptr32(0x1004)); },
            });
            fakeArch.Test_IgnoreAllUnkownTraces();

            scan.EnqueueImageSymbol(ImageSymbol.Procedure(arch, Address.Ptr32(0x1000), state: arch.CreateProcessorState()), true);
            scan.EnqueueImageSymbol(ImageSymbol.Procedure(arch, Address.Ptr32(0x1100), state: arch.CreateProcessorState()), true);
            scan.ScanImage();

            var sExp =
                @"// fn00001000
// Return size: 0
define fn00001000
fn00001000_entry:
	r63 = fp
l00001000:
	r1 = 0x00000000
l00001004:
	Mem0[0x00001800:word32] = r1
	return
fn00001000_exit:

// fn00001100
// Return size: 0
define fn00001100
fn00001100_entry:
	r63 = fp
	goto l00001100
l00001004_in_fn00001100:
	Mem0[0x00001800:word32] = r1
	return
l00001100:
	r1 = 0x00000001
	goto l00001004_in_fn00001100
fn00001100_exit:

";

            AssertProgram(sExp, program);
        }
Exemplo n.º 23
0
        public override RelocationResults Relocate(Program program, Address addrLoad)
        {
            var    relocations = imgU.Relocations;
            ushort segCode     = (ushort)(addrLoad.Selector.Value + (PspSize >> 4));

            for (;;)
            {
                int relocs = (ushort)bitStm.GetByte();
                if (relocs == 0)
                {
                    break;
                }

                uint relocBase = PspSize + bitStm.GetWord() * 0x10u;
                do
                {
                    ushort relocOff = bitStm.GetWord();
                    ushort seg      = imgU.ReadLeUInt16(relocBase + relocOff);
                    seg = (ushort)(seg + segCode);

                    imgU.WriteLeUInt16(relocBase + relocOff, seg);
                    relocations.AddSegmentReference(relocBase + relocOff, seg);
                    segmentMap.AddOverlappingSegment(seg.ToString("X4"), imgU, Address.SegPtr(seg, 0), AccessMode.ReadWriteExecute);
                } while (--relocs != 0);
            }

            ushort pklSs = (ushort)(bitStm.GetWord() + segCode);
            ushort pklSp = (ushort)bitStm.GetWord();

            pklCs = (ushort)(bitStm.GetWord() + segCode);
            pklIp = bitStm.GetWord();

            var state = arch.CreateProcessorState();

            state.SetRegister(Registers.ds, Constant.Word16(addrLoad.Selector.Value));
            state.SetRegister(Registers.es, Constant.Word16(addrLoad.Selector.Value));
            state.SetRegister(Registers.cs, Constant.Word16(pklCs));
            state.SetRegister(Registers.ax, Constant.Word16(0));
            state.SetRegister(Registers.bx, Constant.Word16(0));
            state.SetRegister(Registers.cx, Constant.Word16(0));
            state.SetRegister(Registers.dx, Constant.Word16(0));
            state.SetRegister(Registers.bp, Constant.Word16(0));
            state.SetRegister(Registers.sp, Constant.Word16(pklSp));
            state.SetRegister(Registers.si, Constant.Word16(0));
            state.SetRegister(Registers.di, Constant.Word16(0));

            var sym = ImageSymbol.Procedure(arch, Address.SegPtr(pklCs, pklIp), state: state);

            return(new RelocationResults(
                       new List <ImageSymbol> {
                sym
            },
                       new SortedList <Address, ImageSymbol> {
                { sym.Address, sym }
            }));
        }
Exemplo n.º 24
0
        public List <ImageSymbol> LoadEntryPoints(
            uint offEntryTable,
            NeSegment [] segments,
            Dictionary <int, string> names,
            IProcessorArchitecture arch)
        {
            DebugEx.PrintIf(trace.TraceInfo, "== Loading entry points from offset {0:X}", offEntryTable);
            var rdr = new LeImageReader(RawImage, offEntryTable);

            var entries           = new List <ImageSymbol>();
            int bundleOrdinal     = 1;
            int nextbundleOrdinal = 1;

            for (; ;)
            {
                var cBundleEntries = rdr.ReadByte();
                if (cBundleEntries == 0)
                {
                    break;
                }
                nextbundleOrdinal = bundleOrdinal + cBundleEntries;
                var segNum = rdr.ReadByte();
                for (int i = 0; i < cBundleEntries; ++i)
                {
                    byte flags = rdr.ReadByte();
                    if (flags == 0)
                    {
                        break;
                    }
                    (byte iSeg, ushort offset)entry;
                    if (segNum == 0xFF)
                    {
                        entry = ReadMovableSegmentEntry(rdr);
                    }
                    else
                    {
                        entry = ReadFixedSegmentEntry(rdr, segNum);
                    }
                    var         state = arch.CreateProcessorState();
                    var         seg   = segments[entry.iSeg - 1];
                    var         addr  = seg.Address + entry.offset;
                    ImageSymbol ep    = ImageSymbol.Procedure(arch, addr);
                    if (names.TryGetValue(bundleOrdinal + i, out string name))
                    {
                        ep.Name = name;
                    }
                    ep.Type                  = SymbolType.Procedure;
                    ep.ProcessorState        = state;
                    imageSymbols[ep.Address] = ep;
                    entries.Add(ep);
                    DebugEx.PrintIf(trace.TraceVerbose, "   {0}", ep);
                }
                bundleOrdinal = nextbundleOrdinal;
            }
            return(entries);
        }
Exemplo n.º 25
0
 public override RelocationResults Relocate(Program program, Address addrLoad)
 {
     if (addrEntry != null)
     {
         entryPoints.Add(ImageSymbol.Procedure(program.Architecture, addrEntry));
     }
     return(new RelocationResults(
                entryPoints.Where(e => e != null).ToList(),
                imageSymbols));
 }
Exemplo n.º 26
0
        public override RelocationResults Relocate(Program program, Address addrLoad)
        {
            var entryNames  = LoadEntryNames(this.lfaNew + this.offResidentNameTable);
            var entryPoints = LoadEntryPoints(this.lfaNew + this.offEntryTable, entryNames);

            entryPoints.Add(ImageSymbol.Procedure(program.Architecture, addrEntry));
            return(new RelocationResults(
                       entryPoints,
                       imageSymbols));
        }
Exemplo n.º 27
0
        public List<ImageSymbol> LoadEntryPoints(
            uint offEntryTable, 
            NeSegment [] segments, 
            Dictionary<int, string> names,
            IProcessorArchitecture arch)
        {
            DebugEx.Inform(trace, "== Loading entry points from offset {0:X}", offEntryTable);
            var rdr = new LeImageReader(RawImage, offEntryTable);

            var entries = new List<ImageSymbol>();
            int bundleOrdinal = 1;
            int nextbundleOrdinal = 1;
            for (; ; )
            {
                var cBundleEntries = rdr.ReadByte();
                if (cBundleEntries == 0)
                    break;
                nextbundleOrdinal = bundleOrdinal + cBundleEntries;
                var segNum = rdr.ReadByte();
                if (segNum != 0)
                {
                    // If segNum had been 0, it would have 
                    // meant that all we want to do is allocate 
                    // (skip) some ordinal numbers. Since it wasn't 0,
                    // we proceed to generate entry points.
                    for (int i = 0; i < cBundleEntries; ++i)
                    {
                        byte flags = rdr.ReadByte();
                        (byte iSeg, ushort offset) entry;
                        if (segNum == 0xFF)
                        {
                            entry = ReadMovableSegmentEntry(rdr);
                        }
                        else
                        {
                            entry = ReadFixedSegmentEntry(rdr, segNum);
                        }
                        var seg = segments[entry.iSeg - 1];
                        var addr = seg.Address + entry.offset;
                        var ep = ImageSymbol.Procedure(arch, addr);
                        if (names.TryGetValue(bundleOrdinal + i, out string name))
                        {
                            ep.Name = name;
                        }
                        ep.Type = SymbolType.Procedure;
                        ep.ProcessorState = arch.CreateProcessorState();
                        imageSymbols[ep.Address] = ep;
                        entries.Add(ep);
                        DebugEx.Verbose(trace, "   {0:X2} {1} {2} - {3}", segNum, ep.Address, ep.Name, bundleOrdinal + i);
                    }
                }
                bundleOrdinal = nextbundleOrdinal;
            }
            return entries; 
        }
Exemplo n.º 28
0
        public void Prog_EnsureProcedure_Override_ImageSymbol_Name()
        {
            Given_Architecture();
            Given_Image(0xC3);
            var addr   = program.SegmentMap.BaseAddress;
            var symbol = ImageSymbol.Procedure(this.arch.Object, addr, name: "NameToOverride");

            var proc = program.EnsureProcedure(this.arch.Object, addr, "NewName");

            Assert.AreEqual("NewName", proc.Name);
        }
Exemplo n.º 29
0
        private void Given_x86_Image(Action <X86Assembler> asm)
        {
            var addrBase = Address.Ptr32(0x100000);
            var arch     = new X86ArchitectureFlat32("x86-protected-32");
            var entry    = ImageSymbol.Procedure(arch, addrBase);
            var m        = new X86Assembler(null, new DefaultPlatform(null, arch), addrBase, new List <ImageSymbol> {
                entry
            });

            asm(m);
            this.program = m.GetImage();
        }
Exemplo n.º 30
0
        private bool TryScanProcedure(out ImageSymbol sym)
        {
            ushort us;
            var    addrStart = rdr.Address;

            sym = null;
            while (rdr.TryReadBeUInt16(out us))
            {
                switch (us)
                {
                case RTS:
                case JMP_A0:
                    // Found what looks like a terminator.
                    break;

                case RTD:
                    // Read uint16 of bytes to pop.
                    if (!rdr.TryReadBeUInt16(out us))
                    {
                        return(false);
                    }
                    // looks like a RTD xxx instruction.
                    break;

                default:
                    // Any other words are quietly eaten.
                    continue;
                }

                // Remember the end of the procedure.
                var position = rdr.Offset;

                // We think we saw the end of the procedure. Could there be a MacsBug symbol?
                string symbol;
                if (!TryReadMacsBugSymbol(out symbol))
                {
                    // Don't really want a symbol in this case.
                    // But there might be more procedures.
                    continue;
                }

                if (!SkipConstantData())
                {
                    // That wasn't valid constant data, but there might be more procedures.
                    // But there might be more procedures.
                    continue;
                }

                sym = ImageSymbol.Procedure(arch, addrStart, symbol);
                return(true);
            }
            return(false);
        }