Example #1
0
 public MemberRefOptions(MemberRef mr)
 {
     this.Class = mr.Class;
     this.Name = mr.Name;
     this.Signature = mr.Signature;
     this.CustomAttributes.AddRange(mr.CustomAttributes);
 }
Example #2
0
		public static void SplitNameAndNamespace(UTF8String utf8Name, string fullName, out UTF8String ns, out UTF8String name) {
			if (fullName == null)
				fullName = string.Empty;

			if (!UTF8String.IsNull(utf8Name)) {
				if (fullName == utf8Name.String) {
					ns = UTF8String.Empty;
					name = utf8Name;
					return;
				}

				if (fullName.EndsWith("." + utf8Name.String)) {
					ns = fullName.Substring(0, fullName.Length - utf8Name.String.Length - 1);
					name = utf8Name;
					return;
				}
			}

			int i = fullName.LastIndexOf('.');
			if (i < 0) {
				ns = UTF8String.Empty;
				name = fullName;
			}
			else {
				ns = fullName.Substring(0, i);
				name = fullName.Substring(i + 1);
			}
		}
Example #3
0
		public static EventDefOptions Create(UTF8String name, ITypeDefOrRef eventType) {
			return new EventDefOptions {
				Attributes = 0,
				Name = name,
				EventType = eventType,
			};
		}
Example #4
0
 void InitializeName(UTF8String utf8Name, string fullName)
 {
     UTF8String ns, name;
     Utils.SplitNameAndNamespace(utf8Name, fullName, out ns, out name);
     this.Namespace = ns;
     this.Name = name;
 }
		/// <summary>
		/// Creates a <see cref="SecurityAttribute"/> from an XML string.
		/// </summary>
		/// <param name="module">Owner module</param>
		/// <param name="xml">XML</param>
		/// <returns>A new <see cref="SecurityAttribute"/> instance</returns>
		public static SecurityAttribute CreateFromXml(ModuleDef module, string xml) {
			var attrType = module.CorLibTypes.GetTypeRef("System.Security.Permissions", "PermissionSetAttribute");
			var utf8Xml = new UTF8String(xml);
			var namedArg = new CANamedArgument(false, module.CorLibTypes.String, "XML", new CAArgument(module.CorLibTypes.String, utf8Xml));
			var list = ThreadSafeListCreator.Create<CANamedArgument>(namedArg);
			return new SecurityAttribute(attrType, list);
		}
Example #6
0
		public GenericParamOptions(GenericParam gp) {
			Number = gp.Number;
			Flags = gp.Flags;
			Name = gp.Name;
			Kind = gp.Kind;
			GenericParamConstraints.AddRange(gp.GenericParamConstraints);
			CustomAttributes.AddRange(gp.CustomAttributes);
		}
Example #7
0
		public ParamDefOptions(ParamDef pd) {
			Name = pd.Name;
			Sequence = pd.Sequence;
			Attributes = pd.Attributes;
			Constant = pd.Constant;
			MarshalType = pd.MarshalType;
			CustomAttributes.AddRange(pd.CustomAttributes);
		}
Example #8
0
		public GenericParamOptions(GenericParam gp) {
			this.Number = gp.Number;
			this.Flags = gp.Flags;
			this.Name = gp.Name;
			this.Kind = gp.Kind;
			this.GenericParamConstraints.AddRange(gp.GenericParamConstraints);
			this.CustomAttributes.AddRange(gp.CustomAttributes);
		}
Example #9
0
		public static void Write(this BinaryWriter writer, IWriterError helper, UTF8String s) {
			if (UTF8String.IsNull(s)) {
				helper.Error("UTF8String is null");
				s = UTF8String.Empty;
			}

			writer.WriteCompressedUInt32(helper, (uint)s.DataLength);
			writer.Write(s.Data);
		}
