예제 #1
0
        // Token: 0x06000195 RID: 405 RVA: 0x0006142C File Offset: 0x0005F62C
        protected override void Execute(ConfuserContext context, ProtectionParameters parameters)
        {
            bool flag = parameters.Targets.Any <IDnlibDef>();

            if (flag)
            {
                bool flag2 = !UTF8String.IsNullOrEmpty(context.CurrentModule.Assembly.Culture);
                if (flag2)
                {
                    context.Logger.DebugFormat("Skipping resource encryption for satellite assembly '{0}'.", new object[]
                    {
                        context.CurrentModule.Assembly.FullName
                    });
                }
                else
                {
                    ICompressionService service   = context.Registry.GetService <ICompressionService>();
                    INameService        name      = context.Registry.GetService <INameService>();
                    IMarkerService      marker    = context.Registry.GetService <IMarkerService>();
                    IRuntimeService     service2  = context.Registry.GetService <IRuntimeService>();
                    REContext           recontext = new REContext
                    {
                        Random    = context.Registry.GetService <IRandomService>().GetRandomGenerator(base.Parent.Id),
                        Context   = context,
                        Module    = context.CurrentModule,
                        Marker    = marker,
                        DynCipher = context.Registry.GetService <IDynCipherService>(),
                        Name      = name
                    };
                    recontext.Mode = parameters.GetParameter <Mode>(context, context.CurrentModule, "mode", Mode.Normal);
                    Mode mode = recontext.Mode;
                    if (mode != Mode.Normal)
                    {
                        if (mode != Mode.Dynamic)
                        {
                            throw new UnreachableException();
                        }
                        recontext.ModeHandler = new DynamicMode();
                    }
                    else
                    {
                        recontext.ModeHandler = new NormalMode();
                    }
                    MethodDef runtimeDecompressor = service.GetRuntimeDecompressor(context.CurrentModule, delegate(IDnlibDef member)
                    {
                        name.MarkHelper(member, marker, (Protection)this.Parent);
                        bool flag3 = member is MethodDef;
                        if (flag3)
                        {
                            ProtectionParameters.GetParameters(context, member).Remove(this.Parent);
                        }
                    });
                    this.InjectHelpers(context, service, service2, recontext);
                    this.MutateInitializer(recontext, runtimeDecompressor);
                    MethodDef methodDef = context.CurrentModule.GlobalType.FindStaticConstructor();
                    methodDef.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, recontext.InitMethod));
                    new MDPhase(recontext).Hook();
                }
            }
        }
예제 #2
0
파일: Helper.cs 프로젝트: xubingyue/il2cpp
        public static string AssemblyName(IAssembly asm)
        {
            var sb = new StringBuilder();

            sb.Append(asm.Name);

            if (asm.Version != null)
            {
                sb.AppendFormat(",ver={0}", asm.Version);
            }

            if (!UTF8String.IsNullOrEmpty(asm.Culture))
            {
                sb.AppendFormat(",cul={0}", asm.Culture.String);
            }

            var publicKey = asm.PublicKeyOrToken;

            if (publicKey != null &&
                publicKey.Data != null &&
                publicKey.Data.Length != 0)
            {
                sb.AppendFormat(",{0}={1}",
                                publicKey is PublicKeyToken ? "tok=" : "key=",
                                publicKey);
            }

            return(sb.ToString());
        }
예제 #3
0
        static TargetFrameworkInfo?TryGetTargetFrameworkInfoInternal(AssemblyDef asm)
        {
            var ca = asm.CustomAttributes.Find("System.Runtime.Versioning.TargetFrameworkAttribute");

            if (ca == null)
            {
                return(null);
            }

            if (ca.ConstructorArguments.Count != 1)
            {
                return(null);
            }
            var arg = ca.ConstructorArguments[0];

            if (arg.Type.GetElementType() != ElementType.String)
            {
                return(null);
            }
            var s = arg.Value as UTF8String;

            if (UTF8String.IsNullOrEmpty(s))
            {
                return(null);
            }

            return(TryCreateFromAttributeString(s));
        }
예제 #4
0
 AssemblyDef TryOpenAssembly(string filename)
 {
     lock (openedModules) {
         ModuleDef mod;
         if (openedModules.TryGetValue(filename, out mod))
         {
             return(mod.Assembly);
         }
         openedModules[filename] = null;
         if (!File.Exists(filename))
         {
             return(null);
         }
         try {
             mod = ModuleDefMD.Load(filename);
             if (mod.Assembly == null || UTF8String.IsNullOrEmpty(mod.Assembly.Culture))
             {
                 mod.Dispose();
                 return(null);
             }
             openedModules[filename] = mod;
             return(mod.Assembly);
         }
         catch {
             return(null);
         }
     }
 }
