public RoundTripTests() {
        // we assume peverify.exe is in the path
        host = new HostEnvironment();

       // Debug.Listeners.Clear();
       // Debug.Listeners.Add(new MyTraceListener());
    }
 public UninstallHost(HostEnvironment environment, HostSettings settings, IEnumerable<Action> preActions,
     IEnumerable<Action> postActions,
     bool sudo)
 {
     _environment = environment;
     _settings = settings;
     _preActions = preActions;
     _postActions = postActions;
     _sudo = sudo;
 }
        public ConsoleRunHost(HostSettings settings, HostEnvironment environment, ServiceHandle serviceHandle)
        {
            if (settings == null)
                throw new ArgumentNullException("settings");
            if (environment == null)
                throw new ArgumentNullException("environment");

            _settings = settings;
            _environment = environment;
            _serviceHandle = serviceHandle;
        }
        public WindowsServiceHost(HostEnvironment environment, HostSettings settings, ServiceHandle serviceHandle)
        {
            if (settings == null)
                throw new ArgumentNullException("settings");
            if (serviceHandle == null)
                throw new ArgumentNullException("serviceHandle");

            _settings = settings;
            _serviceHandle = serviceHandle;
            _environment = environment;
        }
        public InstallHost(HostEnvironment environment, HostSettings settings, HostStartMode startMode,
            IEnumerable<string> dependencies,
            Credentials credentials, IEnumerable<Action> preActions, IEnumerable<Action> postActions, bool sudo)
        {
            _environment = environment;
            _settings = settings;

            _installSettings = new InstallServiceSettingsImpl(settings, credentials, startMode, dependencies.ToArray());

            _preActions = preActions;
            _postActions = postActions;
            _sudo = sudo;
        }
        public WindowsServiceHost(HostEnvironment environment, HostSettings settings, ServiceHandle serviceHandle)
        {
            if (settings == null)
                throw new ArgumentNullException("settings");
            if (serviceHandle == null)
                throw new ArgumentNullException("serviceHandle");

            _settings = settings;
            _serviceHandle = serviceHandle;
            _environment = environment;

            CanPauseAndContinue = settings.CanPauseAndContinue;
            CanShutdown = settings.CanShutdown;
        }
Exemple #7
0
        private static int Main(string[] args)
        {
            ParseCommandLine(args);
            HostEnvironment host = new HostEnvironment();
            host.UnableToResolve += host_UnableToResolve;

            host.UnifyToLibPath = true;
            if (!string.IsNullOrWhiteSpace(s_libPath))
                host.AddLibPaths(HostEnvironment.SplitPaths(s_libPath));

            IEnumerable<IAssembly> assemblies = host.LoadAssemblies(HostEnvironment.SplitPaths(s_assembly));

            if (!assemblies.Any())
            {
                Console.WriteLine("ERROR: Failed to load any assemblies from '{0}'", s_assembly);
                return 1;
            }

            string headerText = GetHeaderText();
            bool loopPerAssembly = Directory.Exists(s_out);

            if (loopPerAssembly)
            {
                foreach (var assembly in assemblies)
                {
                    using (TextWriter output = GetOutput(GetFilename(assembly)))
                    using (IStyleSyntaxWriter syntaxWriter = GetSyntaxWriter(output))
                    {
                        if (headerText != null)
                            output.Write(headerText);
                        ICciWriter writer = GetWriter(output, syntaxWriter);
                        writer.WriteAssemblies(new IAssembly[] { assembly });
                    }
                }
            }
            else
            { 
                using (TextWriter output = GetOutput())
                using (IStyleSyntaxWriter syntaxWriter = GetSyntaxWriter(output))
                {
                    if (headerText != null)
                        output.Write(headerText);
                    ICciWriter writer = GetWriter(output, syntaxWriter);
                    writer.WriteAssemblies(assemblies);
                }
            }

            return 0;
        }
Exemple #8
0
        public ConsoleRunHost(HostSettings settings, HostEnvironment environment, ServiceHandle serviceHandle)
        {
            if (settings == null)
                throw new ArgumentNullException("settings");
            if (environment == null)
                throw new ArgumentNullException("environment");

            _settings = settings;
            _environment = environment;
            _serviceHandle = serviceHandle;

            if (settings.CanSessionChanged)
            {
                SystemEvents.SessionSwitch += OnSessionChanged;
            }
        }
        public WindowsServiceHost(HostEnvironment environment, HostSettings settings, ServiceHandle serviceHandle, HostConfigurator configurator)
        {
            if (settings == null)
                throw new ArgumentNullException("settings");
            if (serviceHandle == null)
                throw new ArgumentNullException("serviceHandle");

            _settings = settings;
            _serviceHandle = serviceHandle;
            _environment = environment;
            _configurator = configurator;

            CanPauseAndContinue = settings.CanPauseAndContinue;
            CanShutdown = settings.CanShutdown;
            CanHandleSessionChangeEvent = settings.CanSessionChanged;
            ServiceName = _settings.ServiceName;
        }
        public override IEnumerable<ISourceMappedItem> GetSourceInfo(string assemblyPath, string pdbPath, ReportingResult report)
        {
            using (var host = new HostEnvironment())
            using (var pdbFs = File.OpenRead(pdbPath))
            using (var pdbReader = new PdbReader(pdbFs, host))
            {
                var metadataVisitor = new CciMetadataTraverser(report, pdbReader);
                var traverser = new MetadataTraverser
                {
                    PreorderVisitor = metadataVisitor,
                    TraverseIntoMethodBodies = true
                };

                var cciAssembly = host.LoadAssembly(assemblyPath);
                traverser.Traverse(cciAssembly);

                return metadataVisitor.FoundItems;
            }
        }
Exemple #11
0
        private static int Main(string[] args)
        {
            ParseCommandLine(args);
            HostEnvironment host = new HostEnvironment();
            host.UnableToResolve += host_UnableToResolve;

            host.UnifyToLibPath = true;
            if (!string.IsNullOrWhiteSpace(s_libPath))
                host.AddLibPaths(HostEnvironment.SplitPaths(s_libPath));

            IEnumerable<IAssembly> assemblies = host.LoadAssemblies(HostEnvironment.SplitPaths(s_assembly));

            if (!assemblies.Any())
            {
                Console.WriteLine("ERROR: Failed to load any assemblies from '{0}'", s_assembly);
                return 1;
            }

            using (TextWriter output = GetOutput())
            using (IStyleSyntaxWriter syntaxWriter = GetSyntaxWriter(output))
            {
                if (!String.IsNullOrEmpty(s_headerFile))
                {
                    if (!File.Exists(s_headerFile))
                    {
                        Console.WriteLine("ERROR: header file '{0}' does not exist", s_headerFile);
                        return 1;
                    }

                    using (TextReader headerText = File.OpenText(s_headerFile))
                    {
                        output.Write(headerText.ReadToEnd());
                    }
                }

                ICciWriter writer = GetWriter(output, syntaxWriter);
                writer.WriteAssemblies(assemblies);
            }

            return 0;
        }
        private HostEnvironment CreateHostEnvironment(NameTable nameTable, NuGetFramework framework)
        {
            void UnableToResolve(object sender, UnresolvedReference <IUnit, AssemblyIdentity> e)
            {
                Trace.TraceError("Unable to resolve assembly '{0}' referenced by the implementation assembly '{1}'.", e.Unresolved, e.Referrer);
            }

            var host = new HostEnvironment(nameTable)
            {
                ResolveAgainstRunningFramework = true,
                UnifyToLibPath     = s_unifyToLibPaths,
                LoadErrorTreatment = ErrorTreatment.TreatAsWarning
            };

            host.UnableToResolve += new EventHandler <UnresolvedReference <IUnit, AssemblyIdentity> >(UnableToResolve);

            foreach (var path in _referenceAssemblyProvider.GetReferenceAssemblyPath(framework.HasProfile ? framework.Profile : framework.GetShortFolderName()))
            {
                host.AddLibPath(path);
            }

            return(host);
        }
Exemple #13
0
        private static void Main(string[] args)
        {
            var host     = new HostEnvironment();
            var services = new ServiceCollection();

            services.AddSingleton <IWebHostEnvironment, HostEnvironment>();
            services.AddSingleton <ILoggerFactory, LoggerFactory>();

            var diagnosticSource = new DiagnosticListener("Microsoft.AspNetCore");

            services.AddSingleton <DiagnosticSource>(diagnosticSource);

            var startup = new Startup(host);

            startup.ConfigureServices(services);

            var serviceProvider = services.BuildServiceProvider();
            var service         = serviceProvider.GetService <ITemplateService>();

            var result = service.Welcome("Hello World!");

            Console.WriteLine(result);
        }
        public Host CreateHost()
        {
            Type type = typeof(HostFactory);

            HostLogger.Get <HostConfiguratorImpl>()
            .InfoFormat("{0} v{1}, .NET Framework v{2}", type.Namespace, type.Assembly.GetName().Version,
                        Environment.Version);

            EnvironmentBuilder environmentBuilder = _environmentBuilderFactory();

            HostEnvironment environment = environmentBuilder.Build();

            ServiceBuilder serviceBuilder = _serviceBuilderFactory(_settings);

            HostBuilder builder = _hostBuilderFactory(environment, _settings);

            foreach (HostBuilderConfigurator configurator in _configurators)
            {
                builder = configurator.Configure(builder);
            }

            return(builder.Build(serviceBuilder));
        }
        public void CreateHostBuilder_ObserveEnvironmentLayering()
        {
            var reloadFlagConfig = new Dictionary <string, string>()
            {
                { "hostbuilder:reloadConfigOnChange", "false" }
            };
            var guid               = Guid.NewGuid().ToString();
            var ppeEnvName         = $"PPE{guid}";
            var devEnvName         = $"Development{guid}";
            var ppeFileName        = $"appsettings.{ppeEnvName}.json";
            var devFileName        = $"appsettings.{devEnvName}.json";
            var tempPath           = Path.GetTempPath();
            var appSettingsPPEPath = Path.Combine(tempPath, ppeFileName);
            var appSettingsDEVPath = Path.Combine(tempPath, devFileName);

            var ppeEnv = new HostEnvironment(ppeEnvName);
            var devEnv = new HostEnvironment(devEnvName, ppeEnv);

            SaveConfig(appSettingsPPEPath, ppeEnvName);
            SaveConfig(appSettingsDEVPath, devEnvName);

            // PPE setting is used
            var builder = LayeredSettingsHost.CreateHostBuilder(null, new[] { ppeEnv, devEnv })
                          .UseContentRoot(tempPath)
                          .UseEnvironment(ppeEnvName);
            var config = builder.Build().Services.GetRequiredService <IConfiguration>();

            Assert.Equal(ppeEnvName, config["FileName"]);

            // Dev setting is used and it overrides PPE
            builder = LayeredSettingsHost.CreateHostBuilder(null, new[] { ppeEnv, devEnv })
                      .UseContentRoot(tempPath)
                      .UseEnvironment(devEnvName);
            config = builder.Build().Services.GetRequiredService <IConfiguration>();
            Assert.Equal(devEnvName, config["FileName"]);
        }
        public void BaseTest(Dictionary <string, string> envDictionary, ConfigFileDeclaration[] expected)
        {
            var oldEnv = new Dictionary <string, string>();

            foreach (var e in envDictionary)
            {
                oldEnv[e.Key] = Environment.GetEnvironmentVariable(e.Key);
                Environment.SetEnvironmentVariable(e.Key, e.Value);
            }

            try
            {
                var config = new HostEnvironment(
                    new TestHostEnvironmentSource(),
                    new EnvironmentVarialbesConfigurationSource(),
                    new ApplicationInfoSource(
                        new CurrentApplicationInfo("test", Environment.UserName, Dns.GetHostName())));

                var configs = new ConfigurationLocationsParser(_fileSystem, config, config.ApplicationInfo);
                configs.ConfigFileDeclarations.Count.ShouldBe(expected.Length);

                foreach (var pair in configs.ConfigFileDeclarations.Zip(expected, (first, second) => new { first, second }))
                {
                    pair.first.Pattern.ShouldBe(pair.second.Pattern);
                    pair.first.Priority.ShouldBe(pair.second.Priority);
                }
            }

            finally
            {
                foreach (var e in oldEnv)
                {
                    Environment.SetEnvironmentVariable(e.Key, e.Value);
                }
            }
        }
