예제 #1
0
        public static void Process(LinkerOptions options, out LinkContext context)
        {
            var pipeline = CreatePipeline (options);

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

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

            Run (pipeline, context);
        }
예제 #2
0
        public LinkerOptions CreateLinkerOptions()
        {
            var c   = app.Config <LinkerConfig>();
            var opt = new LinkerOptions();
            var svc = app.GetService <IPathService>();

            c.Directories.ForEach(d => opt.CodeBase.Directories.Add(svc.ResolvePathMacros(d)));
            opt.CodeBase.LookupStartupDirectory = c.LookupStartupDirectory;
            opt.ForceRecompile     = c.ForceRecompile;
            opt.NoWarnings         = c.NoWarnings;
            opt.WarningsAsErrors   = c.WarningsAsErrors;
            opt.SkipTimeStampCheck = c.SkipTimeStampCheck;
            return(opt);
        }
예제 #3
0
        public void LinkAssemblies(string main, ref List <string> assemblies, string output_dir, out MonoTouchLinkContext link_context)
        {
            if (Driver.Verbosity > 0)
            {
                Console.WriteLine("Linking {0} into {1} using mode '{2}'", main, output_dir, App.LinkMode);
            }

            var cache    = Resolver.ToResolverCache();
            var resolver = cache != null
                                ? new AssemblyResolver(cache)
                                : new AssemblyResolver();

            resolver.AddSearchDirectory(Resolver.RootDirectory);
            resolver.AddSearchDirectory(Resolver.FrameworkDirectory);

            var options = new LinkerOptions {
                MainAssembly      = Resolver.Load(main),
                OutputDirectory   = output_dir,
                LinkMode          = App.LinkMode,
                Resolver          = resolver,
                SkippedAssemblies = App.LinkSkipped,
                I18nAssemblies    = App.I18n,
                LinkSymbols       = true,
                LinkAway          = App.LinkAway,
                ExtraDefinitions  = App.Definitions,
                Device            = App.IsDeviceBuild,
                // by default we keep the code to ensure we're executing on the UI thread (for UI code) for debug builds
                // but this can be overridden to either (a) remove it from debug builds or (b) keep it in release builds
                EnsureUIThread   = App.ThreadCheck.HasValue ? App.ThreadCheck.Value : App.EnableDebug,
                OldRegistrar     = (App.Registrar == RegistrarMode.LegacyDynamic || App.Registrar == RegistrarMode.LegacyStatic),
                DebugBuild       = App.EnableDebug,
                Arch             = Is64Build ? 8 : 4,
                IsDualBuild      = App.IsDualBuild,
                Unified          = App.IsUnified,
                DumpDependencies = App.LinkerDumpDependencies,
                RuntimeOptions   = App.RuntimeOptions
            };

            MonoTouch.Tuner.Linker.Process(options, out link_context, out assemblies);

            // reset resolver
            foreach (var file in assemblies)
            {
                /*				var assembly = */Resolver.Load(file);
                // FIXME assembly.MainModule.AssemblyResolver = Resolver;
            }
            Driver.Watch("Link Assemblies", 1);
        }
예제 #4
0
 static LinkContext CreateLinkContext(LinkerOptions options, Pipeline pipeline)
 {
     var context = new LinkContext (pipeline, options.Resolver);
     if (options.DumpDependencies) {
         var prepareDependenciesDump = context.Annotations.GetType ().GetMethod ("PrepareDependenciesDump", new Type[] {});
         if (prepareDependenciesDump != null)
             prepareDependenciesDump.Invoke (context.Annotations, null);
     }
     context.LogInternalExceptions = Xamarin.Android.Tasks.MonoAndroidHelper.LogInternalExceptions;
     context.CoreAction = AssemblyAction.Link;
     context.LinkSymbols = true;
     context.SymbolReaderProvider = new MdbReaderProvider ();
     context.SymbolWriterProvider = new MdbWriterProvider ();
     context.OutputDirectory = options.OutputDirectory;
     return context;
 }
예제 #5
0
파일: Driver.cs 프로젝트: embtest/CppSharp
        public bool ParseLibraries()
        {
            ClangParser.LibraryParsed += OnFileParsed;
            foreach (var module in Options.Modules)
            {
                using (var linkerOptions = new LinkerOptions())
                {
                    foreach (var libraryDir in module.LibraryDirs)
                    {
                        linkerOptions.AddLibraryDirs(libraryDir);
                    }

                    foreach (string library in module.Libraries)
                    {
                        if (Context.Symbols.Libraries.Any(l => l.FileName == library))
                        {
                            continue;
                        }
                        linkerOptions.AddLibraries(library);
                    }

                    using (var res = ClangParser.ParseLibrary(linkerOptions))
                    {
                        if (res.Kind != ParserResultKind.Success)
                        {
                            continue;
                        }

                        for (uint i = 0; i < res.LibrariesCount; i++)
                        {
                            Context.Symbols.Libraries.Add(ClangParser.ConvertLibrary(res.GetLibraries(i)));
                        }
                    }
                }
            }
            ClangParser.LibraryParsed -= OnFileParsed;

            Context.Symbols.IndexSymbols();
            SortModulesByDependencies();

            return(true);
        }