예제 #5
0
        bool IsXamlResource(ModuleDef module, string name, ResourceElementSet set)
        {
            var asm = module.Assembly;

            if (asm is null || !module.IsManifestModule)
            {
                return(false);
            }

            string culture = UTF8String.IsNullOrEmpty(asm.Culture) ? string.Empty : "." + asm.Culture;

            if (!StringComparer.OrdinalIgnoreCase.Equals(asm.Name + ".g" + culture + ".resources", name))
            {
                return(false);
            }

            var elems = set.ResourceElements.ToArray();

            if (elems.Length == 0)
            {
                return(false);
            }
            foreach (var e in elems)
            {
                if (!(e.ResourceData.Code == ResourceTypeCode.ByteArray || e.ResourceData.Code == ResourceTypeCode.Stream))
                {
                    return(false);
                }
            }
            return(true);
        }
예제 #6
0
        public static string CreateDisplayName(PropertyDef property, bool fullName = false)
        {
            var sb = new StringBuilder();

            if (fullName)
            {
                sb.AppendFormat("{0}.", CreateDisplayName(property.DeclaringType, true));
            }

            if (property.PropertySig == null)
            {
                sb.Append(property.Name ?? "<<<NULL>>>");
            }
            else
            {
                if (!UTF8String.IsNullOrEmpty(property.Name))
                {
                    sb.Append(property.Name);
                }
                if (property.PropertySig.Params.Count > 0)
                {
                    sb.Append('[');
                    int count = PrintMethodArgList(sb, property.PropertySig.Params, false, false);
                    sb.Append(']');
                }
                sb.Append(" : ");
                sb.Append(CreateDisplayName(property.PropertySig.RetType));
            }
            return(sb.ToString());
        }
예제 #7
0
        ProjectFile?TryCreateSatelliteFile(ModuleDef module, string rsrcName, FilenameCreator filenameCreator, ProjectFile nonSatFile)
        {
            if (!Options.CreateResX)
            {
                return(null);
            }
            var asm = module.Assembly;

            Debug.Assert(!(asm is null) && !UTF8String.IsNullOrEmpty(asm.Culture));
            if (asm is null || UTF8String.IsNullOrEmpty(asm.Culture))
            {
                return(null);
            }
            var name    = FileUtils.RemoveExtension(rsrcName);
            var ext     = FileUtils.GetExtension(rsrcName);
            var locName = name + "." + asm.Culture + ext;
            var er      = module.Resources.OfType <EmbeddedResource>().FirstOrDefault(a => StringComparer.Ordinal.Equals(a.Name, locName));
            var set     = TryCreateResourceElementSet(module, er);

            if (set is null)
            {
                return(null);
            }

            var dirName = Path.GetDirectoryName(nonSatFile.Filename);
            var dir     = Directory.Length + 1 > dirName.Length ? string.Empty : dirName.Substring(Directory.Length + 1);

            name = Path.GetFileNameWithoutExtension(nonSatFile.Filename);
            ext  = Path.GetExtension(nonSatFile.Filename);
            var filename = filenameCreator.CreateFromRelativePath(Path.Combine(dir, name) + "." + asm.Culture, ext);

            return(CreateResXFile(module, er, set, filename, string.Empty, true));
        }
        /// <summary>
        /// Writes an assembly
        /// </summary>
        /// <typeparam name="T">Writer type</typeparam>
        /// <param name="output">Output</param>
        /// <param name="asm">Assembly</param>
        /// <returns></returns>
        public static T Write <T>(this T output, IAssembly?asm) where T : ITextColorWriter
        {
            if (asm is null)
            {
                return(output);
            }
            var  asmDef = asm as AssemblyDef;
            bool isExe  = asmDef is not null &&
                          asmDef.ManifestModule is not null &&
                          (asmDef.ManifestModule.Characteristics & dnlib.PE.Characteristics.Dll) == 0;

            output.Write(isExe ? BoxedTextColor.AssemblyExe : BoxedTextColor.Assembly, asm.Name);

            output.WriteCommaSpace();

            output.Write(BoxedTextColor.InstanceProperty, "Version");
            output.Write(BoxedTextColor.Operator, "=");
            output.Write(asm.Version);

            output.WriteCommaSpace();

            output.Write(BoxedTextColor.InstanceProperty, "Culture");
            output.Write(BoxedTextColor.Operator, "=");
            output.Write(BoxedTextColor.EnumField, UTF8String.IsNullOrEmpty(asm.Culture) ? "neutral" : asm.Culture.String);

            output.WriteCommaSpace();

            var publicKey = PublicKeyBase.ToPublicKeyToken(asm.PublicKeyOrToken);

            output.Write(BoxedTextColor.InstanceProperty, publicKey is null || publicKey is PublicKeyToken ? "PublicKeyToken" : "PublicKey");
            output.Write(BoxedTextColor.Operator, "=");
            if (PublicKeyBase.IsNullOrEmpty2(publicKey))
            {
                output.Write(BoxedTextColor.Keyword, "null");
            }
            else
            {
                Debug2.Assert(publicKey is not null);
                output.Write(BoxedTextColor.Number, publicKey.ToString());
            }

            if ((asm.Attributes & AssemblyAttributes.Retargetable) != 0)
            {
                output.WriteCommaSpace();
                output.Write(BoxedTextColor.InstanceProperty, "Retargetable");
                output.Write(BoxedTextColor.Operator, "=");
                output.Write(BoxedTextColor.EnumField, "Yes");
            }

            if ((asm.Attributes & AssemblyAttributes.ContentType_Mask) == AssemblyAttributes.ContentType_WindowsRuntime)
            {
                output.WriteCommaSpace();
                output.Write(BoxedTextColor.InstanceProperty, "ContentType");
                output.Write(BoxedTextColor.Operator, "=");
                output.Write(BoxedTextColor.EnumField, "WindowsRuntime");
            }

            return(output);
        }
