public static IFrameworkAssemblyLocator Instance(TargetArchitecture targetArchitecture) { if (targetArchitecture == TargetArchitecture.AMD64 || targetArchitecture == TargetArchitecture.IA64) { return FrameworkAssemblyLocator4x64.Instance(); } else { return FrameworkAssemblyLocator4x86.Instance(); } }
public void AddToAssemblyCache(string filePath, TargetArchitecture architecture) { AssemblyName assemblyName; if (TryGetAssemblyNameDefinition(filePath, true, architecture, out assemblyName)) { TargetPlatform platform = GetTargetPlatform(filePath); if (!pathRepository.AssemblyParts.ContainsKey(filePath)) { pathRepository.AssemblyParts.Add(filePath, platform); } if (!pathRepository.AssemblyPathName.ContainsKey(assemblyName.FullName)) { CheckFileExistence(assemblyName, filePath, true, false); RemoveFromUnresolvedCache(assemblyName.FullName); } } }
private void InitializeDefaultOptions() { _options = new CompilationOptions(); #if FXCORE // We could offer this as a command line option, but then we also need to // load a different RyuJIT, so this is a future nice to have... if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) _targetOS = TargetOS.Windows; else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) _targetOS = TargetOS.Linux; else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) _targetOS = TargetOS.OSX; else throw new NotImplementedException(); switch (RuntimeInformation.ProcessArchitecture) { case Architecture.X86: _targetArchitecture = TargetArchitecture.X86; break; case Architecture.X64: _targetArchitecture = TargetArchitecture.X64; break; case Architecture.Arm: _targetArchitecture = TargetArchitecture.ARM; break; case Architecture.Arm64: _targetArchitecture = TargetArchitecture.ARM64; break; default: throw new NotImplementedException(); } #else _targetOS = TargetOS.Windows; _targetArchitecture = TargetArchitecture.X64; #endif }
public override AssemblyDefinition Resolve(AssemblyNameReference name, string path, TargetArchitecture architecture, bool addToFailedCache, bool bubbleToUserIfFailed = true) { return base.Resolve(name, path, architecture, addToFailedCache, bubbleToUserIfFailed: false); }
private void Build(BuildOptions options, string preset, TargetPlatform targetPlatform, TargetArchitecture architecture) { // Load preset configuration var presetPath = Path.Combine(projectGenDir, "buildtools", "presets", "public", preset + ".xml"); if (!File.Exists(presetPath)) { throw new Exception(string.Format("Missing PhysX preset {0} (file: {1})", preset, presetPath)); } var presetXml = new XmlDocument(); presetXml.Load(presetPath); // Configure preset var cmakeSwitches = presetXml["preset"]["CMakeSwitches"]; ConfigureCmakeSwitch(cmakeSwitches, "PX_BUILDSNIPPETS", "False"); ConfigureCmakeSwitch(cmakeSwitches, "PX_BUILDSAMPLES", "False"); ConfigureCmakeSwitch(cmakeSwitches, "PX_BUILDPUBLICSAMPLES", "False"); ConfigureCmakeSwitch(cmakeSwitches, "PX_GENERATE_STATIC_LIBRARIES", "True"); ConfigureCmakeSwitch(cmakeSwitches, "NV_USE_STATIC_WINCRT", "False"); ConfigureCmakeSwitch(cmakeSwitches, "NV_USE_DEBUG_WINCRT", "False"); ConfigureCmakeSwitch(cmakeSwitches, "PX_FLOAT_POINT_PRECISE_MATH", "False"); var cmakeParams = presetXml["preset"]["CMakeParams"]; switch (targetPlatform) { case TargetPlatform.Android: ConfigureCmakeSwitch(cmakeParams, "CMAKE_INSTALL_PREFIX", $"install/android-{Configuration.AndroidPlatformApi}/PhysX"); ConfigureCmakeSwitch(cmakeParams, "ANDROID_NATIVE_API_LEVEL", $"android-{Configuration.AndroidPlatformApi}"); ConfigureCmakeSwitch(cmakeParams, "ANDROID_ABI", AndroidToolchain.GetAbiName(architecture)); break; } // Save preset presetXml.Save(presetPath); // Peek options var platform = Platform.GetPlatform(targetPlatform); var configuration = "release"; string bits; string arch; string binariesSubDir; string buildPlatform; bool suppressBitsPostfix = false; string binariesPrefix = string.Empty; var envVars = new Dictionary <string, string>(); switch (architecture) { case TargetArchitecture.x86: arch = "x86"; bits = "32"; break; case TargetArchitecture.x64: arch = "x86"; bits = "64"; break; case TargetArchitecture.ARM: arch = "arm"; bits = "32"; break; case TargetArchitecture.ARM64: arch = "arm"; bits = "64"; break; default: throw new InvalidArchitectureException(architecture); } switch (architecture) { case TargetArchitecture.x86: buildPlatform = "Win32"; break; default: buildPlatform = architecture.ToString(); break; } switch (targetPlatform) { case TargetPlatform.Windows: binariesSubDir = string.Format("win.{0}_{1}.vc140.md", arch, bits); break; case TargetPlatform.UWP: binariesSubDir = string.Format("uwp.{0}_{1}.vc141", arch, bits); break; case TargetPlatform.Linux: binariesSubDir = "linux.clang"; binariesPrefix = "lib"; break; case TargetPlatform.PS4: binariesSubDir = "ps4"; buildPlatform = "ORBIS"; suppressBitsPostfix = true; binariesPrefix = "lib"; break; case TargetPlatform.PS5: binariesSubDir = "ps5"; buildPlatform = "PROSPERO"; suppressBitsPostfix = true; binariesPrefix = "lib"; break; case TargetPlatform.XboxOne: case TargetPlatform.XboxScarlett: binariesSubDir = "win.x86_64.vc142.md"; break; case TargetPlatform.Android: switch (architecture) { case TargetArchitecture.ARM64: binariesSubDir = "android.arm64-v8a.fp-soft"; break; default: throw new InvalidArchitectureException(architecture); } binariesPrefix = "lib"; suppressBitsPostfix = true; break; case TargetPlatform.Switch: binariesSubDir = "switch64"; buildPlatform = "NX64"; suppressBitsPostfix = true; binariesPrefix = "lib"; break; case TargetPlatform.Mac: binariesSubDir = "mac.x86_64"; binariesPrefix = "lib"; envVars.Add("MACOSX_DEPLOYMENT_TARGET", Configuration.MacOSXMinVer); break; default: throw new InvalidPlatformException(targetPlatform); } // Setup build environment variables for PhysX build system switch (BuildPlatform) { case TargetPlatform.Windows: { var msBuild = VCEnvironment.MSBuildPath; if (File.Exists(msBuild)) { envVars.Add("PATH", Path.GetDirectoryName(msBuild)); } break; } case TargetPlatform.Linux: envVars.Add("CC", "clang-7"); envVars.Add("CC_FOR_BUILD", "clang-7"); break; case TargetPlatform.Mac: break; default: throw new InvalidPlatformException(BuildPlatform); } if (AndroidNdk.Instance.IsValid) { envVars.Add("PM_ANDROIDNDK_PATH", AndroidNdk.Instance.RootPath); } // Print the PhysX version Log.Info("Building PhysX version " + File.ReadAllText(Path.Combine(root, "physx", "version.txt")) + " to " + binariesSubDir); // Generate project files Utilities.Run(projectGenPath, preset, null, projectGenDir, Utilities.RunOptions.Default, envVars); switch (targetPlatform) { case TargetPlatform.PS4: case TargetPlatform.PS5: // Hack: PS4 uses .o extension for compiler output files but CMake uses .obj even if CMAKE_CXX_OUTPUT_EXTENSION/CMAKE_C_OUTPUT_EXTENSION are specified Utilities.ReplaceInFiles(Path.Combine(root, "physx\\compiler\\" + binariesSubDir), "*.vcxproj", SearchOption.AllDirectories, ".obj", ".o"); break; case TargetPlatform.XboxOne: case TargetPlatform.XboxScarlett: // Hack: force to use proper Win10 SDK Utilities.ReplaceInFiles(Path.Combine(root, "physx\\compiler\\vc16win64"), "*.vcxproj", SearchOption.AllDirectories, "10.0.18362.0", "10.0.19041.0"); // Hack: fix STL include Utilities.ReplaceInFile(Path.Combine(root, "physx\\source\\foundation\\include\\PsAllocator.h"), "#include <typeinfo.h>", "#include <typeinfo>"); break; case TargetPlatform.Android: // Hack: fix compilation errors if (!File.ReadAllText(Path.Combine(root, "physx\\source\\foundation\\include\\PsUtilities.h")).Contains("#if PX_GCC_FAMILY && !PX_EMSCRIPTEN && !PX_LINUX && !PX_ANDROID")) { Utilities.ReplaceInFile(Path.Combine(root, "physx\\source\\foundation\\include\\PsUtilities.h"), "#if PX_GCC_FAMILY && !PX_EMSCRIPTEN && !PX_LINUX", "#if PX_GCC_FAMILY && !PX_EMSCRIPTEN && !PX_LINUX && !PX_ANDROID"); } Utilities.ReplaceInFile(Path.Combine(root, "physx\\source\\compiler\\cmake\\android\\CMakeLists.txt"), "-Wno-maybe-uninitialized", "-Wno-unused-local-typedef -Wno-unused-private-field"); // PhysX build system for Android is old and doesn't support new NDK with clang so invoke cmake manually if (!Directory.Exists(Path.Combine(root, "physx\\compiler\\android"))) { Directory.CreateDirectory(Path.Combine(root, "physx\\compiler\\android")); } envVars.Add("PHYSX_ROOT_DIR", Path.Combine(root, "physx")); envVars.Add("PM_CMAKEMODULES_PATH", Path.Combine(root, "externals/CMakeModules")); envVars.Add("PM_PXSHARED_PATH", Path.Combine(root, "pxshared")); envVars.Add("PM_TARGA_PATH", Path.Combine(root, "externals/targa")); envVars.Add("PM_PATHS", Path.Combine(root, "externals/CMakeModules") + ';' + Path.Combine(root, "externals/targa")); RunCmake(Path.Combine(root, "physx\\compiler\\android"), targetPlatform, architecture, string.Format("\"{0}/physx/compiler/public\" -Wno-dev -DANDROID_NATIVE_API_LEVEL=android-{1} -DTARGET_BUILD_PLATFORM=android --no-warn-unused-cli -DCMAKE_BUILD_TYPE={2} -DCMAKE_PREFIX_PATH=\"{0}/externals/CMakeModules;{0}/externals/targa\" -DPHYSX_ROOT_DIR=\"{0}/physx\" -DPX_OUTPUT_LIB_DIR=\"{0}/physx\" -DPX_OUTPUT_BIN_DIR=\"{0}/physx\" -DPX_BUILDSNIPPETS=FALSE -DPX_GENERATE_STATIC_LIBRARIES=TRUE -DCMAKE_INSTALL_PREFIX=\"{0}/physx/install/android-{1}/PhysX\"", root, Configuration.AndroidPlatformApi, configuration), envVars); break; } // Run building based on the platform var defaultPhysXLibs = new[] { "PhysX", "PhysXCharacterKinematic", "PhysXCommon", "PhysXCooking", "PhysXExtensions", "PhysXFoundation", "PhysXPvdSDK", "PhysXVehicle", }; var dstBinaries = GetThirdPartyFolder(options, targetPlatform, architecture); var srcBinaries = Path.Combine(root, "physx", "bin", binariesSubDir, configuration); switch (BuildPlatform) { case TargetPlatform.Windows: switch (targetPlatform) { case TargetPlatform.Android: Utilities.Run("cmake", "--build .", null, Path.Combine(root, "physx\\compiler\\android"), Utilities.RunOptions.None, envVars); break; default: VCEnvironment.BuildSolution(Path.Combine(solutionFilesRoot, preset, "PhysXSDK.sln"), configuration, buildPlatform); break; } break; case TargetPlatform.Linux: Utilities.Run("make", null, null, Path.Combine(projectGenDir, "compiler", "linux-" + configuration), Utilities.RunOptions.None); break; case TargetPlatform.Mac: Utilities.Run("xcodebuild", "-project PhysXSDK.xcodeproj -alltargets -configuration " + configuration, null, Path.Combine(projectGenDir, "compiler", preset), Utilities.RunOptions.None); break; default: throw new InvalidPlatformException(BuildPlatform); } // Deploy binaries var binariesExtension = platform.StaticLibraryFileExtension; Log.Verbose("Copy PhysX binaries from " + srcBinaries); foreach (var physXLib in defaultPhysXLibs) { var filename = suppressBitsPostfix ? string.Format("{0}{1}_static", binariesPrefix, physXLib) : string.Format("{0}{1}_static_{2}", binariesPrefix, physXLib, bits); filename += binariesExtension; Utilities.FileCopy(Path.Combine(srcBinaries, filename), Path.Combine(dstBinaries, filename)); var filenamePdb = Path.ChangeExtension(filename, "pdb"); if (File.Exists(Path.Combine(srcBinaries, filenamePdb))) { Utilities.FileCopy(Path.Combine(srcBinaries, filenamePdb), Path.Combine(dstBinaries, filenamePdb)); } // Strip debug symbols to reduce binaries size switch (targetPlatform) { case TargetPlatform.Linux: case TargetPlatform.Mac: case TargetPlatform.Android: Utilities.Run("strip", "\"" + filename + "\"", null, dstBinaries, Utilities.RunOptions.None); break; } } srcBinaries = Path.Combine(root, "physx", "compiler", preset, "sdk_source_bin", configuration); var additionalPhysXLibs = new[] { "FastXml", "LowLevel", "LowLevelAABB", "LowLevelDynamics", "PhysXTask", "SceneQuery", "SimulationController", }; foreach (var additionalPhysXLib in additionalPhysXLibs) { var filenamePdb = suppressBitsPostfix ? string.Format("{0}{1}", binariesPrefix, additionalPhysXLib) : string.Format("{0}{1}_{2}", binariesPrefix, additionalPhysXLib, bits); filenamePdb += ".pdb"; if (File.Exists(Path.Combine(srcBinaries, filenamePdb))) { Utilities.FileCopy(Path.Combine(srcBinaries, filenamePdb), Path.Combine(dstBinaries, filenamePdb)); } } }
public ModuleParameters() { this.kind = ModuleKind.Dll; this.Runtime = GetCurrentRuntime(); this.architecture = TargetArchitecture.I386; }
/// <summary> /// Outputs specified headers, sections, methods or runtime functions for one ReadyToRun image /// </summary> /// <param name="r2r">The structure containing the info of the ReadyToRun image</param> public void Dump(ReadyToRunReader r2r) { _dumper.Begin(); bool standardDump = !(_options.EntryPoints || _options.CreatePDB || _options.CreatePerfmap); if (_options.Header && standardDump) { _dumper.WriteDivider("R2R Header"); _dumper.DumpHeader(true); } bool haveQuery = false; if (_options.Section.Length > 0) { haveQuery = true; QuerySection(r2r, _options.Section); } if (_options.RuntimeFunction.Length > 0) { haveQuery = true; QueryRuntimeFunction(r2r, _options.RuntimeFunction); } if (_options.Query.Length > 0) { haveQuery = true; QueryMethod(r2r, "R2R Methods by Query", _options.Query, true); } if (_options.Keyword.Length > 0) { haveQuery = true; QueryMethod(r2r, "R2R Methods by Keyword", _options.Keyword, false); } if (!haveQuery) { // Dump all sections and methods if no queries specified if (_options.EntryPoints) { _dumper.DumpEntryPoints(); } TargetArchitecture architecture = r2r.Machine switch { Machine.I386 => TargetArchitecture.X86, Machine.Amd64 => TargetArchitecture.X64, Machine.ArmThumb2 => TargetArchitecture.ARM, Machine.Arm64 => TargetArchitecture.ARM64, _ => throw new NotImplementedException(r2r.Machine.ToString()), }; TargetOS os = r2r.OperatingSystem switch { OperatingSystem.Windows => TargetOS.Windows, OperatingSystem.Linux => TargetOS.Linux, OperatingSystem.Apple => TargetOS.OSX, OperatingSystem.FreeBSD => TargetOS.FreeBSD, OperatingSystem.NetBSD => TargetOS.FreeBSD, _ => throw new NotImplementedException(r2r.OperatingSystem.ToString()), }; TargetDetails details = new TargetDetails(architecture, os, TargetAbi.NativeAot); if (_options.CreatePDB) { string pdbPath = _options.PdbPath; if (String.IsNullOrEmpty(pdbPath)) { pdbPath = Path.GetDirectoryName(r2r.Filename); } var pdbWriter = new PdbWriter(pdbPath, PDBExtraData.None, details); pdbWriter.WritePDBData(r2r.Filename, ProduceDebugInfoMethods(r2r)); } if (_options.CreatePerfmap) { string perfmapPath = _options.PerfmapPath; if (string.IsNullOrEmpty(perfmapPath)) { perfmapPath = Path.ChangeExtension(r2r.Filename, ".r2rmap"); } PerfMapWriter.Write(perfmapPath, _options.PerfmapFormatVersion, ProduceDebugInfoMethods(r2r), ProduceDebugInfoAssemblies(r2r), details); } if (standardDump) { _dumper.DumpAllMethods(); _dumper.DumpFixupStats(); } } _dumper.End(); }
public virtual void AddToAssemblyCache(string filePath, TargetArchitecture platform, bool storeAssemblyDefInCahce = false) { assemblyPathResolver.AddToAssemblyCache(filePath, platform); AddSearchDirectory(Path.GetDirectoryName(filePath)); if (storeAssemblyDefInCahce && !filePathToAssemblyDefinitionCache.ContainsKey(filePath)) { AssemblyDefinition assemblyDef = LoadAssemblyDefinition(filePath, new ReaderParameters(this), loadPdb: true); if (assemblyDef != null) { AddToResolvedAssemblies(assemblyDef); } } assemblyPathResolver.RemoveFromUnresolvedCache(filePath); }
private bool TrySearchDirectory(AssemblyNameReference name, ReaderParameters parameters, TargetArchitecture architecture, IEnumerable<DirectoryAssemblyInfo> targetDirs, out AssemblyDefinition assemblyDefinition) { assemblyDefinition = null; string lowerName = name.Name.ToLowerInvariant(); foreach (DirectoryAssemblyInfo directoryAssembly in targetDirs) { string assemblyPath = directoryAssembly.FullFileName; if (directoryAssembly.FileNameWithoutExtension == lowerName) { AssemblyName assName = new AssemblyName(name.Name, name.FullName, name.Version, name.PublicKeyToken) { TargetArchitecture = architecture }; bool sameVersion = assemblyPathResolver.CheckFileExistence(assName, assemblyPath, false, false, checkForArchitectPlatfrom: true); if (sameVersion) { assemblyDefinition = GetAssembly(directoryAssembly.FullFileName, parameters); return true; } } } return false; }
/*Telerik Authorship*/ public virtual AssemblyDefinition Resolve(AssemblyNameReference name, string path, TargetArchitecture architecture, bool addToFailedCache, bool bubbleToUserIfFailed = true) { lock (Locker) { this.AddSearchDirectory(path); AssemblyDefinition assemblyDefinition = Resolve(name, path, new ReaderParameters(this), architecture, bubbleToUserIfFailed, addToFailedCache); return assemblyDefinition; } }
public void ExpandInstructionSetByReverseImplication(TargetArchitecture architecture) { this = ExpandInstructionSetByReverseImplicationHelper(architecture, this); }
/// <summary> /// Scans the specified library and any dependencies. /// </summary> /// <param name="TheLibrary">The library to scan.</param> /// <returns> /// CompileResult.OK if completed successfully. /// Otherwise CompileResult.PartialFail or CompileResult.Error depending on /// the extent of the problem. /// </returns> public static CompileResult Scan(ILLibrary TheLibrary) { CompileResult result = CompileResult.OK; if (TheLibrary.ILScanned) { return(result); } TheLibrary.ILScanned = true; foreach (ILLibrary depLib in TheLibrary.Dependencies) { Scan(depLib); } // Create / Add Static Fields ASM Block ASM.ASMBlock StaticFieldsBlock = new ASM.ASMBlock() { Priority = (long.MinValue / 2) - 9 }; TheLibrary.TheASMLibrary.ASMBlocks.Add(StaticFieldsBlock); // Create / Add Types Table ASM Block ASM.ASMBlock TypesTableBlock = new ASM.ASMBlock() { Priority = (long.MinValue / 2) - 8 }; TheLibrary.TheASMLibrary.ASMBlocks.Add(TypesTableBlock); // Create / Add Method Tables ASM Block ASM.ASMBlock MethodTablesBlock = new ASM.ASMBlock() { Priority = (long.MinValue / 2) + 0 }; TheLibrary.TheASMLibrary.ASMBlocks.Add(MethodTablesBlock); // Create / Add Field Tables ASM Block ASM.ASMBlock FieldTablesBlock = new ASM.ASMBlock() { Priority = (long.MinValue / 2) + 1 }; TheLibrary.TheASMLibrary.ASMBlocks.Add(FieldTablesBlock); // Don't use foreach or you get collection modified exceptions for (int i = 0; i < TheLibrary.TypeInfos.Count; i++) { Types.TypeInfo aTypeInfo = TheLibrary.TypeInfos[i]; if (!ScannedTypes.ContainsKey(aTypeInfo.ID)) { ScannedTypes.Add(aTypeInfo.ID, TheLibrary); ScanStaticFields(TheLibrary, aTypeInfo, StaticFieldsBlock); ScanType(TheLibrary, aTypeInfo, TypesTableBlock); ScanMethods(TheLibrary, aTypeInfo, MethodTablesBlock); ScanFields(TheLibrary, aTypeInfo, FieldTablesBlock); } } foreach (Types.MethodInfo aMethodInfo in TheLibrary.ILBlocks.Keys) { ILBlock anILBlock = TheLibrary.ILBlocks[aMethodInfo]; CompileResult singleResult = CompileResult.OK; if (anILBlock.Plugged) { singleResult = ScanPluggedILBlock(TheLibrary, aMethodInfo, anILBlock); } else { singleResult = ScanNonpluggedILBlock(TheLibrary, aMethodInfo, anILBlock); } if (result != CompileResult.OK) { result = singleResult; } } // Create / Add String Literals ASM Block #region String Literals Block ASM.ASMBlock StringLiteralsBlock = new ASM.ASMBlock() { Priority = (long.MinValue / 2) - 10 }; TheLibrary.TheASMLibrary.ASMBlocks.Add(StringLiteralsBlock); string StringTypeId = ILLibrary.SpecialClasses[typeof(Attributes.StringClassAttribute)].First().ID; StringLiteralsBlock.AddExternalLabel(StringTypeId); foreach (KeyValuePair <string, string> aStringLiteral in TheLibrary.StringLiterals) { string value = aStringLiteral.Value; byte[] lengthBytes = BitConverter.GetBytes(value.Length); ASM.ASMOp newLiteralOp = TargetArchitecture.CreateASMOp(ASM.OpCodes.StringLiteral, aStringLiteral.Key, StringTypeId, lengthBytes, value.ToCharArray()); StringLiteralsBlock.Append(newLiteralOp); } #endregion return(result); }
/// <summary> /// Scans the specified non-plugged IL block. /// </summary> /// <param name="TheLibrary">The library currently being compiled.</param> /// <param name="theMethodInfo">The method which generated the IL block.</param> /// <param name="theILBlock">The IL block to scan.</param> /// <returns>CompileResult.OK.</returns> private static CompileResult ScanNonpluggedILBlock(ILLibrary TheLibrary, Types.MethodInfo theMethodInfo, ILBlock theILBlock) { CompileResult result = CompileResult.OK; ASM.ASMBlock TheASMBlock = new ASM.ASMBlock() { OriginMethodInfo = theMethodInfo, Priority = theMethodInfo.Priority }; ILConversionState convState = new ILConversionState() { TheILLibrary = TheLibrary, CurrentStackFrame = new StackFrame(), Input = theILBlock, Result = TheASMBlock }; foreach (ILOp anOp in theILBlock.ILOps) { try { string commentText = TheASMBlock.GenerateILOpLabel(convState.PositionOf(anOp), "") + " -- " + anOp.opCode.ToString() + " -- Offset: " + anOp.Offset.ToString("X2"); ASM.ASMOp newCommentOp = TargetArchitecture.CreateASMOp(ASM.OpCodes.Comment, commentText); TheASMBlock.ASMOps.Add(newCommentOp); int currCount = TheASMBlock.ASMOps.Count; if (anOp is ILOps.MethodStart) { TargetArchitecture.MethodStartOp.Convert(convState, anOp); } else if (anOp is ILOps.MethodEnd) { TargetArchitecture.MethodEndOp.Convert(convState, anOp); } else if (anOp is ILOps.StackSwitch) { TargetArchitecture.StackSwitchOp.Convert(convState, anOp); } else { ILOp ConverterOp = TargetArchitecture.TargetILOps[(ILOp.OpCodes)anOp.opCode.Value]; ConverterOp.Convert(convState, anOp); } if (anOp.LabelRequired) { if (currCount < TheASMBlock.ASMOps.Count) { TheASMBlock.ASMOps[currCount].ILLabelPosition = convState.PositionOf(anOp); TheASMBlock.ASMOps[currCount].RequiresILLabel = true; } } } catch (KeyNotFoundException) { result = CompileResult.PartialFailure; Logger.LogError(Errors.ILCompiler_ScanILOpFailure_ErrorCode, theMethodInfo.ToString(), anOp.Offset, string.Format(Errors.ErrorMessages[Errors.ILCompiler_ScanILOpFailure_ErrorCode], Enum.GetName(typeof(ILOp.OpCodes), anOp.opCode.Value), "Conversion for IL op not found.")); } catch (InvalidOperationException ex) { result = CompileResult.PartialFailure; Logger.LogError(Errors.ILCompiler_ScanILOpFailure_ErrorCode, theMethodInfo.ToString(), anOp.Offset, string.Format(Errors.ErrorMessages[Errors.ILCompiler_ScanILOpFailure_ErrorCode], Enum.GetName(typeof(ILOp.OpCodes), anOp.opCode.Value), ex.Message)); } catch (NotSupportedException ex) { result = CompileResult.PartialFailure; Logger.LogError(Errors.ILCompiler_ScanILOpFailure_ErrorCode, theMethodInfo.ToString(), anOp.Offset, string.Format(Errors.ErrorMessages[Errors.ILCompiler_ScanILOpFailure_ErrorCode], Enum.GetName(typeof(ILOp.OpCodes), anOp.opCode.Value), "An IL op reported something as not supported : " + ex.Message)); } catch (Exception ex) { result = CompileResult.Fail; Logger.LogError(Errors.ILCompiler_ScanILOpFailure_ErrorCode, theMethodInfo.ToString(), anOp.Offset, string.Format(Errors.ErrorMessages[Errors.ILCompiler_ScanILOpFailure_ErrorCode], Enum.GetName(typeof(ILOp.OpCodes), anOp.opCode.Value), ex.Message)); } } TheLibrary.TheASMLibrary.ASMBlocks.Add(TheASMBlock); return(result); }
public static void EmitObject(string objectFilePath, IEnumerable <DependencyNode> nodes, NodeFactory factory, IObjectDumper dumper) { ObjectWriter objectWriter = new ObjectWriter(objectFilePath, factory); bool succeeded = false; try { ObjectNodeSection managedCodeSection; if (factory.Target.OperatingSystem == TargetOS.Windows) { managedCodeSection = ObjectNodeSection.ManagedCodeWindowsContentSection; // Emit sentinels for managed code section. ObjectNodeSection codeStartSection = factory.CompilationModuleGroup.IsSingleFileCompilation ? ObjectNodeSection.ManagedCodeStartSection : objectWriter.GetSharedSection(ObjectNodeSection.ManagedCodeStartSection, "__managedcode_a"); objectWriter.SetSection(codeStartSection); objectWriter.EmitSymbolDef(new Utf8StringBuilder().Append("__managedcode_a")); objectWriter.EmitIntValue(0, 1); ObjectNodeSection codeEndSection = factory.CompilationModuleGroup.IsSingleFileCompilation ? ObjectNodeSection.ManagedCodeEndSection : objectWriter.GetSharedSection(ObjectNodeSection.ManagedCodeEndSection, "__managedcode_z"); objectWriter.SetSection(codeEndSection); objectWriter.EmitSymbolDef(new Utf8StringBuilder().Append("__managedcode_z")); objectWriter.EmitIntValue(1, 1); } else { managedCodeSection = ObjectNodeSection.ManagedCodeUnixContentSection; // TODO 2916: managed code section has to be created here, switch is not necessary. objectWriter.SetSection(ObjectNodeSection.ManagedCodeUnixContentSection); objectWriter.SetSection(LsdaSection); } objectWriter.SetCodeSectionAttribute(managedCodeSection); // Build file info map. objectWriter.BuildFileInfoMap(nodes); var listOfOffsets = new List <int>(); foreach (DependencyNode depNode in nodes) { ObjectNode node = depNode as ObjectNode; if (node == null) { continue; } if (node.ShouldSkipEmittingObjectNode(factory)) { continue; } ObjectData nodeContents = node.GetData(factory); if (dumper != null) { dumper.DumpObjectNode(factory.NameMangler, node, nodeContents); } #if DEBUG foreach (ISymbolNode definedSymbol in nodeContents.DefinedSymbols) { try { _previouslyWrittenNodeNames.Add(definedSymbol.GetMangledName(factory.NameMangler), definedSymbol); } catch (ArgumentException) { ISymbolNode alreadyWrittenSymbol = _previouslyWrittenNodeNames[definedSymbol.GetMangledName(factory.NameMangler)]; Debug.Fail("Duplicate node name emitted to file", $"Symbol {definedSymbol.GetMangledName(factory.NameMangler)} has already been written to the output object file {objectFilePath} with symbol {alreadyWrittenSymbol}"); } } #endif ObjectNodeSection section = node.Section; if (objectWriter.ShouldShareSymbol(node)) { section = objectWriter.GetSharedSection(section, ((ISymbolNode)node).GetMangledName(factory.NameMangler)); } // Ensure section and alignment for the node. objectWriter.SetSection(section); objectWriter.EmitAlignment(nodeContents.Alignment); objectWriter.ResetByteRunInterruptionOffsets(nodeContents.Relocs); // Build symbol definition map. objectWriter.BuildSymbolDefinitionMap(node, nodeContents.DefinedSymbols); // The DWARF CFI unwind is implemented for AMD64 & ARM32 only. TargetArchitecture tarch = factory.Target.Architecture; if (!factory.Target.IsWindows && (tarch == TargetArchitecture.X64 || tarch == TargetArchitecture.ARM)) { objectWriter.BuildCFIMap(factory, node); } // Build debug location map objectWriter.BuildDebugLocInfoMap(node); Relocation[] relocs = nodeContents.Relocs; int nextRelocOffset = -1; int nextRelocIndex = -1; if (relocs.Length > 0) { nextRelocOffset = relocs[0].Offset; nextRelocIndex = 0; } int i = 0; listOfOffsets.Clear(); listOfOffsets.AddRange(objectWriter._byteInterruptionOffsets); int offsetIndex = 0; while (i < nodeContents.Data.Length) { // Emit symbol definitions if necessary objectWriter.EmitSymbolDefinition(i); // Emit CFI codes for the given offset. objectWriter.EmitCFICodes(i); // Emit debug loc info if needed. objectWriter.EmitDebugLocInfo(i); if (i == nextRelocOffset) { Relocation reloc = relocs[nextRelocIndex]; long delta; unsafe { fixed(void *location = &nodeContents.Data[i]) { delta = Relocation.ReadValue(reloc.RelocType, location); } } int size = objectWriter.EmitSymbolReference(reloc.Target, (int)delta, reloc.RelocType); // Emit a copy of original Thumb2 instruction that came from RyuJIT if (reloc.RelocType == RelocType.IMAGE_REL_BASED_THUMB_MOV32 || reloc.RelocType == RelocType.IMAGE_REL_BASED_THUMB_BRANCH24) { unsafe { fixed(void *location = &nodeContents.Data[i]) { objectWriter.EmitBytes((IntPtr)location, size); } } } // Update nextRelocIndex/Offset if (++nextRelocIndex < relocs.Length) { nextRelocOffset = relocs[nextRelocIndex].Offset; } else { // This is the last reloc. Set the next reloc offset to -1 in case the last reloc has a zero size, // which means the reloc does not have vacant bytes corresponding to in the data buffer. E.g, // IMAGE_REL_THUMB_BRANCH24 is a kind of 24-bit reloc whose bits scatte over the instruction that // references it. We do not vacate extra bytes in the data buffer for this kind of reloc. nextRelocOffset = -1; } i += size; } else { while (offsetIndex < listOfOffsets.Count && listOfOffsets[offsetIndex] <= i) { offsetIndex++; } int nextOffset = offsetIndex == listOfOffsets.Count ? nodeContents.Data.Length : listOfOffsets[offsetIndex]; unsafe { // Todo: Use Span<T> instead once it's available to us in this repo fixed(byte *pContents = &nodeContents.Data[i]) { objectWriter.EmitBytes((IntPtr)(pContents), nextOffset - i); i += nextOffset - i; } } } } Debug.Assert(i == nodeContents.Data.Length); // It is possible to have a symbol just after all of the data. objectWriter.EmitSymbolDefinition(nodeContents.Data.Length); // Publish Windows unwind info. if (factory.Target.IsWindows) { objectWriter.PublishUnwindInfo(node); } // Emit the last CFI to close the frame. objectWriter.EmitCFICodes(nodeContents.Data.Length); if (objectWriter.HasFunctionDebugInfo()) { objectWriter.EmitDebugVarInfo(node); objectWriter.EmitDebugEHClauseInfo(node); objectWriter.EmitDebugFunctionInfo(node, nodeContents.Data.Length); } } objectWriter.EmitDebugModuleInfo(); succeeded = true; } finally { objectWriter.Dispose(); if (!succeeded) { // If there was an exception while generating the OBJ file, make sure we don't leave the unfinished // object file around. try { File.Delete(objectFilePath); } catch { } } } }
/// <summary> /// Initializes a new instance of the <see cref="UnixToolchain"/> class. /// </summary> /// <param name="platform">The platform.</param> /// <param name="architecture">The target architecture.</param> /// <param name="toolchainRoots">The root folder for the toolchains installation.</param> /// <param name="systemCompiler">The system compiler to use. Null if use toolset root.</param> /// <param name="toolchainSubDir">The custom toolchain folder location in <paramref name="toolchainRoots"/> directory. If nul the architecture name will be sued.</param> protected UnixToolchain(UnixPlatform platform, TargetArchitecture architecture, string toolchainRoots, string systemCompiler, string toolchainSubDir = null) : base(platform, architecture) { ArchitectureName = GetToolchainName(platform.Target, architecture); // Build paths if (systemCompiler != null) { ToolsetRoot = toolchainRoots; ClangPath = UnixPlatform.Which(systemCompiler); ArPath = UnixPlatform.Which("ar"); LlvmArPath = UnixPlatform.Which("llvm-ar"); RanlibPath = UnixPlatform.Which("ranlib"); StripPath = UnixPlatform.Which("strip"); ObjcopyPath = UnixPlatform.Which("objcopy"); LdPath = UnixPlatform.Which("ld"); } else { var exeExtension = Platform.BuildPlatform.ExecutableFileExtension; ToolsetRoot = toolchainSubDir == null?Path.Combine(toolchainRoots, ArchitectureName) : Path.Combine(toolchainRoots, toolchainSubDir); ClangPath = Path.Combine(Path.Combine(ToolsetRoot, string.Format("bin/{0}-{1}", ArchitectureName, "clang++"))) + exeExtension; if (!File.Exists(ClangPath)) { ClangPath = Path.Combine(Path.Combine(ToolsetRoot, string.Format("bin/{0}-{1}", ArchitectureName, "clang"))) + exeExtension; } if (!File.Exists(ClangPath)) { ClangPath = Path.Combine(ToolsetRoot, "bin/clang++") + exeExtension; } if (!File.Exists(ClangPath)) { ClangPath = Path.Combine(ToolsetRoot, "bin/clang") + exeExtension; } ArPath = Path.Combine(Path.Combine(ToolsetRoot, string.Format("bin/{0}-{1}", ArchitectureName, "ar"))) + exeExtension; LlvmArPath = Path.Combine(Path.Combine(ToolsetRoot, string.Format("bin/{0}", "llvm-ar"))) + exeExtension; RanlibPath = Path.Combine(Path.Combine(ToolsetRoot, string.Format("bin/{0}-{1}", ArchitectureName, "ranlib"))) + exeExtension; StripPath = Path.Combine(Path.Combine(ToolsetRoot, string.Format("bin/{0}-{1}", ArchitectureName, "strip"))) + exeExtension; ObjcopyPath = Path.Combine(Path.Combine(ToolsetRoot, string.Format("bin/{0}-{1}", ArchitectureName, "objcopy"))) + exeExtension; LdPath = Path.Combine(Path.Combine(ToolsetRoot, string.Format("bin/{0}-{1}", ArchitectureName, "ld"))) + exeExtension; } // Determinate compiler version if (!File.Exists(ClangPath)) { throw new Exception(string.Format("Missing Clang ({0})", ClangPath)); } using (var process = new Process()) { process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.FileName = ClangPath; process.StartInfo.Arguments = "--version"; process.Start(); process.WaitForExit(); if (process.ExitCode == 0) { // Parse the version string data = process.StandardOutput.ReadLine(); Regex versionPattern = new Regex("version \\d+(\\.\\d+)+"); Match versionMatch = versionPattern.Match(data); if (versionMatch.Value.StartsWith("version ")) { var versionString = versionMatch.Value.Replace("version ", ""); string[] parts = versionString.Split('.'); int major = 0, minor = 0, patch = 0; if (parts.Length >= 1) { major = Convert.ToInt32(parts[0]); } if (parts.Length >= 2) { minor = Convert.ToInt32(parts[1]); } if (parts.Length >= 3) { patch = Convert.ToInt32(parts[2]); } ClangVersion = new Version(major, minor, patch); } } else { throw new Exception(string.Format("Failed to get Clang version ({0})", ClangPath)); } } // Check version if (ClangVersion.Major < 6) { throw new Exception(string.Format("Unsupported Clang version {0}. Minimum supported is 6.", ClangVersion)); } }
public TargetPlatform GetTargetPlatform(string assemblyFilePath, ModuleDefinition moduleDef) { TargetPlatform targetPlatform = this.DefaultTargetPlatform; if (string.IsNullOrEmpty(assemblyFilePath)) { return(targetPlatform); } if (this.assemblyFrameworkResolverCache.AssemblyPathToTargetPlatform.ContainsKey(assemblyFilePath)) { return(this.assemblyFrameworkResolverCache.AssemblyPathToTargetPlatform[assemblyFilePath]); } else { Task <TargetPlatform> targetPlatformFromDepsJson = null; string moduleLocation = moduleDef.FullyQualifiedName ?? moduleDef.FilePath; string depsJsonLocation = Directory.GetFiles(Path.GetDirectoryName(moduleLocation), "*.deps.json").FirstOrDefault(); if (File.Exists(depsJsonLocation)) { targetPlatformFromDepsJson = Task.Factory.StartNew(() => { return(this.GetPlatformTargetFromDepsJson(moduleLocation)); }); } ///*Telerik Authorship*/ if (moduleDef.Assembly != null) { targetPlatform = this.GetTargetPlatform(moduleDef); if (targetPlatform != this.DefaultTargetPlatform) { this.assemblyFrameworkResolverCache.AddAssemblyTargetPlatformToCache(assemblyFilePath, targetPlatform); return(targetPlatform); } } AssemblyNameReference msCorlib = moduleDef.AssemblyReferences.FirstOrDefault(a => a.Name == "mscorlib"); if (msCorlib == null) { AssemblyNameReference systemRuntimeReference = moduleDef.AssemblyReferences.FirstOrDefault(x => x.Name == "System.Runtime"); targetPlatform = this.GetTargetPlatform(systemRuntimeReference); if (targetPlatform != this.DefaultTargetPlatform) { this.assemblyFrameworkResolverCache.AddAssemblyTargetPlatformToCache(assemblyFilePath, targetPlatform); this.assemblyFrameworkResolverCache.AddAssemblySystemRuntimeReference(assemblyFilePath, systemRuntimeReference); return(targetPlatform); } // the next line is only to keep the old functionality msCorlib = moduleDef.Assembly.Name; } if (moduleDef.Assembly != null && moduleDef.Assembly.Name.IsWindowsRuntime || msCorlib.IsFakeMscorlibReference()) { this.assemblyFrameworkResolverCache.AddAssemblyTargetPlatformToCache(assemblyFilePath, TargetPlatform.WinRT); return(TargetPlatform.WinRT); } /*AssemblyName assemblyName = new AssemblyName(msCorlib.Name, * msCorlib.FullName, * msCorlib.Version, * msCorlib.PublicKeyToken, * Path.GetDirectoryName(assemliyFilePath)) { TargetArchitecture = moduleDef.GetModuleArchitecture() }; * IEnumerable<string> foundPaths = GetAssemblyPaths(assemblyName); * * return GetTargetPlatform(foundPaths.FirstOrDefault());*/ /*Telerik Authorship*/ if (targetPlatformFromDepsJson != null) { targetPlatformFromDepsJson.Wait(); targetPlatform = targetPlatformFromDepsJson.Result; if (targetPlatform != this.DefaultTargetPlatform) { this.assemblyFrameworkResolverCache.AddAssemblyTargetPlatformToCache(assemblyFilePath, targetPlatform); return(targetPlatform); } } /*Telerik Authorship*/ TargetArchitecture moduleArchitecture = moduleDef.GetModuleArchitecture(); /*Telerik Authorship*/ foreach (KeyValuePair <AssemblyName, TargetPlatform> pair in Mscorlibs) { if (AssemblyNameComparer.AreVersionEquals(pair.Key.Version, msCorlib.Version) && AssemblyNameComparer.ArePublicKeyEquals(pair.Key.PublicKeyToken, msCorlib.PublicKeyToken) && moduleArchitecture.CanReference(pair.Key.TargetArchitecture)) { this.assemblyFrameworkResolverCache.AddAssemblyTargetPlatformToCache(assemblyFilePath, pair.Value); return(pair.Value); } } /*Telerik Authorship*/ this.assemblyFrameworkResolverCache.AddAssemblyTargetPlatformToCache(assemblyFilePath, this.DefaultTargetPlatform); return(this.DefaultTargetPlatform); } }
/// <inheritdoc /> void IProjectCustomizer.GetProjectArchitectureName(Project project, Platform platform, TargetArchitecture architecture, ref string name) { if (architecture == TargetArchitecture.x86) { name = "Win32"; } }
/// <inheritdoc /> void IProjectCustomizer.GetSolutionArchitectureName(TargetArchitecture architecture, ref string name) { }
private static InstructionSetFlags ExpandInstructionSetByReverseImplicationHelper(TargetArchitecture architecture, InstructionSetFlags input) { InstructionSetFlags oldflags = input; InstructionSetFlags resultflags = input; do { oldflags = resultflags; switch (architecture) { case TargetArchitecture.ARM64: if (resultflags.HasInstructionSet(InstructionSet.ARM64_ArmBase_Arm64)) { resultflags.AddInstructionSet(InstructionSet.ARM64_ArmBase); } if (resultflags.HasInstructionSet(InstructionSet.ARM64_AdvSimd_Arm64)) { resultflags.AddInstructionSet(InstructionSet.ARM64_AdvSimd); } if (resultflags.HasInstructionSet(InstructionSet.ARM64_Aes_Arm64)) { resultflags.AddInstructionSet(InstructionSet.ARM64_Aes); } if (resultflags.HasInstructionSet(InstructionSet.ARM64_Crc32_Arm64)) { resultflags.AddInstructionSet(InstructionSet.ARM64_Crc32); } if (resultflags.HasInstructionSet(InstructionSet.ARM64_Dp_Arm64)) { resultflags.AddInstructionSet(InstructionSet.ARM64_Dp); } if (resultflags.HasInstructionSet(InstructionSet.ARM64_Rdm_Arm64)) { resultflags.AddInstructionSet(InstructionSet.ARM64_Rdm); } if (resultflags.HasInstructionSet(InstructionSet.ARM64_Sha1_Arm64)) { resultflags.AddInstructionSet(InstructionSet.ARM64_Sha1); } if (resultflags.HasInstructionSet(InstructionSet.ARM64_Sha256_Arm64)) { resultflags.AddInstructionSet(InstructionSet.ARM64_Sha256); } if (resultflags.HasInstructionSet(InstructionSet.ARM64_ArmBase)) { resultflags.AddInstructionSet(InstructionSet.ARM64_AdvSimd); } if (resultflags.HasInstructionSet(InstructionSet.ARM64_ArmBase)) { resultflags.AddInstructionSet(InstructionSet.ARM64_Aes); } if (resultflags.HasInstructionSet(InstructionSet.ARM64_ArmBase)) { resultflags.AddInstructionSet(InstructionSet.ARM64_Crc32); } if (resultflags.HasInstructionSet(InstructionSet.ARM64_AdvSimd)) { resultflags.AddInstructionSet(InstructionSet.ARM64_Dp); } if (resultflags.HasInstructionSet(InstructionSet.ARM64_AdvSimd)) { resultflags.AddInstructionSet(InstructionSet.ARM64_Rdm); } if (resultflags.HasInstructionSet(InstructionSet.ARM64_ArmBase)) { resultflags.AddInstructionSet(InstructionSet.ARM64_Sha1); } if (resultflags.HasInstructionSet(InstructionSet.ARM64_ArmBase)) { resultflags.AddInstructionSet(InstructionSet.ARM64_Sha256); } break; case TargetArchitecture.X64: if (resultflags.HasInstructionSet(InstructionSet.X64_X86Base_X64)) { resultflags.AddInstructionSet(InstructionSet.X64_X86Base); } if (resultflags.HasInstructionSet(InstructionSet.X64_SSE_X64)) { resultflags.AddInstructionSet(InstructionSet.X64_SSE); } if (resultflags.HasInstructionSet(InstructionSet.X64_SSE2_X64)) { resultflags.AddInstructionSet(InstructionSet.X64_SSE2); } if (resultflags.HasInstructionSet(InstructionSet.X64_SSE3_X64)) { resultflags.AddInstructionSet(InstructionSet.X64_SSE3); } if (resultflags.HasInstructionSet(InstructionSet.X64_SSSE3_X64)) { resultflags.AddInstructionSet(InstructionSet.X64_SSSE3); } if (resultflags.HasInstructionSet(InstructionSet.X64_SSE41_X64)) { resultflags.AddInstructionSet(InstructionSet.X64_SSE41); } if (resultflags.HasInstructionSet(InstructionSet.X64_SSE42_X64)) { resultflags.AddInstructionSet(InstructionSet.X64_SSE42); } if (resultflags.HasInstructionSet(InstructionSet.X64_AVX_X64)) { resultflags.AddInstructionSet(InstructionSet.X64_AVX); } if (resultflags.HasInstructionSet(InstructionSet.X64_AVX2_X64)) { resultflags.AddInstructionSet(InstructionSet.X64_AVX2); } if (resultflags.HasInstructionSet(InstructionSet.X64_AES_X64)) { resultflags.AddInstructionSet(InstructionSet.X64_AES); } if (resultflags.HasInstructionSet(InstructionSet.X64_BMI1_X64)) { resultflags.AddInstructionSet(InstructionSet.X64_BMI1); } if (resultflags.HasInstructionSet(InstructionSet.X64_BMI2_X64)) { resultflags.AddInstructionSet(InstructionSet.X64_BMI2); } if (resultflags.HasInstructionSet(InstructionSet.X64_FMA_X64)) { resultflags.AddInstructionSet(InstructionSet.X64_FMA); } if (resultflags.HasInstructionSet(InstructionSet.X64_LZCNT_X64)) { resultflags.AddInstructionSet(InstructionSet.X64_LZCNT); } if (resultflags.HasInstructionSet(InstructionSet.X64_PCLMULQDQ_X64)) { resultflags.AddInstructionSet(InstructionSet.X64_PCLMULQDQ); } if (resultflags.HasInstructionSet(InstructionSet.X64_POPCNT_X64)) { resultflags.AddInstructionSet(InstructionSet.X64_POPCNT); } if (resultflags.HasInstructionSet(InstructionSet.X64_X86Base)) { resultflags.AddInstructionSet(InstructionSet.X64_SSE); } if (resultflags.HasInstructionSet(InstructionSet.X64_SSE)) { resultflags.AddInstructionSet(InstructionSet.X64_SSE2); } if (resultflags.HasInstructionSet(InstructionSet.X64_SSE2)) { resultflags.AddInstructionSet(InstructionSet.X64_SSE3); } if (resultflags.HasInstructionSet(InstructionSet.X64_SSE3)) { resultflags.AddInstructionSet(InstructionSet.X64_SSSE3); } if (resultflags.HasInstructionSet(InstructionSet.X64_SSSE3)) { resultflags.AddInstructionSet(InstructionSet.X64_SSE41); } if (resultflags.HasInstructionSet(InstructionSet.X64_SSE41)) { resultflags.AddInstructionSet(InstructionSet.X64_SSE42); } if (resultflags.HasInstructionSet(InstructionSet.X64_SSE42)) { resultflags.AddInstructionSet(InstructionSet.X64_AVX); } if (resultflags.HasInstructionSet(InstructionSet.X64_AVX)) { resultflags.AddInstructionSet(InstructionSet.X64_AVX2); } if (resultflags.HasInstructionSet(InstructionSet.X64_SSE2)) { resultflags.AddInstructionSet(InstructionSet.X64_AES); } if (resultflags.HasInstructionSet(InstructionSet.X64_AVX)) { resultflags.AddInstructionSet(InstructionSet.X64_BMI1); } if (resultflags.HasInstructionSet(InstructionSet.X64_AVX)) { resultflags.AddInstructionSet(InstructionSet.X64_BMI2); } if (resultflags.HasInstructionSet(InstructionSet.X64_AVX)) { resultflags.AddInstructionSet(InstructionSet.X64_FMA); } if (resultflags.HasInstructionSet(InstructionSet.X64_SSE2)) { resultflags.AddInstructionSet(InstructionSet.X64_PCLMULQDQ); } if (resultflags.HasInstructionSet(InstructionSet.X64_SSE42)) { resultflags.AddInstructionSet(InstructionSet.X64_POPCNT); } if (resultflags.HasInstructionSet(InstructionSet.X64_AVX)) { resultflags.AddInstructionSet(InstructionSet.X64_Vector256); } break; case TargetArchitecture.X86: if (resultflags.HasInstructionSet(InstructionSet.X86_X86Base)) { resultflags.AddInstructionSet(InstructionSet.X86_SSE); } if (resultflags.HasInstructionSet(InstructionSet.X86_SSE)) { resultflags.AddInstructionSet(InstructionSet.X86_SSE2); } if (resultflags.HasInstructionSet(InstructionSet.X86_SSE2)) { resultflags.AddInstructionSet(InstructionSet.X86_SSE3); } if (resultflags.HasInstructionSet(InstructionSet.X86_SSE3)) { resultflags.AddInstructionSet(InstructionSet.X86_SSSE3); } if (resultflags.HasInstructionSet(InstructionSet.X86_SSSE3)) { resultflags.AddInstructionSet(InstructionSet.X86_SSE41); } if (resultflags.HasInstructionSet(InstructionSet.X86_SSE41)) { resultflags.AddInstructionSet(InstructionSet.X86_SSE42); } if (resultflags.HasInstructionSet(InstructionSet.X86_SSE42)) { resultflags.AddInstructionSet(InstructionSet.X86_AVX); } if (resultflags.HasInstructionSet(InstructionSet.X86_AVX)) { resultflags.AddInstructionSet(InstructionSet.X86_AVX2); } if (resultflags.HasInstructionSet(InstructionSet.X86_SSE2)) { resultflags.AddInstructionSet(InstructionSet.X86_AES); } if (resultflags.HasInstructionSet(InstructionSet.X86_AVX)) { resultflags.AddInstructionSet(InstructionSet.X86_BMI1); } if (resultflags.HasInstructionSet(InstructionSet.X86_AVX)) { resultflags.AddInstructionSet(InstructionSet.X86_BMI2); } if (resultflags.HasInstructionSet(InstructionSet.X86_AVX)) { resultflags.AddInstructionSet(InstructionSet.X86_FMA); } if (resultflags.HasInstructionSet(InstructionSet.X86_SSE2)) { resultflags.AddInstructionSet(InstructionSet.X86_PCLMULQDQ); } if (resultflags.HasInstructionSet(InstructionSet.X86_SSE42)) { resultflags.AddInstructionSet(InstructionSet.X86_POPCNT); } if (resultflags.HasInstructionSet(InstructionSet.X86_AVX)) { resultflags.AddInstructionSet(InstructionSet.X86_Vector256); } break; } } while (!oldflags.Equals(resultflags)); return(resultflags); }
public static IEnumerable <InstructionSetInfo> ArchitectureToValidInstructionSets(TargetArchitecture architecture) { switch (architecture) { case TargetArchitecture.ARM64: yield return(new InstructionSetInfo("base", "ArmBase", InstructionSet.ARM64_ArmBase, true)); yield return(new InstructionSetInfo("neon", "AdvSimd", InstructionSet.ARM64_AdvSimd, true)); yield return(new InstructionSetInfo("aes", "Aes", InstructionSet.ARM64_Aes, true)); yield return(new InstructionSetInfo("crc", "Crc32", InstructionSet.ARM64_Crc32, true)); yield return(new InstructionSetInfo("dotprod", "Dp", InstructionSet.ARM64_Dp, true)); yield return(new InstructionSetInfo("rdma", "Rdm", InstructionSet.ARM64_Rdm, true)); yield return(new InstructionSetInfo("sha1", "Sha1", InstructionSet.ARM64_Sha1, true)); yield return(new InstructionSetInfo("sha2", "Sha256", InstructionSet.ARM64_Sha256, true)); yield return(new InstructionSetInfo("lse", "", InstructionSet.ARM64_Atomics, true)); yield return(new InstructionSetInfo("Vector64", "", InstructionSet.ARM64_Vector64, false)); yield return(new InstructionSetInfo("Vector128", "", InstructionSet.ARM64_Vector128, false)); yield return(new InstructionSetInfo("Dczva", "", InstructionSet.ARM64_Dczva, false)); break; case TargetArchitecture.X64: yield return(new InstructionSetInfo("base", "X86Base", InstructionSet.X64_X86Base, true)); yield return(new InstructionSetInfo("sse", "Sse", InstructionSet.X64_SSE, true)); yield return(new InstructionSetInfo("sse2", "Sse2", InstructionSet.X64_SSE2, true)); yield return(new InstructionSetInfo("sse3", "Sse3", InstructionSet.X64_SSE3, true)); yield return(new InstructionSetInfo("ssse3", "Ssse3", InstructionSet.X64_SSSE3, true)); yield return(new InstructionSetInfo("sse4.1", "Sse41", InstructionSet.X64_SSE41, true)); yield return(new InstructionSetInfo("sse4.2", "Sse42", InstructionSet.X64_SSE42, true)); yield return(new InstructionSetInfo("avx", "Avx", InstructionSet.X64_AVX, true)); yield return(new InstructionSetInfo("avx2", "Avx2", InstructionSet.X64_AVX2, true)); yield return(new InstructionSetInfo("aes", "Aes", InstructionSet.X64_AES, true)); yield return(new InstructionSetInfo("bmi", "Bmi1", InstructionSet.X64_BMI1, true)); yield return(new InstructionSetInfo("bmi2", "Bmi2", InstructionSet.X64_BMI2, true)); yield return(new InstructionSetInfo("fma", "Fma", InstructionSet.X64_FMA, true)); yield return(new InstructionSetInfo("lzcnt", "Lzcnt", InstructionSet.X64_LZCNT, true)); yield return(new InstructionSetInfo("pclmul", "Pclmulqdq", InstructionSet.X64_PCLMULQDQ, true)); yield return(new InstructionSetInfo("popcnt", "Popcnt", InstructionSet.X64_POPCNT, true)); yield return(new InstructionSetInfo("Vector128", "", InstructionSet.X64_Vector128, false)); yield return(new InstructionSetInfo("Vector256", "", InstructionSet.X64_Vector256, false)); break; case TargetArchitecture.X86: yield return(new InstructionSetInfo("base", "X86Base", InstructionSet.X86_X86Base, true)); yield return(new InstructionSetInfo("sse", "Sse", InstructionSet.X86_SSE, true)); yield return(new InstructionSetInfo("sse2", "Sse2", InstructionSet.X86_SSE2, true)); yield return(new InstructionSetInfo("sse3", "Sse3", InstructionSet.X86_SSE3, true)); yield return(new InstructionSetInfo("ssse3", "Ssse3", InstructionSet.X86_SSSE3, true)); yield return(new InstructionSetInfo("sse4.1", "Sse41", InstructionSet.X86_SSE41, true)); yield return(new InstructionSetInfo("sse4.2", "Sse42", InstructionSet.X86_SSE42, true)); yield return(new InstructionSetInfo("avx", "Avx", InstructionSet.X86_AVX, true)); yield return(new InstructionSetInfo("avx2", "Avx2", InstructionSet.X86_AVX2, true)); yield return(new InstructionSetInfo("aes", "Aes", InstructionSet.X86_AES, true)); yield return(new InstructionSetInfo("bmi", "Bmi1", InstructionSet.X86_BMI1, true)); yield return(new InstructionSetInfo("bmi2", "Bmi2", InstructionSet.X86_BMI2, true)); yield return(new InstructionSetInfo("fma", "Fma", InstructionSet.X86_FMA, true)); yield return(new InstructionSetInfo("lzcnt", "Lzcnt", InstructionSet.X86_LZCNT, true)); yield return(new InstructionSetInfo("pclmul", "Pclmulqdq", InstructionSet.X86_PCLMULQDQ, true)); yield return(new InstructionSetInfo("popcnt", "Popcnt", InstructionSet.X86_POPCNT, true)); yield return(new InstructionSetInfo("Vector128", "", InstructionSet.X86_Vector128, false)); yield return(new InstructionSetInfo("Vector256", "", InstructionSet.X86_Vector256, false)); break; } }
/*Telerik Authorship*/ private AssemblyDefinition UserSpecifiedAssembly(AssemblyNameReference name, TargetArchitecture architecture) { //If not in denied assemblies cache if (assemblyPathResolver.IsFailedAssembly(name.FullName)) { return null; } if (ResolveFailure != null) { AssemblyDefinition assembly = ResolveFailure(this, new AssemblyResolveEventArgs(name, architecture)); if (assembly != null) { if (!filePathToAssemblyDefinitionCache.ContainsKey(assembly.MainModule.FilePath)) { AddToResolvedAssemblies(assembly); } if (!userDefinedAssemblies.Contains(assembly.MainModule.FilePath)) { userDefinedAssemblies.Add(assembly.MainModule.FilePath); } RemoveFromFailedAssemblies(assembly.FullName); return assembly; } } assemblyPathResolver.AddToUnresolvedCache(name.FullName); return null; }
public void Set64BitInstructionSetVariants(TargetArchitecture architecture) { switch (architecture) { case TargetArchitecture.ARM64: if (HasInstructionSet(InstructionSet.ARM64_ArmBase)) { AddInstructionSet(InstructionSet.ARM64_ArmBase_Arm64); } if (HasInstructionSet(InstructionSet.ARM64_AdvSimd)) { AddInstructionSet(InstructionSet.ARM64_AdvSimd_Arm64); } if (HasInstructionSet(InstructionSet.ARM64_Aes)) { AddInstructionSet(InstructionSet.ARM64_Aes_Arm64); } if (HasInstructionSet(InstructionSet.ARM64_Crc32)) { AddInstructionSet(InstructionSet.ARM64_Crc32_Arm64); } if (HasInstructionSet(InstructionSet.ARM64_Dp)) { AddInstructionSet(InstructionSet.ARM64_Dp_Arm64); } if (HasInstructionSet(InstructionSet.ARM64_Rdm)) { AddInstructionSet(InstructionSet.ARM64_Rdm_Arm64); } if (HasInstructionSet(InstructionSet.ARM64_Sha1)) { AddInstructionSet(InstructionSet.ARM64_Sha1_Arm64); } if (HasInstructionSet(InstructionSet.ARM64_Sha256)) { AddInstructionSet(InstructionSet.ARM64_Sha256_Arm64); } break; case TargetArchitecture.X64: if (HasInstructionSet(InstructionSet.X64_X86Base)) { AddInstructionSet(InstructionSet.X64_X86Base_X64); } if (HasInstructionSet(InstructionSet.X64_SSE)) { AddInstructionSet(InstructionSet.X64_SSE_X64); } if (HasInstructionSet(InstructionSet.X64_SSE2)) { AddInstructionSet(InstructionSet.X64_SSE2_X64); } if (HasInstructionSet(InstructionSet.X64_SSE3)) { AddInstructionSet(InstructionSet.X64_SSE3_X64); } if (HasInstructionSet(InstructionSet.X64_SSSE3)) { AddInstructionSet(InstructionSet.X64_SSSE3_X64); } if (HasInstructionSet(InstructionSet.X64_SSE41)) { AddInstructionSet(InstructionSet.X64_SSE41_X64); } if (HasInstructionSet(InstructionSet.X64_SSE42)) { AddInstructionSet(InstructionSet.X64_SSE42_X64); } if (HasInstructionSet(InstructionSet.X64_AVX)) { AddInstructionSet(InstructionSet.X64_AVX_X64); } if (HasInstructionSet(InstructionSet.X64_AVX2)) { AddInstructionSet(InstructionSet.X64_AVX2_X64); } if (HasInstructionSet(InstructionSet.X64_AES)) { AddInstructionSet(InstructionSet.X64_AES_X64); } if (HasInstructionSet(InstructionSet.X64_BMI1)) { AddInstructionSet(InstructionSet.X64_BMI1_X64); } if (HasInstructionSet(InstructionSet.X64_BMI2)) { AddInstructionSet(InstructionSet.X64_BMI2_X64); } if (HasInstructionSet(InstructionSet.X64_FMA)) { AddInstructionSet(InstructionSet.X64_FMA_X64); } if (HasInstructionSet(InstructionSet.X64_LZCNT)) { AddInstructionSet(InstructionSet.X64_LZCNT_X64); } if (HasInstructionSet(InstructionSet.X64_PCLMULQDQ)) { AddInstructionSet(InstructionSet.X64_PCLMULQDQ_X64); } if (HasInstructionSet(InstructionSet.X64_POPCNT)) { AddInstructionSet(InstructionSet.X64_POPCNT_X64); } break; case TargetArchitecture.X86: break; } }
AssemblyDefinition TryGetTargetAssembly(AssemblyNameReference reference, ReaderParameters parameters, TargetArchitecture architecture) { if (reference == null) { return null; } var assemblyName = new AssemblyName(reference.Name, reference.FullName, reference.Version, reference.PublicKeyToken) { TargetArchitecture = architecture }; IEnumerable<string> filePaths; if (assemblyPathResolver.TryGetAssemblyPathsFromCache(assemblyName, out filePaths)) { return GetTargetAssembly(filePaths, parameters, architecture); } return null; }
/// <summary> /// Runs the cmake tool. /// </summary> /// <param name="path">The path.</param> /// <param name="platform">The output platform.</param> /// <param name="architecture">The output architecture.</param> /// <param name="customArgs">The custom arguments for the CMake.</param> /// <param name="envVars">Custom environment variables to pass to the child process.</param> public static void RunCmake(string path, TargetPlatform platform, TargetArchitecture architecture, string customArgs = null, Dictionary <string, string> envVars = null) { string cmdLine; switch (platform) { case TargetPlatform.Windows: case TargetPlatform.XboxOne: case TargetPlatform.XboxScarlett: case TargetPlatform.UWP: { string arch; switch (architecture) { case TargetArchitecture.x86: arch = string.Empty; break; case TargetArchitecture.x64: arch = " Win64"; break; case TargetArchitecture.ARM: arch = " ARM"; break; case TargetArchitecture.ARM64: arch = " ARM64"; break; default: throw new InvalidArchitectureException(architecture); } cmdLine = string.Format("CMakeLists.txt -G \"Visual Studio 14 2015{0}\"", arch); break; } case TargetPlatform.Linux: case TargetPlatform.PS4: { cmdLine = "CMakeLists.txt"; break; } case TargetPlatform.Switch: { cmdLine = string.Format("-DCMAKE_TOOLCHAIN_FILE=\"{1}\\Source\\Platforms\\Switch\\Data\\Switch.cmake\" -G \"NMake Makefiles\" -DCMAKE_MAKE_PROGRAM=\"{0}..\\..\\VC\\bin\\nmake.exe\"", Environment.GetEnvironmentVariable("VS140COMNTOOLS"), Globals.EngineRoot); break; } case TargetPlatform.Android: { var ndk = AndroidNdk.Instance.RootPath; var abi = AndroidToolchain.GetAbiName(architecture); var hostName = AndroidSdk.GetHostName(); cmdLine = string.Format("-DCMAKE_TOOLCHAIN_FILE=\"{0}/build/cmake/android.toolchain.cmake\" -DANDROID_NDK=\"{0}\" -DANDROID_STL=c++_shared -DANDROID_ABI={1} -DANDROID_PLATFORM=android-{2} -G \"MinGW Makefiles\" -DCMAKE_MAKE_PROGRAM=\"{0}/prebuilt/{3}/bin/make.exe\"", ndk, abi, Configuration.AndroidPlatformApi, hostName); break; } default: throw new InvalidPlatformException(platform); } if (customArgs != null) { cmdLine += " " + customArgs; } Utilities.Run("cmake", cmdLine, null, path, Utilities.RunOptions.None, envVars); }
private int Run() { InitializeDefaultOptions(); ProcessCommandLine(); if (_commandLineOptions.OutputFilePath == null) { throw new CommandLineException("Output filename must be specified (/out <file>)"); } // // Set target Architecture and OS // if (_commandLineOptions.TargetArch != null) { if (_commandLineOptions.TargetArch.Equals("x86", StringComparison.OrdinalIgnoreCase)) { _targetArchitecture = TargetArchitecture.X86; } else if (_commandLineOptions.TargetArch.Equals("x64", StringComparison.OrdinalIgnoreCase)) { _targetArchitecture = TargetArchitecture.X64; } else if (_commandLineOptions.TargetArch.Equals("arm", StringComparison.OrdinalIgnoreCase)) { _targetArchitecture = TargetArchitecture.ARM; } else if (_commandLineOptions.TargetArch.Equals("armel", StringComparison.OrdinalIgnoreCase)) { _targetArchitecture = TargetArchitecture.ARM; } else if (_commandLineOptions.TargetArch.Equals("arm64", StringComparison.OrdinalIgnoreCase)) { _targetArchitecture = TargetArchitecture.ARM64; } else { throw new CommandLineException("Target architecture is not supported"); } } if (_commandLineOptions.TargetOS != null) { if (_commandLineOptions.TargetOS.Equals("windows", StringComparison.OrdinalIgnoreCase)) { _targetOS = TargetOS.Windows; } else if (_commandLineOptions.TargetOS.Equals("linux", StringComparison.OrdinalIgnoreCase)) { _targetOS = TargetOS.Linux; } else if (_commandLineOptions.TargetOS.Equals("osx", StringComparison.OrdinalIgnoreCase)) { _targetOS = TargetOS.OSX; } else { throw new CommandLineException("Target OS is not supported"); } } using (PerfEventSource.StartStopEvents.CompilationEvents()) { ICompilation compilation; using (PerfEventSource.StartStopEvents.LoadingEvents()) { // // Initialize type system context // SharedGenericsMode genericsMode = SharedGenericsMode.CanonicalReferenceTypes; var targetDetails = new TargetDetails(_targetArchitecture, _targetOS, TargetAbi.CoreRT, SimdVectorLength.None); CompilerTypeSystemContext typeSystemContext = new ReadyToRunCompilerContext(targetDetails, genericsMode); // // TODO: To support our pre-compiled test tree, allow input files that aren't managed assemblies since // some tests contain a mixture of both managed and native binaries. // // See: https://github.com/dotnet/corert/issues/2785 // // When we undo this this hack, replace this foreach with // typeSystemContext.InputFilePaths = _inputFilePaths; // Dictionary <string, string> inputFilePaths = new Dictionary <string, string>(); foreach (var inputFile in _inputFilePaths) { try { var module = typeSystemContext.GetModuleFromPath(inputFile.Value); inputFilePaths.Add(inputFile.Key, inputFile.Value); } catch (TypeSystemException.BadImageFormatException) { // Keep calm and carry on. } } typeSystemContext.InputFilePaths = inputFilePaths; typeSystemContext.ReferenceFilePaths = _referenceFilePaths; string systemModuleName = _commandLineOptions.SystemModule ?? DefaultSystemModule; typeSystemContext.SetSystemModule(typeSystemContext.GetModuleForSimpleName(systemModuleName)); if (typeSystemContext.InputFilePaths.Count == 0) { throw new CommandLineException("No input files specified"); } // // Initialize compilation group and compilation roots // // Single method mode? MethodDesc singleMethod = CheckAndParseSingleMethodModeArguments(typeSystemContext); var logger = new Logger(Console.Out, _commandLineOptions.Verbose); List <ModuleDesc> referenceableModules = new List <ModuleDesc>(); foreach (var inputFile in inputFilePaths) { try { referenceableModules.Add(typeSystemContext.GetModuleFromPath(inputFile.Value)); } catch { } // Ignore non-managed pe files } foreach (var referenceFile in _referenceFilePaths.Values) { try { referenceableModules.Add(typeSystemContext.GetModuleFromPath(referenceFile)); } catch { } // Ignore non-managed pe files } ProfileDataManager profileDataManager = new ProfileDataManager(logger, referenceableModules); CompilationModuleGroup compilationGroup; List <ICompilationRootProvider> compilationRoots = new List <ICompilationRootProvider>(); if (singleMethod != null) { // Compiling just a single method compilationGroup = new SingleMethodCompilationModuleGroup(singleMethod); compilationRoots.Add(new SingleMethodRootProvider(singleMethod)); } else { // Either single file, or multifile library, or multifile consumption. EcmaModule entrypointModule = null; foreach (var inputFile in typeSystemContext.InputFilePaths) { EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value); if (module.PEReader.PEHeaders.IsExe) { if (entrypointModule != null) { throw new Exception("Multiple EXE modules"); } entrypointModule = module; } } List <EcmaModule> inputModules = new List <EcmaModule>(); foreach (var inputFile in typeSystemContext.InputFilePaths) { EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value); compilationRoots.Add(new ReadyToRunRootProvider(module, profileDataManager)); inputModules.Add(module); if (!_commandLineOptions.InputBubble) { break; } } List <ModuleDesc> versionBubbleModules = new List <ModuleDesc>(); if (_commandLineOptions.InputBubble) { // In large version bubble mode add reference paths to the compilation group foreach (string referenceFile in _referenceFilePaths.Values) { try { // Currently SimpleTest.targets has no easy way to filter out non-managed assemblies // from the reference list. EcmaModule module = typeSystemContext.GetModuleFromPath(referenceFile); versionBubbleModules.Add(module); } catch (TypeSystemException.BadImageFormatException ex) { Console.WriteLine("Warning: cannot open reference assembly '{0}': {1}", referenceFile, ex.Message); } } } compilationGroup = new ReadyToRunSingleAssemblyCompilationModuleGroup( typeSystemContext, inputModules, versionBubbleModules, _commandLineOptions.CompileBubbleGenerics, _commandLineOptions.Partial ? profileDataManager : null); } // // Compile // string inputFilePath = ""; foreach (var input in typeSystemContext.InputFilePaths) { inputFilePath = input.Value; break; } ReadyToRunCodegenCompilationBuilder builder = new ReadyToRunCodegenCompilationBuilder(typeSystemContext, compilationGroup, inputFilePath); string compilationUnitPrefix = ""; builder.UseCompilationUnitPrefix(compilationUnitPrefix); ILProvider ilProvider = new ReadyToRunILProvider(); DependencyTrackingLevel trackingLevel = _commandLineOptions.DgmlLogFileName == null ? DependencyTrackingLevel.None : (_commandLineOptions.GenerateFullDgmlLog ? DependencyTrackingLevel.All : DependencyTrackingLevel.First); builder .UseIbcTuning(_commandLineOptions.Tuning) .UseResilience(_commandLineOptions.Resilient) .UseMapFile(_commandLineOptions.Map) .UseParallelism(_commandLineOptions.Parallelism) .UseILProvider(ilProvider) .UseJitPath(_commandLineOptions.JitPath) .UseBackendOptions(_commandLineOptions.CodegenOptions) .UseLogger(logger) .UseDependencyTracking(trackingLevel) .UseCompilationRoots(compilationRoots) .UseOptimizationMode(_optimizationMode); compilation = builder.ToCompilation(); } compilation.Compile(_commandLineOptions.OutputFilePath.FullName); if (_commandLineOptions.DgmlLogFileName != null) { compilation.WriteDependencyLog(_commandLineOptions.DgmlLogFileName.FullName); } } return(0); }
/// <summary> /// Gets the dependency third-party packages binaries folder. /// </summary> /// <param name="options">The options.</param> /// <param name="platform">The target platform.</param> /// <param name="architecture">The target architecture.</param> /// <returns>The absolute path to the deps folder for the given platform and architecture configuration.</returns> public static string GetThirdPartyFolder(BuildOptions options, TargetPlatform platform, TargetArchitecture architecture) { return(Path.Combine(options.PlatformsFolder, platform.ToString(), "Binaries", "ThirdParty", architecture.ToString())); }
private int Run(string[] args) { InitializeDefaultOptions(); ArgumentSyntax syntax = ParseCommandLine(args); if (_help) { Help(syntax.GetHelpText()); return(1); } if (_outputFilePath == null) { throw new CommandLineException("Output filename must be specified (/out <file>)"); } // // Set target Architecture and OS // if (_targetArchitectureStr != null) { if (_targetArchitectureStr.Equals("x86", StringComparison.OrdinalIgnoreCase)) { _targetArchitecture = TargetArchitecture.X86; } else if (_targetArchitectureStr.Equals("x64", StringComparison.OrdinalIgnoreCase)) { _targetArchitecture = TargetArchitecture.X64; } else if (_targetArchitectureStr.Equals("arm", StringComparison.OrdinalIgnoreCase)) { _targetArchitecture = TargetArchitecture.ARM; } else if (_targetArchitectureStr.Equals("armel", StringComparison.OrdinalIgnoreCase)) { _targetArchitecture = TargetArchitecture.ARM; } else if (_targetArchitectureStr.Equals("arm64", StringComparison.OrdinalIgnoreCase)) { _targetArchitecture = TargetArchitecture.ARM64; } else if (_targetArchitectureStr.Equals("wasm", StringComparison.OrdinalIgnoreCase)) { _targetArchitecture = TargetArchitecture.Wasm32; _isWasmCodegen = true; } else { throw new CommandLineException("Target architecture is not supported"); } } if (_targetOSStr != null) { if (_targetOSStr.Equals("windows", StringComparison.OrdinalIgnoreCase)) { _targetOS = TargetOS.Windows; } else if (_targetOSStr.Equals("linux", StringComparison.OrdinalIgnoreCase)) { _targetOS = TargetOS.Linux; } else if (_targetOSStr.Equals("osx", StringComparison.OrdinalIgnoreCase)) { _targetOS = TargetOS.OSX; } else { throw new CommandLineException("Target OS is not supported"); } } if (_isWasmCodegen) { _targetArchitecture = TargetArchitecture.Wasm32; } // // Initialize type system context // SharedGenericsMode genericsMode = _useSharedGenerics || !_isWasmCodegen ? SharedGenericsMode.CanonicalReferenceTypes : SharedGenericsMode.Disabled; // TODO: compiler switch for SIMD support? var simdVectorLength = (_isCppCodegen || _isWasmCodegen) ? SimdVectorLength.None : SimdVectorLength.Vector128Bit; var targetAbi = _isCppCodegen ? TargetAbi.CppCodegen : TargetAbi.CoreRT; var targetDetails = new TargetDetails(_targetArchitecture, _targetOS, targetAbi, simdVectorLength); CompilerTypeSystemContext typeSystemContext = (_isReadyToRunCodeGen ? new ReadyToRunCompilerContext(targetDetails, genericsMode) : new CompilerTypeSystemContext(targetDetails, genericsMode)); // // TODO: To support our pre-compiled test tree, allow input files that aren't managed assemblies since // some tests contain a mixture of both managed and native binaries. // // See: https://github.com/dotnet/corert/issues/2785 // // When we undo this this hack, replace this foreach with // typeSystemContext.InputFilePaths = _inputFilePaths; // Dictionary <string, string> inputFilePaths = new Dictionary <string, string>(); foreach (var inputFile in _inputFilePaths) { try { var module = typeSystemContext.GetModuleFromPath(inputFile.Value); inputFilePaths.Add(inputFile.Key, inputFile.Value); } catch (TypeSystemException.BadImageFormatException) { // Keep calm and carry on. } } typeSystemContext.InputFilePaths = inputFilePaths; typeSystemContext.ReferenceFilePaths = _referenceFilePaths; typeSystemContext.SetSystemModule(typeSystemContext.GetModuleForSimpleName(_systemModuleName)); if (typeSystemContext.InputFilePaths.Count == 0) { throw new CommandLineException("No input files specified"); } // // Initialize compilation group and compilation roots // // Single method mode? MethodDesc singleMethod = CheckAndParseSingleMethodModeArguments(typeSystemContext); CompilationModuleGroup compilationGroup; List <ICompilationRootProvider> compilationRoots = new List <ICompilationRootProvider>(); if (singleMethod != null) { // Compiling just a single method compilationGroup = new SingleMethodCompilationModuleGroup(singleMethod); compilationRoots.Add(new SingleMethodRootProvider(singleMethod)); } else { // Either single file, or multifile library, or multifile consumption. EcmaModule entrypointModule = null; bool systemModuleIsInputModule = false; foreach (var inputFile in typeSystemContext.InputFilePaths) { EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value); if (module.PEReader.PEHeaders.IsExe) { if (entrypointModule != null) { throw new Exception("Multiple EXE modules"); } entrypointModule = module; } if (module == typeSystemContext.SystemModule) { systemModuleIsInputModule = true; } if (!_isReadyToRunCodeGen) { compilationRoots.Add(new ExportedMethodsRootProvider(module)); } } if (entrypointModule != null && !_isReadyToRunCodeGen) { compilationRoots.Add(new MainMethodRootProvider(entrypointModule, CreateInitializerList(typeSystemContext))); compilationRoots.Add(new RuntimeConfigurationRootProvider(_runtimeOptions)); } if (_isReadyToRunCodeGen) { List <EcmaModule> inputModules = new List <EcmaModule>(); foreach (var inputFile in typeSystemContext.InputFilePaths) { EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value); compilationRoots.Add(new ReadyToRunRootProvider(module)); inputModules.Add(module); if (!_isInputVersionBubble) { break; } } compilationGroup = new ReadyToRunSingleAssemblyCompilationModuleGroup(typeSystemContext, inputModules); } else if (_multiFile) { List <EcmaModule> inputModules = new List <EcmaModule>(); foreach (var inputFile in typeSystemContext.InputFilePaths) { EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value); if (entrypointModule == null) { // This is a multifile production build - we need to root all methods compilationRoots.Add(new LibraryRootProvider(module)); } inputModules.Add(module); } compilationGroup = new MultiFileSharedCompilationModuleGroup(typeSystemContext, inputModules); } else { if (entrypointModule == null && !_nativeLib) { throw new Exception("No entrypoint module"); } if (!systemModuleIsInputModule) { compilationRoots.Add(new ExportedMethodsRootProvider((EcmaModule)typeSystemContext.SystemModule)); } compilationGroup = new SingleFileCompilationModuleGroup(); if (_rootAllApplicationAssemblies) { compilationRoots.Add(new ApplicationAssemblyRootProvider(typeSystemContext)); } } if (_nativeLib) { // Set owning module of generated native library startup method to compiler generated module, // to ensure the startup method is included in the object file during multimodule mode build compilationRoots.Add(new NativeLibraryInitializerRootProvider(typeSystemContext.GeneratedAssembly, CreateInitializerList(typeSystemContext))); compilationRoots.Add(new RuntimeConfigurationRootProvider(_runtimeOptions)); } if (_rdXmlFilePaths.Count > 0) { Console.WriteLine("Warning: RD.XML processing will change before release (https://github.com/dotnet/corert/issues/5001)"); } foreach (var rdXmlFilePath in _rdXmlFilePaths) { compilationRoots.Add(new RdXmlRootProvider(typeSystemContext, rdXmlFilePath)); } } // // Compile // CompilationBuilder builder; if (_isWasmCodegen) { builder = new WebAssemblyCodegenCompilationBuilder(typeSystemContext, compilationGroup); } else if (_isReadyToRunCodeGen) { string inputFilePath = ""; foreach (var input in typeSystemContext.InputFilePaths) { inputFilePath = input.Value; break; } builder = new ReadyToRunCodegenCompilationBuilder(typeSystemContext, compilationGroup, inputFilePath); } else if (_isCppCodegen) { builder = new CppCodegenCompilationBuilder(typeSystemContext, compilationGroup); } else { builder = new RyuJitCompilationBuilder(typeSystemContext, compilationGroup); } string compilationUnitPrefix = _multiFile ? System.IO.Path.GetFileNameWithoutExtension(_outputFilePath) : ""; builder.UseCompilationUnitPrefix(compilationUnitPrefix); if (!_isCppCodegen && !_isWasmCodegen) { builder.UsePInvokePolicy(new ConfigurablePInvokePolicy(typeSystemContext.Target)); } RemovedFeature removedFeatures = 0; foreach (string feature in _removedFeatures) { if (feature == "EventSource") { removedFeatures |= RemovedFeature.Etw; } else if (feature == "FrameworkStrings") { removedFeatures |= RemovedFeature.FrameworkResources; } else if (feature == "Globalization") { removedFeatures |= RemovedFeature.Globalization; } else if (feature == "Comparers") { removedFeatures |= RemovedFeature.Comparers; } else if (feature == "CurlHandler") { removedFeatures |= RemovedFeature.CurlHandler; } } ILProvider ilProvider = _isReadyToRunCodeGen ? (ILProvider) new ReadyToRunILProvider() : new CoreRTILProvider(); if (removedFeatures != 0) { ilProvider = new RemovingILProvider(ilProvider, removedFeatures); } var stackTracePolicy = _emitStackTraceData ? (StackTraceEmissionPolicy) new EcmaMethodStackTraceEmissionPolicy() : new NoStackTraceEmissionPolicy(); MetadataBlockingPolicy mdBlockingPolicy = _noMetadataBlocking ? (MetadataBlockingPolicy) new NoMetadataBlockingPolicy() : new BlockedInternalsBlockingPolicy(typeSystemContext); ManifestResourceBlockingPolicy resBlockingPolicy = (removedFeatures & RemovedFeature.FrameworkResources) != 0 ? new FrameworkStringResourceBlockingPolicy() : (ManifestResourceBlockingPolicy) new NoManifestResourceBlockingPolicy(); UsageBasedMetadataGenerationOptions metadataGenerationOptions = UsageBasedMetadataGenerationOptions.AnonymousTypeHeuristic; if (_completeTypesMetadata) { metadataGenerationOptions |= UsageBasedMetadataGenerationOptions.CompleteTypesOnly; } if (_scanReflection) { metadataGenerationOptions |= UsageBasedMetadataGenerationOptions.ILScanning; } DynamicInvokeThunkGenerationPolicy invokeThunkGenerationPolicy = new DefaultDynamicInvokeThunkGenerationPolicy(); bool supportsReflection = !_disableReflection && !_isReadyToRunCodeGen && _systemModuleName == DefaultSystemModule; MetadataManager metadataManager; if (_isReadyToRunCodeGen) { metadataManager = new ReadyToRunTableManager(typeSystemContext); } else if (supportsReflection) { metadataManager = new UsageBasedMetadataManager( compilationGroup, typeSystemContext, mdBlockingPolicy, resBlockingPolicy, _metadataLogFileName, stackTracePolicy, invokeThunkGenerationPolicy, ilProvider, metadataGenerationOptions); } else { metadataManager = new EmptyMetadataManager(typeSystemContext); } // Unless explicitly opted in at the command line, we enable scanner for retail builds by default. // We don't do this for CppCodegen and Wasm, because those codegens are behind. // We also don't do this for multifile because scanner doesn't simulate inlining (this would be // fixable by using a CompilationGroup for the scanner that has a bigger worldview, but // let's cross that bridge when we get there). bool useScanner = _useScanner || (_optimizationMode != OptimizationMode.None && !_isCppCodegen && !_isWasmCodegen && !_isReadyToRunCodeGen && !_multiFile); useScanner &= !_noScanner; builder.UseILProvider(ilProvider); ILScanResults scanResults = null; if (useScanner) { ILScannerBuilder scannerBuilder = builder.GetILScannerBuilder() .UseCompilationRoots(compilationRoots) .UseMetadataManager(metadataManager); if (_scanDgmlLogFileName != null) { scannerBuilder.UseDependencyTracking(_generateFullScanDgmlLog ? DependencyTrackingLevel.All : DependencyTrackingLevel.First); } IILScanner scanner = scannerBuilder.ToILScanner(); scanResults = scanner.Scan(); if (metadataManager is UsageBasedMetadataManager usageBasedManager) { metadataManager = usageBasedManager.ToAnalysisBasedMetadataManager(); } } var logger = new Logger(Console.Out, _isVerbose); DebugInformationProvider debugInfoProvider = _enableDebugInfo ? (_ilDump == null ? new DebugInformationProvider() : new ILAssemblyGeneratingMethodDebugInfoProvider(_ilDump, new EcmaOnlyDebugInformationProvider())) : new NullDebugInformationProvider(); DependencyTrackingLevel trackingLevel = _dgmlLogFileName == null ? DependencyTrackingLevel.None : (_generateFullDgmlLog ? DependencyTrackingLevel.All : DependencyTrackingLevel.First); compilationRoots.Add(metadataManager); builder .UseBackendOptions(_codegenOptions) .UseMethodBodyFolding(_methodBodyFolding) .UseMetadataManager(metadataManager) .UseLogger(logger) .UseDependencyTracking(trackingLevel) .UseCompilationRoots(compilationRoots) .UseOptimizationMode(_optimizationMode) .UseDebugInfoProvider(debugInfoProvider); if (scanResults != null) { // If we have a scanner, feed the vtable analysis results to the compilation. // This could be a command line switch if we really wanted to. builder.UseVTableSliceProvider(scanResults.GetVTableLayoutInfo()); // If we have a scanner, feed the generic dictionary results to the compilation. // This could be a command line switch if we really wanted to. builder.UseGenericDictionaryLayoutProvider(scanResults.GetDictionaryLayoutInfo()); // If we feed any outputs of the scanner into the compilation, it's essential // we use scanner's devirtualization manager. It prevents optimizing codegens // from accidentally devirtualizing cases that can never happen at runtime // (e.g. devirtualizing a method on a type that never gets allocated). builder.UseDevirtualizationManager(scanResults.GetDevirtualizationManager()); } ICompilation compilation = builder.ToCompilation(); ObjectDumper dumper = _mapFileName != null ? new ObjectDumper(_mapFileName) : null; CompilationResults compilationResults = compilation.Compile(_outputFilePath, dumper); if (_exportsFile != null) { ExportsFileWriter defFileWriter = new ExportsFileWriter(typeSystemContext, _exportsFile); foreach (var compilationRoot in compilationRoots) { if (compilationRoot is ExportedMethodsRootProvider provider) { defFileWriter.AddExportedMethods(provider.ExportedMethods); } } defFileWriter.EmitExportedMethods(); } if (_dgmlLogFileName != null) { compilationResults.WriteDependencyLog(_dgmlLogFileName); } if (scanResults != null) { SimdHelper simdHelper = new SimdHelper(); if (_scanDgmlLogFileName != null) { scanResults.WriteDependencyLog(_scanDgmlLogFileName); } // If the scanner and compiler don't agree on what to compile, the outputs of the scanner might not actually be usable. // We are going to check this two ways: // 1. The methods and types generated during compilation are a subset of method and types scanned // 2. The methods and types scanned are a subset of methods and types compiled (this has a chance to hold for unoptimized builds only). // Check that methods and types generated during compilation are a subset of method and types scanned bool scanningFail = false; DiffCompilationResults(ref scanningFail, compilationResults.CompiledMethodBodies, scanResults.CompiledMethodBodies, "Methods", "compiled", "scanned", method => !(method.GetTypicalMethodDefinition() is EcmaMethod) || method.Name == "ThrowPlatformNotSupportedException"); DiffCompilationResults(ref scanningFail, compilationResults.ConstructedEETypes, scanResults.ConstructedEETypes, "EETypes", "compiled", "scanned", type => !(type.GetTypeDefinition() is EcmaType)); // If optimizations are enabled, the results will for sure not match in the other direction due to inlining, etc. // But there's at least some value in checking the scanner doesn't expand the universe too much in debug. if (_optimizationMode == OptimizationMode.None) { // Check that methods and types scanned are a subset of methods and types compiled // If we find diffs here, they're not critical, but still might be causing a Size on Disk regression. bool dummy = false; // We additionally skip methods in SIMD module because there's just too many intrisics to handle and IL scanner // doesn't expand them. They would show up as noisy diffs. DiffCompilationResults(ref dummy, scanResults.CompiledMethodBodies, compilationResults.CompiledMethodBodies, "Methods", "scanned", "compiled", method => !(method.GetTypicalMethodDefinition() is EcmaMethod) || simdHelper.IsSimdType(method.OwningType)); DiffCompilationResults(ref dummy, scanResults.ConstructedEETypes, compilationResults.ConstructedEETypes, "EETypes", "scanned", "compiled", type => !(type.GetTypeDefinition() is EcmaType)); } if (scanningFail) { throw new Exception("Scanning failure"); } } if (debugInfoProvider is IDisposable) { ((IDisposable)debugInfoProvider).Dispose(); } return(0); }
/// <summary> /// Creates the toolchain for a given architecture. /// </summary> /// <param name="architecture">The architecture.</param> /// <returns>The toolchain.</returns> protected abstract Toolchain CreateToolchain(TargetArchitecture architecture);
public override unsafe ValueTypeShapeCharacteristics ComputeValueTypeShapeCharacteristics(DefType type) { // Use this constant to make the code below more laconic const ValueTypeShapeCharacteristics NotHA = ValueTypeShapeCharacteristics.None; Debug.Assert(type.IsValueType); TargetArchitecture targetArch = type.Context.Target.Architecture; if ((targetArch != TargetArchitecture.ARM) && (targetArch != TargetArchitecture.ARM64)) { return(NotHA); } if (!type.IsValueType) { return(NotHA); } // There is no reason to compute the entire field layout for the HA type/flag if // the template type is not a universal generic type (information stored in rare flags on the MethodTable) TypeDesc templateType = type.ComputeTemplate(false); if (templateType != null && !templateType.IsCanonicalSubtype(CanonicalFormKind.Universal)) { MethodTable *pEETemplate = templateType.GetRuntimeTypeHandle().ToEETypePtr(); if (!pEETemplate->IsHFA) { return(NotHA); } if (pEETemplate->RequiresAlign8) { return(ValueTypeShapeCharacteristics.Float64Aggregate); } else { return(ValueTypeShapeCharacteristics.Float32Aggregate); } } // Once this is done, the NativeLayoutFields on the type are initialized EnsureFieldLayoutLoadedForGenericType((DefType)type); Debug.Assert(type.NativeLayoutFields != null); // Empty types are not HA if (type.NativeLayoutFields.Length == 0) { return(NotHA); } // Find the common HA element type if any ValueTypeShapeCharacteristics haResultType = NotHA; for (int i = 0; i < type.NativeLayoutFields.Length; i++) { TypeDesc fieldType = type.NativeLayoutFields[i].FieldType; if (type.NativeLayoutFields[i].FieldStorage != NativeFormat.FieldStorage.Instance) { continue; } // If a field isn't a DefType, then this type cannot be a HA type if (!(fieldType is DefType fieldDefType)) { return(NotHA); } // HA types cannot contain non-HA types ValueTypeShapeCharacteristics haFieldType = fieldDefType.ValueTypeShapeCharacteristics & ValueTypeShapeCharacteristics.AggregateMask; if (haFieldType == NotHA) { return(NotHA); } if (haResultType == NotHA) { haResultType = haFieldType; } else if (haResultType != haFieldType) { return(NotHA); // If the field doesn't have the same HA type as the one we've looked at before, the type cannot be HA } } // If we didn't find any instance fields, then this can't be a HA type if (haResultType == NotHA) { return(NotHA); } int haElementSize = haResultType switch { ValueTypeShapeCharacteristics.Float32Aggregate => 4, ValueTypeShapeCharacteristics.Float64Aggregate => 8, ValueTypeShapeCharacteristics.Vector64Aggregate => 8, ValueTypeShapeCharacteristics.Vector128Aggregate => 16, _ => throw new ArgumentOutOfRangeException() }; // Note that we check the total size, but do not perform any checks on number of fields: // - Type of fields can be HA valuetype itself // - Managed C++ HFA valuetypes have just one <alignment member> of type float to signal that // the valuetype is HFA and explicitly specified size int maxSize = haElementSize * type.Context.Target.MaxHomogeneousAggregateElementCount; if (type.InstanceFieldSize.AsInt > maxSize) { return(NotHA); } return(haResultType); }
private bool TryGetAssemblyNameDefinition(string assemblyFilePath, bool caching, TargetArchitecture architecture, out AssemblyName assemblyName, bool checkForArchitectPlatfrom = true) { assemblyName = null; if (pathRepository.AssemblyNameDefinition.ContainsKey(assemblyFilePath)) { assemblyName = pathRepository.AssemblyNameDefinition[assemblyFilePath]; if (!checkForArchitectPlatfrom) { return true; } else if (assemblyName.TargetArchitecture == architecture) { return true; } } if ((caching || assemblyName == null) && File.Exists(assemblyFilePath)) { var moduleDef = ModuleDefinition.ReadModule(assemblyFilePath, readerParameters); if (moduleDef != null && moduleDef.Assembly != null) { AssemblyDefinition assemblyDef = moduleDef.Assembly; assemblyName = new AssemblyName(moduleDef.Name, assemblyDef.FullName, assemblyDef.Name.Version, assemblyDef.Name.PublicKeyToken, Path.GetDirectoryName(assemblyFilePath)) { TargetArchitecture = moduleDef.GetModuleArchitecture() }; pathRepository.AssemblyNameDefinition[assemblyFilePath] = assemblyName; return true; } } return false; }
public override AssemblyDefinition Resolve(string fullName, ReaderParameters parameters, TargetArchitecture platform, bool bubbleToUserIfFailed = true) { return base.Resolve(fullName, parameters, platform, bubbleToUserIfFailed: false); }
public TestTypeSystemContext(TargetArchitecture arch) : base(new TargetDetails(arch, TargetOS.Unknown)) { }
/// <summary> /// Tries to create the build toolchain for a given architecture. Returns null if platform is not supported. /// </summary> /// <param name="targetArchitecture">The target architecture.</param> /// <returns>The toolchain.</returns> public Toolchain TryGetToolchain(TargetArchitecture targetArchitecture) { return(HasRequiredSDKsInstalled ? GetToolchain(targetArchitecture) : null); }
public TestTypeSystemContext(TargetArchitecture arch) : base(new TargetDetails(arch, TargetOS.Unknown, TargetAbi.Unknown)) { }
public void SetTargetArch(TargetArchitecture arch) { switch (arch) { case TargetArchitecture.ARM: MaxInstructionSize = 4; Is64BitArch = false; break; case TargetArchitecture.ARM64: MaxInstructionSize = 8; Is64BitArch = true; break; case TargetArchitecture.X86: MaxInstructionSize = 20; Is64BitArch = false; break; case TargetArchitecture.X64: MaxInstructionSize = 26; Is64BitArch = true; break; case TargetArchitecture.Mips: MaxInstructionSize = 4; Is64BitArch = false; break; default: throw new ArgumentOutOfRangeException("options.TargetArchitecture"); } }
public override bool Execute() { TargetArchitecture architectures, deviceArchitectures, target = TargetArchitecture.Default; string targetOperatingSystem; PDictionary plist, device; PString value, os; switch (Platform) { case ApplePlatform.WatchOS: targetOperatingSystem = "watchOS"; break; case ApplePlatform.TVOS: targetOperatingSystem = "tvOS"; break; default: targetOperatingSystem = "iOS"; break; } if (!Enum.TryParse(Architectures, out architectures)) { Log.LogError(MSBStrings.E0057, Architectures); return(false); } if ((plist = PObject.FromString(TargetiOSDevice) as PDictionary) == null) { Log.LogError(MSBStrings.E0058); return(false); } if (!plist.TryGetValue("device", out device)) { Log.LogError(MSBStrings.E0059); return(false); } if (!device.TryGetValue("architecture", out value)) { Log.LogError(MSBStrings.E0060); return(false); } if (!Enum.TryParse(value.Value, out deviceArchitectures) || deviceArchitectures == TargetArchitecture.Default) { Log.LogError(MSBStrings.E0061, value.Value); return(false); } if (!device.TryGetValue("os", out os)) { Log.LogError(MSBStrings.E0062); return(false); } if (os.Value != targetOperatingSystem || (architectures & deviceArchitectures) == 0) { // the TargetiOSDevice property conflicts with the build configuration (*.user file?), do not build this project for a specific device DeviceSpecificIntermediateOutputPath = IntermediateOutputPath; DeviceSpecificOutputPath = OutputPath; TargetArchitectures = Architectures; TargetDeviceOSVersion = string.Empty; TargetDeviceModel = string.Empty; return(!Log.HasLoggedErrors); } for (int bit = 0; bit < 32; bit++) { var architecture = (TargetArchitecture)(1 << bit); if ((architectures & architecture) == 0) { continue; } if ((deviceArchitectures & architecture) != 0) { target = architecture; } } TargetArchitectures = target.ToString(); if (!device.TryGetValue("model", out value)) { Log.LogError(MSBStrings.E0063); return(false); } TargetDeviceModel = value.Value; if (!device.TryGetValue("os-version", out value)) { Log.LogError(MSBStrings.E0064); return(false); } TargetDeviceOSVersion = value.Value; // Note: we replace ',' with '.' because the ',' breaks the Mono AOT compiler which tries to treat arguments with ','s in them as options. var dirName = TargetDeviceModel.ToLowerInvariant().Replace(",", ".") + "-" + TargetDeviceOSVersion; DeviceSpecificIntermediateOutputPath = Path.Combine(IntermediateOutputPath, "device-builds", dirName) + "/"; DeviceSpecificOutputPath = Path.Combine(OutputPath, "device-builds", dirName) + "/"; return(!Log.HasLoggedErrors); }
public override AssemblyDefinition Resolve(string fullName, ReaderParameters parameters, TargetArchitecture platform, bool bubbleToUserIfFailed = true) { return(base.Resolve(fullName, parameters, platform, bubbleToUserIfFailed: false)); }
public override AssemblyDefinition Resolve(AssemblyNameReference name, string path, TargetArchitecture architecture, bool addToFailedCache, bool bubbleToUserIfFailed = true) { return(base.Resolve(name, path, architecture, addToFailedCache, bubbleToUserIfFailed: false)); }
/*Telerik Authorship*/ public virtual AssemblyDefinition Resolve(string fullName, ReaderParameters parameters, TargetArchitecture platform, bool bubbleToUserIfFailed = true) { lock (Locker) { if (fullName == null) { throw new ArgumentNullException("fullName"); } return Resolve(AssemblyNameReference.Parse(fullName), string.Empty, parameters, platform, bubbleToUserIfFailed); } }
private int Run(string[] args) { InitializeDefaultOptions(); ArgumentSyntax syntax = ParseCommandLine(args); if (_help) { Help(syntax.GetHelpText()); return(1); } if (_outputFilePath == null) { throw new CommandLineException("Output filename must be specified (/out <file>)"); } // // Set target Architecture and OS // if (_targetArchitectureStr != null) { if (_targetArchitectureStr.Equals("x86", StringComparison.OrdinalIgnoreCase)) { _targetArchitecture = TargetArchitecture.X86; } else if (_targetArchitectureStr.Equals("x64", StringComparison.OrdinalIgnoreCase)) { _targetArchitecture = TargetArchitecture.X64; } else if (_targetArchitectureStr.Equals("arm", StringComparison.OrdinalIgnoreCase)) { _targetArchitecture = TargetArchitecture.ARM; } else if (_targetArchitectureStr.Equals("armel", StringComparison.OrdinalIgnoreCase)) { _targetArchitecture = TargetArchitecture.ARMEL; } else if (_targetArchitectureStr.Equals("arm64", StringComparison.OrdinalIgnoreCase)) { _targetArchitecture = TargetArchitecture.ARM64; } else { throw new CommandLineException("Target architecture is not supported"); } } if (_targetOSStr != null) { if (_targetOSStr.Equals("windows", StringComparison.OrdinalIgnoreCase)) { _targetOS = TargetOS.Windows; } else if (_targetOSStr.Equals("linux", StringComparison.OrdinalIgnoreCase)) { _targetOS = TargetOS.Linux; } else if (_targetOSStr.Equals("osx", StringComparison.OrdinalIgnoreCase)) { _targetOS = TargetOS.OSX; } else { throw new CommandLineException("Target OS is not supported"); } } // // Initialize type system context // SharedGenericsMode genericsMode = _useSharedGenerics || !_isCppCodegen ? SharedGenericsMode.CanonicalReferenceTypes : SharedGenericsMode.Disabled; // TODO: compiler switch for SIMD support? var simdVectorLength = _isCppCodegen ? SimdVectorLength.None : SimdVectorLength.Vector128Bit; var targetDetails = new TargetDetails(_targetArchitecture, _targetOS, TargetAbi.CoreRT, simdVectorLength); var typeSystemContext = new CompilerTypeSystemContext(targetDetails, genericsMode); // // TODO: To support our pre-compiled test tree, allow input files that aren't managed assemblies since // some tests contain a mixture of both managed and native binaries. // // See: https://github.com/dotnet/corert/issues/2785 // // When we undo this this hack, replace this foreach with // typeSystemContext.InputFilePaths = _inputFilePaths; // Dictionary <string, string> inputFilePaths = new Dictionary <string, string>(); foreach (var inputFile in _inputFilePaths) { try { var module = typeSystemContext.GetModuleFromPath(inputFile.Value); inputFilePaths.Add(inputFile.Key, inputFile.Value); } catch (TypeSystemException.BadImageFormatException) { // Keep calm and carry on. } } typeSystemContext.InputFilePaths = inputFilePaths; typeSystemContext.ReferenceFilePaths = _referenceFilePaths; typeSystemContext.SetSystemModule(typeSystemContext.GetModuleForSimpleName(_systemModuleName)); if (typeSystemContext.InputFilePaths.Count == 0) { throw new CommandLineException("No input files specified"); } // // Initialize compilation group and compilation roots // // Single method mode? MethodDesc singleMethod = CheckAndParseSingleMethodModeArguments(typeSystemContext); CompilationModuleGroup compilationGroup; List <ICompilationRootProvider> compilationRoots = new List <ICompilationRootProvider>(); if (singleMethod != null) { // Compiling just a single method compilationGroup = new SingleMethodCompilationModuleGroup(singleMethod); compilationRoots.Add(new SingleMethodRootProvider(singleMethod)); } else { // Either single file, or multifile library, or multifile consumption. EcmaModule entrypointModule = null; foreach (var inputFile in typeSystemContext.InputFilePaths) { EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value); if (module.PEReader.PEHeaders.IsExe) { if (entrypointModule != null) { throw new Exception("Multiple EXE modules"); } entrypointModule = module; } compilationRoots.Add(new ExportedMethodsRootProvider(module)); } if (entrypointModule != null) { LibraryInitializers libraryInitializers = new LibraryInitializers(typeSystemContext, _isCppCodegen); compilationRoots.Add(new MainMethodRootProvider(entrypointModule, libraryInitializers.LibraryInitializerMethods)); } if (_multiFile) { List <EcmaModule> inputModules = new List <EcmaModule>(); foreach (var inputFile in typeSystemContext.InputFilePaths) { EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value); if (entrypointModule == null) { // This is a multifile production build - we need to root all methods compilationRoots.Add(new LibraryRootProvider(module)); } inputModules.Add(module); } compilationGroup = new MultiFileSharedCompilationModuleGroup(typeSystemContext, inputModules); } else { if (entrypointModule == null) { throw new Exception("No entrypoint module"); } compilationRoots.Add(new ExportedMethodsRootProvider((EcmaModule)typeSystemContext.SystemModule)); compilationGroup = new SingleFileCompilationModuleGroup(typeSystemContext); } foreach (var rdXmlFilePath in _rdXmlFilePaths) { compilationRoots.Add(new RdXmlRootProvider(typeSystemContext, rdXmlFilePath)); } } // // Compile // CompilationBuilder builder; if (_isCppCodegen) { builder = new CppCodegenCompilationBuilder(typeSystemContext, compilationGroup); } else { builder = new RyuJitCompilationBuilder(typeSystemContext, compilationGroup); } bool useScanner = _useScanner || (_optimizationMode != OptimizationMode.None && !_isCppCodegen); useScanner &= !_noScanner; ILScanResults scanResults = null; if (useScanner) { ILScannerBuilder scannerBuilder = builder.GetILScannerBuilder() .UseCompilationRoots(compilationRoots); if (_scanDgmlLogFileName != null) { scannerBuilder.UseDependencyTracking(_generateFullScanDgmlLog ? DependencyTrackingLevel.All : DependencyTrackingLevel.First); } IILScanner scanner = scannerBuilder.ToILScanner(); scanResults = scanner.Scan(); } var logger = _isVerbose ? new Logger(Console.Out, true) : Logger.Null; DebugInformationProvider debugInfoProvider = _enableDebugInfo ? (_ilDump == null ? new DebugInformationProvider() : new ILAssemblyGeneratingMethodDebugInfoProvider(_ilDump, new EcmaOnlyDebugInformationProvider())) : new NullDebugInformationProvider(); DependencyTrackingLevel trackingLevel = _dgmlLogFileName == null ? DependencyTrackingLevel.None : (_generateFullDgmlLog ? DependencyTrackingLevel.All : DependencyTrackingLevel.First); CompilerGeneratedMetadataManager metadataManager = new CompilerGeneratedMetadataManager(compilationGroup, typeSystemContext, _metadataLogFileName); builder .UseBackendOptions(_codegenOptions) .UseMetadataManager(metadataManager) .UseLogger(logger) .UseDependencyTracking(trackingLevel) .UseCompilationRoots(compilationRoots) .UseOptimizationMode(_optimizationMode) .UseDebugInfoProvider(debugInfoProvider); if (scanResults != null) { // If we have a scanner, feed the vtable analysis results to the compilation. // This could be a command line switch if we really wanted to. builder.UseVTableSliceProvider(scanResults.GetVTableLayoutInfo()); // If we have a scanner, feed the generic dictionary results to the compilation. // This could be a command line switch if we really wanted to. builder.UseGenericDictionaryLayoutProvider(scanResults.GetDictionaryLayoutInfo()); } ICompilation compilation = builder.ToCompilation(); ObjectDumper dumper = _mapFileName != null ? new ObjectDumper(_mapFileName) : null; CompilationResults compilationResults = compilation.Compile(_outputFilePath, dumper); if (_dgmlLogFileName != null) { compilationResults.WriteDependencyLog(_dgmlLogFileName); } if (scanResults != null) { SimdHelper simdHelper = new SimdHelper(); if (_scanDgmlLogFileName != null) { scanResults.WriteDependencyLog(_scanDgmlLogFileName); } // If the scanner and compiler don't agree on what to compile, the outputs of the scanner might not actually be usable. // We are going to check this two ways: // 1. The methods and types generated during compilation are a subset of method and types scanned // 2. The methods and types scanned are a subset of methods and types compiled (this has a chance to hold for unoptimized builds only). // Check that methods and types generated during compilation are a subset of method and types scanned bool scanningFail = false; DiffCompilationResults(ref scanningFail, compilationResults.CompiledMethodBodies, scanResults.CompiledMethodBodies, "Methods", "compiled", "scanned", method => !(method.GetTypicalMethodDefinition() is EcmaMethod)); DiffCompilationResults(ref scanningFail, compilationResults.ConstructedEETypes, scanResults.ConstructedEETypes, "EETypes", "compiled", "scanned", type => !(type.GetTypeDefinition() is EcmaType)); // If optimizations are enabled, the results will for sure not match in the other direction due to inlining, etc. // But there's at least some value in checking the scanner doesn't expand the universe too much in debug. if (_optimizationMode == OptimizationMode.None) { // Check that methods and types scanned are a subset of methods and types compiled // If we find diffs here, they're not critical, but still might be causing a Size on Disk regression. bool dummy = false; // We additionally skip methods in SIMD module because there's just too many intrisics to handle and IL scanner // doesn't expand them. They would show up as noisy diffs. DiffCompilationResults(ref dummy, scanResults.CompiledMethodBodies, compilationResults.CompiledMethodBodies, "Methods", "scanned", "compiled", method => !(method.GetTypicalMethodDefinition() is EcmaMethod) || simdHelper.IsInSimdModule(method.OwningType)); DiffCompilationResults(ref dummy, scanResults.ConstructedEETypes, compilationResults.ConstructedEETypes, "EETypes", "scanned", "compiled", type => !(type.GetTypeDefinition() is EcmaType)); } if (scanningFail) { throw new Exception("Scanning failure"); } } if (debugInfoProvider is IDisposable) { ((IDisposable)debugInfoProvider).Dispose(); } return(0); }
/*Telerik Authorship*/ private AssemblyDefinition Resolve(AssemblyNameReference name, string defaultPath, ReaderParameters parameters, TargetArchitecture architecture, bool bubbleToUserIfFailed, bool addToFailedCache = true) { if (name == null) { throw new ArgumentNullException("name"); } if (parameters == null) { parameters = new ReaderParameters(this); } if (assemblyPathResolver.IsFailedAssembly(name.FullName)) { return null; } AssemblyDefinition assembly = GetFromResolvedAssemblies(new AssemblyName(name.Name, name.FullName, name.Version, name.PublicKey) { TargetArchitecture = architecture }); if (assembly != null) { return assembly; } assembly = SearchDirectory(name, parameters, architecture, defaultPath) ?? TryGetTargetAssembly(name, parameters, architecture); if (assembly != null) { if (!filePathToAssemblyDefinitionCache.ContainsKey(assembly.MainModule.FilePath)) { AddToResolvedAssemblies(assembly); } return assembly; } assembly = GetTargetAssembly(name, parameters, architecture); if (assembly != null) { if (!filePathToAssemblyDefinitionCache.ContainsKey(assembly.MainModule.FilePath)) { AddToResolvedAssemblies(assembly); } return assembly; } if (bubbleToUserIfFailed) { return UserSpecifiedAssembly(name, architecture); } else if (addToFailedCache) { assemblyPathResolver.AddToUnresolvedCache(name.FullName); } return null; }
/*Telerik Authorship*/ internal TypeDefinition Resolve(TypeReference type, ICollection <string> visitedDlls) { if (type == null) { throw new ArgumentNullException("type"); } // TODO: The following code must be uncommented when bug 284860 (the one with the Resolver) is fixed. //if (type is ArrayType) //{ // type = type.Module.TypeSystem.LookupType("System", "Array"); //} //else //{ type = type.GetElementType(); //} var scope = type.Scope; if (scope == null) { return(null); } switch (scope.MetadataScopeType) { case MetadataScopeType.AssemblyNameReference: /*Telerik Authorship*/ TargetArchitecture architecture = type.Module.GetModuleArchitecture(); SpecialTypeAssembly special = type.Module.IsReferenceAssembly() ? SpecialTypeAssembly.Reference : SpecialTypeAssembly.None; var assembly = assembly_resolver.Resolve((AssemblyNameReference)scope, type.Module.ModuleDirectoryPath, architecture, special); if (assembly == null) { return(null); } /*Telerik Authorship*/ if (visitedDlls.Contains(assembly.MainModule.FilePath)) { return(null); } visitedDlls.Add(assembly.MainModule.FilePath); return(GetType(assembly.MainModule, type, visitedDlls)); case MetadataScopeType.ModuleDefinition: /*Telerik Authorship*/ ModuleDefinition theModule = (ModuleDefinition)scope; if (visitedDlls.Contains(theModule.FilePath)) { return(null); } visitedDlls.Add(theModule.FilePath); return(GetType(theModule, type, visitedDlls)); case MetadataScopeType.ModuleReference: var modules = type.Module.Assembly.Modules; var module_ref = (ModuleReference)scope; for (int i = 0; i < modules.Count; i++) { var netmodule = modules[i]; if (netmodule.Name == module_ref.Name) { /*Telerik Authorship*/ if (visitedDlls.Contains(netmodule.FilePath)) { return(null); } visitedDlls.Add(netmodule.FilePath); return(GetType(netmodule, type, visitedDlls)); } } break; } throw new NotSupportedException(); }
/*Telerik Authorship*/ private AssemblyDefinition SearchDirectory(AssemblyNameReference name, ReaderParameters parameters, TargetArchitecture architecture, string defaultPath) { var defaultLocations = DirectoryAssemblies.Where(d => d.Dir.Equals(defaultPath, StringComparison.OrdinalIgnoreCase)); AssemblyDefinition ad; if (TrySearchDirectory(name, parameters, architecture, defaultLocations, out ad)) { return ad; } var notDefaultLocations = DirectoryAssemblies.Except(defaultLocations); if (TrySearchDirectory(name, parameters, architecture, notDefaultLocations, out ad)) { return ad; } return null; }
/// <inheritdoc /> protected override Toolchain CreateToolchain(TargetArchitecture architecture) { return(new UWPToolchain(this, architecture)); }
public AssemblyResolveEventArgs(AssemblyNameReference reference, TargetArchitecture architecture) { this.reference = reference; this.architecture = architecture; }
/// <summary> /// Initializes a new instance of the <see cref="WindowsToolchainBase"/> class. /// </summary> /// <param name="platform">The platform.</param> /// <param name="architecture">The target architecture.</param> /// <param name="toolsetVer">The target platform toolset version.</param> /// <param name="sdkVer">The target platform SDK version.</param> protected WindowsToolchainBase(WindowsPlatformBase platform, TargetArchitecture architecture, WindowsPlatformToolset toolsetVer, WindowsPlatformSDK sdkVer) : base(platform, architecture) { var toolsets = WindowsPlatformBase.GetToolsets(); var sdks = WindowsPlatformBase.GetSDKs(); // Pick the overriden toolset if (Configuration.Compiler != null) { if (Enum.TryParse(Configuration.Compiler, out WindowsPlatformToolset compiler)) { toolsetVer = compiler; } } // Pick the newest installed Visual Studio version if using the default toolset if (toolsetVer == WindowsPlatformToolset.Default) { if (VisualStudioInstance.HasIDE(VisualStudioVersion.VisualStudio2022)) { toolsetVer = WindowsPlatformToolset.v143; } else if (VisualStudioInstance.HasIDE(VisualStudioVersion.VisualStudio2019)) { toolsetVer = WindowsPlatformToolset.v142; } else if (VisualStudioInstance.HasIDE(VisualStudioVersion.VisualStudio2017)) { toolsetVer = WindowsPlatformToolset.v141; } else { toolsetVer = WindowsPlatformToolset.v140; } } // Pick the latest toolset else if (toolsetVer == WindowsPlatformToolset.Latest) { toolsetVer = toolsets.Keys.Max(); } // Pick the latest SDK if (sdkVer == WindowsPlatformSDK.Latest) { sdkVer = sdks.Keys.Max(); } // Get tools Toolset = toolsetVer; SDK = sdkVer; if (!toolsets.ContainsKey(Toolset)) { throw new Exception(string.Format("Missing toolset {0} for platform Windows", Toolset)); } if (!sdks.ContainsKey(SDK)) { throw new Exception(string.Format("Missing SDK {0} for platform Windows", SDK)); } // Get the tools paths string vcToolPath; if (Architecture == TargetArchitecture.x64) { vcToolPath = WindowsPlatformBase.GetVCToolPath64(Toolset); } else { vcToolPath = WindowsPlatformBase.GetVCToolPath32(Toolset); } _vcToolPath = vcToolPath; _compilerPath = Path.Combine(vcToolPath, "cl.exe"); _linkerPath = Path.Combine(vcToolPath, "link.exe"); _libToolPath = Path.Combine(vcToolPath, "lib.exe"); _xdcmakePath = Path.Combine(vcToolPath, "xdcmake.exe"); // Add Visual C++ toolset include and library paths var vcToolChainDir = toolsets[Toolset]; SystemIncludePaths.Add(Path.Combine(vcToolChainDir, "include")); switch (Toolset) { case WindowsPlatformToolset.v140: { switch (Architecture) { case TargetArchitecture.AnyCPU: break; case TargetArchitecture.ARM: SystemLibraryPaths.Add(Path.Combine(vcToolChainDir, "lib", "arm")); break; case TargetArchitecture.ARM64: SystemLibraryPaths.Add(Path.Combine(vcToolChainDir, "lib", "arm64")); break; case TargetArchitecture.x86: SystemLibraryPaths.Add(Path.Combine(vcToolChainDir, "lib")); break; case TargetArchitecture.x64: SystemLibraryPaths.Add(Path.Combine(vcToolChainDir, "lib", "amd64")); break; default: throw new InvalidArchitectureException(architecture); } // When using Visual Studio 2015 toolset and using pre-Windows 10 SDK, find a Windows 10 SDK and add the UCRT include paths if (SDK == WindowsPlatformSDK.v8_1) { var sdk = sdks.FirstOrDefault(x => x.Key != WindowsPlatformSDK.v8_1); if (sdk.Value == null) { throw new Exception("Combination of Windows Toolset v140 and Windows SDK 8.1 requires the Universal CRT to be installed."); } var sdkVersionName = WindowsPlatformBase.GetSDKVersion(sdk.Key).ToString(); string includeRootDir = Path.Combine(sdk.Value, "include", sdkVersionName); SystemIncludePaths.Add(Path.Combine(includeRootDir, "ucrt")); string libraryRootDir = Path.Combine(sdk.Value, "lib", sdkVersionName); switch (Architecture) { case TargetArchitecture.AnyCPU: break; case TargetArchitecture.ARM: SystemLibraryPaths.Add(Path.Combine(libraryRootDir, "ucrt", "arm")); break; case TargetArchitecture.ARM64: SystemLibraryPaths.Add(Path.Combine(libraryRootDir, "ucrt", "arm64")); break; case TargetArchitecture.x86: SystemLibraryPaths.Add(Path.Combine(libraryRootDir, "ucrt", "x86")); break; case TargetArchitecture.x64: SystemLibraryPaths.Add(Path.Combine(libraryRootDir, "ucrt", "x64")); break; default: throw new InvalidArchitectureException(architecture); } } break; } case WindowsPlatformToolset.v141: case WindowsPlatformToolset.v142: case WindowsPlatformToolset.v143: { switch (Architecture) { case TargetArchitecture.AnyCPU: break; case TargetArchitecture.ARM: SystemLibraryPaths.Add(Path.Combine(vcToolChainDir, "lib", "arm")); break; case TargetArchitecture.ARM64: SystemLibraryPaths.Add(Path.Combine(vcToolChainDir, "lib", "arm64")); break; case TargetArchitecture.x86: SystemLibraryPaths.Add(Path.Combine(vcToolChainDir, "lib", "x86")); break; case TargetArchitecture.x64: SystemLibraryPaths.Add(Path.Combine(vcToolChainDir, "lib", "x64")); break; default: throw new InvalidArchitectureException(architecture); } break; } default: throw new ArgumentOutOfRangeException(); } // Add Windows SDK include and library paths var windowsSdkDir = sdks[SDK]; switch (SDK) { case WindowsPlatformSDK.v8_1: { string includeRootDir = Path.Combine(windowsSdkDir, "include"); SystemIncludePaths.Add(Path.Combine(includeRootDir, "shared")); SystemIncludePaths.Add(Path.Combine(includeRootDir, "um")); SystemIncludePaths.Add(Path.Combine(includeRootDir, "winrt")); SystemIncludePaths.Add(Path.Combine(includeRootDir, "ucrt")); string libraryRootDir = Path.Combine(windowsSdkDir, "lib", "winv6.3"); switch (Architecture) { case TargetArchitecture.AnyCPU: break; case TargetArchitecture.ARM: { SystemLibraryPaths.Add(Path.Combine(libraryRootDir, "um", "arm")); break; } case TargetArchitecture.ARM64: { SystemLibraryPaths.Add(Path.Combine(libraryRootDir, "um", "arm64")); break; } case TargetArchitecture.x86: { SystemLibraryPaths.Add(Path.Combine(libraryRootDir, "um", "x86")); SystemLibraryPaths.Add(Path.Combine(libraryRootDir, "ucrt", "x86")); var binRootDir = Path.Combine(windowsSdkDir, "bin", "x86"); _resourceCompilerPath = Path.Combine(binRootDir, "rc.exe"); _makepriPath = Path.Combine(binRootDir, "makepri.exe"); break; } case TargetArchitecture.x64: { SystemLibraryPaths.Add(Path.Combine(libraryRootDir, "um", "x64")); SystemLibraryPaths.Add(Path.Combine(libraryRootDir, "ucrt", "x64")); var binRootDir = Path.Combine(windowsSdkDir, "bin", "x64"); _resourceCompilerPath = Path.Combine(binRootDir, "rc.exe"); _makepriPath = Path.Combine(binRootDir, "makepri.exe"); break; } default: throw new InvalidArchitectureException(architecture); } break; } case WindowsPlatformSDK.v10_0_10240_0: case WindowsPlatformSDK.v10_0_10586_0: case WindowsPlatformSDK.v10_0_14393_0: case WindowsPlatformSDK.v10_0_15063_0: case WindowsPlatformSDK.v10_0_16299_0: case WindowsPlatformSDK.v10_0_17134_0: case WindowsPlatformSDK.v10_0_17763_0: case WindowsPlatformSDK.v10_0_18362_0: case WindowsPlatformSDK.v10_0_19041_0: case WindowsPlatformSDK.v10_0_20348_0: case WindowsPlatformSDK.v10_0_22000_0: { var sdkVersionName = WindowsPlatformBase.GetSDKVersion(SDK).ToString(); string includeRootDir = Path.Combine(windowsSdkDir, "include", sdkVersionName); SystemIncludePaths.Add(Path.Combine(includeRootDir, "ucrt")); SystemIncludePaths.Add(Path.Combine(includeRootDir, "shared")); SystemIncludePaths.Add(Path.Combine(includeRootDir, "um")); SystemIncludePaths.Add(Path.Combine(includeRootDir, "winrt")); string libraryRootDir = Path.Combine(windowsSdkDir, "lib", sdkVersionName); switch (Architecture) { case TargetArchitecture.AnyCPU: break; case TargetArchitecture.ARM: { SystemLibraryPaths.Add(Path.Combine(libraryRootDir, "ucrt", "arm")); SystemLibraryPaths.Add(Path.Combine(libraryRootDir, "um", "arm")); break; } case TargetArchitecture.ARM64: { SystemLibraryPaths.Add(Path.Combine(libraryRootDir, "ucrt", "arm64")); SystemLibraryPaths.Add(Path.Combine(libraryRootDir, "um", "arm64")); break; } case TargetArchitecture.x86: { SystemLibraryPaths.Add(Path.Combine(libraryRootDir, "ucrt", "x86")); SystemLibraryPaths.Add(Path.Combine(libraryRootDir, "um", "x86")); var binRootDir = Path.Combine(windowsSdkDir, "bin", sdkVersionName, "x86"); _resourceCompilerPath = Path.Combine(binRootDir, "rc.exe"); _makepriPath = Path.Combine(binRootDir, "makepri.exe"); break; } case TargetArchitecture.x64: { SystemLibraryPaths.Add(Path.Combine(libraryRootDir, "ucrt", "x64")); SystemLibraryPaths.Add(Path.Combine(libraryRootDir, "um", "x64")); var binRootDir = Path.Combine(windowsSdkDir, "bin", sdkVersionName, "x64"); _resourceCompilerPath = Path.Combine(binRootDir, "rc.exe"); _makepriPath = Path.Combine(binRootDir, "makepri.exe"); break; } default: throw new InvalidArchitectureException(architecture); } break; } default: throw new ArgumentOutOfRangeException(nameof(SDK)); } }
private AssemblyDefinition GetTargetAssembly(IEnumerable<string> filePaths, ReaderParameters parameters, TargetArchitecture architecture) { foreach (string path in filePaths) { if (!string.IsNullOrEmpty(path)) { AssemblyDefinition assembly = GetAssembly(path, parameters); if (assembly.MainModule.GetModuleArchitecture().CanReference(architecture)) { return assembly; } } } return null; }
/// <summary> /// Initializes a new instance of the <see cref="InvalidArchitectureException"/> class. /// </summary> /// <param name="architecture">The architecture.</param> /// <param name="message">The additional message.</param> public InvalidArchitectureException(TargetArchitecture architecture, string message) : base(string.Format("Unknown architecture {0}. " + message, architecture)) { }
public TargetDetails(TargetArchitecture architecture, TargetOS targetOS) { Architecture = architecture; OperatingSystem = targetOS; }
public static bool CanReference(this TargetArchitecture self, TargetArchitecture other) { return self == other || self == TargetArchitecture.AnyCPU || other == TargetArchitecture.AnyCPU; }