Exemple #17
0
        private static IEnumerable<IAssembly> LoadAssemblies(HostEnvironment host, string assemblyPaths)
        {
            host.UnifyToLibPath = true;
            string[] splitPaths = HostEnvironment.SplitPaths(assemblyPaths);

            foreach (string path in splitPaths)
            {
                if (Directory.Exists(path))
                {
                    host.AddLibPath(Path.GetFullPath(path));
                }
                else if (File.Exists(path))
                {
                    host.AddLibPath(Path.GetDirectoryName(Path.GetFullPath(path)));
                }
            }

            return host.LoadAssemblies(splitPaths);
        }
Exemple #18
0
 private static void OutputFacadeToFile(string facadePath, HostEnvironment seedHost, Assembly facade, IAssembly contract, string pdbLocation = null)
 {
     // Use the filename (including extension .dll/.winmd) so people can have some control over the output facade file name.
     string facadeFileName = Path.GetFileName(contract.Location);
     string facadeOutputPath = Path.Combine(facadePath, facadeFileName);
     using (Stream peOutStream = File.Create(facadeOutputPath))
     {
         if (pdbLocation != null)
         {
             if (File.Exists(pdbLocation))
             {
                 string pdbOutputPath = Path.Combine(facadePath, contract.Name + ".pdb");
                 using (Stream pdbReadStream = File.OpenRead(pdbLocation))
                 using (PdbReader pdbReader = new PdbReader(pdbReadStream, seedHost))
                 using (PdbWriter pdbWriter = new PdbWriter(pdbOutputPath, pdbReader))
                 {
                     PeWriter.WritePeToStream(facade, seedHost, peOutStream, pdbReader, pdbReader, pdbWriter);
                 }
             }
             else
             {
                 throw new FacadeGenerationException("Couldn't find the pdb at the given location: " + pdbLocation);
             }
         }
         else
         {
             PeWriter.WritePeToStream(facade, seedHost, peOutStream);
         }
     }
 }
 static HostBuilder DefaultHostBuilderFactory(HostEnvironment environment, HostSettings settings)
 {
     return new RunBuilder(environment, settings);
 }
Exemple #20
0
 static HostBuilder DefaultHostBuilderFactory(HostEnvironment environment, HostSettings settings)
 {
     return(new RunBuilder(environment, settings));
 }
        public static int Main(string[] args)
        {
            ParseCommandLine(args);
            CommandLineTraceHandler.Enable();

            if (s_listRules)
            {
                CompositionHost c = GetCompositionHost();
                ExportCciSettings.StaticSettings = CciComparers.Default.GetEqualityComparer <ITypeReference>();

                var rules = c.GetExports <IDifferenceRule>();

                foreach (var rule in rules.Select(r => r.GetType().Name).OrderBy(r => r, StringComparer.OrdinalIgnoreCase))
                {
                    Console.WriteLine(rule);
                }

                return(0);
            }

            using (TextWriter output = GetOutput())
            {
                if (DifferenceWriter.ExitCode != 0)
                {
                    return(0);
                }

                if (output != Console.Out)
                {
                    Trace.Listeners.Add(new TextWriterTraceListener(output)
                    {
                        Filter = new EventTypeFilter(SourceLevels.Error | SourceLevels.Warning)
                    });
                }
                try
                {
                    BaselineDifferenceFilter filter = GetBaselineDifferenceFilter();
                    NameTable       sharedNameTable = new NameTable();
                    HostEnvironment contractHost    = new HostEnvironment(sharedNameTable);
                    contractHost.UnableToResolve += new EventHandler <UnresolvedReference <IUnit, AssemblyIdentity> >(contractHost_UnableToResolve);
                    contractHost.ResolveAgainstRunningFramework = s_resolveFx;
                    contractHost.UnifyToLibPath = s_unifyToLibPaths;
                    contractHost.AddLibPaths(HostEnvironment.SplitPaths(s_contractLibDirs));
                    IEnumerable <IAssembly> contractAssemblies = contractHost.LoadAssemblies(s_contractSet, s_contractCoreAssembly);

                    if (s_ignoreDesignTimeFacades)
                    {
                        contractAssemblies = contractAssemblies.Where(a => !a.IsFacade());
                    }

                    HostEnvironment implHost = new HostEnvironment(sharedNameTable);
                    implHost.UnableToResolve += new EventHandler <UnresolvedReference <IUnit, AssemblyIdentity> >(implHost_UnableToResolve);
                    implHost.ResolveAgainstRunningFramework = s_resolveFx;
                    implHost.UnifyToLibPath = s_unifyToLibPaths;
                    implHost.AddLibPaths(HostEnvironment.SplitPaths(s_implDirs));
                    if (s_warnOnMissingAssemblies)
                    {
                        implHost.LoadErrorTreatment = ErrorTreatment.TreatAsWarning;
                    }

                    // The list of contractAssemblies already has the core assembly as the first one (if _contractCoreAssembly was specified).
                    IEnumerable <IAssembly> implAssemblies = implHost.LoadAssemblies(contractAssemblies.Select(a => a.AssemblyIdentity), s_warnOnIncorrectVersion);

                    // Exit after loading if the code is set to non-zero
                    if (DifferenceWriter.ExitCode != 0)
                    {
                        return(0);
                    }

                    ICciDifferenceWriter writer = GetDifferenceWriter(output, filter);
                    writer.Write(s_implDirs, implAssemblies, s_contractSet, contractAssemblies);
                    return(0);
                }
                catch (FileNotFoundException)
                {
                    // FileNotFoundException will be thrown by GetBaselineDifferenceFilter if it doesn't find the baseline file
                    // OR if GetComparers doesn't find the remap file.
                    return(2);
                }
            }
        }
Exemple #22
0
 public static Tenant WithHost(this Tenant tenant, HostEnvironment environment)
 {
     tenant.Add(environment);
     return(tenant);
 }
Exemple #23
0
    public static Assembly PruneAssembly(HostEnvironment host, ISlice<MethodReferenceAdaptor, FieldReferenceAdaptor, TypeReferenceAdaptor, IAssemblyReference> slice) {
      Contract.Requires(host != null);
      Contract.Requires(slice != null);

      var newAssemblyName = slice.Name;
      var originalAssembly = slice.ContainingAssembly.ResolvedAssembly;
      Contract.Assume(!(originalAssembly is Dummy));
      var methodDefsToKeep = new HashSet<uint>();
      foreach (var m in slice.Methods) {
        methodDefsToKeep.Add(m.reference.InternedKey);
      }


      var copier = new MetadataDeepCopier(host);
      var thingsToKeep = new HashSet<object>();
      var methodHashAttributes = new Dictionary<IMethodDefinition, MethodHashAttribute>();
      var me = new Prune(host, copier, thingsToKeep, methodDefsToKeep, methodHashAttributes);

      // 1. everything that is specified in the slice should definitely be kept.
      foreach (var c in slice.Chains) {
        me.VisitChain(c);
      }

      // 2. everything reachable from the initial set of things to keep should be kept
      Dictionary<IMethodDefinition, uint> contractOffsets;
      FindReachable.Reachable(host, slice, thingsToKeep, methodDefsToKeep, out contractOffsets);
      me.contractOffsets = contractOffsets;

      // 3. copy the original assembly --- entirely!
      var a_prime = copier.Copy(originalAssembly);
      var nameTable = host.NameTable;
      a_prime.ModuleName = nameTable.GetNameFor(newAssemblyName + ".dll");
      a_prime.Name = nameTable.GetNameFor(newAssemblyName);

      var mutableRoot = (RootUnitNamespace)(a_prime.UnitNamespaceRoot);
      var methodHashAttributeType = DefineMethodHashAttributeType(host, mutableRoot);
      me.methodHashAttributeCtor = new Microsoft.Cci.MethodReference(
          host,
          methodHashAttributeType,
          CallingConvention.HasThis,
          host.PlatformType.SystemVoid,
          host.NameTable.Ctor,
          0,
          me.systemString,
          me.systemInt);

      // 4. delete all unwanted things from the mutable copy
      me.RewriteChildren(a_prime);

      var remainingTypes = new List<INamedTypeDefinition>(a_prime.AllTypes.Count); // will only shrink
      remainingTypes.Add(a_prime.AllTypes[0]); // <Module> class is always kept
      for (int i = 1, n = a_prime.AllTypes.Count; i < n; i++) {
        var t = a_prime.AllTypes[i];
        Contract.Assume(t!= null);
        Contract.Assume(copier.OriginalFor.ContainsKey(t));
        var orig = copier.OriginalFor[t];
        if (thingsToKeep.Contains(orig))
          remainingTypes.Add(t);
      }
      a_prime.AllTypes = remainingTypes;
      // do this afterwards so it doesn't get visited.
      mutableRoot.Members.Add(methodHashAttributeType);
      a_prime.AllTypes.Add(methodHashAttributeType);

      return a_prime;
    }
 public StartHost(HostEnvironment environment, HostSettings settings, Host parentHost)
 {
     _environment = environment;
     _settings    = settings;
     _parentHost  = parentHost;
 }
Exemple #25
0
 public StopHost(HostEnvironment environment, HostSettings settings)
 {
     _environment = environment;
     _settings = settings;
 }
Exemple #26
0
        public static Assembly PruneAssembly(HostEnvironment host, ISlice <MethodReferenceAdaptor, FieldReferenceAdaptor, TypeReferenceAdaptor, IAssemblyReference> slice)
        {
            Contract.Requires(host != null);
            Contract.Requires(slice != null);

            var newAssemblyName  = slice.Name;
            var originalAssembly = slice.ContainingAssembly.ResolvedAssembly;

            Contract.Assume(!(originalAssembly is Dummy));
            var methodDefsToKeep = new HashSet <uint>();

            foreach (var m in slice.Methods)
            {
                methodDefsToKeep.Add(m.reference.InternedKey);
            }


            var copier               = new MetadataDeepCopier(host);
            var thingsToKeep         = new HashSet <object>();
            var methodHashAttributes = new Dictionary <IMethodDefinition, MethodHashAttribute>();
            var me = new Prune(host, copier, thingsToKeep, methodDefsToKeep, methodHashAttributes);

            // 1. everything that is specified in the slice should definitely be kept.
            foreach (var c in slice.Chains)
            {
                me.VisitChain(c);
            }

            // 2. everything reachable from the initial set of things to keep should be kept
            Dictionary <IMethodDefinition, uint> contractOffsets;

            FindReachable.Reachable(host, slice, thingsToKeep, methodDefsToKeep, out contractOffsets);
            me.contractOffsets = contractOffsets;

            // 3. copy the original assembly --- entirely!
            var a_prime   = copier.Copy(originalAssembly);
            var nameTable = host.NameTable;

            a_prime.ModuleName = nameTable.GetNameFor(newAssemblyName + ".dll");
            a_prime.Name       = nameTable.GetNameFor(newAssemblyName);

            var mutableRoot             = (RootUnitNamespace)(a_prime.UnitNamespaceRoot);
            var methodHashAttributeType = DefineMethodHashAttributeType(host, mutableRoot);

            me.methodHashAttributeCtor = new Microsoft.Cci.MethodReference(
                host,
                methodHashAttributeType,
                CallingConvention.HasThis,
                host.PlatformType.SystemVoid,
                host.NameTable.Ctor,
                0,
                me.systemString,
                me.systemInt);

            // 4. delete all unwanted things from the mutable copy
            me.RewriteChildren(a_prime);

            var remainingTypes = new List <INamedTypeDefinition>(a_prime.AllTypes.Count); // will only shrink

            remainingTypes.Add(a_prime.AllTypes[0]);                                      // <Module> class is always kept
            for (int i = 1, n = a_prime.AllTypes.Count; i < n; i++)
            {
                var t = a_prime.AllTypes[i];
                Contract.Assume(t != null);
                Contract.Assume(copier.OriginalFor.ContainsKey(t));
                var orig = copier.OriginalFor[t];
                if (thingsToKeep.Contains(orig))
                {
                    remainingTypes.Add(t);
                }
            }
            a_prime.AllTypes = remainingTypes;
            // do this afterwards so it doesn't get visited.
            mutableRoot.Members.Add(methodHashAttributeType);
            a_prime.AllTypes.Add(methodHashAttributeType);

            return(a_prime);
        }