예제 #9
0
        protected override void Execute(ConfuserContext context, ProtectionParameters parameters)
        {
            if (parameters.Targets.Any())
            {
                if (!UTF8String.IsNullOrEmpty(context.CurrentModule.Assembly.Culture))
                {
                    context.Logger.LogFormat("WARN: Skipping resource encryption for satellite assembly '{0}'.",
                                             context.CurrentModule.Assembly.FullName);
                    return;
                }
                var compression = context.Registry.GetService <ICompressionService>();
                var name        = context.Registry.GetService <INameService>();
                var marker      = context.Registry.GetService <IMarkerService>();
                var rt          = context.Registry.GetService <IRuntimeService>();
                var moduleCtx   = new REContext {
                    Random    = context.Registry.GetService <IRandomService>().GetRandomGenerator(Parent.Id),
                    Context   = context,
                    Module    = context.CurrentModule,
                    Marker    = marker,
                    DynCipher = context.Registry.GetService <IDynCipherService>(),
                    Name      = name
                };

                // Extract parameters
                moduleCtx.Mode = parameters.GetParameter(context, context.CurrentModule, "mode", Mode.Normal);

                switch (moduleCtx.Mode)
                {
                case Mode.Normal:
                    moduleCtx.ModeHandler = new NormalMode();
                    break;

                case Mode.Dynamic:
                    moduleCtx.ModeHandler = new DynamicMode();
                    break;

                default:
                    throw new UnreachableException();
                }

                // Inject helpers
                MethodDef decomp = compression.GetRuntimeDecompressor(context.CurrentModule, member => {
                    name.MarkHelper(member, marker, (Protection)Parent);
                    if (member is MethodDef)
                    {
                        ProtectionParameters.GetParameters(context, member).Remove(Parent);
                    }
                });
                InjectHelpers(context, compression, rt, moduleCtx);

                // Mutate codes
                MutateInitializer(moduleCtx, decomp);

                MethodDef cctor = context.CurrentModule.GlobalType.FindStaticConstructor();
                cctor.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, moduleCtx.InitMethod));

                new MDPhase(moduleCtx).Hook();
            }
        }
예제 #10
0
 static UTF8String GetDllImportMethodName(MethodDef method, ImplMap implMap)
 {
     if (!UTF8String.IsNullOrEmpty(implMap.Name))
     {
         return(implMap.Name);
     }
     return(method.Name);
 }
예제 #11
0
        public static T Write <T>(this T output, IAssembly asm) where T : ITextOutput
        {
            if (asm == null)
            {
                return(output);
            }
            var  asmDef = asm as AssemblyDef;
            bool isExe  = asmDef != null &&
                          asmDef.ManifestModule != null &&
                          (asmDef.ManifestModule.Characteristics & dnlib.PE.Characteristics.Dll) == 0;

            output.Write(asm.Name, isExe ? TextTokenType.AssemblyExe : TextTokenType.Assembly);

            output.WriteCommaSpace();

            output.Write("Version", TextTokenType.InstanceProperty);
            output.Write('=', TextTokenType.Operator);
            output.Write(asm.Version);

            output.WriteCommaSpace();

            output.Write("Culture", TextTokenType.InstanceProperty);
            output.Write('=', TextTokenType.Operator);
            output.Write(UTF8String.IsNullOrEmpty(asm.Culture) ? "neutral" : asm.Culture.String, TextTokenType.EnumField);

            output.WriteCommaSpace();

            var publicKey = PublicKeyBase.ToPublicKeyToken(asm.PublicKeyOrToken);

            output.Write(publicKey == null || publicKey is PublicKeyToken ? "PublicKeyToken" : "PublicKey", TextTokenType.InstanceProperty);
            output.Write('=', TextTokenType.Operator);
            if (PublicKeyBase.IsNullOrEmpty2(publicKey))
            {
                output.Write("null", TextTokenType.Keyword);
            }
            else
            {
                output.Write(publicKey.ToString(), TextTokenType.Number);
            }

            if ((asm.Attributes & AssemblyAttributes.Retargetable) != 0)
            {
                output.WriteCommaSpace();
                output.Write("Retargetable", TextTokenType.InstanceProperty);
                output.Write('=', TextTokenType.Operator);
                output.Write("Yes", TextTokenType.EnumField);
            }

            if ((asm.Attributes & AssemblyAttributes.ContentType_Mask) == AssemblyAttributes.ContentType_WindowsRuntime)
            {
                output.WriteCommaSpace();
                output.Write("ContentType", TextTokenType.InstanceProperty);
                output.Write('=', TextTokenType.Operator);
                output.Write("WindowsRuntime", TextTokenType.EnumField);
            }

            return(output);
        }
