public override IEnumerable <DependencyListEntry> GetStaticDependencies(NodeFactory factory)
        {
            PEMemoryBlock resourceDirectory = _module.PEReader.GetSectionData(_module.PEReader.PEHeaders.CorHeader.ResourcesDirectory.RelativeVirtualAddress);

            foreach (var resourceHandle in _module.MetadataReader.ManifestResources)
            {
                ManifestResource resource = _module.MetadataReader.GetManifestResource(resourceHandle);

                // Don't try to process linked resources or resources in other assemblies
                if (!resource.Implementation.IsNil)
                {
                    continue;
                }

                string resourceName = _module.MetadataReader.GetString(resource.Name);
                if (resourceName == "ILLink.Descriptors.xml")
                {
                    BlobReader reader = resourceDirectory.GetReader((int)resource.Offset, resourceDirectory.Length - (int)resource.Offset);
                    int        length = (int)reader.ReadUInt32();

                    UnmanagedMemoryStream ms;
                    unsafe
                    {
                        ms = new UnmanagedMemoryStream(reader.CurrentPointer, length);
                    }

                    var metadataManager = (UsageBasedMetadataManager)factory.MetadataManager;
                    return(DescriptorMarker.GetDependencies(factory, ms, resource, _module, "resource " + resourceName + " in " + _module.ToString(), metadataManager.FeatureSwitches));
                }
            }
            return(Array.Empty <DependencyListEntry>());
        }
Example #2
0
        public void CreateSimpleEmbeddedResource()
        {
            const string resourceName = "MyResource";
            const string resourceData = "Lorem ipsum dolor sit amet.";

            var testData = Encoding.UTF8.GetBytes(resourceData);

            // set up temp assembly.
            var assembly       = Utilities.CreateTempNetAssembly();
            var tableStream    = assembly.NetDirectory.MetadataHeader.GetStream <TableStream>();
            var resourcesTable = tableStream.GetTable <ManifestResource>();

            // add resource.
            var resource = new ManifestResource(resourceName, ManifestResourceAttributes.Public, testData);

            resourcesTable.Add(resource);

            // build and validate.
            assembly       = Utilities.RebuildNetAssembly(assembly);
            tableStream    = assembly.NetDirectory.MetadataHeader.GetStream <TableStream>();
            resourcesTable = tableStream.GetTable <ManifestResource>();
            resource       = resourcesTable.FirstOrDefault(x => x.Name == resourceName);

            Assert.IsNotNull(resource);
            Assert.AreEqual(resourceData, Encoding.UTF8.GetString(resource.Data));
        }
        private unsafe Stream GetResourceStream(PEReader peReader, ManifestResource resource)
        {
            checked // arithmetic overflow here could cause AV
            {
                PEMemoryBlock memoryBlock  = peReader.GetEntireImage();
                byte *        peImageStart = memoryBlock.Pointer;
                byte *        peImageEnd   = peImageStart + memoryBlock.Length;

                // Locate resource's offset within the Portable Executable image.
                int resourcesDirectoryOffset;
                if (!peReader.PEHeaders.TryGetDirectoryOffset(peReader.PEHeaders.CorHeader.ResourcesDirectory, out resourcesDirectoryOffset))
                {
                    throw new InvalidDataException("Failed to extract the resources from assembly when getting the offset to resources in the PE file.");
                }

                byte *resourceStart = peImageStart + resourcesDirectoryOffset + resource.Offset;

                // We need to get the resource length out from the first int in the resourceStart pointer
                if (resourceStart >= peImageEnd - sizeof(int))
                {
                    throw new InvalidDataException("Failed to extract the resources from assembly because resource offset was out of bounds.");
                }

                int resourceLength = new BlobReader(resourceStart, sizeof(int)).ReadInt32();
                resourceStart += sizeof(int);
                if (resourceLength < 0 || resourceStart >= peImageEnd - resourceLength)
                {
                    throw new InvalidDataException($"Failed to extract the resources from assembly because resource offset or length was out of bounds.");
                }

                return(new UnmanagedMemoryStream(resourceStart, resourceLength));
            }
        }
Example #4
0
            public AssemblyFeatureInfo(EcmaModule module, IReadOnlyDictionary <string, bool> featureSwitchValues)
            {
                Module           = module;
                BlockedResources = new HashSet <string>();

                PEMemoryBlock resourceDirectory = module.PEReader.GetSectionData(module.PEReader.PEHeaders.CorHeader.ResourcesDirectory.RelativeVirtualAddress);

                foreach (var resourceHandle in module.MetadataReader.ManifestResources)
                {
                    ManifestResource resource = module.MetadataReader.GetManifestResource(resourceHandle);

                    // Don't try to process linked resources or resources in other assemblies
                    if (!resource.Implementation.IsNil)
                    {
                        continue;
                    }

                    string resourceName = module.MetadataReader.GetString(resource.Name);
                    if (resourceName == "ILLink.Substitutions.xml")
                    {
                        BlobReader reader = resourceDirectory.GetReader((int)resource.Offset, resourceDirectory.Length - (int)resource.Offset);
                        int        length = (int)reader.ReadUInt32();

                        UnmanagedMemoryStream ms;
                        unsafe
                        {
                            ms = new UnmanagedMemoryStream(reader.CurrentPointer, length);
                        }

                        BlockedResources = SubstitutionsReader.GetSubstitutions(module.Context, XmlReader.Create(ms), module, featureSwitchValues);
                    }
                }
            }
        public void TestLinkEmbedManifest()
        {
            InstallerLinkerArguments args = new InstallerLinkerArguments();

            try
            {
                ConfigFile         configFile         = new ConfigFile();
                SetupConfiguration setupConfiguration = new SetupConfiguration();
                configFile.Children.Add(setupConfiguration);
                args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
                Console.WriteLine("Writing '{0}'", args.config);
                configFile.SaveAs(args.config);
                args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe");
                Console.WriteLine("Linking '{0}'", args.output);
                args.template = dotNetInstallerExeUtils.Executable;
                // manifest
                Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
                args.manifest = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Manifests\\asInvoker.manifest");
                // link
                InstallerLib.InstallerLinker.CreateInstaller(args);
                // check that the linker generated output
                Assert.IsTrue(File.Exists(args.output));
                Assert.IsTrue(new FileInfo(args.output).Length > 0);
                using (ResourceInfo ri = new ResourceInfo())
                {
                    ri.Load(args.output);
                    List <Resource> manifests = ri.Resources[new ResourceId(Kernel32.ResourceTypes.RT_MANIFEST)]; // RT_MANIFEST
                    Assert.IsNotNull(manifests);

                    int  expectedManifestFiles = 1;
                    bool usingHtmlInstaller    = dotNetInstallerExeUtils.Executable.EndsWith("htmlInstaller.exe");
                    if (usingHtmlInstaller)
                    {
                        // the stub file already has an embedded manifest
                        expectedManifestFiles++;
                    }

                    Assert.AreEqual(expectedManifestFiles, manifests.Count);
                    ManifestResource manifest = (ManifestResource)manifests[0]; // RT_MANIFEST
                    Console.WriteLine(manifest.Manifest.OuterXml);
                    XmlNamespaceManager manifestNamespaceManager = new XmlNamespaceManager(manifest.Manifest.NameTable);
                    manifestNamespaceManager.AddNamespace("v1", "urn:schemas-microsoft-com:asm.v1");
                    manifestNamespaceManager.AddNamespace("v3", "urn:schemas-microsoft-com:asm.v3");
                    string level = manifest.Manifest.SelectSingleNode("//v3:requestedExecutionLevel",
                                                                      manifestNamespaceManager).Attributes["level"].Value;
                    Assert.AreEqual(level, "asInvoker");
                }
            }
            finally
            {
                if (File.Exists(args.config))
                {
                    File.Delete(args.config);
                }
                if (File.Exists(args.output))
                {
                    File.Delete(args.output);
                }
            }
        }