예제 #6
0
        private static LinkerOptions CreateLinkerOptions()
        {
            var linkOpt = new LinkerOptions
            {
                ForceRecompile     = opt.ForceRecompile,
                SkipTimeStampCheck = opt.SkipTimeStampCheck,
                WarningsAsErrors   = opt.LinkerWarningsAsErrors,
                NoWarnings         = opt.LinkerNoWarnings
            };

            linkOpt.CodeBase.LookupStartupDirectory = !opt.IgnoreStartupDirectory;

            foreach (var s in opt.ReferencePaths)
            {
                linkOpt.CodeBase.Directories.Add(s);
            }

            linkOpt.CodeBase.Directories.Add(Environment.CurrentDirectory);
            return(linkOpt);
        }
예제 #7
0
        static Pipeline CreatePipeline(LinkerOptions options)
        {
            var pipeline = new Pipeline ();

            if (options.LinkNone) {
                pipeline.AppendStep (new FixAbstractMethodsStep ());
                pipeline.AppendStep (new OutputStep ());
                return pipeline;
            }

            pipeline.AppendStep (new LoadReferencesStep ());

            if (options.I18nAssemblies != I18nAssemblies.None)
                pipeline.AppendStep (new LoadI18nAssemblies (options.I18nAssemblies));

            pipeline.AppendStep (new BlacklistStep ());

            foreach (var desc in options.LinkDescriptions)
                pipeline.AppendStep (new ResolveFromXmlStep (new XPathDocument (desc)));

            pipeline.AppendStep (new CustomizeActions (options.LinkSdkOnly, options.SkippedAssemblies));

            pipeline.AppendStep (new TypeMapStep ());

            // monodroid tuner steps
            pipeline.AppendStep (new SubStepDispatcher {
                new ApplyPreserveAttribute (),
                new PreserveExportedTypes (),
                new RemoveSecurity (),
                new MarkJavaObjects (),
                new PreserveJavaExceptions (),
                new PreserveJavaTypeRegistrations (),
                new PreserveApplications (),
                new RemoveAttributes (),
                new PreserveDynamicTypes (),
                new PreserveSoapHttpClients (),
                new PreserveTypeConverters (),
                new PreserveLinqExpressions (),
                new PreserveRuntimeSerialization (),
            });

            pipeline.AppendStep (new PreserveCrypto ());
            pipeline.AppendStep (new PreserveCode ());

            pipeline.AppendStep (new RemoveLibraryResourceZip ());
            pipeline.AppendStep (new RemoveResources (options.I18nAssemblies)); // remove collation tables
            // end monodroid specific

            pipeline.AppendStep (new FixAbstractMethodsStep ());
            pipeline.AppendStep (new MonoDroidMarkStep ());
            pipeline.AppendStep (new SweepStep ());
            pipeline.AppendStep (new CleanStep ());
            // monodroid tuner steps
            if (!string.IsNullOrWhiteSpace (options.ProguardConfiguration))
                pipeline.AppendStep (new GenerateProguardConfiguration (options.ProguardConfiguration));
            // end monodroid specific
            pipeline.AppendStep (new RegenerateGuidStep ());
            pipeline.AppendStep (new OutputStep ());

            return pipeline;
        }
 public CoreOptimizeGeneratedCode(LinkerOptions options)
 {
     Options = options;
 }
