Пример #1
0
		public virtual void Process (LinkContext context)
		{
			AssemblyDefinition assembly;
			if (!context.TryGetLinkedAssembly ("mscorlib", out assembly))
				return;

			// skip this if we're not linking mscorlib, e.g. --linkskip=mscorlib
			if (context.Annotations.GetAction (assembly) != AssemblyAction.Link)
				return;

			var resources = assembly.MainModule.Resources;

			for (int i = 0; i < resources.Count; i++) {
				var resource = resources [i] as EmbeddedResource;
				if (resource == null)
					continue;

				switch (resource.Name) {
				case "collation.core.bin":
				case "collation.tailoring.bin":
					continue;
				default:
					if (!resource.Name.Contains ("cjk"))
						continue;
					if (IncludeCJK ())
						continue;

					resources.RemoveAt (i--);
					break;
				}
			}
		}
Пример #2
0
 static LinkContext GetDefaultContext(Pipeline pipeline)
 {
     LinkContext context = new LinkContext (pipeline);
     context.CoreAction = AssemblyAction.Skip;
     context.OutputDirectory = "output";
     return context;
 }
Пример #3
0
		public void Process (LinkContext context)
		{
			annotations = context.Annotations;

			ProcessCorlib (context);
			ProcessSystemCore (context);
		}
Пример #4
0
		public void Process (LinkContext context)
		{
			AssemblyDefinition assembly;
			if (!context.TryGetLinkedAssembly ("mscorlib", out assembly))
				return;

			var resources = assembly.MainModule.Resources;

			for (int i = 0; i < resources.Count; i++) {
				var resource = resources [i] as EmbeddedResource;
				if (resource == null)
					continue;

				switch (resource.Name) {
				case "collation.core.bin":
				case "collation.tailoring.bin":
					continue;
				default:
					if (!resource.Name.Contains ("cjk"))
						continue;
					if (IncludeCJK ())
						continue;

					resources.RemoveAt (i--);
					break;
				}
			}
		}
Пример #5
0
        public override void Process(LinkContext context)
        {
            PInvokeModules = (context as MonoMacLinkContext).PInvokeModules;
            base.Process (context);

            if (Exceptions.Count > 0)
                throw new AggregateException (Exceptions);
        }
Пример #6
0
        public void Process(LinkContext context)
        {
            this.context = context;

            PreserveDictionaryConstructor ();
            PreserveQueryableEnumerable ();
            PreserveResourceSet ();
        }
 public override void Initialize(LinkContext context)
 {
     base.Initialize (context);
     // is some user code depending (or not) on reflection to get method's parameters names ?
     // note: member references will still exists (even if not marked) until the assembly is saved
     // so we need this to be pre-computed at the marking stage
     ReflectedParameterNames = Annotations.GetCustomAnnotations ("ParameterInfo").Count > 0;
 }
Пример #8
0
		void ProcessSystemCore (LinkContext context)
		{
			AssemblyDefinition syscore;
			if (!context.TryGetLinkedAssembly ("System.Core", out syscore))
				return;

			// AddPreserveInfo (syscore, "Aes", "AesCryptoServiceProvider");
			TryAddPreserveInfo (syscore, "Aes", "AesManaged");
		}
Пример #9
0
        public override void Process(LinkContext context)
        {
            ProductAssembly = (Profile.Current as BaseProfile).ProductAssembly;

            base.Process (context);

            PreserveDictionaryConstructor ();
            PreserveQueryableEnumerable ();

            if (context.GetParameter ("debug-build") == "True")
                PreserveDebugFeatures ();
        }
Пример #10
0
		public void Process (LinkContext context)
		{
			AssemblyDefinition monomac;
			if (!context.TryGetLinkedAssembly ("MonoMac", out monomac))
				return;

			foreach (TypeDefinition type in monomac.MainModule.Types) {
				if (!type.IsNSObject ())
					continue;

				ProcessNSObject (type);
			}
		}
Пример #11
0
        public override void Process(LinkContext context)
        {
            Context = context;

            base.Process (context);

            // the resources are not part of the mobile profile (just the "classic" mono BCL)
            if (Profile.Current is MobileProfile)
                return;

            Process ("System", ProcessSystem);
            Process ("System.Drawing", ProcessSystemDrawing);
        }
Пример #12
0
        public static void Process(LinkerOptions options, out LinkContext context)
        {
            var pipeline = CreatePipeline (options);

            pipeline.PrependStep (new ResolveFromAssemblyStep (options.MainAssembly));
            if (options.RetainAssemblies != null)
                foreach (var assembly in options.RetainAssemblies)
                    pipeline.PrependStep (new ResolveFromAssemblyStep (assembly));

            context = CreateLinkContext (options, pipeline);
            context.Resolver.AddSearchDirectory (options.OutputDirectory);

            Run (pipeline, context);
        }
Пример #13
0
        public virtual void Process(LinkContext context)
        {
            Context = context;
            Corlib = context.GetAssembly ("mscorlib");

            if (I18n.HasFlag (I18nAssemblies.MidEast)) {
                PreserveCalendar ("UmAlQuraCalendar");
                PreserveCalendar ("HijriCalendar");
            }
            if (I18n.HasFlag (I18nAssemblies.Other))
                PreserveCalendar ("ThaiBuddhistCalendar");

            PreserveResourceSet ();
        }
Пример #14
0
 static LinkContext CreateLinkContext(LinkerOptions options, Pipeline pipeline)
 {
     var context = new LinkContext (pipeline, options.Resolver);
     if (options.DumpDependencies) {
         var prepareDependenciesDump = context.Annotations.GetType ().GetMethod ("PrepareDependenciesDump", new Type[] {});
         if (prepareDependenciesDump != null)
             prepareDependenciesDump.Invoke (context.Annotations, null);
     }
     context.LogInternalExceptions = Xamarin.Android.Tasks.MonoAndroidHelper.LogInternalExceptions;
     context.CoreAction = AssemblyAction.Link;
     context.LinkSymbols = true;
     context.SymbolReaderProvider = new MdbReaderProvider ();
     context.SymbolWriterProvider = new MdbWriterProvider ();
     context.OutputDirectory = options.OutputDirectory;
     return context;
 }
Пример #15
0
        public override void Process(LinkContext context)
        {
            DebugBuild = context.GetParameter ("debug-build") == "True";

            base.Process (context);

            if (list.Count > 0)
                throw new AggregateException (list);

            if (!serialization_required) {
            #if DEBUG
                Console.WriteLine ("{0} serialization constructors were removed because no SerializationInfo is created", pending_serialization_constructors.Count);
            #endif
                pending_serialization_constructors.Clear ();
            }
        }
Пример #16
0
        public void Process(LinkContext context)
        {
            var profile = (Profile.Current as BaseProfile);

            AssemblyDefinition assembly;
            if (!context.TryGetLinkedAssembly (profile.ProductAssembly, out assembly))
                return;

            // skip this if we're not linking monotouch, e.g. --linkskip=monotouch
            if (context.Annotations.GetAction (assembly) != AssemblyAction.Link)
                return;

            foreach (TypeDefinition type in assembly.MainModule.Types) {
                ProcessType (type);
            }
        }
Пример #17
0
		void ProcessCorlib (LinkContext context)
		{
			AssemblyDefinition corlib;
			if (!context.TryGetLinkedAssembly ("mscorlib", out corlib))
				return;

			AddPreserveInfo (corlib, "DES", "DESCryptoServiceProvider");
			AddPreserveInfo (corlib, "DSA", "DSACryptoServiceProvider");
			AddPreserveInfo (corlib, "RandomNumberGenerator", "RNGCryptoServiceProvider");
			AddPreserveInfo (corlib, "SHA1", "SHA1CryptoServiceProvider");
			AddPreserveInfo (corlib, "SHA1", "SHA1Managed");
			AddPreserveInfo (corlib, "MD5", "MD5CryptoServiceProvider");
			AddPreserveInfo (corlib, "RC2", "RC2CryptoServiceProvider");
			AddPreserveInfo (corlib, "TripleDES", "TripleDESCryptoServiceProvider");

			AddPreserveInfo (corlib, "Rijndael", "RijndaelManaged");
			AddPreserveInfo (corlib, "RIPEMD160", "RIPEMD160Managed");
			AddPreserveInfo (corlib, "SHA256", "SHA256Managed");
			AddPreserveInfo (corlib, "SHA384", "SHA384Managed");
			AddPreserveInfo (corlib, "SHA512", "SHA512Managed");

			AddPreserveInfo (corlib, "HMAC", "HMACMD5");
			AddPreserveInfo (corlib, "HMAC", "HMACRIPEMD160");
			AddPreserveInfo (corlib, "HMAC", "HMACSHA1");
			AddPreserveInfo (corlib, "HMAC", "HMACSHA256");
			AddPreserveInfo (corlib, "HMAC", "HMACSHA384");
			AddPreserveInfo (corlib, "HMAC", "HMACSHA512");

			AddPreserveInfo (corlib, "HMACMD5", "MD5CryptoServiceProvider");
			AddPreserveInfo (corlib, "HMACRIPEMD160", "RIPEMD160Managed");
			AddPreserveInfo (corlib, "HMACSHA1", "SHA1CryptoServiceProvider");
			AddPreserveInfo (corlib, "HMACSHA1", "SHA1Managed");
			AddPreserveInfo (corlib, "HMACSHA256", "SHA256Managed");
			AddPreserveInfo (corlib, "HMACSHA384", "SHA384Managed");
			AddPreserveInfo (corlib, "HMACSHA512", "SHA512Managed");

			TryAddPreserveInfo (corlib, "Aes", "AesManaged");

			var corlibAes = GetCryptoType (corlib, "Aes");
			Preserve (corlibAes, GetCryptoType (corlib, "AesManaged"));

			AssemblyDefinition syscore;
			if (context.TryGetLinkedAssembly ("System.Core", out syscore))
				Preserve (corlibAes, GetCryptoType (syscore, "AesCryptoServiceProvider"));
		}