Example #6
0
        public void CreateSimpleEmbeddedResource()
        {
            const string resourceName = "MyResource";
            const string resourceData = "Lorem ipsum dolor sit amet.";

            var testData = Encoding.UTF8.GetBytes(resourceData);

            // set up temp assembly.
            var assembly = Utilities.CreateTempNetAssembly();
            var tableStream = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>();
            var resourcesTable = tableStream.GetTable<ManifestResource>();

            // add resource.
            var resource = new ManifestResource(resourceName, ManifestResourceAttributes.Public, testData);
            resourcesTable.Add(resource);

            // build and validate.
            assembly = Utilities.RebuildNetAssembly(assembly);
            tableStream = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>();
            resourcesTable = tableStream.GetTable<ManifestResource>();
            resource = resourcesTable.FirstOrDefault(x => x.Name == resourceName);

            Assert.IsNotNull(resource);
            Assert.AreEqual(resourceData, Encoding.UTF8.GetString(resource.Data));
        }
Example #7
0
        private unsafe InternalManifestResourceInfo GetInternalManifestResourceInfo(string resourceName)
        {
            InternalManifestResourceInfo     result            = new InternalManifestResourceInfo();
            ManifestResourceHandleCollection manifestResources = MetadataReader.ManifestResources;

            foreach (var resourceHandle in manifestResources)
            {
                ManifestResource resource = MetadataReader.GetManifestResource(resourceHandle);
                if (MetadataReader.StringComparer.Equals(resource.Name, resourceName))
                {
                    result.Found = true;
                    if (resource.Implementation.IsNil)
                    {
                        checked
                        {
                            // Embedded data resource
                            result.ResourceLocation = ResourceLocation.Embedded | ResourceLocation.ContainedInManifestFile;
                            PEReader pe = PEReader;

                            PEMemoryBlock resourceDirectory = pe.GetSectionData(pe.PEHeaders.CorHeader.ResourcesDirectory.RelativeVirtualAddress);
                            BlobReader    reader            = resourceDirectory.GetReader((int)resource.Offset, resourceDirectory.Length - (int)resource.Offset);
                            uint          length            = reader.ReadUInt32();
                            result.PointerToResource = reader.CurrentPointer;

                            // Length check the size of the resource to ensure it fits in the PE file section, note, this is only safe as its in a checked region
                            if (length + sizeof(Int32) > reader.Length)
                            {
                                throw new BadImageFormatException();
                            }
                            result.SizeOfResource = length;
                        }
                    }
                    else
                    {
                        if (resource.Implementation.Kind == HandleKind.AssemblyFile)
                        {
                            // Get file name
                            result.ResourceLocation = default(ResourceLocation);
                            AssemblyFile file = MetadataReader.GetAssemblyFile((AssemblyFileHandle)resource.Implementation);
                            if (file.ContainsMetadata)
                            {
                                result.ResourceLocation = ResourceLocation.Embedded;
                                throw new PlatformNotSupportedException(); // Support for multi-module assemblies is not implemented on this platform
                            }
                            result.FileName = MetadataReader.GetString(file.Name);
                        }
                        else if (resource.Implementation.Kind == HandleKind.AssemblyReference)
                        {
                            // Resolve assembly reference
                            result.ResourceLocation = ResourceLocation.ContainedInAnotherAssembly;
                            RuntimeAssemblyName destinationAssemblyName = ((AssemblyReferenceHandle)resource.Implementation).ToRuntimeAssemblyName(MetadataReader);
                            result.ReferencedAssembly = RuntimeAssembly.GetRuntimeAssemblyIfExists(destinationAssemblyName);
                        }
                    }
                }
            }

            return(result);
        }
Example #8
0
 public void AddManifestResource(ManifestResource mr)
 {
     if (manifestResources == null)
     {
         manifestResources = new ArrayList();
     }
     manifestResources.Add(mr);
 }
 public ManifestResourceEntry(PEFile module, ManifestResourceHandle handle)
 {
     this.metadataOffset   = module.Reader.PEHeaders.MetadataStartOffset;
     this.module           = module;
     this.metadata         = module.Metadata;
     this.handle           = handle;
     this.manifestResource = metadata.GetManifestResource(handle);
 }
        public void TestMultipleHashManifest()
        {
            var multipleHashManifest = Path.Combine(RootPath, "MultipleHashManifest.bin");
            var manifestBytes        = File.ReadAllBytes(multipleHashManifest);
            var manifest             = ManifestResource.Create();

            manifest.InitFromRawDecompressed(manifestBytes);
            CheckMultipleHashManifest(manifest);
        }
Example #11
0
        private static void ApplyManifest(string path)
        {
            var manifestResource = new ManifestResource();
            var manifestXml      = new XmlDocument();

            manifestXml.LoadXml(Properties.Resources.RequireAdministratorManifest);
            manifestResource.Manifest = manifestXml;
            manifestResource.SaveTo(path);
        }
Example #12
0
    void initialize()
    {
        manifest = new Manifest();
        plugins  = new AgentDependency();
        if (System.IO.File.Exists(AgentDependency.AgentsFile))
        {
            plugins = AndroidAgentEditor.LoadAgentsFromFile(AgentDependency.AgentsFile);
            if (System.IO.File.Exists(Manifest.ManifestFile))
            {
                manifest = AndroidManifestEditor.LoadManifestFromFile(Manifest.ManifestFile);
            }
            else
            {
                manifest = new Manifest();
            }

            if (System.IO.File.Exists(ManifestResource.StringsFilename))
            {
                exist_strings = StringEditor.LoadResourcesFromFile(ManifestResource.StringsFilename);
            }
            else
            {
                exist_strings = new ManifestResource();
            }
            strings = new ManifestResource();
        }
        else
        {
            Debug.LogError("AgentDependencies.xml not found.");
        }

        PositiveButton.fixedWidth    = 30;
        PositiveButton.stretchWidth  = false;
        NegetiveButton.fixedWidth    = 30;
        NegetiveButton.stretchWidth  = false;
        BoldLabel.normal.textColor   = Color.white;
        BoldLabel.fontStyle          = FontStyle.Bold;
        SubBoldLabel.fontStyle       = FontStyle.Bold;
        RedLabel.normal.textColor    = new Color(0.8f, 0.1f, 0.1f, 1.0f);
        GreenLabel.normal.textColor  = new Color(0.1f, 0.8f, 0.1f, 1.0f);
        YellowLabel.normal.textColor = new Color(0.8f, 0.8f, 0.1f, 1.0f);

        if (System.IO.Directory.Exists(AgentVersion.VersionsPath))
        {
            Versions = GetVersionsFromPath(AgentVersion.VersionsPath, plugins);
        }
        else
        {
            Versions = new List <AgentSetVersion>();
        }

        guiVersions   = new UnityGUI_Versions(Versions, plugins, manifest);
        guiProperties = new UnityGUI_AgentVersion(manifest);
        guiVersions.SetStyles(PositiveButton, NegetiveButton, BoldLabel, GreenLabel, RedLabel, YellowLabel);
        guiProperties.SetStyles(PositiveButton, NegetiveButton, SubBoldLabel, GreenLabel, RedLabel, YellowLabel);
    }