예제 #9
0
        protected override string GenerateCommandLineCommands()
        {
            var           args          = GenerateCommandLineArguments();
            List <string> unescapedArgs = new List <string> ();

            TargetArchitecture architectures;

            if (string.IsNullOrEmpty(Architectures) || !Enum.TryParse(Architectures, out architectures))
            {
                architectures = TargetArchitecture.Default;
            }

            if (architectures == TargetArchitecture.ARMv6)
            {
                Log.LogError(MSBStrings.E0053);
                return(null);
            }

            args.AddQuotedLine((SdkIsSimulator ? "--sim=" : "--dev=") + Path.GetFullPath(AppBundleDir));

            args.AddQuotedLine($"--executable={ExecutableName}");

            if (IsAppExtension)
            {
                args.AddLine("--extension");
            }

            if (Debug)
            {
                if (FastDev && !SdkIsSimulator)
                {
                    args.AddLine("--fastdev");
                }
            }

            if (LinkerDumpDependencies)
            {
                args.AddLine("--linkerdumpdependencies");
            }

            if (!string.IsNullOrEmpty(Interpreter))
            {
                args.AddLine($"--interpreter={Interpreter}");
            }

            switch (LinkMode.ToLowerInvariant())
            {
            case "sdkonly": args.AddLine("--linksdkonly"); break;

            case "none":    args.AddLine("--nolink"); break;
            }

            args.AddQuotedLine($"--sdk={SdkVersion}");

            if (UseFloat32 /* We want to compile 32-bit floating point code to use 32-bit floating point operations */)
            {
                args.AddLine("--aot-options=-O=float32");
            }
            else
            {
                args.AddLine("--aot-options=-O=-float32");
            }

            if (LinkDescriptions != null)
            {
                foreach (var desc in LinkDescriptions)
                {
                    args.AddQuotedLine($"--xml={desc.ItemSpec}");
                }
            }

            if (EnableBitcode)
            {
                switch (Platform)
                {
                case ApplePlatform.WatchOS:
                    args.AddLine("--bitcode=full");
                    break;

                case ApplePlatform.TVOS:
                    args.AddLine("--bitcode=asmonly");
                    break;

                default:
                    throw new InvalidOperationException(string.Format("Bitcode is currently not supported on {0}.", Platform));
                }
            }

            string thumb = UseThumb && UseLlvm ? "+thumb2" : "";
            string llvm  = UseLlvm ? "+llvm" : "";
            string abi   = "";

            if (SdkIsSimulator)
            {
                if (architectures.HasFlag(TargetArchitecture.i386))
                {
                    abi += (abi.Length > 0 ? "," : "") + "i386";
                }

                if (architectures.HasFlag(TargetArchitecture.x86_64))
                {
                    abi += (abi.Length > 0 ? "," : "") + "x86_64";
                }

                if (string.IsNullOrEmpty(abi))
                {
                    architectures = TargetArchitecture.i386;
                    abi           = "i386";
                }
            }
            else
            {
                if (architectures == TargetArchitecture.Default)
                {
                    architectures = TargetArchitecture.ARMv7;
                }

                if (architectures.HasFlag(TargetArchitecture.ARMv7))
                {
                    abi += (abi.Length > 0 ? "," : "") + "armv7" + llvm + thumb;
                }

                if (architectures.HasFlag(TargetArchitecture.ARMv7s))
                {
                    abi += (abi.Length > 0 ? "," : "") + "armv7s" + llvm + thumb;
                }

                if (architectures.HasFlag(TargetArchitecture.ARM64))
                {
                    // Note: ARM64 does not have thumb.
                    abi += (abi.Length > 0 ? "," : "") + "arm64" + llvm;
                }

                if (architectures.HasFlag(TargetArchitecture.ARMv7k))
                {
                    abi += (abi.Length > 0 ? "," : "") + "armv7k" + llvm;
                }

                if (architectures.HasFlag(TargetArchitecture.ARM64_32))
                {
                    abi += (abi.Length > 0 ? "," : "") + "arm64_32" + llvm;
                }

                if (string.IsNullOrEmpty(abi))
                {
                    abi = "armv7" + llvm + thumb;
                }
            }

            // Output the CompiledArchitectures
            CompiledArchitectures = architectures.ToString();

            args.AddLine($"--abi={abi}");

            // output symbols to preserve when stripping
            args.AddQuotedLine($"--symbollist={Path.GetFullPath (SymbolsList)}");

            // don't have mtouch generate the dsyms...
            args.AddLine("--dsym=no");

            var gcc = new LinkerOptions();

            if (!string.IsNullOrEmpty(ExtraArgs))
            {
                var    extraArgs = CommandLineArgumentBuilder.Parse(ExtraArgs);
                var    target    = MainAssembly.ItemSpec;
                string projectDir;

                if (ProjectDir.StartsWith("~/", StringComparison.Ordinal))
                {
                    // Note: Since the Visual Studio plugin doesn't know the user's home directory on the Mac build host,
                    // it simply uses paths relative to "~/". Expand these paths to their full path equivalents.
                    var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

                    projectDir = Path.Combine(home, ProjectDir.Substring(2));
                }
                else
                {
                    projectDir = ProjectDir;
                }

                var customTags = new Dictionary <string, string> (StringComparer.OrdinalIgnoreCase)
                {
                    { "projectdir", projectDir },
                    // Apparently msbuild doesn't propagate the solution path, so we can't get it.
                    // { "solutiondir",  proj.ParentSolution != null ? proj.ParentSolution.BaseDirectory : proj.BaseDirectory },
                    { "appbundledir", AppBundleDir },
                    { "targetpath", Path.Combine(Path.GetDirectoryName(target), Path.GetFileName(target)) },
                    { "targetdir", Path.GetDirectoryName(target) },
                    { "targetname", Path.GetFileName(target) },
                    { "targetext", Path.GetExtension(target) },
                };

                for (int i = 0; i < extraArgs.Length; i++)
                {
                    var argument   = extraArgs[i];
                    int startIndex = 0;

                    while (argument.Length > startIndex && argument[startIndex] == '-')
                    {
                        startIndex++;
                    }

                    int endIndex = startIndex;
                    while (endIndex < argument.Length && argument[endIndex] != '=')
                    {
                        endIndex++;
                    }

                    int length = endIndex - startIndex;

                    if (length == 9 && string.CompareOrdinal(argument, startIndex, "gcc_flags", 0, 9) == 0)
                    {
                        // user-defined -gcc_flags argument
                        string flags = null;

                        if (endIndex < extraArgs[i].Length)
                        {
                            flags = Unquote(argument, endIndex + 1);
                        }
                        else if (i + 1 < extraArgs.Length)
                        {
                            flags = extraArgs[++i];
                        }

                        if (!string.IsNullOrEmpty(flags))
                        {
                            var gccArgs = CommandLineArgumentBuilder.Parse(flags);

                            for (int j = 0; j < gccArgs.Length; j++)
                            {
                                gcc.Arguments.Add(StringParserService.Parse(gccArgs[j], customTags));
                            }
                        }
                    }
                    else
                    {
                        // other user-defined mtouch arguments
                        unescapedArgs.Add(StringParserService.Parse(argument, customTags));
                    }
                }
            }

            gcc.BuildNativeReferenceFlags(Log, NativeReferences);
            gcc.Arguments.AddQuoted(LinkNativeCodeTaskBase.GetEmbedEntitlementsInExecutableLinkerFlags(CompiledEntitlements));

            foreach (var framework in gcc.Frameworks)
            {
                args.AddQuotedLine($"--framework={Path.GetFullPath (framework)}");
            }

            foreach (var framework in gcc.WeakFrameworks)
            {
                args.AddQuotedLine($"--weak-framework={Path.GetFullPath (framework)}");
            }

            if (gcc.Cxx)
            {
                args.AddLine("--cxx");
            }

            if (gcc.Arguments.Length > 0)
            {
                unescapedArgs.Add($"--gcc_flags={gcc.Arguments.ToString ()}");
            }

            foreach (var asm in References)
            {
                if (IsFrameworkItem(asm))
                {
                    args.AddQuotedLine($"--reference={ResolveFrameworkFile (asm.ItemSpec)}");
                }
                else
                {
                    args.AddQuotedLine($"--reference={Path.GetFullPath (asm.ItemSpec)}");
                }
            }

            foreach (var ext in AppExtensionReferences)
            {
                args.AddQuotedLine($"--app-extension={Path.GetFullPath (ext.ItemSpec)}");
            }

            if (!string.IsNullOrWhiteSpace(License))
            {
                args.AddLine($"--license={License}");
            }

            return(args.CreateResponseFile(this, ResponseFilePath, unescapedArgs));
        }
 public CoreHttpMessageHandler(LinkerOptions options)
 {
     Options = options;
 }