Пример #18
0
        public override void Process(LinkContext context)
        {
            base.Process (context);

            // deal with [TypeForwardedTo] pseudo-attributes
            foreach (AssemblyDefinition assembly in _context.GetAssemblies ()) {
                if (!assembly.MainModule.HasExportedTypes)
                    continue;

                foreach (var exported in assembly.MainModule.ExportedTypes) {
                    if (!exported.IsForwarder)
                        continue;
                    var type = exported.Resolve ();
                    if (!Annotations.IsMarked (type))
                        continue;
                    Annotations.Mark (exported);
                }
            }
        }
        public override void Initialize(LinkContext context)
        {
            base.Initialize (context);

            // we cannot override ProcessAssembly as some decisions needs to be done before applyting the [Preserve]
            // synonyms

            foreach (var assembly in context.GetAssemblies ()) {
                if (!assembly.HasCustomAttributes)
                    continue;

                foreach (var attribute in assembly.CustomAttributes) {
                    if (!attribute.Constructor.DeclaringType.Is (Namespaces.Foundation, "PreserveAttribute"))
                        continue;

                    if (!attribute.HasConstructorArguments)
                        continue;
                    var tr = (attribute.ConstructorArguments [0].Value as TypeReference);
                    if (tr == null)
                        continue;

                    // we do not call `this.ProcessType` since
                    // (a) we're potentially processing a different assembly and `is_active` represent the current one
                    // (b) it will try to fetch the [Preserve] attribute on the type (and it's not there) as `base` would
                    var type = tr.Resolve ();
                    Annotations.Mark (type);
                    if (attribute.HasFields) {
                        foreach (var named_argument in attribute.Fields) {
                            if (named_argument.Name == "AllMembers" && (bool)named_argument.Argument.Value)
                                Annotations.SetPreserve (type, TypePreserve.All);
                        }
                    }

                    // if the type is a custom attribute then it means we want to preserve what's decorated
                    // with this attribute (not just the attribute alone)
                    if (type.Inherits ("System", "Attribute")) {
                        if (preserve_synonyms == null)
                            preserve_synonyms = new HashSet<TypeDefinition> ();
                        preserve_synonyms.Add (type);
                    }
                }
            }
        }
Пример #20
0
        public override void Process(LinkContext context)
        {
            ProductAssembly = (Profile.Current as BaseProfile).ProductAssembly;

            base.Process (context);

            // adjust IL inside generated Dispose methods (overriding NSObject)
            // to remove references to fields that were not marked
            TypeDefinition nsobject = GetType (ProductAssembly, Namespaces.Foundation + ".NSObject");

            if (nsobject != null) {
                foreach (MethodDefinition d in nsobject.Methods) {
                    if (d.Name == "Dispose" && d.HasParameters) {
                        ProcessDispose (d, d);
                        break;
                    }
                }
            }

            dispose_methods.Clear ();
        }
Пример #21
0
 public virtual AnnotationStore CreateAnnotationStore(LinkContext context) => new AnnotationStore(context);
Пример #22
0
 public override void Initialize(LinkContext context)
 {
     base.Initialize (context);
     debug_build = context.GetParameter ("debug-build") == "True";
 }
Пример #23
0
        public static void Process(LinkerOptions options, out LinkContext context, out List<string> assemblies)
        {
            switch (options.TargetFramework.Identifier) {
            case "Xamarin.Mac":
                Profile.Current = new MacMobileProfile (options.Architecture == "x86_64" ? 64 : 32);
                break;
            default:
                Profile.Current = new MonoMacProfile ();
                break;
            }
            Namespaces.Initialize ();

            var pipeline = CreatePipeline (options);

            pipeline.PrependStep (new ResolveFromAssemblyStep (options.MainAssembly));

            context = CreateLinkContext (options, pipeline);
            context.Resolver.AddSearchDirectory (options.OutputDirectory);

            try {
                pipeline.Process (context);
            } catch (AssemblyResolutionException fnfe) {
                throw new MonoMacException (2002, true, fnfe, fnfe.Message);
            } catch (AggregateException) {
                throw;
            } catch (MonoMacException) {
                throw;
            } catch (ResolutionException re) {
                TypeReference tr = (re.Member as TypeReference);
                IMetadataScope scope = tr == null ? re.Member.DeclaringType.Scope : tr.Scope;
                throw new MonoMacException (2002, true, re, "Failed to resolve \"{0}\" reference from \"{1}\"", re.Member, scope);
            } catch (Exception e) {
                throw new MonoMacException (2001, true, e, "Could not link assemblies. Reason: {0}", e.Message);
            }

            assemblies = ListAssemblies (context);
        }
		public override void Process (LinkContext context)
		{
			_context = context;
			XApiReader reader = new XApiReader (_document, this);
			reader.Process (context);
		}
