private void Sort(List <StreamLoader> loaders)
 {
     for (int i = 0; i < loaders.Count - 1; i++)
     {
         for (int j = i + 1; j < loaders.Count; j++)
         {
             if (loaders[i].start > loaders[j].start)
             {
                 StreamLoader temp = loaders[i];
                 loaders[i] = loaders[j];
                 loaders[j] = temp;
             }
         }
     }
 }
Example #2
0
    public static void unpackConfig(StreamLoader streamLoader)
    {
        ByteBuffer buffer = ByteBuffer.Wrap(streamLoader.getDataForName("flo2.dat"));
        int        count  = buffer.GetShort();

        overLayFlo317s = new OverLayFlo317[count];
        for (int i = 0; i < count; i++)
        {
            if (overLayFlo317s[i] == null)
            {
                overLayFlo317s[i] = new OverLayFlo317();
            }
            overLayFlo317s[i].parse(buffer);
        }
        Debug.Log("530 Overlay Floors amount: " + count);
    }
Example #3
0
        public void ParsingFileLoaderGraphHandlerExplicitTurtle()
        {
            Graph        g       = new Graph();
            GraphHandler handler = new GraphHandler(g);

#if PORTABLE
            using (var input = File.OpenRead(TestDataFile))
            {
                StreamLoader.Load(handler, TestDataFile, input);
            }
#else
            FileLoader.Load(handler, TestDataFile);
#endif

            TestTools.ShowGraph(g);
            Assert.IsFalse(g.IsEmpty, "Graph should not be empty");
        }
Example #4
0
        public void ParsingFileLoaderCountHandlerTurtle()
        {
            Graph orig = new Graph();

            orig.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl");
            CountHandler handler = new CountHandler();

#if PORTABLE
            using (var input = File.OpenRead(TestDataFile))
            {
                StreamLoader.Load(handler, TestDataFile, input);
            }
#else
            FileLoader.Load(handler, "temp.ttl");
#endif

            Assert.AreEqual(orig.Triples.Count, handler.Count);
        }
Example #5
0
        public static void LoadFromFile(this IGraph g, string filename, IRdfReader parser)
        {
            var path = System.IO.Path.GetFullPath(filename);

            if (g.IsEmpty && g.BaseUri == null)
            {
                if (System.IO.Path.IsPathRooted(filename))
                {
                    g.BaseUri = UriFactory.Create("file:///" + filename);
                }
                else
                {
                    g.BaseUri = UriFactory.Create("file:///" + path);
                }
            }
            using (var stream = System.IO.File.OpenRead(path))
            {
                StreamLoader.Load(g, filename, stream, parser);
            }
        }
        /// <summary>
        /// Creates a content manager that creates OpenGL object instances, like textures
        /// </summary>
        /// <param name="resourceAssembly">The resource assembly that contains the resources.</param>
        /// <returns>A content manager instance</returns>
        public static FileContentManager Create(Assembly resourceAssembly)
        {
            var streamLoader = new StreamLoader();

            streamLoader.AddMappings(resourceAssembly);
            streamLoader.AddMappings(Assembly.GetExecutingAssembly());

            var mgr = new FileContentManager(streamLoader);

            mgr.RegisterImporter(ContentImporters.String);
            mgr.RegisterImporter(ContentImporters.ByteBuffer);
            mgr.RegisterImporter(ContentImporters.DefaultMesh);
            mgr.RegisterImporter(BitmapImporter);
            mgr.RegisterImporter(TextureArrayImporter);
            mgr.RegisterImporter(ShaderProgramImporter);
            mgr.RegisterUpdater <Texture2dGL>(Update);
            mgr.RegisterUpdater <ShaderProgramGL>(Update);
            mgr.RegisterUpdater <TextureArray2dGL>(Update);
            return(mgr);
        }
Example #7
0
            public StreamLine(StreamLine other)
            {
                name     = other.name + "_duplicated";
                group    = other.group;
                loadType = other.loadType;
                flags    = other.flags;
                unk10    = other.unk10;
                unk11    = other.unk11;
                unk5     = other.unk5;
                unk12    = other.unk12;
                unk13    = other.unk13;
                unk14    = other.unk14;
                unk15    = other.unk15;

                loadList = new StreamLoader[other.loadList.Length];
                for (int i = 0; i < other.loadList.Length; i++)
                {
                    loadList[i] = new StreamLoader(other.loadList[i]);
                }
            }
        /// <summary>
        /// Creates a content manager that creates OpenGL object instances, like textures
        /// </summary>
        /// <param name="resourceAssembly">The assembly that contains the resources.</param>
        /// <param name="solutionMode">Should shaders be built with solution on or off</param>
        /// <returns>A content manager instance</returns>
        public static FileContentManager Create(Assembly resourceAssembly, bool solutionMode)
        {
            var streamLoader = new StreamLoader();

            streamLoader.AddMappings(resourceAssembly);
            streamLoader.AddMappings(Assembly.GetExecutingAssembly()); //Zenseless.OpenGL resources

            var mgr = new FileContentManager(streamLoader);

            mgr.RegisterImporter(ContentImporters.String);
            mgr.RegisterImporter(ContentImporters.ByteBuffer);
            mgr.RegisterImporter(ContentImporters.DefaultMesh);
            mgr.RegisterImporter(BitmapImporter);
            mgr.RegisterUpdater <Texture2dGL>(Update);
            mgr.RegisterImporter(TextureArrayImporter);
            mgr.RegisterUpdater <TextureArray2dGL>(Update);
            mgr.RegisterImporter((namedStreams) => ShaderProgramImporter(namedStreams, solutionMode));
            mgr.RegisterUpdater <ShaderProgramGL>((prog, namedStreams) => Update(prog, namedStreams, solutionMode));

            return(mgr);
        }