Exemple #27
0
        private static NamespaceTypeDefinition DefineMethodHashAttributeType(HostEnvironment host, RootUnitNamespace rootUnitNamespace)
        {
            Contract.Requires(host != null);
            var internFactory = host.InternFactory;

            #region Define the type
            var methodHashAttributeType = new NamespaceTypeDefinition()
            {
                BaseClasses = new List <ITypeReference> {
                    host.PlatformType.SystemAttribute,
                },
                ContainingUnitNamespace = rootUnitNamespace,
                InternFactory           = internFactory,
                //IsBeforeFieldInit = true,
                IsClass  = true,
                IsPublic = true,
                //IsSealed = true,
                Methods = new List <IMethodDefinition>(1),
                Name    = host.NameTable.GetNameFor("MethodHashAttribute"),
                //Layout = LayoutKind.Auto,
                //StringFormat = StringFormatKind.Ansi,
            };
            #endregion

            #region Define the ctor
            var systemVoidType           = host.PlatformType.SystemVoid;
            List <IStatement> statements = new List <IStatement>();
            SourceMethodBody  body       = new SourceMethodBody(host)
            {
                LocalsAreZeroed = true,
                Block           = new BlockStatement()
                {
                    Statements = statements
                },
            };

            var ctor = new MethodDefinition()
            {
                Body = body,
                CallingConvention        = CallingConvention.HasThis,
                ContainingTypeDefinition = methodHashAttributeType,
                InternFactory            = internFactory,
                IsRuntimeSpecial         = true,
                IsStatic      = false,
                IsSpecialName = true,
                Name          = host.NameTable.Ctor,
                Type          = systemVoidType,
                Visibility    = TypeMemberVisibility.Public,
            };
            var systemStringType = host.PlatformType.SystemString;
            var systemIntType    = host.PlatformType.SystemInt32;
            ctor.Parameters = new List <IParameterDefinition>()
            {
                new ParameterDefinition()
                {
                    ContainingSignature = ctor,
                    Name  = host.NameTable.GetNameFor("a"),
                    Type  = systemStringType,
                    Index = 0,
                },
                new ParameterDefinition()
                {
                    ContainingSignature = ctor,
                    Name  = host.NameTable.GetNameFor("b"),
                    Type  = systemIntType,
                    Index = 1,
                }
            };

            body.MethodDefinition = ctor;
            var thisRef = new ThisReference()
            {
                Type = methodHashAttributeType,
            };
            // base();
            foreach (var baseClass in methodHashAttributeType.BaseClasses)
            {
                var baseCtor = new Microsoft.Cci.MutableCodeModel.MethodReference()
                {
                    CallingConvention     = CallingConvention.HasThis,
                    ContainingType        = baseClass,
                    GenericParameterCount = 0,
                    InternFactory         = internFactory,
                    Name = host.NameTable.Ctor,
                    Type = systemVoidType,
                };
                statements.Add(
                    new ExpressionStatement()
                {
                    Expression = new MethodCall()
                    {
                        MethodToCall = baseCtor,
                        IsStaticCall = false, // REVIEW: Is this needed in addition to setting the ThisArgument?
                        ThisArgument = new ThisReference()
                        {
                            Type = methodHashAttributeType,
                        },
                        Type      = systemVoidType, // REVIEW: Is this the right way to do this?
                        Arguments = new List <IExpression>(),
                    }
                }
                    );
                break;
            }

            // return;
            statements.Add(new ReturnStatement());
            methodHashAttributeType.Methods.Add(ctor);
            #endregion Define the ctor
            return(methodHashAttributeType);
        }
Exemple #28
0
        public static int Main(string[] args)
        {
            ParseCommandLine(args);
            CommandLineTraceHandler.Enable();

            if (s_listRules)
            {
                CompositionHost c = GetCompositionHost();
                ExportCciSettings.StaticSettings = CciComparers.Default.GetEqualityComparer<ITypeReference>();

                var rules = c.GetExports<IDifferenceRule>();

                foreach (var rule in rules.Select(r => r.GetType().Name).OrderBy(r => r))
                {
                    Console.WriteLine(rule);
                }

                return 0;
            }

            using (TextWriter output = GetOutput())
            {
                if (DifferenceWriter.ExitCode != 0)
                    return 0;

                if (output != Console.Out)
                    Trace.Listeners.Add(new TextWriterTraceListener(output) { Filter = new EventTypeFilter(SourceLevels.Error | SourceLevels.Warning) });
                try
                {
                    BaselineDifferenceFilter filter = GetBaselineDifferenceFilter();
                    NameTable sharedNameTable = new NameTable();
                    HostEnvironment contractHost = new HostEnvironment(sharedNameTable);
                    contractHost.UnableToResolve += new EventHandler<UnresolvedReference<IUnit, AssemblyIdentity>>(contractHost_UnableToResolve);
                    contractHost.ResolveAgainstRunningFramework = s_resolveFx;
                    contractHost.UnifyToLibPath = s_unifyToLibPaths;
                    contractHost.AddLibPaths(HostEnvironment.SplitPaths(s_contractLibDirs));
                    IEnumerable<IAssembly> contractAssemblies = contractHost.LoadAssemblies(s_contractSet, s_contractCoreAssembly);

                    if (s_ignoreDesignTimeFacades)
                        contractAssemblies = contractAssemblies.Where(a => !a.IsFacade());

                    HostEnvironment implHost = new HostEnvironment(sharedNameTable);
                    implHost.UnableToResolve += new EventHandler<UnresolvedReference<IUnit, AssemblyIdentity>>(implHost_UnableToResolve);
                    implHost.ResolveAgainstRunningFramework = s_resolveFx;
                    implHost.UnifyToLibPath = s_unifyToLibPaths;
                    implHost.AddLibPaths(HostEnvironment.SplitPaths(s_implDirs));
                    if (s_warnOnMissingAssemblies)
                        implHost.LoadErrorTreatment = ErrorTreatment.TreatAsWarning;

                    // The list of contractAssemblies already has the core assembly as the first one (if _contractCoreAssembly was specified).
                    IEnumerable<IAssembly> implAssemblies = implHost.LoadAssemblies(contractAssemblies.Select(a => a.AssemblyIdentity), s_warnOnIncorrectVersion);

                    // Exit after loading if the code is set to non-zero
                    if (DifferenceWriter.ExitCode != 0)
                        return 0;

                    ICciDifferenceWriter writer = GetDifferenceWriter(output, filter);
                    writer.Write(s_implDirs, implAssemblies, s_contractSet, contractAssemblies);
                    return 0;
                }
                catch (FileNotFoundException)
                {
                    // FileNotFoundException will be thrown by GetBaselineDifferenceFilter if it doesn't find the baseline file
                    // OR if GetComparers doesn't find the remap file.
                    return 2;
                }                
            }
        }
Exemple #29
0
    public static void Run(ApiCatalogModel catalog,
                           IReadOnlyCollection <string> filePaths,
                           IReadOnlyList <NuGetFramework> frameworks,
                           bool analyzeObsoletion,
                           IReadOnlyList <string> platforms,
                           Action <AssemblyResult> resultReceiver)
    {
        var apiByGuid           = catalog.GetAllApis().ToDictionary(a => a.Guid);
        var availabilityContext = ApiAvailabilityContext.Create(catalog);

        var platformContexts = frameworks.Select(fx => PlatformAnnotationContext.Create(availabilityContext, fx.GetShortFolderName()))
                               .ToDictionary(pc => pc.Framework);

        foreach (var api in catalog.GetAllApis())
        {
            var forwardedApi = catalog.GetForwardedApi(api);
            if (forwardedApi is not null)
            {
                apiByGuid[api.Guid] = forwardedApi.Value;
            }
        }

        var apiAvailability = new ConcurrentDictionary <ApiModel, ApiAvailability>();

        var resultSink = new BlockingCollection <AssemblyResult>();

        var resultSinkTask = Task.Run(() =>
        {
            foreach (var result in resultSink.GetConsumingEnumerable())
            {
                resultReceiver(result);
            }
        });

        Parallel.ForEach(filePaths, filePath =>
        {
            using var env    = new HostEnvironment();
            var assembly     = env.LoadAssemblyFrom(filePath);
            var assemblyName = assembly is not null
                                ? assembly.Name.Value
                                : Path.GetFileName(filePath);
            if (assembly is null)
            {
                var result = new AssemblyResult(assemblyName, "Not a valid .NET assembly", Array.Empty <ApiResult>());
                resultSink.Add(result);
            }
            else
            {
                var assemblyTfm       = assembly.GetTargetFrameworkMoniker();
                var assemblyFramework = string.IsNullOrEmpty(assemblyTfm) ? null : NuGetFramework.Parse(assemblyTfm);

                var crawler = new AssemblyCrawler();
                crawler.Crawl(assembly);

                var crawlerResults = crawler.GetResults();

                var apiResults             = new List <ApiResult>();
                var frameworkResultBuilder = new List <FrameworkResult>(frameworks.Count);
                var platformResultBuilder  = new List <PlatformResult?>(platforms.Count);

                foreach (var apiKey in crawlerResults.Data.Keys)
                {
                    if (apiByGuid.TryGetValue(apiKey.Guid, out var api))
                    {
                        var availability = apiAvailability.GetOrAdd(api, a => availabilityContext.GetAvailability(a));

                        frameworkResultBuilder.Clear();

                        foreach (var framework in frameworks)
                        {
                            // Analyze availability

                            AvailabilityResult availabilityResult;

                            var infos = availability.Frameworks.Where(fx => fx.Framework == framework).ToArray();

                            // NOTE: There are APIs that exist in multiple places in-box, e.g. Microsoft.Windows.Themes.ListBoxChrome.
                            //       It doesn't really matter for our purposes. Either way, we'll pick the first one.
                            var info = infos.FirstOrDefault(i => i.IsInBox) ?? infos.FirstOrDefault(i => !i.IsInBox);

                            if (info is null)
                            {
                                availabilityResult = AvailabilityResult.Unavailable;
                            }
                            else if (info.IsInBox)
                            {
                                availabilityResult = AvailabilityResult.AvailableInBox;
                            }
                            else
                            {
                                availabilityResult = AvailabilityResult.AvailableInPackage(info.Package.Value);
                            }

                            // Analyze obsoletion

                            ObsoletionResult?obsoletionResult;

                            if (!analyzeObsoletion || info?.Declaration.Obsoletion is null)
                            {
                                obsoletionResult = null;
                            }
                            else
                            {
                                var compiledAgainstObsoleteApi = false;

                                if (assemblyFramework is not null)
                                {
                                    var compiledAvailability = availabilityContext.GetAvailability(api, assemblyFramework);
                                    if (compiledAvailability?.Declaration.Obsoletion is not null)
                                    {
                                        compiledAgainstObsoleteApi = true;
                                    }
                                }

                                if (compiledAgainstObsoleteApi)
                                {
                                    obsoletionResult = null;
                                }
                                else
                                {
                                    var o            = info.Declaration.Obsoletion.Value;
                                    obsoletionResult = new ObsoletionResult(o.Message, o.Url);
                                }
                            }

                            // Analyze platform support

                            platformResultBuilder.Clear();

                            if (info is null)
                            {
                                for (var i = 0; i < platforms.Count; i++)
                                {
                                    platformResultBuilder.Add(null);
                                }
                            }
                            else
                            {
                                var platformContext = platformContexts[framework];
                                foreach (var platform in platforms)
                                {
                                    var annotation     = platformContext.GetPlatformAnnotation(api);
                                    var isSupported    = annotation.IsSupported(platform);
                                    var platformResult = isSupported ? PlatformResult.Supported : PlatformResult.Unsupported;
                                    platformResultBuilder.Add(platformResult);
                                }
                            }

                            var frameworkResult = new FrameworkResult(availabilityResult, obsoletionResult, platformResultBuilder.ToArray());
                            frameworkResultBuilder.Add(frameworkResult);
                        }

                        var apiResult = new ApiResult(api, frameworkResultBuilder.ToArray());
                        apiResults.Add(apiResult);
                    }
                }

                var results = new AssemblyResult(assemblyName, null, apiResults.ToArray());
                resultSink.Add(results);
            }
        });

        resultSink.CompleteAdding();
        resultSinkTask.Wait();
    }