Пример #25
0
        // Perform setup of the LinkContext and parse the arguments.
        // Return values:
        // 0 => successfully set up context with all arguments
        // 1 => argument processing stopped early without errors
        // -1 => error setting up context
        protected int SetupContext(ILogger customLogger = null)
        {
            Pipeline p = GetStandardPipeline();

            context = GetDefaultContext(p);

            if (customLogger != null)
            {
                context.Logger = customLogger;
            }

#if !FEATURE_ILLINK
            I18nAssemblies assemblies = I18nAssemblies.All;
#endif
            var    custom_steps         = new List <string> ();
            var    excluded_features    = new HashSet <string> (StringComparer.Ordinal);
            var    set_optimizations    = new List <(CodeOptimizations, string, bool)> ();
            bool   dumpDependencies     = false;
            string dependenciesFileName = null;
            bool   ignoreDescriptors    = false;
            bool   removeCAS            = true;
            bool   new_mvid_used        = false;
            bool   deterministic_used   = false;

            bool resolver = false;
            while (arguments.Count > 0)
            {
                string token = arguments.Dequeue();
                if (token.Length < 2)
                {
                    ErrorUnrecognizedOption(token);
                    return(-1);
                }

                //
                // Handling of --value like options
                //
                if (token [0] == '-' && token [1] == '-')
                {
                    switch (token)
                    {
                    case "--skip-unresolved":
                        if (!GetBoolParam(token, l => context.IgnoreUnresolved = context.Resolver.IgnoreUnresolved = l))
                        {
                            return(-1);
                        }

                        continue;

                    case "--verbose":
                        context.LogMessages = true;
                        continue;

                    case "--dependencies-file":
                        if (!GetStringParam(token, l => dependenciesFileName = l))
                        {
                            return(-1);
                        }

                        continue;

                    case "--dump-dependencies":
                        dumpDependencies = true;
                        continue;

                    case "--reduced-tracing":
                        if (!GetBoolParam(token, l => context.EnableReducedTracing = l))
                        {
                            return(-1);
                        }

                        continue;

                    case "--used-attrs-only":
                        if (!GetBoolParam(token, l => context.KeepUsedAttributeTypesOnly = l))
                        {
                            return(-1);
                        }

                        continue;

                    case "--strip-security":
                        if (!GetBoolParam(token, l => removeCAS = l))
                        {
                            return(-1);
                        }

                        continue;

                    case "--strip-resources":
                        if (!GetBoolParam(token, l => context.StripResources = l))
                        {
                            return(-1);
                        }

                        continue;

                    case "--substitutions":
                        if (arguments.Count < 1)
                        {
                            ErrorMissingArgument(token);
                            return(-1);
                        }

                        if (!GetStringParam(token, l => context.AddSubstitutionFile(l)))
                        {
                            return(-1);
                        }

                        continue;

                    case "--exclude-feature":
                        if (arguments.Count < 1)
                        {
                            ErrorMissingArgument(token);
                            return(-1);
                        }

                        if (!GetStringParam(token, l => {
                            foreach (var feature in l.Split(','))
                            {
                                if (!excluded_features.Contains(feature))
                                {
                                    excluded_features.Add(feature);
                                }
                            }
                        }))
                        {
                            return(-1);
                        }

                        continue;

                    case "--explicit-reflection":
                        if (!GetBoolParam(token, l => context.AddReflectionAnnotations = l))
                        {
                            return(-1);
                        }

                        continue;

                    case "--custom-step":
                        if (!GetStringParam(token, l => custom_steps.Add(l)))
                        {
                            return(-1);
                        }

                        continue;

                    case "--keep-facades":
                        if (!GetBoolParam(token, l => context.KeepTypeForwarderOnlyAssemblies = l))
                        {
                            return(-1);
                        }

                        continue;

                    case "--keep-dep-attributes":
                        if (!GetBoolParam(token, l => context.KeepDependencyAttributes = l))
                        {
                            return(-1);
                        }

                        continue;

                    case "--ignore-descriptors":
                        if (!GetBoolParam(token, l => ignoreDescriptors = l))
                        {
                            return(-1);
                        }

                        continue;

                    case "--disable-opt":
                        if (!GetStringParam(token, l => {
                            if (!GetOptimizationName(l, out var opt))
                            {
                                return;
                            }

                            string assemblyName = GetNextStringValue();
                            set_optimizations.Add((opt, assemblyName, false));
                        }))
                        {
                            return(-1);
                        }

                        continue;

                    case "--enable-opt":
                        if (!GetStringParam(token, l => {
                            if (!GetOptimizationName(l, out var opt))
                            {
                                return;
                            }

                            string assemblyName = GetNextStringValue();
                            set_optimizations.Add((opt, assemblyName, true));
                        }))
                        {
                            return(-1);
                        }

                        continue;

                    case "--new-mvid":
                        //
                        // This is not same as --deterministic which calculates MVID
                        // from stable assembly content. This option creates a new random
                        // mvid or uses mvid of the source assembly.
                        //
                        if (!GetBoolParam(token, l => {
                            if (!l)
                            {
                                p.RemoveStep(typeof(RegenerateGuidStep));
                            }
                        }))
                        {
                            return(-1);
                        }

                        new_mvid_used = true;
                        continue;

                    case "--deterministic":
                        if (!GetBoolParam(token, l => context.DeterministicOutput = l))
                        {
                            return(-1);
                        }

                        deterministic_used = true;
                        continue;

                    case "--output-assemblylist":
                        if (!GetStringParam(token, l => context.AssemblyListFile = l))
                        {
                            return(-1);
                        }

                        continue;

                    case "--output-pinvokes":
                        if (!GetStringParam(token, l => context.PInvokesListFile = l))
                        {
                            return(-1);
                        }

                        continue;

                    case "--version":
                        Version();
                        return(1);

                    case "--about":
                        About();
                        return(1);
                    }
                }

                if (token [0] == '-' || token [1] == '/')
                {
                    switch (token.Substring(1))
                    {
                    case "d":
                        if (!GetStringParam(token, l => {
                            DirectoryInfo info = new DirectoryInfo(l);
                            context.Resolver.AddSearchDirectory(info.FullName);
                        }))
                        {
                            return(-1);
                        }

                        continue;

                    case "o":
                    case "out":
                        if (!GetStringParam(token, l => context.OutputDirectory = l))
                        {
                            return(-1);
                        }

                        continue;

                    case "c":
                        if (!GetStringParam(token, l => context.CoreAction = ParseAssemblyAction(l)))
                        {
                            return(-1);
                        }

                        continue;

                    case "u":
                        if (!GetStringParam(token, l => context.UserAction = ParseAssemblyAction(l)))
                        {
                            return(-1);
                        }

                        continue;

                    case "p":
                        if (arguments.Count < 2)
                        {
                            ErrorMissingArgument(token);
                            return(-1);
                        }

                        AssemblyAction action = ParseAssemblyAction(arguments.Dequeue());
                        context.Actions [arguments.Dequeue()] = action;
                        continue;

                    case "t":
                        context.KeepTypeForwarderOnlyAssemblies = true;
                        continue;

                    case "x":
                        if (!GetStringParam(token, l => {
                            foreach (string file in GetFiles(l))
                            {
                                AddResolveFromXmlStep(p, file);
                            }
                        }))
                        {
                            return(-1);
                        }

                        resolver = true;
                        continue;

                    case "r":
                    case "a":
                        if (!GetStringParam(token, l => {
                            var rootVisibility = (token [1] == 'r')
                                                                ? ResolveFromAssemblyStep.RootVisibility.PublicAndFamily
                                                                : ResolveFromAssemblyStep.RootVisibility.Any;
                            foreach (string file in GetFiles(l))
                            {
                                p.PrependStep(new ResolveFromAssemblyStep(file, rootVisibility));
                            }
                        }))
                        {
                            return(-1);
                        }

                        resolver = true;
                        continue;

#if !FEATURE_ILLINK
                    case "i":
                        if (!GetStringParam(token, l => {
                            foreach (string file in GetFiles(l))
                            {
                                p.PrependStep(new ResolveFromXApiStep(new XPathDocument(file)));
                            }
                        }))
                        {
                            return(-1);
                        }

                        resolver = true;
                        continue;

                    case "l":
                        if (!GetStringParam(token, l => assemblies = ParseI18n(l)))
                        {
                            return(-1);
                        }

                        continue;
#endif
                    case "m":
                        if (arguments.Count < 2)
                        {
                            ErrorMissingArgument(token);
                            return(-1);
                        }

                        context.SetParameter(arguments.Dequeue(), arguments.Dequeue());
                        continue;

                    case "b":
                        if (!GetBoolParam(token, l => context.LinkSymbols = l))
                        {
                            return(-1);
                        }

                        continue;

                    case "g":
                        if (!GetBoolParam(token, l => context.DeterministicOutput = !l))
                        {
                            return(-1);
                        }

                        continue;

                    case "z":
                        if (!GetBoolParam(token, l => ignoreDescriptors = !l))
                        {
                            return(-1);
                        }

                        continue;

                    case "v":
                        if (!GetBoolParam(token, l => context.KeepMembersForDebugger = l))
                        {
                            return(-1);
                        }

                        continue;

                    case "?":
                    case "help":
                        Usage();
                        return(1);

                    case "reference":
                        if (!GetStringParam(token, l => context.Resolver.AddReferenceAssembly(l)))
                        {
                            return(-1);
                        }

                        continue;
                    }
                }

                ErrorUnrecognizedOption(token);
                return(-1);
            }

            if (!resolver)
            {
                Console.WriteLine($"No files to link were specified. Use one of '{resolvers}' options");
                return(-1);
            }

            if (new_mvid_used && deterministic_used)
            {
                Console.WriteLine($"Options '--new-mvid' and '--deterministic' cannot be used at the same time");
                return(-1);
            }

            if (dumpDependencies)
            {
                AddXmlDependencyRecorder(context, dependenciesFileName);
            }

            if (set_optimizations.Count > 0)
            {
                foreach (var(opt, assemblyName, enable) in set_optimizations)
                {
                    if (enable)
                    {
                        context.Optimizations.Enable(opt, assemblyName);
                    }
                    else
                    {
                        context.Optimizations.Disable(opt, assemblyName);
                    }
                }
            }

            //
            // Modify the default pipeline
            //
            if (ignoreDescriptors)
            {
                p.RemoveStep(typeof(BlacklistStep));
            }

            if (context.DeterministicOutput)
            {
                p.RemoveStep(typeof(RegenerateGuidStep));
            }

            if (context.AddReflectionAnnotations)
            {
                p.AddStepAfter(typeof(MarkStep), new ReflectionBlockedStep());
            }

#if !FEATURE_ILLINK
            p.AddStepAfter(typeof(LoadReferencesStep), new LoadI18nAssemblies(assemblies));

            if (assemblies != I18nAssemblies.None)
            {
                p.AddStepAfter(typeof(PreserveDependencyLookupStep), new PreserveCalendarsStep(assemblies));
            }
#endif

            if (_needAddBypassNGenStep)
            {
                p.AddStepAfter(typeof(SweepStep), new AddBypassNGenStep());
            }

            p.AddStepBefore(typeof(MarkStep), new BodySubstituterStep());

            if (removeCAS)
            {
                p.AddStepBefore(typeof(MarkStep), new RemoveSecurityStep());
            }

            if (excluded_features.Count > 0)
            {
                p.AddStepBefore(typeof(MarkStep), new RemoveFeaturesStep()
                {
                    FeatureCOM           = excluded_features.Contains("com"),
                    FeatureETW           = excluded_features.Contains("etw"),
                    FeatureSRE           = excluded_features.Contains("sre"),
                    FeatureGlobalization = excluded_features.Contains("globalization")
                });

                var excluded = new string [excluded_features.Count];
                excluded_features.CopyTo(excluded);
                context.ExcludedFeatures = excluded;
            }

            p.AddStepBefore(typeof(MarkStep), new RemoveUnreachableBlocksStep());
            p.AddStepBefore(typeof(OutputStep), new ClearInitLocalsStep());
            p.AddStepBefore(typeof(OutputStep), new SealerStep());

            //
            // Pipeline setup with all steps enabled
            //
            // LoadReferencesStep
            // BlacklistStep [optional]
            // PreserveDependencyLookupStep
            // TypeMapStep
            // BodySubstituterStep [optional]
            // RemoveSecurityStep [optional]
            // RemoveFeaturesStep [optional]
            // RemoveUnreachableBlocksStep [optional]
            // MarkStep
            // ReflectionBlockedStep [optional]
            // SweepStep
            // AddBypassNGenStep [optional]
            // CodeRewriterStep
            // CleanStep
            // RegenerateGuidStep [optional]
            // ClearInitLocalsStep
            // OutputStep
            //

            foreach (string custom_step in custom_steps)
            {
                if (!AddCustomStep(p, custom_step))
                {
                    return(-1);
                }
            }

            return(0);
        }