Example #10
0
		public static MethodDefOptions Create(UTF8String name, MethodSig methodSig) {
			return new MethodDefOptions {
				ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed,
				Attributes = MethodAttributes.Public | MethodAttributes.ReuseSlot | MethodAttributes.HideBySig | (methodSig.HasThis ? 0 : MethodAttributes.Static),
				Name = name,
				MethodSig = methodSig,
				ImplMap = null,
			};
		}
Example #11
0
		public EventDefOptions(EventDef evt) {
			Attributes = evt.Attributes;
			Name = evt.Name;
			EventType = evt.EventType;
			AddMethod = evt.AddMethod;
			InvokeMethod = evt.InvokeMethod;
			RemoveMethod = evt.RemoveMethod;
			OtherMethods.AddRange(evt.OtherMethods);
			CustomAttributes.AddRange(evt.CustomAttributes);
		}
Example #12
0
		public PropertyDefOptions(PropertyDef prop) {
			Attributes = prop.Attributes;
			Name = prop.Name;
			PropertySig = prop.PropertySig;
			Constant = prop.Constant;
			GetMethods.AddRange(prop.GetMethods);
			SetMethods.AddRange(prop.SetMethods);
			OtherMethods.AddRange(prop.OtherMethods);
			CustomAttributes.AddRange(prop.CustomAttributes);
		}
Example #13
0
		public static PropertyDefOptions Create(ModuleDef module, UTF8String name, bool isInstance) {
			return new PropertyDefOptions {
				Attributes = 0,
				Name = name,
				PropertySig = isInstance ?
								PropertySig.CreateInstance(module.CorLibTypes.Int32) :
								PropertySig.CreateStatic(module.CorLibTypes.Int32),
				Constant = null,
			};
		}
Example #14
0
		public static TypeDefOptions Create(UTF8String ns, UTF8String name, ITypeDefOrRef baseType, bool isNestedType) {
			return new TypeDefOptions {
				Attributes = (isNestedType ? TypeAttributes.NestedPublic : TypeAttributes.Public) | TypeAttributes.AutoLayout | TypeAttributes.Class | TypeAttributes.AnsiClass,
				Namespace = ns ?? UTF8String.Empty,
				Name = name ?? UTF8String.Empty,
				PackingSize = null,
				ClassSize = null,
				BaseType = baseType,
			};
		}
Example #15
0
		public PropertyDefOptions(PropertyDef prop) {
			this.Attributes = prop.Attributes;
			this.Name = prop.Name;
			this.PropertySig = prop.PropertySig;
			this.Constant = prop.Constant;
			this.GetMethods.AddRange(prop.GetMethods);
			this.SetMethods.AddRange(prop.SetMethods);
			this.OtherMethods.AddRange(prop.OtherMethods);
			this.CustomAttributes.AddRange(prop.CustomAttributes);
		}
Example #16
0
		public EventDefOptions(EventDef evt) {
			this.Attributes = evt.Attributes;
			this.Name = evt.Name;
			this.EventType = evt.EventType;
			this.AddMethod = evt.AddMethod;
			this.InvokeMethod = evt.InvokeMethod;
			this.RemoveMethod = evt.RemoveMethod;
			this.OtherMethods.AddRange(evt.OtherMethods);
			this.CustomAttributes.AddRange(evt.CustomAttributes);
		}
Example #17
0
		public AssemblyOptions(AssemblyDef asm) {
			HashAlgorithm = asm.HashAlgorithm;
			Version = asm.Version;
			Attributes = asm.Attributes;
			PublicKey = asm.PublicKey;
			Name = asm.Name;
			Culture = asm.Culture;
			ClrVersion = Module.ClrVersion.DefaultVersion;
			CustomAttributes.AddRange(asm.CustomAttributes);
			DeclSecurities.AddRange(asm.DeclSecurities);
		}
Example #18
0
		public MethodDefOptions(MethodDef method) {
			this.ImplAttributes = method.ImplAttributes;
			this.Attributes = method.Attributes;
			this.Name = method.Name;
			this.MethodSig = method.MethodSig;
			this.ImplMap = method.ImplMap;
			this.CustomAttributes.AddRange(method.CustomAttributes);
			this.DeclSecurities.AddRange(method.DeclSecurities);
			this.ParamDefs.AddRange(method.ParamDefs);
			this.GenericParameters.AddRange(method.GenericParameters);
			this.Overrides.AddRange(method.Overrides);
		}