Exemple #30
0
        public static void RunBclRewriter(string[] args)
        {
            #region Parse the command-line arguments.
            if (!Parser.ParseArgumentsWithUsage(args, typeof(Program)))
            {
                throw new UsageException();
            }
            #endregion

            #region Figure out paths
            s_assemblyName = Path.GetFullPath(s_assemblyName); // this has to be specified

            string outputBaseName = null;
            if (!String.IsNullOrEmpty(s_output))
            {
                s_output       = Path.GetFullPath(s_output);
                outputBaseName = Path.GetFileNameWithoutExtension(s_output);
            }
            else
            {
                s_output       = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileNameWithoutExtension(s_assemblyName) + ".small" + Path.GetExtension(s_assemblyName));
                outputBaseName = s_assemblyName;
            }

            string pdbSourceFile = Path.ChangeExtension(s_assemblyName, "pdb");
            string outputPdb     = Path.ChangeExtension(s_output, "pdb");
            string outputFolder  = Path.GetDirectoryName(s_output);

            // if the user wants to do an in-place rewrite, we copy the file to a temp file
            if (s_output == s_assemblyName)
            {
                String tempPath    = s_assemblyName + TempExtension;
                String tempPdbPath = pdbSourceFile + TempExtension;

                File.Copy(s_assemblyName, tempPath, true);
                s_assemblyName = tempPath;

                if (File.Exists(pdbSourceFile))
                {
                    File.Copy(pdbSourceFile, tempPdbPath, true);
                    pdbSourceFile = tempPdbPath;
                }
            }

            if (!Directory.Exists(outputFolder))
            {
                Directory.CreateDirectory(outputFolder);
            }

            #endregion

            #region Load input files
            HostEnvironment host = new HostEnvironment(new NameTable(), s_assemblyDependencyPaths, s_referencedAssemblies);

            IAssembly /*?*/ assembly = host.LoadUnitFrom(s_assemblyName) as IAssembly;
            // TODO: Handle multimodule assemblies
            if (assembly == null || assembly == Dummy.Assembly)
            {
                throw new UsageException(args[0] + " is not a PE file containing a CLR assembly, or an error occurred when loading it.");
            }

            if (!File.Exists(s_includeListFile))
            {
                throw new UsageException(String.Format("ERROR: Can't find code model file '{0}'", s_includeListFile));
            }

            ThinModel model = new ThinModel(new ThinnerOptions(host, new AssemblyIdentity[] { assembly.AssemblyIdentity }));
            model.LoadModel(s_includeListFile, new ModelReaderOptions(s_platform, s_architecture, s_flavor, s_treatFxInternalAsPublic, s_defines));
            #endregion

            #region Calculate api closure.
            ConsoleTimer.StartTimer("Calculating api closure");
            model.LoadMetadataFrom(assembly);

            ThinModel apiClosure = model.CalculateApiClosure();
            if (s_keepTempFiles)
            {
                apiClosure.SaveModel(Path.ChangeExtension(s_output, ".apiClosure.xml"));
            }
            ConsoleTimer.EndTimer("Calculating api closure");
            #endregion

            #region Calculate impl closure.
            ConsoleTimer.StartTimer("Calculating implementation closure");
            apiClosure.LoadMetadataFrom(assembly);

            ThinModel implClosure = apiClosure.CalculateImplementationClosure(true, FieldOptions.KeepAll);

            if (s_keepTempFiles)
            {
                implClosure.SaveModel(Path.ChangeExtension(s_output, ".implClosure.xml"));
            }
            ConsoleTimer.EndTimer("Calculating implementation closure");
            #endregion

            #region Trim.
            ConsoleTimer.StartTimer("Trimming assembly");
            IncludeSet includeSet = new IncludeSet();
            includeSet.LoadFrom(implClosure);

            var      copier         = new MetadataDeepCopier(host);
            Assembly copiedAssembly = copier.Copy(assembly);

            Trimmer trimmer = new Trimmer(includeSet, true, false, true, host, s_removeSerializable);
            trimmer.RewriteChildren(copiedAssembly);
            Assembly mutableAssembly = copiedAssembly;
            assembly = mutableAssembly;

            ConsoleTimer.EndTimer("Trimming assembly");
            #endregion

            #region Update assembly name.
            ConsoleTimer.StartTimer("Updating assembly name");

            // If the output assembly name is different, update the internal assembly name to match.
            AssemblyIdentity originalAssemblyIdentity = mutableAssembly.AssemblyIdentity;
            if (!outputBaseName.Equals(originalAssemblyIdentity.Name.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                mutableAssembly.Name       = host.NameTable.GetNameFor(outputBaseName);
                mutableAssembly.ModuleName = mutableAssembly.Name;
            }

            // If we changed the assembly identity, update references to it.
            if (!mutableAssembly.AssemblyIdentity.Equals(originalAssemblyIdentity))
            {
                trimmer.UpdateAssemblyReferences(originalAssemblyIdentity, mutableAssembly.AssemblyIdentity);
            }

            ConsoleTimer.EndTimer("Updating assembly name");
            #endregion

            #region Write out the assembly
            ConsoleTimer.StartTimer("Writing assembly");
            PdbReader pdbReader = null;
            PdbWriter pdbWriter = null;
            if (File.Exists(pdbSourceFile))
            {
                Stream pdbStream = File.OpenRead(pdbSourceFile);
                pdbReader = new PdbReader(pdbStream, host);
                pdbWriter = new PdbWriter(outputPdb, pdbReader);
                Console.WriteLine("Writing pdb: {0}", outputPdb);
            }

            Console.WriteLine("Writing assembly: {0}", s_output);
            FileStream file = File.Create(s_output);

            try
            {
                PeWriter.WritePeToStream(assembly, host, file, pdbReader, pdbReader, pdbWriter);
            }
            finally
            {
                if (file != null)
                {
                    file.Dispose();
                }

                if (pdbWriter != null)
                {
                    pdbWriter.Dispose();
                }
            }

            ConsoleTimer.EndTimer("Writing assembly");
            #endregion
        }
        private IEnumerable <MemberDependency> GetDependencies(string assemblyLocation)
        {
            using (var host = new HostEnvironment())
            {
                host.UnableToResolve += (s, e) =>
                {
                    string callingAssembly = e.Referrer.FullName();

                    // Try to get better information about the referrer. This may throw, but we don't want to crash even if we do.
                    try
                    {
                        callingAssembly = e.Referrer.GetAssemblyReference().AssemblyIdentity.Format();
                    }
                    catch { }

                    HashSet <string> newValue = new HashSet <string>();
                    newValue.Add(callingAssembly);
                    _unresolvedAssemblies.AddOrUpdate(e.Unresolved.Format(), newValue, (key, existingHashSet) =>
                    {
                        lock (existingHashSet)
                        {
                            existingHashSet.Add(callingAssembly);
                        }
                        return(existingHashSet);
                    });
                };

                host.UnifyToLibPath = true;
                var cciAssembly = host.LoadAssembly(assemblyLocation);

                if (cciAssembly == null)
                {
                    _assembliesWithError.Add(assemblyLocation);
                    // error.
                    yield break;
                }


                // Extract the fileversion and assembly version from the assembly.
                FileVersionInfo fileInfo     = FileVersionInfo.GetVersionInfo(assemblyLocation);
                AssemblyInfo    assemblyInfo = new AssemblyInfo();
                assemblyInfo.AssemblyIdentity       = cciAssembly.AssemblyIdentity.Format();
                assemblyInfo.FileVersion            = fileInfo.FileVersion ?? string.Empty;
                assemblyInfo.TargetFrameworkMoniker = cciAssembly.GetTargetFrameworkMoniker();

                // remember this assembly as a user assembly.
                _userAssemblies.Add(assemblyInfo);

                // Identify references to members (generic and non-generic)
                foreach (var reference in cciAssembly.GetTypeMemberReferences())
                {
                    if (reference.ContainingType.GetAssemblyReference() == null)
                    {
                        continue;
                    }

                    string definedIn = reference.ContainingType.GetAssemblyReference().ContainingAssembly.AssemblyIdentity.Format();
                    // return the type
                    yield return(new MemberDependency()
                    {
                        CallingAssembly = assemblyInfo,
                        MemberDocId = reference.ContainingType.DocId(),
                        DefinedInAssemblyIdentity = definedIn
                    });

                    //return the member
                    yield return(new MemberDependency()
                    {
                        CallingAssembly = assemblyInfo,
                        MemberDocId = reference.DocId(),
                        TypeDocId = reference.ContainingType.DocId(),
                        DefinedInAssemblyIdentity = definedIn
                    });
                }

                // Identify references to types
                foreach (var refence in cciAssembly.GetTypeReferences())
                {
                    string definedIn = refence.GetAssemblyReference().ContainingAssembly.AssemblyIdentity.Format();
                    //return the type
                    yield return(new MemberDependency()
                    {
                        CallingAssembly = assemblyInfo,
                        MemberDocId = refence.DocId(),
                        DefinedInAssemblyIdentity = definedIn
                    });
                }
            }
        }
Exemple #32
0
 public BenchMarkType(CloudProvider cloudProvider, HostEnvironment hostEnvironment, Runtime runtime)
 {
     CloudProvider   = cloudProvider;
     HostEnvironment = hostEnvironment;
     Runtime         = runtime;
 }
 public StartHost(HostEnvironment environment, HostSettings settings)
     : this(environment, settings, null)
 {
 }