Пример #26
0
 protected virtual void ProcessStep(LinkContext context, IStep step)
 {
     step.Process(context);
 }
Пример #27
0
        public static IEnumerable <FieldDefinition> GetFieldsOnTypeHierarchy(this TypeDefinition thisType, LinkContext context, Func <FieldDefinition, bool>?filter, BindingFlags?bindingFlags = BindingFlags.Default)
        {
            TypeDefinition?type       = thisType;
            bool           onBaseType = false;

            while (type != null)
            {
                foreach (var field in type.Fields)
                {
                    // Ignore private fields on a base type - those are completely ignored by reflection
                    // (anything private on the base type is not visible via the derived type)
                    if (onBaseType && field.IsPrivate)
                    {
                        continue;
                    }

                    // Note that compiler generated fields backing some properties and events will get through here.
                    // This is intentional as reflection treats these as fields as well.

                    if (filter != null && !filter(field))
                    {
                        continue;
                    }

                    if ((bindingFlags & (BindingFlags.Instance | BindingFlags.Static)) == BindingFlags.Static && !field.IsStatic)
                    {
                        continue;
                    }

                    if ((bindingFlags & (BindingFlags.Instance | BindingFlags.Static)) == BindingFlags.Instance && field.IsStatic)
                    {
                        continue;
                    }

                    if ((bindingFlags & (BindingFlags.Public | BindingFlags.NonPublic)) == BindingFlags.Public && !field.IsPublic)
                    {
                        continue;
                    }

                    if ((bindingFlags & (BindingFlags.Public | BindingFlags.NonPublic)) == BindingFlags.NonPublic && field.IsPublic)
                    {
                        continue;
                    }

                    yield return(field);
                }

                if ((bindingFlags & BindingFlags.DeclaredOnly) == BindingFlags.DeclaredOnly)
                {
                    yield break;
                }

                type       = context.TryResolve(type.BaseType);
                onBaseType = true;
            }
        }
Пример #28
0
        public static IEnumerable <IMetadataTokenProvider> GetDynamicallyAccessedMembers(this TypeDefinition typeDefinition, LinkContext context, DynamicallyAccessedMemberTypes memberTypes, bool declaredOnly = false)
        {
            if (memberTypes == DynamicallyAccessedMemberTypes.None)
            {
                yield break;
            }

            if (memberTypes == DynamicallyAccessedMemberTypes.All)
            {
                var members = new List <IMetadataTokenProvider> ();
                typeDefinition.GetAllOnType(context, declaredOnly, members);
                foreach (var m in members)
                {
                    yield return(m);
                }
                yield break;
            }

            var declaredOnlyFlags = declaredOnly ? BindingFlags.DeclaredOnly : BindingFlags.Default;

            if (memberTypes.HasFlag(DynamicallyAccessedMemberTypes.NonPublicConstructors))
            {
                foreach (var c in typeDefinition.GetConstructorsOnType(filter: null, bindingFlags: BindingFlags.NonPublic))
                {
                    yield return(c);
                }
            }

            if (memberTypes.HasFlag(DynamicallyAccessedMemberTypes.PublicConstructors))
            {
                foreach (var c in typeDefinition.GetConstructorsOnType(filter: null, bindingFlags: BindingFlags.Public))
                {
                    yield return(c);
                }
            }

            if (memberTypes.HasFlag(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor))
            {
                foreach (var c in typeDefinition.GetConstructorsOnType(filter: m => m.IsPublic && m.Parameters.Count == 0))
                {
                    yield return(c);
                }
            }

            if (memberTypes.HasFlag(DynamicallyAccessedMemberTypes.NonPublicMethods))
            {
                foreach (var m in typeDefinition.GetMethodsOnTypeHierarchy(context, filter: null, bindingFlags: BindingFlags.NonPublic | declaredOnlyFlags))
                {
                    yield return(m);
                }
            }

            if (memberTypes.HasFlag(DynamicallyAccessedMemberTypes.PublicMethods))
            {
                foreach (var m in typeDefinition.GetMethodsOnTypeHierarchy(context, filter: null, bindingFlags: BindingFlags.Public | declaredOnlyFlags))
                {
                    yield return(m);
                }
            }

            if (memberTypes.HasFlag(DynamicallyAccessedMemberTypes.NonPublicFields))
            {
                foreach (var f in typeDefinition.GetFieldsOnTypeHierarchy(context, filter: null, bindingFlags: BindingFlags.NonPublic | declaredOnlyFlags))
                {
                    yield return(f);
                }
            }

            if (memberTypes.HasFlag(DynamicallyAccessedMemberTypes.PublicFields))
            {
                foreach (var f in typeDefinition.GetFieldsOnTypeHierarchy(context, filter: null, bindingFlags: BindingFlags.Public | declaredOnlyFlags))
                {
                    yield return(f);
                }
            }

            if (memberTypes.HasFlag(DynamicallyAccessedMemberTypes.NonPublicNestedTypes))
            {
                foreach (var nested in typeDefinition.GetNestedTypesOnType(filter: null, bindingFlags: BindingFlags.NonPublic))
                {
                    yield return(nested);

                    var members = new List <IMetadataTokenProvider> ();
                    nested.GetAllOnType(context, declaredOnly: false, members);
                    foreach (var m in members)
                    {
                        yield return(m);
                    }
                }
            }

            if (memberTypes.HasFlag(DynamicallyAccessedMemberTypes.PublicNestedTypes))
            {
                foreach (var nested in typeDefinition.GetNestedTypesOnType(filter: null, bindingFlags: BindingFlags.Public))
                {
                    yield return(nested);

                    var members = new List <IMetadataTokenProvider> ();
                    nested.GetAllOnType(context, declaredOnly: false, members);
                    foreach (var m in members)
                    {
                        yield return(m);
                    }
                }
            }

            if (memberTypes.HasFlag(DynamicallyAccessedMemberTypes.NonPublicProperties))
            {
                foreach (var p in typeDefinition.GetPropertiesOnTypeHierarchy(context, filter: null, bindingFlags: BindingFlags.NonPublic | declaredOnlyFlags))
                {
                    yield return(p);
                }
            }

            if (memberTypes.HasFlag(DynamicallyAccessedMemberTypes.PublicProperties))
            {
                foreach (var p in typeDefinition.GetPropertiesOnTypeHierarchy(context, filter: null, bindingFlags: BindingFlags.Public | declaredOnlyFlags))
                {
                    yield return(p);
                }
            }

            if (memberTypes.HasFlag(DynamicallyAccessedMemberTypes.NonPublicEvents))
            {
                foreach (var e in typeDefinition.GetEventsOnTypeHierarchy(context, filter: null, bindingFlags: BindingFlags.NonPublic | declaredOnlyFlags))
                {
                    yield return(e);
                }
            }

            if (memberTypes.HasFlag(DynamicallyAccessedMemberTypes.PublicEvents))
            {
                foreach (var e in typeDefinition.GetEventsOnTypeHierarchy(context, filter: null, bindingFlags: BindingFlags.Public | declaredOnlyFlags))
                {
                    yield return(e);
                }
            }

            if (memberTypes.HasFlag(DynamicallyAccessedMemberTypesOverlay.Interfaces))
            {
                foreach (var i in typeDefinition.GetAllInterfaceImplementations(context, declaredOnly))
                {
                    yield return(i);
                }
            }
        }