Example #13
0
 public uint GetResourceOffset(ManifestResource resource)
 {
     if (!_resources.TryGetValue(resource, out uint offset))
     {
         _resources.Add(resource, _length);
         _length += (uint)resource.Data.Length + sizeof(uint);
         return(offset);
     }
     return(offset);
 }
        public void TestLoadManifestResources()
        {
            ManifestResource manifestResource = new ManifestResource();
            Uri    uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
            string dll = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\write.exe");

            manifestResource.LoadFrom(dll, Kernel32.ManifestType.CreateProcess);
            DumpResource.Dump(manifestResource);
            Assert.AreEqual(Kernel32.ManifestType.CreateProcess, manifestResource.ManifestType);
        }
        public void TestMultipleHashManifestStream()
        {
            var multipleHashManifest = Path.Combine(RootPath, "MultipleHashmanifest.bin");

            using (var manifestStream = File.OpenRead(multipleHashManifest))
            {
                var manifest = ManifestResource.Create();
                manifest.InitFromStream(manifestStream);
                CheckMultipleHashManifest(manifest);
            }
        }
        public void TestLoadUnicodeManifestResourceWithBOM()
        {
            // the 6840.dll has a manifest with a BOM marker (the actual file)
            ManifestResource mr = new ManifestResource();
            Uri    uri          = new Uri(Assembly.GetExecutingAssembly().CodeBase);
            string dll          = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\6840.dll");

            mr.LoadFrom(dll, Kernel32.ManifestType.IsolationAware);
            Assert.IsNotNull(mr.Manifest);
            Console.WriteLine(mr.Manifest.OuterXml);
        }
Example #17
0
        public IReadOnlyList <ResourceIndexData> GetOrCreateIndexData(NodeFactory factory)
        {
            if (_indexData != null)
            {
                return(_indexData);
            }

            _totalLength = 0;
            _indexData   = new List <ResourceIndexData>();
            // Build up index information
            foreach (EcmaAssembly module in factory.MetadataManager.GetCompilationModulesWithMetadata().OfType <EcmaAssembly>())
            {
                PEMemoryBlock resourceDirectory = module.PEReader.GetSectionData(module.PEReader.PEHeaders.CorHeader.ResourcesDirectory.RelativeVirtualAddress);

                try
                {
                    checked
                    {
                        foreach (var resourceHandle in module.MetadataReader.ManifestResources)
                        {
                            ManifestResource resource = module.MetadataReader.GetManifestResource(resourceHandle);

                            // Don't try to embed linked resources or resources in other assemblies
                            if (!resource.Implementation.IsNil)
                            {
                                continue;
                            }

                            string resourceName = module.MetadataReader.GetString(resource.Name);

                            // Check if emitting the manifest resource is blocked by policy.
                            if (factory.MetadataManager.IsManifestResourceBlocked(module, resourceName))
                            {
                                continue;
                            }

                            string            assemblyName = module.GetName().FullName;
                            BlobReader        reader       = resourceDirectory.GetReader((int)resource.Offset, resourceDirectory.Length - (int)resource.Offset);
                            int               length       = (int)reader.ReadUInt32();
                            ResourceIndexData indexData    = new ResourceIndexData(assemblyName, resourceName, _totalLength, (int)resource.Offset + sizeof(Int32), module, length);
                            _indexData.Add(indexData);
                            _totalLength += length;
                        }
                    }
                }
                catch (OverflowException)
                {
                    throw new BadImageFormatException();
                }
            }

            return(_indexData);
        }
Example #18
0
        resource.Implementation.IsNil;     // row id == 0

        public static unsafe Stream GetStream(this ManifestResource resource, PEReader peReader)
        {
            if (!resource.IsExtractable())
            {
                throw new ArgumentException("not an embedded extractable resource", nameof(resource));
            }

            var resourcesRva = peReader.PEHeaders.CorHeader.ResourcesDirectory.RelativeVirtualAddress;
            var section      = peReader.GetSectionData(resourcesRva);

            return(new EmbeddedResourceStream(section.Pointer + resource.Offset));
        }
        public void TestOneHashOneFile()
        {
            var manifestPath  = Path.Combine(RootPath, "ManifestOneHashOneFile.bin");
            var manifestBytes = File.ReadAllBytes(manifestPath);
            var manifest      = ManifestResource.Create();

            manifest.InitFromRawDecompressed(manifestBytes);

            var name         = manifest.Entries[0].ToString();
            var expectedName = "f6cb837a26516e3693f255a9cdc63d9a.ScriptCompiledBytecode-Resource";

            Assert.AreEqual(expectedName, name);
        }
Example #20
0
 public static ManifestResource LoadResourcesFromFile(string path)
 {
     ManifestResource m = new ManifestResource();
     System.IO.StreamReader reader = new System.IO.StreamReader(path);
     string xmldata = reader.ReadToEnd();
     reader.Close();
     XmlDocument doc = new XmlDocument();
     doc.LoadXml(xmldata);
     XmlNode manifest = doc.GetElementsByTagName(Manifest.Element.resources)[0];
     m.Read(manifest);
     doc.Clone();
     return m;
 }
        public void TestManifestToString()
        {
            var multipleHashManifest = Path.Combine(RootPath, "MultipleHashManifest.bin");
            var manifestBytes        = File.ReadAllBytes(multipleHashManifest);
            var manifest             = ManifestResource.Create();

            manifest.InitFromRawDecompressed(manifestBytes);

            var name         = manifest.Entries[0].ToString();
            var expectedName = "af86c2b4266db473d57fe6b08f609ee6.LuaScript-Resource";

            Assert.AreEqual(expectedName, name);
        }
 public FileSegmentBuilder GetResourceSegment(ManifestResource resource)
 {
     FileSegmentBuilder segment;
     if (!_resourceSegments.TryGetValue(resource, out segment))
     {
         segment = new FileSegmentBuilder();
         segment.Segments.Add(new DataSegment(BitConverter.GetBytes(resource.Data.Length)));
         segment.Segments.Add(new DataSegment(resource.Data));
         _resourceSegments.Add(resource, segment);
         Segments.Add(segment);
     }
     return segment;
 }
        public FileSegmentBuilder GetResourceSegment(ManifestResource resource)
        {
            FileSegmentBuilder segment;

            if (!_resourceSegments.TryGetValue(resource, out segment))
            {
                segment = new FileSegmentBuilder();
                segment.Segments.Add(new DataSegment(BitConverter.GetBytes(resource.Data.Length)));
                segment.Segments.Add(new DataSegment(resource.Data));
                _resourceSegments.Add(resource, segment);
                Segments.Add(segment);
            }
            return(segment);
        }
Example #24
0
 public static void SaveResourcesToFile(string path, ManifestResource m)
 {
     if (!System.IO.Directory.Exists(ManifestResource.StringsFolder))
         System.IO.Directory.CreateDirectory(ManifestResource.StringsFolder);
     XmlTextWriter	writer = new XmlTextWriter(path, System.Text.Encoding.UTF8);
     writer.Indentation = 4;
     writer.Formatting = Formatting.Indented;
     writer.Settings.NewLineHandling = NewLineHandling.Entitize;
     writer.Settings.NewLineOnAttributes = true;
     writer.WriteStartDocument();
     writer.WriteComment("This file is generated by Manifest Editor (created by Peyman Abdi peyman[at]nemo-games[dot]com).");
     m.Write(writer);
     writer.Close();
     AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
 }