Exemple #34
0
    private static NamespaceTypeDefinition DefineMethodHashAttributeType(HostEnvironment host, RootUnitNamespace rootUnitNamespace) {
      Contract.Requires(host != null);
      var internFactory = host.InternFactory;

      #region Define the type
      var methodHashAttributeType = new NamespaceTypeDefinition() {
        BaseClasses = new List<ITypeReference> { host.PlatformType.SystemAttribute, },
        ContainingUnitNamespace = rootUnitNamespace,
        InternFactory = internFactory,
        //IsBeforeFieldInit = true,
        IsClass = true,
        IsPublic = true,
        //IsSealed = true,
        Methods = new List<IMethodDefinition>(1),
        Name = host.NameTable.GetNameFor("MethodHashAttribute"),
        //Layout = LayoutKind.Auto,
        //StringFormat = StringFormatKind.Ansi,
      };
      #endregion

      #region Define the ctor
      var systemVoidType = host.PlatformType.SystemVoid;
      List<IStatement> statements = new List<IStatement>();
      SourceMethodBody body = new SourceMethodBody(host) {
        LocalsAreZeroed = true,
        Block = new BlockStatement() { Statements = statements },
      };

      var ctor = new MethodDefinition() {
        Body = body,
        CallingConvention = CallingConvention.HasThis,
        ContainingTypeDefinition = methodHashAttributeType,
        InternFactory = internFactory,
        IsRuntimeSpecial = true,
        IsStatic = false,
        IsSpecialName = true,
        Name = host.NameTable.Ctor,
        Type = systemVoidType,
        Visibility = TypeMemberVisibility.Public,
      };
      var systemStringType = host.PlatformType.SystemString;
      var systemIntType = host.PlatformType.SystemInt32;
      ctor.Parameters = new List<IParameterDefinition>(){
        new ParameterDefinition() {
          ContainingSignature = ctor,
          Name = host.NameTable.GetNameFor("a"),
          Type = systemStringType,
          Index = 0,
        },
        new ParameterDefinition() {
          ContainingSignature = ctor,
          Name = host.NameTable.GetNameFor("b"),
          Type = systemIntType,
          Index = 1,
        }
      };

      body.MethodDefinition = ctor;
      var thisRef = new ThisReference() { Type = methodHashAttributeType, };
      // base();
      foreach (var baseClass in methodHashAttributeType.BaseClasses) {
        var baseCtor = new Microsoft.Cci.MutableCodeModel.MethodReference() {
          CallingConvention = CallingConvention.HasThis,
          ContainingType = baseClass,
          GenericParameterCount = 0,
          InternFactory = internFactory,
          Name = host.NameTable.Ctor,
          Type = systemVoidType,
        };
        statements.Add(
          new ExpressionStatement() {
            Expression = new MethodCall() {
              MethodToCall = baseCtor,
              IsStaticCall = false, // REVIEW: Is this needed in addition to setting the ThisArgument?
              ThisArgument = new ThisReference() { Type = methodHashAttributeType, },
              Type = systemVoidType, // REVIEW: Is this the right way to do this?
              Arguments = new List<IExpression>(),
            }
          }
          );
        break;
      }

      // return;
      statements.Add(new ReturnStatement());
      methodHashAttributeType.Methods.Add(ctor);
      #endregion Define the ctor
      return methodHashAttributeType;

    }
 public HelpBuilder(HostEnvironment environment, HostSettings settings)
 {
     _settings    = settings;
     _environment = environment;
 }
Exemple #36
0
 public StopHost(HostEnvironment environment, HostSettings settings)
 {
     _environment = environment;
     _settings    = settings;
 }
Exemple #37
0
        public static void Main(string[] args)
        {
            string         seeds                          = null;
            string         contracts                      = null;
            string         facadePath                     = null;
            Version        assemblyFileVersion            = null;
            bool           clearBuildAndRevision          = false;
            bool           ignoreMissingTypes             = false;
            bool           ignoreBuildAndRevisionMismatch = false;
            bool           buildDesignTimeFacades         = false;
            string         inclusionContracts             = null;
            ErrorTreatment seedLoadErrorTreatment         = ErrorTreatment.Default;
            ErrorTreatment contractLoadErrorTreatment     = ErrorTreatment.Default;

            string[] seedTypePreferencesUnsplit = null;
            bool     forceZeroVersionSeeds      = false;
            bool     producePdb = true;
            string   partialFacadeAssemblyPath = null;

            bool parsingSucceeded = CommandLineParser.ParseForConsoleApplication((parser) =>
            {
                parser.DefineQualifier("facadePath", ref facadePath, "Path to output the facades.");
                parser.DefineQualifier("seeds", ref seeds, "Path to the seed assemblies. Can contain multiple assemblies or directories delimited by ',' or ';'.");
                parser.DefineQualifier("contracts", ref contracts, "Path to the contract assemblies. Can contain multiple assemblies or directories delimited by ',' or ';'.");
                parser.DefineOptionalQualifier("assemblyFileVersion", ref assemblyFileVersion, "Override the AssemblyFileVersion attribute from the contract with the given version for the generated facade.");
                parser.DefineOptionalQualifier("clearBuildAndRevision", ref clearBuildAndRevision, "Generate facade assembly version x.y.0.0 for contract version x.y.z.w");
                parser.DefineOptionalQualifier("ignoreBuildAndRevisionMismatch", ref ignoreBuildAndRevisionMismatch, "Ignore a mismatch in revision and build for partial facade.");
                parser.DefineOptionalQualifier("ignoreMissingTypes", ref ignoreMissingTypes, "Ignore types that cannot be found in the seed assemblies. This is not recommended but is sometimes helpful while hacking around or trying to produce partial facades.");
                parser.DefineOptionalQualifier("designTime", ref buildDesignTimeFacades, "Enable design-time facade generation (marks facades with reference assembly flag and attribute).");
                parser.DefineOptionalQualifier("include", ref inclusionContracts, "Add types from these contracts to the facades. Can contain multiple assemblies or directories delimited by ',' or ';'.");
                parser.DefineOptionalQualifier("seedError", ref seedLoadErrorTreatment, "Error handling for seed assembly load failure.");
                parser.DefineOptionalQualifier("contractError", ref seedLoadErrorTreatment, "Error handling for contract assembly load failure.");
                parser.DefineOptionalQualifier("preferSeedType", ref seedTypePreferencesUnsplit, "Set which seed assembly to choose for a given type when it is defined in more than one assembly. Format: FullTypeName=PreferredSeedAssemblyName");
                parser.DefineOptionalQualifier("forceZeroVersionSeeds", ref forceZeroVersionSeeds, "Forces all seed assembly versions to 0.0.0.0, regardless of their true version.");
                parser.DefineOptionalQualifier("partialFacadeAssemblyPath", ref partialFacadeAssemblyPath, "Specifies the path to a single partial facade assembly, into which appropriate type forwards will be added to satisfy the given contract. If this option is specified, only a single partial assembly and a single contract may be given.");
                parser.DefineOptionalQualifier("producePdb", ref producePdb, "Specifices if a PDB file should be produced for the resulting partial facade.");
            }, args);

            if (!parsingSucceeded)
            {
                return;
            }

            CommandLineTraceHandler.Enable();

            if (!Directory.Exists(facadePath))
            {
                Directory.CreateDirectory(facadePath);
            }

            var nameTable     = new NameTable();
            var internFactory = new InternFactory();

            try
            {
                Dictionary <string, string> seedTypePreferences = ParseSeedTypePreferences(seedTypePreferencesUnsplit);

                using (var contractHost = new HostEnvironment(nameTable, internFactory))
                    using (var seedHost = new HostEnvironment(nameTable, internFactory))
                    {
                        contractHost.LoadErrorTreatment = contractLoadErrorTreatment;
                        seedHost.LoadErrorTreatment     = seedLoadErrorTreatment;

                        var contractAssemblies = LoadAssemblies(contractHost, contracts);
                        IReadOnlyDictionary <string, IEnumerable <string> > docIdTable = GenerateDocIdTable(contractAssemblies, inclusionContracts);

                        IAssembly[] seedAssemblies = LoadAssemblies(seedHost, seeds).ToArray();

                        IAssemblyReference seedCoreAssemblyRef = ((Microsoft.Cci.Immutable.PlatformType)seedHost.PlatformType).CoreAssemblyRef;

                        if (forceZeroVersionSeeds)
                        {
                            // Create a deep copier, copy the seed assemblies, and zero out their versions.
                            var copier = new MetadataDeepCopier(seedHost);

                            for (int i = 0; i < seedAssemblies.Length; i++)
                            {
                                var mutableSeed = copier.Copy(seedAssemblies[i]);
                                mutableSeed.Version = new Version(0, 0, 0, 0);
                                // Copy the modified seed assembly back.
                                seedAssemblies[i] = mutableSeed;

                                if (mutableSeed.Name.UniqueKey == seedCoreAssemblyRef.Name.UniqueKey)
                                {
                                    seedCoreAssemblyRef = mutableSeed;
                                }
                            }
                        }

                        var typeTable       = GenerateTypeTable(seedAssemblies);
                        var facadeGenerator = new FacadeGenerator(seedHost, contractHost, docIdTable, typeTable, seedTypePreferences, clearBuildAndRevision, buildDesignTimeFacades, assemblyFileVersion);

                        if (partialFacadeAssemblyPath != null)
                        {
                            if (contractAssemblies.Count() != 1)
                            {
                                throw new FacadeGenerationException(
                                          "When partialFacadeAssemblyPath is specified, only exactly one corresponding contract assembly can be specified.");
                            }

                            IAssembly contractAssembly      = contractAssemblies.First();
                            IAssembly partialFacadeAssembly = seedHost.LoadAssembly(partialFacadeAssemblyPath);
                            if (contractAssembly.Name != partialFacadeAssembly.Name ||
                                contractAssembly.Version.Major != partialFacadeAssembly.Version.Major ||
                                contractAssembly.Version.Minor != partialFacadeAssembly.Version.Minor ||
                                (!ignoreBuildAndRevisionMismatch && contractAssembly.Version.Build != partialFacadeAssembly.Version.Build) ||
                                (!ignoreBuildAndRevisionMismatch && contractAssembly.Version.Revision != partialFacadeAssembly.Version.Revision) ||
                                contractAssembly.GetPublicKeyToken() != partialFacadeAssembly.GetPublicKeyToken())
                            {
                                throw new FacadeGenerationException(
                                          string.Format("The partial facade assembly's name, version, and public key token must exactly match the contract to be filled. Contract: {0}, Facade: {1}",
                                                        contractAssembly.AssemblyIdentity,
                                                        partialFacadeAssembly.AssemblyIdentity));
                            }

                            Assembly filledPartialFacade = facadeGenerator.GenerateFacade(contractAssembly, seedCoreAssemblyRef, ignoreMissingTypes, overrideContractAssembly: partialFacadeAssembly);

                            string pdbLocation = null;

                            if (producePdb)
                            {
                                string pdbFolder = Path.GetDirectoryName(partialFacadeAssemblyPath);
                                pdbLocation = Path.Combine(pdbFolder, contractAssembly.Name + ".pdb");
                                if (producePdb && !File.Exists(pdbLocation))
                                {
                                    pdbLocation = null;
                                    Trace.TraceWarning("No PDB file present for un-transformed partial facade. No PDB will be generated.");
                                }
                            }

                            OutputFacadeToFile(facadePath, seedHost, filledPartialFacade, contractAssembly, pdbLocation);
                        }
                        else
                        {
                            foreach (var contract in contractAssemblies)
                            {
                                Assembly facade = facadeGenerator.GenerateFacade(contract, seedCoreAssemblyRef, ignoreMissingTypes);
                                if (facade == null)
                                {
#if !COREFX
                                    Debug.Assert(Environment.ExitCode != 0);
#endif
                                    continue;
                                }

                                OutputFacadeToFile(facadePath, seedHost, facade, contract);
                            }
                        }
                    }
            }
            catch (FacadeGenerationException ex)
            {
                Trace.TraceError(ex.Message);
#if !COREFX
                Debug.Assert(Environment.ExitCode != 0);
#endif
            }
        }