예제 #11
0
        static Pipeline CreatePipeline(LinkerOptions options)
        {
            var pipeline = new Pipeline ();

            pipeline.AppendStep (options.LinkMode == LinkMode.None ? new LoadOptionalReferencesStep () : new LoadReferencesStep ());

            if (options.I18nAssemblies != I18nAssemblies.None)
                pipeline.AppendStep (new LoadI18nAssemblies (options.I18nAssemblies));

            // that must be done early since the XML files can "add" new assemblies [#15878]
            // and some of the assemblies might be (directly or referenced) SDK assemblies
            foreach (string definition in options.ExtraDefinitions)
                pipeline.AppendStep (GetResolveStep (definition));

            if (options.LinkMode != LinkMode.None)
                pipeline.AppendStep (new BlacklistStep ());

            pipeline.AppendStep (new CustomizeMacActions (options.LinkMode, options.SkippedAssemblies));

            // We need to store the Field attribute in annotations, since it may end up removed.
            pipeline.AppendStep (new ProcessExportedFields ());

            if (options.LinkMode != LinkMode.None) {
                pipeline.AppendStep (new TypeMapStep ());

                pipeline.AppendStep (new SubStepDispatcher {
                    new ApplyPreserveAttribute (),
                    new CoreRemoveSecurity (),
                    new OptimizeGeneratedCodeSubStep (options.EnsureUIThread),
                    new CoreRemoveAttributes (),
                    new CoreHttpMessageHandler (options),
                    new CoreTlsProviderStep (options),
                    new MarkNSObjects (),
                });

                pipeline.AppendStep (new MonoMacPreserveCode (options));
                pipeline.AppendStep (new PreserveCrypto ());

                pipeline.AppendStep (new MonoMacMarkStep ());
                pipeline.AppendStep (new MacRemoveResources (options));
                pipeline.AppendStep (new MobileSweepStep ());
                pipeline.AppendStep (new CleanStep ());

                pipeline.AppendStep (new MonoMacNamespaces ());
                pipeline.AppendStep (new RemoveSelectors ());

                pipeline.AppendStep (new RegenerateGuidStep ());
            }

            pipeline.AppendStep (new ListExportedSymbols ());

            pipeline.AppendStep (new OutputStep ());

            return pipeline;
        }
예제 #12
0
 static LinkContext CreateLinkContext(LinkerOptions options, Pipeline pipeline)
 {
     var context = new MonoMacLinkContext (pipeline, options.Resolver);
     context.CoreAction = AssemblyAction.Link;
     context.LinkSymbols = options.LinkSymbols;
     if (options.LinkSymbols) {
         context.SymbolReaderProvider = new MdbReaderProvider ();
         context.SymbolWriterProvider = new MdbWriterProvider ();
     }
     context.OutputDirectory = options.OutputDirectory;
     return context;
 }