예제 #12
0
        void RemoveDuplicateEmbeddedResources()
        {
            var resources = new Dictionary <ResourceKey, List <EmbeddedResource> >();

            foreach (var tmp in module.Resources)
            {
                var rsrc = tmp as EmbeddedResource;
                if (rsrc == null)
                {
                    continue;
                }
                if (rsrc.Offset == null)
                {
                    continue;
                }
                List <EmbeddedResource> list;
                var key = new ResourceKey(rsrc);
                if (!resources.TryGetValue(key, out list))
                {
                    resources[key] = list = new List <EmbeddedResource>();
                }
                list.Add(rsrc);
            }

            foreach (var list in resources.Values)
            {
                if (list.Count <= 1)
                {
                    continue;
                }

                EmbeddedResource resourceToKeep = null;
                foreach (var rsrc in list)
                {
                    if (UTF8String.IsNullOrEmpty(rsrc.Name))
                    {
                        continue;
                    }

                    resourceToKeep = rsrc;
                    break;
                }
                if (resourceToKeep == null)
                {
                    continue;
                }

                foreach (var rsrc in list)
                {
                    if (rsrc == resourceToKeep)
                    {
                        continue;
                    }
                    AddResourceToBeRemoved(rsrc, string.Format("Duplicate of resource {0}", Utils.ToCsharpString(resourceToKeep.Name)));
                }
            }
        }
예제 #13
0
 public NamespaceTreeViewItem(IDocumentService documentService, UTF8String name, IEnumerable <TypeDef> types)
 {
     this.documentService = documentService;
     this.Name            = name;
     this.Types           = types.ToArray();
     this.Texts           = new[]
     {
         new TextRun(UTF8String.IsNullOrEmpty(this.Name) ? "-" : this.Name.String, "d-namespace"),
     };
 }
예제 #14
0
 /// <summary>
 /// Adds a string to the #Strings heap, but does not re-use an existing position
 /// </summary>
 /// <param name="s">The string</param>
 /// <returns>The offset of the string in the #Strings heap</returns>
 public uint Create(UTF8String s)
 {
     if (isReadOnly)
     {
         throw new ModuleWriterException("Trying to modify #Strings when it's read-only");
     }
     if (UTF8String.IsNullOrEmpty(s))
     {
         s = UTF8String.Empty;
     }
     return(AddToCache(s));
 }
예제 #15
0
        static string GetDotNetVersion(AssemblyDef asm, out string profile)
        {
            profile = null;
            var ca = asm.CustomAttributes.Find("System.Runtime.Versioning.TargetFrameworkAttribute");

            if (ca == null)
            {
                return(null);
            }

            if (ca.ConstructorArguments.Count != 1)
            {
                return(null);
            }
            var arg = ca.ConstructorArguments[0];

            if (arg.Type.GetElementType() != ElementType.String)
            {
                return(null);
            }
            var s = arg.Value as UTF8String;

            if (UTF8String.IsNullOrEmpty(s))
            {
                return(null);
            }
            var          values         = s.String.Split(new char[] { ',' });
            bool         isDNF          = values.Any(a => StringComparer.OrdinalIgnoreCase.Equals(a, ".NETFramework"));
            const string VERSION_PREFIX = "Version=v";
            var          verString      = values.FirstOrDefault(a => a.StartsWith(VERSION_PREFIX, StringComparison.OrdinalIgnoreCase));

            if (isDNF && verString != null)
            {
                var ver   = verString.Substring(VERSION_PREFIX.Length);
                var match = new Regex(@"^\d+(?:\.\d+(?:\.\d+(?:\.\d+)?)?)?$").Match(ver);
                // "65535.65535.65535.65535"
                if (match.Success && ver.Length <= 5 * 4 + 3)
                {
                    const string PROFILE_PREFIX = "Profile=";
                    var          pv             = values.FirstOrDefault(a => a.StartsWith(PROFILE_PREFIX, StringComparison.Ordinal));
                    if (pv != null)
                    {
                        profile = pv.Substring(PROFILE_PREFIX.Length).Trim();
                    }
                    return("v" + ver);
                }
            }

            return(null);
        }