Пример #29
0
        public static IEnumerable <MethodDefinition> GetMethodsOnTypeHierarchy(this TypeDefinition thisType, LinkContext context, Func <MethodDefinition, bool>?filter, BindingFlags?bindingFlags = null)
        {
            TypeDefinition?type       = thisType;
            bool           onBaseType = false;

            while (type != null)
            {
                foreach (var method in type.Methods)
                {
                    // Ignore constructors as those are not considered methods from a reflection's point of view
                    if (method.IsConstructor)
                    {
                        continue;
                    }

                    // Ignore private methods on a base type - those are completely ignored by reflection
                    // (anything private on the base type is not visible via the derived type)
                    if (onBaseType && method.IsPrivate)
                    {
                        continue;
                    }

                    // Note that special methods like property getter/setter, event adder/remover will still get through and will be marked.
                    // This is intentional as reflection treats these as methods as well.

                    if (filter != null && !filter(method))
                    {
                        continue;
                    }

                    if ((bindingFlags & (BindingFlags.Instance | BindingFlags.Static)) == BindingFlags.Static && !method.IsStatic)
                    {
                        continue;
                    }

                    if ((bindingFlags & (BindingFlags.Instance | BindingFlags.Static)) == BindingFlags.Instance && method.IsStatic)
                    {
                        continue;
                    }

                    if ((bindingFlags & (BindingFlags.Public | BindingFlags.NonPublic)) == BindingFlags.Public && !method.IsPublic)
                    {
                        continue;
                    }

                    if ((bindingFlags & (BindingFlags.Public | BindingFlags.NonPublic)) == BindingFlags.NonPublic && method.IsPublic)
                    {
                        continue;
                    }

                    yield return(method);
                }

                if ((bindingFlags & BindingFlags.DeclaredOnly) == BindingFlags.DeclaredOnly)
                {
                    yield break;
                }

                type       = context.TryResolve(type.BaseType);
                onBaseType = true;
            }
        }
Пример #30
0
 public TypeHierarchyCache(LinkContext context)
 {
     this.context = context;
 }
 public UnconditionalSuppressMessageAttributeState(LinkContext context)
 {
     _context              = context;
     _suppressions         = new Dictionary <ICustomAttributeProvider, Dictionary <int, SuppressMessageInfo> > ();
     InitializedAssemblies = new HashSet <AssemblyDefinition> ();
 }
Пример #32
0
 public virtual Tracer CreateTracer(LinkContext context) => new Tracer(context);
Пример #33
0
 public virtual MarkingHelpers CreateMarkingHelpers(LinkContext context) => new MarkingHelpers(context);
Пример #34
0
 public AnnotationStore(LinkContext context) => this.context = context;
Пример #35
0
        /// <summary>
        /// Create a warning message.
        /// </summary>
        /// <param name="context">Context with the relevant warning suppression info.</param>
        /// <param name="text">Humanly readable message describing the warning</param>
        /// <param name="code">Unique warning ID. Please see https://github.com/mono/linker/blob/master/doc/error-codes.md
        /// for the list of warnings and possibly add a new one</param>
        /// /// <param name="origin">Type or member where the warning is coming from</param>
        /// <param name="subcategory">Optionally, further categorize this warning</param>
        /// <returns>New MessageContainer of 'Warning' category</returns>
        internal static MessageContainer CreateWarningMessage(LinkContext context, string text, int code, IMemberDefinition origin, string subcategory = MessageSubCategory.None)
        {
            MessageOrigin _origin = new MessageOrigin(origin);

            return(CreateWarningMessage(context, text, code, _origin, subcategory));
        }
Пример #36
0
        public static IEnumerable <EventDefinition> GetEventsOnTypeHierarchy(this TypeDefinition thisType, LinkContext context, Func <EventDefinition, bool>?filter, BindingFlags?bindingFlags = BindingFlags.Default)
        {
            TypeDefinition?type       = thisType;
            bool           onBaseType = false;

            while (type != null)
            {
                foreach (var @event in type.Events)
                {
                    // Ignore private properties on a base type - those are completely ignored by reflection
                    // (anything private on the base type is not visible via the derived type)
                    // Note that properties themselves are not actually private, their accessors are
                    if (onBaseType &&
                        (@event.AddMethod == null || @event.AddMethod.IsPrivate) &&
                        (@event.RemoveMethod == null || @event.RemoveMethod.IsPrivate))
                    {
                        continue;
                    }

                    if (filter != null && !filter(@event))
                    {
                        continue;
                    }

                    if ((bindingFlags & (BindingFlags.Instance | BindingFlags.Static)) == BindingFlags.Static)
                    {
                        if ((@event.AddMethod != null) && [email protected])
                        {
                            continue;
                        }
                        if ((@event.RemoveMethod != null) && [email protected])
                        {
                            continue;
                        }
                    }

                    if ((bindingFlags & (BindingFlags.Instance | BindingFlags.Static)) == BindingFlags.Instance)
                    {
                        if ((@event.AddMethod != null) && @event.AddMethod.IsStatic)
                        {
                            continue;
                        }
                        if ((@event.RemoveMethod != null) && @event.RemoveMethod.IsStatic)
                        {
                            continue;
                        }
                    }

                    if ((bindingFlags & (BindingFlags.Public | BindingFlags.NonPublic)) == BindingFlags.Public)
                    {
                        if ((@event.AddMethod == null || [email protected]) &&
                            (@event.RemoveMethod == null || [email protected]))
                        {
                            continue;
                        }
                    }

                    if ((bindingFlags & (BindingFlags.Public | BindingFlags.NonPublic)) == BindingFlags.NonPublic)
                    {
                        if ((@event.AddMethod != null) && @event.AddMethod.IsPublic)
                        {
                            continue;
                        }
                        if ((@event.RemoveMethod != null) && @event.RemoveMethod.IsPublic)
                        {
                            continue;
                        }
                    }

                    yield return(@event);
                }

                if ((bindingFlags & BindingFlags.DeclaredOnly) == BindingFlags.DeclaredOnly)
                {
                    yield break;
                }

                type       = context.TryResolve(type.BaseType);
                onBaseType = true;
            }
        }
Пример #37
0
		public void Process (LinkContext context)
		{
			while (_steps.Count > 0) {
				IStep step = (IStep) _steps [0];
				step.Process (context);
				_steps.Remove (step);
			}
		}
Пример #38
0
        public static IEnumerable <InterfaceImplementation> GetAllInterfaceImplementations(this TypeDefinition thisType, LinkContext context, bool declaredOnly)
        {
            TypeDefinition?type = thisType;

            while (type != null)
            {
                foreach (var i in type.Interfaces)
                {
                    yield return(i);

                    TypeDefinition?interfaceType = context.TryResolve(i.InterfaceType);
                    if (interfaceType != null)
                    {
                        // declaredOnly here doesn't matter since interfaces don't have base types
                        foreach (var innerInterface in interfaceType.GetAllInterfaceImplementations(context, declaredOnly: true))
                        {
                            yield return(innerInterface);
                        }
                    }
                }

                if (declaredOnly)
                {
                    yield break;
                }

                type = context.TryResolve(type.BaseType);
            }
        }
Пример #39
0
		public void Process (LinkContext context)
		{
			_context = context;
			ProcessAssemblies (_document.CreateNavigator ());
		}
Пример #40
0
 public static void GetAllOnType(this TypeDefinition type, LinkContext context, bool declaredOnly, List <IMetadataTokenProvider> members) => GetAllOnType(type, context, declaredOnly, members, new HashSet <TypeDefinition> ());
Пример #41
0
 public MarkingHelpers(LinkContext context)
 {
     _context = context;
 }
Пример #42
0
 public SerializationMarker(LinkContext context)
 {
     _context = context;
 }