Exemple #38
0
        private static ICciDifferenceWriter GetDifferenceWriter(TextWriter writer,
                                                                IDifferenceFilter filter,
                                                                bool enforceOptionalRules,
                                                                bool mdil,
                                                                bool excludeNonBrowsable,
                                                                bool includeInternals,
                                                                bool excludeCompilerGenerated,
                                                                string remapFile,
                                                                bool groupByAssembly,
                                                                string leftOperand,
                                                                string rightOperand,
                                                                string excludeAttributes,
                                                                bool allowDefaultInterfaceMethods)
        {
            CompositionHost container = GetCompositionHost();

            bool RuleFilter(IDifferenceRuleMetadata ruleMetadata)
            {
                if (ruleMetadata.OptionalRule && !enforceOptionalRules)
                {
                    return(false);
                }

                if (ruleMetadata.MdilServicingRule && !mdil)
                {
                    return(false);
                }
                return(true);
            }

            if (mdil && excludeNonBrowsable)
            {
                Trace.TraceWarning("Enforcing MDIL servicing rules and exclusion of non-browsable types are both enabled, but they are not compatible so non-browsable types will not be excluded.");
            }

            if (includeInternals && (mdil || excludeNonBrowsable))
            {
                Trace.TraceWarning("Enforcing MDIL servicing rules or exclusion of non-browsable types are enabled " +
                                   "along with including internals -- an incompatible combination. Internal members will not be included.");
            }

            var cciFilter = GetCciFilter(mdil, excludeNonBrowsable, includeInternals, excludeCompilerGenerated);
            var settings  = new MappingSettings
            {
                Comparers             = GetComparers(remapFile),
                DiffFactory           = new ElementDifferenceFactory(container, RuleFilter),
                DiffFilter            = GetDiffFilter(cciFilter),
                Filter                = cciFilter,
                GroupByAssembly       = groupByAssembly,
                IncludeForwardedTypes = true,
            };

            if (filter == null)
            {
                filter = new DifferenceFilter <IncompatibleDifference>();
            }

            var diffWriter = new DifferenceWriter(writer, settings, filter);

            ExportCciSettings.StaticSettings = settings.TypeComparer;
            ExportCciSettings.StaticOperands = new DifferenceOperands()
            {
                Contract       = leftOperand,
                Implementation = rightOperand
            };
            ExportCciSettings.StaticAttributeFilter = GetAttributeFilter(HostEnvironment.SplitPaths(excludeAttributes));
            ExportCciSettings.StaticRuleSettings    = new RuleSettings {
                AllowDefaultInterfaceMethods = allowDefaultInterfaceMethods
            };

            // Always compose the diff writer to allow it to import or provide exports
            container.SatisfyImports(diffWriter);

            return(diffWriter);
        }
Exemple #39
0
 public StartHost(HostEnvironment environment, HostSettings settings, Host parentHost)
 {
     _environment = environment;
     _settings = settings;
     _parentHost = parentHost;
 }
Exemple #40
0
 public CommandHost(HostEnvironment environment, HostSettings settings, int command)
 {
     _environment = environment;
     _settings = settings;
     _command = command;
 }
 public IosBuildHostInstance(HostEnvironment hostEnvironment, RootContainerFactory rootState) : base(hostEnvironment, rootState)
 {
     _hostEnvironment = hostEnvironment;
 }
Exemple #42
0
        public static int Main(string[] args)
        {
            var app = new CommandLineApplication
            {
                Name                 = "ApiCompat",
                FullName             = "A command line tool to verify that two sets of APIs are compatible.",
                ResponseFileHandling = ResponseFileHandling.ParseArgsAsSpaceSeparated
            };

            app.HelpOption("-?|-h|--help");
            app.VersionOption("-v|--version", GetAssemblyVersion());

            CommandArgument contracts = app.Argument("contracts", "Comma delimited list of assemblies or directories of assemblies for all the contract assemblies.");

            contracts.IsRequired();
            CommandOption implDirs = app.Option("-i|--impl-dirs", "Comma delimited list of directories to find the implementation assemblies for each contract assembly.", CommandOptionType.SingleValue);

            implDirs.IsRequired(allowEmptyStrings: true);
            CommandOption baseline                     = app.Option("-b|--baseline", "Baseline file to skip known diffs.", CommandOptionType.SingleValue);
            CommandOption mdil                         = app.Option("-m|--mdil", "Enforce MDIL servicing rules in addition to IL rules.", CommandOptionType.NoValue);
            CommandOption outFilePath                  = app.Option("-o|--out", "Output file path. Default is the console.", CommandOptionType.SingleValue);
            CommandOption leftOperand                  = app.Option("-l|--left-operand", "Name for left operand in comparison, default is 'contract'.", CommandOptionType.SingleValue);
            CommandOption rightOperand                 = app.Option("-r|--right-operand", "Name for right operand in comparison, default is 'implementation'.", CommandOptionType.SingleValue);
            CommandOption listRules                    = app.Option("--list-rules", "Outputs all the rules. If this options is supplied all other options are ignored.", CommandOptionType.NoValue);
            CommandOption remapFile                    = app.Option("--remap-file", "File with a list of type and/or namespace remappings to consider apply to names while diffing.", CommandOptionType.SingleValue);
            CommandOption skipGroupByAssembly          = app.Option("--skip-group-by-assembly", "Skip grouping the differences by assembly instead of flattening the namespaces.", CommandOptionType.NoValue);
            CommandOption skipUnifyToLibPath           = app.Option("--skip-unify-to-lib-path", "Skip unifying the assembly references to the loaded assemblies and the assemblies found in the given directories (contractDepends and implDirs).", CommandOptionType.NoValue);
            CommandOption resolveFx                    = app.Option("--resolve-fx", "If a contract or implementation dependency cannot be found in the given directories, fallback to try to resolve against the framework directory on the machine.", CommandOptionType.NoValue);
            CommandOption contractDepends              = app.Option("--contract-depends", "Comma delimited list of directories used to resolve the dependencies of the contract assemblies.", CommandOptionType.SingleValue);
            CommandOption contractCoreAssembly         = app.Option("--contract-core-assembly", "Simple name for the core assembly to use.", CommandOptionType.SingleValue);
            CommandOption ignoreDesignTimeFacades      = app.Option("--ignore-design-time-facades", "Ignore design time facades in the contract set while analyzing.", CommandOptionType.NoValue);
            CommandOption warnOnIncorrectVersion       = app.Option("--warn-on-incorrect-version", "Warn if the contract version number doesn't match the found implementation version number.", CommandOptionType.NoValue);
            CommandOption warnOnMissingAssemblies      = app.Option("--warn-on-missing-assemblies", "Warn if the contract assembly cannot be found in the implementation directories. Default is to error and not do analysis.", CommandOptionType.NoValue);
            CommandOption excludeNonBrowsable          = app.Option("--exclude-non-browsable", "When MDIL servicing rules are not being enforced, exclude validation on types that are marked with EditorBrowsable(EditorBrowsableState.Never).", CommandOptionType.NoValue);
            CommandOption excludeAttributes            = app.Option("--exclude-attributes", "Specify a api list in the DocId format of which attributes to exclude.", CommandOptionType.SingleValue);
            CommandOption enforceOptionalRules         = app.Option("--enforce-optional-rules", "Enforce optional rules, in addition to the mandatory set of rules.", CommandOptionType.NoValue);
            CommandOption allowDefaultInterfaceMethods = app.Option("--allow-default-interface-methods", "Allow default interface methods additions to not be considered breaks. This flag should only be used if you know your consumers support DIM", CommandOptionType.NoValue);

            app.OnExecute(() =>
            {
                string leftOperandValue  = leftOperand.HasValue() ? leftOperand.Value() : "contract";
                string rightOperandValue = rightOperand.HasValue() ? rightOperand.Value() : "implementation";

                if (listRules.HasValue())
                {
                    CompositionHost c = GetCompositionHost();
                    ExportCciSettings.StaticSettings = CciComparers.Default.GetEqualityComparer <ITypeReference>();

                    var rules = c.GetExports <IDifferenceRule>();

                    foreach (var rule in rules.OrderBy(r => r.GetType().Name, StringComparer.OrdinalIgnoreCase))
                    {
                        string ruleName = rule.GetType().Name;

                        if (IsOptionalRule(rule))
                        {
                            ruleName += " (optional)";
                        }

                        Console.WriteLine(ruleName);
                    }

                    return(0);
                }

                using (TextWriter output = GetOutput(outFilePath.Value()))
                {
                    if (DifferenceWriter.ExitCode != 0)
                    {
                        return(0);
                    }

                    if (output != Console.Out)
                    {
                        Trace.Listeners.Add(new TextWriterTraceListener(output)
                        {
                            Filter = new EventTypeFilter(SourceLevels.Error | SourceLevels.Warning)
                        });
                    }

                    try
                    {
                        BaselineDifferenceFilter filter             = GetBaselineDifferenceFilter(baseline.Value());
                        NameTable sharedNameTable                   = new NameTable();
                        HostEnvironment contractHost                = new HostEnvironment(sharedNameTable);
                        contractHost.UnableToResolve               += (sender, e) => Trace.TraceError($"Unable to resolve assembly '{e.Unresolved}' referenced by the {leftOperandValue} assembly '{e.Referrer}'.");
                        contractHost.ResolveAgainstRunningFramework = resolveFx.HasValue();
                        contractHost.UnifyToLibPath                 = !skipUnifyToLibPath.HasValue();
                        contractHost.AddLibPaths(HostEnvironment.SplitPaths(contractDepends.Value()));
                        IEnumerable <IAssembly> contractAssemblies = contractHost.LoadAssemblies(contracts.Value, contractCoreAssembly.Value());

                        if (ignoreDesignTimeFacades.HasValue())
                        {
                            contractAssemblies = contractAssemblies.Where(a => !a.IsFacade());
                        }

                        HostEnvironment implHost  = new HostEnvironment(sharedNameTable);
                        implHost.UnableToResolve += (sender, e) => Trace.TraceError($"Unable to resolve assembly '{e.Unresolved}' referenced by the {rightOperandValue} assembly '{e.Referrer}'.");
                        implHost.ResolveAgainstRunningFramework = resolveFx.HasValue();
                        implHost.UnifyToLibPath = !skipUnifyToLibPath.HasValue();
                        implHost.AddLibPaths(HostEnvironment.SplitPaths(implDirs.Value()));
                        if (warnOnMissingAssemblies.HasValue())
                        {
                            implHost.LoadErrorTreatment = ErrorTreatment.TreatAsWarning;
                        }

                        // The list of contractAssemblies already has the core assembly as the first one (if _contractCoreAssembly was specified).
                        IEnumerable <IAssembly> implAssemblies = implHost.LoadAssemblies(contractAssemblies.Select(a => a.AssemblyIdentity), warnOnIncorrectVersion.HasValue());

                        // Exit after loading if the code is set to non-zero
                        if (DifferenceWriter.ExitCode != 0)
                        {
                            return(0);
                        }

                        ICciDifferenceWriter writer = GetDifferenceWriter(output, filter, enforceOptionalRules.HasValue(), mdil.HasValue(),
                                                                          excludeNonBrowsable.HasValue(), remapFile.Value(), !skipGroupByAssembly.HasValue(), leftOperandValue, rightOperandValue, excludeAttributes.Value(), allowDefaultInterfaceMethods.HasValue());
                        writer.Write(implDirs.Value(), implAssemblies, contracts.Value, contractAssemblies);

                        return(0);
                    }
                    catch (FileNotFoundException)
                    {
                        // FileNotFoundException will be thrown by GetBaselineDifferenceFilter if it doesn't find the baseline file
                        // OR if GetComparers doesn't find the remap file.
                        return(2);
                    }
                }
            });

            return(app.Execute(args));
        }
 public WinformsRunHost(HostEnvironment environment, HostSettings settings, ServiceHandle serviceHandle)
 {
     _environment = environment;
     _settings = settings;
     _serviceHandle = serviceHandle;
 }