Example #19
0
		public FieldDefOptions(FieldDef field) {
			Attributes = field.Attributes;
			Name = field.Name;
			FieldSig = field.FieldSig;
			FieldOffset = field.FieldOffset;
			MarshalType = field.MarshalType;
			RVA = field.RVA;
			InitialValue = field.InitialValue;
			ImplMap = field.ImplMap;
			Constant = field.Constant;
			CustomAttributes.AddRange(field.CustomAttributes);
		}
Example #20
0
		internal static void InitializeName(string fullname, out UTF8String @namespace, out UTF8String name) {
			string s = fullname ?? string.Empty;
			int index = s.LastIndexOf('.');
			if (index < 0) {
				@namespace = UTF8String.Empty;
				name = s;
			}
			else {
				@namespace = s.Substring(0, index);
				name = s.Substring(index + 1);
			}
		}
Example #21
0
		public FieldDefOptions(FieldDef field) {
			this.Attributes = field.Attributes;
			this.Name = field.Name;
			this.FieldSig = field.FieldSig;
			this.FieldOffset = field.FieldOffset;
			this.MarshalType = field.MarshalType;
			this.RVA = field.RVA;
			this.InitialValue = field.InitialValue;
			this.ImplMap = field.ImplMap;
			this.Constant = field.Constant;
			this.CustomAttributes.AddRange(field.CustomAttributes);
		}
Example #22
0
		public static FieldDefOptions Create(UTF8String name, FieldSig fieldSig) {
			return new FieldDefOptions {
				Attributes = FieldAttributes.Public,
				Name = name,
				FieldSig = fieldSig,
				FieldOffset = null,
				MarshalType = null,
				RVA = 0,
				InitialValue = null,
				ImplMap = null,
				Constant = null,
			};
		}
Example #23
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);
        }
		static bool Compare(ITypeDefOrRef type, UTF8String expNs, UTF8String expName) {
			if (type == null)
				return false;

			var tr = type as TypeRef;
			if (tr != null)
				return tr.Namespace == expNs && tr.Name == expName;
			var td = type as TypeDef;
			if (td != null)
				return td.Namespace == expNs && td.Name == expName;

			return false;
		}
Example #25
0
		public MethodDefOptions(MethodDef method) {
			ImplAttributes = method.ImplAttributes;
			Attributes = method.Attributes;
			SemanticsAttributes = method.SemanticsAttributes;
			RVA = method.RVA;
			Name = method.Name;
			MethodSig = method.MethodSig;
			ImplMap = method.ImplMap;
			CustomAttributes.AddRange(method.CustomAttributes);
			DeclSecurities.AddRange(method.DeclSecurities);
			ParamDefs.AddRange(method.ParamDefs);
			GenericParameters.AddRange(method.GenericParameters);
			Overrides.AddRange(method.Overrides);
		}
Example #26
0
		public ModuleOptions(ModuleDef module) {
			Mvid = module.Mvid;
			EncId = module.EncId;
			EncBaseId = module.EncBaseId;
			Name = module.Name;
			Kind = module.Kind;
			Characteristics = module.Characteristics;
			DllCharacteristics = module.DllCharacteristics;
			RuntimeVersion = module.RuntimeVersion;
			Machine = module.Machine;
			Cor20HeaderFlags = module.Cor20HeaderFlags;
			Cor20HeaderRuntimeVersion = module.Cor20HeaderRuntimeVersion;
			TablesHeaderVersion = module.TablesHeaderVersion;
			ManagedEntryPoint = module.ManagedEntryPoint;
			NativeEntryPoint = module.NativeEntryPoint;
			CustomAttributes.AddRange(module.CustomAttributes);
		}
		void Populate(IImageStream reader) {
			reader.Position = 1;
			while (reader.Position < reader.Length) {
				uint offset = (uint)reader.Position;
				var bytes = reader.ReadBytesUntilByte(0);
				if (bytes == null)
					break;

				reader.ReadByte();	// terminating zero
				if (bytes.Length == 0)
					continue;

				var s = new UTF8String(bytes);
				if (!cachedDict.ContainsKey(s))
					cachedDict[s] = offset;
			}
		}