Пример #43
0
        static DynamicDependency?GetDynamicDependency(LinkContext context, CustomAttribute ca)
        {
            var args = ca.ConstructorArguments;

            if (args.Count < 1 || args.Count > 3)
            {
                return(null);
            }

            // First argument is string or DynamicallyAccessedMemberTypes
            string?memberSignature = args[0].Value as string;

            if (args.Count == 1)
            {
                return(memberSignature == null ? null : new DynamicDependency(memberSignature));
            }
            DynamicallyAccessedMemberTypes?memberTypes = null;

            if (memberSignature == null)
            {
                var argType = args[0].Type;
                if (!argType.IsTypeOf <DynamicallyAccessedMemberTypes> ())
                {
                    return(null);
                }
                try {
                    memberTypes = (DynamicallyAccessedMemberTypes)args[0].Value;
                } catch (InvalidCastException) { }
                if (memberTypes == null)
                {
                    return(null);
                }
            }

            // Second argument is Type for ctors with two args, string for ctors with three args
            if (args.Count == 2)
            {
                if (!(args[1].Value is TypeReference type))
                {
                    return(null);
                }
                return(memberSignature == null ? new DynamicDependency(memberTypes !.Value, type) : new DynamicDependency(memberSignature, type));
            }
            Debug.Assert(args.Count == 3);
            if (!(args[1].Value is string typeName))
            {
                return(null);
            }

            // Third argument is assembly name
            if (!(args[2].Value is string assemblyName))
            {
                return(null);
            }

            var dynamicDependency = memberSignature == null ? new DynamicDependency(memberTypes !.Value, typeName, assemblyName) : new DynamicDependency(memberSignature, typeName, assemblyName);

            dynamicDependency.OriginalAttribute = ca;

            return(dynamicDependency);
        }
Пример #44
0
        static void Main(string[] args)
        {
            var mydir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory;
            var monoroot = mydir.Parent.Parent.Parent.Parent;

            var inputdir = Path.Combine(monoroot.FullName,"builds/monodistribution/lib/mono/unity");
            var outputdir = Path.Combine(monoroot.FullName, "tmp/unity_linkered");

            if (Directory.Exists(outputdir))
                Directory.Delete(outputdir, true);
            Directory.CreateDirectory(outputdir);

            var assemblies = new List<string>();
            var nonassemblies = new List<string>();
            var files = new List<string>();
            foreach(var file in Directory.GetFiles(inputdir))
            {
                var ext = Path.GetExtension(file);
                var filename = Path.GetFileName(file);
                files.Add(filename);
                if (ext == ".dll" || ext==".exe")
                    assemblies.Add(filename);
                else
                    nonassemblies.Add(filename);
            }

            Console.WriteLine("InputDir: "+inputdir);
            Console.WriteLine("OutputDir: "+outputdir);

            Pipeline p = new Pipeline();

            foreach(var file in assemblies)
            {
                var fullfile = Path.Combine(inputdir,file);
                IStep s = null;
                var action = GetAssemblyAction(file);
                if (action==AssemblyAction.Link)
                    s = new MarkPublicApiExceptStep(fullfile);
                else if (action == AssemblyAction.Copy)
                    s = new ResolveFromAssemblyStep(fullfile);
                if (s!=null) p.AppendStep(s);
            }
            p.AppendStep(new LoadReferencesStep());
            p.AppendStep(new BlacklistStep());
            p.AppendStep(new TypeMapStep());
            p.AppendStep(new MarkAllFieldsOfSerializableTypes());
            p.AppendStep(new MarkStep());
            p.AppendStep(new SweepStep());
            p.AppendStep(new CleanStep());
            p.AppendStep(new RegenerateGuidStep());
            p.AppendStep(new OutputStep());
            p.AppendStep(new OutputMarkBacktraceReportStep());
            p.AppendStep(new FailIfWeMissTypesThatWeShippedInAPreviousVersionStep());

            LinkContext context = new LinkContext(p);
            context.CoreAction = AssemblyAction.Link;
            context.OutputDirectory = outputdir;
            context.Resolver.AddSearchDirectory(inputdir);
            p.Process(context);

            foreach(var file in files.Where(f => GetAssemblyAction(f)==AssemblyAction.Copy))
            {
                var _from = Path.Combine(inputdir,file);
                var _to = Path.Combine(outputdir,file);
                File.Copy(_from,_to,true);
            }
            WriteDiffReport(inputdir,assemblies, outputdir);
        }
Пример #45
0
        static List<string> ListAssemblies(LinkContext context)
        {
            var list = new List<string> ();
            foreach (var assembly in context.GetAssemblies ()) {
                if (context.Annotations.GetAction (assembly) == AssemblyAction.Delete)
                    continue;

                list.Add (GetFullyQualifiedName (assembly));
            }

            return list;
        }
 public UnconditionalSuppressMessageAttributeState(LinkContext context)
 {
     _context           = context;
     _localSuppressions = new Dictionary <ICustomAttributeProvider, Dictionary <int, SuppressMessageInfo> > ();
 }
		public void Process (LinkContext context)
		{
			CustomizePipeline (context.Pipeline);
			ProcessAssemblies (context.GetAssemblies ());
		}
Пример #48
0
        public static TypeReference GetParameterType(this MethodReference method, int parameterIndex, LinkContext context)
        {
            if (method.DeclaringType is GenericInstanceType genericInstance)
            {
                return(TypeReferenceExtensions.InflateGenericType(genericInstance, method.Parameters[parameterIndex].ParameterType, context));
            }

            return(method.Parameters[parameterIndex].ParameterType);
        }
Пример #49
0
        public static IEnumerable <MethodReference> GetMethods(this TypeReference type, LinkContext context)
        {
            TypeDefinition typeDef = context.Resolve(type);

            if (typeDef?.HasMethods != true)
            {
                yield break;
            }

            if (type is GenericInstanceType genericInstanceType)
            {
                foreach (var methodDef in typeDef.Methods)
                {
                    yield return(MakeMethodReferenceForGenericInstanceType(genericInstanceType, methodDef));
                }
            }
            else
            {
                foreach (var method in typeDef.Methods)
                {
                    yield return(method);
                }
            }
        }
Пример #50
0
 public static IEnumerable <AssemblyDefinition> GetAssemblies(this LinkContext context)
 {
     return(LinkerConfiguration.GetInstance(context).Assemblies);
 }
Пример #51
0
 static void Run(Pipeline pipeline, LinkContext context)
 {
     pipeline.Process (context);
 }
Пример #52
0
        void Run()
        {
            Pipeline p = GetStandardPipeline();

            using (LinkContext context = GetDefaultContext(p)) {
                I18nAssemblies assemblies   = I18nAssemblies.All;
                var            custom_steps = new List <string> ();

                bool resolver = false;
                while (HaveMoreTokens())
                {
                    string token = GetParam();
                    if (token.Length < 2)
                    {
                        Usage("Option is too short");
                    }

                    if (!(token [0] == '-' || token [1] == '/'))
                    {
                        Usage("Expecting an option, got instead: " + token);
                    }

                    if (token [0] == '-' && token [1] == '-')
                    {
                        if (token.Length < 3)
                        {
                            Usage("Option is too short");
                        }

                        if (token == "--skip-unresolved")
                        {
                            context.IgnoreUnresolved = bool.Parse(GetParam());
                            continue;
                        }

                        if (token == "--dump-dependencies")
                        {
                            var prepareDependenciesDump = context.Annotations.GetType().GetMethod("PrepareDependenciesDump", new Type [] { });
                            if (prepareDependenciesDump != null)
                            {
                                prepareDependenciesDump.Invoke(context.Annotations, null);
                            }
                            continue;
                        }

                        switch (token [2])
                        {
                        case 'v':
                            Version();
                            break;

                        case 'a':
                            About();
                            break;

                        default:
                            Usage(null);
                            break;
                        }
                    }

                    switch (token [1])
                    {
                    case 'd': {
                        DirectoryInfo info = new DirectoryInfo(GetParam());
                        context.Resolver.AddSearchDirectory(info.FullName);
                        break;
                    }

                    case 'o':
                        context.OutputDirectory = GetParam();
                        break;

                    case 'c':
                        context.CoreAction = ParseAssemblyAction(GetParam());
                        break;

                    case 'u':
                        context.UserAction = ParseAssemblyAction(GetParam());
                        break;

                    case 'p':
                        AssemblyAction action = ParseAssemblyAction(GetParam());
                        context.Actions [GetParam()] = action;
                        break;

                    case 's':
                        custom_steps.Add(GetParam());
                        break;

                    case 't':
                        context.KeepTypeForwarderOnlyAssemblies = true;
                        break;

                    case 'x':
                        foreach (string file in GetFiles(GetParam()))
                        {
                            p.PrependStep(new ResolveFromXmlStep(new XPathDocument(file)));
                        }
                        resolver = true;
                        break;

                    case 'r':
                    case 'a':
                        var rootVisibility = (token [1] == 'r')
                                                        ? ResolveFromAssemblyStep.RootVisibility.PublicAndFamily
                                                        : ResolveFromAssemblyStep.RootVisibility.Any;
                        foreach (string file in GetFiles(GetParam()))
                        {
                            p.PrependStep(new ResolveFromAssemblyStep(file, rootVisibility));
                        }
                        resolver = true;
                        break;

                    case 'i':
                        foreach (string file in GetFiles(GetParam()))
                        {
                            p.PrependStep(new ResolveFromXApiStep(new XPathDocument(file)));
                        }
                        resolver = true;
                        break;

                    case 'l':
                        assemblies = ParseI18n(GetParam());
                        break;

                    case 'm':
                        context.SetParameter(GetParam(), GetParam());
                        break;

                    case 'b':
                        context.LinkSymbols = bool.Parse(GetParam());
                        break;

                    case 'g':
                        if (!bool.Parse(GetParam()))
                        {
                            p.RemoveStep(typeof(RegenerateGuidStep));
                        }
                        break;

                    case 'z':
                        if (!bool.Parse(GetParam()))
                        {
                            p.RemoveStep(typeof(BlacklistStep));
                        }
                        break;

                    case 'v':
                        context.KeepMembersForDebuggerAttributes = bool.Parse(GetParam());
                        break;

                    default:
                        Usage("Unknown option: `" + token [1] + "'");
                        break;
                    }
                }

                if (!resolver)
                {
                    Usage("No resolver was created (use -x, -a or -i)");
                }

                foreach (string custom_step in custom_steps)
                {
                    AddCustomStep(p, custom_step);
                }

                p.AddStepAfter(typeof(LoadReferencesStep), new LoadI18nAssemblies(assemblies));

                if (_needAddBypassNGenStep)
                {
                    p.AddStepAfter(typeof(SweepStep), new AddBypassNGenStep());
                }

                p.Process(context);
            }
        }