Example #9
0
    private void InitializeRune()
    {
        anIntArray1232 = new int[32];
        int a = 2;

        for (int k = 0; k < 32; k++)
        {
            anIntArray1232 [k] = a - 1;
            a += a;
        }
        signlink.storeid = 0;
        signlink.run();
        for (int i = 0; i < 5; i++)
        {
            decompressors [i] = new Decompressor(signlink.cache_dat, signlink.cache_idx [i], i + 1);
        }
        StreamLoader streamLoader_6 = streamLoaderForName(5, "update list",
                                                          "versionlist");

        onDemandFetcher = new OnDemandFetcher();
        onDemandFetcher.start(streamLoader_6);

        StreamLoader streamLoader = streamLoaderForName(2, "config", "config");

        RS2Sharp.Animation.unpackConfig(streamLoader);
        //RS2Sharp.Texture.method368(streamLoader_3);
        RS2Sharp.Texture.method372(0.80000000000000004D);
        RS2Sharp.Texture.method367();
        ItemDef.unpackConfig(streamLoader);
        EntityDef.unpackConfig(streamLoader);
        IDK.unpackConfig(streamLoader);
        SpotAnim.unpackConfig(streamLoader);
        Varp.unpackConfig(streamLoader);
        VarBit.unpackConfig(streamLoader);
        ObjectDef.unpackConfig(streamLoader);
        Flo.unpackConfig(streamLoader);
        OverLayFlo317.unpackConfig(streamLoader);
        Model.initialize(65535, onDemandFetcher);
        initialized = true;
    }
Example #10
0
        static void ReadApkManifest(String manifestPath, String resourcesPath)
        {
            AxmlFile axml      = new AxmlFile(StreamLoader.FromFile(manifestPath));
            ArscFile resources = new ArscFile(File.ReadAllBytes(resourcesPath));

            if (!axml.Header.IsValid || !resources.Header.IsValid)
            {
                throw new InvalidOperationException();
            }

            AndroidManifest apk = AndroidManifest.Load(axml, resources);

            Console.WriteLine("Label: " + apk.Application.Label);
            Console.WriteLine("Package: " + apk.Package);
            Console.WriteLine("Icon: " + apk.Application.Icon);
            Console.WriteLine("Permissions: " + String.Join(", ", apk.UsesPermission.Select(p => p.Name)));
            Console.WriteLine("Services: " + String.Join(", ", apk.Application.Service));
            Console.WriteLine("Activities: " + String.Join(", ", apk.Application.Activity));
            Console.WriteLine("Reciever: " + String.Join(", ", apk.Application.Reciever));
            Console.WriteLine("Features: " + String.Join(", ", apk.UsesFeature));
            Console.WriteLine("Uses Libraries: " + String.Join(", ", apk.Application.UsesLibrary.Select(p => p.Name)));
        }
Example #11
0
        private void CompareResultGraphs(string results, string expectedResultsPath, bool reduced)
        {
            var expectedResultGraph = new Graph();

#if PORTABLE
            using (var s = File.OpenRead(expectedResultsPath))
            {
                StreamLoader.Load(expectedResultGraph, expectedResultsPath, s);
            }
#else
            FileLoader.Load(expectedResultGraph, expectedResultsPath);
#endif
            var resultSet = expectedResultGraph.GetUriNode(new Uri("http://www.w3.org/2001/sw/DataAccess/tests/result-set#ResultSet"));
            if (resultSet != null)
            {
                var rdfParser         = new SparqlRdfParser();
                var xmlParser         = new SparqlXmlParser();
                var actualResultSet   = new SparqlResultSet();
                var expectedResultSet = new SparqlResultSet();
                using (var tr = new StringReader(results))
                {
                    xmlParser.Load(actualResultSet, tr);
                }
#if PORTABLE
                rdfParser.Load(expectedResultSet, new StreamReader(expectedResultsPath));
#else
                rdfParser.Load(expectedResultSet, expectedResultsPath);
#endif
                var bnodeMap = new Dictionary <string, string>();
                CompareSparqlResults(actualResultSet, expectedResultSet, reduced, bnodeMap);
            }
            else
            {
                // This is a constructed graph
                var actualGraph = new Graph();
                actualGraph.LoadFromString(results);
                CompareTripleCollections(actualGraph.Triples, expectedResultGraph.Triples, reduced);
            }
        }
 public CollectionsXmlMapper(StreamLoader streamLoader)
 {
     this.streamLoader = streamLoader;
 }