Example #28
0
		public TypeDefOptions(TypeDef type) {
			this.Attributes = type.Attributes;
			this.Namespace = type.Namespace;
			this.Name = type.Name;
			if (type.ClassLayout == null) {
				PackingSize = null;
				ClassSize = null;
			}
			else {
				PackingSize = type.ClassLayout.PackingSize;
				ClassSize = type.ClassLayout.ClassSize;
			}
			this.BaseType = type.BaseType;
			this.CustomAttributes.AddRange(type.CustomAttributes);
			this.DeclSecurities.AddRange(type.DeclSecurities);
			this.GenericParameters.AddRange(type.GenericParameters);
			this.Interfaces.AddRange(type.Interfaces);
		}
Example #29
0
		public static CustomAttribute Find(this IHasCustomAttribute provider, UTF8String ns, UTF8String name) {
			if (provider == null || provider.CustomAttributes.Count == 0)
				return null;
			foreach (var ca in provider.CustomAttributes) {
				var tr = ca.AttributeType as TypeRef;
				if (tr != null) {
					if (tr.Namespace == ns && tr.Name == name)
						return ca;
					continue;
				}

				var td = ca.AttributeType as TypeDef;
				if (td != null) {
					if (td.Namespace == ns && td.Name == name)
						return ca;
					continue;
				}
			}
			return null;
		}
Example #30
0
		public ResourceOptions(Resource resource) {
			this.ResourceType = resource.ResourceType;
			this.Name = resource.Name ?? UTF8String.Empty;
			this.Attributes = resource.Attributes;
			switch (resource.ResourceType) {
			case ResourceType.Embedded:
				break;

			case ResourceType.AssemblyLinked:
				this.Assembly = ((AssemblyLinkedResource)resource).Assembly;
				break;

			case ResourceType.Linked:
				this.File = ((LinkedResource)resource).File;
				break;

			default:
				throw new InvalidOperationException();
			}
		}
Example #31
0
 void Write(BinaryWriter writer, UTF8String s)
 {
     writer.Write(helper, s);
 }
Example #32
0
        internal static void InitializeName(string fullname, out UTF8String @namespace, out UTF8String name)
        {
            string s     = fullname ?? string.Empty;
            int    index = s.LastIndexOf('.');

            if (index < 0)
            {
                @namespace = UTF8String.Empty;
                name       = s;
            }
            else
            {
                @namespace = s.Substring(0, index);
                name       = s.Substring(index + 1);
            }
        }
Example #33
0
 public static bool CheckTypeDefOrTypeRefName(ITypeDefOrRef tdr, UTF8String @namespace, UTF8String name)
 {
     if (tdr is TypeDef td)
     {
         return(td.Name == name && td.Namespace == @namespace);
     }
     if (tdr is TypeRef tr)
     {
         return(tr.Name == name && tr.Namespace == @namespace);
     }
     return(false);
 }
 public string GetName(UTF8String oldName, INameCreator nameCreator)
 {
     return(GetName(UTF8String.ToSystemStringOrEmpty(oldName), nameCreator));
 }