예제 #16
0
        public override void Create(DecompileContext ctx)
        {
            IList <string> refs;

            using (var stream = File.Create(Filename))
                refs = decompileBaml(bamlData, stream);
            foreach (var asmRef in refs)
            {
                var a = new AssemblyNameInfo(asmRef);
                if (!UTF8String.IsNullOrEmpty(a.Name))
                {
                    asmRefs.Add(a);
                }
            }
        }
예제 #17
0
        public static string CreateDisplayName(IMethod method, bool fullName = false)
        {
            var sb = new StringBuilder();

            if (fullName)
            {
                sb.AppendFormat("{0}.", CreateDisplayName(method.DeclaringType, true));
            }

            if (method.MethodSig == null)
            {
                sb.Append(method.Name ?? "<<<NULL>>>");
            }
            else
            {
                if (!UTF8String.IsNullOrEmpty(method.Name))
                {
                    sb.Append(method.Name);
                }
                if (method.MethodSig.Generic)
                {
                    sb.Append('<');
                    uint genParamCount = method.MethodSig.GenParamCount;
                    for (uint i = 0; i < genParamCount; i++)
                    {
                        if (i != 0)
                        {
                            sb.Append(", ");
                        }
                        sb.Append(FullNameCreator.Name(new GenericMVar(i, method as MethodDef), false));
                    }
                    sb.Append('>');
                }
                sb.Append('(');
                int count = PrintMethodArgList(sb, method.MethodSig.Params, false, false);
                PrintMethodArgList(sb, method.MethodSig.ParamsAfterSentinel, count > 0, true);
                if (method.Name == ".ctor" || method.Name == ".cctor")
                {
                    sb.Append(")");
                }
                else
                {
                    sb.Append(") : ");
                    sb.Append(CreateDisplayName(method.MethodSig.RetType));
                }
            }
            return(sb.ToString());
        }
예제 #18
0
        TypeDef GetNestedType(string name)
        {
            if (typeOpt == null)
            {
                return(null);
            }
            var nestedTypes = typeOpt.NestedTypes;
            int count       = nestedTypes.Count;

            for (int i = 0; i < count; i++)
            {
                var type = nestedTypes[i];
                if (UTF8String.IsNullOrEmpty(type.Namespace))
                {
                    if (type.Name == name)
                    {
                        return(type);
                    }
                    var typeName = type.Name.String;
                    if (typeName.StartsWith(name) && typeName.Length >= name.Length + 2)
                    {
                        int index = name.Length;
                        if (typeName[index] == '`')
                        {
                            Debug.Assert(index + 1 < typeName.Length);
                            bool ok = true;
                            index++;
                            while (index < typeName.Length)
                            {
                                if (!char.IsDigit(typeName[index]))
                                {
                                    ok = false;
                                    break;
                                }
                                index++;
                            }
                            if (ok)
                            {
                                return(type);
                            }
                        }
                    }
                }
            }
            return(null);
        }
예제 #19
0
 TypeDef GetNestedType(string name)
 {
     if (typeOpt == null)
     {
         return(null);
     }
     foreach (var type in typeOpt.NestedTypes.GetSafeEnumerable())
     {
         if (UTF8String.IsNullOrEmpty(type.Namespace))
         {
             if (type.Name == name)
             {
                 return(type);
             }
             var typeName = type.Name.String;
             if (typeName.StartsWith(name) && typeName.Length >= name.Length + 2)
             {
                 int i = name.Length;
                 if (typeName[i] == '`')
                 {
                     Debug.Assert(i + 1 < typeName.Length);
                     bool ok = true;
                     i++;
                     while (i < typeName.Length)
                     {
                         if (!char.IsDigit(typeName[i]))
                         {
                             ok = false;
                             break;
                         }
                         i++;
                     }
                     if (ok)
                     {
                         return(type);
                     }
                 }
             }
         }
     }
     return(null);
 }
예제 #20
0
        /// <summary>
        /// Adds a string to the #Strings heap
        /// </summary>
        /// <param name="s">The string</param>
        /// <returns>The offset of the string in the #Strings heap</returns>
        public uint Add(UTF8String s)
        {
            if (isReadOnly)
            {
                throw new ModuleWriterException("Trying to modify #Strings when it's read-only");
            }
            if (UTF8String.IsNullOrEmpty(s))
            {
                return(0);
            }

            uint offset;

            if (cachedDict.TryGetValue(s, out offset))
            {
                return(offset);
            }

            return(AddToCache(s));
        }
예제 #21
0
        static Dictionary <string, List <MethodDef> > GetPinvokes(TypeDef type)
        {
            var pinvokes = new Dictionary <string, List <MethodDef> >(StringComparer.Ordinal);

            foreach (var method in type.Methods)
            {
                var info = method.ImplMap;
                if (info == null || UTF8String.IsNullOrEmpty(info.Name))
                {
                    continue;
                }
                List <MethodDef> list;
                if (!pinvokes.TryGetValue(info.Name.String, out list))
                {
                    pinvokes[info.Name.String] = list = new List <MethodDef>();
                }
                list.Add(method);
            }
            return(pinvokes);
        }