Exemple #44
0
        public static void Main(string[] args)
        {
            string seeds = null;
            string contracts = null;
            string facadePath = null;
            Version assemblyFileVersion = null;
            bool clearBuildAndRevision = false;
            bool ignoreMissingTypes = false;
            bool buildDesignTimeFacades = false;
            string inclusionContracts = null;
            ErrorTreatment seedLoadErrorTreatment = ErrorTreatment.Default;
            ErrorTreatment contractLoadErrorTreatment = ErrorTreatment.Default;
            string[] seedTypePreferencesUnsplit = null;
            bool forceZeroVersionSeeds = false;
            bool producePdb = true;
            string partialFacadeAssemblyPath = null;

            bool parsingSucceeded = CommandLineParser.ParseForConsoleApplication((parser) =>
            {
                parser.DefineQualifier("facadePath", ref facadePath, "Path to output the facades.");
                parser.DefineQualifier("seeds", ref seeds, "Path to the seed assemblies. Can contain multiple assemblies or directories delimited by ',' or ';'.");
                parser.DefineQualifier("contracts", ref contracts, "Path to the contract assemblies. Can contain multiple assemblies or directories delimited by ',' or ';'.");
                parser.DefineOptionalQualifier("assemblyFileVersion", ref assemblyFileVersion, "Override the AssemblyFileVersion attribute from the contract with the given version for the generated facade.");
                parser.DefineOptionalQualifier("clearBuildAndRevision", ref clearBuildAndRevision, "Generate facade assembly version x.y.0.0 for contract version x.y.z.w");
                parser.DefineOptionalQualifier("ignoreMissingTypes", ref ignoreMissingTypes, "Ignore types that cannot be found in the seed assemblies. This is not recommended but is sometimes helpful while hacking around or trying to produce partial facades.");
                parser.DefineOptionalQualifier("designTime", ref buildDesignTimeFacades, "Enable design-time facade generation (marks facades with reference assembly flag and attribute).");
                parser.DefineOptionalQualifier("include", ref inclusionContracts, "Add types from these contracts to the facades. Can contain multiple assemblies or directories delimited by ',' or ';'.");
                parser.DefineOptionalQualifier("seedError", ref seedLoadErrorTreatment, "Error handling for seed assembly load failure.");
                parser.DefineOptionalQualifier("contractError", ref seedLoadErrorTreatment, "Error handling for contract assembly load failure.");
                parser.DefineOptionalQualifier("preferSeedType", ref seedTypePreferencesUnsplit, "Set which seed assembly to choose for a given type when it is defined in more than one assembly. Format: FullTypeName=PreferredSeedAssemblyName");
                parser.DefineOptionalQualifier("forceZeroVersionSeeds", ref forceZeroVersionSeeds, "Forces all seed assembly versions to 0.0.0.0, regardless of their true version.");
                parser.DefineOptionalQualifier("partialFacadeAssemblyPath", ref partialFacadeAssemblyPath, "Specifies the path to a single partial facade assembly, into which appropriate type forwards will be added to satisfy the given contract. If this option is specified, only a single partial assembly and a single contract may be given.");
                parser.DefineOptionalQualifier("producePdb", ref producePdb, "Specifices if a PDB file should be produced for the resulting partial facade.");
            }, args);

            if (!parsingSucceeded)
            {
                return;
            }

            CommandLineTraceHandler.Enable();

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

            var nameTable = new NameTable();
            var internFactory = new InternFactory();

            try
            {
                Dictionary<string, string> seedTypePreferences = ParseSeedTypePreferences(seedTypePreferencesUnsplit);

                using (var contractHost = new HostEnvironment(nameTable, internFactory))
                using (var seedHost = new HostEnvironment(nameTable, internFactory))
                {
                    contractHost.LoadErrorTreatment = contractLoadErrorTreatment;
                    seedHost.LoadErrorTreatment = seedLoadErrorTreatment;

                    var contractAssemblies = LoadAssemblies(contractHost, contracts);
                    IReadOnlyDictionary<string, IEnumerable<string>> docIdTable = GenerateDocIdTable(contractAssemblies, inclusionContracts);

                    IAssembly[] seedAssemblies = LoadAssemblies(seedHost, seeds).ToArray();

                    IAssemblyReference seedCoreAssemblyRef = ((Microsoft.Cci.Immutable.PlatformType)seedHost.PlatformType).CoreAssemblyRef;

                    if (forceZeroVersionSeeds)
                    {
                        // Create a deep copier, copy the seed assemblies, and zero out their versions.
                        var copier = new MetadataDeepCopier(seedHost);

                        for (int i = 0; i < seedAssemblies.Length; i++)
                        {
                            var mutableSeed = copier.Copy(seedAssemblies[i]);
                            mutableSeed.Version = new Version(0, 0, 0, 0);
                            // Copy the modified seed assembly back.
                            seedAssemblies[i] = mutableSeed;

                            if (mutableSeed.Name.UniqueKey == seedCoreAssemblyRef.Name.UniqueKey)
                            {
                                seedCoreAssemblyRef = mutableSeed;
                            }
                        }
                    }

                    var typeTable = GenerateTypeTable(seedAssemblies);
                    var facadeGenerator = new FacadeGenerator(seedHost, contractHost, docIdTable, typeTable, seedTypePreferences, clearBuildAndRevision, buildDesignTimeFacades, assemblyFileVersion);

                    if (partialFacadeAssemblyPath != null)
                    {
                        if (contractAssemblies.Count() != 1)
                        {
                            throw new FacadeGenerationException(
                                "When partialFacadeAssemblyPath is specified, only exactly one corresponding contract assembly can be specified.");
                        }

                        IAssembly contractAssembly = contractAssemblies.First();
                        IAssembly partialFacadeAssembly = seedHost.LoadAssembly(partialFacadeAssemblyPath);
                        if (contractAssembly.Name != partialFacadeAssembly.Name
                            || contractAssembly.Version != partialFacadeAssembly.Version
                            || contractAssembly.GetPublicKeyToken() != partialFacadeAssembly.GetPublicKeyToken())
                        {
                            throw new FacadeGenerationException(
                                string.Format("The partial facade assembly's name, version, and public key token must exactly match the contract to be filled. Contract: {0}, Facade: {1}",
                                    contractAssembly.AssemblyIdentity,
                                    partialFacadeAssembly.AssemblyIdentity));
                        }

                        Assembly filledPartialFacade = facadeGenerator.GenerateFacade(contractAssembly, seedCoreAssemblyRef, ignoreMissingTypes, overrideContractAssembly: partialFacadeAssembly);

                        string pdbLocation = null;

                        if (producePdb)
                        {
                            string pdbFolder = Path.GetDirectoryName(partialFacadeAssemblyPath);
                            pdbLocation = Path.Combine(pdbFolder, contractAssembly.Name + ".pdb");
                            if (producePdb && !File.Exists(pdbLocation))
                            {
                                pdbLocation = null;
                                Trace.TraceWarning("No PDB file present for un-transformed partial facade. No PDB will be generated.");
                            }
                        }

                        OutputFacadeToFile(facadePath, seedHost, filledPartialFacade, contractAssembly, pdbLocation);
                    }
                    else
                    {
                        foreach (var contract in contractAssemblies)
                        {
                            Assembly facade = facadeGenerator.GenerateFacade(contract, seedCoreAssemblyRef, ignoreMissingTypes);
                            if (facade == null)
                            {
#if !COREFX
                                Debug.Assert(Environment.ExitCode != 0);
#endif
                                continue;
                            }

                            OutputFacadeToFile(facadePath, seedHost, facade, contract);
                        }
                    }
                }
            }
            catch (FacadeGenerationException ex)
            {
                Trace.TraceError(ex.Message);
#if !COREFX
                Debug.Assert(Environment.ExitCode != 0);
#endif
            }
        }
        private IEnumerable<MemberDependency> GetDependencies(string assemblyLocation)
        {
            using (var host = new HostEnvironment())
            {
                host.UnableToResolve += (s, e) =>
                {
                    string callingAssembly = e.Referrer.FullName();

                    // Try to get better information about the referrer. This may throw, but we don't want to crash even if we do.
                    try
                    {
                        callingAssembly = e.Referrer.GetAssemblyReference().AssemblyIdentity.Format();
                    }
                    catch { }

                    HashSet<string> newValue = new HashSet<string>();
                    newValue.Add(callingAssembly);
                    _unresolvedAssemblies.AddOrUpdate(e.Unresolved.Format(), newValue, (key, existingHashSet) =>
                    {
                        lock (existingHashSet)
                        {
                            existingHashSet.Add(callingAssembly);
                        }
                        return existingHashSet;
                    });
                };

                host.UnifyToLibPath = true;
                var cciAssembly = host.LoadAssembly(assemblyLocation);

                if (cciAssembly == null)
                {
                    _assembliesWithError.Add(assemblyLocation);
                    // error.
                    yield break;
                }


                // Extract the fileversion and assembly version from the assembly.
                FileVersionInfo fileInfo = FileVersionInfo.GetVersionInfo(assemblyLocation);
                AssemblyInfo assemblyInfo = new AssemblyInfo();
                assemblyInfo.AssemblyIdentity = cciAssembly.AssemblyIdentity.Format();
                assemblyInfo.FileVersion = fileInfo.FileVersion ?? string.Empty;
                assemblyInfo.TargetFrameworkMoniker = cciAssembly.GetTargetFrameworkMoniker();

                // remember this assembly as a user assembly.
                _userAssemblies.Add(assemblyInfo);

                // Identify references to members (generic and non-generic)
                foreach (var reference in cciAssembly.GetTypeMemberReferences())
                {
                    if (reference.ContainingType.GetAssemblyReference() == null)
                        continue;

                    string definedIn = reference.ContainingType.GetAssemblyReference().ContainingAssembly.AssemblyIdentity.Format();
                    // return the type
                    yield return new MemberDependency()
                    {
                        CallingAssembly = assemblyInfo,
                        MemberDocId = reference.ContainingType.DocId(),
                        DefinedInAssemblyIdentity = definedIn
                    };

                    //return the member
                    yield return new MemberDependency()
                    {
                        CallingAssembly = assemblyInfo,
                        MemberDocId = reference.DocId(),
                        TypeDocId = reference.ContainingType.DocId(),
                        DefinedInAssemblyIdentity = definedIn
                    };
                }

                // Identify references to types
                foreach (var refence in cciAssembly.GetTypeReferences())
                {
                    string definedIn = refence.GetAssemblyReference().ContainingAssembly.AssemblyIdentity.Format();
                    //return the type
                    yield return new MemberDependency()
                    {
                        CallingAssembly = assemblyInfo,
                        MemberDocId = refence.DocId(),
                        DefinedInAssemblyIdentity = definedIn
                    };
                }
            }
        }