Example #25
0
 internal void WriteManifestRes(ManifestResource resource)
 {
     if (resource.UpdateRowOnRebuild)
     {
         object[] parts = new object[]
         {
             resource.Offset,
             (uint)resource.Attributes,
             GetHeapOffset(newStringsHeap, newStringsHeap.GetStringOffset(resource.Name)),
             GetCodedIndex(tablesHeap.Implementation, resource.Implementation),
         };
         resource.MetaDataRow = new MetaDataRow(parts);
     }
     writer.Write(resource.MetaDataRow.GenerateBytes());
 }
Example #26
0
    void initialize()
    {
        if (System.IO.File.Exists(ManifestResource.StringsFilename))
            strings = LoadResourcesFromFile(ManifestResource.StringsFilename);
        else
            strings = new ManifestResource();
        if (System.IO.File.Exists(Manifest.ManifestFile))
            manifest = AndroidManifestEditor.LoadManifestFromFile(Manifest.ManifestFile);
        else
            manifest = new Manifest();
        FindManifestStrings(manifest, strings);

        BoldLabel.normal.textColor = Color.white;
        BoldLabel.fontStyle = FontStyle.Bold;
    }
Example #27
0
        private static unsafe byte[] GetEmbeddedResourceContents(PEReader peReader, ManifestResource resource)
        {
            if (!resource.Implementation.IsNil)
            {
                throw new ArgumentException("Resource is not embedded in the PE file.", "resource");
            }

            checked // arithmetic overflow here could cause AV
            {
                // Locate start and end of PE image in unmanaged memory.
                var    block = peReader.GetEntireImage();
                IntPtr peImageStartAsIntPtr = block.Pointer;
                int    peImageSize          = block.Length;
                byte * peImageStart         = (byte *)peImageStartAsIntPtr;
                byte * peImageEnd           = peImageStart + peImageSize;
                Debug.Assert(peImageStart != null && peImageSize > 0);

                // Locate offset to resources within PE image.
                int offsetToResources;
                if (!peReader.PEHeaders.TryGetDirectoryOffset(peReader.PEHeaders.CorHeader.ResourcesDirectory, out offsetToResources))
                {
                    throw new InvalidDataException("Failed to get offset to resources in PE file.");
                }
                Debug.Assert(offsetToResources > 0);
                byte *resourceStart = peImageStart + offsetToResources + resource.Offset;

                // Get the length of the the resource from the first 4 bytes.
                if (resourceStart >= peImageEnd - sizeof(int))
                {
                    throw new InvalidDataException("resource offset out of bounds.");
                }
                int resourceLength = *(int *)(resourceStart);
                resourceStart += sizeof(int);
                if (resourceLength < 0 || resourceStart >= peImageEnd - resourceLength)
                {
                    throw new InvalidDataException("resource offset or length out of bounds.");
                }

                // TODO: Use UmanagedMemoryStream when available on core clr
                var buffer = new byte[resourceLength];
                for (int i = 0; i < resourceLength; i++)
                {
                    buffer[i] = *(resourceStart + i);
                }

                return(buffer);
            }
        }
Example #28
0
 public static void FindManifestStrings(Manifest manifest, ManifestResource strings)
 {
     foreach (ManifestMetaData mmd in manifest.application.meta_data)
     {
         if (mmd.value.StartsWith("@string/"))
             if (!strings.hasName(mmd.value.Substring(8))) strings.addString(mmd.name, "PUT VALUE HERE", "", true);
     }
     foreach (ManifestActivity ma in manifest.application.activity)
     {
         foreach (ManifestMetaData mmd in ma.meta_data)
         {
             if (mmd.value.StartsWith("@string/"))
                 if (!strings.hasName(mmd.value.Substring(8))) strings.addString(mmd.name, "PUT VALUE HERE", "", true);
         }
     }
 }
        public void TestLinkDefaultManifest()
        {
            InstallerLinkerArguments args = new InstallerLinkerArguments();

            try
            {
                ConfigFile         configFile         = new ConfigFile();
                SetupConfiguration setupConfiguration = new SetupConfiguration();
                configFile.Children.Add(setupConfiguration);
                args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
                Console.WriteLine("Writing '{0}'", args.config);
                configFile.SaveAs(args.config);
                args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe");
                Console.WriteLine("Linking '{0}'", args.output);
                args.template = dotNetInstallerExeUtils.Executable;
                InstallerLib.InstallerLinker.CreateInstaller(args);
                // check that the linker generated output
                Assert.IsTrue(File.Exists(args.output));
                Assert.IsTrue(new FileInfo(args.output).Length > 0);
                using (ResourceInfo ri = new ResourceInfo())
                {
                    ri.Load(args.output);
                    List <Resource> manifests = ri.Resources[new ResourceId(Kernel32.ResourceTypes.RT_MANIFEST)]; // RT_MANIFEST
                    Assert.IsNotNull(manifests);
                    Assert.AreEqual(1, manifests.Count);
                    ManifestResource manifest = (ManifestResource)manifests[0]; // RT_MANIFEST
                    Console.WriteLine(manifest.Manifest.OuterXml);
                    XmlNamespaceManager manifestNamespaceManager = new XmlNamespaceManager(manifest.Manifest.NameTable);
                    manifestNamespaceManager.AddNamespace("v1", "urn:schemas-microsoft-com:asm.v1");
                    manifestNamespaceManager.AddNamespace("v3", "urn:schemas-microsoft-com:asm.v3");
                    string level = manifest.Manifest.SelectSingleNode("//v3:requestedExecutionLevel",
                                                                      manifestNamespaceManager).Attributes["level"].Value;
                    Assert.AreEqual(level, "requireAdministrator");
                }
            }
            finally
            {
                if (File.Exists(args.config))
                {
                    File.Delete(args.config);
                }
                if (File.Exists(args.output))
                {
                    File.Delete(args.output);
                }
            }
        }
        private void CheckMultipleHashManifest(ManifestResource manifest)
        {
            var expectedEntries = new List <ManifestResource.ManifestEntry>()
            {
                new ManifestResource.ManifestEntry
                {
                    Name       = "LuaScript-Resource",
                    HashString = "af86c2b4266db473d57fe6b08f609ee6",
                    Unknown    = 0,
                },
            };
            var expectedHashes = new List <string>()
            {
                "7f709ed3b97b2cc76a2ec6d49bda6ab3",
                "2578df524038e7b266d33cb46f6a4b41",
                "31620f0df57b26bbee566c37b78f5be4",
                "7ada26eeb44f015a855bd7d1c1ca1f10",
                "f88cd480b0d40a83c9312319f47fbb73",
                "ed3f2ae137f6a7dd0a436eefbfab2334",
                "b87690a2355c318029249055318d06b9",
                "b4b27173e54350c1f0b5ac9136fa464e",
                "f89cf7069bef5a24a84ade56e58e5171",
                "f3fbb248f0add27fa441dbaf60fe9a71",
                "eda1ef90b00a6a8562025d147998474f",
                "7d654d2280096e160c2535bb869e3acf",
                "0d366eab88a16c2f824738afb29098ad",
                "f1b2d12d05678ef7b5fb62d8cc4e9b3d",
            };
            var expectedUnknownA = new List <Tuple <long, long, long> >()
            {
                new Tuple <long, long, long>(-1, -1, 1),
            };
            var expectedUnknownB = new List <int>()
            {
            };

            Assert.AreEqual(expectedEntries.Count, manifest.Entries.Count);
            for (var i = 0; i < manifest.Entries.Count; i++)
            {
                Assert.AreEqual(expectedEntries[i].HashString, manifest.Entries[i].HashString);
                Assert.AreEqual(expectedEntries[i].Name, manifest.Entries[i].Name);
                Assert.AreEqual(expectedEntries[i].Unknown, manifest.Entries[i].Unknown);
            }
            Assert.True(expectedHashes.SequenceEqual(manifest.HashList));
            Assert.True(expectedUnknownA.SequenceEqual(manifest.UnknownListA));
            Assert.True(expectedUnknownB.SequenceEqual(manifest.UnknownListB));
        }