예제 #22
0
        public static string CreateDisplayName(EventDef evnt, bool fullName = false)
        {
            var sb = new StringBuilder();

            if (fullName)
            {
                sb.AppendFormat("{0}.", CreateDisplayName(evnt.DeclaringType, true));
            }

            if (evnt.EventType == null)
            {
                sb.Append(evnt.Name ?? "<<<NULL>>>");
            }
            else
            {
                if (!UTF8String.IsNullOrEmpty(evnt.Name))
                {
                    sb.Append(evnt.Name);
                }
            }
            return(sb.ToString());
        }
예제 #23
0
        public static string CreateDisplayName(IField field, bool fullName = false)
        {
            var sb = new StringBuilder();

            if (fullName)
            {
                sb.AppendFormat("{0}.", CreateDisplayName(field.DeclaringType, true));
            }

            if (field.FieldSig.Type == null)
            {
                sb.Append(field.Name ?? "<<<NULL>>>");
            }
            else
            {
                if (!UTF8String.IsNullOrEmpty(field.Name))
                {
                    sb.Append(field.Name);
                }
                sb.Append(" : ");
                sb.Append(CreateDisplayName(field.FieldSig.Type));
            }
            return(sb.ToString());
        }
예제 #24
0
        void Initialize()
        {
            if (!(namespaces is null))
            {
                return;
            }

            // Only include actual used namespaces, eg. if "ns1.ns2.Type1" is used, but there's no
            // "ns1.TypeX", don't include "ns1" as a valid namespace.
            var hash = new HashSet <string>(module.Types.Select(a => UTF8String.ToSystemStringOrEmpty(a.Namespace)));

            hash.Remove(string.Empty);

            var sb   = new StringBuilder();
            var dict = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase);

            foreach (var ns in hash)
            {
                sb.Clear();
                foreach (var n in ns.Split('.'))
                {
                    if (sb.Length > 0)
                    {
                        sb.Append('.');
                    }
                    sb.Append(n);
                    var ns2 = sb.ToString();
                    dict[ns2] = ns2;
                }
            }

            // XAML resources only include the last part of types, eg. BaseNS.NS1.Type1 => ns1/type1
            var pmap2       = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase);
            var pmap3       = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase);
            var pnsmap      = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase);
            var stringCache = new Dictionary <string, string>(StringComparer.Ordinal);

            // Don't include nested types
            foreach (var t in module.Types)
            {
                string fullName;
                var    nsu = t.Namespace;
                if (UTF8String.IsNullOrEmpty(nsu))
                {
                    fullName = (t.Name ?? UTF8String.Empty).String;
                }
                else
                {
                    fullName = nsu !.String + "." + (t.Name ?? UTF8String.Empty).String;
                }
                pmap3[fullName] = fullName;
                var name = fullName;
                while (name.Length > 0)
                {
                    pmap2[name] = fullName;
                    int index = name.IndexOf('.');
                    if (index < 0)
                    {
                        break;
                    }
                    name = name.Substring(index + 1);
                }

                var ns = (t.Namespace ?? UTF8String.Empty).String;
                while (ns.Length > 0)
                {
                    if (stringCache.TryGetValue(ns, out var tmp))
                    {
                        ns = tmp;
                    }
                    else
                    {
                        stringCache[ns] = ns;
                    }
                    pnsmap[ns] = ns;
                    int index = ns.IndexOf('.');
                    if (index < 0)
                    {
                        break;
                    }
                    ns = ns.Substring(index + 1);
                }
            }

            partialNamespaceMap      = pnsmap;
            partialTypeToFullNameMap = pmap2;
            typeToFullNameMap        = pmap3;
            lowerCaseNsToReal        = dict;
            namespaces = hash;
        }