Пример #53
0
 public Tracer(LinkContext context) => this.context = context;
Пример #54
0
 public void Process(LinkContext context)
 {
     _context = context;
     ProcessAssemblies(_document.CreateNavigator());
 }
Пример #55
0
        /// <summary>
        /// Performs packing.
        /// </summary>
        public void Run()
        {
            // Steps
            // 1) Mono.Cecil: Determine assembly dependencies
            // 2) ILMerge: Merge exe into a single assembly
            // 3) Mono.Linker
            var includeMergeListRegex = new string[] { @"SharpDX\..*" };

            // Step 1 : Mono.Cecil: Determine assembly dependencies
            var assembly = AssemblyDefinition.ReadAssembly(MainAssembly);
            var corlib = (AssemblyNameReference)assembly.MainModule.TypeSystem.Corlib;
            bool isNet40 = corlib.Version.Major == 4;

            var paths = new List<string>();

            var fromDirectory = Path.GetDirectoryName(assembly.MainModule.FullyQualifiedName);

            // Load SharpDX assemblies
            AddAssemblies(assembly, paths, fromDirectory, includeMergeListRegex);

            // Load assemblies to link
            foreach (var assemblyToLinkName in AssembliesToLink)
            {
                var assemblyToLink = AssemblyDefinition.ReadAssembly(assemblyToLinkName);
                paths.Add(assemblyToLink.MainModule.FullyQualifiedName);
            }


            // Step 2: ILMerge: Merge exe into a single assembly
            var merge = new ILMerge();

            String[] files = paths.ToArray();

            if (!Directory.Exists(OutputDirectory))
                Directory.CreateDirectory(OutputDirectory);

            //Here we get the first file name (which was the .exe file) and use that
            // as the output
            String strOutputFile = System.IO.Path.GetFileName(files[0]);

            merge.OutputFile = OutputDirectory + "\\" + strOutputFile;
            merge.SetInputAssemblies(files);
            merge.DebugInfo = false;
            merge.CopyAttributes = true;
            merge.AllowMultipleAssemblyLevelAttributes = true;
            merge.XmlDocumentation = false;

            // Special case for v4 framework
            // See http://research.microsoft.com/en-us/people/mbarnett/ilmerge.aspx
            if (isNet40)
            {
                // Retrieve the install root path for the framework
                string installRoot = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\.NetFramework", false).GetValue("InstallRoot").ToString();
                var directorties = Directory.GetDirectories(installRoot, "v4.*");
                if (directorties.Length == 0)
                    UsageError(string.Format(System.Globalization.CultureInfo.InvariantCulture, "Cannot found any .Net 4.0 directory from [{0}] ", installRoot));
                merge.SetTargetPlatform("v4", directorties[0]);                
            }

            merge.Merge();

            // Step 3: Mono.Linker
            if (!NoLinker)
            {
                var pipeline = GetStandardPipeline();
                var context = new LinkContext(pipeline) {CoreAction = AssemblyAction.Skip, OutputDirectory = OutputDirectory};
                context.OutputDirectory = OutputDirectory;

                var mainAssemblyDirectory = new DirectoryInfo(Path.GetDirectoryName(Path.GetFullPath(MainAssembly)));
                context.Resolver.AddSearchDirectory(mainAssemblyDirectory.FullName);

                // Load assembly merged previously by ILMerge
                var mergedAssemblyDefinition = context.Resolve(merge.OutputFile);

                // Create Mono.Linker default pipeline
                pipeline = GetStandardPipeline();
                pipeline.PrependStep(new ResolveFromAssemblyStep(mergedAssemblyDefinition));

                // Add custom step for ComObject constructors
                pipeline.AddStepBefore(typeof (SweepStep), new ComObjectStep());

                pipeline.Process(context);
            }

            Console.WriteLine("Assembly successfully packed to [{0}]", merge.OutputFile);
        }
