diff --git a/Directory.Build.props b/Directory.Build.props index e4d1872cb981c6..d49aa20c15ad38 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -101,6 +101,7 @@ preview latest true + true diff --git a/eng/Analyzers.props b/eng/Analyzers.props index 8babf8c41f5f9b..8a3a2f6d3fd18d 100644 --- a/eng/Analyzers.props +++ b/eng/Analyzers.props @@ -2,9 +2,9 @@ $(MSBuildThisFileDirectory)CodeAnalysis.ruleset - false + false - + diff --git a/eng/referenceAssemblies.props b/eng/referenceAssemblies.props index 4aabb96b89999f..4bdcf75ef31973 100644 --- a/eng/referenceAssemblies.props +++ b/eng/referenceAssemblies.props @@ -6,7 +6,7 @@ $(AdditionalBuildTargetFrameworks);netstandard2.1 - false + false diff --git a/src/coreclr/src/System.Private.CoreLib/System.Private.CoreLib.csproj b/src/coreclr/src/System.Private.CoreLib/System.Private.CoreLib.csproj index 00c76181c3d0f8..489eb0c4b4162b 100644 --- a/src/coreclr/src/System.Private.CoreLib/System.Private.CoreLib.csproj +++ b/src/coreclr/src/System.Private.CoreLib/System.Private.CoreLib.csproj @@ -48,7 +48,6 @@ true $(OutputPath)$(MSBuildProjectName).xml - true diff --git a/src/coreclr/src/tools/Directory.Build.props b/src/coreclr/src/tools/Directory.Build.props index d7eed0273181c6..d3d6aedf615f75 100644 --- a/src/coreclr/src/tools/Directory.Build.props +++ b/src/coreclr/src/tools/Directory.Build.props @@ -3,5 +3,6 @@ false false + false diff --git a/src/coreclr/tests/Directory.Build.props b/src/coreclr/tests/Directory.Build.props index ce06d5d9a27f3e..75c7e913c9fc03 100644 --- a/src/coreclr/tests/Directory.Build.props +++ b/src/coreclr/tests/Directory.Build.props @@ -65,4 +65,9 @@ + + + false + + diff --git a/src/coreclr/tests/dir.sdkbuild.props b/src/coreclr/tests/dir.sdkbuild.props index 7e0c081b7abd37..483b2c91772cea 100644 --- a/src/coreclr/tests/dir.sdkbuild.props +++ b/src/coreclr/tests/dir.sdkbuild.props @@ -10,6 +10,7 @@ false false AnyCPU + $(NoWarn),618,SYSLIB0012 false diff --git a/src/installer/Directory.Build.props b/src/installer/Directory.Build.props index c7fe15ac4e5254..5d7e74fb27a49f 100644 --- a/src/installer/Directory.Build.props +++ b/src/installer/Directory.Build.props @@ -142,11 +142,6 @@ - - - true - - false false diff --git a/src/installer/managed/Microsoft.NET.HostModel/AppHost/AppHostCustomizationUnsupportedOSException.cs b/src/installer/managed/Microsoft.NET.HostModel/AppHost/AppHostCustomizationUnsupportedOSException.cs index 34650f231f5088..0b0b055bdc688b 100644 --- a/src/installer/managed/Microsoft.NET.HostModel/AppHost/AppHostCustomizationUnsupportedOSException.cs +++ b/src/installer/managed/Microsoft.NET.HostModel/AppHost/AppHostCustomizationUnsupportedOSException.cs @@ -6,11 +6,10 @@ namespace Microsoft.NET.HostModel.AppHost { /// - /// The application host executable cannot be customized because adding resources requires + /// The application host executable cannot be customized because adding resources requires /// that the build be performed on Windows (excluding Nano Server). /// public class AppHostCustomizationUnsupportedOSException : AppHostUpdateException { } } - diff --git a/src/installer/managed/Microsoft.NET.HostModel/AppHost/AppHostMachOFormatException.cs b/src/installer/managed/Microsoft.NET.HostModel/AppHost/AppHostMachOFormatException.cs index 33d1b183293aa5..c52ef11d3b72ba 100644 --- a/src/installer/managed/Microsoft.NET.HostModel/AppHost/AppHostMachOFormatException.cs +++ b/src/installer/managed/Microsoft.NET.HostModel/AppHost/AppHostMachOFormatException.cs @@ -22,11 +22,11 @@ public enum MachOFormatError SignBlobNotLast, // Signature blob must be at the very end of the file SignDoesntFollowSymtab, // Signature blob must immediately follow the Symtab MemoryMapAccessFault, // Error reading the memory-mapped apphost - InvalidUTF8 // UTF8 decoding failed + InvalidUTF8 // UTF8 decoding failed } /// - /// The MachO application host executable cannot be customized because + /// The MachO application host executable cannot be customized because /// it was not in the expected format /// public class AppHostMachOFormatException : AppHostUpdateException @@ -39,4 +39,3 @@ public AppHostMachOFormatException(MachOFormatError error) } } } - diff --git a/src/installer/managed/Microsoft.NET.HostModel/AppHost/AppHostNotCUIException.cs b/src/installer/managed/Microsoft.NET.HostModel/AppHost/AppHostNotCUIException.cs index 3d26b6139e638c..b89a22dced400a 100644 --- a/src/installer/managed/Microsoft.NET.HostModel/AppHost/AppHostNotCUIException.cs +++ b/src/installer/managed/Microsoft.NET.HostModel/AppHost/AppHostNotCUIException.cs @@ -6,11 +6,10 @@ namespace Microsoft.NET.HostModel.AppHost { /// - /// Unable to use the input file as application host executable because it's not a + /// Unable to use the input file as application host executable because it's not a /// Windows executable for the CUI (Console) subsystem. /// public class AppHostNotCUIException : AppHostUpdateException { } } - diff --git a/src/installer/managed/Microsoft.NET.HostModel/AppHost/AppHostNotPEFileException.cs b/src/installer/managed/Microsoft.NET.HostModel/AppHost/AppHostNotPEFileException.cs index d9f9b7787bb244..6712d875f7683f 100644 --- a/src/installer/managed/Microsoft.NET.HostModel/AppHost/AppHostNotPEFileException.cs +++ b/src/installer/managed/Microsoft.NET.HostModel/AppHost/AppHostNotPEFileException.cs @@ -6,11 +6,10 @@ namespace Microsoft.NET.HostModel.AppHost { /// - /// Unable to use the input file as an application host executable + /// Unable to use the input file as an application host executable /// because it's not a Windows PE file /// public class AppHostNotPEFileException : AppHostUpdateException { } } - diff --git a/src/installer/managed/Microsoft.NET.HostModel/AppHost/AppHostUpdateException.cs b/src/installer/managed/Microsoft.NET.HostModel/AppHost/AppHostUpdateException.cs index 897287bdbd8d5d..4570c7710c2dbf 100644 --- a/src/installer/managed/Microsoft.NET.HostModel/AppHost/AppHostUpdateException.cs +++ b/src/installer/managed/Microsoft.NET.HostModel/AppHost/AppHostUpdateException.cs @@ -6,11 +6,10 @@ namespace Microsoft.NET.HostModel.AppHost { /// - /// An instance of this exception is thrown when an AppHost binary update + /// An instance of this exception is thrown when an AppHost binary update /// fails due to known user errors. /// public class AppHostUpdateException : Exception { } } - diff --git a/src/installer/managed/Microsoft.NET.HostModel/AppHost/AppNameTooLongException.cs b/src/installer/managed/Microsoft.NET.HostModel/AppHost/AppNameTooLongException.cs index c32f5b16b602cb..18a984b17c5918 100644 --- a/src/installer/managed/Microsoft.NET.HostModel/AppHost/AppNameTooLongException.cs +++ b/src/installer/managed/Microsoft.NET.HostModel/AppHost/AppNameTooLongException.cs @@ -18,4 +18,3 @@ public AppNameTooLongException(string name) } } - diff --git a/src/installer/managed/Microsoft.NET.HostModel/AppHost/BinaryUtils.cs b/src/installer/managed/Microsoft.NET.HostModel/AppHost/BinaryUtils.cs index de6d0bfce2f715..d275278955cdc7 100644 --- a/src/installer/managed/Microsoft.NET.HostModel/AppHost/BinaryUtils.cs +++ b/src/installer/managed/Microsoft.NET.HostModel/AppHost/BinaryUtils.cs @@ -60,8 +60,8 @@ private static unsafe void Pad0(byte[] searchPattern, byte[] patternToReplace, b } public static unsafe void SearchAndReplace( - string filePath, - byte[] searchPattern, + string filePath, + byte[] searchPattern, byte[] patternToReplace, bool pad0s = true) { diff --git a/src/installer/managed/Microsoft.NET.HostModel/AppHost/ElfUtils.cs b/src/installer/managed/Microsoft.NET.HostModel/AppHost/ElfUtils.cs index 4e86240843dcd7..127fc8f65808fb 100644 --- a/src/installer/managed/Microsoft.NET.HostModel/AppHost/ElfUtils.cs +++ b/src/installer/managed/Microsoft.NET.HostModel/AppHost/ElfUtils.cs @@ -10,12 +10,12 @@ internal static class ElfUtils // The Linux Headers are copied from elf.h #pragma warning disable 0649 - struct ElfHeader + private struct ElfHeader { - byte EI_MAG0; - byte EI_MAG1; - byte EI_MAG2; - byte EI_MAG3; + private byte EI_MAG0; + private byte EI_MAG1; + private byte EI_MAG2; + private byte EI_MAG3; public bool IsValid() { @@ -49,4 +49,3 @@ public static bool IsElfImage(string filePath) } } } - diff --git a/src/installer/managed/Microsoft.NET.HostModel/AppHost/HostWriter.cs b/src/installer/managed/Microsoft.NET.HostModel/AppHost/HostWriter.cs index 9dcf55d2beeb58..47d7c8a8c8e200 100644 --- a/src/installer/managed/Microsoft.NET.HostModel/AppHost/HostWriter.cs +++ b/src/installer/managed/Microsoft.NET.HostModel/AppHost/HostWriter.cs @@ -155,7 +155,7 @@ public static void SetAsBundle( long bundleHeaderOffset) { byte[] bundleHeaderPlaceholder = { - // 8 bytes represent the bundle header-offset + // 8 bytes represent the bundle header-offset // Zero for non-bundle apphosts (default). 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 32 bytes represent the bundle signature: SHA-256 for ".net core bundle" @@ -206,7 +206,7 @@ void FindBundleHeader() throw new PlaceHolderNotFoundInAppHostException(bundleSignature); } - headerOffset = accessor.ReadInt64(position - sizeof(Int64)); + headerOffset = accessor.ReadInt64(position - sizeof(long)); } } } diff --git a/src/installer/managed/Microsoft.NET.HostModel/AppHost/MachOUtils.cs b/src/installer/managed/Microsoft.NET.HostModel/AppHost/MachOUtils.cs index 2514caed0c0e8f..251fe853767559 100644 --- a/src/installer/managed/Microsoft.NET.HostModel/AppHost/MachOUtils.cs +++ b/src/installer/managed/Microsoft.NET.HostModel/AppHost/MachOUtils.cs @@ -11,13 +11,13 @@ namespace Microsoft.NET.HostModel.AppHost { internal static class MachOUtils { - // The MachO Headers are copied from + // The MachO Headers are copied from // https://opensource.apple.com/source/cctools/cctools-870/include/mach-o/loader.h // // The data fields and enumerations match the structure definitions in the above file, // and hence do not conform to C# CoreFx naming style. - enum Magic : uint + private enum Magic : uint { MH_MAGIC = 0xfeedface, MH_CIGAM = 0xcefaedfe, @@ -25,13 +25,13 @@ enum Magic : uint MH_CIGAM_64 = 0xcffaedfe } - enum FileType : uint + private enum FileType : uint { MH_EXECUTE = 0x2 } #pragma warning disable 0649 - struct MachHeader + private struct MachHeader { public Magic magic; public int cputype; @@ -63,22 +63,22 @@ public bool IsValid() } } - enum Command : uint + private enum Command : uint { LC_SYMTAB = 0x2, LC_SEGMENT_64 = 0x19, LC_CODE_SIGNATURE = 0x1d, } - struct LoadCommand + private struct LoadCommand { public Command cmd; public uint cmdsize; } // The linkedit_data_command contains the offsets and sizes of a blob - // of data in the __LINKEDIT segment (including LC_CODE_SIGNATURE). - struct LinkEditDataCommand + // of data in the __LINKEDIT segment (including LC_CODE_SIGNATURE). + private struct LinkEditDataCommand { public Command cmd; public uint cmdsize; @@ -86,7 +86,7 @@ struct LinkEditDataCommand public uint datasize; } - struct SymtabCommand + private struct SymtabCommand { public uint cmd; public uint cmdsize; @@ -96,7 +96,7 @@ struct SymtabCommand public uint strsize; }; - unsafe struct SegmentCommand64 + private unsafe struct SegmentCommand64 { public Command cmd; public uint cmdsize; @@ -159,9 +159,9 @@ public static bool IsMachOImage(string filePath) /// /// This Method is a utility to remove the code-signature (if any) /// from a MachO AppHost binary. - /// + /// /// The tool assumes the following layout of the executable: - /// + /// /// * MachoHeader (64-bit, executable, not swapped integers) /// * LoadCommands /// LC_SEGMENT_64 (__PAGEZERO) @@ -169,37 +169,37 @@ public static bool IsMachOImage(string filePath) /// LC_SEGMENT_64 (__DATA) /// LC_SEGMENT_64 (__LINKEDIT) /// ... - /// LC_SYMTAB + /// LC_SYMTAB /// ... /// LC_CODE_SIGNATURE (last) - /// + /// /// * ... Different Segments ... - /// + /// /// * The __LINKEDIT Segment (last) - /// * ... Different sections ... - /// * SYMTAB + /// * ... Different sections ... + /// * SYMTAB /// * (Some alignment bytes) /// * The Code-signature - /// + /// /// In order to remove the signature, the method: /// - Removes (zeros out) the LC_CODE_SIGNATURE command /// - Adjusts the size and count of the load commands in the header /// - Truncates the size of the __LINKEDIT segment to the end of SYMTAB /// - Truncates the apphost file to the end of the __LINKEDIT segment - /// + /// /// /// Path to the AppHost /// - /// True if - /// - The input is a MachO binary, and - /// - It is a signed binary, and + /// True if + /// - The input is a MachO binary, and + /// - It is a signed binary, and /// - The signature was successfully removed - /// False otherwise + /// False otherwise /// /// /// The input is a MachO file, but doesn't match the expect format of the AppHost. /// - unsafe public static bool RemoveSignature(string filePath) + public static unsafe bool RemoveSignature(string filePath) { using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite)) { @@ -278,7 +278,7 @@ unsafe public static bool RemoveSignature(string filePath) Verify(symtab->symoff > linkEdit->fileoff, MachOFormatError.SymtabNotInLinkEdit); Verify(signature->dataoff > linkEdit->fileoff, MachOFormatError.SignNotInLinkEdit); - // The signature blob immediately follows the symtab blob, + // The signature blob immediately follows the symtab blob, // except for a few bytes of padding. Verify(signature->dataoff >= symtabEnd && signature->dataoff - symtabEnd < 32, MachOFormatError.SignBlobNotLast); @@ -294,7 +294,7 @@ unsafe public static bool RemoveSignature(string filePath) linkEdit->filesize -= signatureSize; // codesign --remove-signature doesn't reset the vmsize. - // Setting the vmsize here makes the output bin-equal with the original + // Setting the vmsize here makes the output bin-equal with the original // unsigned apphost (and not bin-equal with a signed-unsigned-apphost). linkEdit->vmsize = linkEdit->filesize; } @@ -321,4 +321,3 @@ unsafe public static bool RemoveSignature(string filePath) } } } - diff --git a/src/installer/managed/Microsoft.NET.HostModel/AppHost/PEUtils.cs b/src/installer/managed/Microsoft.NET.HostModel/AppHost/PEUtils.cs index ce5a847af6eebd..e5659ae531c487 100644 --- a/src/installer/managed/Microsoft.NET.HostModel/AppHost/PEUtils.cs +++ b/src/installer/managed/Microsoft.NET.HostModel/AppHost/PEUtils.cs @@ -12,7 +12,7 @@ public static class PEUtils /// /// The first two bytes of a PE file are a constant signature. /// - private const UInt16 PEFileSignature = 0x5A4D; + private const ushort PEFileSignature = 0x5A4D; /// /// The offset of the PE header pointer in the DOS header. @@ -27,12 +27,12 @@ public static class PEUtils /// /// The value of the sybsystem field which indicates Windows GUI (Graphical UI) /// - private const UInt16 WindowsGUISubsystem = 0x2; + private const ushort WindowsGUISubsystem = 0x2; /// /// The value of the subsystem field which indicates Windows CUI (Console) /// - private const UInt16 WindowsCUISubsystem = 0x3; + private const ushort WindowsCUISubsystem = 0x3; /// /// Check whether the apphost file is a windows PE image by looking at the first few bytes. @@ -50,7 +50,7 @@ internal static unsafe bool IsPEImage(MemoryMappedViewAccessor accessor) // https://en.wikipedia.org/wiki/Portable_Executable // Validate that we're looking at Windows PE file - if (((UInt16*)bytes)[0] != PEFileSignature || accessor.Capacity < PEHeaderPointerOffset + sizeof(UInt32)) + if (((ushort*)bytes)[0] != PEFileSignature || accessor.Capacity < PEHeaderPointerOffset + sizeof(uint)) { return false; } @@ -69,7 +69,7 @@ public static bool IsPEImage(string filePath) { using (BinaryReader reader = new BinaryReader(File.OpenRead(filePath))) { - if (reader.BaseStream.Length < PEHeaderPointerOffset + sizeof(UInt32)) + if (reader.BaseStream.Length < PEHeaderPointerOffset + sizeof(uint)) { return false; } @@ -93,14 +93,14 @@ internal static unsafe void SetWindowsGraphicalUserInterfaceBit(MemoryMappedView byte* bytes = pointer + accessor.PointerOffset; // https://en.wikipedia.org/wiki/Portable_Executable - UInt32 peHeaderOffset = ((UInt32*)(bytes + PEHeaderPointerOffset))[0]; + uint peHeaderOffset = ((uint*)(bytes + PEHeaderPointerOffset))[0]; - if (accessor.Capacity < peHeaderOffset + SubsystemOffset + sizeof(UInt16)) + if (accessor.Capacity < peHeaderOffset + SubsystemOffset + sizeof(ushort)) { throw new AppHostNotPEFileException(); } - UInt16* subsystem = ((UInt16*)(bytes + peHeaderOffset + SubsystemOffset)); + ushort* subsystem = ((ushort*)(bytes + peHeaderOffset + SubsystemOffset)); // https://docs.microsoft.com/en-us/windows/desktop/Debug/pe-format#windows-subsystem // The subsystem of the prebuilt apphost should be set to CUI @@ -136,7 +136,7 @@ public static unsafe void SetWindowsGraphicalUserInterfaceBit(string filePath) /// This method will return the subsystem CUI/GUI value. The apphost file should be a windows PE file. /// /// The memory accessor which has the apphost file opened. - internal static unsafe UInt16 GetWindowsGraphicalUserInterfaceBit(MemoryMappedViewAccessor accessor) + internal static unsafe ushort GetWindowsGraphicalUserInterfaceBit(MemoryMappedViewAccessor accessor) { byte* pointer = null; @@ -146,14 +146,14 @@ internal static unsafe UInt16 GetWindowsGraphicalUserInterfaceBit(MemoryMappedVi byte* bytes = pointer + accessor.PointerOffset; // https://en.wikipedia.org/wiki/Portable_Executable - UInt32 peHeaderOffset = ((UInt32*)(bytes + PEHeaderPointerOffset))[0]; + uint peHeaderOffset = ((uint*)(bytes + PEHeaderPointerOffset))[0]; - if (accessor.Capacity < peHeaderOffset + SubsystemOffset + sizeof(UInt16)) + if (accessor.Capacity < peHeaderOffset + SubsystemOffset + sizeof(ushort)) { throw new AppHostNotPEFileException(); } - UInt16* subsystem = ((UInt16*)(bytes + peHeaderOffset + SubsystemOffset)); + ushort* subsystem = ((ushort*)(bytes + peHeaderOffset + SubsystemOffset)); return subsystem[0]; } @@ -166,7 +166,7 @@ internal static unsafe UInt16 GetWindowsGraphicalUserInterfaceBit(MemoryMappedVi } } - public static unsafe UInt16 GetWindowsGraphicalUserInterfaceBit(string filePath) + public static unsafe ushort GetWindowsGraphicalUserInterfaceBit(string filePath) { using (var mappedFile = MemoryMappedFile.CreateFromFile(filePath)) { diff --git a/src/installer/managed/Microsoft.NET.HostModel/AppHost/PlaceHolderNotFoundInAppHostException.cs b/src/installer/managed/Microsoft.NET.HostModel/AppHost/PlaceHolderNotFoundInAppHostException.cs index fa8a0931f441c0..4268e640154507 100644 --- a/src/installer/managed/Microsoft.NET.HostModel/AppHost/PlaceHolderNotFoundInAppHostException.cs +++ b/src/installer/managed/Microsoft.NET.HostModel/AppHost/PlaceHolderNotFoundInAppHostException.cs @@ -6,7 +6,7 @@ namespace Microsoft.NET.HostModel.AppHost { /// - /// Unable to use input file as a valid application host executable, as it does not contain + /// Unable to use input file as a valid application host executable, as it does not contain /// the expected placeholder byte sequence. /// public class PlaceHolderNotFoundInAppHostException : AppHostUpdateException @@ -18,4 +18,3 @@ public PlaceHolderNotFoundInAppHostException(byte[] pattern) } } } - diff --git a/src/installer/managed/Microsoft.NET.HostModel/AppHost/RetryUtil.cs b/src/installer/managed/Microsoft.NET.HostModel/AppHost/RetryUtil.cs index 38be96dc3f0c7f..898cab0295c11c 100644 --- a/src/installer/managed/Microsoft.NET.HostModel/AppHost/RetryUtil.cs +++ b/src/installer/managed/Microsoft.NET.HostModel/AppHost/RetryUtil.cs @@ -12,10 +12,10 @@ namespace Microsoft.NET.HostModel /// /// HostModel library implements several services for updating the AppHost DLL. /// These updates involve multiple file open/close operations. - /// An Antivirus scanner may intercept in-between and lock the file, + /// An Antivirus scanner may intercept in-between and lock the file, /// causing the operations to fail with IO-Error. /// So, the operations are retried a few times on failures such as - /// - IOException + /// - IOException /// - Failure with Win32 errors indicating file-lock /// public static class RetryUtil diff --git a/src/installer/managed/Microsoft.NET.HostModel/Bundle/BundleOptions.cs b/src/installer/managed/Microsoft.NET.HostModel/Bundle/BundleOptions.cs index d8eb92a9c497ba..646e1b094310dd 100644 --- a/src/installer/managed/Microsoft.NET.HostModel/Bundle/BundleOptions.cs +++ b/src/installer/managed/Microsoft.NET.HostModel/Bundle/BundleOptions.cs @@ -19,4 +19,3 @@ public enum BundleOptions BundleAllContent = BundleNativeBinaries | BundleOtherFiles, }; } - diff --git a/src/installer/managed/Microsoft.NET.HostModel/Bundle/Bundler.cs b/src/installer/managed/Microsoft.NET.HostModel/Bundle/Bundler.cs index 8fc97d6bc4a38d..6e1d202e1c67eb 100644 --- a/src/installer/managed/Microsoft.NET.HostModel/Bundle/Bundler.cs +++ b/src/installer/managed/Microsoft.NET.HostModel/Bundle/Bundler.cs @@ -18,16 +18,16 @@ namespace Microsoft.NET.HostModel.Bundle /// public class Bundler { - readonly string HostName; - readonly string OutputDir; - readonly string DepsJson; - readonly string RuntimeConfigJson; - readonly string RuntimeConfigDevJson; + private readonly string HostName; + private readonly string OutputDir; + private readonly string DepsJson; + private readonly string RuntimeConfigJson; + private readonly string RuntimeConfigDevJson; - readonly Trace Tracer; + private readonly Trace Tracer; public readonly Manifest BundleManifest; - readonly TargetInfo Target; - readonly BundleOptions Options; + private readonly TargetInfo Target; + private readonly BundleOptions Options; public Bundler(string hostName, string outputDir, @@ -58,7 +58,7 @@ public Bundler(string hostName, /// /// Returns the offset of the start 'file' within 'bundle' - long AddToBundle(Stream bundle, Stream file, FileType type) + private long AddToBundle(Stream bundle, Stream file, FileType type) { if (type == FileType.Assembly) { @@ -78,17 +78,17 @@ long AddToBundle(Stream bundle, Stream file, FileType type) return startOffset; } - bool IsHost(string fileRelativePath) + private bool IsHost(string fileRelativePath) { return fileRelativePath.Equals(HostName); } - bool ShouldIgnore(string fileRelativePath) + private bool ShouldIgnore(string fileRelativePath) { return fileRelativePath.Equals(RuntimeConfigDevJson); } - bool ShouldExclude(FileType type, string relativePath) + private bool ShouldExclude(FileType type, string relativePath) { switch (type) { @@ -112,7 +112,7 @@ bool ShouldExclude(FileType type, string relativePath) } } - bool IsAssembly(string path, out bool isPE) + private bool IsAssembly(string path, out bool isPE) { isPE = false; @@ -134,7 +134,7 @@ bool IsAssembly(string path, out bool isPE) return false; } - FileType InferType(FileSpec fileSpec) + private FileType InferType(FileSpec fileSpec) { if (fileSpec.BundleRelativePath.Equals(DepsJson)) { @@ -172,7 +172,7 @@ FileType InferType(FileSpec fileSpec) /// /// /// An enumeration FileSpecs for the files to be embedded. - /// + /// /// Files in fileSpecs that are not bundled within the single file bundle, /// and should be published as separate files are marked as "IsExcluded" by this method. /// This doesn't include unbundled files that should be dropped, and not publised as output. @@ -271,4 +271,3 @@ public string GenerateBundle(IReadOnlyList fileSpecs) } } } - diff --git a/src/installer/managed/Microsoft.NET.HostModel/Bundle/FileEntry.cs b/src/installer/managed/Microsoft.NET.HostModel/Bundle/FileEntry.cs index ef687aee1d849f..7315c2a026313a 100644 --- a/src/installer/managed/Microsoft.NET.HostModel/Bundle/FileEntry.cs +++ b/src/installer/managed/Microsoft.NET.HostModel/Bundle/FileEntry.cs @@ -7,8 +7,8 @@ namespace Microsoft.NET.HostModel.Bundle { /// /// FileEntry: Records information about embedded files. - /// - /// The bundle manifest records the following meta-data for each + /// + /// The bundle manifest records the following meta-data for each /// file embedded in the bundle: /// * Type (1 byte) /// * NameLength (7-bit extension encoding, typically 1 byte) @@ -44,4 +44,3 @@ public void Write(BinaryWriter writer) public override string ToString() => $"{RelativePath} [{Type}] @{Offset} Sz={Size}"; } } - diff --git a/src/installer/managed/Microsoft.NET.HostModel/Bundle/FileSpec.cs b/src/installer/managed/Microsoft.NET.HostModel/Bundle/FileSpec.cs index e245b33a0c610a..b6a368ab070984 100644 --- a/src/installer/managed/Microsoft.NET.HostModel/Bundle/FileSpec.cs +++ b/src/installer/managed/Microsoft.NET.HostModel/Bundle/FileSpec.cs @@ -7,9 +7,9 @@ namespace Microsoft.NET.HostModel.Bundle { /// /// Information about files to embed into the Bundle (input to the Bundler). - /// + /// /// SourcePath: path to the file to be bundled at compile time - /// BundleRelativePath: path where the file is expected at run time, + /// BundleRelativePath: path where the file is expected at run time, /// relative to the app DLL. /// public class FileSpec @@ -27,11 +27,10 @@ public FileSpec(string sourcePath, string bundleRelativePath) public bool IsValid() { - return !string.IsNullOrWhiteSpace(SourcePath) && + return !string.IsNullOrWhiteSpace(SourcePath) && !string.IsNullOrWhiteSpace(BundleRelativePath); } public override string ToString() => $"SourcePath: {SourcePath}, RelativePath: {BundleRelativePath} {(Excluded ? "[Excluded]" : "")}"; } } - diff --git a/src/installer/managed/Microsoft.NET.HostModel/Bundle/FileType.cs b/src/installer/managed/Microsoft.NET.HostModel/Bundle/FileType.cs index b72fac55bc4536..3369d3149d9b16 100644 --- a/src/installer/managed/Microsoft.NET.HostModel/Bundle/FileType.cs +++ b/src/installer/managed/Microsoft.NET.HostModel/Bundle/FileType.cs @@ -5,7 +5,7 @@ namespace Microsoft.NET.HostModel.Bundle { /// /// FileType: Identifies the type of file embedded into the bundle. - /// + /// /// The bundler differentiates a few kinds of files via the manifest, /// with respect to the way in which they'll be used by the runtime. /// @@ -19,4 +19,3 @@ public enum FileType : byte Symbols // PDB Files }; } - diff --git a/src/installer/managed/Microsoft.NET.HostModel/Bundle/Manifest.cs b/src/installer/managed/Microsoft.NET.HostModel/Bundle/Manifest.cs index b2f70002cc9588..0beddb2b8cacc9 100644 --- a/src/installer/managed/Microsoft.NET.HostModel/Bundle/Manifest.cs +++ b/src/installer/managed/Microsoft.NET.HostModel/Bundle/Manifest.cs @@ -11,22 +11,22 @@ namespace Microsoft.NET.HostModel.Bundle /// /// BundleManifest is a description of the contents of a bundle file. /// This class handles creation and consumption of bundle-manifests. - /// + /// /// Here is the description of the Bundle Layout: /// _______________________________________________ - /// AppHost + /// AppHost /// /// /// ------------Embedded Files --------------------- /// The embedded files including the app, its - /// configuration files, dependencies, and + /// configuration files, dependencies, and /// possibly the runtime. - /// - /// - /// - /// - /// - /// + /// + /// + /// + /// + /// + /// /// /// ------------ Bundle Header ------------- /// MajorVersion @@ -43,9 +43,9 @@ namespace Microsoft.NET.HostModel.Bundle /// - - - - - - Manifest Entries - - - - - - - - - - - /// Series of FileEntries (for each embedded file) /// [File Type, Name, Offset, Size information] - /// - /// - /// + /// + /// + /// /// _________________________________________________ /// public class Manifest @@ -55,13 +55,13 @@ public class Manifest // by constructing the bundler with BundleAllConent option. // This mode is expected to be deprecated in future versions of .NET. [Flags] - enum HeaderFlags : ulong + private enum HeaderFlags : ulong { None = 0, NetcoreApp3CompatMode = 1 } - // Bundle ID is a string that is used to uniquely + // Bundle ID is a string that is used to uniquely // identify this bundle. It is choosen to be compatible // with path-names so that the AppHost can use it in // extraction path. @@ -75,9 +75,9 @@ enum HeaderFlags : ulong public static string CurrentVersion => $"{CurrentMajorVersion}.{MinorVersion}"; public string DesiredVersion => $"{DesiredMajorVersion}.{MinorVersion}"; - FileEntry DepsJsonEntry = null; - FileEntry RuntimeConfigJsonEntry = null; - HeaderFlags Flags; + private FileEntry DepsJsonEntry; + private FileEntry RuntimeConfigJsonEntry; + private HeaderFlags Flags; public List Files; @@ -94,7 +94,7 @@ public FileEntry AddEntry(FileType type, string relativePath, long offset, long FileEntry entry = new FileEntry(type, relativePath, offset, size); Files.Add(entry); - switch(entry.Type) + switch (entry.Type) { case FileType.DepsJson: DepsJsonEntry = entry; @@ -118,9 +118,9 @@ public long Write(BinaryWriter writer) long startOffset = writer.BaseStream.Position; // Write the bundle header - writer.Write(DesiredMajorVersion); + writer.Write(DesiredMajorVersion); writer.Write(MinorVersion); - writer.Write(Files.Count()); + writer.Write(Files.Count); writer.Write(BundleID); if (DesiredMajorVersion == 2) diff --git a/src/installer/managed/Microsoft.NET.HostModel/Bundle/TargetInfo.cs b/src/installer/managed/Microsoft.NET.HostModel/Bundle/TargetInfo.cs index 867e77947d4795..05d5ff9d89ee19 100644 --- a/src/installer/managed/Microsoft.NET.HostModel/Bundle/TargetInfo.cs +++ b/src/installer/managed/Microsoft.NET.HostModel/Bundle/TargetInfo.cs @@ -11,7 +11,7 @@ namespace Microsoft.NET.HostModel.Bundle { /// /// TargetInfo: Information about the target for which the single-file bundle is built. - /// + /// /// Currently the TargetInfo only tracks: /// - the target operating system /// - the target architecture @@ -37,12 +37,12 @@ public TargetInfo(OSPlatform? os, Architecture? arch, Version targetFrameworkVer Debug.Assert(IsLinux || IsOSX || IsWindows); - if(FrameworkVersion.CompareTo(net50) >= 0) + if (FrameworkVersion.CompareTo(net50) >= 0) { BundleVersion = 2u; DefaultOptions = BundleOptions.None; } - else if(FrameworkVersion.Major == 3 && (FrameworkVersion.Minor == 0 || FrameworkVersion.Minor == 1)) + else if (FrameworkVersion.Major == 3 && (FrameworkVersion.Minor == 0 || FrameworkVersion.Minor == 1)) { BundleVersion = 1u; DefaultOptions = BundleOptions.BundleAllContent; @@ -85,7 +85,7 @@ public override string ToString() return $"OS: {os} Arch: {arch} FrameworkVersion: {FrameworkVersion}"; } - static OSPlatform HostOS => RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? OSPlatform.Linux : + private static OSPlatform HostOS => RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? OSPlatform.Linux : RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? OSPlatform.OSX : OSPlatform.Windows; public bool IsLinux => OS.Equals(OSPlatform.Linux); @@ -105,11 +105,10 @@ public override string ToString() public bool ShouldExclude(string relativePath) => (FrameworkVersion.Major != 3) && (relativePath.Equals(HostFxr) || relativePath.Equals(HostPolicy)); - readonly Version net50 = new Version(5, 0); - string HostFxr => IsWindows ? "hostfxr.dll" : IsLinux ? "libhostfxr.so" : "libhostfxr.dylib"; - string HostPolicy => IsWindows ? "hostpolicy.dll" : IsLinux ? "libhostpolicy.so" : "libhostpolicy.dylib"; + private readonly Version net50 = new Version(5, 0); + private string HostFxr => IsWindows ? "hostfxr.dll" : IsLinux ? "libhostfxr.so" : "libhostfxr.dylib"; + private string HostPolicy => IsWindows ? "hostpolicy.dll" : IsLinux ? "libhostpolicy.so" : "libhostpolicy.dylib"; } } - diff --git a/src/installer/managed/Microsoft.NET.HostModel/Bundle/Trace.cs b/src/installer/managed/Microsoft.NET.HostModel/Bundle/Trace.cs index 07b5f504151377..89c1c52a77c5bf 100644 --- a/src/installer/managed/Microsoft.NET.HostModel/Bundle/Trace.cs +++ b/src/installer/managed/Microsoft.NET.HostModel/Bundle/Trace.cs @@ -10,7 +10,7 @@ namespace Microsoft.NET.HostModel.Bundle /// public class Trace { - readonly bool Verbose = false; + private readonly bool Verbose; public Trace(bool verbose) { @@ -31,4 +31,3 @@ public void Error(string type, string message) } } } - diff --git a/src/installer/managed/Microsoft.NET.HostModel/ComHost/ClsidMap.cs b/src/installer/managed/Microsoft.NET.HostModel/ComHost/ClsidMap.cs index 151223b23b1729..b88584f87d2163 100644 --- a/src/installer/managed/Microsoft.NET.HostModel/ComHost/ClsidMap.cs +++ b/src/installer/managed/Microsoft.NET.HostModel/ComHost/ClsidMap.cs @@ -180,7 +180,7 @@ private static CustomAttributeHandle GetComVisibleAttribute(MetadataReader reade return attr; } } - return new CustomAttributeHandle(); + return default; } private static Guid GetTypeGuid(MetadataReader reader, TypeDefinition type) diff --git a/src/installer/managed/Microsoft.NET.HostModel/ComHost/ComHostCustomizationUnsupportedOSException.cs b/src/installer/managed/Microsoft.NET.HostModel/ComHost/ComHostCustomizationUnsupportedOSException.cs index 94b3f779b155ff..dc942b5a5909e9 100644 --- a/src/installer/managed/Microsoft.NET.HostModel/ComHost/ComHostCustomizationUnsupportedOSException.cs +++ b/src/installer/managed/Microsoft.NET.HostModel/ComHost/ComHostCustomizationUnsupportedOSException.cs @@ -6,11 +6,10 @@ namespace Microsoft.NET.HostModel.ComHost { /// - /// The application host executable cannot be customized because adding resources requires + /// The application host executable cannot be customized because adding resources requires /// that the build be performed on Windows (excluding Nano Server). /// public class ComHostCustomizationUnsupportedOSException : Exception { } } - diff --git a/src/installer/managed/Microsoft.NET.HostModel/ResourceUpdater.cs b/src/installer/managed/Microsoft.NET.HostModel/ResourceUpdater.cs index 9428686d6a1b95..b0cc571518751b 100644 --- a/src/installer/managed/Microsoft.NET.HostModel/ResourceUpdater.cs +++ b/src/installer/managed/Microsoft.NET.HostModel/ResourceUpdater.cs @@ -96,7 +96,7 @@ public delegate bool EnumResLangProc(IntPtr hModule, ushort wLang, IntPtr lParam); - [DllImport(nameof(Kernel32),SetLastError=true)] + [DllImport(nameof(Kernel32), SetLastError=true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool EnumResourceTypes(IntPtr hModule, EnumResTypeProc lpEnumFunc, diff --git a/src/installer/tests/Directory.Build.props b/src/installer/tests/Directory.Build.props index ca6c95c96a8a36..c1066573d3af7b 100644 --- a/src/installer/tests/Directory.Build.props +++ b/src/installer/tests/Directory.Build.props @@ -11,6 +11,7 @@ $(TargetArchitecture) $(NetCoreAppCurrent) -notrait category=failing + false diff --git a/src/installer/tests/TestUtils/ArgumentEscaper.cs b/src/installer/tests/TestUtils/ArgumentEscaper.cs index 5986e3f6e0d27e..58198005c01c43 100644 --- a/src/installer/tests/TestUtils/ArgumentEscaper.cs +++ b/src/installer/tests/TestUtils/ArgumentEscaper.cs @@ -12,21 +12,21 @@ public static class ArgumentEscaper /// /// Undo the processing which took place to create string[] args in Main, /// so that the next process will receive the same string[] args - /// + /// /// See here for more info: /// https://docs.microsoft.com/en-us/archive/blogs/twistylittlepassagesallalike/everyone-quotes-command-line-arguments-the-wrong-way /// /// /// public static string EscapeAndConcatenateArgArrayForProcessStart(IEnumerable args) - { + { return string.Join(" ", EscapeArgArray(args)); } /// /// Undo the processing which took place to create string[] args in Main, /// so that the next process will receive the same string[] args - /// + /// /// See here for more info: /// https://docs.microsoft.com/en-us/archive/blogs/twistylittlepassagesallalike/everyone-quotes-command-line-arguments-the-wrong-way /// @@ -40,7 +40,7 @@ public static string EscapeAndConcatenateArgArrayForCmdProcessStart(IEnumerable< /// /// Undo the processing which took place to create string[] args in Main, /// so that the next process will receive the same string[] args - /// + /// /// See here for more info: /// https://docs.microsoft.com/en-us/archive/blogs/twistylittlepassagesallalike/everyone-quotes-command-line-arguments-the-wrong-way /// @@ -60,9 +60,9 @@ private static IEnumerable EscapeArgArray(IEnumerable args) /// /// This prefixes every character with the '^' character to force cmd to - /// interpret the argument string literally. An alternative option would + /// interpret the argument string literally. An alternative option would /// be to do this only for cmd metacharacters. - /// + /// /// See here for more info: /// https://docs.microsoft.com/en-us/archive/blogs/twistylittlepassagesallalike/everyone-quotes-command-line-arguments-the-wrong-way /// @@ -85,7 +85,7 @@ private static string EscapeArg(string arg) var sb = new StringBuilder(); var quoted = ShouldSurroundWithQuotes(arg); - if (quoted) sb.Append("\""); + if (quoted) sb.Append('"'); for (int i = 0; i < arg.Length; ++i) { @@ -120,20 +120,20 @@ private static string EscapeArg(string arg) sb.Append(arg[i]); } } - - if (quoted) sb.Append("\""); + + if (quoted) sb.Append('"'); return sb.ToString(); } /// - /// Prepare as single argument to + /// Prepare as single argument to /// roundtrip properly through cmd. - /// + /// /// This prefixes every character with the '^' character to force cmd to - /// interpret the argument string literally. An alternative option would + /// interpret the argument string literally. An alternative option would /// be to do this only for cmd metacharacters. - /// + /// /// See here for more info: /// https://docs.microsoft.com/en-us/archive/blogs/twistylittlepassagesallalike/everyone-quotes-command-line-arguments-the-wrong-way /// @@ -152,7 +152,6 @@ private static string EscapeArgForCmd(string argument) if (character == '"') { - sb.Append('^'); sb.Append('"'); sb.Append('^'); @@ -160,7 +159,7 @@ private static string EscapeArgForCmd(string argument) } else { - sb.Append("^"); + sb.Append('^'); sb.Append(character); } } @@ -171,13 +170,13 @@ private static string EscapeArgForCmd(string argument) } /// - /// Prepare as single argument to + /// Prepare as single argument to /// roundtrip properly through cmd. - /// + /// /// This prefixes every character with the '^' character to force cmd to - /// interpret the argument string literally. An alternative option would + /// interpret the argument string literally. An alternative option would /// be to do this only for cmd metacharacters. - /// + /// /// See here for more info: /// https://docs.microsoft.com/en-us/archive/blogs/twistylittlepassagesallalike/everyone-quotes-command-line-arguments-the-wrong-way /// diff --git a/src/libraries/Common/src/System/SR.vb b/src/libraries/Common/src/System/SR.vb index 0d2638aef63e47..f2b5ba3e904303 100644 --- a/src/libraries/Common/src/System/SR.vb +++ b/src/libraries/Common/src/System/SR.vb @@ -7,7 +7,6 @@ ' Imports System.Resources -Imports System.Text Namespace System diff --git a/src/libraries/Directory.Build.props b/src/libraries/Directory.Build.props index 15fa4039246620..e3c3c3dc07dbe4 100644 --- a/src/libraries/Directory.Build.props +++ b/src/libraries/Directory.Build.props @@ -226,11 +226,11 @@ strict;nullablePublicOnly - true false true - true + + false diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft.VisualBasic.Core.vbproj b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft.VisualBasic.Core.vbproj index c9e62a61083dba..4a43d5cc114048 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft.VisualBasic.Core.vbproj +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft.VisualBasic.Core.vbproj @@ -11,12 +11,12 @@ 42025 $(DefineConstants),LATEBINDING=True $(DefineConstants),TARGET_WINDOWS=True - $(NoWarn);CA1823 + $(NoWarn),CA1810,CA2200 + $(NoWarn);CA1823 + Microsoft.VisualBasic.Core false - - false $(NetCoreAppCurrent);$(NetCoreAppCurrent)-Windows_NT diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/ByteType.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/ByteType.vb index 129339af34704e..0952af65bd6084 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/ByteType.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/ByteType.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. Imports System -Imports System.Globalization Imports Microsoft.VisualBasic.CompilerServices.Utils diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/ConversionResolution.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/ConversionResolution.vb index 889b2725bc5c29..0e2d365cba5d9c 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/ConversionResolution.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/ConversionResolution.vb @@ -7,7 +7,6 @@ Imports System.Diagnostics Imports System.Collections.Generic Imports Microsoft.VisualBasic.CompilerServices.Symbols -Imports Microsoft.VisualBasic.CompilerServices.ConversionResolution Imports Microsoft.VisualBasic.CompilerServices.ConversionResolution.OperatorCaches Namespace Microsoft.VisualBasic.CompilerServices @@ -1197,13 +1196,8 @@ Namespace Microsoft.VisualBasic.CompilerServices End Class - Friend Shared ReadOnly ConversionCache As FixedList - Friend Shared ReadOnly UnconvertibleTypeCache As FixedExistanceList - - Shared Sub New() - ConversionCache = New FixedList - UnconvertibleTypeCache = New FixedExistanceList - End Sub + Friend Shared ReadOnly ConversionCache As FixedList = New FixedList + Friend Shared ReadOnly UnconvertibleTypeCache As FixedExistanceList = New FixedExistanceList End Class End Class diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/IDOBinder.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/IDOBinder.vb index c8fb73e8058398..fc5a085194b083 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/IDOBinder.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/IDOBinder.vb @@ -3,8 +3,6 @@ Imports System Imports System.Collections.Generic -Imports System.Collections.ObjectModel -Imports System.Diagnostics Imports System.Dynamic Imports System.Linq.Expressions Imports System.Reflection @@ -1189,7 +1187,7 @@ Namespace Microsoft.VisualBasic.CompilerServices 'There is some inconsistency in the handling of argNames, sometimes it 'has been normalized to non-null by this point, sometimes not. If argNames Is Nothing Then - argNames = New String(-1) {} + argNames = Array.Empty(Of String)() End If callInfo = New CallInfo(args.Length - valueArgs, argNames) diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/IOUtils.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/IOUtils.vb index 48ef55b0522f7c..fc65b34af8c244 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/IOUtils.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/IOUtils.vb @@ -6,7 +6,6 @@ Imports System.Security Imports System.IO Imports Microsoft.VisualBasic.CompilerServices.ExceptionUtils -Imports Microsoft.VisualBasic.CompilerServices.Utils Namespace Microsoft.VisualBasic.CompilerServices diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/IntegerType.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/IntegerType.vb index d6121c725b6953..3cd455c32cde44 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/IntegerType.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/IntegerType.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. Imports System -Imports System.Globalization Imports Microsoft.VisualBasic.CompilerServices.Utils diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/LateBinding.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/LateBinding.vb index 4e113a309e7a6b..61fe5bc8ec2bee 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/LateBinding.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/LateBinding.vb @@ -3,10 +3,8 @@ Imports System Imports System.Diagnostics -Imports System.Globalization Imports System.Reflection Imports System.Runtime.InteropServices -Imports System.Runtime.Remoting Imports Microsoft.VisualBasic.CompilerServices.ExceptionUtils Imports Microsoft.VisualBasic.CompilerServices.Utils diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/LikeOperator.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/LikeOperator.vb index ac48462ee3948c..3ad52a98fd0acf 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/LikeOperator.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/LikeOperator.vb @@ -9,7 +9,6 @@ Imports System.Globalization Imports System.Collections.Generic Imports System.Diagnostics -Imports Microsoft.VisualBasic.Strings Imports Microsoft.VisualBasic.CompilerServices.Symbols Imports Microsoft.VisualBasic.CompilerServices.Operators Imports Microsoft.VisualBasic.CompilerServices.Utils diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/LongType.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/LongType.vb index d5a29b5d032242..4adce2269dcf3a 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/LongType.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/LongType.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. Imports System -Imports System.Globalization Imports Microsoft.VisualBasic.CompilerServices.Utils diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/NewLateBinding.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/NewLateBinding.vb index 17f75db4879df0..c635c59427ab3f 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/NewLateBinding.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/NewLateBinding.vb @@ -2,20 +2,13 @@ ' The .NET Foundation licenses this file to you under the MIT license. Imports System -Imports System.Collections Imports System.Collections.Generic Imports System.Diagnostics Imports System.Dynamic -Imports System.Globalization Imports System.Reflection -Imports System.Runtime.InteropServices Imports Microsoft.VisualBasic.CompilerServices.Symbols Imports Microsoft.VisualBasic.CompilerServices.OverloadResolution -Imports Microsoft.VisualBasic.CompilerServices.ExceptionUtils -Imports Microsoft.VisualBasic.CompilerServices.Utils -Imports Microsoft.VisualBasic.CompilerServices.ReflectionExtensions -Imports System.Runtime.Versioning #Const NEW_BINDER = True #Const BINDING_LOG = False @@ -814,7 +807,7 @@ Namespace Microsoft.VisualBasic.CompilerServices ByVal RValueBase As Boolean) ObjectLateSetComplex( - Instance, Nothing, MemberName, Arguments, New String() {}, + Instance, Nothing, MemberName, Arguments, Array.Empty(Of String)(), NoTypeArguments, OptimisticSet, RValueBase) End Sub 'FallbackSetComplex diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/ObjectFlowControl.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/ObjectFlowControl.vb index e027ad776c84a6..5721969344f11e 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/ObjectFlowControl.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/ObjectFlowControl.vb @@ -3,7 +3,6 @@ Imports System Imports System.ComponentModel -Imports System.Diagnostics Imports System.Reflection Imports Microsoft.VisualBasic.CompilerServices.ConversionResolution diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/ObjectType.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/ObjectType.vb index 82a7ca3be7bf47..a29bfd6748dde4 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/ObjectType.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/ObjectType.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. Imports System -Imports System.Diagnostics -Imports System.Globalization Imports Microsoft.VisualBasic.CompilerServices.StringType Imports Microsoft.VisualBasic.CompilerServices.Utils diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/Operators.Resolution.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/Operators.Resolution.vb index cb0ba07e430276..21fc0b62ad2ab5 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/Operators.Resolution.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/Operators.Resolution.vb @@ -4,13 +4,10 @@ Imports System Imports System.Collections.Generic Imports System.Diagnostics -Imports System.Dynamic -Imports System.Linq.Expressions Imports System.Reflection Imports Microsoft.VisualBasic.CompilerServices.Symbols Imports Microsoft.VisualBasic.CompilerServices.OverloadResolution -Imports Microsoft.VisualBasic.CompilerServices.Utils Namespace Microsoft.VisualBasic.CompilerServices diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/Operators.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/Operators.vb index 7de3b309d293c0..f53bef20d0580d 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/Operators.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/Operators.vb @@ -4,14 +4,9 @@ Option Strict On Imports System -Imports System.Collections.Generic Imports System.ComponentModel Imports System.Diagnostics -Imports System.Globalization -Imports System.Reflection Imports System.Runtime.CompilerServices - -Imports Microsoft.VisualBasic.CompilerServices.ExceptionUtils Imports Microsoft.VisualBasic.CompilerServices.Symbols Imports Microsoft.VisualBasic.CompilerServices.Utils diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/ProjectData.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/ProjectData.vb index 4470b6673923f4..afed7d21fb0c74 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/ProjectData.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/ProjectData.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. Imports System -Imports Microsoft.VisualBasic.CompilerServices.Utils -Imports Microsoft.VisualBasic.FileIO Namespace Global.Microsoft.VisualBasic.CompilerServices diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/ShortType.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/ShortType.vb index 930f48a4106bdc..aaff8977bd5cee 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/ShortType.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/ShortType.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. Imports System -Imports System.Globalization Imports Microsoft.VisualBasic.CompilerServices.Utils diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/StructUtils.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/StructUtils.vb index 44450234636ffc..878a5cb2b7c67d 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/StructUtils.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/StructUtils.vb @@ -2,12 +2,10 @@ ' The .NET Foundation licenses this file to you under the MIT license. Imports System -Imports System.Globalization Imports System.Diagnostics Imports System.Reflection Imports Microsoft.VisualBasic.CompilerServices.ExceptionUtils -Imports Microsoft.VisualBasic.CompilerServices.Utils Namespace Microsoft.VisualBasic.CompilerServices diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/Symbols.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/Symbols.vb index f1e17f6cf1c3d2..6c1f4764069239 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/Symbols.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/Symbols.vb @@ -4,7 +4,6 @@ Imports System Imports System.Reflection Imports System.Diagnostics -Imports System.Collections Imports System.Collections.Generic Imports System.Linq @@ -55,10 +54,10 @@ Namespace Microsoft.VisualBasic.CompilerServices MAX End Enum - Friend Shared ReadOnly NoArguments As Object() = {} - Friend Shared ReadOnly NoArgumentNames As String() = {} - Friend Shared ReadOnly NoTypeArguments As Type() = {} - Friend Shared ReadOnly NoTypeParameters As Type() = {} + Friend Shared ReadOnly NoArguments As Object() = Array.Empty(Of Object)() + Friend Shared ReadOnly NoArgumentNames As String() = Array.Empty(Of String)() + Friend Shared ReadOnly NoTypeArguments As Type() = Array.Empty(Of Type)() + Friend Shared ReadOnly NoTypeParameters As Type() = Array.Empty(Of Type)() Friend Shared ReadOnly OperatorCLSNames As String() Friend Shared ReadOnly OperatorNames As String() @@ -840,7 +839,7 @@ Namespace Microsoft.VisualBasic.CompilerServices BindingFlags.Static Or BindingFlags.Instance - Private Shared ReadOnly s_noMembers As MemberInfo() = {} + Private Shared ReadOnly s_noMembers As MemberInfo() = Array.Empty(Of MemberInfo)() Private Shared Function FilterInvalidMembers(ByVal members As MemberInfo()) As MemberInfo() diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/VB6File.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/VB6File.vb index 4a11379ef58aba..c8e02071fe1b82 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/VB6File.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/VB6File.vb @@ -2632,7 +2632,7 @@ SkipWhiteSpaceExit: If CheckEOF(lChar) Then m_eof = True Else - Do While (sTermChars.IndexOf(ChrW(lChar)) = -1) + Do While (Not sTermChars.Contains(ChrW(lChar))) lChar = m_sr.Read() m_position += 1 diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/VBBinder.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/VBBinder.vb index ab4ba8c9e4902d..ec70075d9f584a 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/VBBinder.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/VBBinder.vb @@ -1963,7 +1963,9 @@ NextMethod8: For i As Integer = 0 To namedParameters.GetUpperBound(0) If (namedParameters(i) Is Nothing) Then Diagnostics.Debug.Assert(False, "Should never be reached") +#Disable Warning CA2208 ' Instantiate argument exceptions correctly Throw New ArgumentException +#Enable Warning CA2208 ' Instantiate argument exceptions correctly End If Next i End If @@ -1991,7 +1993,7 @@ NextMethod8: p = GetMethodsByName(objType, objIReflect, name, invokeAttr) If (args Is Nothing) Then - args = New Object() {} + args = Array.Empty(Of Object)() End If Dim binderState As Object = Nothing diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/ErrObject.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/ErrObject.vb index d331c1b8a546a3..2c6b57998348fd 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/ErrObject.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/ErrObject.vb @@ -3,13 +3,12 @@ Imports Microsoft.VisualBasic.CompilerServices Imports Microsoft.VisualBasic.CompilerServices.Utils -Imports Microsoft.VisualBasic.CompilerServices.ExceptionUtils Imports System Imports System.Runtime.InteropServices Namespace Microsoft.VisualBasic - + Public NotInheritable Class ErrObject ' Error object private values @@ -432,7 +431,7 @@ Namespace Microsoft.VisualBasic Friend Function MapErrorNumber(ByVal Number As Integer) As Integer If Number > 65535 Then ' Number cannot be greater than 65535. - Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1), "Number") + Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1), NameOf(Number)) End If If Number >= 0 Then diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileIO/FileSystem.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileIO/FileSystem.vb index 13ac7596db8f39..8205efd585e4dc 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileIO/FileSystem.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileIO/FileSystem.vb @@ -740,7 +740,7 @@ Namespace Microsoft.VisualBasic.FileIO ' Cannot call through IO.File.WriteAllBytes (since they don't support append) ' so only check for trailing separator - CheckFilePathTrailingSeparator(file, "file") + CheckFilePathTrailingSeparator(file, NameOf(file)) Dim FileStream As IO.FileStream = Nothing Try @@ -787,7 +787,7 @@ Namespace Microsoft.VisualBasic.FileIO 'Cannot call through IO.File.WriteAllText (since they don't support: append, prefer current encoding than specified one) ' so only check for trailing separator. - CheckFilePathTrailingSeparator(file, "file") + CheckFilePathTrailingSeparator(file, NameOf(file)) Dim StreamWriter As IO.StreamWriter = Nothing Try @@ -2195,7 +2195,7 @@ Namespace Microsoft.VisualBasic.FileIO Private m_SearchText As String ' The text to search. Private m_IgnoreCase As Boolean ' Should we ignore case? Private m_Decoder As Text.Decoder ' The Decoder to use. - Private m_PreviousCharBuffer() As Char = {} ' The cached character array from previous call to IsTextExist. + Private m_PreviousCharBuffer() As Char = Array.Empty(Of Char)() ' The cached character array from previous call to IsTextExist. Private m_CheckPreamble As Boolean = True ' True to check for preamble. False otherwise. Private m_Preamble() As Byte ' The byte order mark we need to consider. End Class 'Private Class TextSearchHelper diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileIO/MalformedLineException.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileIO/MalformedLineException.vb index f11e7dde4b6aa9..adcab1329dd581 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileIO/MalformedLineException.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileIO/MalformedLineException.vb @@ -7,8 +7,6 @@ Imports System Imports System.ComponentModel Imports System.Globalization -Imports Microsoft.VisualBasic.CompilerServices.Utils - Namespace Microsoft.VisualBasic.FileIO ''' diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileIO/SpecialDirectories.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileIO/SpecialDirectories.vb index 2d5a72d78f9d55..fdd6a222588810 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileIO/SpecialDirectories.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileIO/SpecialDirectories.vb @@ -6,7 +6,6 @@ Option Explicit On Imports System Imports System.Environment Imports System.Reflection -Imports Microsoft.VisualBasic.CompilerServices.Utils Imports ExUtils = Microsoft.VisualBasic.CompilerServices.ExceptionUtils Namespace Microsoft.VisualBasic.FileIO diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileIO/TextFieldParser.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileIO/TextFieldParser.vb index c37df3fd08d34c..cd92369dfcd3c0 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileIO/TextFieldParser.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileIO/TextFieldParser.vb @@ -12,7 +12,6 @@ Imports System.Text Imports System.Text.RegularExpressions Imports Microsoft.VisualBasic.CompilerServices.ExceptionUtils -Imports Microsoft.VisualBasic.CompilerServices.Utils Namespace Microsoft.VisualBasic.FileIO @@ -222,7 +221,7 @@ Namespace Microsoft.VisualBasic.FileIO Return m_TextFieldType End Get Set(ByVal value As FieldType) - ValidateFieldTypeEnumValue(value, "value") + ValidateFieldTypeEnumValue(value, NameOf(value)) m_TextFieldType = value m_NeedPropertyCheck = True End Set @@ -838,6 +837,7 @@ Namespace Microsoft.VisualBasic.FileIO End If Cursor = i + 1 +#Disable Warning CA1834 ' Consider using 'StringBuilder.Append(char)' when applicable ' See if vbLf should be added as well If Character = vbCr Then If Cursor < m_CharsRead Then @@ -852,6 +852,7 @@ Namespace Microsoft.VisualBasic.FileIO End If End If End If +#Enable Warning CA1834 ' Consider using 'StringBuilder.Append(char)' when applicable Return Builder.ToString() End If @@ -1425,13 +1426,13 @@ Namespace Microsoft.VisualBasic.FileIO Private m_Reader As TextReader ' An array holding the strings that indicate a line is a comment - Private m_CommentTokens() As String = New String() {} + Private m_CommentTokens() As String = Array.Empty(Of String)() ' The line last read by either ReadLine or ReadFields Private m_LineNumber As Long = 1 ' Flags whether or not there is data left to read. Assume there is at creation - Private m_EndOfData As Boolean = False + Private m_EndOfData As Boolean ' Holds the last malformed line Private m_ErrorLine As String = "" @@ -1476,13 +1477,13 @@ Namespace Microsoft.VisualBasic.FileIO Private m_TrimWhiteSpace As Boolean = True ' The position of the cursor in the buffer - Private m_Position As Integer = 0 + Private m_Position As Integer ' The position of the peek cursor - Private m_PeekPosition As Integer = 0 + Private m_PeekPosition As Integer ' The number of chars in the buffer - Private m_CharsRead As Integer = 0 + Private m_CharsRead As Integer ' Indicates that the user has changed properties so that we need to validate before a read Private m_NeedPropertyCheck As Boolean = True @@ -1520,7 +1521,7 @@ Namespace Microsoft.VisualBasic.FileIO Private Const ENDING_QUOTE As String = """[{0}]*" ' Indicates passed in stream should be not be closed - Private m_LeaveOpen As Boolean = False + Private m_LeaveOpen As Boolean End Class ''' diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileSystem.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileSystem.vb index 34c75b914ff26e..7caadfba707e98 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileSystem.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileSystem.vb @@ -1247,7 +1247,7 @@ Namespace Microsoft.VisualBasic ' This exception should never be hit. ' We will throw Arguments are not valid. - Throw New ArgumentException(SR.Argument_InvalidValue, "om") + Throw New ArgumentException(SR.Argument_InvalidValue, NameOf(om)) End Function Friend Sub CloseAllFiles(ByVal assem As System.Reflection.Assembly) diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/Financial.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/Financial.vb index 38e324928a8170..8ae002256879ca 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/Financial.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/Financial.vb @@ -3,8 +3,6 @@ Imports System Imports System.Math -Imports Microsoft.VisualBasic.CompilerServices -Imports Microsoft.VisualBasic.CompilerServices.Utils Namespace Microsoft.VisualBasic diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/Helpers/ForEachEnum.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/Helpers/ForEachEnum.vb index aa72dfd15923b8..88e40df41161d8 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/Helpers/ForEachEnum.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/Helpers/ForEachEnum.vb @@ -4,7 +4,6 @@ Imports System Imports System.Collections Imports System.Diagnostics -Imports Microsoft.VisualBasic.CompilerServices Namespace Microsoft.VisualBasic @@ -20,7 +19,7 @@ Namespace Microsoft.VisualBasic ' because of threading and synchronization issues involved which would then cause ' perf degrade. - Private mDisposed As Boolean = False + Private mDisposed As Boolean 'The collection this enumerator is enumerating over Private mCollectionObject As Microsoft.VisualBasic.Collection diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/Helpers/NativeMethods.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/Helpers/NativeMethods.vb index eb7f656c6ff2ce..36404accab340a 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/Helpers/NativeMethods.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/Helpers/NativeMethods.vb @@ -16,6 +16,7 @@ Namespace Microsoft.VisualBasic.CompilerServices CloseHandle _ Lib "kernel32" (ByVal hObject As IntPtr) As Integer +#Disable Warning CA1838 ' Avoid 'StringBuilder' parameters for P/Invokes ''' Given a 32-bit SHFILEOPSTRUCT, call the appropriate SHFileOperation function diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/Information.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/Information.vb index 4c85fc225ead73..407c683501a084 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/Information.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/Information.vb @@ -2,8 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. Imports System -Imports System.Globalization -Imports System.Security Imports Microsoft.VisualBasic.CompilerServices Imports Microsoft.VisualBasic.CompilerServices.ExceptionUtils Imports Microsoft.VisualBasic.CompilerServices.Utils diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/Interaction.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/Interaction.vb index b8ec8bdb31a511..bb3b41868d5254 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/Interaction.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/Interaction.vb @@ -3,14 +3,12 @@ Imports System Imports System.Reflection -Imports System.Text Imports System.Runtime.InteropServices Imports System.Runtime.Versioning Imports Microsoft.Win32 Imports Microsoft.VisualBasic.CompilerServices Imports Microsoft.VisualBasic.CompilerServices.ExceptionUtils -Imports Microsoft.VisualBasic.CompilerServices.Utils Namespace Microsoft.VisualBasic diff --git a/src/mono/netcore/System.Private.CoreLib/System.Private.CoreLib.csproj b/src/mono/netcore/System.Private.CoreLib/System.Private.CoreLib.csproj index 034e8fc051164c..224987c6ec4a09 100644 --- a/src/mono/netcore/System.Private.CoreLib/System.Private.CoreLib.csproj +++ b/src/mono/netcore/System.Private.CoreLib/System.Private.CoreLib.csproj @@ -45,7 +45,6 @@ true $(OutputPath)$(MSBuildProjectName).xml - true diff --git a/src/mono/netcore/gen-xunit-runner/gen-xunit-runner.csproj b/src/mono/netcore/gen-xunit-runner/gen-xunit-runner.csproj index db5d7ffbac947a..70197bc5771ed1 100644 --- a/src/mono/netcore/gen-xunit-runner/gen-xunit-runner.csproj +++ b/src/mono/netcore/gen-xunit-runner/gen-xunit-runner.csproj @@ -3,7 +3,8 @@ Exe netcoreapp3.0 - false + false + false diff --git a/src/mono/netcore/sample/Android/Program.csproj b/src/mono/netcore/sample/Android/Program.csproj index e627bfee6da934..889ecbbdd897ca 100644 --- a/src/mono/netcore/sample/Android/Program.csproj +++ b/src/mono/netcore/sample/Android/Program.csproj @@ -10,6 +10,7 @@ true <_TrimmerDefaultAction>link true + $(NoWarn),CA1050 diff --git a/src/mono/netcore/sample/HelloWorld/Program.cs b/src/mono/netcore/sample/HelloWorld/Program.cs index 45d83b35c78218..9f95d6411e6801 100644 --- a/src/mono/netcore/sample/HelloWorld/Program.cs +++ b/src/mono/netcore/sample/HelloWorld/Program.cs @@ -2,9 +2,9 @@ namespace HelloWorld { - class Program + internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { bool isMono = typeof(object).Assembly.GetType("Mono.RuntimeStructs") != null; Console.WriteLine("Hello World " + (isMono ? "from Mono!" : "from CoreCLR!")); diff --git a/src/mono/netcore/sample/iOS/Program.csproj b/src/mono/netcore/sample/iOS/Program.csproj index 7973414b0fa683..832b98b5502f51 100644 --- a/src/mono/netcore/sample/iOS/Program.csproj +++ b/src/mono/netcore/sample/iOS/Program.csproj @@ -12,6 +12,7 @@ <_TrimmerDefaultAction>link True true + false diff --git a/src/mono/netcore/sample/wasm/browser/Program.cs b/src/mono/netcore/sample/wasm/browser/Program.cs index 9ee366cc71c29d..1cf44433f6d190 100644 --- a/src/mono/netcore/sample/wasm/browser/Program.cs +++ b/src/mono/netcore/sample/wasm/browser/Program.cs @@ -9,7 +9,7 @@ namespace Sample { public class Test { - public static void Main(String[] args) + public static void Main(string[] args) { Console.WriteLine ("Hello, World!"); } diff --git a/src/mono/netcore/sample/wasm/console/Program.cs b/src/mono/netcore/sample/wasm/console/Program.cs index 85a347fe3371fe..b7771e9a5357f5 100644 --- a/src/mono/netcore/sample/wasm/console/Program.cs +++ b/src/mono/netcore/sample/wasm/console/Program.cs @@ -6,7 +6,7 @@ public class Test { - public static void Main (String[] args) { + public static void Main (string[] args) { Console.WriteLine ("Hello, World!"); } } diff --git a/src/mono/netcore/tests/HwIntrinsics/HwIntrinsics.csproj b/src/mono/netcore/tests/HwIntrinsics/HwIntrinsics.csproj index 08cba7b3151da1..b62323d60fc97f 100644 --- a/src/mono/netcore/tests/HwIntrinsics/HwIntrinsics.csproj +++ b/src/mono/netcore/tests/HwIntrinsics/HwIntrinsics.csproj @@ -7,5 +7,6 @@ netcoreapp3.0 false true + false diff --git a/src/mono/netcore/tools/jitdiff/jitdiff.cs b/src/mono/netcore/tools/jitdiff/jitdiff.cs index 4daab1da58b3e5..ec511cd9d01cd8 100644 --- a/src/mono/netcore/tools/jitdiff/jitdiff.cs +++ b/src/mono/netcore/tools/jitdiff/jitdiff.cs @@ -6,211 +6,211 @@ namespace JitDiffTools { - class Program - { - static void Main (string [] args) - { - if (args?.Length != 2) - { - Console.WriteLine ("usage:\n\tjitdiff folder1 folder2"); - return; - } - - string [] filesBefore = Directory.GetFiles (args [0], "*.dasm"); - string [] filesAfter = Directory.GetFiles (args [1], "*.dasm"); - var pairs = new List> (); - - foreach (string fileBefore in filesBefore) - { - string fileName = Path.GetFileName (fileBefore); - string fileAfter = filesAfter.FirstOrDefault (f => - Path.GetFileName (f).Equals (fileName, StringComparison.InvariantCultureIgnoreCase)); - - if (fileAfter != null) - pairs.Add (new Tuple (fileBefore, fileAfter)); - } - - long totalFileDiff = 0; - Console.WriteLine (); - foreach (var pair in pairs) - { - long sizeBefore = new FileInfo (pair.Item1).Length; - long sizeAfter = new FileInfo (pair.Item2).Length; - long diff = sizeAfter - sizeBefore; - totalFileDiff += diff; - if (diff != 0) - Console.WriteLine ($"Total diff for {Path.GetFileName (pair.Item1)}: {diff} bytes"); - } - if (totalFileDiff != 0) - Console.WriteLine ($"Total diff for all files: {totalFileDiff} bytes"); - - Console.WriteLine ("\n=====================\n= Per-method diffs (may take a while):\n=====================\n"); - foreach (var pair in pairs) - { - PrintDiffs (pair.Item1, pair.Item2); - } - Console.WriteLine ("Done."); - } - - static void PrintDiffs (string fileBefore, string fileAfter) - { - List diff = GetDiffs (fileBefore, fileAfter); - - int totalRegression = 0, totalImprovement = 0; - int methodRegressed = 0, methodImproved = 0; - foreach (var diffItem in diff.OrderByDescending (d => d.DiffPercentage)) - { - if (diffItem.HasChanges) - { - Console.WriteLine (diffItem); - if (diffItem.Diff > 0) - { - totalRegression += diffItem.Diff; - methodRegressed++; - } - else - { - totalImprovement += diffItem.Diff; - methodImproved++; - } - } - } - - if (methodRegressed == 0 && methodImproved == 0) - return; - - Console.WriteLine ("\n"); - Console.WriteLine (Path.GetFileNameWithoutExtension (fileBefore)); - Console.WriteLine ($"Methods \"regressed\": {methodRegressed}"); - Console.WriteLine ($"Methods \"improved\": {methodImproved}"); - Console.WriteLine ($"Total regression: {totalRegression} lines, Total improvement: {totalImprovement} lines."); - Console.WriteLine ("\n"); - } - - static List GetDiffs (string file1, string file2) - { - List file1Functions = ParseFunctions (file1); - List file2Functions = ParseFunctions (file2); - - var diffItems = new List (); // diffs - - foreach (FunctionInfo file1Function in file1Functions) - { - // SingleOrDefault to make sure functions are unique - FunctionInfo file2Function = file2Functions.FirstOrDefault (f => f.Name == file1Function.Name); - diffItems.Add (new DiffItem (file1Function, file2Function)); // file2Function can be null here - means function was removed in file2 - } - - foreach (FunctionInfo file2Function in file2Functions) - { - // SingleOrDefault to make sure functions are unique - FunctionInfo file1Function = file1Functions.FirstOrDefault (f => f.Name == file2Function.Name); - if (file1Function == null) - diffItems.Add (new DiffItem (null, file2Function)); // function was added in file2 - } - - return diffItems; - } - - static bool TryParseFunctionName (string str, out string name) - { - // depends on objdump, let's use the whole line as a name if it ends with `:` - if (str.EndsWith (':')) - { - // Possible formats: - // 1) func_name: - // 2) p_%var%_func_name: - // 3) %var% : - // 4) %var% : - name = Regex.Replace (str, @"\b([a-f0-9]+)\b", m => ""); - name = Regex.Replace (name, @"(p_\d+_)?", m => ""); - return true; - } - name = null; - return false; - } - - static List ParseFunctions (string file) - { - string [] lines = File.ReadAllLines (file) - .Select (l => l.Trim (' ', '\t', '\r', '\n')) - .Where (l => !string.IsNullOrEmpty (l)) - .ToArray (); - - var result = new List (); - FunctionInfo current = null; - foreach (string line in lines) - { - if (TryParseFunctionName (line, out string name)) - { - current = new FunctionInfo (name); - result.Add (current); - } - current?.Body.Add (line); - } - return result; - } - } - - public class FunctionInfo - { - public FunctionInfo (string name) - { - if (string.IsNullOrWhiteSpace (name)) - throw new ArgumentException ("Function name should not be empty", nameof (name)); - Name = name; - } - - public string Name { get; } - - public List Body { get; set; } = new List(); - - public override string ToString () => $"{Name} (lines:{Body?.Count})"; - } - - public class DiffItem - { - public DiffItem (FunctionInfo before, FunctionInfo after) - { - if (before == null && after == null) - throw new ArgumentException ("Both Before and After can not be null at the same time"); - if (before != null && after != null && before.Name != after.Name) - throw new ArgumentException ("After.Name != Before.Name"); - Before = before; - After = after; - Name = before != null ? before.Name : after.Name; - } - - public string Name { get; } - - public FunctionInfo Before { get; } - - public FunctionInfo After { get; } - - public int Diff => CalculateBytes (After) - CalculateBytes (Before); - - static int CalculateBytes (FunctionInfo info) - { - // TODO: calculate bytes - return info?.Body?.Count ?? 0; - } - - public bool HasChanges => Diff != 0; - - public double DiffPercentage - { - get - { - int b = Before?.Body?.Count ?? 0; - int a = (After?.Body?.Count ?? 0) * 100; - if (a == 0 && b == 0) - return 0; - if (a > 0 && b == 0) - return -100; - return -(100 - a / b); - } - } - - public override string ToString () => $"Diff for {Name}: {Diff} lines ({DiffPercentage:F1}%)"; - } -} \ No newline at end of file + internal class Program + { + private static void Main (string [] args) + { + if (args?.Length != 2) + { + Console.WriteLine ("usage:\n\tjitdiff folder1 folder2"); + return; + } + + string [] filesBefore = Directory.GetFiles (args [0], "*.dasm"); + string [] filesAfter = Directory.GetFiles (args [1], "*.dasm"); + var pairs = new List> (); + + foreach (string fileBefore in filesBefore) + { + string fileName = Path.GetFileName (fileBefore); + string fileAfter = filesAfter.FirstOrDefault (f => + Path.GetFileName (f).Equals (fileName, StringComparison.InvariantCultureIgnoreCase)); + + if (fileAfter != null) + pairs.Add (new Tuple (fileBefore, fileAfter)); + } + + long totalFileDiff = 0; + Console.WriteLine (); + foreach (var pair in pairs) + { + long sizeBefore = new FileInfo (pair.Item1).Length; + long sizeAfter = new FileInfo (pair.Item2).Length; + long diff = sizeAfter - sizeBefore; + totalFileDiff += diff; + if (diff != 0) + Console.WriteLine ($"Total diff for {Path.GetFileName (pair.Item1)}: {diff} bytes"); + } + if (totalFileDiff != 0) + Console.WriteLine ($"Total diff for all files: {totalFileDiff} bytes"); + + Console.WriteLine ("\n=====================\n= Per-method diffs (may take a while):\n=====================\n"); + foreach (var pair in pairs) + { + PrintDiffs (pair.Item1, pair.Item2); + } + Console.WriteLine ("Done."); + } + + private static void PrintDiffs (string fileBefore, string fileAfter) + { + List diff = GetDiffs (fileBefore, fileAfter); + + int totalRegression = 0, totalImprovement = 0; + int methodRegressed = 0, methodImproved = 0; + foreach (var diffItem in diff.OrderByDescending (d => d.DiffPercentage)) + { + if (diffItem.HasChanges) + { + Console.WriteLine (diffItem); + if (diffItem.Diff > 0) + { + totalRegression += diffItem.Diff; + methodRegressed++; + } + else + { + totalImprovement += diffItem.Diff; + methodImproved++; + } + } + } + + if (methodRegressed == 0 && methodImproved == 0) + return; + + Console.WriteLine ("\n"); + Console.WriteLine (Path.GetFileNameWithoutExtension (fileBefore)); + Console.WriteLine ($"Methods \"regressed\": {methodRegressed}"); + Console.WriteLine ($"Methods \"improved\": {methodImproved}"); + Console.WriteLine ($"Total regression: {totalRegression} lines, Total improvement: {totalImprovement} lines."); + Console.WriteLine ("\n"); + } + + private static List GetDiffs (string file1, string file2) + { + List file1Functions = ParseFunctions (file1); + List file2Functions = ParseFunctions (file2); + + var diffItems = new List (); // diffs + + foreach (FunctionInfo file1Function in file1Functions) + { + // SingleOrDefault to make sure functions are unique + FunctionInfo file2Function = file2Functions.FirstOrDefault (f => f.Name == file1Function.Name); + diffItems.Add (new DiffItem (file1Function, file2Function)); // file2Function can be null here - means function was removed in file2 + } + + foreach (FunctionInfo file2Function in file2Functions) + { + // SingleOrDefault to make sure functions are unique + FunctionInfo file1Function = file1Functions.FirstOrDefault (f => f.Name == file2Function.Name); + if (file1Function == null) + diffItems.Add (new DiffItem (null, file2Function)); // function was added in file2 + } + + return diffItems; + } + + private static bool TryParseFunctionName (string str, out string name) + { + // depends on objdump, let's use the whole line as a name if it ends with `:` + if (str.EndsWith (':')) + { + // Possible formats: + // 1) func_name: + // 2) p_%var%_func_name: + // 3) %var% : + // 4) %var% : + name = Regex.Replace (str, @"\b([a-f0-9]+)\b", m => ""); + name = Regex.Replace (name, @"(p_\d+_)?", m => ""); + return true; + } + name = null; + return false; + } + + private static List ParseFunctions (string file) + { + string [] lines = File.ReadAllLines (file) + .Select (l => l.Trim (' ', '\t', '\r', '\n')) + .Where (l => !string.IsNullOrEmpty (l)) + .ToArray (); + + var result = new List (); + FunctionInfo current = null; + foreach (string line in lines) + { + if (TryParseFunctionName (line, out string name)) + { + current = new FunctionInfo (name); + result.Add (current); + } + current?.Body.Add (line); + } + return result; + } + } + + public class FunctionInfo + { + public FunctionInfo (string name) + { + if (string.IsNullOrWhiteSpace (name)) + throw new ArgumentException ("Function name should not be empty", nameof(name)); + Name = name; + } + + public string Name { get; } + + public List Body { get; set; } = new List(); + + public override string ToString () => $"{Name} (lines:{Body?.Count})"; + } + + public class DiffItem + { + public DiffItem (FunctionInfo before, FunctionInfo after) + { + if (before == null && after == null) + throw new ArgumentException ("Both Before and After can not be null at the same time"); + if (before != null && after != null && before.Name != after.Name) + throw new ArgumentException ("After.Name != Before.Name"); + Before = before; + After = after; + Name = before != null ? before.Name : after.Name; + } + + public string Name { get; } + + public FunctionInfo Before { get; } + + public FunctionInfo After { get; } + + public int Diff => CalculateBytes (After) - CalculateBytes (Before); + + private static int CalculateBytes (FunctionInfo info) + { + // TODO: calculate bytes + return info?.Body?.Count ?? 0; + } + + public bool HasChanges => Diff != 0; + + public double DiffPercentage + { + get + { + int b = Before?.Body?.Count ?? 0; + int a = (After?.Body?.Count ?? 0) * 100; + if (a == 0 && b == 0) + return 0; + if (a > 0 && b == 0) + return -100; + return -(100 - a / b); + } + } + + public override string ToString () => $"Diff for {Name}: {Diff} lines ({DiffPercentage:F1}%)"; + } +} diff --git a/src/mono/wasm/debugger/BrowserDebugHost/BrowserDebugHost.csproj b/src/mono/wasm/debugger/BrowserDebugHost/BrowserDebugHost.csproj index 957a218f910253..5f8b53f269dddb 100644 --- a/src/mono/wasm/debugger/BrowserDebugHost/BrowserDebugHost.csproj +++ b/src/mono/wasm/debugger/BrowserDebugHost/BrowserDebugHost.csproj @@ -3,6 +3,7 @@ $(NetCoreAppCurrent) true + $(NoWarn),CA2007 diff --git a/src/mono/wasm/debugger/BrowserDebugHost/Program.cs b/src/mono/wasm/debugger/BrowserDebugHost/Program.cs index c987310961a353..c203cd0d8291de 100644 --- a/src/mono/wasm/debugger/BrowserDebugHost/Program.cs +++ b/src/mono/wasm/debugger/BrowserDebugHost/Program.cs @@ -22,7 +22,7 @@ public class Program { public static void Main(string[] args) { - var host = new WebHostBuilder() + IWebHost host = new WebHostBuilder() .UseSetting("UseIISIntegration", false.ToString()) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) diff --git a/src/mono/wasm/debugger/BrowserDebugHost/Startup.cs b/src/mono/wasm/debugger/BrowserDebugHost/Startup.cs index 5787dbf1fd8df0..01974d8a5619fc 100644 --- a/src/mono/wasm/debugger/BrowserDebugHost/Startup.cs +++ b/src/mono/wasm/debugger/BrowserDebugHost/Startup.cs @@ -35,26 +35,26 @@ public Startup(IConfiguration configuration) => // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IOptionsMonitor optionsAccessor, IWebHostEnvironment env) { - var options = optionsAccessor.CurrentValue; + ProxyOptions options = optionsAccessor.CurrentValue; app.UseDeveloperExceptionPage() .UseWebSockets() .UseDebugProxy(options); } } - static class DebugExtensions + internal static class DebugExtensions { public static Dictionary MapValues(Dictionary response, HttpContext context, Uri debuggerHost) { var filtered = new Dictionary(); - var request = context.Request; + HttpRequest request = context.Request; - foreach (var key in response.Keys) + foreach (string key in response.Keys) { switch (key) { case "devtoolsFrontendUrl": - var front = response[key]; + string front = response[key]; filtered[key] = $"{debuggerHost.Scheme}://{debuggerHost.Authority}{front.Replace($"ws={debuggerHost.Authority}", $"ws={request.Host}")}"; break; case "webSocketDebuggerUrl": @@ -77,7 +77,7 @@ public static IApplicationBuilder UseDebugProxy( ProxyOptions options, Func, HttpContext, Uri, Dictionary> mapFunc) { - var devToolsHost = options.DevToolsUrl; + Uri devToolsHost = options.DevToolsUrl; app.UseRouter(router => { router.MapGet("/", Copy); @@ -91,8 +91,8 @@ public static IApplicationBuilder UseDebugProxy( string GetEndpoint(HttpContext context) { - var request = context.Request; - var requestPath = request.Path; + HttpRequest request = context.Request; + PathString requestPath = request.Path; return $"{devToolsHost.Scheme}://{devToolsHost.Authority}{request.Path}{request.QueryString}"; } @@ -100,11 +100,11 @@ async Task Copy(HttpContext context) { using (var httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(5) }) { - var response = await httpClient.GetAsync(GetEndpoint(context)); + HttpResponseMessage response = await httpClient.GetAsync(GetEndpoint(context)); context.Response.ContentType = response.Content.Headers.ContentType.ToString(); if ((response.Content.Headers.ContentLength ?? 0) > 0) context.Response.ContentLength = response.Content.Headers.ContentLength; - var bytes = await response.Content.ReadAsByteArrayAsync(); + byte[] bytes = await response.Content.ReadAsByteArrayAsync(); await context.Response.Body.WriteAsync(bytes); } @@ -112,7 +112,7 @@ async Task Copy(HttpContext context) async Task RewriteSingle(HttpContext context) { - var version = await ProxyGetJsonAsync>(GetEndpoint(context)); + Dictionary version = await ProxyGetJsonAsync>(GetEndpoint(context)); context.Response.ContentType = "application/json"; await context.Response.WriteAsync( JsonSerializer.Serialize(mapFunc(version, context, devToolsHost))); @@ -120,8 +120,8 @@ await context.Response.WriteAsync( async Task RewriteArray(HttpContext context) { - var tabs = await ProxyGetJsonAsync[]>(GetEndpoint(context)); - var alteredTabs = tabs.Select(t => mapFunc(t, context, devToolsHost)).ToArray(); + Dictionary[] tabs = await ProxyGetJsonAsync[]>(GetEndpoint(context)); + Dictionary[] alteredTabs = tabs.Select(t => mapFunc(t, context, devToolsHost)).ToArray(); context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonSerializer.Serialize(alteredTabs)); } @@ -137,13 +137,13 @@ async Task ConnectProxy(HttpContext context) var endpoint = new Uri($"ws://{devToolsHost.Authority}{context.Request.Path.ToString()}"); try { - using var loggerFactory = LoggerFactory.Create( + using ILoggerFactory loggerFactory = LoggerFactory.Create( builder => builder.AddConsole().AddFilter(null, LogLevel.Information)); context.Request.Query.TryGetValue("urlSymbolServer", out StringValues urlSymbolServerList); var proxy = new DebuggerProxy(loggerFactory, urlSymbolServerList.ToList()); - - var ideSocket = await context.WebSockets.AcceptWebSocketAsync(); + + System.Net.WebSockets.WebSocket ideSocket = await context.WebSockets.AcceptWebSocketAsync(); await proxy.Run(endpoint, ideSocket); } @@ -156,11 +156,11 @@ async Task ConnectProxy(HttpContext context) return app; } - static async Task ProxyGetJsonAsync(string url) + private static async Task ProxyGetJsonAsync(string url) { using (var httpClient = new HttpClient()) { - var response = await httpClient.GetAsync(url); + HttpResponseMessage response = await httpClient.GetAsync(url); return await JsonSerializer.DeserializeAsync(await response.Content.ReadAsStreamAsync()); } } diff --git a/src/mono/wasm/debugger/BrowserDebugProxy/BrowserDebugProxy.csproj b/src/mono/wasm/debugger/BrowserDebugProxy/BrowserDebugProxy.csproj index e5d92818e2c93c..1ca220bc558f69 100644 --- a/src/mono/wasm/debugger/BrowserDebugProxy/BrowserDebugProxy.csproj +++ b/src/mono/wasm/debugger/BrowserDebugProxy/BrowserDebugProxy.csproj @@ -2,6 +2,7 @@ $(NetCoreAppCurrent) + $(NoWarn),CA2007 diff --git a/src/mono/wasm/debugger/BrowserDebugProxy/DebugStore.cs b/src/mono/wasm/debugger/BrowserDebugProxy/DebugStore.cs index 820b917f2a037e..f1240dcf8cba5c 100644 --- a/src/mono/wasm/debugger/BrowserDebugProxy/DebugStore.cs +++ b/src/mono/wasm/debugger/BrowserDebugProxy/DebugStore.cs @@ -29,7 +29,7 @@ internal class BreakpointRequest public int Column { get; private set; } public MethodInfo Method { get; private set; } - JObject request; + private JObject request; public bool IsResolved => Assembly != null; public List Locations { get; } = new List(); @@ -62,10 +62,10 @@ public static BreakpointRequest Parse(string id, JObject args) public bool IsMatch(SourceFile sourceFile) { - var url = request?["url"]?.Value(); + string url = request?["url"]?.Value(); if (url == null) { - var urlRegex = request?["urlRegex"].Value(); + string urlRegex = request?["urlRegex"].Value(); var regex = new Regex(urlRegex); return regex.IsMatch(sourceFile.Url.ToString()) || regex.IsMatch(sourceFile.DocUrl); } @@ -78,8 +78,8 @@ public bool TryResolve(SourceFile sourceFile) if (!IsMatch(sourceFile)) return false; - var line = request?["lineNumber"]?.Value(); - var column = request?["columnNumber"]?.Value(); + int? line = request?["lineNumber"]?.Value(); + int? column = request?["columnNumber"]?.Value(); if (line == null || column == null) return false; @@ -134,10 +134,10 @@ public CliLocation(MethodInfo method, int offset) internal class SourceLocation { - SourceId id; - int line; - int column; - CliLocation cliLoc; + private SourceId id; + private int line; + private int column; + private CliLocation cliLoc; public SourceLocation(SourceId id, int line, int column) { @@ -166,11 +166,11 @@ public static SourceLocation Parse(JObject obj) if (obj == null) return null; - if (!SourceId.TryParse(obj["scriptId"]?.Value(), out var id)) + if (!SourceId.TryParse(obj["scriptId"]?.Value(), out SourceId id)) return null; - var line = obj["lineNumber"]?.Value(); - var column = obj["columnNumber"]?.Value(); + int? line = obj["lineNumber"]?.Value(); + int? column = obj["columnNumber"]?.Value(); if (id == null || line == null || column == null) return null; @@ -208,9 +208,9 @@ public override int GetHashCode(SourceLocation loc) internal class SourceId { - const string Scheme = "dotnet://"; + private const string Scheme = "dotnet://"; - readonly int assembly, document; + private readonly int assembly, document; public int Assembly => assembly; public int Document => document; @@ -230,20 +230,20 @@ public SourceId(string id) public static bool TryParse(string id, out SourceId source) { source = null; - if (!TryParse(id, out var assembly, out var document)) + if (!TryParse(id, out int assembly, out int document)) return false; source = new SourceId(assembly, document); return true; } - static bool TryParse(string id, out int assembly, out int document) + private static bool TryParse(string id, out int assembly, out int document) { assembly = document = 0; if (id == null || !id.StartsWith(Scheme, StringComparison.Ordinal)) return false; - var sp = id.Substring(Scheme.Length).Split('_'); + string[] sp = id.Substring(Scheme.Length).Split('_'); if (sp.Length != 2) return false; @@ -275,8 +275,8 @@ public override bool Equals(object obj) internal class MethodInfo { - MethodDefinition methodDef; - SourceFile source; + private MethodDefinition methodDef; + private SourceFile source; public SourceId SourceId => source.SourceId; @@ -294,14 +294,14 @@ public MethodInfo(AssemblyInfo assembly, MethodDefinition methodDef, SourceFile this.methodDef = methodDef; this.source = source; - var sps = DebugInformation.SequencePoints; - if (sps == null || sps.Count() < 1) + Mono.Collections.Generic.Collection sps = DebugInformation.SequencePoints; + if (sps == null || sps.Count < 1) return; SequencePoint start = sps[0]; SequencePoint end = sps[0]; - foreach (var sp in sps) + foreach (SequencePoint sp in sps) { if (sp.StartLine < start.StartLine) start = sp; @@ -321,7 +321,7 @@ public MethodInfo(AssemblyInfo assembly, MethodDefinition methodDef, SourceFile public SourceLocation GetLocationByIl(int pos) { SequencePoint prev = null; - foreach (var sp in DebugInformation.SequencePoints) + foreach (SequencePoint sp in DebugInformation.SequencePoints) { if (sp.Offset > pos) break; @@ -353,9 +353,9 @@ public VarInfo[] GetLiveVarsAt(int offset) internal class TypeInfo { - AssemblyInfo assembly; - TypeDefinition type; - List methods; + private AssemblyInfo assembly; + private TypeDefinition type; + private List methods; public TypeInfo(AssemblyInfo assembly, TypeDefinition type) { @@ -371,16 +371,16 @@ public TypeInfo(AssemblyInfo assembly, TypeDefinition type) public override string ToString() => "TypeInfo('" + FullName + "')"; } - class AssemblyInfo + internal class AssemblyInfo { - static int next_id; - ModuleDefinition image; - readonly int id; - readonly ILogger logger; - Dictionary methods = new Dictionary(); - Dictionary sourceLinkMappings = new Dictionary(); - Dictionary typesByName = new Dictionary(); - readonly List sources = new List(); + private static int next_id; + private ModuleDefinition image; + private readonly int id; + private readonly ILogger logger; + private Dictionary methods = new Dictionary(); + private Dictionary sourceLinkMappings = new Dictionary(); + private Dictionary typesByName = new Dictionary(); + private readonly List sources = new List(); internal string Url { get; } public bool TriedToLoadSymbolsOnDemand { get; set; } @@ -439,23 +439,23 @@ public AssemblyInfo(ILogger logger) { this.logger = logger; } - + public ModuleDefinition Image => image; public void ClearDebugInfo() { - foreach (var type in image.GetTypes()) + foreach (TypeDefinition type in image.GetTypes()) { var typeInfo = new TypeInfo(this, type); typesByName[type.FullName] = typeInfo; - foreach (var method in type.Methods) + foreach (MethodDefinition method in type.Methods) { method.DebugInformation = null; } } } - + public void Populate() { ProcessSourceLink(); @@ -467,7 +467,7 @@ SourceFile FindSource(Document doc) if (doc == null) return null; - if (d2s.TryGetValue(doc, out var source)) + if (d2s.TryGetValue(doc, out SourceFile source)) return source; var src = new SourceFile(this, sources.Count, doc, GetSourceLinkUrl(doc.Url)); @@ -476,16 +476,16 @@ SourceFile FindSource(Document doc) return src; }; - foreach (var type in image.GetTypes()) + foreach (TypeDefinition type in image.GetTypes()) { var typeInfo = new TypeInfo(this, type); typesByName[type.FullName] = typeInfo; - foreach (var method in type.Methods) + foreach (MethodDefinition method in type.Methods) { - foreach (var sp in method.DebugInformation.SequencePoints) + foreach (SequencePoint sp in method.DebugInformation.SequencePoints) { - var source = FindSource(sp.Document); + SourceFile source = FindSource(sp.Document); var methodInfo = new MethodInfo(this, method, source); methods[method.MetadataToken.RID] = methodInfo; if (source != null) @@ -499,15 +499,15 @@ SourceFile FindSource(Document doc) private void ProcessSourceLink() { - var sourceLinkDebugInfo = image.CustomDebugInformations.FirstOrDefault(i => i.Kind == CustomDebugInformationKind.SourceLink); + CustomDebugInformation sourceLinkDebugInfo = image.CustomDebugInformations.FirstOrDefault(i => i.Kind == CustomDebugInformationKind.SourceLink); if (sourceLinkDebugInfo != null) { - var sourceLinkContent = ((SourceLinkDebugInformation)sourceLinkDebugInfo).Content; + string sourceLinkContent = ((SourceLinkDebugInformation)sourceLinkDebugInfo).Content; if (sourceLinkContent != null) { - var jObject = JObject.Parse(sourceLinkContent)["documents"]; + JToken jObject = JObject.Parse(sourceLinkContent)["documents"]; sourceLinkMappings = JsonConvert.DeserializeObject>(jObject.ToString()); } } @@ -518,7 +518,7 @@ private Uri GetSourceLinkUrl(string document) if (sourceLinkMappings.TryGetValue(document, out string url)) return new Uri(url); - foreach (var sourceLinkDocument in sourceLinkMappings) + foreach (KeyValuePair sourceLinkDocument in sourceLinkMappings) { string key = sourceLinkDocument.Key; @@ -527,11 +527,11 @@ private Uri GetSourceLinkUrl(string document) continue; } - var keyTrim = key.TrimEnd('*'); + string keyTrim = key.TrimEnd('*'); if (document.StartsWith(keyTrim, StringComparison.OrdinalIgnoreCase)) { - var docUrlPart = document.Replace(keyTrim, ""); + string docUrlPart = document.Replace(keyTrim, ""); return new Uri(sourceLinkDocument.Value.TrimEnd('*') + docUrlPart); } } @@ -552,23 +552,23 @@ public SourceFile GetDocById(int document) public MethodInfo GetMethodByToken(uint token) { - methods.TryGetValue(token, out var value); + methods.TryGetValue(token, out MethodInfo value); return value; } public TypeInfo GetTypeByName(string name) { - typesByName.TryGetValue(name, out var res); + typesByName.TryGetValue(name, out TypeInfo res); return res; } } internal class SourceFile { - Dictionary methods; - AssemblyInfo assembly; - int id; - Document doc; + private Dictionary methods; + private AssemblyInfo assembly; + private int id; + private Document doc; internal SourceFile(AssemblyInfo assembly, int id, Document doc, Uri sourceLinkUri) { @@ -611,19 +611,19 @@ internal void AddMethod(MethodInfo mi) public (int startLine, int startColumn, int endLine, int endColumn) GetExtents() { - var start = Methods.OrderBy(m => m.StartLocation.Line).ThenBy(m => m.StartLocation.Column).First(); - var end = Methods.OrderByDescending(m => m.EndLocation.Line).ThenByDescending(m => m.EndLocation.Column).First(); + MethodInfo start = Methods.OrderBy(m => m.StartLocation.Line).ThenBy(m => m.StartLocation.Column).First(); + MethodInfo end = Methods.OrderByDescending(m => m.EndLocation.Line).ThenByDescending(m => m.EndLocation.Column).First(); return (start.StartLocation.Line, start.StartLocation.Column, end.EndLocation.Line, end.EndLocation.Column); } - async Task GetDataAsync(Uri uri, CancellationToken token) + private async Task GetDataAsync(Uri uri, CancellationToken token) { var mem = new MemoryStream(); try { if (uri.IsFile && File.Exists(uri.LocalPath)) { - using (var file = File.Open(SourceUri.LocalPath, FileMode.Open)) + using (FileStream file = File.Open(SourceUri.LocalPath, FileMode.Open)) { await file.CopyToAsync(mem, token).ConfigureAwait(false); mem.Position = 0; @@ -631,8 +631,8 @@ async Task GetDataAsync(Uri uri, CancellationToken token) } else if (uri.Scheme == "http" || uri.Scheme == "https") { - var client = new HttpClient(); - using (var stream = await client.GetStreamAsync(uri)) + using (var client = new HttpClient()) + using (Stream stream = await client.GetStreamAsync(uri, token)) { await stream.CopyToAsync(mem, token).ConfigureAwait(false); mem.Position = 0; @@ -646,35 +646,39 @@ async Task GetDataAsync(Uri uri, CancellationToken token) return mem; } - static HashAlgorithm GetHashAlgorithm(DocumentHashAlgorithm algorithm) + private static HashAlgorithm GetHashAlgorithm(DocumentHashAlgorithm algorithm) { switch (algorithm) { case DocumentHashAlgorithm.SHA1: +#pragma warning disable CA5350 // Do Not Use Weak Cryptographic Algorithms return SHA1.Create(); +#pragma warning restore CA5350 // Do Not Use Weak Cryptographic Algorithms case DocumentHashAlgorithm.SHA256: return SHA256.Create(); case DocumentHashAlgorithm.MD5: +#pragma warning disable CA5351 // Do Not Use Broken Cryptographic Algorithms return MD5.Create(); +#pragma warning restore CA5351 // Do Not Use Broken Cryptographic Algorithms } return null; } - bool CheckPdbHash(byte[] computedHash) + private bool CheckPdbHash(byte[] computedHash) { if (computedHash.Length != doc.Hash.Length) return false; - for (var i = 0; i < computedHash.Length; i++) + for (int i = 0; i < computedHash.Length; i++) if (computedHash[i] != doc.Hash[i]) return false; return true; } - byte[] ComputePdbHash(Stream sourceStream) + private byte[] ComputePdbHash(Stream sourceStream) { - var algorithm = GetHashAlgorithm(doc.HashAlgorithm); + HashAlgorithm algorithm = GetHashAlgorithm(doc.HashAlgorithm); if (algorithm != null) using (algorithm) return algorithm.ComputeHash(sourceStream); @@ -687,9 +691,9 @@ byte[] ComputePdbHash(Stream sourceStream) if (doc.EmbeddedSource.Length > 0) return new MemoryStream(doc.EmbeddedSource, false); - foreach (var url in new[] { SourceUri, SourceLinkUri }) + foreach (Uri url in new[] { SourceUri, SourceLinkUri }) { - var mem = await GetDataAsync(url, token).ConfigureAwait(false); + MemoryStream mem = await GetDataAsync(url, token).ConfigureAwait(false); if (mem != null && (!checkHash || CheckPdbHash(ComputePdbHash(mem)))) { mem.Position = 0; @@ -716,9 +720,9 @@ public object ToScriptSource(int executionContextId, object executionContextAuxD internal class DebugStore { - List assemblies = new List(); - readonly HttpClient client; - readonly ILogger logger; + private List assemblies = new List(); + private readonly HttpClient client; + private readonly ILogger logger; public DebugStore(ILogger logger, HttpClient client) { @@ -729,7 +733,7 @@ public DebugStore(ILogger logger, HttpClient client) public DebugStore(ILogger logger) : this(logger, new HttpClient()) { } - class DebugItem + private class DebugItem { public string Url { get; set; } public Task Data { get; set; } @@ -739,7 +743,7 @@ public async IAsyncEnumerable Load(SessionId sessionId, string[] loa { var asm_files = new List(); var pdb_files = new List(); - foreach (var file_name in loaded_files) + foreach (string file_name in loaded_files) { if (file_name.EndsWith(".pdb", StringComparison.OrdinalIgnoreCase)) pdb_files.Add(file_name); @@ -748,7 +752,7 @@ public async IAsyncEnumerable Load(SessionId sessionId, string[] loa } List steps = new List(); - foreach (var url in asm_files) + foreach (string url in asm_files) { try { @@ -761,7 +765,7 @@ public async IAsyncEnumerable Load(SessionId sessionId, string[] loa new DebugItem { Url = url, - Data = Task.WhenAll(client.GetByteArrayAsync(url), pdb != null ? client.GetByteArrayAsync(pdb) : Task.FromResult(null)) + Data = Task.WhenAll(client.GetByteArrayAsync(url, token), pdb != null ? client.GetByteArrayAsync(pdb, token) : Task.FromResult(null)) }); } catch (Exception e) @@ -771,12 +775,12 @@ public async IAsyncEnumerable Load(SessionId sessionId, string[] loa } var resolver = new DefaultAssemblyResolver(); - foreach (var step in steps) + foreach (DebugItem step in steps) { AssemblyInfo assembly = null; try { - var bytes = await step.Data.ConfigureAwait(false); + byte[][] bytes = await step.Data.ConfigureAwait(false); assembly = new AssemblyInfo(resolver, step.Url, bytes[0], bytes[1]); } catch (Exception e) @@ -787,7 +791,7 @@ public async IAsyncEnumerable Load(SessionId sessionId, string[] loa continue; assemblies.Add(assembly); - foreach (var source in assembly.Sources) + foreach (SourceFile source in assembly.Sources) yield return source; } } @@ -802,10 +806,10 @@ public async IAsyncEnumerable Load(SessionId sessionId, string[] loa V8 uses zero based indexing for both line and column. PPDBs uses one based indexing for both line and column. */ - static bool Match(SequencePoint sp, SourceLocation start, SourceLocation end) + private static bool Match(SequencePoint sp, SourceLocation start, SourceLocation end) { - var spStart = (Line: sp.StartLine - 1, Column: sp.StartColumn - 1); - var spEnd = (Line: sp.EndLine - 1, Column: sp.EndColumn - 1); + (int Line, int Column) spStart = (Line: sp.StartLine - 1, Column: sp.StartColumn - 1); + (int Line, int Column) spEnd = (Line: sp.EndLine - 1, Column: sp.EndColumn - 1); if (start.Line > spEnd.Line) return false; @@ -831,9 +835,9 @@ public List FindPossibleBreakpoints(SourceLocation start, Source return null; } - var sourceId = start.Id; + SourceId sourceId = start.Id; - var doc = GetFileById(sourceId); + SourceFile doc = GetFileById(sourceId); var res = new List(); if (doc == null) @@ -842,9 +846,9 @@ public List FindPossibleBreakpoints(SourceLocation start, Source return res; } - foreach (var method in doc.Methods) + foreach (MethodInfo method in doc.Methods) { - foreach (var sequencePoint in method.DebugInformation.SequencePoints) + foreach (SequencePoint sequencePoint in method.DebugInformation.SequencePoints) { if (!sequencePoint.IsHidden && Match(sequencePoint, start, end)) res.Add(new SourceLocation(method, sequencePoint)); @@ -857,9 +861,9 @@ public List FindPossibleBreakpoints(SourceLocation start, Source V8 uses zero based indexing for both line and column. PPDBs uses one based indexing for both line and column. */ - static bool Match(SequencePoint sp, int line, int column) + private static bool Match(SequencePoint sp, int line, int column) { - var bp = (line: line + 1, column: column + 1); + (int line, int column) bp = (line: line + 1, column: column + 1); if (sp.StartLine > bp.line || sp.EndLine < bp.line) return false; @@ -881,15 +885,15 @@ public IEnumerable FindBreakpointLocations(BreakpointRequest req { request.TryResolve(this); - var asm = assemblies.FirstOrDefault(a => a.Name.Equals(request.Assembly, StringComparison.OrdinalIgnoreCase)); - var sourceFile = asm?.Sources?.SingleOrDefault(s => s.DebuggerFileName.Equals(request.File, StringComparison.OrdinalIgnoreCase)); + AssemblyInfo asm = assemblies.FirstOrDefault(a => a.Name.Equals(request.Assembly, StringComparison.OrdinalIgnoreCase)); + SourceFile sourceFile = asm?.Sources?.SingleOrDefault(s => s.DebuggerFileName.Equals(request.File, StringComparison.OrdinalIgnoreCase)); if (sourceFile == null) yield break; - foreach (var method in sourceFile.Methods) + foreach (MethodInfo method in sourceFile.Methods) { - foreach (var sequencePoint in method.DebugInformation.SequencePoints) + foreach (SequencePoint sequencePoint in method.DebugInformation.SequencePoints) { if (!sequencePoint.IsHidden && Match(sequencePoint, request.Line, request.Column)) yield return new SourceLocation(method, sequencePoint); diff --git a/src/mono/wasm/debugger/BrowserDebugProxy/DevToolsHelper.cs b/src/mono/wasm/debugger/BrowserDebugProxy/DevToolsHelper.cs index 2bfabd9bf8dd50..ece6305561f9f3 100644 --- a/src/mono/wasm/debugger/BrowserDebugProxy/DevToolsHelper.cs +++ b/src/mono/wasm/debugger/BrowserDebugProxy/DevToolsHelper.cs @@ -33,7 +33,7 @@ public SessionId(string sessionId) public static bool operator !=(SessionId a, SessionId b) => a.sessionId != b.sessionId; - public static SessionId Null { get; } = new SessionId(); + public static SessionId Null { get; } public override string ToString() => $"session-{sessionId}"; } @@ -74,7 +74,7 @@ public static bool TryParse(string id, out DotnetObjectId objectId) if (!id.StartsWith("dotnet:")) return false; - var parts = id.Split(":", 3); + string[] parts = id.Split(":", 3); if (parts.Length < 3) return false; @@ -101,12 +101,12 @@ public struct Result public bool IsOk => Value != null; public bool IsErr => Error != null; - Result(JObject result, JObject error) + private Result(JObject result, JObject error) { if (result != null && error != null) throw new ArgumentException($"Both {nameof(result)} and {nameof(error)} arguments cannot be non-null."); - bool resultHasError = String.Compare((result?["result"] as JObject)?["subtype"]?.Value(), "error") == 0; + bool resultHasError = string.Compare((result?["result"] as JObject)?["subtype"]?.Value(), "error") == 0; if (result != null && resultHasError) { this.Value = null; @@ -167,8 +167,8 @@ internal class MonoCommands { public string expression { get; set; } public string objectGroup { get; set; } = "mono-debugger"; - public bool includeCommandLineAPI { get; set; } = false; - public bool silent { get; set; } = false; + public bool includeCommandLineAPI { get; set; } + public bool silent { get; set; } public bool returnByValue { get; set; } = true; public MonoCommands(string expression) => this.expression = expression; @@ -223,7 +223,7 @@ internal class MonoConstants public const string EVENT_RAISED = "mono_wasm_debug_event_raised:aef14bca-5519-4dfe-b35a-f867abc123ae"; } - class Frame + internal class Frame { public Frame(MethodInfo method, SourceLocation location, int id) { @@ -237,7 +237,7 @@ public Frame(MethodInfo method, SourceLocation location, int id) public int Id { get; private set; } } - class Breakpoint + internal class Breakpoint { public SourceLocation Location { get; private set; } public int RemoteId { get; set; } @@ -261,14 +261,14 @@ public Breakpoint(string stackId, SourceLocation loc, BreakpointState state) } } - enum BreakpointState + internal enum BreakpointState { Active, Disabled, Pending } - enum StepKind + internal enum StepKind { Into, Out, @@ -280,7 +280,7 @@ internal class ExecutionContext public string DebuggerId { get; set; } public Dictionary BreakpointRequests { get; } = new Dictionary(); - public TaskCompletionSource ready = null; + public TaskCompletionSource ready; public bool IsRuntimeReady => ready != null && ready.Task.IsCompleted; public int Id { get; set; } @@ -292,7 +292,7 @@ internal class ExecutionContext internal DebugStore store; public TaskCompletionSource Source { get; } = new TaskCompletionSource(); - Dictionary perScopeCaches { get; } = new Dictionary(); + private Dictionary perScopeCaches { get; } = new Dictionary(); public DebugStore Store { @@ -307,7 +307,7 @@ public DebugStore Store public PerScopeCache GetCacheForScope(int scope_id) { - if (perScopeCaches.TryGetValue(scope_id, out var cache)) + if (perScopeCaches.TryGetValue(scope_id, out PerScopeCache cache)) return cache; cache = new PerScopeCache(); diff --git a/src/mono/wasm/debugger/BrowserDebugProxy/DevToolsProxy.cs b/src/mono/wasm/debugger/BrowserDebugProxy/DevToolsProxy.cs index e9d501ad4390ca..ade381d754cb8d 100644 --- a/src/mono/wasm/debugger/BrowserDebugProxy/DevToolsProxy.cs +++ b/src/mono/wasm/debugger/BrowserDebugProxy/DevToolsProxy.cs @@ -16,10 +16,10 @@ namespace Microsoft.WebAssembly.Diagnostics { - class DevToolsQueue + internal class DevToolsQueue { - Task current_send; - List pending; + private Task current_send; + private List pending; public WebSocket Ws { get; private set; } public Task CurrentSend { get { return current_send; } } @@ -62,14 +62,14 @@ public Task Pump(CancellationToken token) internal class DevToolsProxy { - TaskCompletionSource side_exception = new TaskCompletionSource(); - TaskCompletionSource client_initiated_close = new TaskCompletionSource(); - Dictionary> pending_cmds = new Dictionary>(); - ClientWebSocket browser; - WebSocket ide; - int next_cmd_id; - List pending_ops = new List(); - List queues = new List(); + private TaskCompletionSource side_exception = new TaskCompletionSource(); + private TaskCompletionSource client_initiated_close = new TaskCompletionSource(); + private Dictionary> pending_cmds = new Dictionary>(); + private ClientWebSocket browser; + private WebSocket ide; + private int next_cmd_id; + private List pending_ops = new List(); + private List queues = new List(); protected readonly ILogger logger; @@ -88,7 +88,7 @@ protected virtual Task AcceptCommand(MessageId id, string method, JObject return Task.FromResult(false); } - async Task ReadOne(WebSocket socket, CancellationToken token) + private async Task ReadOne(WebSocket socket, CancellationToken token) { byte[] buff = new byte[4000]; var mem = new MemoryStream(); @@ -102,7 +102,7 @@ async Task ReadOne(WebSocket socket, CancellationToken token) return null; } - var result = await socket.ReceiveAsync(new ArraySegment(buff), token); + WebSocketReceiveResult result = await socket.ReceiveAsync(new ArraySegment(buff), token); if (result.MessageType == WebSocketMessageType.Close) { client_initiated_close.TrySetResult(true); @@ -116,33 +116,33 @@ async Task ReadOne(WebSocket socket, CancellationToken token) } } - DevToolsQueue GetQueueForSocket(WebSocket ws) + private DevToolsQueue GetQueueForSocket(WebSocket ws) { return queues.FirstOrDefault(q => q.Ws == ws); } - DevToolsQueue GetQueueForTask(Task task) + private DevToolsQueue GetQueueForTask(Task task) { return queues.FirstOrDefault(q => q.CurrentSend == task); } - void Send(WebSocket to, JObject o, CancellationToken token) + private void Send(WebSocket to, JObject o, CancellationToken token) { - var sender = browser == to ? "Send-browser" : "Send-ide"; + string sender = browser == to ? "Send-browser" : "Send-ide"; - var method = o["method"]?.ToString(); + string method = o["method"]?.ToString(); //if (method != "Debugger.scriptParsed" && method != "Runtime.consoleAPICalled") Log("protocol", $"{sender}: " + JsonConvert.SerializeObject(o)); - var bytes = Encoding.UTF8.GetBytes(o.ToString()); + byte[] bytes = Encoding.UTF8.GetBytes(o.ToString()); - var queue = GetQueueForSocket(to); + DevToolsQueue queue = GetQueueForSocket(to); - var task = queue.Send(bytes, token); + Task task = queue.Send(bytes, token); if (task != null) pending_ops.Add(task); } - async Task OnEvent(SessionId sessionId, string method, JObject args, CancellationToken token) + private async Task OnEvent(SessionId sessionId, string method, JObject args, CancellationToken token) { try { @@ -158,13 +158,13 @@ async Task OnEvent(SessionId sessionId, string method, JObject args, Cancellatio } } - async Task OnCommand(MessageId id, string method, JObject args, CancellationToken token) + private async Task OnCommand(MessageId id, string method, JObject args, CancellationToken token) { try { if (!await AcceptCommand(id, method, args, token)) { - var res = await SendCommandInternal(id, method, args, token); + Result res = await SendCommandInternal(id, method, args, token); SendResponseInternal(id, res, token); } } @@ -174,11 +174,11 @@ async Task OnCommand(MessageId id, string method, JObject args, CancellationToke } } - void OnResponse(MessageId id, Result result) + private void OnResponse(MessageId id, Result result) { //logger.LogTrace ("got id {0} res {1}", id, result); // Fixme - if (pending_cmds.Remove(id, out var task)) + if (pending_cmds.Remove(id, out TaskCompletionSource task)) { task.SetResult(result); return; @@ -186,11 +186,11 @@ void OnResponse(MessageId id, Result result) logger.LogError("Cannot respond to command: {id} with result: {result} - command is not pending", id, result); } - void ProcessBrowserMessage(string msg, CancellationToken token) + private void ProcessBrowserMessage(string msg, CancellationToken token) { var res = JObject.Parse(msg); - var method = res["method"]?.ToString(); + string method = res["method"]?.ToString(); //if (method != "Debugger.scriptParsed" && method != "Runtime.consoleAPICalled") Log("protocol", $"browser: {msg}"); @@ -200,7 +200,7 @@ void ProcessBrowserMessage(string msg, CancellationToken token) OnResponse(new MessageId(res["sessionId"]?.Value(), res["id"].Value()), Result.FromJson(res)); } - void ProcessIdeMessage(string msg, CancellationToken token) + private void ProcessIdeMessage(string msg, CancellationToken token) { Log("protocol", $"ide: {msg}"); if (!string.IsNullOrEmpty(msg)) @@ -219,7 +219,7 @@ internal async Task SendCommand(SessionId id, string method, JObject arg return await SendCommandInternal(id, method, args, token); } - Task SendCommandInternal(SessionId sessionId, string method, JObject args, CancellationToken token) + private Task SendCommandInternal(SessionId sessionId, string method, JObject args, CancellationToken token) { int id = Interlocked.Increment(ref next_cmd_id); @@ -247,7 +247,7 @@ public void SendEvent(SessionId sessionId, string method, JObject args, Cancella SendEventInternal(sessionId, method, args, token); } - void SendEventInternal(SessionId sessionId, string method, JObject args, CancellationToken token) + private void SendEventInternal(SessionId sessionId, string method, JObject args, CancellationToken token) { var o = JObject.FromObject(new { @@ -265,7 +265,7 @@ internal void SendResponse(MessageId id, Result result, CancellationToken token) SendResponseInternal(id, result, token); } - void SendResponseInternal(MessageId id, Result result, CancellationToken token) + private void SendResponseInternal(MessageId id, Result result, CancellationToken token) { JObject o = result.ToJObject(id); if (result.IsErr) @@ -300,11 +300,11 @@ public async Task Run(Uri browserUri, WebSocket ideSocket) { while (!x.IsCancellationRequested) { - var task = await Task.WhenAny(pending_ops.ToArray()); + Task task = await Task.WhenAny(pending_ops.ToArray()); //logger.LogTrace ("pump {0} {1}", task, pending_ops.IndexOf (task)); if (task == pending_ops[0]) { - var msg = ((Task)task).Result; + string msg = ((Task)task).Result; if (msg != null) { pending_ops[0] = ReadOne(browser, x.Token); //queue next read @@ -313,7 +313,7 @@ public async Task Run(Uri browserUri, WebSocket ideSocket) } else if (task == pending_ops[1]) { - var msg = ((Task)task).Result; + string msg = ((Task)task).Result; if (msg != null) { pending_ops[1] = ReadOne(ide, x.Token); //queue next read @@ -322,12 +322,12 @@ public async Task Run(Uri browserUri, WebSocket ideSocket) } else if (task == pending_ops[2]) { - var res = ((Task)task).Result; + bool res = ((Task)task).Result; throw new Exception("side task must always complete with an exception, what's going on???"); } else if (task == pending_ops[3]) { - var res = ((Task)task).Result; + bool res = ((Task)task).Result; Log("verbose", $"DevToolsProxy: Client initiated close from {browserUri}"); x.Cancel(); } @@ -335,10 +335,10 @@ public async Task Run(Uri browserUri, WebSocket ideSocket) { //must be a background task pending_ops.Remove(task); - var queue = GetQueueForTask(task); + DevToolsQueue queue = GetQueueForTask(task); if (queue != null) { - var tsk = queue.Pump(x.Token); + Task tsk = queue.Pump(x.Token); if (tsk != null) pending_ops.Add(tsk); } diff --git a/src/mono/wasm/debugger/BrowserDebugProxy/EvaluateExpression.cs b/src/mono/wasm/debugger/BrowserDebugProxy/EvaluateExpression.cs index f863a3c8a892fb..b19d3f257e9c4f 100644 --- a/src/mono/wasm/debugger/BrowserDebugProxy/EvaluateExpression.cs +++ b/src/mono/wasm/debugger/BrowserDebugProxy/EvaluateExpression.cs @@ -21,12 +21,12 @@ namespace Microsoft.WebAssembly.Diagnostics internal class EvaluateExpression { - class FindVariableNMethodCall : CSharpSyntaxWalker + private class FindVariableNMethodCall : CSharpSyntaxWalker { public List identifiers = new List(); public List methodCall = new List(); public List memberAccesses = new List(); - public List argValues = new List(); + public List argValues = new List(); public override void Visit(SyntaxNode node) { @@ -63,8 +63,8 @@ public SyntaxTree ReplaceVars(SyntaxTree syntaxTree, IEnumerable ma_val // 1. Replace all this.a occurrences with this_a_ABDE root = root.ReplaceNodes(memberAccesses, (maes, _) => { - var ma_str = maes.ToString(); - if (!memberAccessToParamName.TryGetValue(ma_str, out var id_name)) + string ma_str = maes.ToString(); + if (!memberAccessToParamName.TryGetValue(ma_str, out string id_name)) { // Generate a random suffix string suffix = Guid.NewGuid().ToString().Substring(0, 5); @@ -80,10 +80,10 @@ public SyntaxTree ReplaceVars(SyntaxTree syntaxTree, IEnumerable ma_val var paramsSet = new HashSet(); // 2. For every unique member ref, add a corresponding method param - foreach (var (maes, value) in memberAccesses.Zip(ma_values)) + foreach ((MemberAccessExpressionSyntax maes, JObject value) in memberAccesses.Zip(ma_values)) { - var node_str = maes.ToString(); - if (!memberAccessToParamName.TryGetValue(node_str, out var id_name)) + string node_str = maes.ToString(); + if (!memberAccessToParamName.TryGetValue(node_str, out string id_name)) { throw new Exception($"BUG: Expected to find an id name for the member access string: {node_str}"); } @@ -91,7 +91,7 @@ public SyntaxTree ReplaceVars(SyntaxTree syntaxTree, IEnumerable ma_val root = UpdateWithNewMethodParam(root, id_name, value); } - foreach (var (idns, value) in identifiers.Zip(id_values)) + foreach ((IdentifierNameSyntax idns, JObject value) in identifiers.Zip(id_values)) { root = UpdateWithNewMethodParam(root, idns.Identifier.Text, value); } @@ -112,7 +112,7 @@ CompilationUnitSyntax UpdateWithNewMethodParam(CompilationUnitSyntax root, strin argValues.Add(ConvertJSToCSharpType(value)); - var updatedMethod = method.AddParameterListParameters( + MethodDeclarationSyntax updatedMethod = method.AddParameterListParameters( SyntaxFactory.Parameter( SyntaxFactory.Identifier(id_name)) .WithType(SyntaxFactory.ParseTypeName(GetTypeFullName(value)))); @@ -126,9 +126,9 @@ CompilationUnitSyntax UpdateWithNewMethodParam(CompilationUnitSyntax root, strin private object ConvertJSToCSharpType(JToken variable) { - var value = variable["value"]; - var type = variable["type"].Value(); - var subType = variable["subtype"]?.Value(); + JToken value = variable["value"]; + string type = variable["type"].Value(); + string subType = variable["subtype"]?.Value(); switch (type) { @@ -148,8 +148,8 @@ private object ConvertJSToCSharpType(JToken variable) private string GetTypeFullName(JToken variable) { - var type = variable["type"].ToString(); - var subType = variable["subtype"]?.Value(); + string type = variable["type"].ToString(); + string subType = variable["subtype"]?.Value(); object value = ConvertJSToCSharpType(variable); switch (type) @@ -167,7 +167,7 @@ private string GetTypeFullName(JToken variable) } } - static SyntaxNode GetExpressionFromSyntaxTree(SyntaxTree syntaxTree) + private static SyntaxNode GetExpressionFromSyntaxTree(SyntaxTree syntaxTree) { CompilationUnitSyntax root = syntaxTree.GetCompilationUnitRoot(); ClassDeclarationSyntax classDeclaration = root.Members.ElementAt(0) as ClassDeclarationSyntax; @@ -183,10 +183,10 @@ private static async Task> ResolveMemberAccessExpressions(IEnumer MemberReferenceResolver resolver, CancellationToken token) { var memberAccessValues = new List(); - foreach (var maes in member_accesses) + foreach (MemberAccessExpressionSyntax maes in member_accesses) { - var memberAccessString = maes.ToString(); - var value = await resolver.Resolve(memberAccessString, token); + string memberAccessString = maes.ToString(); + JObject value = await resolver.Resolve(memberAccessString, token); if (value == null) throw new ReturnAsErrorException($"Failed to resolve member access for {memberAccessString}", "ReferenceError"); @@ -199,7 +199,7 @@ private static async Task> ResolveMemberAccessExpressions(IEnumer private static async Task> ResolveIdentifiers(IEnumerable identifiers, MemberReferenceResolver resolver, CancellationToken token) { var values = new List(); - foreach (var var in identifiers) + foreach (IdentifierNameSyntax var in identifiers) { JObject value = await resolver.Resolve(var.Identifier.Text, token); if (value == null) @@ -222,9 +222,9 @@ public static object Evaluate() { return (" + expression + @"); } - }"); + }", cancellationToken: token); - var expressionTree = GetExpressionFromSyntaxTree(syntaxTree); + SyntaxNode expressionTree = GetExpressionFromSyntaxTree(syntaxTree); if (expressionTree == null) throw new Exception($"BUG: Unable to evaluate {expression}, could not get expression from the syntax tree"); @@ -236,15 +236,15 @@ public static object Evaluate() // and the returned expression from GetExpressionFromSyntaxTree is `a`! if (expressionTree.Kind() == SyntaxKind.IdentifierName || expressionTree.Kind() == SyntaxKind.ThisExpression) { - var var_name = expressionTree.ToString(); - var value = await resolver.Resolve(var_name, token); + string var_name = expressionTree.ToString(); + JObject value = await resolver.Resolve(var_name, token); if (value == null) throw new ReturnAsErrorException($"Cannot find member named '{var_name}'.", "ReferenceError"); return value; } - var memberAccessValues = await ResolveMemberAccessExpressions(findVarNMethodCall.memberAccesses, resolver, token); + IList memberAccessValues = await ResolveMemberAccessExpressions(findVarNMethodCall.memberAccesses, resolver, token); // eg. "this.dateTime", " dateTime.TimeOfDay" if (expressionTree.Kind() == SyntaxKind.SimpleMemberAccessExpression && findVarNMethodCall.memberAccesses.Count == 1) @@ -252,7 +252,7 @@ public static object Evaluate() return memberAccessValues[0]; } - var identifierValues = await ResolveIdentifiers(findVarNMethodCall.identifiers, resolver, token); + IList identifierValues = await ResolveIdentifiers(findVarNMethodCall.identifiers, resolver, token); syntaxTree = findVarNMethodCall.ReplaceVars(syntaxTree, memberAccessValues, identifierValues); expressionTree = GetExpressionFromSyntaxTree(syntaxTree); @@ -271,16 +271,16 @@ public static object Evaluate() references: references, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); - var semanticModel = compilation.GetSemanticModel(syntaxTree); - var typeInfo = semanticModel.GetTypeInfo(expressionTree); + SemanticModel semanticModel = compilation.GetSemanticModel(syntaxTree); + CodeAnalysis.TypeInfo typeInfo = semanticModel.GetTypeInfo(expressionTree, cancellationToken: token); using (var ms = new MemoryStream()) { - EmitResult result = compilation.Emit(ms); + EmitResult result = compilation.Emit(ms, cancellationToken: token); if (!result.Success) { var sb = new StringBuilder(); - foreach (var d in result.Diagnostics) + foreach (Diagnostic d in result.Diagnostics) sb.Append(d.ToString()); throw new ReturnAsErrorException(sb.ToString(), "CompilationError"); @@ -290,7 +290,7 @@ public static object Evaluate() Assembly assembly = Assembly.Load(ms.ToArray()); Type type = assembly.GetType("CompileAndRunTheExpression"); - var ret = type.InvokeMember("Evaluate", + object ret = type.InvokeMember("Evaluate", BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public, null, null, @@ -300,7 +300,7 @@ public static object Evaluate() } } - static readonly HashSet NumericTypes = new HashSet + private static readonly HashSet NumericTypes = new HashSet { typeof(decimal), typeof(byte), typeof(sbyte), typeof(short), typeof(ushort), @@ -308,7 +308,7 @@ public static object Evaluate() typeof(float), typeof(double) }; - static object ConvertCSharpToJSType(object v, ITypeSymbol type) + private static object ConvertCSharpToJSType(object v, ITypeSymbol type) { if (v == null) return new { type = "object", subtype = "null", className = type.ToString() }; @@ -329,7 +329,7 @@ static object ConvertCSharpToJSType(object v, ITypeSymbol type) } - class ReturnAsErrorException : Exception + internal class ReturnAsErrorException : Exception { public Result Error { get; } public ReturnAsErrorException(JObject error) diff --git a/src/mono/wasm/debugger/BrowserDebugProxy/MemberReferenceResolver.cs b/src/mono/wasm/debugger/BrowserDebugProxy/MemberReferenceResolver.cs index 145e2237c5e2ab..bde69748bfb658 100644 --- a/src/mono/wasm/debugger/BrowserDebugProxy/MemberReferenceResolver.cs +++ b/src/mono/wasm/debugger/BrowserDebugProxy/MemberReferenceResolver.cs @@ -20,7 +20,7 @@ internal class MemberReferenceResolver private PerScopeCache scopeCache; private VarInfo[] varIds; private ILogger logger; - private bool locals_fetched = false; + private bool locals_fetched; public MemberReferenceResolver(MonoProxy proxy, ExecutionContext ctx, MessageId msg_id, int scope_id, ILogger logger) { @@ -37,27 +37,27 @@ public async Task Resolve(string var_name, CancellationToken token) { if (scopeCache.Locals.Count == 0 && !locals_fetched) { - var scope_res = await proxy.GetScopeProperties(messageId, scopeId, token); + Result scope_res = await proxy.GetScopeProperties(messageId, scopeId, token); if (scope_res.IsErr) throw new Exception($"BUG: Unable to get properties for scope: {scopeId}. {scope_res}"); locals_fetched = true; } - if (scopeCache.Locals.TryGetValue(var_name, out var obj)) + if (scopeCache.Locals.TryGetValue(var_name, out JObject obj)) { return obj["value"]?.Value(); } - if (scopeCache.MemberReferences.TryGetValue(var_name, out var ret)) + if (scopeCache.MemberReferences.TryGetValue(var_name, out JObject ret)) return ret; if (varIds == null) { - var scope = ctx.CallStack.FirstOrDefault(s => s.Id == scopeId); + Frame scope = ctx.CallStack.FirstOrDefault(s => s.Id == scopeId); varIds = scope.Method.GetLiveVarsAt(scope.Location.CliLocation.Offset); } - var res = await proxy.SendMonoCommand(messageId, MonoCommands.EvaluateMemberAccess(scopeId, var_name, varIds), token); + Result res = await proxy.SendMonoCommand(messageId, MonoCommands.EvaluateMemberAccess(scopeId, var_name, varIds), token); if (res.IsOk) { ret = res.Value?["result"]?["value"]?["value"]?.Value(); diff --git a/src/mono/wasm/debugger/BrowserDebugProxy/MonoProxy.cs b/src/mono/wasm/debugger/BrowserDebugProxy/MonoProxy.cs index 1d4fb6b53922b5..4ef569d8667d95 100644 --- a/src/mono/wasm/debugger/BrowserDebugProxy/MonoProxy.cs +++ b/src/mono/wasm/debugger/BrowserDebugProxy/MonoProxy.cs @@ -19,33 +19,32 @@ namespace Microsoft.WebAssembly.Diagnostics { - internal class MonoProxy : DevToolsProxy { - IList urlSymbolServerList; - static HttpClient client = new HttpClient(); - HashSet sessions = new HashSet(); - Dictionary contexts = new Dictionary(); + private IList urlSymbolServerList; + private static HttpClient client = new HttpClient(); + private HashSet sessions = new HashSet(); + private Dictionary contexts = new Dictionary(); - public MonoProxy(ILoggerFactory loggerFactory, IList urlSymbolServerList, bool hideWebDriver = true) : base(loggerFactory) - { + public MonoProxy(ILoggerFactory loggerFactory, IList urlSymbolServerList, bool hideWebDriver = true) : base(loggerFactory) + { this.hideWebDriver = hideWebDriver; this.urlSymbolServerList = urlSymbolServerList ?? new List(); } - readonly bool hideWebDriver; + private readonly bool hideWebDriver; internal ExecutionContext GetContext(SessionId sessionId) { - if (contexts.TryGetValue(sessionId, out var context)) + if (contexts.TryGetValue(sessionId, out ExecutionContext context)) return context; throw new ArgumentException($"Invalid Session: \"{sessionId}\"", nameof(sessionId)); } - bool UpdateContext(SessionId sessionId, ExecutionContext executionContext, out ExecutionContext previousExecutionContext) + private bool UpdateContext(SessionId sessionId, ExecutionContext executionContext, out ExecutionContext previousExecutionContext) { - var previous = contexts.TryGetValue(sessionId, out previousExecutionContext); + bool previous = contexts.TryGetValue(sessionId, out previousExecutionContext); contexts[sessionId] = executionContext; return previous; } @@ -58,10 +57,10 @@ protected override async Task AcceptEvent(SessionId sessionId, string meth { case "Runtime.consoleAPICalled": { - var type = args["type"]?.ToString(); + string type = args["type"]?.ToString(); if (type == "debug") { - var a = args["args"]; + JToken a = args["args"]; if (a?[0]?["value"]?.ToString() == MonoConstants.RUNTIME_IS_READY && a?[1]?["value"]?.ToString() == "fe00e07a-5519-4dfe-b35a-f867dbaf2e28") { @@ -71,8 +70,8 @@ protected override async Task AcceptEvent(SessionId sessionId, string meth { // The optional 3rd argument is the stringified assembly // list so that we don't have to make more round trips - var context = GetContext(sessionId); - var loaded = a?[2]?["value"]?.ToString(); + ExecutionContext context = GetContext(sessionId); + string loaded = a?[2]?["value"]?.ToString(); if (loaded != null) context.LoadedFiles = JToken.Parse(loaded).ToObject(); } @@ -113,12 +112,12 @@ protected override async Task AcceptEvent(SessionId sessionId, string meth case "Runtime.executionContextCreated": { SendEvent(sessionId, method, args, token); - var ctx = args?["context"]; + JToken ctx = args?["context"]; var aux_data = ctx?["auxData"] as JObject; - var id = ctx["id"].Value(); + int id = ctx["id"].Value(); if (aux_data != null) { - var is_default = aux_data["isDefault"]?.Value(); + bool? is_default = aux_data["isDefault"]?.Value(); if (is_default == true) { await OnDefaultContext(sessionId, new ExecutionContext { Id = id, AuxData = aux_data }, token); @@ -130,7 +129,7 @@ protected override async Task AcceptEvent(SessionId sessionId, string meth case "Debugger.paused": { //TODO figure out how to stich out more frames and, in particular what happens when real wasm is on the stack - var top_func = args?["callFrames"]?[0]?["functionName"]?.Value(); + string top_func = args?["callFrames"]?[0]?["functionName"]?.Value(); if (top_func == "mono_wasm_fire_bp" || top_func == "_mono_wasm_fire_bp" || top_func == "_mono_wasm_fire_exception") { @@ -146,7 +145,7 @@ protected override async Task AcceptEvent(SessionId sessionId, string meth case "Debugger.scriptParsed": { - var url = args?["url"]?.Value() ?? ""; + string url = args?["url"]?.Value() ?? ""; switch (url) { @@ -173,12 +172,12 @@ protected override async Task AcceptEvent(SessionId sessionId, string meth return false; } - async Task IsRuntimeAlreadyReadyAlready(SessionId sessionId, CancellationToken token) + private async Task IsRuntimeAlreadyReadyAlready(SessionId sessionId, CancellationToken token) { - if (contexts.TryGetValue(sessionId, out var context) && context.IsRuntimeReady) + if (contexts.TryGetValue(sessionId, out ExecutionContext context) && context.IsRuntimeReady) return true; - var res = await SendMonoCommand(sessionId, MonoCommands.IsRuntimeReady(), token); + Result res = await SendMonoCommand(sessionId, MonoCommands.IsRuntimeReady(), token); return res.Value?["result"]?["value"]?.Value() ?? false; } @@ -189,21 +188,21 @@ protected override async Task AcceptCommand(MessageId id, string method, J if (hideWebDriver && id == SessionId.Null) await DeleteWebDriver(id, token); - if (!contexts.TryGetValue(id, out var context)) + if (!contexts.TryGetValue(id, out ExecutionContext context)) return false; switch (method) { case "Target.attachToTarget": { - var resp = await SendCommand(id, method, args, token); + Result resp = await SendCommand(id, method, args, token); await DeleteWebDriver(new SessionId(resp.Value["sessionId"]?.ToString()), token); break; } case "Debugger.enable": { - var resp = await SendCommand(id, method, args, token); + Result resp = await SendCommand(id, method, args, token); context.DebuggerId = resp.Value["debuggerId"]?.ToString(); @@ -216,13 +215,13 @@ protected override async Task AcceptCommand(MessageId id, string method, J case "Debugger.getScriptSource": { - var script = args?["scriptId"]?.Value(); + string script = args?["scriptId"]?.Value(); return await OnGetScriptSource(id, script, token); } case "Runtime.compileScript": { - var exp = args?["expression"]?.Value(); + string exp = args?["expression"]?.Value(); if (exp.StartsWith("//dotnet:", StringComparison.Ordinal)) { OnCompileDotnetScript(id, token); @@ -233,7 +232,7 @@ protected override async Task AcceptCommand(MessageId id, string method, J case "Debugger.getPossibleBreakpoints": { - var resp = await SendCommand(id, method, args, token); + Result resp = await SendCommand(id, method, args, token); if (resp.IsOk && resp.Value["locations"].HasValues) { SendResponse(id, resp, token); @@ -257,19 +256,19 @@ protected override async Task AcceptCommand(MessageId id, string method, J case "Debugger.setBreakpointByUrl": { - var resp = await SendCommand(id, method, args, token); + Result resp = await SendCommand(id, method, args, token); if (!resp.IsOk) { SendResponse(id, resp, token); return true; } - var bpid = resp.Value["breakpointId"]?.ToString(); - var locations = resp.Value["locations"]?.Values(); + string bpid = resp.Value["breakpointId"]?.ToString(); + IEnumerable locations = resp.Value["locations"]?.Values(); var request = BreakpointRequest.Parse(bpid, args); // is the store done loading? - var loaded = context.Source.Task.IsCompleted; + bool loaded = context.Source.Task.IsCompleted; if (!loaded) { // Send and empty response immediately if not @@ -280,7 +279,7 @@ protected override async Task AcceptCommand(MessageId id, string method, J if (await IsRuntimeAlreadyReadyAlready(id, token)) { - var store = await RuntimeReady(id, token); + DebugStore store = await RuntimeReady(id, token); Log("verbose", $"BP req {args}"); await SetBreakpoint(id, store, request, !loaded, token); @@ -327,7 +326,7 @@ protected override async Task AcceptCommand(MessageId id, string method, J case "Debugger.evaluateOnCallFrame": { - if (!DotnetObjectId.TryParse(args?["callFrameId"], out var objectId)) + if (!DotnetObjectId.TryParse(args?["callFrameId"], out DotnetObjectId objectId)) return false; switch (objectId.Scheme) @@ -343,17 +342,17 @@ protected override async Task AcceptCommand(MessageId id, string method, J case "Runtime.getProperties": { - if (!DotnetObjectId.TryParse(args?["objectId"], out var objectId)) + if (!DotnetObjectId.TryParse(args?["objectId"], out DotnetObjectId objectId)) break; - var result = await RuntimeGetProperties(id, objectId, args, token); + Result result = await RuntimeGetProperties(id, objectId, args, token); SendResponse(id, result, token); return true; } case "Runtime.releaseObject": { - if (!(DotnetObjectId.TryParse(args["objectId"], out var objectId) && objectId.Scheme == "cfo_res")) + if (!(DotnetObjectId.TryParse(args["objectId"], out DotnetObjectId objectId) && objectId.Scheme == "cfo_res")) break; await SendMonoCommand(id, MonoCommands.ReleaseObject(objectId), token); @@ -373,7 +372,7 @@ protected override async Task AcceptCommand(MessageId id, string method, J case "DotnetDebugger.addSymbolServerUrl": { string url = args["url"]?.Value(); - if (!String.IsNullOrEmpty(url) && !urlSymbolServerList.Contains(url)) + if (!string.IsNullOrEmpty(url) && !urlSymbolServerList.Contains(url)) urlSymbolServerList.Add(url); return true; } @@ -381,7 +380,7 @@ protected override async Task AcceptCommand(MessageId id, string method, J { Console.WriteLine("set-breakpoint-by-method: " + id + " " + args); - var store = await RuntimeReady(id, token); + DebugStore store = await RuntimeReady(id, token); string aname = args["assemblyName"]?.Value(); string typeName = args["typeName"]?.Value(); string methodName = args["methodName"]?.Value(); @@ -392,7 +391,7 @@ protected override async Task AcceptCommand(MessageId id, string method, J } // GetAssemblyByName seems to work on file names - var assembly = store.GetAssemblyByName(aname); + AssemblyInfo assembly = store.GetAssemblyByName(aname); if (assembly == null) assembly = store.GetAssemblyByName(aname + ".exe"); if (assembly == null) @@ -403,14 +402,14 @@ protected override async Task AcceptCommand(MessageId id, string method, J return true; } - var type = assembly.GetTypeByName(typeName); + TypeInfo type = assembly.GetTypeByName(typeName); if (type == null) { SendResponse(id, Result.Err($"Type '{typeName}' not found."), token); return true; } - var methodInfo = type.Methods.FirstOrDefault(m => m.Name == methodName); + MethodInfo methodInfo = type.Methods.FirstOrDefault(m => m.Name == methodName); if (methodInfo == null) { // Maybe this is an async method, in which case the debug info is attached @@ -426,7 +425,7 @@ protected override async Task AcceptCommand(MessageId id, string method, J return true; } - var src_url = methodInfo.Assembly.Sources.Single(sf => sf.SourceId == methodInfo.SourceId).Url; + string src_url = methodInfo.Assembly.Sources.Single(sf => sf.SourceId == methodInfo.SourceId).Url; SendResponse(id, Result.OkFromObject(new { result = new { line = methodInfo.StartLocation.Line, column = methodInfo.StartLocation.Column, url = src_url } @@ -436,7 +435,7 @@ protected override async Task AcceptCommand(MessageId id, string method, J } case "Runtime.callFunctionOn": { - if (!DotnetObjectId.TryParse(args["objectId"], out var objectId)) + if (!DotnetObjectId.TryParse(args["objectId"], out DotnetObjectId objectId)) return false; if (objectId.Scheme == "scope") @@ -448,8 +447,8 @@ protected override async Task AcceptCommand(MessageId id, string method, J return true; } - var res = await SendMonoCommand(id, MonoCommands.CallFunctionOn(args), token); - var res_value_type = res.Value?["result"]?["value"]?.Type; + Result res = await SendMonoCommand(id, MonoCommands.CallFunctionOn(args), token); + JTokenType? res_value_type = res.Value?["result"]?["value"]?.Type; if (res.IsOk && res_value_type == JTokenType.Object || res_value_type == JTokenType.Object) res = Result.OkFromObject(new { result = res.Value["result"]["value"] }); @@ -462,21 +461,21 @@ protected override async Task AcceptCommand(MessageId id, string method, J return false; } - async Task RuntimeGetProperties(MessageId id, DotnetObjectId objectId, JToken args, CancellationToken token) + private async Task RuntimeGetProperties(MessageId id, DotnetObjectId objectId, JToken args, CancellationToken token) { if (objectId.Scheme == "scope") { return await GetScopeProperties(id, int.Parse(objectId.Value), token); } - var res = await SendMonoCommand(id, MonoCommands.GetDetails(objectId, args), token); + Result res = await SendMonoCommand(id, MonoCommands.GetDetails(objectId, args), token); if (res.IsErr) return res; if (objectId.Scheme == "cfo_res") { // Runtime.callFunctionOn result object - var value_json_str = res.Value["result"]?["value"]?["__value_as_json_string__"]?.Value(); + string value_json_str = res.Value["result"]?["value"]?["__value_as_json_string__"]?.Value(); if (value_json_str != null) { res = Result.OkFromObject(new @@ -497,14 +496,14 @@ async Task RuntimeGetProperties(MessageId id, DotnetObjectId objectId, J return res; } - async Task OnPause(SessionId sessionId, JObject args, CancellationToken token) + private async Task OnPause(SessionId sessionId, JObject args, CancellationToken token) { //FIXME we should send release objects every now and then? Or intercept those we inject and deal in the runtime - var res = await SendMonoCommand(sessionId, MonoCommands.GetCallStack(), token); - var orig_callframes = args?["callFrames"]?.Values(); - var context = GetContext(sessionId); + Result res = await SendMonoCommand(sessionId, MonoCommands.GetCallStack(), token); + IEnumerable orig_callframes = args?["callFrames"]?.Values(); + ExecutionContext context = GetContext(sessionId); JObject data = null; - var reason = "other";//other means breakpoint + string reason = "other";//other means breakpoint if (res.IsErr) { @@ -513,7 +512,7 @@ async Task OnPause(SessionId sessionId, JObject args, CancellationToken to } //step one, figure out where did we hit - var res_value = res.Value?["result"]?["value"]; + JToken res_value = res.Value?["result"]?["value"]; if (res_value == null || res_value is JValue) { //Give up and send the original call stack @@ -521,7 +520,7 @@ async Task OnPause(SessionId sessionId, JObject args, CancellationToken to } Log("verbose", $"call stack (err is {res.Error} value is:\n{res.Value}"); - var bp_id = res_value?["breakpoint_id"]?.Value(); + int? bp_id = res_value?["breakpoint_id"]?.Value(); Log("verbose", $"We just hit bp {bp_id}"); if (!bp_id.HasValue) { @@ -529,20 +528,20 @@ async Task OnPause(SessionId sessionId, JObject args, CancellationToken to return false; } - var bp = context.BreakpointRequests.Values.SelectMany(v => v.Locations).FirstOrDefault(b => b.RemoteId == bp_id.Value); + Breakpoint bp = context.BreakpointRequests.Values.SelectMany(v => v.Locations).FirstOrDefault(b => b.RemoteId == bp_id.Value); var callFrames = new List(); - foreach (var frame in orig_callframes) + foreach (JObject frame in orig_callframes) { - var function_name = frame["functionName"]?.Value(); - var url = frame["url"]?.Value(); + string function_name = frame["functionName"]?.Value(); + string url = frame["url"]?.Value(); if ("mono_wasm_fire_bp" == function_name || "_mono_wasm_fire_bp" == function_name || "_mono_wasm_fire_exception" == function_name) { if ("_mono_wasm_fire_exception" == function_name) { - var exception_obj_id = await SendMonoCommand(sessionId, MonoCommands.GetExceptionObject(), token); - var res_val = exception_obj_id.Value?["result"]?["value"]; + Result exception_obj_id = await SendMonoCommand(sessionId, MonoCommands.GetExceptionObject(), token); + JToken res_val = exception_obj_id.Value?["result"]?["value"]; var exception_dotnet_obj_id = new DotnetObjectId("object", res_val?["exception_id"]?.Value()); data = JObject.FromObject(new { @@ -557,27 +556,27 @@ async Task OnPause(SessionId sessionId, JObject args, CancellationToken to } var frames = new List(); - var the_mono_frames = res.Value?["result"]?["value"]?["frames"]?.Values(); + IEnumerable the_mono_frames = res.Value?["result"]?["value"]?["frames"]?.Values(); - foreach (var mono_frame in the_mono_frames) + foreach (JObject mono_frame in the_mono_frames) { int frame_id = mono_frame["frame_id"].Value(); - var il_pos = mono_frame["il_pos"].Value(); - var method_token = mono_frame["method_token"].Value(); - var assembly_name = mono_frame["assembly_name"].Value(); + int il_pos = mono_frame["il_pos"].Value(); + uint method_token = mono_frame["method_token"].Value(); + string assembly_name = mono_frame["assembly_name"].Value(); // This can be different than `method.Name`, like in case of generic methods - var method_name = mono_frame["method_name"]?.Value(); + string method_name = mono_frame["method_name"]?.Value(); - var store = await LoadStore(sessionId, token); - var asm = store.GetAssemblyByName(assembly_name); + DebugStore store = await LoadStore(sessionId, token); + AssemblyInfo asm = store.GetAssemblyByName(assembly_name); if (asm == null) { Log("debug", $"Unable to find assembly: {assembly_name}"); continue; } - var method = asm.GetMethodByToken(method_token); + MethodInfo method = asm.GetMethodByToken(method_token); if (method == null && !asm.Image.HasSymbols) { @@ -598,7 +597,7 @@ async Task OnPause(SessionId sessionId, JObject args, CancellationToken to continue; } - var location = method?.GetLocationByIl(il_pos); + SourceLocation location = method?.GetLocationByIl(il_pos); // When hitting a breakpoint on the "IncrementCount" method in the standard // Blazor project template, one of the stack frames is inside mscorlib.dll @@ -653,7 +652,7 @@ async Task OnPause(SessionId sessionId, JObject args, CancellationToken to } } - var bp_list = new string[bp == null ? 0 : 1]; + string[] bp_list = new string[bp == null ? 0 : 1]; if (bp != null) bp_list[0] = bp.StackId; @@ -669,28 +668,28 @@ async Task OnPause(SessionId sessionId, JObject args, CancellationToken to return true; } - async Task LoadSymbolsOnDemand(AssemblyInfo asm, uint method_token, SessionId sessionId, CancellationToken token) + private async Task LoadSymbolsOnDemand(AssemblyInfo asm, uint method_token, SessionId sessionId, CancellationToken token) { - var context = GetContext(sessionId); + ExecutionContext context = GetContext(sessionId); if (asm.TriedToLoadSymbolsOnDemand) return null; asm.TriedToLoadSymbolsOnDemand = true; ImageDebugHeader header = asm.Image.GetDebugHeader(); - for (var i = 0; i < header.Entries.Length; i++) + for (int i = 0; i < header.Entries.Length; i++) { - var entry = header.Entries[i]; + ImageDebugHeaderEntry entry = header.Entries[i]; if (entry.Directory.Type != ImageDebugType.CodeView) { continue; } - var data = entry.Data; + byte[] data = entry.Data; if (data.Length < 24) return null; - var pdbSignature = (data[0] + int pdbSignature = (data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24)); @@ -698,34 +697,34 @@ async Task LoadSymbolsOnDemand(AssemblyInfo asm, uint method_token, if (pdbSignature != 0x53445352) // "SDSR" mono/metadata/debug-mono-ppdb.c#L101 return null; - var buffer = new byte[16]; + byte[] buffer = new byte[16]; Buffer.BlockCopy(data, 4, buffer, 0, 16); - var pdbAge = (data[20] + int pdbAge = (data[20] | (data[21] << 8) | (data[22] << 16) | (data[23] << 24)); var pdbGuid = new Guid(buffer); - var buffer2 = new byte[(data.Length - 24) - 1]; + byte[] buffer2 = new byte[(data.Length - 24) - 1]; Buffer.BlockCopy(data, 24, buffer2, 0, (data.Length - 24) - 1); - var pdbName = System.Text.Encoding.UTF8.GetString(buffer2, 0, buffer2.Length); + string pdbName = System.Text.Encoding.UTF8.GetString(buffer2, 0, buffer2.Length); pdbName = Path.GetFileName(pdbName); - foreach (var urlSymbolServer in urlSymbolServerList) + foreach (string urlSymbolServer in urlSymbolServerList) { - var downloadURL = $"{urlSymbolServer}/{pdbName}/{pdbGuid.ToString("N").ToUpper() + pdbAge}/{pdbName}"; + string downloadURL = $"{urlSymbolServer}/{pdbName}/{pdbGuid.ToString("N").ToUpper() + pdbAge}/{pdbName}"; try { - using HttpResponseMessage response = await client.GetAsync(downloadURL); - using Stream streamToReadFrom = await response.Content.ReadAsStreamAsync(); + using HttpResponseMessage response = await client.GetAsync(downloadURL, token); + using Stream streamToReadFrom = await response.Content.ReadAsStreamAsync(token); var portablePdbReaderProvider = new PdbReaderProvider(); - var symbolReader = portablePdbReaderProvider.GetSymbolReader(asm.Image, streamToReadFrom); + ISymbolReader symbolReader = portablePdbReaderProvider.GetSymbolReader(asm.Image, streamToReadFrom); asm.ClearDebugInfo(); //workaround while cecil PR #686 is not merged asm.Image.ReadSymbols(symbolReader); asm.Populate(); - foreach (var source in asm.Sources) + foreach (SourceFile source in asm.Sources) { var scriptSource = JObject.FromObject(source.ToScriptSource(context.Id, context.AuxData)); SendEvent(sessionId, "Debugger.scriptParsed", scriptSource, token); @@ -743,13 +742,13 @@ async Task LoadSymbolsOnDemand(AssemblyInfo asm, uint method_token, Log("info", "Unable to load symbols on demand assembly: {asm.Name}"); return null; } - - async Task OnDefaultContext(SessionId sessionId, ExecutionContext context, CancellationToken token) + + private async Task OnDefaultContext(SessionId sessionId, ExecutionContext context, CancellationToken token) { Log("verbose", "Default context created, clearing state and sending events"); - if (UpdateContext(sessionId, context, out var previousContext)) + if (UpdateContext(sessionId, context, out ExecutionContext previousContext)) { - foreach (var kvp in previousContext.BreakpointRequests) + foreach (KeyValuePair kvp in previousContext.BreakpointRequests) { context.BreakpointRequests[kvp.Key] = kvp.Value.Clone(); } @@ -759,9 +758,9 @@ async Task OnDefaultContext(SessionId sessionId, ExecutionContext context, Cance await RuntimeReady(sessionId, token); } - async Task OnResume(MessageId msg_id, CancellationToken token) + private async Task OnResume(MessageId msg_id, CancellationToken token) { - var ctx = GetContext(msg_id); + ExecutionContext ctx = GetContext(msg_id); if (ctx.CallStack != null) { // Stopped on managed code @@ -772,18 +771,18 @@ async Task OnResume(MessageId msg_id, CancellationToken token) GetContext(msg_id).ClearState(); } - async Task Step(MessageId msg_id, StepKind kind, CancellationToken token) + private async Task Step(MessageId msg_id, StepKind kind, CancellationToken token) { - var context = GetContext(msg_id); + ExecutionContext context = GetContext(msg_id); if (context.CallStack == null) return false; if (context.CallStack.Count <= 1 && kind == StepKind.Out) return false; - var res = await SendMonoCommand(msg_id, MonoCommands.StartSingleStepping(kind), token); + Result res = await SendMonoCommand(msg_id, MonoCommands.StartSingleStepping(kind), token); - var ret_code = res.Value?["result"]?["value"]?.Value(); + int? ret_code = res.Value?["result"]?["value"]?.Value(); if (ret_code.HasValue && ret_code.Value == 0) { @@ -800,7 +799,7 @@ async Task Step(MessageId msg_id, StepKind kind, CancellationToken token) return true; } - async Task OnJSEventRaised(SessionId sessionId, JObject eventArgs, CancellationToken token) + private async Task OnJSEventRaised(SessionId sessionId, JObject eventArgs, CancellationToken token) { string eventName = eventArgs?["eventName"]?.Value(); if (string.IsNullOrEmpty(eventName)) @@ -821,11 +820,11 @@ async Task OnJSEventRaised(SessionId sessionId, JObject eventArgs, Cancell } } - async Task OnEvaluateOnCallFrame(MessageId msg_id, int scope_id, string expression, CancellationToken token) + private async Task OnEvaluateOnCallFrame(MessageId msg_id, int scope_id, string expression, CancellationToken token) { try { - var context = GetContext(msg_id); + ExecutionContext context = GetContext(msg_id); if (context.CallStack == null) return false; @@ -866,25 +865,25 @@ internal async Task GetScopeProperties(MessageId msg_id, int scope_id, C { try { - var ctx = GetContext(msg_id); - var scope = ctx.CallStack.FirstOrDefault(s => s.Id == scope_id); + ExecutionContext ctx = GetContext(msg_id); + Frame scope = ctx.CallStack.FirstOrDefault(s => s.Id == scope_id); if (scope == null) return Result.Err(JObject.FromObject(new { message = $"Could not find scope with id #{scope_id}" })); - var var_ids = scope.Method.GetLiveVarsAt(scope.Location.CliLocation.Offset); - var res = await SendMonoCommand(msg_id, MonoCommands.GetScopeVariables(scope.Id, var_ids), token); + VarInfo[] var_ids = scope.Method.GetLiveVarsAt(scope.Location.CliLocation.Offset); + Result res = await SendMonoCommand(msg_id, MonoCommands.GetScopeVariables(scope.Id, var_ids), token); //if we fail we just buble that to the IDE (and let it panic over it) if (res.IsErr) return res; - var values = res.Value?["result"]?["value"]?.Values().ToArray(); + JObject[] values = res.Value?["result"]?["value"]?.Values().ToArray(); if (values == null || values.Length == 0) return Result.OkFromObject(new { result = Array.Empty() }); - var frameCache = ctx.GetCacheForScope(scope_id); - foreach (var value in values) + PerScopeCache frameCache = ctx.GetCacheForScope(scope_id); + foreach (JObject value in values) { frameCache.Locals[value["name"]?.Value()] = value; } @@ -898,15 +897,15 @@ internal async Task GetScopeProperties(MessageId msg_id, int scope_id, C } } - async Task SetMonoBreakpoint(SessionId sessionId, string reqId, SourceLocation location, CancellationToken token) + private async Task SetMonoBreakpoint(SessionId sessionId, string reqId, SourceLocation location, CancellationToken token) { var bp = new Breakpoint(reqId, location, BreakpointState.Pending); - var asm_name = bp.Location.CliLocation.Method.Assembly.Name; - var method_token = bp.Location.CliLocation.Method.Token; - var il_offset = bp.Location.CliLocation.Offset; + string asm_name = bp.Location.CliLocation.Method.Assembly.Name; + uint method_token = bp.Location.CliLocation.Method.Token; + int il_offset = bp.Location.CliLocation.Offset; - var res = await SendMonoCommand(sessionId, MonoCommands.SetBreakpoint(asm_name, method_token, il_offset), token); - var ret_code = res.Value?["result"]?["value"]?.Value(); + Result res = await SendMonoCommand(sessionId, MonoCommands.SetBreakpoint(asm_name, method_token, il_offset), token); + int? ret_code = res.Value?["result"]?["value"]?.Value(); if (ret_code.HasValue) { @@ -918,32 +917,32 @@ async Task SetMonoBreakpoint(SessionId sessionId, string reqId, Sour return bp; } - async Task LoadStore(SessionId sessionId, CancellationToken token) + private async Task LoadStore(SessionId sessionId, CancellationToken token) { - var context = GetContext(sessionId); + ExecutionContext context = GetContext(sessionId); if (Interlocked.CompareExchange(ref context.store, new DebugStore(logger), null) != null) return await context.Source.Task; try { - var loaded_files = context.LoadedFiles; + string[] loaded_files = context.LoadedFiles; if (loaded_files == null) { - var loaded = await SendMonoCommand(sessionId, MonoCommands.GetLoadedFiles(), token); + Result loaded = await SendMonoCommand(sessionId, MonoCommands.GetLoadedFiles(), token); loaded_files = loaded.Value?["result"]?["value"]?.ToObject(); } await - foreach (var source in context.store.Load(sessionId, loaded_files, token).WithCancellation(token)) + foreach (SourceFile source in context.store.Load(sessionId, loaded_files, token).WithCancellation(token)) { var scriptSource = JObject.FromObject(source.ToScriptSource(context.Id, context.AuxData)); Log("verbose", $"\tsending {source.Url} {context.Id} {sessionId.sessionId}"); SendEvent(sessionId, "Debugger.scriptParsed", scriptSource, token); - foreach (var req in context.BreakpointRequests.Values) + foreach (BreakpointRequest req in context.BreakpointRequests.Values) { if (req.TryResolve(source)) { @@ -962,37 +961,37 @@ async Task LoadStore(SessionId sessionId, CancellationToken token) return context.store; } - async Task RuntimeReady(SessionId sessionId, CancellationToken token) + private async Task RuntimeReady(SessionId sessionId, CancellationToken token) { - var context = GetContext(sessionId); + ExecutionContext context = GetContext(sessionId); if (Interlocked.CompareExchange(ref context.ready, new TaskCompletionSource(), null) != null) return await context.ready.Task; - var clear_result = await SendMonoCommand(sessionId, MonoCommands.ClearAllBreakpoints(), token); + Result clear_result = await SendMonoCommand(sessionId, MonoCommands.ClearAllBreakpoints(), token); if (clear_result.IsErr) { Log("verbose", $"Failed to clear breakpoints due to {clear_result}"); } - var store = await LoadStore(sessionId, token); + DebugStore store = await LoadStore(sessionId, token); context.ready.SetResult(store); SendEvent(sessionId, "Mono.runtimeReady", new JObject(), token); return store; } - async Task RemoveBreakpoint(MessageId msg_id, JObject args, CancellationToken token) + private async Task RemoveBreakpoint(MessageId msg_id, JObject args, CancellationToken token) { - var bpid = args?["breakpointId"]?.Value(); + string bpid = args?["breakpointId"]?.Value(); - var context = GetContext(msg_id); - if (!context.BreakpointRequests.TryGetValue(bpid, out var breakpointRequest)) + ExecutionContext context = GetContext(msg_id); + if (!context.BreakpointRequests.TryGetValue(bpid, out BreakpointRequest breakpointRequest)) return; - foreach (var bp in breakpointRequest.Locations) + foreach (Breakpoint bp in breakpointRequest.Locations) { - var res = await SendMonoCommand(msg_id, MonoCommands.RemoveBreakpoint(bp.RemoteId), token); - var ret_code = res.Value?["result"]?["value"]?.Value(); + Result res = await SendMonoCommand(msg_id, MonoCommands.RemoveBreakpoint(bp.RemoteId), token); + int? ret_code = res.Value?["result"]?["value"]?.Value(); if (ret_code.HasValue) { @@ -1003,9 +1002,9 @@ async Task RemoveBreakpoint(MessageId msg_id, JObject args, CancellationToken to context.BreakpointRequests.Remove(bpid); } - async Task SetBreakpoint(SessionId sessionId, DebugStore store, BreakpointRequest req, bool sendResolvedEvent, CancellationToken token) + private async Task SetBreakpoint(SessionId sessionId, DebugStore store, BreakpointRequest req, bool sendResolvedEvent, CancellationToken token) { - var context = GetContext(sessionId); + ExecutionContext context = GetContext(sessionId); if (req.Locations.Any()) { Log("debug", $"locations already loaded for {req.Id}"); @@ -1015,7 +1014,7 @@ async Task SetBreakpoint(SessionId sessionId, DebugStore store, BreakpointReques var comparer = new SourceLocation.LocationComparer(); // if column is specified the frontend wants the exact matches // and will clear the bp if it isn't close enoug - var locations = store.FindBreakpointLocations(req) + IEnumerable> locations = store.FindBreakpointLocations(req) .Distinct(comparer) .Where(l => l.Line == req.Line && (req.Column == 0 || l.Column == req.Column)) .OrderBy(l => l.Column) @@ -1025,10 +1024,10 @@ async Task SetBreakpoint(SessionId sessionId, DebugStore store, BreakpointReques var breakpoints = new List(); - foreach (var sourceId in locations) + foreach (IGrouping sourceId in locations) { - var loc = sourceId.First(); - var bp = await SetMonoBreakpoint(sessionId, req.Id, loc, token); + SourceLocation loc = sourceId.First(); + Breakpoint bp = await SetMonoBreakpoint(sessionId, req.Id, loc, token); // If we didn't successfully enable the breakpoint // don't add it to the list of locations for this id @@ -1051,9 +1050,9 @@ async Task SetBreakpoint(SessionId sessionId, DebugStore store, BreakpointReques return; } - async Task GetPossibleBreakpoints(MessageId msg, SourceLocation start, SourceLocation end, CancellationToken token) + private async Task GetPossibleBreakpoints(MessageId msg, SourceLocation start, SourceLocation end, CancellationToken token) { - var bps = (await RuntimeReady(msg, token)).FindPossibleBreakpoints(start, end); + List bps = (await RuntimeReady(msg, token)).FindPossibleBreakpoints(start, end); if (bps == null) return false; @@ -1064,24 +1063,24 @@ async Task GetPossibleBreakpoints(MessageId msg, SourceLocation start, Sou return true; } - void OnCompileDotnetScript(MessageId msg_id, CancellationToken token) + private void OnCompileDotnetScript(MessageId msg_id, CancellationToken token) { SendResponse(msg_id, Result.OkFromObject(new { }), token); } - async Task OnGetScriptSource(MessageId msg_id, string script_id, CancellationToken token) + private async Task OnGetScriptSource(MessageId msg_id, string script_id, CancellationToken token) { - if (!SourceId.TryParse(script_id, out var id)) + if (!SourceId.TryParse(script_id, out SourceId id)) return false; - var src_file = (await LoadStore(msg_id, token)).GetFileById(id); + SourceFile src_file = (await LoadStore(msg_id, token)).GetFileById(id); try { var uri = new Uri(src_file.Url); string source = $"// Unable to find document {src_file.SourceUri}"; - using (var data = await src_file.GetSourceAsync(checkHash: false, token: token)) + using (Stream data = await src_file.GetSourceAsync(checkHash: false, token: token)) { if (data.Length == 0) return false; @@ -1105,12 +1104,12 @@ async Task OnGetScriptSource(MessageId msg_id, string script_id, Cancellat return true; } - async Task DeleteWebDriver(SessionId sessionId, CancellationToken token) + private async Task DeleteWebDriver(SessionId sessionId, CancellationToken token) { // see https://github.com/mono/mono/issues/19549 for background if (hideWebDriver && sessions.Add(sessionId)) { - var res = await SendCommand(sessionId, + Result res = await SendCommand(sessionId, "Page.addScriptToEvaluateOnNewDocument", JObject.FromObject(new { source = "delete navigator.constructor.prototype.webdriver" }), token); @@ -1120,7 +1119,7 @@ async Task DeleteWebDriver(SessionId sessionId, CancellationToken token) } } - bool JObjectTryParse(string str, out JObject obj, bool log_exception = true) + private bool JObjectTryParse(string str, out JObject obj, bool log_exception = true) { obj = null; if (string.IsNullOrEmpty(str)) diff --git a/src/mono/wasm/debugger/DebuggerTestSuite/DebuggerTestSuite.csproj b/src/mono/wasm/debugger/DebuggerTestSuite/DebuggerTestSuite.csproj index 09b79eb67dc295..cded4a2b78a261 100644 --- a/src/mono/wasm/debugger/DebuggerTestSuite/DebuggerTestSuite.csproj +++ b/src/mono/wasm/debugger/DebuggerTestSuite/DebuggerTestSuite.csproj @@ -3,6 +3,7 @@ $(NetCoreAppCurrent) true + false diff --git a/src/mono/wasm/debugger/tests/debugger-test.csproj b/src/mono/wasm/debugger/tests/debugger-test.csproj index 045cf4c35fe7d8..6f44146218fa7c 100644 --- a/src/mono/wasm/debugger/tests/debugger-test.csproj +++ b/src/mono/wasm/debugger/tests/debugger-test.csproj @@ -11,6 +11,7 @@ Library 219 true + false portable diff --git a/src/tests/Common/Coreclr.TestWrapper/Coreclr.TestWrapper.csproj b/src/tests/Common/Coreclr.TestWrapper/Coreclr.TestWrapper.csproj index 0141e5aa4182ea..e20017721e31b6 100644 --- a/src/tests/Common/Coreclr.TestWrapper/Coreclr.TestWrapper.csproj +++ b/src/tests/Common/Coreclr.TestWrapper/Coreclr.TestWrapper.csproj @@ -5,6 +5,7 @@ $(RepoRoot)src\tests\Common\Coreclr.TestWrapper\obj\project.assets.json $(NetCoreAppCurrentTargetFrameworkMoniker) $(NetCoreAppCurrent) + false diff --git a/src/tests/Directory.Build.props b/src/tests/Directory.Build.props index a6e8657405ca9c..682a1f89888279 100644 --- a/src/tests/Directory.Build.props +++ b/src/tests/Directory.Build.props @@ -45,7 +45,8 @@ false false - 78,162,164,168,169,219,251,252,414,429,642,649,652,675,1691,1717,1718,3001,3002,3003,3005,3008 + 78,162,164,168,169,219,251,252,414,429,618,642,649,652,659,675,1691,1717,1718,3001,3002,3003,3005,3008,SYSLIB0004,SYSLIB0011,SYSLIB0012 + false false true Test diff --git a/src/tests/run.proj b/src/tests/run.proj index 5ade3b2aa1296f..774de96f8d17f8 100644 --- a/src/tests/run.proj +++ b/src/tests/run.proj @@ -100,6 +100,7 @@ $(_XunitEpilog) $(XUnitTestBinBase)\$(CategoryWithSlash) $(MicrosoftNETCoreAppVersion) + false diff --git a/tools-local/tasks/installer.tasks/installer.tasks.csproj b/tools-local/tasks/installer.tasks/installer.tasks.csproj index 368fe4c58d9f30..fc7b567d4b6477 100644 --- a/tools-local/tasks/installer.tasks/installer.tasks.csproj +++ b/tools-local/tasks/installer.tasks/installer.tasks.csproj @@ -4,6 +4,7 @@ $(TargetFrameworks);net461 false false + false diff --git a/tools-local/tasks/mobile.tasks/AndroidAppBuilder/AndroidAppBuilder.cs b/tools-local/tasks/mobile.tasks/AndroidAppBuilder/AndroidAppBuilder.cs index b4d0dc719abf11..12bb6f2a6d108b 100644 --- a/tools-local/tasks/mobile.tasks/AndroidAppBuilder/AndroidAppBuilder.cs +++ b/tools-local/tasks/mobile.tasks/AndroidAppBuilder/AndroidAppBuilder.cs @@ -31,20 +31,20 @@ public class AndroidAppBuilderTask : Task public string? OutputDir { get; set; } public string? AndroidSdk { get; set; } - + public string? AndroidNdk { get; set; } - + public string? MinApiLevel { get; set; } - + public string? BuildApiLevel { get; set; } - + public string? BuildToolsVersion { get; set; } public bool StripDebugSymbols { get; set; } [Output] public string ApkBundlePath { get; set; } = ""!; - + [Output] public string ApkPackageId { get; set; } = ""!; @@ -62,7 +62,7 @@ public override bool Execute() apkBuilder.BuildToolsVersion = BuildToolsVersion; apkBuilder.StripDebugSymbols = StripDebugSymbols; (ApkBundlePath, ApkPackageId) = apkBuilder.BuildApk(SourceDir, Abi, MainLibraryFileName, MonoRuntimeHeaders); - + return true; } } diff --git a/tools-local/tasks/mobile.tasks/AndroidAppBuilder/AndroidAppBuilder.csproj b/tools-local/tasks/mobile.tasks/AndroidAppBuilder/AndroidAppBuilder.csproj index 179ca9aa2af4ab..a170c74773ed54 100644 --- a/tools-local/tasks/mobile.tasks/AndroidAppBuilder/AndroidAppBuilder.csproj +++ b/tools-local/tasks/mobile.tasks/AndroidAppBuilder/AndroidAppBuilder.csproj @@ -5,6 +5,7 @@ true false enable + $(NoWarn),CA1050 diff --git a/tools-local/tasks/mobile.tasks/AndroidAppBuilder/ApkBuilder.cs b/tools-local/tasks/mobile.tasks/AndroidAppBuilder/ApkBuilder.cs index 92812402ce296e..c9b586399a09c1 100644 --- a/tools-local/tasks/mobile.tasks/AndroidAppBuilder/ApkBuilder.cs +++ b/tools-local/tasks/mobile.tasks/AndroidAppBuilder/ApkBuilder.cs @@ -1,3 +1,6 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + using System; using System.Collections.Generic; using System.IO; @@ -65,8 +68,8 @@ public class ApkBuilder // make sure BuildApiLevel >= MinApiLevel // only if these api levels are not "preview" (not integers) - if (int.TryParse(BuildApiLevel, out int intApi) && - int.TryParse(MinApiLevel, out int intMinApi) && + if (int.TryParse(BuildApiLevel, out int intApi) && + int.TryParse(MinApiLevel, out int intMinApi) && intApi < intMinApi) { throw new ArgumentException($"BuildApiLevel={BuildApiLevel} <= MinApiLevel={MinApiLevel}. " + @@ -82,7 +85,7 @@ public class ApkBuilder Directory.CreateDirectory(Path.Combine(OutputDir, "obj")); Directory.CreateDirectory(Path.Combine(OutputDir, "assets-tozip")); Directory.CreateDirectory(Path.Combine(OutputDir, "assets")); - + var extensionsToIgnore = new List { ".so", ".a", ".gz" }; if (StripDebugSymbols) { @@ -125,7 +128,7 @@ public class ApkBuilder Utils.RunProcess(zip, workingDir: Path.Combine(OutputDir, "assets-tozip"), args: "-q -r ../assets/assets.zip ."); Directory.Delete(Path.Combine(OutputDir, "assets-tozip"), true); - + if (!File.Exists(androidJar)) throw new ArgumentException($"API level={BuildApiLevel} is not downloaded in Android SDK"); @@ -144,12 +147,12 @@ public class ApkBuilder .Replace("%EntryPointLibName%", Path.GetFileName(entryPointLib) .Replace("%RID%", GetRid(abi))); File.WriteAllText(Path.Combine(OutputDir, "monodroid.c"), monodroidSrc); - - string cmakeGenArgs = $"-DCMAKE_TOOLCHAIN_FILE={androidToolchain} -DANDROID_ABI=\"{abi}\" -DANDROID_STL=none " + + + string cmakeGenArgs = $"-DCMAKE_TOOLCHAIN_FILE={androidToolchain} -DANDROID_ABI=\"{abi}\" -DANDROID_STL=none " + $"-DANDROID_NATIVE_API_LEVEL={MinApiLevel} -B monodroid"; string cmakeBuildArgs = "--build monodroid"; - + if (StripDebugSymbols) { // Use "-s" to strip debug symbols, it complains it's unused but it works @@ -172,11 +175,11 @@ public class ApkBuilder string packageId = $"net.dot.{ProjectName}"; - File.WriteAllText(Path.Combine(javaSrcFolder, "MainActivity.java"), + File.WriteAllText(Path.Combine(javaSrcFolder, "MainActivity.java"), Utils.GetEmbeddedResource("MainActivity.java")); - File.WriteAllText(Path.Combine(javaSrcFolder, "MonoRunner.java"), + File.WriteAllText(Path.Combine(javaSrcFolder, "MonoRunner.java"), Utils.GetEmbeddedResource("MonoRunner.java")); - File.WriteAllText(Path.Combine(OutputDir, "AndroidManifest.xml"), + File.WriteAllText(Path.Combine(OutputDir, "AndroidManifest.xml"), Utils.GetEmbeddedResource("AndroidManifest.xml") .Replace("%PackageName%", packageId) .Replace("%MinSdkLevel%", MinApiLevel)); @@ -190,7 +193,7 @@ public class ApkBuilder string apkFile = Path.Combine(OutputDir, "bin", $"{ProjectName}.unaligned.apk"); Utils.RunProcess(aapt, $"package -f -m -F {apkFile} -A assets -M AndroidManifest.xml -I {androidJar}", workingDir: OutputDir); - + var dynamicLibs = new List(); dynamicLibs.Add(Path.Combine(OutputDir, "monodroid", "libmonodroid.so")); dynamicLibs.AddRange(Directory.GetFiles(sourceDir, "*.so")); @@ -222,7 +225,7 @@ public class ApkBuilder File.Delete(apkFile); // 5. Generate key - + string signingKey = Path.Combine(OutputDir, "debug.keystore"); if (!File.Exists(signingKey)) { @@ -233,7 +236,7 @@ public class ApkBuilder // 6. Sign APK - Utils.RunProcess(apksigner, $"sign --min-sdk-version {MinApiLevel} --ks debug.keystore " + + Utils.RunProcess(apksigner, $"sign --min-sdk-version {MinApiLevel} --ks debug.keystore " + $"--ks-pass pass:android --key-pass pass:android {alignedApk}", workingDir: OutputDir); Utils.LogInfo($"\nAPK size: {(new FileInfo(alignedApk).Length / 1000_000.0):0.#} Mb.\n"); @@ -241,14 +244,14 @@ public class ApkBuilder return (alignedApk, packageId); } - private static string GetRid(string abi) => abi switch + private static string GetRid(string abi) => abi switch { "arm64-v8a" => "android-arm64", "armeabi-v7a" => "android-arm", "x86_64" => "android-x64", _ => "android-" + abi }; - + /// /// Scan android SDK for build tools (ignore preview versions) /// @@ -266,7 +269,7 @@ private static string GetLatestBuildTools(string androidSdkDir) return buildTools; } - + /// /// Scan android SDK for api levels (ignore preview versions) /// diff --git a/tools-local/tasks/mobile.tasks/AndroidAppBuilder/Utils.cs b/tools-local/tasks/mobile.tasks/AndroidAppBuilder/Utils.cs index 159b457f29dce0..93413b11663301 100644 --- a/tools-local/tasks/mobile.tasks/AndroidAppBuilder/Utils.cs +++ b/tools-local/tasks/mobile.tasks/AndroidAppBuilder/Utils.cs @@ -77,7 +77,7 @@ public static string RunProcess( if (!ignoreErrors && process.ExitCode != 0) throw new Exception("Error: " + errorBuilder); - return outputBuilder.ToString().Trim('\r','\n'); + return outputBuilder.ToString().Trim('\r', '\n'); } public static void DirectoryCopy(string sourceDir, string destDir, Func predicate) diff --git a/tools-local/tasks/mobile.tasks/AotCompilerTask/MonoAOTCompiler.cs b/tools-local/tasks/mobile.tasks/AotCompilerTask/MonoAOTCompiler.cs index d3c5250f35420e..debd10c80f11ec 100644 --- a/tools-local/tasks/mobile.tasks/AotCompilerTask/MonoAOTCompiler.cs +++ b/tools-local/tasks/mobile.tasks/AotCompilerTask/MonoAOTCompiler.cs @@ -20,7 +20,7 @@ public class MonoAOTCompiler : Microsoft.Build.Utilities.Task /// /// Assemblies to be AOTd. They need to be in a self-contained directory. - /// + /// /// Metadata: /// - AotArguments: semicolon-separated list of options that will be passed to --aot= /// - ProcessArguments: semicolon-separated list of options that will be passed to the AOT compiler itself @@ -75,9 +75,9 @@ public class MonoAOTCompiler : Microsoft.Build.Utilities.Task /// public string? MsymPath { get; set; } - ConcurrentBag compiledAssemblies = new ConcurrentBag(); - MonoAotMode parsedAotMode; - MonoAotOutputType parsedOutputType; + private ConcurrentBag compiledAssemblies = new ConcurrentBag(); + private MonoAotMode parsedAotMode; + private MonoAotOutputType parsedOutputType; public override bool Execute() { @@ -224,18 +224,18 @@ private void PrecompileLibrary(ITaskItem assemblyItem) // we need to quote the entire --aot arguments here to make sure it is parsed // on Windows as one argument. Otherwise it will be split up into multiple // values, which wont work. - processArgs.Add($"\"--aot={String.Join(",", aotArgs)}\""); + processArgs.Add($"\"--aot={string.Join(",", aotArgs)}\""); processArgs.Add(assembly); var envVariables = new Dictionary { {"MONO_PATH", directory}, - {"MONO_ENV_OPTIONS", String.Empty} // we do not want options to be provided out of band to the cross compilers + {"MONO_ENV_OPTIONS", string.Empty} // we do not want options to be provided out of band to the cross compilers }; // run the AOT compiler - Utils.RunProcess(CompilerBinaryPath, String.Join(" ", processArgs), envVariables, directory); + Utils.RunProcess(CompilerBinaryPath, string.Join(" ", processArgs), envVariables, directory); compiledAssemblies.Add(aotAssembly); } @@ -252,4 +252,4 @@ public enum MonoAotOutputType { Normal, AsmOnly, -} \ No newline at end of file +} diff --git a/tools-local/tasks/mobile.tasks/AotCompilerTask/MonoAOTCompiler.csproj b/tools-local/tasks/mobile.tasks/AotCompilerTask/MonoAOTCompiler.csproj index b487236cc36277..ab121a31019716 100644 --- a/tools-local/tasks/mobile.tasks/AotCompilerTask/MonoAOTCompiler.csproj +++ b/tools-local/tasks/mobile.tasks/AotCompilerTask/MonoAOTCompiler.csproj @@ -5,6 +5,7 @@ true false enable + $(NoWarn),CA1050 diff --git a/tools-local/tasks/mobile.tasks/AotCompilerTask/Utils.cs b/tools-local/tasks/mobile.tasks/AotCompilerTask/Utils.cs index 49d77dc34b4e96..a7c23d4132ac43 100644 --- a/tools-local/tasks/mobile.tasks/AotCompilerTask/Utils.cs +++ b/tools-local/tasks/mobile.tasks/AotCompilerTask/Utils.cs @@ -64,7 +64,7 @@ public static string RunProcess( throw new Exception("Error: " + errorBuilder); } - return outputBuilder.ToString().Trim('\r','\n'); + return outputBuilder.ToString().Trim('\r', '\n'); } public static TaskLoggingHelper? Logger { get; set; } diff --git a/tools-local/tasks/mobile.tasks/AppleAppBuilder/AppleAppBuilder.cs b/tools-local/tasks/mobile.tasks/AppleAppBuilder/AppleAppBuilder.cs index fbe28c2e2438f5..744b2960e9d47e 100644 --- a/tools-local/tasks/mobile.tasks/AppleAppBuilder/AppleAppBuilder.cs +++ b/tools-local/tasks/mobile.tasks/AppleAppBuilder/AppleAppBuilder.cs @@ -122,7 +122,7 @@ public override bool Execute() throw new ArgumentException($"ProjectName='{ProjectName}' should not contain spaces"); } - string[] excludes = new string[0]; + string[] excludes = Array.Empty(); if (ExcludeFromAppDir != null) { excludes = ExcludeFromAppDir @@ -143,7 +143,7 @@ public override bool Execute() { // use AOT files if available var obj = file.GetMetadata("AssemblerFile"); - if (!String.IsNullOrEmpty(obj)) + if (!string.IsNullOrEmpty(obj)) { assemblerFiles.Add(obj); } diff --git a/tools-local/tasks/mobile.tasks/AppleAppBuilder/AppleAppBuilder.csproj b/tools-local/tasks/mobile.tasks/AppleAppBuilder/AppleAppBuilder.csproj index 255150988f9c7d..09e2a5ffde4534 100644 --- a/tools-local/tasks/mobile.tasks/AppleAppBuilder/AppleAppBuilder.csproj +++ b/tools-local/tasks/mobile.tasks/AppleAppBuilder/AppleAppBuilder.csproj @@ -5,6 +5,7 @@ true false enable + $(NoWarn),CA1050 diff --git a/tools-local/tasks/mobile.tasks/AppleAppBuilder/Utils.cs b/tools-local/tasks/mobile.tasks/AppleAppBuilder/Utils.cs index e9773a38596553..83304bd393c1e3 100644 --- a/tools-local/tasks/mobile.tasks/AppleAppBuilder/Utils.cs +++ b/tools-local/tasks/mobile.tasks/AppleAppBuilder/Utils.cs @@ -72,7 +72,7 @@ public static string RunProcess( throw new Exception("Error: " + errorBuilder); } - return outputBuilder.ToString().Trim('\r','\n'); + return outputBuilder.ToString().Trim('\r', '\n'); } public static TaskLoggingHelper? Logger { get; set; } diff --git a/tools-local/tasks/mobile.tasks/AppleAppBuilder/Xcode.cs b/tools-local/tasks/mobile.tasks/AppleAppBuilder/Xcode.cs index 990b5d988acf2d..1d67b35f34996f 100644 --- a/tools-local/tasks/mobile.tasks/AppleAppBuilder/Xcode.cs +++ b/tools-local/tasks/mobile.tasks/AppleAppBuilder/Xcode.cs @@ -85,7 +85,7 @@ public static string GenerateXCode( cmakeLists = cmakeLists.Replace("%NativeLibrariesToLink%", toLink); cmakeLists = cmakeLists.Replace("%AotSources%", aotSources); - cmakeLists = cmakeLists.Replace("%Defines%", + cmakeLists = cmakeLists.Replace("%Defines%", useAotForSimulator ? "add_definitions(-DUSE_AOT_FOR_SIMULATOR=1)" : ""); string plist = Utils.GetEmbeddedResource("Info.plist.template") diff --git a/tools-local/tasks/mobile.tasks/WasmAppBuilder/PInvokeTableGenerator.cs b/tools-local/tasks/mobile.tasks/WasmAppBuilder/PInvokeTableGenerator.cs index e37f83ec12f192..4e4b19edc3bc96 100644 --- a/tools-local/tasks/mobile.tasks/WasmAppBuilder/PInvokeTableGenerator.cs +++ b/tools-local/tasks/mobile.tasks/WasmAppBuilder/PInvokeTableGenerator.cs @@ -161,15 +161,15 @@ private string GenPInvokeDecl(PInvoke pinvoke) var pars = method.GetParameters(); foreach (var p in pars) { if (pindex > 0) - sb.Append(","); + sb.Append(','); sb.Append(MapType(pars[pindex].ParameterType)); - pindex ++; + pindex++; } sb.Append(");"); return sb.ToString(); } - void EmitNativeToInterp(StreamWriter w, List callbacks) + private void EmitNativeToInterp(StreamWriter w, List callbacks) { // Generate native->interp entry functions // These are called by native code, so they need to obtain @@ -209,16 +209,16 @@ void EmitNativeToInterp(StreamWriter w, List callbacks) int pindex = 0; if (method.ReturnType.Name != "Void") { sb.Append("int"); - pindex ++; + pindex++; } foreach (var p in method.GetParameters()) { if (pindex > 0) - sb.Append(","); + sb.Append(','); sb.Append("int"); - pindex ++; + pindex++; } if (pindex > 0) - sb.Append(","); + sb.Append(','); // Extra arg sb.Append("int"); sb.Append(");\n"); @@ -241,10 +241,10 @@ void EmitNativeToInterp(StreamWriter w, List callbacks) pindex = 0; foreach (var p in method.GetParameters()) { if (pindex > 0) - sb.Append(","); + sb.Append(','); sb.Append(MapType(method.GetParameters()[pindex].ParameterType)); sb.Append(" arg" + pindex); - pindex ++; + pindex++; } sb.Append(") { \n"); if (!is_void) @@ -253,15 +253,15 @@ void EmitNativeToInterp(StreamWriter w, List callbacks) pindex = 0; if (!is_void) { sb.Append("&res"); - pindex ++; + pindex++; } int aindex = 0; foreach (var p in method.GetParameters()) { if (pindex > 0) sb.Append(", "); sb.Append("&arg" + aindex); - pindex ++; - aindex ++; + pindex++; + aindex++; } if (pindex > 0) sb.Append(", "); @@ -269,9 +269,9 @@ void EmitNativeToInterp(StreamWriter w, List callbacks) sb.Append(");\n"); if (!is_void) sb.Append("return res;\n"); - sb.Append("}"); + sb.Append('}'); w.WriteLine(sb); - cb_index ++; + cb_index++; } // Array of function pointers @@ -295,7 +295,7 @@ void EmitNativeToInterp(StreamWriter w, List callbacks) w.WriteLine ("};"); } - static bool IsBlittable (Type type) + private static bool IsBlittable (Type type) { if (type.IsPrimitive || type.IsByRef || type.IsPointer) return true; @@ -303,14 +303,14 @@ static bool IsBlittable (Type type) return false; } - static void Error (string msg) + private static void Error (string msg) { // FIXME: throw new Exception(msg); } } -class PInvoke +internal class PInvoke { public PInvoke(string entryPoint, string module, MethodInfo method) { @@ -324,7 +324,7 @@ public PInvoke(string entryPoint, string module, MethodInfo method) public MethodInfo Method; } -class PInvokeCallback +internal class PInvokeCallback { public PInvokeCallback(MethodInfo method) { diff --git a/tools-local/tasks/mobile.tasks/WasmAppBuilder/WasmAppBuilder.cs b/tools-local/tasks/mobile.tasks/WasmAppBuilder/WasmAppBuilder.cs index 8fd2470c784898..cd1ea7021d386b 100644 --- a/tools-local/tasks/mobile.tasks/WasmAppBuilder/WasmAppBuilder.cs +++ b/tools-local/tasks/mobile.tasks/WasmAppBuilder/WasmAppBuilder.cs @@ -30,7 +30,7 @@ public class WasmAppBuilder : Task // If true, continue when a referenced assembly cannot be found. // If false, throw an exception. - public bool SkipMissingAssemblies { get; set; } + public bool SkipMissingAssemblies { get; set; } // full list of ICU data files we produce can be found here: // https://github.com/dotnet/icu/tree/maint/maint-67/icu-filters @@ -45,8 +45,8 @@ public class WasmAppBuilder : Task public ITaskItem[]? RemoteSources { get; set; } public bool InvariantGlobalization { get; set; } - SortedDictionary? _assemblies; - Resolver? _resolver; + private SortedDictionary? _assemblies; + private Resolver? _resolver; private class WasmAppConfig { @@ -130,18 +130,18 @@ public override bool Execute () { foreach (var item in ExtraAssemblies) { - try - { - var refAssembly = mlc.LoadFromAssemblyPath(item.ItemSpec); - Add(mlc, refAssembly); - } - catch (System.IO.FileLoadException) - { - if (!SkipMissingAssemblies) - { - throw; - } - } + try + { + var refAssembly = mlc.LoadFromAssemblyPath(item.ItemSpec); + Add(mlc, refAssembly); + } + catch (System.IO.FileLoadException) + { + if (!SkipMissingAssemblies) + { + throw; + } + } } } @@ -228,7 +228,7 @@ public override bool Execute () if (!InvariantGlobalization) config.Assets.Add(new IcuData(IcuDataFileName!) { LoadRemote = RemoteSources?.Length > 0 }); - + config.Assets.Add(new VfsEntry ("dotnet.timezones.blat") { VirtualPath = "/usr/share/zoneinfo/"}); if (RemoteSources?.Length > 0) { @@ -270,9 +270,9 @@ private void Add(MetadataLoadContext mlc, Assembly assembly) } } -class Resolver : MetadataAssemblyResolver +internal class Resolver : MetadataAssemblyResolver { - List _searchPaths; + private List _searchPaths; public Resolver(List searchPaths) { diff --git a/tools-local/tasks/mobile.tasks/WasmAppBuilder/WasmAppBuilder.csproj b/tools-local/tasks/mobile.tasks/WasmAppBuilder/WasmAppBuilder.csproj index ab82b35f708073..1c9664874e2df4 100644 --- a/tools-local/tasks/mobile.tasks/WasmAppBuilder/WasmAppBuilder.csproj +++ b/tools-local/tasks/mobile.tasks/WasmAppBuilder/WasmAppBuilder.csproj @@ -4,6 +4,7 @@ Library false enable + $(NoWarn),CA1050 diff --git a/tools-local/tasks/mobile.tasks/WasmBuildTasks/CompileTimeZoneData.cs b/tools-local/tasks/mobile.tasks/WasmBuildTasks/CompileTimeZoneData.cs index a52d8e9c441bef..f7ebb449d6921c 100644 --- a/tools-local/tasks/mobile.tasks/WasmBuildTasks/CompileTimeZoneData.cs +++ b/tools-local/tasks/mobile.tasks/WasmBuildTasks/CompileTimeZoneData.cs @@ -1,3 +1,6 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + using System; using System.Collections.Generic; using System.IO; @@ -25,13 +28,13 @@ public class CompileTimeZoneData : Task private const string ZoneTabFileName = "zone1970.tab"; - private void CompileTimeZoneDataSource() + private void CompileTimeZoneDataSource() { - using (Process process = new Process()) + using (Process process = new Process()) { process.StartInfo.UseShellExecute = false; process.StartInfo.FileName = "zic"; - foreach (var f in TimeZones!) + foreach (var f in TimeZones!) { process.StartInfo.Arguments = $"-d \"{OutputDirectory}\" \"{Path.Combine(InputDirectory!, f)}\""; process.Start(); @@ -40,17 +43,17 @@ private void CompileTimeZoneDataSource() } } - private void FilterTimeZoneData() + private void FilterTimeZoneData() { - // Remove unnecessary timezone files in the root dir - // for ex: `CST6CDT`, `MST`, etc. - foreach (var entry in new DirectoryInfo (OutputDirectory!).EnumerateFiles()) + // Remove unnecessary timezone files in the root dir + // for ex: `CST6CDT`, `MST`, etc. + foreach (var entry in new DirectoryInfo (OutputDirectory!).EnumerateFiles()) { File.Delete(entry.FullName); } } - private void FilterZoneTab(string[] filters, string ZoneTabFile) + private void FilterZoneTab(string[] filters, string ZoneTabFile) { var path = Path.Combine(OutputDirectory!, "zone.tab"); using (StreamReader sr = new StreamReader(ZoneTabFile)) @@ -58,7 +61,7 @@ private void FilterZoneTab(string[] filters, string ZoneTabFile) { string? line; while ((line = sr.ReadLine()) != null) { - if (filters.Any(x => Regex.IsMatch(line, $@"\b{x}\b"))) + if (filters.Any(x => Regex.IsMatch(line, $@"\b{x}\b"))) { sw.WriteLine(line); } @@ -66,29 +69,29 @@ private void FilterZoneTab(string[] filters, string ZoneTabFile) } } - public override bool Execute() + public override bool Execute() { string ZoneTabFile = Path.Combine(InputDirectory!, ZoneTabFileName); if (!Directory.Exists(OutputDirectory)) Directory.CreateDirectory(OutputDirectory!); - if (!File.Exists(ZoneTabFile)) + if (!File.Exists(ZoneTabFile)) { - Log.LogError($"Could not find required file {ZoneTabFile}"); + Log.LogError($"Could not find required file {ZoneTabFile}"); return false; } CompileTimeZoneDataSource(); - - string[] filtered = new string[] { "America/Los_Angeles", "Australia/Sydney", "Europe/London", "Pacific/Tongatapu", + + string[] filtered = new string[] { "America/Los_Angeles", "Australia/Sydney", "Europe/London", "Pacific/Tongatapu", "America/Sao_Paulo", "Australia/Perth", "Africa/Nairobi", "Europe/Berlin", "Europe/Moscow", "Africa/Tripoli", "America/Argentina/Catamarca", "Europe/Lisbon", "America/St_Johns"}; - + FilterTimeZoneData(); FilterZoneTab(filtered, ZoneTabFile); return !Log.HasLoggedErrors; } -} \ No newline at end of file +} diff --git a/tools-local/tasks/mobile.tasks/WasmBuildTasks/GenerateWasmBundle.cs b/tools-local/tasks/mobile.tasks/WasmBuildTasks/GenerateWasmBundle.cs index 469f692cc171a8..e504975b857c95 100644 --- a/tools-local/tasks/mobile.tasks/WasmBuildTasks/GenerateWasmBundle.cs +++ b/tools-local/tasks/mobile.tasks/WasmBuildTasks/GenerateWasmBundle.cs @@ -1,3 +1,6 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + using System; using System.Buffers.Binary; using System.Collections.Generic; @@ -18,16 +21,16 @@ public class GenerateWasmBundle : Task public string? InputDirectory { get; set; } [Required] - public string? OutputFileName { get; set; } + public string? OutputFileName { get; set; } - private (byte[] json_bytes, MemoryStream stream) EnumerateData() + private (byte[] json_bytes, MemoryStream stream) EnumerateData() { var indices = new List(); var stream = new MemoryStream(); - + var directoryInfo = new DirectoryInfo(InputDirectory!); - - foreach (var entry in directoryInfo.EnumerateFiles("*", SearchOption.AllDirectories)) + + foreach (var entry in directoryInfo.EnumerateFiles("*", SearchOption.AllDirectories)) { var relativePath = Path.GetRelativePath(InputDirectory!, entry.FullName); indices.Add(new object[] { relativePath, entry.Length }); @@ -35,23 +38,23 @@ public class GenerateWasmBundle : Task using (var readStream = entry.OpenRead()) readStream.CopyTo(stream); } - + stream.Position = 0; var jsonBytes = JsonSerializer.SerializeToUtf8Bytes(indices); - + return (jsonBytes, stream); } public override bool Execute() { - if (!Directory.Exists(InputDirectory)) + if (!Directory.Exists(InputDirectory)) { Log.LogError($"Input directory '{InputDirectory}' does not exist"); return false; } (byte[] json_bytes, MemoryStream stream) data = EnumerateData(); - + using (var file = File.Open(OutputFileName!, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) { var lengthBytes = new byte[4]; @@ -60,11 +63,10 @@ public override bool Execute() file.Write(magicBytes); file.Write(lengthBytes); file.Write(data.json_bytes); - + data.stream.CopyTo(file); } - + return true; } } - diff --git a/tools-local/tasks/mobile.tasks/WasmBuildTasks/WasmBuildTasks.csproj b/tools-local/tasks/mobile.tasks/WasmBuildTasks/WasmBuildTasks.csproj index fd2ba129eaf4ed..1f1496af371959 100644 --- a/tools-local/tasks/mobile.tasks/WasmBuildTasks/WasmBuildTasks.csproj +++ b/tools-local/tasks/mobile.tasks/WasmBuildTasks/WasmBuildTasks.csproj @@ -3,6 +3,7 @@ $(NetCoreAppCurrent) Library enable + $(NoWarn),CA1050