예제 #25
0
        static void CreateDisplayName(StringBuilder sb, RecursionCounter recu, TypeSig sig, bool fullName)
        {
            if (sig == null)
            {
                sb.Append("<<<NULL>>>");
                return;
            }
            if (!recu.Increment())
            {
                sb.Append("<<<INFRECURSION>>>");
                return;
            }

            switch (sig.ElementType)
            {
            case ElementType.Void:
            case ElementType.Boolean:
            case ElementType.Char:
            case ElementType.I1:
            case ElementType.U1:
            case ElementType.I2:
            case ElementType.U2:
            case ElementType.I4:
            case ElementType.U4:
            case ElementType.I8:
            case ElementType.U8:
            case ElementType.R4:
            case ElementType.R8:
            case ElementType.String:
            case ElementType.TypedByRef:
            case ElementType.I:
            case ElementType.U:
            case ElementType.Object:
            case ElementType.ValueType:
            case ElementType.Class:
                var type = ((TypeDefOrRefSig)sig).TypeDefOrRef;
                if (fullName)
                {
                    sb.Append(type.ReflectionFullName);
                }
                else
                {
                    sb.Append(type.Name ?? "<<<NULL>>>");
                }
                break;

            case ElementType.Ptr:
                CreateDisplayName(sb, recu, sig.Next, fullName);
                sb.Append('*');
                break;

            case ElementType.ByRef:
                CreateDisplayName(sb, recu, sig.Next, fullName);
                sb.Append('&');
                break;

            case ElementType.Array: {
                CreateDisplayName(sb, recu, sig.Next, fullName);
                var arraySig = (ArraySig)sig;
                sb.Append('[');
                uint rank = arraySig.Rank;
                if (rank == 0)
                {
                    sb.Append("<RANK0>");                             // Not allowed
                }
                else if (rank == 1)
                {
                    sb.Append('*');
                }
                else
                {
                    for (int i = 0; i < (int)rank; i++)
                    {
                        if (i != 0)
                        {
                            sb.Append(", ");
                        }

                        const int  NO_LOWER = int.MinValue;
                        const uint NO_SIZE  = uint.MaxValue;
                        int        lower    = arraySig.LowerBounds.Get(i, NO_LOWER);
                        uint       size     = arraySig.Sizes.Get(i, NO_SIZE);
                        if (lower != NO_LOWER)
                        {
                            sb.Append(lower);
                            sb.Append("..");
                            if (size != NO_SIZE)
                            {
                                sb.Append(lower + (int)size - 1);
                            }
                            else
                            {
                                sb.Append('.');
                            }
                        }
                    }
                }
                sb.Append(']');
                break;
            }

            case ElementType.SZArray:
                CreateDisplayName(sb, recu, sig.Next, fullName);
                sb.Append("[]");
                break;

            case ElementType.CModReqd:
                CreateDisplayName(sb, recu, sig.Next, fullName);
                sb.Append(" modreq(");
                sb.Append(((ModifierSig)sig).Modifier.Name ?? "<<<NULL>>>");
                sb.Append(")");
                break;

            case ElementType.CModOpt:
                CreateDisplayName(sb, recu, sig.Next, fullName);
                sb.Append(" modopt(");
                sb.Append(((ModifierSig)sig).Modifier.Name ?? "<<<NULL>>>");
                sb.Append(")");
                break;

            case ElementType.Pinned:
                CreateDisplayName(sb, recu, sig.Next, fullName);
                break;

            case ElementType.ValueArray:
                CreateDisplayName(sb, recu, sig.Next, fullName);
                var valueArraySig = (ValueArraySig)sig;
                sb.Append(" ValueArray(");
                sb.Append(valueArraySig.Size);
                sb.Append(')');
                break;

            case ElementType.Module:
                CreateDisplayName(sb, recu, sig.Next, fullName);
                var moduleSig = (ModuleSig)sig;
                sb.Append(" Module(");
                sb.Append(moduleSig.Index);
                sb.Append(')');
                break;

            case ElementType.GenericInst: {
                var genericInstSig = (GenericInstSig)sig;
                var typeGenArgs    = genericInstSig.GenericArguments;
                CreateDisplayName(sb, recu, genericInstSig.GenericType, fullName);
                sb.Append('<');
                int i = -1;
                foreach (var genArg in typeGenArgs.GetSafeEnumerable())
                {
                    i++;
                    if (i != 0)
                    {
                        sb.Append(", ");
                    }
                    CreateDisplayName(sb, recu, genArg, false);
                }
                sb.Append('>');
            }
            break;

            case ElementType.Var:
            case ElementType.MVar:
                var gs = (GenericSig)sig;
                var gp = gs.GenericParam;
                if (gp == null || UTF8String.IsNullOrEmpty(gp.Name))
                {
                    sb.Append(gs.IsMethodVar ? "!!" : "!");
                    sb.Append(gs.Number);
                }
                else
                {
                    sb.Append(gp.Name);
                }
                break;

            case ElementType.FnPtr:
                sb.Append("(fnptr)");
                break;

            case ElementType.Sentinel:
                break;

            case ElementType.End:
            case ElementType.R:
            case ElementType.Internal:
            default:
                break;
            }

            recu.Decrement();
        }
예제 #26
0
 public uint Create(UTF8String name) => Create(UTF8String.IsNullOrEmpty(name) ? Array.Empty <byte>() : name.Data);