Example #13
0
        private void BuildData()
        {
            linesTree.Nodes.Clear();
            blockView.Nodes.Clear();
            groupTree.Nodes.Clear();
            PropertyGrid_Stream.SelectedObject = null;
            stream = new StreamMapLoader(file);

            for (int i = 0; i < stream.GroupHeaders.Length; i++)
            {
                TreeNode node = new TreeNode("group" + i);
                node.Text = stream.GroupHeaders[i];
                StreamHeaderGroup HeaderGroup = new StreamHeaderGroup();
                HeaderGroup.HeaderName = node.Text;
                node.Tag = HeaderGroup;
                linesTree.Nodes.Add(node);
            }
            for (int i = 0; i < stream.Groups.Length; i++)
            {
                var      line = stream.Groups[i];
                TreeNode node = new TreeNode();
                node.Name = "GroupLoader" + i;
                node.Text = line.Name;
                node.Tag  = line;

                for (int x = line.startOffset; x < line.startOffset + line.endOffset; x++)
                {
                    var loader = stream.Loaders[x];
                    loader.AssignedGroup = line.Name;
                    loader.GroupID       = i;
                }

                groupTree.Nodes.Add(node);
            }
            for (int i = 0; i != stream.Lines.Length; i++)
            {
                var      line = stream.Lines[i];
                TreeNode node = new TreeNode();
                node.Name = line.Name;
                node.Text = line.Name;
                node.Tag  = line;

                List <StreamLoader> list = new List <StreamLoader>();
                for (int x = 0; x < stream.Loaders.Length; x++)
                {
                    var loader = stream.Loaders[x];
                    if (line.lineID >= loader.start && line.lineID <= loader.end)
                    {
                        var newLoader = new StreamLoader(loader);
                        list.Add(newLoader);
                    }
                }
                line.loadList = list.ToArray();
                linesTree.Nodes[line.groupID].Nodes.Add(node);
            }
            for (int i = 0; i < stream.Blocks.Length; i++)
            {
                TreeNode node = new TreeNode();
                node.Name = "Block" + i;
                node.Text = "Block: " + i;
                node.Tag  = stream.Blocks[i];
                blockView.Nodes.Add(node);
            }
        }
Example #14
0
        internal static async Task InjectDLL(Process Process, string DLLName, bool x86proc)
        {
            IntPtr hProcess = Process.Handle;

            // Length of string containing the DLL file name +1 byte padding
            IntPtr LenWrite = new IntPtr(DLLName.Length + 1);
            // Allocate memory within the virtual address space of the target process
            IntPtr AllocMem = VirtualAllocEx(hProcess, (IntPtr)null, LenWrite, AllocationType.Commit, MemoryProtection.ExecuteReadWrite); //allocation pour WriteProcessMemory

            // Write DLL file name to allocated memory in target process
            WriteProcessMemory(hProcess, AllocMem, Encoding.Default.GetBytes(DLLName), LenWrite, out uint bytesout);
            // Function pointer "Injector"
            IntPtr Injector;

            if (Environment.Is64BitProcess && x86proc)//WOW64 case
            {
                MODULEENTRY32 k32mod = GetModules((uint)Process.Id).SingleOrDefault(x => x.szModule.Equals("kernel32.dll", StringComparison.InvariantCultureIgnoreCase));
                using (PEFile pe = new PEFile(StreamLoader.FromFile(k32mod.szExePath)))//alternatively ReadProcessMemory... but source name?
                {
                    Version winver             = Environment.OSVersion.Version;
                    string  LoadLibraryVariant = winver.Major <= 6 && winver.Minor <= 1 ? "LoadLibraryA" : "LoadLibraryExA";
                    Injector = IntPtr.Add(k32mod.hModule, (int)pe.Export.GetExportFunctions().SingleOrDefault(x => x.Name.Equals(LoadLibraryVariant)).Address);
                }
            }
            else
            {
                Injector = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
            }

            if (Injector == null)
            {
                LogHost.Default.Error("Injector Error!");
                // return failed
                return;
            }

            // Create thread in target process, and store handle in hThread
            IntPtr hThread = CreateRemoteThread(hProcess, (IntPtr)null, IntPtr.Zero, Injector, AllocMem, 0, out bytesout);

            // Make sure thread handle is valid
            if (hThread == null)
            {
                //incorrect thread handle ... return failed
                LogHost.Default.Error("hThread [ 1 ] Error!");
                return;
            }
            // Time-out is 10 seconds...
            uint Result = WaitForSingleObject(hThread, 10 * 1000);

            // Check whether thread timed out...
            if (Result == 0x00000080L || Result == 0x00000102L || Result == 0xFFFFFFFF)
            {
                /* Thread timed out... */
                LogHost.Default.Error("hThread [ 2 ] Error!");
                // Make sure thread handle is valid before closing... prevents crashes.
                if (hThread != null)
                {
                    //Close thread in target process
                    CloseHandle(hThread);
                }
                return;
            }
            // Sleep for 1 second
            await Task.Delay(1000);//Thread.Sleep(1000);

            //for (int w = 0; !PersistentNamedPipeServer.Instance.IsConnected && w < 1000; w += 10)
            //{
            //    await Task.Delay(10);
            //}
            // Clear up allocated space ( Allocmem )
            VirtualFreeEx(hProcess, AllocMem, (UIntPtr)0, 0x8000);
            // Make sure thread handle is valid before closing... prevents crashes.
            if (hThread != null)
            {
                //Close thread in target process
                CloseHandle(hThread);
            }
            // return succeeded
            return;
        }