Example #35
0
        static void Write(ITextOutput output, IAssembly asm)
        {
            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.Write(',', TextTokenType.Operator);
            output.WriteSpace();

            output.Write("Version", TextTokenType.InstanceProperty);
            output.Write('=', TextTokenType.Operator);
            output.Write(asm.Version.Major.ToString(), TextTokenType.Number);
            output.Write('.', TextTokenType.Operator);
            output.Write(asm.Version.Minor.ToString(), TextTokenType.Number);
            output.Write('.', TextTokenType.Operator);
            output.Write(asm.Version.Build.ToString(), TextTokenType.Number);
            output.Write('.', TextTokenType.Operator);
            output.Write(asm.Version.Revision.ToString(), TextTokenType.Number);

            output.Write(',', TextTokenType.Operator);
            output.WriteSpace();

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

            output.Write(',', TextTokenType.Operator);
            output.WriteSpace();

            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.Write(',', TextTokenType.Operator);
                output.WriteSpace();
                output.Write("Retargetable", TextTokenType.InstanceProperty);
                output.Write('=', TextTokenType.Operator);
                output.Write("Yes", TextTokenType.EnumField);
            }

            if ((asm.Attributes & AssemblyAttributes.ContentType_Mask) == AssemblyAttributes.ContentType_WindowsRuntime)
            {
                output.Write(',', TextTokenType.Operator);
                output.WriteSpace();
                output.Write("ContentType", TextTokenType.InstanceProperty);
                output.Write('=', TextTokenType.Operator);
                output.Write("WindowsRuntime", TextTokenType.EnumField);
            }
        }
Example #36
0
 void Write(DataWriter writer, UTF8String s) => writer.Write(helper, s);
Example #37
0
 public static string ToCsharpString(UTF8String s)
 {
     return(ToCsharpString(UTF8String.ToSystemStringOrEmpty(s)));
 }
Example #38
0
 public Info(UTF8String scope, UTF8String identifier)
 {
     this.Scope      = scope;
     this.Identifier = identifier;
 }
Example #39
0
        void Initialize()
        {
            if (namespaces != 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 string 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;
        }
Example #40
0
 public bool Equals(Info other)
 {
     return(stricmp(Scope, other.Scope) &&
            UTF8String.Equals(Identifier, other.Identifier));
 }
Example #41
0
 public TypeDefOptions()
 {
     Namespace = null !;
     Name      = null !;
 }
Example #42
0
 public StringsOffsetInfo(UTF8String value, uint stringsId)
 {
     Value     = value;
     StringsId = stringsId;
     Debug.Assert((stringsId & STRINGS_ID_FLAG) != 0);
 }
Example #43
0
        bool CheckResolutionScopeIsSameModule(MDToken resolutionScope, ModuleDef module)
        {
            switch (resolutionScope.Table)
            {
            case Table.Module:
                return(resolutionScope.Rid == 1);

            case Table.ModuleRef:
                var moduleRefRow = mdEditor.RealMetadata.TablesStream.ReadModuleRefRow(resolutionScope.Rid);
                if (moduleRefRow == null)
                {
                    return(false);
                }
                var moduleRefName = mdEditor.RealMetadata.StringsStream.ReadNoNull(moduleRefRow.Name);
                return(StringComparer.OrdinalIgnoreCase.Equals(moduleRefName.String, module.Name.String));

            case Table.AssemblyRef:
                var asm = module.Assembly;
                if (asm == null)
                {
                    return(false);
                }
                var assemblyRefRow = mdEditor.RealMetadata.TablesStream.ReadAssemblyRefRow(resolutionScope.Rid);
                // The version number isn't checked due to binding redirects
                var assemblyRefName = mdEditor.RealMetadata.StringsStream.ReadNoNull(assemblyRefRow.Name);
                if (!StringComparer.OrdinalIgnoreCase.Equals(assemblyRefName.String, UTF8String.ToSystemStringOrEmpty(asm.Name)))
                {
                    return(false);
                }
                var assemblyRefLocale = mdEditor.RealMetadata.StringsStream.ReadNoNull(assemblyRefRow.Name);
                if (!StringComparer.OrdinalIgnoreCase.Equals(assemblyRefLocale.String, UTF8String.ToSystemStringOrEmpty(asm.Culture)))
                {
                    return(false);
                }
                var    data = mdEditor.RealMetadata.BlobStream.ReadNoNull(assemblyRefRow.PublicKeyOrToken);
                byte[] asmPublicKeyOrTokenData;
                if ((assemblyRefRow.Flags & (uint)AssemblyAttributes.PublicKey) != 0)
                {
                    asmPublicKeyOrTokenData = asm.PublicKey?.Data ?? Array.Empty <byte>();
                }
                else
                {
                    asmPublicKeyOrTokenData = asm.PublicKeyToken?.Data ?? Array.Empty <byte>();
                }
                return(DataEquals(data, asmPublicKeyOrTokenData));

            default:
                return(false);
            }
        }
Example #44
0
 /// <summary>
 /// Gets a <see cref="CorLibTypeSig"/> if <paramref name="namespace"/> and
 /// <paramref name="name"/> matches a primitive type.
 /// </summary>
 /// <param name="self">this</param>
 /// <param name="namespace">Namespace</param>
 /// <param name="name">Name</param>
 /// <param name="defAsm">Definition assembly</param>
 /// <returns>A <see cref="CorLibTypeSig"/> or <c>null</c> if it didn't match any primitive type</returns>
 public static CorLibTypeSig GetCorLibTypeSig(this ICorLibTypes self, UTF8String @namespace, UTF8String name, IAssembly defAsm) =>
 self.GetCorLibTypeSig(UTF8String.ToSystemStringOrEmpty(@namespace), UTF8String.ToSystemStringOrEmpty(name), defAsm);
Example #45
0
        protected override void Execute(ConfuserContext context, ProtectionParameters parameters)
        {
            if (parameters.Targets.Any())
            {
                if (!UTF8String.IsNullOrEmpty(context.CurrentModule.Assembly.Culture))
                {
                    context.Logger.DebugFormat("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
                var 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);

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

                new MDPhase(moduleCtx).Hook();
            }
        }
Example #46
0
 public string GetName(UTF8String oldName, INameCreator nameCreator) => GetName(UTF8String.ToSystemStringOrEmpty(oldName), nameCreator);
Example #47
0
 public MemberRefInfo(MemberRef mr)
 {
     this.MemberRef = mr;
     this.OrigName  = mr.Name;
 }
Example #48
0
 public string GetName(UTF8String oldName, Func <string> createNewName) => GetName(UTF8String.ToSystemStringOrEmpty(oldName), createNewName);
Example #49
0
 void Write(UTF8String s) => writer.Write(helper, s);
Example #50
0
 public AssemblyRefInfo(AssemblyRef asmRef)
 {
     this.AssemblyRef          = asmRef;
     this.OrigName             = asmRef.Name;
     this.OrigPublicKeyOrToken = asmRef.PublicKeyOrToken;
 }
Example #51
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);
        }