예제 #27
0
        void CreateUI(ITextColorWriter output, object?o, bool includeNamespace)
        {
            if (o is NamespaceSearchResult ns)
            {
                output.WriteNamespace(ns.Namespace);
                return;
            }

            if (o is TypeDef td)
            {
                Debug2.Assert(!(Context.Decompiler is null));
                Context.Decompiler.WriteType(output, td, includeNamespace);
                return;
            }

            if (o is MethodDef md)
            {
                var methodNameColor = Context.Decompiler.MetadataTextColorProvider.GetColor(md);
                output.Write(methodNameColor, IdentifierEscaper.Escape(md.Name));
                if (md.ImplMap is ImplMap implMap && !UTF8String.IsNullOrEmpty(implMap.Name) && implMap.Name != md.Name)
                {
                    output.WriteSpace();
                    output.Write(BoxedTextColor.Punctuation, "(");
                    output.Write(methodNameColor, IdentifierEscaper.Escape(implMap.Name));
                    output.Write(BoxedTextColor.Punctuation, ")");
                }
                return;
            }

            if (o is FieldDef fd)
            {
                output.Write(Context.Decompiler.MetadataTextColorProvider.GetColor(fd), IdentifierEscaper.Escape(fd.Name));
                return;
            }

            if (o is PropertyDef pd)
            {
                output.Write(Context.Decompiler.MetadataTextColorProvider.GetColor(pd), IdentifierEscaper.Escape(pd.Name));
                return;
            }

            if (o is EventDef ed)
            {
                output.Write(Context.Decompiler.MetadataTextColorProvider.GetColor(ed), IdentifierEscaper.Escape(ed.Name));
                return;
            }

            if (o is AssemblyDef asm)
            {
                output.Write(asm);
                return;
            }

            if (o is ModuleDef mod)
            {
                output.WriteModule(mod.FullName);
                return;
            }

            if (o is AssemblyRef asmRef)
            {
                output.Write(asmRef);
                return;
            }

            if (o is ModuleRef modRef)
            {
                output.WriteModule(modRef.FullName);
                return;
            }

            if (o is ParamDef paramDef)
            {
                output.Write(BoxedTextColor.Parameter, IdentifierEscaper.Escape(paramDef.Name));
                return;
            }

            // non-.NET file
            if (o is IDsDocument document)
            {
                output.Write(BoxedTextColor.Text, document.GetShortName());
                return;
            }

            if (o is ResourceNode resNode)
            {
                output.WriteFilename(resNode.Name);
                return;
            }

            if (o is ResourceElementNode resElNode)
            {
                output.WriteFilename(resElNode.Name);
                return;
            }

            if (o is ErrorMessage em)
            {
                output.Write(em.Color, em.Text);
                return;
            }

            Debug2.Assert(o is null);
        }
예제 #28
0
        static Info?GetInfo(TypeDef td)
        {
            if (td == null)
            {
                return(null);
            }
            if (td.IsWindowsRuntime)
            {
                return(null);
            }

            UTF8String scope = null, identifier = null;
            var        tia = td.CustomAttributes.Find("System.Runtime.InteropServices.TypeIdentifierAttribute");

            if (tia != null)
            {
                if (tia.ConstructorArguments.Count >= 2)
                {
                    if (tia.ConstructorArguments[0].Type.GetElementType() != ElementType.String)
                    {
                        return(null);
                    }
                    if (tia.ConstructorArguments[1].Type.GetElementType() != ElementType.String)
                    {
                        return(null);
                    }
                    scope      = tia.ConstructorArguments[0].Value as UTF8String ?? tia.ConstructorArguments[0].Value as string;
                    identifier = tia.ConstructorArguments[1].Value as UTF8String ?? tia.ConstructorArguments[1].Value as string;
                }
            }
            else
            {
                var mod = td.Module;
                var asm = mod == null ? null : mod.Assembly;
                if (asm == null)
                {
                    return(null);
                }
                bool isTypeLib = asm.CustomAttributes.IsDefined("System.Runtime.InteropServices.ImportedFromTypeLibAttribute") ||
                                 asm.CustomAttributes.IsDefined("System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute");
                if (!isTypeLib)
                {
                    return(null);
                }
            }

            if (UTF8String.IsNull(identifier))
            {
                CustomAttribute gca;
                if (td.IsInterface && td.IsImport)
                {
                    gca = td.CustomAttributes.Find("System.Runtime.InteropServices.GuidAttribute");
                }
                else
                {
                    var mod = td.Module;
                    var asm = mod == null ? null : mod.Assembly;
                    if (asm == null)
                    {
                        return(null);
                    }
                    gca = asm.CustomAttributes.Find("System.Runtime.InteropServices.GuidAttribute");
                }
                if (gca == null)
                {
                    return(null);
                }
                if (gca.ConstructorArguments.Count < 1)
                {
                    return(null);
                }
                if (gca.ConstructorArguments[0].Type.GetElementType() != ElementType.String)
                {
                    return(null);
                }
                scope = gca.ConstructorArguments[0].Value as UTF8String ?? gca.ConstructorArguments[0].Value as string;
                var ns   = td.Namespace;
                var name = td.Name;
                if (UTF8String.IsNullOrEmpty(ns))
                {
                    identifier = name;
                }
                else if (UTF8String.IsNullOrEmpty(name))
                {
                    identifier = new UTF8String(Concat(ns.Data, (byte)'.', empty));
                }
                else
                {
                    identifier = new UTF8String(Concat(ns.Data, (byte)'.', name.Data));
                }
            }
            return(new Info(scope, identifier));
        }