Example #15
0
        static void ReadDex(String filePath)
        {
            using (DexFile info = new DexFile(StreamLoader.FromFile(filePath)))
            {
                var items = info.STRING_ID_ITEM;

                foreach (string_data_row row in info.STRING_DATA_ITEM)
                {
                    Utils.ConsoleWriteMembers(row);
                }


                Utils.ConsoleWriteMembers(info.header);

                foreach (DexApi.map_item mapItem in info.map_list)
                {
                    Utils.ConsoleWriteMembers(mapItem);
                }

                foreach (annotation_set_row row in info.ANNOTATION_SET_ITEM)
                {
                    Utils.ConsoleWriteMembers(row);
                }

                foreach (annotation_set_ref_row row in info.ANNOTATION_SET_REF_LIST)
                {
                    Utils.ConsoleWriteMembers(row);
                }

                foreach (annotation_directory_row row in info.ANNOTATIONS_DIRECTORY_ITEM)
                {
                    Utils.ConsoleWriteMembers(row);
                }

                foreach (field_annotation_row row in info.field_annotation)
                {
                    Utils.ConsoleWriteMembers(row);
                }

                foreach (parameter_annotation_row row in info.parameter_annotation)
                {
                    Utils.ConsoleWriteMembers(row);
                }

                foreach (method_annotation_row row in info.method_annotation)
                {
                    Utils.ConsoleWriteMembers(row);
                }

                foreach (class_data_row row in info.CLASS_DATA_ITEM)
                {
                    Utils.ConsoleWriteMembers(row);
                }

                foreach (encoded_field_row row in info.encoded_field)
                {
                    Utils.ConsoleWriteMembers(row);
                }

                foreach (encoded_method_row row in info.encoded_method)
                {
                    Utils.ConsoleWriteMembers(row);
                }

                foreach (code_row row in info.CODE_ITEM)
                {
                    Utils.ConsoleWriteMembers(row);
                }

                foreach (try_item_row row in info.try_item)
                {
                    Utils.ConsoleWriteMembers(row);
                }

                foreach (encoded_catch_handler_row row in info.encoded_catch_handler_list)
                {
                    Utils.ConsoleWriteMembers(row);
                }

                foreach (encoded_type_addr_pair_row row in info.encoded_type_addr_pair)
                {
                    Utils.ConsoleWriteMembers(row);
                }

                foreach (type_list_row row in info.TYPE_LIST)
                {
                    Utils.ConsoleWriteMembers(row);
                }

                foreach (type_id_row row in info.TYPE_ID_ITEM)
                {
                    Utils.ConsoleWriteMembers(row);
                }

                foreach (proto_id_row row in info.PROTO_ID_ITEM)
                {
                    Utils.ConsoleWriteMembers(row);
                }

                foreach (field_id_row row in info.FIELD_ID_ITEM)
                {
                    Utils.ConsoleWriteMembers(row);
                }

                foreach (method_id_row row in info.METHOD_ID_ITEM)
                {
                    Utils.ConsoleWriteMembers(row);
                }

                foreach (class_def_row row in info.CLASS_DEF_ITEM)
                {
                    Utils.ConsoleWriteMembers(row);
                }
            }
        }
Example #16
0
        public void ReadFromFile(BinaryReader reader)
        {
            if (reader.ReadInt32() != 1299346515)
            {
                return;
            }

            if (reader.ReadInt32() != 0x6)
            {
                return;
            }

            int fileSize = reader.ReadInt32();
            int unk0     = reader.ReadInt32();

            int numGroups     = reader.ReadInt32();
            int groupOffset   = reader.ReadInt32();
            int numHeaders    = reader.ReadInt32();
            int headerOffset  = reader.ReadInt32();
            int numLines      = reader.ReadInt32();
            int lineOffset    = reader.ReadInt32();
            int numLoaders    = reader.ReadInt32();
            int loadersOffset = reader.ReadInt32();
            int numBlocks     = reader.ReadInt32();
            int blockOffset   = reader.ReadInt32();
            int numHashes     = reader.ReadInt32();
            int hashOffset    = reader.ReadInt32();
            int poolSize      = reader.ReadInt32();
            int poolOffset    = reader.ReadInt32();

            if (reader.BaseStream.Position != groupOffset)
            {
                throw new FormatException();
            }

            groups = new StreamGroup[numGroups];
            for (int i = 0; i < numGroups; i++)
            {
                StreamGroup map = new StreamGroup();
                map.nameIDX     = reader.ReadInt32();
                map.Name        = ReadFromBuffer((long)((ulong)map.nameIDX + (ulong)poolOffset), reader.BaseStream.Position, reader);
                map.Type        = reader.ReadInt32();
                map.Unk01       = reader.ReadInt32();
                map.startOffset = reader.ReadInt32();
                map.endOffset   = reader.ReadInt32();
                map.unk5        = reader.ReadInt32();
                groups[i]       = map;
            }

            if (reader.BaseStream.Position != headerOffset)
            {
                throw new FormatException();
            }

            groupHeaders = new string[numHeaders];
            ulong[] ulongHeaders = new ulong[numHeaders];

            for (int i = 0; i < numHeaders; i++)
            {
                ulongHeaders[i] = reader.ReadUInt64();
                groupHeaders[i] = ReadFromBuffer((long)(ulongHeaders[i] + (ulong)poolOffset), reader.BaseStream.Position, reader);
            }

            if (reader.BaseStream.Position != lineOffset)
            {
                throw new FormatException();
            }

            lines = new StreamLine[numLines];

            for (int i = 0; i < numLines; i++)
            {
                StreamLine map = new StreamLine();
                map.nameIDX  = reader.ReadInt32();
                map.lineID   = reader.ReadInt32();
                map.groupID  = reader.ReadInt32();
                map.LoadType = reader.ReadInt32();
                map.flagIDX  = reader.ReadInt32();
                map.Unk5     = reader.ReadInt32();
                map.Unk10    = reader.ReadUInt64();
                map.Unk11    = reader.ReadUInt64();
                map.Unk12    = reader.ReadInt32();
                map.Unk13    = reader.ReadInt32();
                map.Unk14    = reader.ReadInt32();
                map.Unk15    = reader.ReadInt32();
                map.Group    = groupHeaders[map.groupID];
                map.Name     = ReadFromBuffer((long)((ulong)map.nameIDX + (ulong)poolOffset), reader.BaseStream.Position, reader);
                map.Flags    = ReadBufferSpecial((long)((ulong)map.flagIDX + (ulong)poolOffset), reader.BaseStream.Position, reader).TrimEnd('\0').Replace('\0', '|');
                lines[i]     = map;
            }

            if (reader.BaseStream.Position != loadersOffset)
            {
                throw new FormatException();
            }

            loaders = new StreamLoader[numLoaders];

            for (int i = 0; i < numLoaders; i++)
            {
                StreamLoader map = new StreamLoader();
                map.start       = reader.ReadInt32();
                map.end         = reader.ReadInt32();
                map.type        = reader.ReadInt32();
                map.loaderSubID = reader.ReadInt32();
                map.loaderID    = reader.ReadInt32();
                map.LoadType    = reader.ReadInt32();
                map.pathIDX     = reader.ReadInt32();
                map.entityIDX   = reader.ReadInt32();
                map.Path        = ReadFromBuffer((long)((ulong)map.pathIDX + (ulong)poolOffset), reader.BaseStream.Position, reader);
                map.Entity      = ReadBufferSpecial((long)((ulong)map.entityIDX + (ulong)poolOffset), reader.BaseStream.Position, reader).TrimEnd('\0').Replace('\0', '|');
                loaders[i]      = map;
            }

            if (reader.BaseStream.Position != blockOffset)
            {
                throw new FormatException();
            }

            blocks = new StreamBlock[numBlocks];
            for (int i = 0; i < numBlocks; i++)
            {
                StreamBlock map = new StreamBlock();
                map.startOffset = reader.ReadInt32();
                map.endOffset   = reader.ReadInt32();
                blocks[i]       = map;
            }

            if (reader.BaseStream.Position != hashOffset)
            {
                throw new FormatException();
            }

            hashes = new ulong[numHashes];

            for (int i = 0; i < numHashes; i++)
            {
                hashes[i] = reader.ReadUInt64();
            }

            if (reader.BaseStream.Position != poolOffset)
            {
                throw new FormatException();
            }

            reader.BaseStream.Seek(poolSize, SeekOrigin.Current);

            if (reader.BaseStream.Position != reader.BaseStream.Length)
            {
                throw new FormatException("Borked this up");
            }
        }