예제 #13
0
        bool Execute(DirectoryAssemblyResolver res)
        {
            // Put every assembly we'll need in the resolver
            foreach (var assembly in ResolvedAssemblies)
            {
                res.Load(Path.GetFullPath(assembly.ItemSpec));
            }

            var resolver = new AssemblyResolver(res.ToResolverCache());

            // Set up for linking
            var options = new LinkerOptions();

            options.MainAssembly     = res.GetAssembly(MainAssembly);
            options.OutputDirectory  = Path.GetFullPath(OutputDirectory);
            options.LinkSdkOnly      = string.Compare(LinkMode, "SdkOnly", true) == 0;
            options.LinkNone         = false;
            options.Resolver         = resolver;
            options.LinkDescriptions = LinkDescriptions.Select(item => Path.GetFullPath(item.ItemSpec)).ToArray();
            options.I18nAssemblies   = Linker.ParseI18nAssemblies(I18nAssemblies);
            if (!options.LinkSdkOnly)
            {
                options.RetainAssemblies = GetRetainAssemblies(res);
            }
            options.DumpDependencies          = DumpDependencies;
            options.HttpClientHandlerType     = HttpClientHandlerType;
            options.TlsProvider               = TlsProvider;
            options.PreserveJniMarshalMethods = PreserveJniMarshalMethods;
            options.DeterministicOutput       = Deterministic;

            var skiplist = new List <string> ();

            if (string.Compare(UseSharedRuntime, "true", true) == 0)
            {
                skiplist.AddRange(Profile.SharedRuntimeAssemblies.Where(a => a.EndsWith(".dll")).Select(a => Path.GetFileNameWithoutExtension(a)));
            }

            // Add LinkSkip options
            if (!string.IsNullOrWhiteSpace(LinkSkip))
            {
                skiplist.AddRange(LinkSkip.Split(',', ';'));
            }

            options.SkippedAssemblies = skiplist;

            if (EnableProguard)
            {
                options.ProguardConfiguration = ProguardConfiguration;
            }

            // Link!
            try {
                LinkContext link_context;
                Linker.Process(options, this, out link_context);

                foreach (var assembly in ResolvedAssemblies)
                {
                    var copysrc             = assembly.ItemSpec;
                    var filename            = Path.GetFileName(assembly.ItemSpec);
                    var assemblyDestination = Path.Combine(OutputDirectory, filename);

                    if (!MonoAndroidHelper.IsForceRetainedAssembly(filename))
                    {
                        continue;
                    }

                    MonoAndroidHelper.CopyAssemblyAndSymbols(copysrc, assemblyDestination);
                }
            } catch (ResolutionException ex) {
                Diagnostic.Error(2006, ex, "Could not resolve reference to '{0}' (defined in assembly '{1}') with scope '{2}'. When the scope is different from the defining assembly, it usually means that the type is forwarded.", ex.Member, ex.Member.Module.Assembly, ex.Scope);
            }

            return(true);
        }
예제 #14
0
 public CoreTlsProviderStep(LinkerOptions options)
 {
     Options = options;
 }
예제 #15
0
파일: Program.cs 프로젝트: ngoffee/ela
        static int Run(string file, string outputFile)
        {
            Console.Write("\r\nGenerating documentation file: {0}...", outputFile);

            var fi  = new FileInfo(file);
            var doc = default(Doc);

            using (var sr = new StreamReader(file))
            {
                var lst  = new List <String>();
                var line = String.Empty;

                while ((line = sr.ReadLine()) != null)
                {
                    lst.Add(line);
                }

                var p = new DocParser();
                doc = p.Parse(lst.ToArray());
            }

            var gen  = default(HtmGenerator);
            var lopt = new LinkerOptions();
            var copt = new CompilerOptions {
                Prelude = "prelude"
            };

            ConfigurationManager.AppSettings["refs"].Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
            .ToList().ForEach(s => lopt.CodeBase.Directories.Add(s));

            if (!String.IsNullOrEmpty(doc.File) && doc.File.Trim(' ').Length != 0)
            {
                var elaFile = new FileInfo(Path.Combine(fi.DirectoryName, doc.File));

                if (!elaFile.Exists)
                {
                    foreach (var d in lopt.CodeBase.Directories)
                    {
                        elaFile = new FileInfo(Path.Combine(d, doc.File));

                        if (elaFile.Exists)
                        {
                            break;
                        }
                    }
                }

                var elap = new ElaParser();
                var res  = elap.Parse(elaFile);

                if (!res.Success)
                {
                    res.Messages.ToList().ForEach(m => Console.WriteLine("\r\n" + m));
                    return(-1);
                }

                lopt.CodeBase.Directories.Add(elaFile.Directory.FullName);
                var lnk  = new ElaIncrementalLinker(lopt, copt, new ModuleFileInfo(elaFile.FullName));
                var lres = lnk.Build();

                if (!lres.Success)
                {
                    lres.Messages.ToList().ForEach(m => Console.Write("\r\n" + m));
                    return(-1);
                }

                var vm = new ElaMachine(lres.Assembly);
                vm.Run();
                gen = new HtmGenerator(res.Program, doc, lnk, vm);
            }
            else
            {
                var lnk = new ElaIncrementalLinker(lopt, copt);
                gen = new HtmGenerator(null, doc, lnk, null);
            }

            var src = gen.Generate();

            var outFi = new FileInfo(outputFile);

            if (!outFi.Directory.Exists)
            {
                outFi.Directory.Create();
            }

            using (var fs = new StreamWriter(File.Create(outputFile)))
                fs.Write(src);

            Console.Write(" Done");
            return(0);
        }
예제 #16
0
        public void GivenAnInputObjectWithIncorrectExtensionCheckThatParseThrowsAnInvalidInputObjectException()
        {
            var args = new string[] { "MyObject.obj" };

            Assert.Throws <InvalidObjectExtensionException>(() => LinkerOptions.Parse(args));
        }