Пример #56
0
        public void Run(ILogger customLogger = null)
        {
            Pipeline p = GetStandardPipeline();

            using (LinkContext context = GetDefaultContext(p)) {
                if (customLogger != null)
                {
                    context.Logger = customLogger;
                }

                I18nAssemblies assemblies             = I18nAssemblies.All;
                var            custom_steps           = new List <string> ();
                var            excluded_features      = new HashSet <string> (StringComparer.Ordinal);
                var            disabled_optimizations = new HashSet <string> (StringComparer.Ordinal);
                var            enabled_optimizations  = new HashSet <string> (StringComparer.Ordinal);
                bool           dumpDependencies       = false;
                bool           ignoreDescriptors      = false;
                bool           removeCAS = true;

                bool resolver = false;
                while (HaveMoreTokens())
                {
                    string token = GetParam();
                    if (token.Length < 2)
                    {
                        Usage("Option is too short");
                    }

                    if (!(token [0] == '-' || token [1] == '/'))
                    {
                        Usage("Expecting an option, got instead: " + token);
                    }

                    if (token [0] == '-' && token [1] == '-')
                    {
                        if (token.Length < 3)
                        {
                            Usage("Option is too short");
                        }

                        switch (token)
                        {
                        case "--skip-unresolved":
                            bool ignoreUnresolved = bool.Parse(GetParam());
                            context.IgnoreUnresolved          = ignoreUnresolved;
                            context.Resolver.IgnoreUnresolved = ignoreUnresolved;
                            continue;

                        case "--verbose":
                            context.LogMessages = true;
                            continue;

                        case "--dependencies-file":
                            context.Tracer.DependenciesFileName = GetParam();
                            continue;

                        case "--dump-dependencies":
                            dumpDependencies = true;
                            continue;

                        case "--reduced-tracing":
                            context.EnableReducedTracing = bool.Parse(GetParam());
                            continue;

                        case "--used-attrs-only":
                            context.KeepUsedAttributeTypesOnly = bool.Parse(GetParam());
                            continue;

                        case "--strip-security":
                            removeCAS = bool.Parse(GetParam());
                            continue;

                        case "--strip-resources":
                            context.StripResources = bool.Parse(GetParam());
                            continue;

                        case "--substitutions":
                            context.AddSubstitutionFile(GetParam());
                            continue;

                        case "--exclude-feature":
                            var name = GetParam();
                            foreach (var feature in name.Split(','))
                            {
                                if (!excluded_features.Contains(feature))
                                {
                                    excluded_features.Add(feature);
                                }
                            }
                            continue;

                        case "--explicit-reflection":
                            context.AddReflectionAnnotations = true;
                            continue;

                        case "--custom-step":
                            custom_steps.Add(GetParam());
                            continue;

                        case "--keep-facades":
                            context.KeepTypeForwarderOnlyAssemblies = bool.Parse(GetParam());
                            continue;

                        case "--keep-dep-attributes":
                            context.KeepDependencyAttributes = bool.Parse(GetParam());
                            continue;

                        case "--ignore-descriptors":
                            ignoreDescriptors = bool.Parse(GetParam());
                            continue;

                        case "--disable-opt":
                            var opt = GetParam().ToLower();
                            if (!disabled_optimizations.Contains(opt))
                            {
                                disabled_optimizations.Add(opt);
                            }

                            continue;

                        case "--enable-opt":
                            opt = GetParam().ToLower();
                            if (!enabled_optimizations.Contains(opt))
                            {
                                enabled_optimizations.Add(opt);
                            }

                            continue;

                        case "--new-mvid":
                            if (!bool.Parse(GetParam()))
                            {
                                p.RemoveStep(typeof(RegenerateGuidStep));
                            }
                            continue;

                        case "--deterministic":
                            context.DeterministicOutput = true;
                            p.RemoveStep(typeof(RegenerateGuidStep));
                            continue;

                        case "--output-assemblylist":
                            context.AssemblyListFile = GetParam();
                            continue;
                        }

                        switch (token [2])
                        {
                        case 'v':
                            Version();
                            break;

                        case 'a':
                            About();
                            break;

                        default:
                            Usage(null);
                            break;
                        }
                    }

                    // Ensure this does not conflict with '-r' below.
                    if (token == "-reference")
                    {
                        context.Resolver.AddReferenceAssembly(GetParam());
                        continue;
                    }

                    switch (token [1])
                    {
                    case 'd':
                        DirectoryInfo info = new DirectoryInfo(GetParam());
                        context.Resolver.AddSearchDirectory(info.FullName);
                        break;

                    case 'o':
                        context.OutputDirectory = GetParam();
                        break;

                    case 'c':
                        context.CoreAction = ParseAssemblyAction(GetParam());
                        break;

                    case 'u':
                        context.UserAction = ParseAssemblyAction(GetParam());
                        break;

                    case 'p':
                        AssemblyAction action = ParseAssemblyAction(GetParam());
                        context.Actions [GetParam()] = action;
                        break;

                    case 't':
                        context.KeepTypeForwarderOnlyAssemblies = true;
                        break;

                    case 'x':
                        foreach (string file in GetFiles(GetParam()))
                        {
                            p.PrependStep(new ResolveFromXmlStep(new XPathDocument(file)));
                        }
                        resolver = true;
                        break;

                    case 'r':
                    case 'a':
                        var rootVisibility = (token [1] == 'r')
                                                        ? ResolveFromAssemblyStep.RootVisibility.PublicAndFamily
                                                        : ResolveFromAssemblyStep.RootVisibility.Any;
                        foreach (string file in GetFiles(GetParam()))
                        {
                            p.PrependStep(new ResolveFromAssemblyStep(file, rootVisibility));
                        }
                        resolver = true;
                        break;

                    case 'i':
                        foreach (string file in GetFiles(GetParam()))
                        {
                            p.PrependStep(new ResolveFromXApiStep(new XPathDocument(file)));
                        }
                        resolver = true;
                        break;

                    case 'l':
                        assemblies = ParseI18n(GetParam());
                        break;

                    case 'm':
                        context.SetParameter(GetParam(), GetParam());
                        break;

                    case 'b':
                        context.LinkSymbols = bool.Parse(GetParam());
                        break;

                    case 'g':
                        if (!bool.Parse(GetParam()))
                        {
                            p.RemoveStep(typeof(RegenerateGuidStep));
                        }
                        break;

                    case 'z':
                        ignoreDescriptors = !bool.Parse(GetParam());
                        break;

                    case 'v':
                        context.KeepMembersForDebugger = bool.Parse(GetParam());
                        break;

                    default:
                        Usage("Unknown option: `" + token [1] + "'");
                        break;
                    }
                }

                if (!resolver)
                {
                    Usage("No resolver was created (use -x, -a or -i)");
                }

                if (ignoreDescriptors)
                {
                    p.RemoveStep(typeof(BlacklistStep));
                }

                if (dumpDependencies)
                {
                    context.Tracer.Start();
                }

                foreach (string custom_step in custom_steps)
                {
                    AddCustomStep(p, custom_step);
                }

                if (context.AddReflectionAnnotations)
                {
                    p.AddStepAfter(typeof(MarkStep), new ReflectionBlockedStep());
                }

                p.AddStepAfter(typeof(LoadReferencesStep), new LoadI18nAssemblies(assemblies));

                if (_needAddBypassNGenStep)
                {
                    p.AddStepAfter(typeof(SweepStep), new AddBypassNGenStep());
                }

                if (assemblies != I18nAssemblies.None)
                {
                    p.AddStepAfter(typeof(PreserveDependencyLookupStep), new PreserveCalendarsStep(assemblies));
                }

                p.AddStepBefore(typeof(MarkStep), new BodySubstituterStep());

                if (removeCAS)
                {
                    p.AddStepBefore(typeof(MarkStep), new RemoveSecurityStep());
                }

                if (excluded_features.Count > 0)
                {
                    p.AddStepBefore(typeof(MarkStep), new RemoveFeaturesStep()
                    {
                        FeatureCOM           = excluded_features.Contains("com"),
                        FeatureETW           = excluded_features.Contains("etw"),
                        FeatureSRE           = excluded_features.Contains("sre"),
                        FeatureGlobalization = excluded_features.Contains("globalization")
                    });

                    var excluded = new string [excluded_features.Count];
                    excluded_features.CopyTo(excluded);
                    context.ExcludedFeatures = excluded;
                }

                p.AddStepBefore(typeof(MarkStep), new RemoveUnreachableBlocksStep());

                if (disabled_optimizations.Count > 0)
                {
                    foreach (var item in disabled_optimizations)
                    {
                        switch (item)
                        {
                        case "beforefieldinit":
                            context.DisabledOptimizations |= CodeOptimizations.BeforeFieldInit;
                            break;

                        case "overrideremoval":
                            context.DisabledOptimizations |= CodeOptimizations.OverrideRemoval;
                            break;

                        case "unreachablebodies":
                            context.DisabledOptimizations |= CodeOptimizations.UnreachableBodies;
                            break;

                        case "unusedinterfaces":
                            context.DisabledOptimizations |= CodeOptimizations.UnusedInterfaces;
                            break;
                        }
                    }
                }

                if (enabled_optimizations.Count > 0)
                {
                    foreach (var item in enabled_optimizations)
                    {
                        switch (item)
                        {
                        case "unreachablebodies":
                            context.DisabledOptimizations &= ~CodeOptimizations.UnreachableBodies;
                            break;

                        case "clearinitlocals":
                            context.DisabledOptimizations &= ~CodeOptimizations.ClearInitLocals;
                            break;
                        }
                    }
                }

                if (context.IsOptimizationEnabled(CodeOptimizations.ClearInitLocals))
                {
                    p.AddStepBefore(typeof(OutputStep), new ClearInitLocalsStep());
                }

                PreProcessPipeline(p);

                try {
                    p.Process(context);
                }
                finally {
                    if (dumpDependencies)
                    {
                        context.Tracer.Finish();
                    }
                }
            }
        }
Пример #57
0
 public static void LogMessage(this LinkContext context, string messsage)
 {
     throw new NotImplementedException();
 }
Пример #58
0
 static DescriptorMarker GetExternalResolveStep(LinkContext context, EmbeddedResource resource, AssemblyDefinition assembly)
 {
     return(new DescriptorMarker(context, resource.GetResourceStream(), resource, assembly, "resource " + resource.Name + " in " + assembly.FullName));
 }
Пример #59
0
        static void GetAllOnType(TypeDefinition type, LinkContext context, bool declaredOnly, List <IMetadataTokenProvider> members, HashSet <TypeDefinition> types)
        {
            if (!types.Add(type))
            {
                return;
            }

            if (type.HasNestedTypes)
            {
                foreach (var nested in type.NestedTypes)
                {
                    members.Add(nested);
                    // Base types and interfaces of nested types are always included.
                    GetAllOnType(nested, context, declaredOnly: false, members, types);
                }
            }

            if (!declaredOnly)
            {
                var baseType = context.TryResolve(type.BaseType);
                if (baseType != null)
                {
                    GetAllOnType(baseType, context, declaredOnly: false, members, types);
                }
            }

            if (type.HasInterfaces)
            {
                if (declaredOnly)
                {
                    foreach (var iface in type.GetAllInterfaceImplementations(context, declaredOnly: true))
                    {
                        members.Add(iface);
                    }
                }
                else
                {
                    foreach (var iface in type.Interfaces)
                    {
                        members.Add(iface);
                        var interfaceType = context.TryResolve(iface.InterfaceType);
                        if (interfaceType == null)
                        {
                            continue;
                        }
                        GetAllOnType(interfaceType, context, declaredOnly: false, members, types);
                    }
                }
            }

            if (type.HasFields)
            {
                foreach (var f in type.Fields)
                {
                    members.Add(f);
                }
            }

            if (type.HasMethods)
            {
                foreach (var m in type.Methods)
                {
                    members.Add(m);
                }
            }

            if (type.HasProperties)
            {
                foreach (var p in type.Properties)
                {
                    members.Add(p);
                }
            }

            if (type.HasEvents)
            {
                foreach (var e in type.Events)
                {
                    members.Add(e);
                }
            }
        }
Пример #60
0
 protected virtual void AddXmlDependencyRecorder(LinkContext context, string fileName)
 {
     context.Tracer.AddRecorder(new XmlDependencyRecorder(context, fileName));
 }