Example #52
0
 public static string ToCsharpString(UTF8String s) => ToCsharpString(UTF8String.ToSystemStringOrEmpty(s));
Example #53
0
 private void Write(UTF8String s)
 {
     writer.Write(helper, s);
 }
Example #54
0
        /// <summary>
        /// Checks whether a custom attribute exists
        /// </summary>
        /// <param name="provider">Custom attribute provider</param>
        /// <param name="namespace">Namespace of custom attribute</param>
        /// <param name="name">Name of custom attribute</param>
        /// <returns></returns>
        public static bool IsDefined(this IHasCustomAttribute provider, UTF8String @namespace, UTF8String name)
        {
            if (provider == null || provider.CustomAttributes.Count == 0)
            {
                return(false);
            }
            foreach (var ca in provider.CustomAttributes)
            {
                if (ca.AttributeType is TypeRef tr)
                {
                    if (tr.Namespace == @namespace && tr.Name == name)
                    {
                        return(true);
                    }
                    continue;
                }

                if (ca.AttributeType is TypeDef td)
                {
                    if (td.Namespace == @namespace && td.Name == name)
                    {
                        return(true);
                    }
                    continue;
                }
            }
            return(false);
        }
Example #55
0
 public AssemblyRefInfo(AssemblyRef asmRef)
 {
     AssemblyRef          = asmRef;
     OrigName             = asmRef.Name;
     OrigPublicKeyOrToken = asmRef.PublicKeyOrToken;
 }