예제 #17
0
        public void GivenEmptyArgumentListCheckThatParseThrowsANoInputObjectsException()
        {
            var args = new string[] { };

            Assert.Throws <NoInputObjectsException>(() => LinkerOptions.Parse(args));
        }
예제 #18
0
        public void GivenArgumentListWithIncompleteOOptionCheckThatIncompleteArgumentExceptionIsThrown()
        {
            var args = new string[] { "AnObject.mob", "-o" };

            Assert.Throws <IncompleteArgumentException>(() => LinkerOptions.Parse(args));
        }
예제 #19
0
        bool Execute(DirectoryAssemblyResolver res)
        {
            // Put every assembly we'll need in the resolver
            foreach (var assembly in ResolvedAssemblies)
            {
                res.Load(Path.GetFullPath(assembly.ItemSpec));
            }

            var resolver = new AssemblyResolver(res.ToResolverCache());

            // Set up for linking
            var options = new LinkerOptions();

            options.MainAssembly     = res.GetAssembly(MainAssembly);
            options.OutputDirectory  = Path.GetFullPath(OutputDirectory);
            options.LinkSdkOnly      = string.Compare(LinkMode, "SdkOnly", true) == 0;
            options.LinkNone         = string.Compare(LinkMode, "None", true) == 0;
            options.Resolver         = resolver;
            options.LinkDescriptions = LinkDescriptions.Select(item => Path.GetFullPath(item.ItemSpec)).ToArray();
            options.I18nAssemblies   = Linker.ParseI18nAssemblies(I18nAssemblies);
            if (!options.LinkSdkOnly)
            {
                options.RetainAssemblies = GetRetainAssemblies(res);
            }
            options.DumpDependencies          = DumpDependencies;
            options.HttpClientHandlerType     = HttpClientHandlerType;
            options.TlsProvider               = TlsProvider;
            options.PreserveJniMarshalMethods = PreserveJniMarshalMethods;

            var skiplist = new List <string> ();

            if (string.Compare(UseSharedRuntime, "true", true) == 0)
            {
                skiplist.AddRange(Profile.SharedRuntimeAssemblies.Where(a => a.EndsWith(".dll")).Select(a => Path.GetFileNameWithoutExtension(a)));
            }
            if (!string.IsNullOrWhiteSpace(LinkOnlyNewerThan) && File.Exists(LinkOnlyNewerThan))
            {
                var newerThan   = File.GetLastWriteTime(LinkOnlyNewerThan);
                var skipOldOnes = ResolvedAssemblies.Where(a => File.GetLastWriteTime(a.ItemSpec) < newerThan);
                foreach (var old in skipOldOnes)
                {
                    Log.LogMessage(MBF.MessageImportance.Low, "  Skip linking unchanged file: " + old.ItemSpec);
                }
                skiplist = skipOldOnes.Select(a => Path.GetFileNameWithoutExtension(a.ItemSpec)).Concat(skiplist).ToList();
            }

            // Add LinkSkip options
            if (!string.IsNullOrWhiteSpace(LinkSkip))
            {
                foreach (var assembly in LinkSkip.Split(',', ';'))
                {
                    skiplist.Add(assembly);
                }
            }

            options.SkippedAssemblies = skiplist;

            if (EnableProguard)
            {
                options.ProguardConfiguration = ProguardConfiguration;
            }

            // Link!
            try {
                LinkContext link_context;
                Linker.Process(options, this, out link_context);

                var copydst = OptionalDestinationDirectory ?? OutputDirectory;

                foreach (var assembly in ResolvedAssemblies)
                {
                    var copysrc             = assembly.ItemSpec;
                    var filename            = Path.GetFileName(assembly.ItemSpec);
                    var assemblyDestination = Path.Combine(copydst, filename);

                    if (options.LinkNone)
                    {
                        if (skiplist.Any(s => Path.GetFileNameWithoutExtension(filename) == s))
                        {
                            // For skipped assemblies, skip if there is existing file in the destination.
                            // We cannot just copy the linker output from *current* run output, because
                            // it always renew the assemblies, in *different* binary values, whereas
                            // the dll in the OptionalDestinationDirectory must retain old and unchanged.
                            if (File.Exists(assemblyDestination))
                            {
                                MonoAndroidHelper.SetLastAccessAndWriteTimeUtc(assemblyDestination, DateTime.UtcNow, Log);
                                continue;
                            }
                        }
                        else
                        {
                            // Prefer fixup assemblies if exists, otherwise just copy the original.
                            copysrc = Path.Combine(OutputDirectory, filename);
                            copysrc = File.Exists(copysrc) ? copysrc : assembly.ItemSpec;
                        }
                    }
                    else if (!MonoAndroidHelper.IsForceRetainedAssembly(filename))
                    {
                        continue;
                    }

                    if (MonoAndroidHelper.CopyIfChanged(copysrc, assemblyDestination))
                    {
                        MonoAndroidHelper.SetLastAccessAndWriteTimeUtc(assemblyDestination, DateTime.UtcNow, Log);
                    }
                    try {
                        var mdbDestination = assemblyDestination + ".mdb";
                        if (MonoAndroidHelper.CopyIfChanged(assembly.ItemSpec + ".mdb", mdbDestination))
                        {
                            MonoAndroidHelper.SetLastAccessAndWriteTimeUtc(mdbDestination, DateTime.UtcNow, Log);
                        }
                    } catch (Exception) {                     // skip it, mdb sometimes fails to read and it's optional
                    }
                    var pdb = Path.ChangeExtension(copysrc, "pdb");
                    if (File.Exists(pdb) && Files.IsPortablePdb(pdb))
                    {
                        var pdbDestination = Path.ChangeExtension(Path.Combine(copydst, filename), "pdb");
                        if (MonoAndroidHelper.CopyIfChanged(pdb, pdbDestination))
                        {
                            MonoAndroidHelper.SetLastAccessAndWriteTimeUtc(pdbDestination, DateTime.UtcNow, Log);
                        }
                    }
                }
            } catch (ResolutionException ex) {
                Diagnostic.Error(2006, ex, "Could not resolve reference to '{0}' (defined in assembly '{1}') with scope '{2}'. When the scope is different from the defining assembly, it usually means that the type is forwarded.", ex.Member, ex.Member.Module.Assembly, ex.Scope);
            }

            return(true);
        }