Exemple #46
0
        private static IReadOnlyDictionary<string, IEnumerable<string>> GenerateDocIdTable(IEnumerable<IAssembly> contractAssemblies, string inclusionContracts)
        {
            Dictionary<string, HashSet<string>> mutableDocIdTable = new Dictionary<string, HashSet<string>>();
            foreach (IAssembly contractAssembly in contractAssemblies)
            {
                string simpleName = contractAssembly.AssemblyIdentity.Name.Value;
                if (mutableDocIdTable.ContainsKey(simpleName))
                    throw new FacadeGenerationException(string.Format("Multiple contracts named \"{0}\" specified on -contracts.", simpleName));
                mutableDocIdTable[simpleName] = new HashSet<string>(EnumerateDocIdsToForward(contractAssembly));
            }

            if (inclusionContracts != null)
            {
                foreach (string inclusionContractPath in HostEnvironment.SplitPaths(inclusionContracts))
                {
                    // Assembly identity conflicts are permitted and normal in the inclusion contract list so load each one in a throwaway host to avoid problems.
                    using (HostEnvironment inclusionHost = new HostEnvironment(new NameTable(), new InternFactory()))
                    {
                        IAssembly inclusionAssembly = inclusionHost.LoadAssemblyFrom(inclusionContractPath);
                        if (inclusionAssembly == null || inclusionAssembly is Dummy)
                            throw new FacadeGenerationException(string.Format("Could not load assembly \"{0}\".", inclusionContractPath));
                        string simpleName = inclusionAssembly.Name.Value;
                        HashSet<string> hashset;
                        if (!mutableDocIdTable.TryGetValue(simpleName, out hashset))
                        {
                            Trace.TraceWarning("An assembly named \"{0}\" was specified in the -include list but no contract was specified named \"{0}\". Ignoring.", simpleName);
                        }
                        else
                        {
                            foreach (string docId in EnumerateDocIdsToForward(inclusionAssembly))
                            {
                                hashset.Add(docId);
                            }
                        }
                    }
                }
            }

            Dictionary<string, IEnumerable<string>> docIdTable = new Dictionary<string, IEnumerable<string>>();
            foreach (KeyValuePair<string, HashSet<string>> kv in mutableDocIdTable)
            {
                string key = kv.Key;
                IEnumerable<string> sortedDocIds = kv.Value.OrderBy(s => s);
                docIdTable.Add(key, sortedDocIds);
            }
            return docIdTable;
        }
            public static Environment For(GeneralOptions options, Dictionary <string, IMethodAnalysis> methodAnalyzers, Dictionary <string, IClassAnalysis> classAnalyzers, HostEnvironment host)
            {
                var codeProvider    = CciILCodeProvider.CreateCodeProvider(host);
                var codeWriter      = CCI2Slicer.CreateSlicer(host);
                var metadataDecoder = codeProvider.MetaDataDecoder;
                var contractDecoder = codeProvider.ContractDecoder;

                return(new Environment(options, codeWriter, metadataDecoder, contractDecoder, methodAnalyzers, classAnalyzers));
            }
 public CalculatorServiceHost(HostEnvironment environment)
 {
     this.environment = environment;
 }
Exemple #49
0
        public override bool Execute()
        {
            HostEnvironment host = new();

            host.UnableToResolve += (sender, e) =>
                                    Log.LogWarning("Unable to resolve assembly '{0}' referenced by '{1}'.", e.Unresolved.ToString(), e.Referrer.ToString());

            host.UnifyToLibPath = true;
            if (!string.IsNullOrWhiteSpace(LibPath))
            {
                host.AddLibPaths(HostEnvironment.SplitPaths(LibPath));
            }

            IEnumerable <IAssembly> assemblies = host.LoadAssemblies(HostEnvironment.SplitPaths(Assembly));

            if (!assemblies.Any())
            {
                Log.LogError("ERROR: Failed to load any assemblies from '{0}'", Assembly);
                return(false);
            }

            string headerText      = GetHeaderText(HeaderFile, WriterType, SyntaxWriterType);
            bool   loopPerAssembly = Directory.Exists(OutputPath);

            if (loopPerAssembly)
            {
                foreach (IAssembly assembly in assemblies)
                {
                    using (TextWriter output = GetOutput(GetFilename(assembly, WriterType, SyntaxWriterType)))
                        using (IStyleSyntaxWriter syntaxWriter = GetSyntaxWriter(output, WriterType, SyntaxWriterType))
                        {
                            ICciWriter writer = null;
                            try
                            {
                                if (headerText != null)
                                {
                                    output.Write(headerText);
                                }

                                bool includeInternals = RespectInternals &&
                                                        assembly.Attributes.HasAttributeOfType(InternalsVisibleTypeName);
                                writer = GetWriter(output, syntaxWriter, includeInternals);
                                writer.WriteAssemblies(new IAssembly[] { assembly });
                            }
                            finally
                            {
                                if (writer is CSharpWriter csWriter)
                                {
                                    csWriter.Dispose();
                                }
                            }
                        }
                }
            }
            else
            {
                using (TextWriter output = GetOutput(OutputPath))
                    using (IStyleSyntaxWriter syntaxWriter = GetSyntaxWriter(output, WriterType, SyntaxWriterType))
                    {
                        ICciWriter writer = null;
                        try
                        {
                            if (headerText != null)
                            {
                                output.Write(headerText);
                            }

                            bool includeInternals = RespectInternals &&
                                                    assemblies.Any(assembly => assembly.Attributes.HasAttributeOfType(InternalsVisibleTypeName));
                            writer = GetWriter(output, syntaxWriter, includeInternals);
                            writer.WriteAssemblies(assemblies);
                        }
                        finally
                        {
                            if (writer is CSharpWriter csWriter)
                            {
                                csWriter.Dispose();
                            }
                        }
                    }
            }

            return(!Log.HasLoggedErrors);
        }
Exemple #50
0
 public StartHost(HostEnvironment environment, HostSettings settings)
     : this(environment, settings, null)
 {
 }
Exemple #51
0
 public CommandHost(HostEnvironment environment, HostSettings settings, int command)
 {
     _environment = environment;
     _settings    = settings;
     _command     = command;
 }
Exemple #52
0
        public static bool Execute(
            string seeds,
            string contracts,
            string facadePath,
            Version assemblyFileVersion               = null,
            bool clearBuildAndRevision                = false,
            bool ignoreMissingTypes                   = false,
            bool ignoreBuildAndRevisionMismatch       = false,
            bool buildDesignTimeFacades               = false,
            string inclusionContracts                 = null,
            ErrorTreatment seedLoadErrorTreatment     = ErrorTreatment.Default,
            ErrorTreatment contractLoadErrorTreatment = ErrorTreatment.Default,
            string[] seedTypePreferencesUnsplit       = null,
            bool forceZeroVersionSeeds                = false,
            bool producePdb = true,
            string partialFacadeAssemblyPath = null)
        {
            if (!Directory.Exists(facadePath))
            {
                Directory.CreateDirectory(facadePath);
            }

            var nameTable     = new NameTable();
            var internFactory = new InternFactory();

            try
            {
                Dictionary <string, string> seedTypePreferences = ParseSeedTypePreferences(seedTypePreferencesUnsplit);

                using (var contractHost = new HostEnvironment(nameTable, internFactory))
                    using (var seedHost = new HostEnvironment(nameTable, internFactory))
                    {
                        contractHost.LoadErrorTreatment = contractLoadErrorTreatment;
                        seedHost.LoadErrorTreatment     = seedLoadErrorTreatment;

                        var contractAssemblies = LoadAssemblies(contractHost, contracts);
                        IReadOnlyDictionary <string, IEnumerable <string> > docIdTable = GenerateDocIdTable(contractAssemblies, inclusionContracts);

                        IAssembly[] seedAssemblies = LoadAssemblies(seedHost, seeds).ToArray();

                        IAssemblyReference seedCoreAssemblyRef = ((Microsoft.Cci.Immutable.PlatformType)seedHost.PlatformType).CoreAssemblyRef;

                        if (forceZeroVersionSeeds)
                        {
                            // Create a deep copier, copy the seed assemblies, and zero out their versions.
                            var copier = new MetadataDeepCopier(seedHost);

                            for (int i = 0; i < seedAssemblies.Length; i++)
                            {
                                var mutableSeed = copier.Copy(seedAssemblies[i]);
                                mutableSeed.Version = new Version(0, 0, 0, 0);
                                // Copy the modified seed assembly back.
                                seedAssemblies[i] = mutableSeed;

                                if (mutableSeed.Name.UniqueKey == seedCoreAssemblyRef.Name.UniqueKey)
                                {
                                    seedCoreAssemblyRef = mutableSeed;
                                }
                            }
                        }

                        var typeTable       = GenerateTypeTable(seedAssemblies);
                        var facadeGenerator = new FacadeGenerator(seedHost, contractHost, docIdTable, typeTable, seedTypePreferences, clearBuildAndRevision, buildDesignTimeFacades, assemblyFileVersion);

                        if (partialFacadeAssemblyPath != null)
                        {
                            if (contractAssemblies.Count() != 1)
                            {
                                throw new FacadeGenerationException(
                                          "When partialFacadeAssemblyPath is specified, only exactly one corresponding contract assembly can be specified.");
                            }

                            IAssembly contractAssembly      = contractAssemblies.First();
                            IAssembly partialFacadeAssembly = seedHost.LoadAssembly(partialFacadeAssemblyPath);
                            if (contractAssembly.Name != partialFacadeAssembly.Name ||
                                contractAssembly.Version.Major != partialFacadeAssembly.Version.Major ||
                                contractAssembly.Version.Minor != partialFacadeAssembly.Version.Minor ||
                                (!ignoreBuildAndRevisionMismatch && contractAssembly.Version.Build != partialFacadeAssembly.Version.Build) ||
                                (!ignoreBuildAndRevisionMismatch && contractAssembly.Version.Revision != partialFacadeAssembly.Version.Revision) ||
                                contractAssembly.GetPublicKeyToken() != partialFacadeAssembly.GetPublicKeyToken())
                            {
                                throw new FacadeGenerationException(
                                          string.Format("The partial facade assembly's name, version, and public key token must exactly match the contract to be filled. Contract: {0}, Facade: {1}",
                                                        contractAssembly.AssemblyIdentity,
                                                        partialFacadeAssembly.AssemblyIdentity));
                            }

                            Assembly filledPartialFacade = facadeGenerator.GenerateFacade(contractAssembly, seedCoreAssemblyRef, ignoreMissingTypes, overrideContractAssembly: partialFacadeAssembly);

                            if (filledPartialFacade == null)
                            {
                                Trace.TraceError("Errors were encountered while generating the facade.");
                                return(false);
                            }

                            string pdbLocation = null;

                            if (producePdb)
                            {
                                string pdbFolder = Path.GetDirectoryName(partialFacadeAssemblyPath);
                                pdbLocation = Path.Combine(pdbFolder, contractAssembly.Name + ".pdb");
                                if (producePdb && !File.Exists(pdbLocation))
                                {
                                    pdbLocation = null;
                                    Trace.TraceWarning("No PDB file present for un-transformed partial facade. No PDB will be generated.");
                                }
                            }

                            OutputFacadeToFile(facadePath, seedHost, filledPartialFacade, contractAssembly, pdbLocation);
                        }
                        else
                        {
                            foreach (var contract in contractAssemblies)
                            {
                                Assembly facade = facadeGenerator.GenerateFacade(contract, seedCoreAssemblyRef, ignoreMissingTypes);
                                if (facade == null)
                                {
#if !COREFX
                                    Debug.Assert(Environment.ExitCode != 0);
#endif
                                    return(false);
                                }

                                OutputFacadeToFile(facadePath, seedHost, facade, contract);
                            }
                        }
                    }

                return(true);
            }
            catch (FacadeGenerationException ex)
            {
                Trace.TraceError(ex.Message);
#if !COREFX
                Debug.Assert(Environment.ExitCode != 0);
#endif
                return(false);
            }
        }
 public override void Apply(HostEnvironment settings)
 {
     Birch.XamarinForms.Hosts.BuildHost.CreateHost(settings);
 }
Exemple #54
0
 public IssueReport(HostEnvironment host)
 => this.host = host ?? throw new ArgumentNullException(nameof(host));
Exemple #55
0
 public static CCI2Slicer CreateSlicer(HostEnvironment host)
 {
     Contract.Requires(host != null);
     // MB: no singleton please
     return(new CCI2Slicer(host));
 }