Example #56
0
 void InitializeName(UTF8String utf8Name, string fullName)
 {
     Utils.SplitNameAndNamespace(utf8Name, fullName, out var ns, out var name);
     Namespace = ns;
     Name      = name;
 }
Example #57
0
 public TypeRefInfo(TypeRef tr)
 {
     this.TypeRef       = tr;
     this.OrigNamespace = tr.Namespace;
 }
Example #58
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));
        }
Example #59
0
        bool GetCorLibToken(out MDToken corlibToken)
        {
            var stringsStream = mdEditor.RealMetadata.StringsStream.CreateReader();

            // Check if we have any assembly refs to the corlib
            {
                var table      = mdEditor.RealMetadata.TablesStream.AssemblyRefTable;
                var p          = peFile + (int)table.StartOffset;
                int rowSize    = (int)table.RowSize;
                var columnName = table.Columns[6];
                p += columnName.Offset;
                for (uint i = 0; i < table.Rows; i++, p += rowSize)
                {
                    uint       nameOffset      = columnName.Size == 2 ? *(ushort *)p : *(uint *)p;
                    UTF8String foundCorlibName = null;
                    foreach (var corlibName in corlibSimpleNames)
                    {
                        if (StringsStreamNameEquals(ref stringsStream, nameOffset, corlibName.Data))
                        {
                            foundCorlibName = corlibName;
                            break;
                        }
                    }
                    if ((object)foundCorlibName == null)
                    {
                        continue;
                    }

                    // Don't use any WinMD mscorlib refs (version = 255.255.255.255)
                    if (StringComparer.OrdinalIgnoreCase.Equals(foundCorlibName.String, "mscorlib") &&
                        *(ulong *)(p - columnName.Offset) == 0x00FF_00FF_00FF_00FF)
                    {
                        continue;
                    }

                    corlibToken = new MDToken(Table.AssemblyRef, i + 1);
                    return(true);
                }
            }

            // Check if we are the corlib. We're the corlib if System.Object is defined and if there
            // are no assembly references
            if (mdEditor.RealMetadata.TablesStream.AssemblyRefTable.Rows == 0)
            {
                var table           = mdEditor.RealMetadata.TablesStream.TypeDefTable;
                var p               = peFile + (int)table.StartOffset;
                int rowSize         = (int)table.RowSize;
                var columnName      = table.Columns[1];
                var columnNamespace = table.Columns[2];
                var columnExtends   = table.Columns[3];
                for (uint i = 0; i < table.Rows; i++, p += rowSize)
                {
                    if ((*(uint *)p & (uint)TypeAttributes.VisibilityMask) >= (int)TypeAttributes.NestedPublic)
                    {
                        continue;
                    }
                    uint nameOffset = columnName.Size == 2 ? *(ushort *)(p + columnName.Offset) : *(uint *)(p + columnName.Offset);
                    if (!StringsStreamNameEquals(ref stringsStream, nameOffset, nameObject.Data))
                    {
                        continue;
                    }
                    uint namespaceOffset = columnNamespace.Size == 2 ? *(ushort *)(p + columnNamespace.Offset) : *(uint *)(p + columnNamespace.Offset);
                    if (!StringsStreamNameEquals(ref stringsStream, namespaceOffset, nameSystem.Data))
                    {
                        continue;
                    }
                    uint extendsCodedToken = columnExtends.Size == 2 ? *(ushort *)(p + columnExtends.Offset) : *(uint *)(p + columnExtends.Offset);
                    if (!CodedToken.TypeDefOrRef.Decode(extendsCodedToken, out MDToken extends))
                    {
                        continue;
                    }
                    if (extends.Rid != 0)
                    {
                        continue;
                    }

                    corlibToken = new MDToken(Table.Module, 1);
                    return(true);
                }
            }

            corlibToken = default;
            return(false);
        }
Example #60
0
			public TypeRefInfo(TypeRef tr) {
				TypeRef = tr;
				OrigNamespace = tr.Namespace;
				OrigName = tr.Name;
			}