예제 #20
0
        public static void Process(LinkerOptions options, out LinkContext context, out List<string> assemblies)
        {
            switch (options.TargetFramework.Identifier) {
            case "Xamarin.Mac":
                Profile.Current = new MacMobileProfile (options.Architecture == "x86_64" ? 64 : 32);
                break;
            default:
                Profile.Current = new MonoMacProfile ();
                break;
            }
            Namespaces.Initialize ();

            var pipeline = CreatePipeline (options);

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

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

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

            assemblies = ListAssemblies (context);
        }
예제 #21
0
        public override bool Execute()
        {
            Log.LogDebugMessage("LinkAssemblies Task");
            Log.LogDebugMessage("  UseSharedRuntime: {0}", UseSharedRuntime);
            Log.LogDebugMessage("  MainAssembly: {0}", MainAssembly);
            Log.LogDebugMessage("  OutputDirectory: {0}", OutputDirectory);
            Log.LogDebugMessage("  OptionalDestinationDirectory: {0}", OptionalDestinationDirectory);
            Log.LogDebugMessage("  I18nAssemblies: {0}", I18nAssemblies);
            Log.LogDebugMessage("  LinkMode: {0}", LinkMode);
            Log.LogDebugMessage("  LinkSkip: {0}", LinkSkip);
            Log.LogDebugTaskItems("  LinkDescriptions:", LinkDescriptions);
            Log.LogDebugTaskItems("  ResolvedAssemblies:", ResolvedAssemblies);
            Log.LogDebugMessage("  EnableProguard: {0}", EnableProguard);
            Log.LogDebugMessage("  ProguardConfiguration: {0}", ProguardConfiguration);
            Log.LogDebugMessage("  DumpDependencies: {0}", DumpDependencies);
            Log.LogDebugMessage("  LinkOnlyNewerThan: {0}", LinkOnlyNewerThan);

            var res = new DirectoryAssemblyResolver(Log.LogWarning, loadDebugSymbols: false);

            // Put every assembly we'll need in the resolver
            foreach (var assembly in ResolvedAssemblies)
            {
                res.Load(Path.GetFullPath(assembly.ItemSpec));
            }

            var resolver = new AssemblyResolver(res.ToResolverCache());

            // Set up for linking
            var options = new LinkerOptions();

            options.MainAssembly     = res.GetAssembly(MainAssembly);
            options.OutputDirectory  = Path.GetFullPath(OutputDirectory);
            options.LinkSdkOnly      = string.Compare(LinkMode, "SdkOnly", true) == 0;
            options.LinkNone         = string.Compare(LinkMode, "None", true) == 0;
            options.Resolver         = resolver;
            options.LinkDescriptions = LinkDescriptions.Select(item => Path.GetFullPath(item.ItemSpec)).ToArray();
            options.I18nAssemblies   = Linker.ParseI18nAssemblies(I18nAssemblies);
            if (!options.LinkSdkOnly)
            {
                options.RetainAssemblies = GetRetainAssemblies(res);
            }
            options.DumpDependencies = DumpDependencies;

            var skiplist = new List <string> ();

            if (string.Compare(UseSharedRuntime, "true", true) == 0)
            {
                skiplist.AddRange(Profile.SharedRuntimeAssemblies.Where(a => a.EndsWith(".dll")).Select(a => Path.GetFileNameWithoutExtension(a)));
            }
            if (!string.IsNullOrWhiteSpace(LinkOnlyNewerThan) && File.Exists(LinkOnlyNewerThan))
            {
                var newerThan   = File.GetLastWriteTime(LinkOnlyNewerThan);
                var skipOldOnes = ResolvedAssemblies.Where(a => File.GetLastWriteTime(a.ItemSpec) < newerThan);
                foreach (var old in skipOldOnes)
                {
                    Log.LogMessage(MessageImportance.Low, "  Skip linking unchanged file: " + old.ItemSpec);
                }
                skiplist = skipOldOnes.Select(a => Path.GetFileNameWithoutExtension(a.ItemSpec)).Concat(skiplist).ToList();
            }

            // Add LinkSkip options
            if (!string.IsNullOrWhiteSpace(LinkSkip))
            {
                foreach (var assembly in LinkSkip.Split(',', ';'))
                {
                    skiplist.Add(assembly);
                }
            }

            options.SkippedAssemblies = skiplist;

            if (EnableProguard)
            {
                options.ProguardConfiguration = ProguardConfiguration;
            }

            // Link!
            try {
                LinkContext link_context;
                Linker.Process(options, out link_context);

                var copydst = OptionalDestinationDirectory ?? OutputDirectory;

                foreach (var assembly in ResolvedAssemblies)
                {
                    var copysrc  = assembly.ItemSpec;
                    var filename = Path.GetFileName(assembly.ItemSpec);

                    if (options.LinkNone)
                    {
                        if (skiplist.Any(s => Path.GetFileNameWithoutExtension(filename) == s))
                        {
                            // For skipped assemblies, skip if there is existing file in the destination.
                            // We cannot just copy the linker output from *current* run output, because
                            // it always renew the assemblies, in *different* binary values, whereas
                            // the dll in the OptionalDestinationDirectory must retain old and unchanged.
                            if (File.Exists(Path.Combine(copydst, filename)))
                            {
                                continue;
                            }
                            copysrc = assembly.ItemSpec;
                        }
                        else
                        {
                            // Prefer fixup assemblies if exists, otherwise just copy the original.
                            copysrc = Path.Combine(OutputDirectory, filename);
                            copysrc = File.Exists(copysrc) ? copysrc : assembly.ItemSpec;
                        }
                    }
                    else if (!MonoAndroidHelper.IsForceRetainedAssembly(filename))
                    {
                        continue;
                    }

                    MonoAndroidHelper.CopyIfChanged(copysrc, Path.Combine(copydst, filename));
                    try {
                        MonoAndroidHelper.CopyIfChanged(assembly.ItemSpec + ".mdb", Path.Combine(copydst, filename + ".mdb"));
                    } catch (Exception) {                     // skip it, mdb sometimes fails to read and it's optional
                    }
                }
            } catch (ResolutionException ex) {
                Diagnostic.Error(2006, ex, "Reference to metadata item '{0}' (defined in '{1}') from '{1}' could not be resolved.", ex.Member, ex.Member.Module.Assembly, ex.Scope);
            }

            return(true);
        }
 public CoreHttpMessageHandler(LinkerOptions options)
 {
     Options = options;
 }