Example #17
0
        static void ReadApk(String filePath)
        {
            using (ApkFile apk = new ApkFile(filePath))
            {
                Console.WriteLine("Package: {0}", apk.AndroidManifest.Package);
                Console.WriteLine("Application name: {0} ({1})", apk.AndroidManifest.Application.Label, apk.AndroidManifest.VersionName);

                if (apk.MfFile != null)
                {
                    UInt32 totalFiles   = 0;
                    UInt32 hashNotFound = 0;
                    UInt32 invalidHash  = 0;
                    foreach (String apkFilePath in apk.GetFiles())
                    {
                        totalFiles++;
                        String sHash = apk.MfFile[apkFilePath];
                        if (sHash == null)
                        {
                            //Console.WriteLine("Hash not found for file: {0}", apkFilePath);
                            hashNotFound++;
                        }
                        else if (!apk.MfFile.ValidateHash(apkFilePath, apk.GetFile(apkFilePath)))
                        {
                            //Console.WriteLine("InvalidHash: {0} ({1})", apkFilePath, sHash);
                            invalidHash++;
                        }
                    }

                    Console.WriteLine("Total files: {0:N0}", totalFiles);
                    if (hashNotFound > 0)
                    {
                        Console.WriteLine("Hash Not found: {0:N0}", hashNotFound);
                    }
                    if (invalidHash > 0)
                    {
                        Console.WriteLine("Invalid hash: {0:N0}", invalidHash);
                    }
                }

                TreeDto root = BuildTree(apk.GetHeaderFiles().ToArray(), '/');
                String  test = ConvertTreeToStringRec(root, 0);

                foreach (String xmlFile in apk.GetHeaderFiles())
                {
                    switch (Path.GetExtension(xmlFile).ToLowerInvariant())
                    {
                    case ".xml":
                        /*if(xmlFile.Equals("AndroidManifest.xml", StringComparison.OrdinalIgnoreCase))
                         *      continue;*/

                        Byte[] file = apk.GetFile(xmlFile);
                        //ManifestFile manifest = new ManifestFile(file);
                        //Console.WriteLine(manifest.Xml.ConvertToString());

                        AxmlFile axml = new AxmlFile(StreamLoader.FromMemory(file, xmlFile));
                        if (axml.Header.IsValid)
                        {
                            XmlNode xml = axml.RootNode;
                            Console.WriteLine("---" + xmlFile + ":");
                            Console.WriteLine(xml.ConvertToString());
                        }
                        else
                        {
                            Console.WriteLine("---" + xmlFile + ":");
                            Console.WriteLine(System.Text.Encoding.UTF8.GetString(file));
                        }
                        break;
                    }
                }

                ReadApkManifestRecursive(apk.AndroidManifest);
            }
        }
Example #18
0
 public void Setup()
 {
     loader = new StreamLoader();
 }
Example #19
0
 /// <summary>Create instance of test loader</summary>
 /// <param name="filePath"></param>
 public LookupLoader(String filePath)
 {
     this._baseLoader = StreamLoader.FromFile(filePath);
     this._map        = new Byte[new FileInfo(filePath).Length];
 }
Example #20
0
        static void ReadManifest(String filePath)
        {
            AxmlFile manifest = new AxmlFile(StreamLoader.FromFile(filePath));

            Console.Write(manifest.RootNode.ConvertToString());
        }