Example #31
0
    public static ManifestResource          LoadResourcesFromFile(string path)
    {
        ManifestResource m = new ManifestResource();

        System.IO.StreamReader reader = new System.IO.StreamReader(path);
        string xmldata = reader.ReadToEnd();

        reader.Close();
        XmlDocument doc = new XmlDocument();

        doc.LoadXml(xmldata);
        XmlNode manifest = doc.GetElementsByTagName(Manifest.Element.resources)[0];

        m.Read(manifest);
        doc.Clone();
        return(m);
    }
Example #32
0
        public sealed override String[] GetManifestResourceNames()
        {
            ManifestResourceHandleCollection manifestResources = MetadataReader.ManifestResources;

            string[] resourceNames = new string[manifestResources.Count];

            int iResource = 0;

            foreach (var resourceHandle in manifestResources)
            {
                ManifestResource resource = MetadataReader.GetManifestResource(resourceHandle);
                resourceNames[iResource] = MetadataReader.GetString(resource.Name);
                iResource++;
            }

            return(resourceNames);
        }
        public void TestLoadAndSaveCreateProcessManifestResource()
        {
            Uri    uri            = new Uri(Assembly.GetExecutingAssembly().CodeBase);
            string filename       = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\write.exe");
            string targetFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe");

            File.Copy(filename, targetFilename, true);
            Console.WriteLine(targetFilename);
            ManifestResource manifestResource = new ManifestResource(Kernel32.ManifestType.CreateProcess);

            manifestResource.SaveTo(targetFilename);
            Console.WriteLine("Written manifest:");
            ManifestResource newManifestResource = new ManifestResource();

            newManifestResource.LoadFrom(targetFilename);
            DumpResource.Dump(newManifestResource);
            File.Delete(targetFilename);
        }
        /// <summary>
        /// Adds a single manifest resource to the buffer.
        /// </summary>
        /// <param name="resource">The resource to add.</param>
        /// <returns>The new metadata token of the resource.</returns>
        public MetadataToken AddManifestResource(ManifestResource resource)
        {
            uint offset = resource.Offset;

            if (resource.IsEmbedded)
            {
                if (resource.EmbeddedDataSegment is {} segment)
                {
                    using var stream = new MemoryStream();
                    segment.Write(new BinaryStreamWriter(stream));
                    offset = Resources.GetResourceDataOffset(stream.ToArray());
                }
                else
                {
                    ErrorListener.MetadataBuilder($"Embedded resource {resource.SafeToString()} does not have any contents.");
                    offset = 0;
                }
            }
Example #35
0
    public static void                      SaveResourcesToFile(string path, ManifestResource m)
    {
        if (!System.IO.Directory.Exists(ManifestResource.StringsFolder))
        {
            System.IO.Directory.CreateDirectory(ManifestResource.StringsFolder);
        }
        XmlTextWriter writer = new XmlTextWriter(path, System.Text.Encoding.UTF8);

        writer.Indentation = 4;
        writer.Formatting  = Formatting.Indented;
        writer.Settings.NewLineHandling     = NewLineHandling.Entitize;
        writer.Settings.NewLineOnAttributes = true;
        writer.WriteStartDocument();
        writer.WriteComment("This file is generated by Manifest Editor (created by Peyman Abdi peyman[at]nemo-games[dot]com).");
        m.Write(writer);
        writer.Close();
        AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
    }
Example #36
0
        private void AddManifestResource(ManifestResource resource)
        {
            var table       = (ManifestResourceTable)_tableStream.GetTable(MetadataTokenType.ManifestResource);
            var resourceRow = new MetadataRow <uint, ManifestResourceAttributes, uint, uint>
            {
                Column1 = _parentBuffer.ResourcesBuffer.GetResourceOffset(resource),
                Column2 = resource.Attributes,
                Column3 = _parentBuffer.StringStreamBuffer.GetStringOffset(resource.Name),
                Column4 = !resource.IsEmbedded
                    ? _tableStream.GetIndexEncoder(CodedIndex.Implementation)
                          .EncodeToken(GetImplementationToken(resource.Implementation))
                    : 0,
            };

            table.Add(resourceRow);
            _members.Add(resource, resourceRow.MetadataToken);

            AddCustomAttributes(resource);
        }
    void initialize()
    {
        manifest = new Manifest();
        plugins = new AgentDependency();
        if (System.IO.File.Exists(AgentDependency.AgentsFile))
        {
            plugins = AndroidAgentEditor.LoadAgentsFromFile(AgentDependency.AgentsFile);
            if (System.IO.File.Exists(Manifest.ManifestFile))
                manifest = AndroidManifestEditor.LoadManifestFromFile(Manifest.ManifestFile);
            else
                manifest = new Manifest();

            if (System.IO.File.Exists(ManifestResource.StringsFilename))
                exist_strings = StringEditor.LoadResourcesFromFile(ManifestResource.StringsFilename);
            else
                exist_strings = new ManifestResource();
            strings = new ManifestResource();
        } else
            Debug.LogError("AgentDependencies.xml not found.");

        PositiveButton.fixedWidth = 30;
        PositiveButton.stretchWidth = false;
        NegetiveButton.fixedWidth = 30;
        NegetiveButton.stretchWidth = false;
        BoldLabel.normal.textColor = Color.white;
        BoldLabel.fontStyle = FontStyle.Bold;
        SubBoldLabel.fontStyle = FontStyle.Bold;
        RedLabel.normal.textColor = new Color(0.8f, 0.1f, 0.1f, 1.0f);
        GreenLabel.normal.textColor = new Color(0.1f, 0.8f, 0.1f, 1.0f);
        YellowLabel.normal.textColor = new Color(0.8f, 0.8f, 0.1f, 1.0f);

        if (System.IO.Directory.Exists(AgentVersion.VersionsPath))
            Versions = GetVersionsFromPath(AgentVersion.VersionsPath, plugins);
        else
            Versions = new List<AgentSetVersion>();

        guiVersions = new UnityGUI_Versions(Versions, plugins, manifest);
        guiProperties = new UnityGUI_AgentVersion(manifest);
        guiVersions.SetStyles(PositiveButton, NegetiveButton, BoldLabel, GreenLabel, RedLabel, YellowLabel);
        guiProperties.SetStyles(PositiveButton, NegetiveButton, SubBoldLabel, GreenLabel, RedLabel, YellowLabel);
    }
 public bool isStringsReady(ManifestResource strings)
 {
     for (int i = 0; i < Strings.Count; i++)
     {
         if (!strings.hasName(Strings.strings[i].name)) return false;
         else
         {
             if (strings.getValue(Strings.strings[i].name) != Strings.strings[i].value) return false;
         }
     }
     return true;
 }
 public bool isStringsReady(ManifestResource strings)
 {
     for (int i = 0; i < Plugins.Count; i++) if (Plugins[i].status && !Plugins[i].isStringsReady(strings)) return false;
     return true;
 }
Example #40
0
        public Task<Binary> Save()
        {
            lock (this) {
                if (_saving != null) {
                    return _saving;
                }

                if (Unloaded) {
                    throw new CoAppBinaryException("Binary '{0}' has been unloaded", Filename);
                }

                if (!Modified) {
                    return this.AsResultTask();
                }

                _saving = Task<Binary>.Factory.StartNew(() => {
                    // Console.WriteLine("Actual Signing Process started for [{0}]/[{1}]", Filename , WorkingCopy);
                    if (!IsManaged) {
                        StripSignatures(WorkingCopy); // this is irrelevant if the binary is managed--we'll be writing out a new one.
                    }

                    if (!_loadOptions.HasFlag(BinaryLoadOptions.NoManaged) && IsManaged && (_modifiedManaged || _modifiedResources)) {
                        WaitForResourceAndManagedLoaders();

                        // handle managed code rewrites
                        // we can only edit the file if it's IL only, mixed mode assemblies can only be strong named, signed and native-resource-edited.
                        // set the strong name key data
                        if (!StrongNameKey.IsNullOrEmpty()) {
                            if (_mutableAssembly == null) {
                                Console.WriteLine("HEY! : {0}", Filename);
                            }

                            _mutableAssembly.PublicKey = StrongNameKey.ToList();

                            // change any assembly attributes we need to change
                            if (_mutableAssembly != null) {
                                if (StrongNameKeyCertificate != null) {
                                    foreach (var ar in _mutableAssembly.AssemblyReferences) {
                                        // rewrite assembly references that need to be updated.
                                        if (!ar.PublicKeyToken.Any()) {
                                            var dep = FindAssembly(ar.Name.Value, ar.Version.ToString());
                                            if (dep == null) {
                                                // can't strong name a file that doesn't have its deps all strong named.
                                                throw new CoAppException("dependent assembly '{0}-{1}' not available for strong naming".format(ar.Name.Value,
                                                    ar.Version.ToString()));
                                            }

                                            if (dep._mutableAssembly.PublicKey.IsNullOrEmpty()) {
                                                if (!_loadOptions.HasFlag(BinaryLoadOptions.NoUnsignedManagedDependencies)) {
                                                    Console.WriteLine(
                                                        "Warning: Non-strong-named dependent reference found: '{0}-{1}' updating with same strong-name-key.",
                                                        ar.Name, ar.Version);
                                                    dep.StrongNameKeyCertificate = StrongNameKeyCertificate;
                                                    dep.SigningCertificate = SigningCertificate;

                                                    dep.AssemblyCopyright = AssemblyCopyright;
                                                    dep.AssemblyCompany = AssemblyCompany;
                                                    dep.AssemblyProduct = AssemblyProduct;

                                                    // wait for the dependency to finish saving.
                                                    dep.Save().Wait();
                                                } else {
                                                    throw new CoAppException("dependent assembly '{0}-{1}' not strong named".format(ar.Name.Value,
                                                        ar.Version.ToString()));
                                                }
                                            }
                                            (ar as Microsoft.Cci.MutableCodeModel.AssemblyReference).PublicKeyToken =
                                                dep._mutableAssembly.PublicKeyToken.ToList();
                                            (ar as Microsoft.Cci.MutableCodeModel.AssemblyReference).PublicKey = dep._mutableAssembly.PublicKey;
                                        }
                                    }
                                }
                            }
                            // we should see if we can get assembly attributes, since sometimes they can be set, but not the native ones.
                            try {
                                if (!_mutableAssembly.AssemblyAttributes.IsNullOrEmpty()) {
                                    foreach (var a in _mutableAssembly.AssemblyAttributes) {
                                        var attributeArgument = (a.Arguments.FirstOrDefault() as MetadataConstant);
                                        if (attributeArgument != null) {
                                            var attributeName = a.Type.ToString();
                                            switch (attributeName) {
                                                case "System.Reflection.AssemblyTitleAttribute":
                                                    attributeArgument.Value = string.IsNullOrEmpty(AssemblyTitle) ? string.Empty : AssemblyTitle;
                                                    break;
                                                case "System.Reflection.AssemblyDescriptionAttribute":
                                                    attributeArgument.Value = string.IsNullOrEmpty(AssemblyDescription) ? string.Empty : AssemblyDescription;
                                                    break;
                                                case "System.Reflection.AssemblyCompanyAttribute":
                                                    attributeArgument.Value = string.IsNullOrEmpty(AssemblyCompany) ? string.Empty : AssemblyCompany;
                                                    break;
                                                case "System.Reflection.AssemblyProductAttribute":
                                                    attributeArgument.Value = string.IsNullOrEmpty(AssemblyProduct) ? string.Empty : AssemblyProduct;
                                                    break;
                                                    //case "System.Reflection.AssemblyVersionAttribute":
                                                    // attributeArgument.Value = (string)AssemblyVersion;
                                                    // break;
                                                case "System.Reflection.AssemblyFileVersionAttribute":
                                                    attributeArgument.Value = (string)AssemblyFileVersion;
                                                    break;
                                                case "System.Reflection.AssemblyCopyrightAttribute":
                                                    attributeArgument.Value = string.IsNullOrEmpty(AssemblyCopyright) ? string.Empty : AssemblyCopyright;
                                                    break;
                                                case "System.Reflection.AssemblyTrademarkAttribute":
                                                    attributeArgument.Value = string.IsNullOrEmpty(AssemblyTrademark) ? string.Empty : AssemblyTrademark;
                                                    break;
                                                case "BugTrackerAttribute":
                                                    attributeArgument.Value = string.IsNullOrEmpty(BugTracker) ? string.Empty : BugTracker;
                                                    break;
                                            }
                                        }
                                    }
                                }
                            } catch {
                                // hmm. carry on.
                            }
                        }

                        // save it to disk
                        WorkingCopy.TryHardToMakeFileWriteable();
                        using (var peStream = File.Create(WorkingCopy)) {
                            PeWriter.WritePeToStream(_mutableAssembly, _host, peStream);
                        }
                    }

                    if (!_loadOptions.HasFlag(BinaryLoadOptions.NoManifest) && Manifest.Value != null && Manifest.Value.Modified) {
                        // rewrite Manifests
                        // GS01: We only support one manifest right now.
                        // so we're gonna remove the extra ones.
                        // figure out the bigger case later.
                        var manifestKeys = NativeResources.Value.Resources.Keys.Where(each => each.ResourceType == ResourceTypes.RT_MANIFEST).ToArray();
                        foreach (var k in manifestKeys) {
                            var v = NativeResources.Value.Resources[k];
                            if (!v.IsNullOrEmpty()) {
                                foreach (var inst in v) {
                                    Resource.Delete(WorkingCopy, inst.Type, inst.Name, inst.Language);
                                }
                            }
                            NativeResources.Value.Resources.Remove(k);
                        }

                        var IsLibrary = Path.GetExtension(Filename).ToLower() == ".dll";

                        var manifestResource = new ManifestResource(IsLibrary ? ManifestType.IsolationAware : ManifestType.CreateProcess) {ManifestText = Manifest.Value.ToString(), Language = 1033};
                        // GS01: I'm hardcoding this for now. We're probably gonna have to be way smarter about this.
                        NativeResources.Value.Resources.Add(new ResourceId(ResourceTypes.RT_MANIFEST), new List<Resource> {
                            manifestResource
                        });

                        manifestResource.SaveTo(WorkingCopy);
                    }

                    if (!_loadOptions.HasFlag(BinaryLoadOptions.NoResources) && _modifiedResources) {
                        // rewrite Resources
                        VersionResource versionResource;
                        StringTable versionStringTable;

                        var versionKey = NativeResources.Value.Resources.Keys.FirstOrDefault(each => each.ResourceType == ResourceTypes.RT_VERSION);
                        if (versionKey != null) {
                            versionResource = NativeResources.Value.Resources[versionKey].First() as VersionResource;
                            versionStringTable = (versionResource["StringFileInfo"] as StringFileInfo).Strings.Values.First();
                        } else {
                            versionResource = new VersionResource();
                            NativeResources.Value.Resources.Add(new ResourceId(ResourceTypes.RT_VERSION), new List<Resource> {
                                versionResource
                            });

                            var sfi = new StringFileInfo();
                            versionResource["StringFileInfo"] = sfi;
                            sfi.Strings["040904b0"] = (versionStringTable = new StringTable("040904b0"));

                            var vfi = new VarFileInfo();
                            versionResource["VarFileInfo"] = vfi;
                            var translation = new VarTable("Translation");
                            vfi.Vars["Translation"] = translation;
                            translation[0x0409] = 0x04b0;
                        }

                        versionResource.FileVersion = FileVersion;
                        versionResource.ProductVersion = ProductVersion;

                        versionStringTable["ProductName"] = ProductName;
                        versionStringTable["CompanyName"] = CompanyName;
                        versionStringTable["FileDescription"] = FileDescription;
                        versionStringTable["Comments"] = _comments;
                        versionStringTable["Assembly Version"] = AssemblyVersion.Value;
                        versionStringTable["FileVersion"] = _fileVersion;
                        versionStringTable["ProductVersion"] = _productVersion;
                        versionStringTable["InternalName"] = _internalName;
                        versionStringTable["OriginalFilename"] = _originalFilename;
                        versionStringTable["LegalCopyright"] = _legalCopyright;
                        versionStringTable["LegalTrademarks"] = _legalTrademarks;
                        versionStringTable["BugTracker"] = _bugTracker;

                        versionResource.SaveTo(WorkingCopy);
                    }

                    if (!_loadOptions.HasFlag(BinaryLoadOptions.NoSignature) && _modifiedSignature && _signingCertificate != null) {
                        // Strongname & Sign the package

                        // strong name the binary (if we're doing managed stuff).
                        if (!_loadOptions.HasFlag(BinaryLoadOptions.NoManaged) && IsManaged && StrongNameKeyCertificate != null &&
                            (StrongNameKeyCertificate.Certificate.PrivateKey is RSACryptoServiceProvider)) {
                            ApplyStrongName(WorkingCopy, StrongNameKeyCertificate);
                        }

                        // sign the binary
                        SignFile(WorkingCopy, SigningCertificate.Certificate);
                    }

                    if (_loadingMD5 != null) {
                        _loadingMD5 = null;
                    }

                    LoadMD5().Wait();

                    // Console.WriteLine("Replacing original File [{0}]", Filename);
                    Filename.TryHardToDelete();
                    File.Copy(WorkingCopy, Filename);

                    _modified = false;
                    _modifiedResources = false;
                    _modifiedManaged = false;
                    _modifiedSignature = false;

                    // Console.WriteLine("Completed Signing Process started for [{0}]/[{1}]", Filename, WorkingCopy);
                    return this;
                });
                _saving.ContinueWith((a) => {
                    _saving = null;
                }, TaskContinuationOptions.AttachedToParent);
            }
            return _saving;
        }
    private void ApplyVersion(AgentSetVersion v)
    {
        PlayerSettings.bundleVersion = v.versionName;
        PlayerSettings.Android.bundleVersionCode = int.Parse(v.versionCode);
        PlayerSettings.bundleIdentifier = v.bundleid;
        manifest.package = v.bundleid;
        manifest.versionCode = v.versionCode;
        manifest.versionName = v.versionName;

        PreDefinitions = v.PreDefine.ToArray();
        SetPreDefinitions();

        System.IO.Directory.CreateDirectory(Application.dataPath + "/Plugins/Android/");
        System.IO.Directory.CreateDirectory(Application.dataPath + "/Plugins/Android/res");
        System.IO.Directory.CreateDirectory(Application.dataPath + "/Plugins/Android/libs");

        foreach (AgentManifest mans in plugins.Agents)
        {
            if (!v.hasPlugin(mans.filename))
            {
                SetPluginDefinition(SearchPathForFilename(Application.dataPath, mans.filename), false);
                RemoveDependencies(mans);
            } else if (v.getVersionOfPlugin(mans.filename).status == false)
            {
                SetPluginDefinition(SearchPathForFilename(Application.dataPath, mans.filename), false);
                RemoveDependencies(v.getVersionOfPlugin(mans.filename));
            }
        }
        foreach (AgentManifest mans in plugins.Agents)
        {
            if (v.hasPlugin(mans.filename))
            {
                AgentVersion plug = v.getVersionOfPlugin(mans.filename);
                if (plug.status)
                {
                    SetPluginDefinition(SearchPathForFilename(Application.dataPath, mans.filename), true);
                    AddPluginDependencies(plug);
                }
            }
        }
        AndroidManifestEditor.SaveManifestToFile(Manifest.ManifestFile, manifest);
        ManifestResource current_strings;
        if (System.IO.File.Exists(ManifestResource.StringsFilename))
            current_strings = StringEditor.LoadResourcesFromFile(ManifestResource.StringsFilename);
        else
            current_strings = new ManifestResource();
        for (int i = 0; i < strings.Count; i++)
        {
            if (current_strings.hasName(strings.strings[i].name))
                current_strings.setValue(strings.strings[i].name, strings.strings[i]);
            else
                current_strings.addString(strings.strings[i].name, strings.strings[i]);
        }
        StringEditor.SaveResourcesToFile(ManifestResource.StringsFilename, current_strings);
        Debug.Log("Done :)");
    }
Example #42
0
        public void Save(bool autoHandleDependencies = false) {
            lock (this) {
                if (_manifest != null) {
                    _pendingChanges = _manifest.Modified || _pendingChanges;
                }
                // Logger.Message("Saving Binary '{0}' : Pending Changes: {1} ", _filename, _pendingChanges);
                if (_pendingChanges) {
                    // saves any changes made to the binary.
                    // work on a back up of the file
                    var tmpFilename = _filename.CreateWritableWorkingCopy();

                    try {
                        // remove any digital signatures from the binary before doing anything
                        if (!IsManaged) {
                            StripSignatures(tmpFilename); // this is irrelevant if the binary is managed--we'll be writing out a new one.
                        }
                        // rewrite any native resources that we want to change.

                        if (IsManaged && ILOnly) {
                            // we can only edit the file if it's IL only, mixed mode assemblies can only be strong named, signed and native-resource-edited.
                            // set the strong name key data
                            MutableAssembly.PublicKey = StrongNameKey.ToList();

                            // change any assembly attributes we need to change
                            if (MutableAssembly != null) {
                                if (StrongNameKeyCertificate != null) {
                                    foreach (var ar in MutableAssembly.AssemblyReferences) {
                                        if (!ar.PublicKeyToken.Any()) {
                                            var dep = FindAssembly(ar.Name.Value, ar.Version.ToString());
                                            if (dep == null) {
                                                // can't strong name a file that doesn't have its deps all strong named.
                                                throw new ClrPlusException("dependent assembly '{0}-{1}' not available for strong naming".format(ar.Name.Value, ar.Version.ToString()));
                                            }

                                            lock (dep) {
                                                // this should wait until the dependency is finished saving, right?
                                            }

                                            if (dep.MutableAssembly.PublicKey.IsNullOrEmpty()) {
                                                if (autoHandleDependencies) {
                                                    Console.WriteLine(
                                                        "Warning: Non-strong-named dependent reference found: '{0}-{1}' updating with same strong-name-key.",
                                                        ar.Name, ar.Version);
                                                    dep.StrongNameKeyCertificate = StrongNameKeyCertificate;
                                                    dep.SigningCertificate = SigningCertificate;

                                                    dep.AssemblyCopyright = AssemblyCopyright;
                                                    dep.AssemblyCompany = AssemblyCompany;
                                                    dep.AssemblyProduct = AssemblyProduct;

                                                    dep.Save();
                                                } else {
                                                    throw new ClrPlusException("dependent assembly '{0}-{1}' not strong named".format(ar.Name.Value, ar.Version.ToString()));
                                                }
                                            }
                                            (ar as Microsoft.Cci.MutableCodeModel.AssemblyReference).PublicKeyToken = dep.MutableAssembly.PublicKeyToken.ToList();
                                            (ar as Microsoft.Cci.MutableCodeModel.AssemblyReference).PublicKey = dep.MutableAssembly.PublicKey;
                                        }
                                    }
                                }

                                // we should see if we can get assembly attributes, since sometimes they can be set, but not the native ones.
                                try {
                                    foreach (var a in MutableAssembly.AssemblyAttributes) {
                                        var attributeArgument = (a.Arguments.FirstOrDefault() as MetadataConstant);
                                        if (attributeArgument != null) {
                                            var attributeName = a.Type.ToString();
                                            switch (attributeName) {
                                                case "System.Reflection.AssemblyTitleAttribute":
                                                    attributeArgument.Value = string.IsNullOrEmpty(AssemblyTitle) ? string.Empty : AssemblyTitle;
                                                    break;
                                                case "System.Reflection.AssemblyDescriptionAttribute":
                                                    attributeArgument.Value = string.IsNullOrEmpty(AssemblyDescription) ? string.Empty : AssemblyDescription;
                                                    break;
                                                case "System.Reflection.AssemblyCompanyAttribute":
                                                    attributeArgument.Value = string.IsNullOrEmpty(AssemblyCompany) ? string.Empty : AssemblyCompany;
                                                    break;
                                                case "System.Reflection.AssemblyProductAttribute":
                                                    attributeArgument.Value = string.IsNullOrEmpty(AssemblyProduct) ? string.Empty : AssemblyProduct;
                                                    break;
                                                case "System.Reflection.AssemblyVersionAttribute":
                                                    attributeArgument.Value = string.IsNullOrEmpty(AssemblyVersion) ? string.Empty : AssemblyVersion;
                                                    break;
                                                case "System.Reflection.AssemblyFileVersionAttribute":
                                                    attributeArgument.Value = string.IsNullOrEmpty(AssemblyFileVersion) ? string.Empty : AssemblyFileVersion;
                                                    break;
                                                case "System.Reflection.AssemblyCopyrightAttribute":
                                                    attributeArgument.Value = string.IsNullOrEmpty(AssemblyCopyright) ? string.Empty : AssemblyCopyright;
                                                    break;
                                                case "System.Reflection.AssemblyTrademarkAttribute":
                                                    attributeArgument.Value = string.IsNullOrEmpty(AssemblyTrademark) ? string.Empty : AssemblyTrademark;
                                                    break;
                                                case "BugTrackerAttribute":
                                                    attributeArgument.Value = string.IsNullOrEmpty(BugTracker) ? string.Empty : BugTracker;
                                                    break;
                                            }
                                        }
                                    }
                                } catch {
                                    // hmm. carry on.
                                }
                            }

                            // save it to disk
                            using (var peStream = File.Create(tmpFilename)) {
                                PeWriter.WritePeToStream(MutableAssembly, _host, peStream);
                            }
                        }

                        // update native metadata 
                        try {
                            var ri = new ResourceInfo();

                            ri.Load(tmpFilename);

                            if (_manifest != null && _manifest.Modified) {
                                // GS01: We only support one manifest right now. 
                                // so we're gonna remove the extra ones.
                                // figure out the bigger case later. 
                                var manifestKeys = ri.Resources.Keys.Where(each => each.ResourceType == ResourceTypes.RT_MANIFEST).ToArray();
                                foreach (var k in manifestKeys) {
                                    ri.Resources.Remove(k);
                                }

                                var manifestResource = new ManifestResource();
                                manifestResource.ManifestText = _manifest.ToString();
                                ri.Resources.Add(new ResourceId(ResourceTypes.RT_MANIFEST), new List<Resource> {
                                    manifestResource
                                });
                                manifestResource.SaveTo(tmpFilename);
                            }

                            VersionResource versionResource;
                            StringTable versionStringTable;

                            var versionKey = ri.Resources.Keys.Where(each => each.ResourceType == ResourceTypes.RT_VERSION).FirstOrDefault();
                            if (versionKey != null) {
                                versionResource = ri.Resources[versionKey].First() as VersionResource;
                                versionStringTable = (versionResource["StringFileInfo"] as StringFileInfo).Strings.Values.First();
                            } else {
                                versionResource = new VersionResource();
                                ri.Resources.Add(new ResourceId(ResourceTypes.RT_VERSION), new List<Resource> {
                                    versionResource
                                });

                                var sfi = new StringFileInfo();
                                versionResource["StringFileInfo"] = sfi;
                                sfi.Strings["040904b0"] = (versionStringTable = new StringTable("040904b0"));

                                var vfi = new VarFileInfo();
                                versionResource["VarFileInfo"] = vfi;
                                var translation = new VarTable("Translation");
                                vfi.Vars["Translation"] = translation;
                                translation[0x0409] = 0x04b0;
                            }

                            versionResource.FileVersion = FileVersion;
                            versionResource.ProductVersion = ProductVersion;

                            versionStringTable["ProductName"] = ProductName;
                            versionStringTable["CompanyName"] = CompanyName;
                            versionStringTable["FileDescription"] = FileDescription;
                            versionStringTable["Comments"] = _comments;
                            versionStringTable["Assembly Version"] = _assemblyVersion;
                            versionStringTable["FileVersion"] = _fileVersion;
                            versionStringTable["ProductVersion"] = _productVersion;
                            versionStringTable["InternalName"] = _internalName;
                            versionStringTable["OriginalFilename"] = _originalFilename;
                            versionStringTable["LegalCopyright"] = _legalCopyright;
                            versionStringTable["LegalTrademarks"] = _legalTrademarks;
                            versionStringTable["BugTracker"] = _bugTracker;

                            versionResource.SaveTo(tmpFilename);
                        } catch (Exception e) {
                            Console.WriteLine("{0} -- {1}", e.Message, e.StackTrace);
                        }

                        // strong name the binary
                        if (IsManaged && StrongNameKeyCertificate != null && (StrongNameKeyCertificate.Certificate.PrivateKey is RSACryptoServiceProvider)) {
                            ApplyStrongName(tmpFilename, StrongNameKeyCertificate);
                        }

                        // sign the binary
                        if (_signingCertificate != null) {
                            SignFile(tmpFilename, SigningCertificate.Certificate);
                        }

                        _filename.TryHardToDelete();
                        File.Move(tmpFilename, _filename);
                    } catch (Exception e) {
#if TODO                        
                        Logger.Error(e);
#endif
                        // get rid of whatever we tried
                        tmpFilename.TryHardToDelete();

                        // as you were...
                        throw;
                    }
                }
                _pendingChanges = false;
                if (_manifest != null) {
                    _manifest.Modified = false;
                }
            }
        }