예제 #23
0
        bool Execute(DirectoryAssemblyResolver res)
        {
            // Put every assembly we'll need in the resolver
            foreach (var assembly in ResolvedAssemblies)
            {
                res.Load(Path.GetFullPath(assembly.ItemSpec));
            }

            var resolver = new AssemblyResolver(res.ToResolverCache());

            // Set up for linking
            var options = new LinkerOptions();

            options.MainAssembly     = res.GetAssembly(MainAssembly);
            options.OutputDirectory  = Path.GetFullPath(OutputDirectory);
            options.LinkSdkOnly      = string.Compare(LinkMode, "SdkOnly", true) == 0;
            options.LinkNone         = false;
            options.Resolver         = resolver;
            options.LinkDescriptions = LinkDescriptions.Select(item => Path.GetFullPath(item.ItemSpec)).ToArray();
            options.I18nAssemblies   = Linker.ParseI18nAssemblies(I18nAssemblies);
            if (!options.LinkSdkOnly)
            {
                options.RetainAssemblies = GetRetainAssemblies(res);
            }
            options.DumpDependencies          = DumpDependencies;
            options.HttpClientHandlerType     = HttpClientHandlerType;
            options.TlsProvider               = TlsProvider;
            options.AddKeepAlives             = AddKeepAlives;
            options.PreserveJniMarshalMethods = PreserveJniMarshalMethods;
            options.DeterministicOutput       = Deterministic;
            options.LinkResources             = LinkResources;

            var skiplist = new List <string> ();

            // Add LinkSkip options
            if (!string.IsNullOrWhiteSpace(LinkSkip))
            {
                skiplist.AddRange(LinkSkip.Split(',', ';'));
            }

            options.SkippedAssemblies = skiplist;

            if (EnableProguard)
            {
                options.ProguardConfiguration = ProguardConfiguration;
            }

            // Link!
            try {
                LinkContext link_context;
                Linker.Process(options, this, out link_context);

                foreach (var assembly in ResolvedAssemblies)
                {
                    var copysrc             = assembly.ItemSpec;
                    var filename            = Path.GetFileName(assembly.ItemSpec);
                    var assemblyDestination = Path.Combine(OutputDirectory, filename);

                    if (!MonoAndroidHelper.IsForceRetainedAssembly(filename))
                    {
                        continue;
                    }

                    MonoAndroidHelper.CopyAssemblyAndSymbols(copysrc, assemblyDestination);
                }
            } catch (ResolutionException ex) {
                Diagnostic.Error(2006, ex, Properties.Resources.XA2006, ex.Member, ex.Member.Module.Assembly, ex.Scope);
            }

            return(true);
        }
 public CoreTlsProviderStep(LinkerOptions options)
 {
     Options = options;
 }