Example #21
0
        public void ReadFromFile(BinaryReader reader)
        {
            if (reader.ReadInt32() != 1299346515)
            {
                return;
            }

            if (reader.ReadInt32() != 0x6)
            {
                return;
            }

            int fileSize = reader.ReadInt32();
            int unk0     = reader.ReadInt32();

            int numGroups     = reader.ReadInt32();
            int groupOffset   = reader.ReadInt32();
            int numHeaders    = reader.ReadInt32();
            int headerOffset  = reader.ReadInt32();
            int numLines      = reader.ReadInt32();
            int lineOffset    = reader.ReadInt32();
            int numLoaders    = reader.ReadInt32();
            int loadersOffset = reader.ReadInt32();
            int numBlocks     = reader.ReadInt32();
            int blockOffset   = reader.ReadInt32();
            int numHashes     = reader.ReadInt32();
            int hashOffset    = reader.ReadInt32();
            int poolSize      = reader.ReadInt32();
            int poolOffset    = reader.ReadInt32();

            Debug.Assert(reader.BaseStream.Position == groupOffset, "Failed to reach the starting offset for group declaration!");

            groups = new StreamGroup[numGroups];
            for (int i = 0; i < numGroups; i++)
            {
                StreamGroup map = new StreamGroup();
                map.nameIDX     = reader.ReadInt32();
                map.Name        = ReadFromBuffer((long)((ulong)map.nameIDX + (ulong)poolOffset), reader.BaseStream.Position, reader);
                map.Type        = (GroupTypes)reader.ReadInt32();
                map.Unk01       = reader.ReadInt32();
                map.startOffset = reader.ReadInt32();
                map.endOffset   = reader.ReadInt32();
                map.unk5        = reader.ReadInt32();
                groups[i]       = map;
            }

            Debug.Assert(reader.BaseStream.Position == headerOffset, "Did not reach the header starting offset");

            groupHeaders = new string[numHeaders];
            ulong[] ulongHeaders = new ulong[numHeaders];

            for (int i = 0; i < numHeaders; i++)
            {
                ulongHeaders[i] = reader.ReadUInt64();
                groupHeaders[i] = ReadFromBuffer((long)(ulongHeaders[i] + (ulong)poolOffset), reader.BaseStream.Position, reader);
            }

            Debug.Assert(reader.BaseStream.Position == lineOffset, "Did not reach the line data starting offset!");

            lines = new StreamLine[numLines];

            for (int i = 0; i < numLines; i++)
            {
                StreamLine map = new StreamLine();
                map.nameIDX  = reader.ReadInt32();
                map.lineID   = reader.ReadInt32();
                map.groupID  = reader.ReadInt32();
                map.LoadType = reader.ReadInt32();
                map.flagIDX  = reader.ReadInt32();
                map.Unk5     = reader.ReadInt32();
                map.Unk10    = reader.ReadUInt64();
                map.Unk11    = reader.ReadUInt64();
                map.Unk12    = reader.ReadInt32();
                map.Unk13    = reader.ReadInt32();
                map.Unk14    = reader.ReadInt32();
                map.Unk15    = reader.ReadInt32();
                map.Group    = groupHeaders[map.groupID];
                map.Name     = ReadFromBuffer((long)((ulong)map.nameIDX + (ulong)poolOffset), reader.BaseStream.Position, reader);
                map.Flags    = ReadBufferSpecial((long)((ulong)map.flagIDX + (ulong)poolOffset), reader.BaseStream.Position, reader).TrimEnd('\0').Replace('\0', '|');
                lines[i]     = map;
            }

            Debug.Assert(reader.BaseStream.Position == loadersOffset, "Did not reach the loader data starting offset!");

            loaders = new StreamLoader[numLoaders];

            for (int i = 0; i < numLoaders; i++)
            {
                StreamLoader map = new StreamLoader();
                map.start = reader.ReadInt32();
                map.end   = reader.ReadInt32();
                map.Type  = (GroupTypes)reader.ReadInt32();

                map.LoaderSubID = reader.ReadInt32();
                map.LoaderID    = reader.ReadInt32();
                map.LoadType    = reader.ReadInt32();
                map.pathIDX     = reader.ReadInt32();
                map.entityIDX   = reader.ReadInt32();
                map.Path        = ReadFromBuffer((long)((ulong)map.pathIDX + (ulong)poolOffset), reader.BaseStream.Position, reader);
                map.Entity      = ReadBufferSpecial((long)((ulong)map.entityIDX + (ulong)poolOffset), reader.BaseStream.Position, reader).TrimEnd('\0').Replace('\0', '|');
                loaders[i]      = map;
            }

            Debug.Assert(reader.BaseStream.Position == blockOffset, "Did not reach the block declaration starting offset!");

            blocks = new StreamBlock[numBlocks];
            for (int i = 0; i < numBlocks; i++)
            {
                StreamBlock map = new StreamBlock();
                map.startOffset = reader.ReadInt32();
                map.endOffset   = reader.ReadInt32();
                map.Hashes      = new ulong[map.endOffset - map.startOffset];
                blocks[i]       = map;
            }

            Debug.Assert(reader.BaseStream.Position == hashOffset, "Did not reach the block hashes starting offset!");

            hashes = new ulong[numHashes];

            for (int i = 0; i < numHashes; i++)
            {
                hashes[i] = reader.ReadUInt64();
            }

            for (int i = 0; i < numBlocks; i++)
            {
                var block = blocks[i];
                Array.Copy(hashes, block.startOffset, block.Hashes, 0, block.Hashes.Length);
            }

            Debug.Assert(reader.BaseStream.Position == poolOffset, "Did not reach the buffer pool starting offset!");

            reader.BaseStream.Seek(poolSize, SeekOrigin.Current);

            Debug.Assert(reader.BaseStream.Position == reader.BaseStream.Length, "Did not reach the end of the file!");
        }
Example #22
0
 public CollectionXmlMapper(StreamLoader streamLoader)
 {
     this.streamLoader = streamLoader;
 }
Example #23
0
        static void Main(string[] args)
        {
            Console.WriteLine("Skater.net Deobfuscator \n \n");

            int         nombreDeStringEncodée = 0;
            ModuleDefMD module = ModuleDefMD.Load(args[0]);
            //Type which contains String Initialization
            TypeDef InitialType = null;
            //We grab native method to count all of them
            List <MethodDef> ListOfNativeMeths = new List <MethodDef>();
            Stopwatch        stopWatch         = new Stopwatch();

            stopWatch.Start();
            foreach (TypeDef t in module.GetTypes())
            {
                foreach (MethodDef m in t.Methods)
                {
                    if (m.Name.Contains("OOOOlx"))
                    {
                        ListOfNativeMeths.Add(m);
                    }
                }
            }
            nombreDeStringEncodée = ListOfNativeMeths.Count();
            //We grab the type to find cctor afterwards
            InitialType = ListOfNativeMeths.First().DeclaringType;
            string DLLName = ListOfNativeMeths.First().ImplMap.Module.Name;

            Console.WriteLine("Native DLL Name : " + DLLName);
            //We stock strings in a list
            List <string> deHexedstring = new List <string>();


            //Reading PE
            using (PEFile file = new PEFile(StreamLoader.FromFile(Path.GetDirectoryName(args[0]) + @"\" + DLLName)))
            {
                var section = file.Header.Sections;
                foreach (var item in section)
                {
                    var realName = new string(item.Name);
                    //Strings are stored in .data section
                    if (realName.Contains(".data"))
                    {
                        //offset of the beginning of the section
                        var start = item.PointerToRawData;
                        //calculation of section's size
                        var length = item.PointerToRawData + item.SizeOfRawData;

                        //We copy all bytes into a list
                        List <byte> b = new List <byte>();
                        using (FileStream fsSourceDDS = new FileStream(Path.GetDirectoryName(args[0]) + @"\" + DLLName, FileMode.Open, FileAccess.Read))
                            using (BinaryReader binaryReader = new BinaryReader(fsSourceDDS))
                            {
                                fsSourceDDS.Seek(start, SeekOrigin.Begin);
                                while (start < length)
                                {
                                    byte y = binaryReader.ReadByte();
                                    b.Add(y);
                                    start++;
                                }
                            }
                        dataSectionContent = b.ToArray();

                        string input = ByteArrayToString(dataSectionContent);

                        //we split the whole strings
                        string[] datacontent = input.Split(new string[] { "00" }, StringSplitOptions.None);

                        //We remove empty results
                        datacontent = datacontent.Where(x => !string.IsNullOrEmpty(x)).ToArray();


                        //We only need values associated to strings
                        string[] encodedstring = datacontent.Take(nombreDeStringEncodée).Select(i => i.ToString()).ToArray();


                        foreach (var hexedstring in encodedstring)
                        {
                            deHexedstring.Add(Encoding.UTF8.GetString(StringToByteArray(hexedstring)));
                        }
                    }
                }
            }
            //That's why we needed to find the type
            MethodDef cctor = InitialType.FindStaticConstructor();

            if (cctor == null)
            {
                Console.WriteLine("Impossible to find Method which initialize strings");
                return;
            }
            //We make a dictionnary to replace values of field
            Dictionary <FieldDef, string> FieldValue = new Dictionary <FieldDef, string>();

            for (int i = 0; i < cctor.Body.Instructions.Count - 1; i++)
            {
                if (cctor.Body.Instructions[i].OpCode == OpCodes.Ldsfld && cctor.Body.Instructions[i + 1].OpCode == OpCodes.Call && cctor.Body.Instructions[i + 2].OpCode == OpCodes.Stsfld)
                {
                    cctor.Body.Instructions[i].OpCode     = OpCodes.Nop;
                    cctor.Body.Instructions[i + 1].OpCode = OpCodes.Ldstr;
                    string decrypted = smethod_0(deHexedstring[0]);
                    cctor.Body.Instructions[i + 1].Operand = decrypted;
                    FieldValue.Add((FieldDef)cctor.Body.Instructions[i + 2].Operand, decrypted);
                    deHexedstring.RemoveAt(0);
                }
            }
            int DecryptedStrings = 0;

            //Replacing field values
            foreach (TypeDef type in module.Types)
            {
                foreach (MethodDef method in type.Methods)
                {
                    if (method.HasBody && method.Body.HasInstructions)
                    {
                        Cleaner(method);
                        for (int i = 0; i < method.Body.Instructions.Count - 1; i++)
                        {
                            try
                            {
                                if (method.Body.Instructions[i].OpCode == OpCodes.Ldsfld)
                                {
                                    FieldDef fld = (FieldDef)method.Body.Instructions[i].Operand;
                                    if (FieldValue.Keys.Contains(fld))
                                    {
                                        method.Body.Instructions[i].OpCode  = OpCodes.Ldstr;
                                        method.Body.Instructions[i].Operand = FieldValue[fld];
                                        DecryptedStrings++;
                                    }
                                }
                            }
                            catch
                            {
                            }
                        }
                    }
                }
            }
            stopWatch.Stop();
            Console.WriteLine("Done ! Elapsed time : " + stopWatch.Elapsed.TotalSeconds);
            //Saving ASM
            string SavingPath = module.Kind == ModuleKind.Dll ? args[0].Replace(".dll", "-Deobfuscated.dll") : args[0].Replace(".exe", "-Deobfuscated.exe");
            var    opts       = new ModuleWriterOptions(module);

            opts.MetaDataOptions.Flags = MetaDataFlags.PreserveAll;
            opts.Logger = DummyLogger.NoThrowInstance;
            module.Write(SavingPath, opts);
            Console.WriteLine("Sucessfully decrypted {0} strings", DecryptedStrings);
            Console.WriteLine("Control Flow removed", DecryptedStrings);
            Console.ReadLine();
        }
        private void BuildData()
        {
            linesTree.Nodes.Clear();
            blockView.Nodes.Clear();
            groupTree.Nodes.Clear();
            stream = new StreamMapLoader(file);

            for (int i = 0; i < stream.groupHeaders.Length; i++)
            {
                TreeNode node = new TreeNode("group" + i);
                node.Text = stream.groupHeaders[i];
                node.Tag  = "Header";
                linesTree.Nodes.Add(node);
            }
            for (int i = 0; i < stream.groups.Length; i++)
            {
                var      line = stream.groups[i];
                TreeNode node = new TreeNode();
                node.Name = "GroupLoader" + i;
                node.Text = line.Name;
                node.Tag  = line;

                for (int x = line.startOffset; x < line.startOffset + line.endOffset; x++)
                {
                    var loader = stream.loaders[x];
                    loader.Group = line.Name;
                }

                groupTree.Nodes.Add(node);
            }
            for (int i = 0; i != stream.lines.Length; i++)
            {
                var      line = stream.lines[i];
                TreeNode node = new TreeNode();
                node.Name = line.Name;
                node.Text = line.Name;
                node.Tag  = line;

                List <StreamLoader> list = new List <StreamLoader>();
                for (int x = 0; x < stream.loaders.Length; x++)
                {
                    var loader = stream.loaders[x];
                    if (line.lineID >= loader.start && line.lineID <= loader.end)
                    {
                        var newLoader = new StreamLoader(loader);
                        list.Add(newLoader);
                    }
                }
                line.loadList = list.ToArray();
                linesTree.Nodes[line.groupID].Nodes.Add(node);
            }
            for (int i = 0; i < stream.blocks.Length; i++)
            {
                var          block = stream.blocks[i];
                List <ulong> hash  = new List <ulong>();
                for (int x = block.startOffset; x < block.endOffset; x++)
                {
                    hash.Add(stream.hashes[x]);
                }
                block.Hashes = hash.ToArray();

                TreeNode node = new TreeNode();
                node.Name = "Block" + i;
                node.Text = "Block: " + i;
                node.Tag  = block;
                blockView.Nodes.Add(node);
            }
        }
Example #25
0
        static void ReadSo(String binFile)
        {
            using (ElfFile file = new ElfFile(StreamLoader.FromFile(binFile)))
            {
                Utils.ConsoleWriteMembers(file.Header.Identification);
                if (file.Header.IsValid)
                {
                    DebugStringSection debugSection = file.GetDebugStringSection();
                    if (debugSection != null)
                    {
                        foreach (var symbolSec in debugSection)
                        {
                            Utils.ConsoleWriteMembers(symbolSec);
                        }
                    }

                    foreach (var noteSec in file.GetNotesSections())
                    {
                        foreach (var note in noteSec)
                        {
                            Utils.ConsoleWriteMembers(note);
                        }
                    }

                    Utils.ConsoleWriteMembers(file.Header.Header);

                    foreach (var strSec in file.GetStringSections())
                    {
                        foreach (var str in strSec)
                        {
                            Utils.ConsoleWriteMembers(str);
                        }
                    }

                    foreach (var symbolSec in file.GetSymbolSections())
                    {
                        foreach (var symbol in symbolSec)
                        {
                            Utils.ConsoleWriteMembers(symbol);
                        }
                    }

                    foreach (var relSec in file.GetRelocationSections())
                    {
                        foreach (var rel in relSec)
                        {
                            Utils.ConsoleWriteMembers(rel);
                        }
                    }

                    foreach (var relaSec in file.GetRelocationASections())
                    {
                        foreach (var rela in relaSec)                       //TODO: Check it
                        {
                            Utils.ConsoleWriteMembers(rela);
                        }
                    }

                    SymbolSection symbols = file.GetSymbolSections().FirstOrDefault();
                    if (symbols != null)
                    {
                        foreach (var item in symbols)
                        {
                            if (String.IsNullOrEmpty(item.Name))
                            {
                                Console.WriteLine("EMPTY REF");
                            }
                        }

                        /*StringSection strings = file.GetStringSections().FirstOrDefault(p => p.Section.Name == ".dynstr");
                         * foreach(var item in symbols)
                         * {
                         *      String str = strings[item.st_name];
                         *      Console.WriteLine(str);
                         *      if(String.IsNullOrEmpty(str))
                         *              Console.WriteLine("EMPTY REF");
                         *      if(item.st_shndx != 0)
                         *      {
                         *              Section someSec = file.Sections.First(p => p.Index == item.st_shndx);
                         *              Utils.ConsoleWriteMembers(someSec);
                         *      }
                         * }*/
                    }

                    String[] secTypes = file.Sections.Select(p => p.sh_type.ToString()).Distinct().ToArray();
                }
            }
        }
 public PercentileXmlMapper(StreamLoader streamLoader)
 {
     this.streamLoader = streamLoader;
 }
Example #27
0
 public PercentileXmlMapper(StreamLoader streamLoader)
 {
     this.streamLoader = streamLoader;
 }