diff options
Diffstat (limited to 'src/mscorlib/src/System/Text')
35 files changed, 1258 insertions, 1263 deletions
diff --git a/src/mscorlib/src/System/Text/ASCIIEncoding.cs b/src/mscorlib/src/System/Text/ASCIIEncoding.cs index bf1a62df55..fc7589f2d8 100644 --- a/src/mscorlib/src/System/Text/ASCIIEncoding.cs +++ b/src/mscorlib/src/System/Text/ASCIIEncoding.cs @@ -7,6 +7,7 @@ namespace System.Text using System; using System.Runtime.Serialization; using System.Security.Permissions; + using System.Diagnostics; using System.Diagnostics.Contracts; // ASCIIEncoding @@ -70,7 +71,6 @@ namespace System.Text return EncodingForwarder.GetByteCount(this, chars); } - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public override unsafe int GetByteCount(char* chars, int count) @@ -99,7 +99,6 @@ namespace System.Text return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex); } - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) @@ -115,7 +114,6 @@ namespace System.Text return EncodingForwarder.GetCharCount(this, bytes, index, count); } - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public override unsafe int GetCharCount(byte* bytes, int count) @@ -129,7 +127,6 @@ namespace System.Text return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex); } - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) @@ -150,15 +147,14 @@ namespace System.Text // GetByteCount // Note: We start by assuming that the output will be the same as count. Having // an encoder or fallback may change that assumption - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetByteCount(char* chars, int charCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(charCount >= 0, "[ASCIIEncoding.GetByteCount]count is negative"); - Contract.Assert(chars != null, "[ASCIIEncoding.GetByteCount]chars is null"); + Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetByteCount]count is negative"); + Debug.Assert(chars != null, "[ASCIIEncoding.GetByteCount]chars is null"); // Assert because we shouldn't be able to have a null encoder. - Contract.Assert(encoderFallback != null, "[ASCIIEncoding.GetByteCount]Attempting to use null fallback encoder"); + Debug.Assert(encoderFallback != null, "[ASCIIEncoding.GetByteCount]Attempting to use null fallback encoder"); char charLeftOver = (char)0; EncoderReplacementFallback fallback = null; @@ -172,7 +168,7 @@ namespace System.Text if (encoder != null) { charLeftOver = encoder.charLeftOver; - Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), + Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate"); fallback = encoder.Fallback as EncoderReplacementFallback; @@ -191,7 +187,7 @@ namespace System.Text } // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert - Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || + Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetByteCount]Expected empty fallback buffer"); // if (encoder.InternalHasFallbackBuffer && encoder.FallbackBuffer.Remaining > 0) @@ -228,8 +224,8 @@ namespace System.Text // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { - Contract.Assert(Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate"); - Contract.Assert(encoder != null, "[ASCIIEncoding.GetByteCount]Expected encoder"); + Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate"); + Debug.Assert(encoder != null, "[ASCIIEncoding.GetByteCount]Expected encoder"); // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback @@ -279,24 +275,23 @@ namespace System.Text byteCount++; } - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[ASCIIEncoding.GetByteCount]Expected Empty fallback buffer"); return byteCount; } - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(bytes != null, "[ASCIIEncoding.GetBytes]bytes is null"); - Contract.Assert(byteCount >= 0, "[ASCIIEncoding.GetBytes]byteCount is negative"); - Contract.Assert(chars != null, "[ASCIIEncoding.GetBytes]chars is null"); - Contract.Assert(charCount >= 0, "[ASCIIEncoding.GetBytes]charCount is negative"); + Debug.Assert(bytes != null, "[ASCIIEncoding.GetBytes]bytes is null"); + Debug.Assert(byteCount >= 0, "[ASCIIEncoding.GetBytes]byteCount is negative"); + Debug.Assert(chars != null, "[ASCIIEncoding.GetBytes]chars is null"); + Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetBytes]charCount is negative"); // Assert because we shouldn't be able to have a null encoder. - Contract.Assert(encoderFallback != null, "[ASCIIEncoding.GetBytes]Attempting to use null encoder fallback"); + Debug.Assert(encoderFallback != null, "[ASCIIEncoding.GetBytes]Attempting to use null encoder fallback"); // Get any left over characters char charLeftOver = (char)0; @@ -328,11 +323,11 @@ namespace System.Text fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true); } - Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), + Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetBytes]leftover character should be high surrogate"); // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert - Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || + Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetBytes]Expected empty fallback buffer"); // if (encoder.m_throwOnOverflow && encoder.InternalHasFallbackBuffer && @@ -411,7 +406,7 @@ namespace System.Text if (charLeftOver > 0) { // Initialize the buffer - Contract.Assert(encoder != null, + Debug.Assert(encoder != null, "[ASCIIEncoding.GetBytes]Expected non null encoder if we have surrogate left over"); fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(chars, charEnd, encoder, true); @@ -465,7 +460,7 @@ namespace System.Text // didn't use this char, we'll throw or use buffer if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false) { - Contract.Assert(chars > charStart || bytes == byteStart, + Debug.Assert(chars > charStart || bytes == byteStart, "[ASCIIEncoding.GetBytes]Expected chars to have advanced already."); chars--; // don't use last char } @@ -494,7 +489,7 @@ namespace System.Text encoder.m_charsUsed = (int)(chars - charStart); } - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 || + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 || (encoder != null && !encoder.m_throwOnOverflow ), "[ASCIIEncoding.GetBytes]Expected Empty fallback buffer at end"); @@ -502,12 +497,11 @@ namespace System.Text } // This is internal and called by something else, - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder) { // Just assert, we're called internally so these should be safe, checked already - Contract.Assert(bytes != null, "[ASCIIEncoding.GetCharCount]bytes is null"); - Contract.Assert(count >= 0, "[ASCIIEncoding.GetCharCount]byteCount is negative"); + Debug.Assert(bytes != null, "[ASCIIEncoding.GetCharCount]bytes is null"); + Debug.Assert(count >= 0, "[ASCIIEncoding.GetCharCount]byteCount is negative"); // ASCII doesn't do best fit, so don't have to check for it, find out which decoder fallback we're using DecoderReplacementFallback fallback = null; @@ -517,7 +511,7 @@ namespace System.Text else { fallback = decoder.Fallback as DecoderReplacementFallback; - Contract.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || + Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetCharCount]Expected empty fallback buffer"); } @@ -568,22 +562,21 @@ namespace System.Text } // Fallback buffer must be empty - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[ASCIIEncoding.GetCharCount]Expected Empty fallback buffer"); // Converted sequence is same length as input return charCount; } - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS decoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(bytes != null, "[ASCIIEncoding.GetChars]bytes is null"); - Contract.Assert(byteCount >= 0, "[ASCIIEncoding.GetChars]byteCount is negative"); - Contract.Assert(chars != null, "[ASCIIEncoding.GetChars]chars is null"); - Contract.Assert(charCount >= 0, "[ASCIIEncoding.GetChars]charCount is negative"); + Debug.Assert(bytes != null, "[ASCIIEncoding.GetChars]bytes is null"); + Debug.Assert(byteCount >= 0, "[ASCIIEncoding.GetChars]byteCount is negative"); + Debug.Assert(chars != null, "[ASCIIEncoding.GetChars]chars is null"); + Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetChars]charCount is negative"); // Do it fast way if using ? replacement fallback byte* byteEnd = bytes + byteCount; @@ -600,7 +593,7 @@ namespace System.Text else { fallback = decoder.Fallback as DecoderReplacementFallback; - Contract.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || + Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetChars]Expected empty fallback buffer"); } @@ -668,7 +661,7 @@ namespace System.Text if (!fallbackBuffer.InternalFallback(byteBuffer, bytes, ref chars)) { // May or may not throw, but we didn't get this byte - Contract.Assert(bytes > byteStart || chars == charStart, + Debug.Assert(bytes > byteStart || chars == charStart, "[ASCIIEncoding.GetChars]Expected bytes to have advanced already (fallback case)"); bytes--; // unused byte fallbackBuffer.InternalReset(); // Didn't fall this back @@ -681,7 +674,7 @@ namespace System.Text // Make sure we have buffer space if (chars >= charEnd) { - Contract.Assert(bytes > byteStart || chars == charStart, + Debug.Assert(bytes > byteStart || chars == charStart, "[ASCIIEncoding.GetChars]Expected bytes to have advanced already (normal case)"); bytes--; // unused byte ThrowCharsOverflow(decoder, chars == charStart); // throw? @@ -698,7 +691,7 @@ namespace System.Text decoder.m_bytesUsed = (int)(bytes - byteStart); // Expect Empty fallback buffer for GetChars - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[ASCIIEncoding.GetChars]Expected Empty fallback buffer"); return (int)(chars - charStart); @@ -708,7 +701,7 @@ namespace System.Text public override int GetMaxByteCount(int charCount) { if (charCount < 0) - throw new ArgumentOutOfRangeException("charCount", + throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -721,7 +714,7 @@ namespace System.Text // 1 to 1 for most characters. Only surrogates with fallbacks have less. if (byteCount > 0x7fffffff) - throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); + throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); return (int)byteCount; } @@ -729,7 +722,7 @@ namespace System.Text public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) - throw new ArgumentOutOfRangeException("byteCount", + throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -741,7 +734,7 @@ namespace System.Text charCount *= DecoderFallback.MaxCharCount; if (charCount > 0x7fffffff) - throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow")); + throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow")); return (int)charCount; } diff --git a/src/mscorlib/src/System/Text/BaseCodePageEncoding.cs b/src/mscorlib/src/System/Text/BaseCodePageEncoding.cs index 4c9ca6eaaf..0a42237dc1 100644 --- a/src/mscorlib/src/System/Text/BaseCodePageEncoding.cs +++ b/src/mscorlib/src/System/Text/BaseCodePageEncoding.cs @@ -6,6 +6,7 @@ namespace System.Text { using System; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.InteropServices; @@ -72,7 +73,6 @@ namespace System.Text [NonSerialized] protected bool m_bUseMlangTypeForSerialization = false; - [System.Security.SecuritySafeCritical] // static constructors should be safe to call static BaseCodePageEncoding() { } @@ -136,32 +136,26 @@ namespace System.Text } // Initialize our global stuff - [SecurityCritical] unsafe static CodePageDataFileHeader* m_pCodePageFileHeader = (CodePageDataFileHeader*)GlobalizationAssembly.GetGlobalizationResourceBytePtr( typeof(CharUnicodeInfo).Assembly, CODE_PAGE_DATA_FILE_NAME); // Real variables [NonSerialized] - [SecurityCritical] unsafe protected CodePageHeader* pCodePage = null; // Safe handle wrapper around section map view - [System.Security.SecurityCritical] // auto-generated [NonSerialized] protected SafeViewOfFileHandle safeMemorySectionHandle = null; // Safe handle wrapper around mapped file handle - [System.Security.SecurityCritical] // auto-generated [NonSerialized] protected SafeFileMappingHandle safeFileMappingHandle = null; - [System.Security.SecurityCritical] // auto-generated internal BaseCodePageEncoding(int codepage) : this(codepage, codepage) { } - [System.Security.SecurityCritical] // auto-generated internal BaseCodePageEncoding(int codepage, int dataCodePage) : base(codepage == 0? Microsoft.Win32.Win32Native.GetACP(): codepage) { @@ -171,7 +165,6 @@ namespace System.Text } // Constructor called by serialization. - [System.Security.SecurityCritical] // auto-generated internal BaseCodePageEncoding(SerializationInfo info, StreamingContext context) : base(0) { // We cannot ever call this, we've proxied ourselved to CodePageEncoding @@ -179,12 +172,11 @@ namespace System.Text } // ISerializable implementation - [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // Make sure to get the base stuff too This throws if info is null SerializeEncoding(info, context); - Contract.Assert(info!=null, "[BaseCodePageEncoding.GetObjectData] Expected null info to throw"); + Debug.Assert(info!=null, "[BaseCodePageEncoding.GetObjectData] Expected null info to throw"); // Just need Everett maxCharSize (BaseCodePageEncoding) or m_maxByteSize (MLangBaseCodePageEncoding) info.AddValue(m_bUseMlangTypeForSerialization ? "m_maxByteSize" : "maxCharSize", @@ -196,7 +188,6 @@ namespace System.Text } // We need to load tables for our code page - [System.Security.SecurityCritical] // auto-generated private unsafe void LoadCodePageTables() { CodePageHeader* pCodePage = FindCodePage(dataTableCodePage); @@ -217,7 +208,6 @@ namespace System.Text } // Look up the code page pointer - [System.Security.SecurityCritical] // auto-generated private static unsafe CodePageHeader* FindCodePage(int codePage) { // We'll have to loop through all of the m_pCodePageIndex[] items to find our code page, this isn't @@ -240,7 +230,6 @@ namespace System.Text } // Get our code page byte count - [System.Security.SecurityCritical] // auto-generated internal static unsafe int GetCodePageByteSize(int codePage) { // Get our code page info @@ -250,18 +239,16 @@ namespace System.Text if (pCodePage == null) return 0; - Contract.Assert(pCodePage->ByteCount == 1 || pCodePage->ByteCount == 2, + Debug.Assert(pCodePage->ByteCount == 1 || pCodePage->ByteCount == 2, "[BaseCodePageEncoding] Code page (" + codePage + ") has invalid byte size (" + pCodePage->ByteCount + ") in table"); // Return what it says for byte count return pCodePage->ByteCount; } // We have a managed code page entry, so load our tables - [System.Security.SecurityCritical] protected abstract unsafe void LoadManagedCodePage(); // Allocate memory to load our code page - [System.Security.SecurityCritical] // auto-generated protected unsafe byte* GetSharedMemory(int iSize) { // Build our name @@ -271,7 +258,7 @@ namespace System.Text // This gets shared memory for our map. If its can't, it gives us clean memory. Byte *pMemorySection = EncodingTable.nativeCreateOpenFileMapping(strName, iSize, out mappedFileHandle); - Contract.Assert(pMemorySection != null, + Debug.Assert(pMemorySection != null, "[BaseCodePageEncoding.GetSharedMemory] Expected non-null memory section to be opened"); // If that failed, we have to die. @@ -291,7 +278,6 @@ namespace System.Text return pMemorySection; } - [System.Security.SecurityCritical] // auto-generated protected unsafe virtual String GetMemorySectionName() { int iUseCodePage = this.bFlagDataTable ? dataTableCodePage : CodePage; @@ -303,29 +289,26 @@ namespace System.Text return strName; } - [System.Security.SecurityCritical] protected abstract unsafe void ReadBestFitTable(); - [System.Security.SecuritySafeCritical] internal override char[] GetBestFitUnicodeToBytesData() { // Read in our best fit table if necessary if (arrayUnicodeBestFit == null) ReadBestFitTable(); - Contract.Assert(arrayUnicodeBestFit != null, + Debug.Assert(arrayUnicodeBestFit != null, "[BaseCodePageEncoding.GetBestFitUnicodeToBytesData]Expected non-null arrayUnicodeBestFit"); // Normally we don't have any best fit data. return arrayUnicodeBestFit; } - [System.Security.SecuritySafeCritical] internal override char[] GetBestFitBytesToUnicodeData() { // Read in our best fit table if necessary if (arrayBytesBestFit == null) ReadBestFitTable(); - Contract.Assert(arrayBytesBestFit != null, + Debug.Assert(arrayBytesBestFit != null, "[BaseCodePageEncoding.GetBestFitBytesToUnicodeData]Expected non-null arrayBytesBestFit"); // Normally we don't have any best fit data. @@ -336,7 +319,6 @@ namespace System.Text // is invalid. so we detect that by validating the memory section handle then re-initialize the memory // section by calling LoadManagedCodePage() method and eventually the mapped file handle and // the memory section pointer will get finalized one more time. - [System.Security.SecurityCritical] // auto-generated internal unsafe void CheckMemorySection() { if (safeMemorySectionHandle != null && safeMemorySectionHandle.DangerousGetHandle() == IntPtr.Zero) diff --git a/src/mscorlib/src/System/Text/CodePageEncoding.cs b/src/mscorlib/src/System/Text/CodePageEncoding.cs index 9f1b2d2620..7805c6580a 100644 --- a/src/mscorlib/src/System/Text/CodePageEncoding.cs +++ b/src/mscorlib/src/System/Text/CodePageEncoding.cs @@ -11,6 +11,7 @@ namespace System.Text using System; using System.Runtime.Serialization; using System.Security.Permissions; + using System.Diagnostics; using System.Diagnostics.Contracts; /*=================================CodePageEncoding================================== @@ -44,7 +45,7 @@ namespace System.Text internal CodePageEncoding(SerializationInfo info, StreamingContext context) { // Any info? - if (info==null) throw new ArgumentNullException("info"); + if (info==null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); // All versions have a code page @@ -74,7 +75,6 @@ namespace System.Text } // Just get it from GetEncoding - [System.Security.SecurityCritical] // auto-generated public Object GetRealObject(StreamingContext context) { // Get our encoding (Note: This has default fallbacks for readonly and everett cases) @@ -93,11 +93,10 @@ namespace System.Text } // ISerializable implementation - [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // We cannot ever call this. - Contract.Assert(false, "Didn't expect to make it to CodePageEncoding ISerializable.GetObjectData"); + Debug.Assert(false, "Didn't expect to make it to CodePageEncoding ISerializable.GetObjectData"); throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException")); } @@ -113,25 +112,23 @@ namespace System.Text internal Decoder(SerializationInfo info, StreamingContext context) { // Any info? - if (info==null) throw new ArgumentNullException("info"); + if (info==null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); this.realEncoding = (Encoding)info.GetValue("encoding", typeof(Encoding)); } // Just get it from GetDecider - [System.Security.SecurityCritical] // auto-generated public Object GetRealObject(StreamingContext context) { return this.realEncoding.GetDecoder(); } // ISerializable implementation, get data for this object - [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // We cannot ever call this. - Contract.Assert(false, "Didn't expect to make it to CodePageEncoding.Decoder.GetObjectData"); + Debug.Assert(false, "Didn't expect to make it to CodePageEncoding.Decoder.GetObjectData"); throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException")); } } diff --git a/src/mscorlib/src/System/Text/DBCSCodePageEncoding.cs b/src/mscorlib/src/System/Text/DBCSCodePageEncoding.cs index c103d7898f..28b85d591e 100644 --- a/src/mscorlib/src/System/Text/DBCSCodePageEncoding.cs +++ b/src/mscorlib/src/System/Text/DBCSCodePageEncoding.cs @@ -6,6 +6,7 @@ namespace System.Text { using System; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Text; using System.Threading; @@ -20,13 +21,10 @@ namespace System.Text { // Pointers to our memory section parts [NonSerialized] - [SecurityCritical] protected unsafe char* mapBytesToUnicode = null; // char 65536 [NonSerialized] - [SecurityCritical] protected unsafe ushort* mapUnicodeToBytes = null; // byte 65536 [NonSerialized] - [SecurityCritical] protected unsafe int* mapCodePageCached = null; // to remember which CP is cached [NonSerialized] @@ -45,23 +43,20 @@ namespace System.Text [NonSerialized] protected char charUnknown = (char)0; - [System.Security.SecurityCritical] // auto-generated public DBCSCodePageEncoding(int codePage) : this(codePage, codePage) { } - [System.Security.SecurityCritical] // auto-generated internal DBCSCodePageEncoding(int codePage, int dataCodePage) : base(codePage, dataCodePage) { } // Constructor called by serialization. // Note: We use the base GetObjectData however - [System.Security.SecurityCritical] // auto-generated internal DBCSCodePageEncoding(SerializationInfo info, StreamingContext context) : base(0) { // Actually this can't ever get called, CodePageEncoding is our proxy - Contract.Assert(false, "Didn't expect to make it to DBCSCodePageEncoding serialization constructor"); + Debug.Assert(false, "Didn't expect to make it to DBCSCodePageEncoding serialization constructor"); throw new ArgumentNullException("this"); } @@ -93,11 +88,10 @@ namespace System.Text // corrospond to those unicode code points. // We have a managed code page entry, so load our tables // - [System.Security.SecurityCritical] // auto-generated protected override unsafe void LoadManagedCodePage() { // Should be loading OUR code page - Contract.Assert(pCodePage->CodePage == this.dataTableCodePage, + Debug.Assert(pCodePage->CodePage == this.dataTableCodePage, "[DBCSCodePageEncoding.LoadManagedCodePage]Expected to load data table code page"); // Make sure we're really a 1 byte code page @@ -120,7 +114,7 @@ namespace System.Text byteCountUnknown++; // We use fallback encoder, which uses ?, which so far all of our tables do as well - Contract.Assert(bytesUnknown == 0x3f, + Debug.Assert(bytesUnknown == 0x3f, "[DBCSCodePageEncoding.LoadManagedCodePage]Expected 0x3f (?) as unknown byte character"); // Get our mapped section (bytes to allocate = 2 bytes per 65536 Unicode chars + 2 bytes per 65536 DBCS chars) @@ -134,7 +128,7 @@ namespace System.Text // If its cached (& filled in) we don't have to do anything else if (*mapCodePageCached != 0) { - Contract.Assert(((*mapCodePageCached == this.dataTableCodePage && this.bFlagDataTable) || + Debug.Assert(((*mapCodePageCached == this.dataTableCodePage && this.bFlagDataTable) || (*mapCodePageCached == this.CodePage && !this.bFlagDataTable)), "[DBCSCodePageEncoding.LoadManagedCodePage]Expected mapped section cached page flag to be set to data table or regular code page."); @@ -188,7 +182,7 @@ namespace System.Text else if (input == LEAD_BYTE_CHAR) // 0xfffe { // Lead byte mark - Contract.Assert(bytePosition < 0x100, "[DBCSCodePageEncoding.LoadManagedCodePage]expected lead byte to be < 0x100"); + Debug.Assert(bytePosition < 0x100, "[DBCSCodePageEncoding.LoadManagedCodePage]expected lead byte to be < 0x100"); useBytes = bytePosition; // input stays 0xFFFE } @@ -235,7 +229,6 @@ namespace System.Text } // Any special processing for this code page - [System.Security.SecurityCritical] // auto-generated protected virtual unsafe void CleanUpEndBytes(char* chars) { } @@ -256,7 +249,6 @@ namespace System.Text } // Read in our best fit table - [System.Security.SecurityCritical] // auto-generated protected unsafe override void ReadBestFitTable() { // Lock so we don't confuse ourselves. @@ -407,7 +399,7 @@ namespace System.Text // If they're out of order we need to sort them. if (bOutOfOrder) { - Contract.Assert((arrayTemp.Length / 2) < 20, + Debug.Assert((arrayTemp.Length / 2) < 20, "[DBCSCodePageEncoding.ReadBestFitTable]Expected small best fit table < 20 for code page " + CodePage + ", not " + arrayTemp.Length / 2); for (int i = 0; i < arrayTemp.Length - 2; i+=2) @@ -515,7 +507,7 @@ namespace System.Text // We can't do this assert for CP 51932 & 50220 because they aren't // calling CleanUpBytes() for best fit. All the string stuff here // also makes this assert slow. - // Contract.Assert(arrayTemp[iBestFitCount-1] != (char)0xFFFD, String.Format( + // Debug.Assert(arrayTemp[iBestFitCount-1] != (char)0xFFFD, String.Format( // "[DBCSCodePageEncoding.ReadBestFitTable] No valid Unicode value {0:X4} for round trip bytes {1:X4}, encoding {2}", // (int)mapBytesToUnicode[input], (int)input, CodePage)); } @@ -534,15 +526,14 @@ namespace System.Text // GetByteCount // Note: We start by assuming that the output will be the same as count. Having // an encoder or fallback may change that assumption - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(count >= 0, "[DBCSCodePageEncoding.GetByteCount]count is negative"); - Contract.Assert(chars != null, "[DBCSCodePageEncoding.GetByteCount]chars is null"); + Debug.Assert(count >= 0, "[DBCSCodePageEncoding.GetByteCount]count is negative"); + Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetByteCount]chars is null"); // Assert because we shouldn't be able to have a null encoder. - Contract.Assert(encoderFallback != null, "[DBCSCodePageEncoding.GetByteCount]Attempting to use null fallback"); + Debug.Assert(encoderFallback != null, "[DBCSCodePageEncoding.GetByteCount]Attempting to use null fallback"); CheckMemorySection(); @@ -568,8 +559,8 @@ namespace System.Text // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { - Contract.Assert(Char.IsHighSurrogate(charLeftOver), "[DBCSCodePageEncoding.GetByteCount]leftover character should be high surrogate"); - Contract.Assert(encoder != null, + Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[DBCSCodePageEncoding.GetByteCount]leftover character should be high surrogate"); + Debug.Assert(encoder != null, "[DBCSCodePageEncoding.GetByteCount]Expect to have encoder if we have a charLeftOver"); // Since left over char was a surrogate, it'll have to be fallen back. @@ -625,18 +616,17 @@ namespace System.Text return (int)byteCount; } - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(bytes != null, "[DBCSCodePageEncoding.GetBytes]bytes is null"); - Contract.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetBytes]byteCount is negative"); - Contract.Assert(chars != null, "[DBCSCodePageEncoding.GetBytes]chars is null"); - Contract.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetBytes]charCount is negative"); + Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetBytes]bytes is null"); + Debug.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetBytes]byteCount is negative"); + Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetBytes]chars is null"); + Debug.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetBytes]charCount is negative"); // Assert because we shouldn't be able to have a null encoder. - Contract.Assert(encoderFallback != null, "[DBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback"); + Debug.Assert(encoderFallback != null, "[DBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback"); CheckMemorySection(); @@ -654,7 +644,7 @@ namespace System.Text if (encoder != null) { charLeftOver = encoder.charLeftOver; - Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), + Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), "[DBCSCodePageEncoding.GetBytes]leftover character should be high surrogate"); // Go ahead and get the fallback buffer (need leftover fallback if converting) @@ -669,7 +659,7 @@ namespace System.Text // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { - Contract.Assert(encoder != null, + Debug.Assert(encoder != null, "[DBCSCodePageEncoding.GetBytes]Expect to have encoder if we have a charLeftOver"); // Since left over char was a surrogate, it'll have to be fallen back. @@ -702,7 +692,7 @@ namespace System.Text if (fallbackBuffer == null) { // Initialize the buffer - Contract.Assert(encoder == null, + Debug.Assert(encoder == null, "[DBCSCodePageEncoding.GetBytes]Expected delayed create fallback only if no encoder."); fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); fallbackBuffer.InternalInitialize(charEnd - charCount, charEnd, encoder, true); @@ -724,7 +714,7 @@ namespace System.Text // didn't use this char, we'll throw or use buffer if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false) { - Contract.Assert(chars > charStart, + Debug.Assert(chars > charStart, "[DBCSCodePageEncoding.GetBytes]Expected chars to have advanced (double byte case)"); chars--; // don't use last char } @@ -743,7 +733,7 @@ namespace System.Text // didn't use this char, we'll throw or use buffer if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false) { - Contract.Assert(chars > charStart, + Debug.Assert(chars > charStart, "[DBCSCodePageEncoding.GetBytes]Expected chars to have advanced (single byte case)"); chars--; // don't use last char } @@ -771,7 +761,7 @@ namespace System.Text // If we're not converting we must not have a fallback buffer // (We don't really have a way to clear none-encoder using fallbacks however) -// Contract.Assert((encoder == null || encoder.m_throwOnOverflow) && +// Debug.Assert((encoder == null || encoder.m_throwOnOverflow) && // (fallbackBuffer == null || fallbackBuffer.Remaining == 0), // "[DBCSEncoding.GetBytes]Expected empty fallback buffer at end if not converting"); @@ -779,12 +769,11 @@ namespace System.Text } // This is internal and called by something else, - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) { // Just assert, we're called internally so these should be safe, checked already - Contract.Assert(bytes != null, "[DBCSCodePageEncoding.GetCharCount]bytes is null"); - Contract.Assert(count >= 0, "[DBCSCodePageEncoding.GetCharCount]byteCount is negative"); + Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetCharCount]bytes is null"); + Debug.Assert(count >= 0, "[DBCSCodePageEncoding.GetCharCount]byteCount is negative"); CheckMemorySection(); @@ -800,7 +789,7 @@ namespace System.Text // Shouldn't have anything in fallback buffer for GetCharCount // (don't have to check m_throwOnOverflow for count) - Contract.Assert(decoder == null || + Debug.Assert(decoder == null || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer at start"); @@ -818,7 +807,7 @@ namespace System.Text } - Contract.Assert(fallbackBuffer == null, + Debug.Assert(fallbackBuffer == null, "[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer"); fallbackBuffer = decoder.FallbackBuffer; fallbackBuffer.InternalInitialize(bytes, null); @@ -842,7 +831,7 @@ namespace System.Text charCount--; // We'll need a fallback - Contract.Assert(fallbackBuffer == null, + Debug.Assert(fallbackBuffer == null, "[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer for unknown pair"); fallbackBuffer = decoder.FallbackBuffer; fallbackBuffer.InternalInitialize(byteEnd - count, null); @@ -917,7 +906,7 @@ namespace System.Text } // Shouldn't have anything in fallback buffer for GetChars - Contract.Assert(decoder == null || !decoder.m_throwOnOverflow || + Debug.Assert(decoder == null || !decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer at end"); @@ -925,15 +914,14 @@ namespace System.Text return charCount; } - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS baseDecoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(bytes != null, "[DBCSCodePageEncoding.GetChars]bytes is null"); - Contract.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetChars]byteCount is negative"); - Contract.Assert(chars != null, "[DBCSCodePageEncoding.GetChars]chars is null"); - Contract.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetChars]charCount is negative"); + Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetChars]bytes is null"); + Debug.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetChars]byteCount is negative"); + Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetChars]chars is null"); + Debug.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetChars]charCount is negative"); CheckMemorySection(); @@ -951,7 +939,7 @@ namespace System.Text DecoderFallbackBuffer fallbackBuffer = null; // Shouldn't have anything in fallback buffer for GetChars - Contract.Assert(decoder == null || !decoder.m_throwOnOverflow || + Debug.Assert(decoder == null || !decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[DBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start"); @@ -970,7 +958,7 @@ namespace System.Text // Well, we're flushing, so use '?' or fallback // fallback leftover byte - Contract.Assert(fallbackBuffer == null, + Debug.Assert(fallbackBuffer == null, "[DBCSCodePageEncoding.GetChars]Expected empty fallback"); fallbackBuffer = decoder.FallbackBuffer; fallbackBuffer.InternalInitialize(bytes, charEnd); @@ -995,7 +983,7 @@ namespace System.Text char cDecoder = mapBytesToUnicode[iBytes]; if (cDecoder == UNKNOWN_CHAR_FLAG && iBytes != 0) { - Contract.Assert(fallbackBuffer == null, + Debug.Assert(fallbackBuffer == null, "[DBCSCodePageEncoding.GetChars]Expected empty fallback for two bytes"); fallbackBuffer = decoder.FallbackBuffer; fallbackBuffer.InternalInitialize(byteEnd - byteCount, charEnd); @@ -1073,7 +1061,7 @@ namespace System.Text if (!fallbackBuffer.InternalFallback(byteBuffer, bytes, ref chars)) { // May or may not throw, but we didn't get these byte(s) - Contract.Assert(bytes >= byteStart + byteBuffer.Length, + Debug.Assert(bytes >= byteStart + byteBuffer.Length, "[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for fallback"); bytes-=byteBuffer.Length; // didn't use these byte(s) fallbackBuffer.InternalReset(); // Didn't fall this back @@ -1087,12 +1075,12 @@ namespace System.Text if (chars >= charEnd) { // May or may not throw, but we didn't get these byte(s) - Contract.Assert(bytes > byteStart, + Debug.Assert(bytes > byteStart, "[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for lead byte"); bytes--; // unused byte if (iBytes >= 0x100) { - Contract.Assert(bytes > byteStart, + Debug.Assert(bytes > byteStart, "[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for trail byte"); bytes--; // 2nd unused byte } @@ -1118,7 +1106,7 @@ namespace System.Text } // Shouldn't have anything in fallback buffer for GetChars - Contract.Assert(decoder == null || !decoder.m_throwOnOverflow || + Debug.Assert(decoder == null || !decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[DBCSCodePageEncoding.GetChars]Expected empty fallback buffer at end"); @@ -1129,7 +1117,7 @@ namespace System.Text public override int GetMaxByteCount(int charCount) { if (charCount < 0) - throw new ArgumentOutOfRangeException("charCount", + throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -1143,7 +1131,7 @@ namespace System.Text byteCount *= 2; if (byteCount > 0x7fffffff) - throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); + throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); return (int)byteCount; } @@ -1151,7 +1139,7 @@ namespace System.Text public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) - throw new ArgumentOutOfRangeException("byteCount", + throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -1163,7 +1151,7 @@ namespace System.Text charCount *= DecoderFallback.MaxCharCount; if (charCount > 0x7fffffff) - throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow")); + throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow")); return (int)charCount; } diff --git a/src/mscorlib/src/System/Text/Decoder.cs b/src/mscorlib/src/System/Text/Decoder.cs index f794dc4dce..0ebbacddcf 100644 --- a/src/mscorlib/src/System/Text/Decoder.cs +++ b/src/mscorlib/src/System/Text/Decoder.cs @@ -7,6 +7,7 @@ namespace System.Text using System.Runtime.Serialization; using System.Text; using System; + using System.Diagnostics; using System.Diagnostics.Contracts; // A Decoder is used to decode a sequence of blocks of bytes into a // sequence of blocks of characters. Following instantiation of a decoder, @@ -49,13 +50,13 @@ namespace System.Text set { if (value == null) - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); Contract.EndContractBlock(); // Can't change fallback if buffer is wrong if (m_fallbackBuffer != null && m_fallbackBuffer.Remaining > 0) throw new ArgumentException( - Environment.GetResourceString("Argument_FallbackBufferNotEmpty"), "value"); + Environment.GetResourceString("Argument_FallbackBufferNotEmpty"), nameof(value)); m_fallback = value; m_fallbackBuffer = null; @@ -124,18 +125,17 @@ namespace System.Text // We expect this to be the workhorse for NLS Encodings, but for existing // ones we need a working (if slow) default implimentation) - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public virtual unsafe int GetCharCount(byte* bytes, int count, bool flush) { // Validate input parameters if (bytes == null) - throw new ArgumentNullException("bytes", + throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); if (count < 0) - throw new ArgumentOutOfRangeException("count", + throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -189,7 +189,6 @@ namespace System.Text // the char[] to our char* output buffer. If the result count was wrong, we // could easily overflow our output buffer. Therefore we do an extra test // when we copy the buffer so that we don't overflow charCount either. - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public virtual unsafe int GetChars(byte* bytes, int byteCount, @@ -197,11 +196,11 @@ namespace System.Text { // Validate input parameters if (chars == null || bytes == null) - throw new ArgumentNullException(chars == null ? "chars" : "bytes", + throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); if (byteCount < 0 || charCount < 0) - throw new ArgumentOutOfRangeException((byteCount<0 ? "byteCount" : "charCount"), + throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -218,7 +217,7 @@ namespace System.Text // Do the work int result = GetChars(arrByte, 0, byteCount, arrChar, 0, flush); - Contract.Assert(result <= charCount, "Returned more chars than we have space for"); + Debug.Assert(result <= charCount, "Returned more chars than we have space for"); // Copy the char array // WARNING: We MUST make sure that we don't copy too many chars. We can't @@ -256,23 +255,23 @@ namespace System.Text { // Validate parameters if (bytes == null || chars == null) - throw new ArgumentNullException((bytes == null ? "bytes" : "chars"), + throw new ArgumentNullException((bytes == null ? nameof(bytes) : nameof(chars)), Environment.GetResourceString("ArgumentNull_Array")); if (byteIndex < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException((byteIndex<0 ? "byteIndex" : "byteCount"), + throw new ArgumentOutOfRangeException((byteIndex<0 ? nameof(byteIndex) : nameof(byteCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"), + throw new ArgumentOutOfRangeException((charIndex<0 ? nameof(charIndex) : nameof(charCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (bytes.Length - byteIndex < byteCount) - throw new ArgumentOutOfRangeException("bytes", + throw new ArgumentOutOfRangeException(nameof(bytes), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); if (chars.Length - charIndex < charCount) - throw new ArgumentOutOfRangeException("chars", + throw new ArgumentOutOfRangeException(nameof(chars), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); Contract.EndContractBlock(); @@ -306,7 +305,6 @@ namespace System.Text // Note that if all of the input bytes are not consumed, then we'll do a /2, which means // that its likely that we didn't consume as many bytes as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public virtual unsafe void Convert(byte* bytes, int byteCount, @@ -315,11 +313,11 @@ namespace System.Text { // Validate input parameters if (chars == null || bytes == null) - throw new ArgumentNullException(chars == null ? "chars" : "bytes", + throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); if (byteCount < 0 || charCount < 0) - throw new ArgumentOutOfRangeException((byteCount<0 ? "byteCount" : "charCount"), + throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); diff --git a/src/mscorlib/src/System/Text/DecoderBestFitFallback.cs b/src/mscorlib/src/System/Text/DecoderBestFitFallback.cs index 5c1dcd9682..6389b4b141 100644 --- a/src/mscorlib/src/System/Text/DecoderBestFitFallback.cs +++ b/src/mscorlib/src/System/Text/DecoderBestFitFallback.cs @@ -10,6 +10,7 @@ namespace System.Text using System; using System.Text; using System.Threading; + using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] @@ -101,7 +102,7 @@ namespace System.Text public override bool Fallback(byte[] bytesUnknown, int index) { // We expect no previous fallback in our buffer - Contract.Assert(iCount < 1, "[DecoderReplacementFallbackBuffer.Fallback] Calling fallback without a previously empty buffer"); + Debug.Assert(iCount < 1, "[DecoderReplacementFallbackBuffer.Fallback] Calling fallback without a previously empty buffer"); cBestFit = TryBestFit(bytesUnknown); if (cBestFit == '\0') @@ -155,7 +156,6 @@ namespace System.Text } // Clear the buffer - [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe void Reset() { iCount = -1; @@ -163,7 +163,6 @@ namespace System.Text } // This version just counts the fallback and doesn't actually copy anything. - [System.Security.SecurityCritical] // auto-generated internal unsafe override int InternalFallback(byte[] bytes, byte* pBytes) // Right now this has both bytes and bytes[], since we might have extra bytes, hence the // array, and we might need the index, hence the byte* @@ -212,7 +211,7 @@ namespace System.Text if (cTest == cCheck) { // We found it - Contract.Assert(index + 1 < oFallback.arrayBestFit.Length, + Debug.Assert(index + 1 < oFallback.arrayBestFit.Length, "[InternalDecoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array"); return oFallback.arrayBestFit[index + 1]; } @@ -233,7 +232,7 @@ namespace System.Text if (oFallback.arrayBestFit[index] == cCheck) { // We found it - Contract.Assert(index + 1 < oFallback.arrayBestFit.Length, + Debug.Assert(index + 1 < oFallback.arrayBestFit.Length, "[InternalDecoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array"); return oFallback.arrayBestFit[index + 1]; } diff --git a/src/mscorlib/src/System/Text/DecoderFallback.cs b/src/mscorlib/src/System/Text/DecoderFallback.cs index 1698fd37ab..42483a724d 100644 --- a/src/mscorlib/src/System/Text/DecoderFallback.cs +++ b/src/mscorlib/src/System/Text/DecoderFallback.cs @@ -7,6 +7,7 @@ using System; using System.Security; using System.Threading; using System.Globalization; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Text @@ -115,13 +116,10 @@ namespace System.Text // Internal items to help us figure out what we're doing as far as error messages, etc. // These help us with our performance and messages internally - [SecurityCritical] internal unsafe byte* byteStart; - [SecurityCritical] internal unsafe char* charEnd; // Internal Reset - [System.Security.SecurityCritical] // auto-generated internal unsafe void InternalReset() { byteStart = null; @@ -130,7 +128,6 @@ namespace System.Text // Set the above values // This can't be part of the constructor because DecoderFallbacks would have to know how to impliment these. - [System.Security.SecurityCritical] // auto-generated internal unsafe void InternalInitialize(byte* byteStart, char* charEnd) { this.byteStart = byteStart; @@ -145,7 +142,6 @@ namespace System.Text // Right now this has both bytes and bytes[], since we might have extra bytes, hence the // array, and we might need the index, hence the byte* // Don't touch ref chars unless we succeed - [System.Security.SecurityCritical] // auto-generated internal unsafe virtual bool InternalFallback(byte[] bytes, byte* pBytes, ref char* chars) { // Copy bytes to array (slow, but right now that's what we get to do. @@ -153,7 +149,7 @@ namespace System.Text // for (int i = 0; i < count; i++) // bytesUnknown[i] = *(bytes++); - Contract.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize"); + Debug.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize"); // See if there's a fallback character and we have an output buffer then copy our string. if (this.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length))) @@ -204,7 +200,6 @@ namespace System.Text } // This version just counts the fallback and doesn't actually copy anything. - [System.Security.SecurityCritical] // auto-generated internal unsafe virtual int InternalFallback(byte[] bytes, byte* pBytes) // Right now this has both bytes and bytes[], since we might have extra bytes, hence the // array, and we might need the index, hence the byte* @@ -214,7 +209,7 @@ namespace System.Text // for (int i = 0; i < count; i++) // bytesUnknown[i] = *(bytes++); - Contract.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize"); + Debug.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize"); // See if there's a fallback character and we have an output buffer then copy our string. if (this.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length))) @@ -277,7 +272,7 @@ namespace System.Text // Throw it, using our complete bytes throw new ArgumentException( Environment.GetResourceString("Argument_RecursiveFallbackBytes", - strBytes.ToString()), "bytesUnknown"); + strBytes.ToString()), nameof(bytesUnknown)); } } diff --git a/src/mscorlib/src/System/Text/DecoderNLS.cs b/src/mscorlib/src/System/Text/DecoderNLS.cs index c2e82dd250..e44c43adef 100644 --- a/src/mscorlib/src/System/Text/DecoderNLS.cs +++ b/src/mscorlib/src/System/Text/DecoderNLS.cs @@ -42,7 +42,6 @@ namespace System.Text } // ISerializable implementation. called during serialization. - [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { SerializeDecoder(info); @@ -77,20 +76,19 @@ namespace System.Text return GetCharCount(bytes, index, count, false); } - [System.Security.SecuritySafeCritical] // auto-generated public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool flush) { // Validate Parameters if (bytes == null) - throw new ArgumentNullException("bytes", + throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"), + throw new ArgumentOutOfRangeException((index<0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (bytes.Length - index < count) - throw new ArgumentOutOfRangeException("bytes", + throw new ArgumentOutOfRangeException(nameof(bytes), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); Contract.EndContractBlock(); @@ -104,16 +102,15 @@ namespace System.Text return GetCharCount(pBytes + index, count, flush); } - [System.Security.SecurityCritical] // auto-generated public unsafe override int GetCharCount(byte* bytes, int count, bool flush) { // Validate parameters if (bytes == null) - throw new ArgumentNullException("bytes", + throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); if (count < 0) - throw new ArgumentOutOfRangeException("count", + throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -131,25 +128,24 @@ namespace System.Text return GetChars(bytes, byteIndex, byteCount, chars, charIndex, false); } - [System.Security.SecuritySafeCritical] // auto-generated public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush) { // Validate Parameters if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? "bytes" : "chars", + throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), Environment.GetResourceString("ArgumentNull_Array")); if (byteIndex < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException((byteIndex<0 ? "byteIndex" : "byteCount"), + throw new ArgumentOutOfRangeException((byteIndex<0 ? nameof(byteIndex) : nameof(byteCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if ( bytes.Length - byteIndex < byteCount) - throw new ArgumentOutOfRangeException("bytes", + throw new ArgumentOutOfRangeException(nameof(bytes), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); if (charIndex < 0 || charIndex > chars.Length) - throw new ArgumentOutOfRangeException("charIndex", + throw new ArgumentOutOfRangeException(nameof(charIndex), Environment.GetResourceString("ArgumentOutOfRange_Index")); Contract.EndContractBlock(); @@ -170,17 +166,16 @@ namespace System.Text pChars + charIndex, charCount, flush); } - [System.Security.SecurityCritical] // auto-generated public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) { // Validate parameters if (chars == null || bytes == null) - throw new ArgumentNullException((chars == null ? "chars" : "bytes"), + throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), Environment.GetResourceString("ArgumentNull_Array")); if (byteCount < 0 || charCount < 0) - throw new ArgumentOutOfRangeException((byteCount<0 ? "byteCount" : "charCount"), + throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -194,30 +189,29 @@ namespace System.Text // This method is used when the output buffer might not be big enough. // Just call the pointer version. (This gets chars) - [System.Security.SecuritySafeCritical] // auto-generated public override unsafe void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Validate parameters if (bytes == null || chars == null) - throw new ArgumentNullException((bytes == null ? "bytes" : "chars"), + throw new ArgumentNullException((bytes == null ? nameof(bytes) : nameof(chars)), Environment.GetResourceString("ArgumentNull_Array")); if (byteIndex < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException((byteIndex<0 ? "byteIndex" : "byteCount"), + throw new ArgumentOutOfRangeException((byteIndex<0 ? nameof(byteIndex) : nameof(byteCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"), + throw new ArgumentOutOfRangeException((charIndex<0 ? nameof(charIndex) : nameof(charCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (bytes.Length - byteIndex < byteCount) - throw new ArgumentOutOfRangeException("bytes", + throw new ArgumentOutOfRangeException(nameof(bytes), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); if (chars.Length - charIndex < charCount) - throw new ArgumentOutOfRangeException("chars", + throw new ArgumentOutOfRangeException(nameof(chars), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); Contract.EndContractBlock(); @@ -241,18 +235,17 @@ namespace System.Text // This is the version that used pointers. We call the base encoding worker function // after setting our appropriate internal variables. This is getting chars - [System.Security.SecurityCritical] // auto-generated public unsafe override void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Validate input parameters if (chars == null || bytes == null) - throw new ArgumentNullException(chars == null ? "chars" : "bytes", + throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); if (byteCount < 0 || charCount < 0) - throw new ArgumentOutOfRangeException((byteCount<0 ? "byteCount" : "charCount"), + throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); diff --git a/src/mscorlib/src/System/Text/DecoderReplacementFallback.cs b/src/mscorlib/src/System/Text/DecoderReplacementFallback.cs index c732d15816..77c856046d 100644 --- a/src/mscorlib/src/System/Text/DecoderReplacementFallback.cs +++ b/src/mscorlib/src/System/Text/DecoderReplacementFallback.cs @@ -5,6 +5,7 @@ namespace System.Text { using System; + using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] @@ -21,7 +22,7 @@ namespace System.Text public DecoderReplacementFallback(String replacement) { if (replacement == null) - throw new ArgumentNullException("replacement"); + throw new ArgumentNullException(nameof(replacement)); Contract.EndContractBlock(); // Make sure it doesn't have bad surrogate pairs @@ -58,7 +59,7 @@ namespace System.Text break; } if (bFoundHigh) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex", "replacement")); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex", nameof(replacement))); strDefault = replacement; } @@ -156,7 +157,7 @@ namespace System.Text } // Now make sure its in the expected range - Contract.Assert(fallbackIndex < strDefault.Length && fallbackIndex >= 0, + Debug.Assert(fallbackIndex < strDefault.Length && fallbackIndex >= 0, "Index exceeds buffer range"); return strDefault[fallbackIndex]; @@ -187,7 +188,6 @@ namespace System.Text } // Clear the buffer - [System.Security.SecuritySafeCritical] // auto-generated public override unsafe void Reset() { fallbackCount = -1; @@ -196,7 +196,6 @@ namespace System.Text } // This version just counts the fallback and doesn't actually copy anything. - [System.Security.SecurityCritical] // auto-generated internal unsafe override int InternalFallback(byte[] bytes, byte* pBytes) // Right now this has both bytes and bytes[], since we might have extra bytes, hence the // array, and we might need the index, hence the byte* diff --git a/src/mscorlib/src/System/Text/EUCJPEncoding.cs b/src/mscorlib/src/System/Text/EUCJPEncoding.cs index 7c90caec0b..44345b22b9 100644 --- a/src/mscorlib/src/System/Text/EUCJPEncoding.cs +++ b/src/mscorlib/src/System/Text/EUCJPEncoding.cs @@ -50,13 +50,11 @@ namespace System.Text internal class EUCJPEncoding : DBCSCodePageEncoding { // This pretends to be CP 932 as far as memory tables are concerned. - [System.Security.SecurityCritical] // auto-generated public EUCJPEncoding() : base(51932, 932) { this.m_bUseMlangTypeForSerialization = true; } - [System.Security.SecurityCritical] // auto-generated protected unsafe override String GetMemorySectionName() { int iUseCodePage = this.bFlagDataTable ? dataTableCodePage : CodePage; @@ -165,7 +163,6 @@ namespace System.Text return true; } - [System.Security.SecurityCritical] // auto-generated protected override unsafe void CleanUpEndBytes(char* chars) { // Need to special case CP 51932 diff --git a/src/mscorlib/src/System/Text/Encoder.cs b/src/mscorlib/src/System/Text/Encoder.cs index d223dd9d46..b9d4581276 100644 --- a/src/mscorlib/src/System/Text/Encoder.cs +++ b/src/mscorlib/src/System/Text/Encoder.cs @@ -7,6 +7,7 @@ namespace System.Text using System.Runtime.Serialization; using System.Text; using System; + using System.Diagnostics; using System.Diagnostics.Contracts; // An Encoder is used to encode a sequence of blocks of characters into // a sequence of blocks of bytes. Following instantiation of an encoder, @@ -49,13 +50,13 @@ namespace System.Text set { if (value == null) - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); Contract.EndContractBlock(); // Can't change fallback if buffer is wrong if (m_fallbackBuffer != null && m_fallbackBuffer.Remaining > 0) throw new ArgumentException( - Environment.GetResourceString("Argument_FallbackBufferNotEmpty"), "value"); + Environment.GetResourceString("Argument_FallbackBufferNotEmpty"), nameof(value)); m_fallback = value; m_fallbackBuffer = null; @@ -120,18 +121,17 @@ namespace System.Text // We expect this to be the workhorse for NLS encodings // unfortunately for existing overrides, it has to call the [] version, // which is really slow, so avoid this method if you might be calling external encodings. - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public virtual unsafe int GetByteCount(char* chars, int count, bool flush) { // Validate input parameters if (chars == null) - throw new ArgumentNullException("chars", + throw new ArgumentNullException(nameof(chars), Environment.GetResourceString("ArgumentNull_Array")); if (count < 0) - throw new ArgumentOutOfRangeException("count", + throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -182,7 +182,6 @@ namespace System.Text // the byte[] to our byte* output buffer. If the result count was wrong, we // could easily overflow our output buffer. Therefore we do an extra test // when we copy the buffer so that we don't overflow byteCount either. - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public virtual unsafe int GetBytes(char* chars, int charCount, @@ -190,11 +189,11 @@ namespace System.Text { // Validate input parameters if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? "bytes" : "chars", + throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), Environment.GetResourceString("ArgumentNull_Array")); if (charCount < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException((charCount<0 ? "charCount" : "byteCount"), + throw new ArgumentOutOfRangeException((charCount<0 ? nameof(charCount) : nameof(byteCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -211,7 +210,7 @@ namespace System.Text // Do the work int result = GetBytes(arrChar, 0, charCount, arrByte, 0, flush); - Contract.Assert(result <= byteCount, "Returned more bytes than we have space for"); + Debug.Assert(result <= byteCount, "Returned more bytes than we have space for"); // Copy the byte array // WARNING: We MUST make sure that we don't copy too many bytes. We can't @@ -248,23 +247,23 @@ namespace System.Text { // Validate parameters if (chars == null || bytes == null) - throw new ArgumentNullException((chars == null ? "chars" : "bytes"), + throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), Environment.GetResourceString("ArgumentNull_Array")); if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"), + throw new ArgumentOutOfRangeException((charIndex<0 ? nameof(charIndex) : nameof(charCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (byteIndex < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException((byteIndex<0 ? "byteIndex" : "byteCount"), + throw new ArgumentOutOfRangeException((byteIndex<0 ? nameof(byteIndex) : nameof(byteCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (chars.Length - charIndex < charCount) - throw new ArgumentOutOfRangeException("chars", + throw new ArgumentOutOfRangeException(nameof(chars), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); if (bytes.Length - byteIndex < byteCount) - throw new ArgumentOutOfRangeException("bytes", + throw new ArgumentOutOfRangeException(nameof(bytes), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); Contract.EndContractBlock(); @@ -299,7 +298,6 @@ namespace System.Text // Note that if all of the input chars are not consumed, then we'll do a /2, which means // that its likely that we didn't consume as many chars as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public virtual unsafe void Convert(char* chars, int charCount, @@ -308,10 +306,10 @@ namespace System.Text { // Validate input parameters if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? "bytes" : "chars", + throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), Environment.GetResourceString("ArgumentNull_Array")); if (charCount < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException((charCount<0 ? "charCount" : "byteCount"), + throw new ArgumentOutOfRangeException((charCount<0 ? nameof(charCount) : nameof(byteCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); diff --git a/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs b/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs index 352e9695cf..c5f82a299b 100644 --- a/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs +++ b/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs @@ -11,6 +11,7 @@ namespace System.Text using System.Globalization; using System.Text; using System.Threading; + using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] @@ -103,7 +104,7 @@ namespace System.Text // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. // Shouldn't be able to get here for all of our code pages, table would have to be messed up. - Contract.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(non surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback"); + Debug.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(non surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback"); iCount = iSize = 1; cBestFit = TryBestFit(charUnknown); @@ -117,7 +118,7 @@ namespace System.Text { // Double check input surrogate pair if (!Char.IsHighSurrogate(charUnknownHigh)) - throw new ArgumentOutOfRangeException("charUnknownHigh", + throw new ArgumentOutOfRangeException(nameof(charUnknownHigh), Environment.GetResourceString("ArgumentOutOfRange_Range", 0xD800, 0xDBFF)); @@ -130,7 +131,7 @@ namespace System.Text // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. 0 is processing last character, < 0 is not falling back // Shouldn't be able to get here, table would have to be messed up. - Contract.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback"); + Debug.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback"); // Go ahead and get our fallback, surrogates don't have best fit cBestFit = '?'; @@ -183,7 +184,6 @@ namespace System.Text } // Clear the buffer - [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe void Reset() { iCount = -1; @@ -212,7 +212,7 @@ namespace System.Text if (cTest == cUnknown) { // We found it - Contract.Assert(index + 1 < oFallback.arrayBestFit.Length, + Debug.Assert(index + 1 < oFallback.arrayBestFit.Length, "[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array"); return oFallback.arrayBestFit[index + 1]; } @@ -233,7 +233,7 @@ namespace System.Text if (oFallback.arrayBestFit[index] == cUnknown) { // We found it - Contract.Assert(index + 1 < oFallback.arrayBestFit.Length, + Debug.Assert(index + 1 < oFallback.arrayBestFit.Length, "[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array"); return oFallback.arrayBestFit[index + 1]; } diff --git a/src/mscorlib/src/System/Text/EncoderExceptionFallback.cs b/src/mscorlib/src/System/Text/EncoderExceptionFallback.cs index 5ab51cb6dd..051f50ac7c 100644 --- a/src/mscorlib/src/System/Text/EncoderExceptionFallback.cs +++ b/src/mscorlib/src/System/Text/EncoderExceptionFallback.cs @@ -62,7 +62,7 @@ namespace System.Text { if (!Char.IsHighSurrogate(charUnknownHigh)) { - throw new ArgumentOutOfRangeException("charUnknownHigh", + throw new ArgumentOutOfRangeException(nameof(charUnknownHigh), Environment.GetResourceString("ArgumentOutOfRange_Range", 0xD800, 0xDBFF)); } @@ -145,13 +145,13 @@ namespace System.Text { if (!Char.IsHighSurrogate(charUnknownHigh)) { - throw new ArgumentOutOfRangeException("charUnknownHigh", + throw new ArgumentOutOfRangeException(nameof(charUnknownHigh), Environment.GetResourceString("ArgumentOutOfRange_Range", 0xD800, 0xDBFF)); } if (!Char.IsLowSurrogate(charUnknownLow)) { - throw new ArgumentOutOfRangeException("CharUnknownLow", + throw new ArgumentOutOfRangeException(nameof(CharUnknownLow), Environment.GetResourceString("ArgumentOutOfRange_Range", 0xDC00, 0xDFFF)); } diff --git a/src/mscorlib/src/System/Text/EncoderFallback.cs b/src/mscorlib/src/System/Text/EncoderFallback.cs index 4b170414d5..db2bf93bdd 100644 --- a/src/mscorlib/src/System/Text/EncoderFallback.cs +++ b/src/mscorlib/src/System/Text/EncoderFallback.cs @@ -5,6 +5,7 @@ using System; using System.Security; using System.Threading; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Text @@ -111,9 +112,7 @@ namespace System.Text // Internal items to help us figure out what we're doing as far as error messages, etc. // These help us with our performance and messages internally - [SecurityCritical] internal unsafe char* charStart; - [SecurityCritical] internal unsafe char* charEnd; internal EncoderNLS encoder; internal bool setEncoder; @@ -124,7 +123,6 @@ namespace System.Text // Internal Reset // For example, what if someone fails a conversion and wants to reset one of our fallback buffers? - [System.Security.SecurityCritical] // auto-generated internal unsafe void InternalReset() { charStart = null; @@ -135,7 +133,6 @@ namespace System.Text // Set the above values // This can't be part of the constructor because EncoderFallbacks would have to know how to impliment these. - [System.Security.SecurityCritical] // auto-generated internal unsafe void InternalInitialize(char* charStart, char* charEnd, EncoderNLS encoder, bool setEncoder) { this.charStart = charStart; @@ -163,11 +160,10 @@ namespace System.Text // Note that this could also change the contents of this.encoder, which is the same // object that the caller is using, so the caller could mess up the encoder for us // if they aren't careful. - [System.Security.SecurityCritical] // auto-generated internal unsafe virtual bool InternalFallback(char ch, ref char* chars) { // Shouldn't have null charStart - Contract.Assert(charStart != null, + Debug.Assert(charStart != null, "[EncoderFallback.InternalFallbackBuffer]Fallback buffer is not initialized"); // Get our index, remember chars was preincremented to point at next char, so have to -1 diff --git a/src/mscorlib/src/System/Text/EncoderNLS.cs b/src/mscorlib/src/System/Text/EncoderNLS.cs index d5c52f48d8..2add017d68 100644 --- a/src/mscorlib/src/System/Text/EncoderNLS.cs +++ b/src/mscorlib/src/System/Text/EncoderNLS.cs @@ -45,7 +45,6 @@ namespace System.Text } // ISerializable implementation. called during serialization. - [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { SerializeEncoder(info); @@ -77,20 +76,19 @@ namespace System.Text m_fallbackBuffer.Reset(); } - [System.Security.SecuritySafeCritical] // auto-generated public override unsafe int GetByteCount(char[] chars, int index, int count, bool flush) { // Validate input parameters if (chars == null) - throw new ArgumentNullException( "chars", + throw new ArgumentNullException(nameof(chars), Environment.GetResourceString("ArgumentNull_Array")); if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"), + throw new ArgumentOutOfRangeException((index<0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (chars.Length - index < count) - throw new ArgumentOutOfRangeException("chars", + throw new ArgumentOutOfRangeException(nameof(chars), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); Contract.EndContractBlock(); @@ -107,16 +105,15 @@ namespace System.Text return result; } - [System.Security.SecurityCritical] // auto-generated public unsafe override int GetByteCount(char* chars, int count, bool flush) { // Validate input parameters if (chars == null) - throw new ArgumentNullException( "chars", + throw new ArgumentNullException(nameof(chars), Environment.GetResourceString("ArgumentNull_Array")); if (count < 0) - throw new ArgumentOutOfRangeException("count", + throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -125,25 +122,24 @@ namespace System.Text return m_encoding.GetByteCount(chars, count, this); } - [System.Security.SecuritySafeCritical] // auto-generated public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush) { // Validate parameters if (chars == null || bytes == null) - throw new ArgumentNullException((chars == null ? "chars" : "bytes"), + throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), Environment.GetResourceString("ArgumentNull_Array")); if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"), + throw new ArgumentOutOfRangeException((charIndex<0 ? nameof(charIndex) : nameof(charCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (chars.Length - charIndex < charCount) - throw new ArgumentOutOfRangeException("chars", + throw new ArgumentOutOfRangeException(nameof(chars), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); if (byteIndex < 0 || byteIndex > bytes.Length) - throw new ArgumentOutOfRangeException("byteIndex", + throw new ArgumentOutOfRangeException(nameof(byteIndex), Environment.GetResourceString("ArgumentOutOfRange_Index")); Contract.EndContractBlock(); @@ -163,16 +159,15 @@ namespace System.Text pBytes + byteIndex, byteCount, flush); } - [System.Security.SecurityCritical] // auto-generated public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush) { // Validate parameters if (chars == null || bytes == null) - throw new ArgumentNullException((chars == null ? "chars" : "bytes"), + throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), Environment.GetResourceString("ArgumentNull_Array")); if (byteCount < 0 || charCount < 0) - throw new ArgumentOutOfRangeException((byteCount<0 ? "byteCount" : "charCount"), + throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -183,30 +178,29 @@ namespace System.Text // This method is used when your output buffer might not be large enough for the entire result. // Just call the pointer version. (This gets bytes) - [System.Security.SecuritySafeCritical] // auto-generated public override unsafe void Convert(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { // Validate parameters if (chars == null || bytes == null) - throw new ArgumentNullException((chars == null ? "chars" : "bytes"), + throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), Environment.GetResourceString("ArgumentNull_Array")); if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"), + throw new ArgumentOutOfRangeException((charIndex<0 ? nameof(charIndex) : nameof(charCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (byteIndex < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException((byteIndex<0 ? "byteIndex" : "byteCount"), + throw new ArgumentOutOfRangeException((byteIndex<0 ? nameof(byteIndex) : nameof(byteCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (chars.Length - charIndex < charCount) - throw new ArgumentOutOfRangeException("chars", + throw new ArgumentOutOfRangeException(nameof(chars), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); if (bytes.Length - byteIndex < byteCount) - throw new ArgumentOutOfRangeException("bytes", + throw new ArgumentOutOfRangeException(nameof(bytes), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); Contract.EndContractBlock(); @@ -230,17 +224,16 @@ namespace System.Text // This is the version that uses pointers. We call the base encoding worker function // after setting our appropriate internal variables. This is getting bytes - [System.Security.SecurityCritical] // auto-generated public override unsafe void Convert(char* chars, int charCount, byte* bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { // Validate input parameters if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? "bytes" : "chars", + throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), Environment.GetResourceString("ArgumentNull_Array")); if (charCount < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException((charCount<0 ? "charCount" : "byteCount"), + throw new ArgumentOutOfRangeException((charCount<0 ? nameof(charCount) : nameof(byteCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); diff --git a/src/mscorlib/src/System/Text/EncoderReplacementFallback.cs b/src/mscorlib/src/System/Text/EncoderReplacementFallback.cs index 15dfee8912..604cddf9bb 100644 --- a/src/mscorlib/src/System/Text/EncoderReplacementFallback.cs +++ b/src/mscorlib/src/System/Text/EncoderReplacementFallback.cs @@ -6,6 +6,7 @@ namespace System.Text { using System; using System.Runtime; + using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] @@ -23,7 +24,7 @@ namespace System.Text { // Must not be null if (replacement == null) - throw new ArgumentNullException("replacement"); + throw new ArgumentNullException(nameof(replacement)); Contract.EndContractBlock(); // Make sure it doesn't have bad surrogate pairs @@ -60,7 +61,7 @@ namespace System.Text break; } if (bFoundHigh) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex", "replacement")); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex", nameof(replacement))); strDefault = replacement; } @@ -147,7 +148,7 @@ namespace System.Text { // Double check input surrogate pair if (!Char.IsHighSurrogate(charUnknownHigh)) - throw new ArgumentOutOfRangeException("charUnknownHigh", + throw new ArgumentOutOfRangeException(nameof(charUnknownHigh), Environment.GetResourceString("ArgumentOutOfRange_Range", 0xD800, 0xDBFF)); @@ -189,7 +190,7 @@ namespace System.Text } // Now make sure its in the expected range - Contract.Assert(fallbackIndex < strDefault.Length && fallbackIndex >= 0, + Debug.Assert(fallbackIndex < strDefault.Length && fallbackIndex >= 0, "Index exceeds buffer range"); return strDefault[fallbackIndex]; @@ -220,7 +221,6 @@ namespace System.Text } // Clear the buffer - [System.Security.SecuritySafeCritical] // auto-generated public override unsafe void Reset() { fallbackCount = -1; diff --git a/src/mscorlib/src/System/Text/Encoding.cs b/src/mscorlib/src/System/Text/Encoding.cs index 8533016293..658bdbb133 100644 --- a/src/mscorlib/src/System/Text/Encoding.cs +++ b/src/mscorlib/src/System/Text/Encoding.cs @@ -15,6 +15,7 @@ namespace System.Text using System.Security.Permissions; using System.Threading; using System.Text; + using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using Win32Native = Microsoft.Win32.Win32Native; @@ -189,7 +190,7 @@ namespace System.Text // Validate code page if (codePage < 0) { - throw new ArgumentOutOfRangeException("codePage"); + throw new ArgumentOutOfRangeException(nameof(codePage)); } Contract.EndContractBlock(); @@ -208,7 +209,7 @@ namespace System.Text // Validate code page if (codePage < 0) { - throw new ArgumentOutOfRangeException("codePage"); + throw new ArgumentOutOfRangeException(nameof(codePage)); } Contract.EndContractBlock(); @@ -275,7 +276,7 @@ namespace System.Text internal void DeserializeEncoding(SerializationInfo info, StreamingContext context) { // Any info? - if (info==null) throw new ArgumentNullException("info"); + if (info==null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); // All versions have a code page @@ -314,7 +315,7 @@ namespace System.Text internal void SerializeEncoding(SerializationInfo info, StreamingContext context) { // Any Info? - if (info==null) throw new ArgumentNullException("info"); + if (info==null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); // These are new V2.0 Whidbey stuff @@ -344,7 +345,7 @@ namespace System.Text public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, byte[] bytes) { if (bytes==null) - throw new ArgumentNullException("bytes"); + throw new ArgumentNullException(nameof(bytes)); Contract.Ensures(Contract.Result<byte[]>() != null); return Convert(srcEncoding, dstEncoding, bytes, 0, bytes.Length); @@ -359,11 +360,11 @@ namespace System.Text public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, byte[] bytes, int index, int count) { if (srcEncoding == null || dstEncoding == null) { - throw new ArgumentNullException((srcEncoding == null ? "srcEncoding" : "dstEncoding"), + throw new ArgumentNullException((srcEncoding == null ? nameof(srcEncoding) : nameof(dstEncoding)), Environment.GetResourceString("ArgumentNull_Array")); } if (bytes == null) { - throw new ArgumentNullException("bytes", + throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); } Contract.Ensures(Contract.Result<byte[]>() != null); @@ -389,9 +390,6 @@ namespace System.Text private static volatile Hashtable encodings; #endif -#if !FEATURE_CORECLR - [System.Security.SecurityCritical] -#endif public static void RegisterProvider(EncodingProvider provider) { // Parameters validated inside EncodingProvider @@ -399,9 +397,6 @@ namespace System.Text } [Pure] -#if !FEATURE_CORECLR - [System.Security.SecuritySafeCritical] // auto-generated -#endif public static Encoding GetEncoding(int codepage) { Encoding result = EncodingProvider.GetEncodingFromProvider(codepage); @@ -416,7 +411,7 @@ namespace System.Text // if (codepage < 0 || codepage > 65535) { throw new ArgumentOutOfRangeException( - "codepage", Environment.GetResourceString("ArgumentOutOfRange_Range", + nameof(codepage), Environment.GetResourceString("ArgumentOutOfRange_Range", 0, 65535)); } @@ -443,7 +438,7 @@ namespace System.Text case CodePageNoThread: // 3 CP_THREAD_ACP case CodePageNoSymbol: // 42 CP_SYMBOL throw new ArgumentException(Environment.GetResourceString( - "Argument_CodepageNotSupported", codepage), "codepage"); + "Argument_CodepageNotSupported", codepage), nameof(codepage)); } #if FEATURE_CODEPAGES_FILE @@ -478,7 +473,7 @@ namespace System.Text result = GetEncodingCodePage(codepage) ?? GetEncodingRare(codepage); } - Contract.Assert(result != null, "result != null"); + Debug.Assert(result != null, "result != null"); encodings.Add(key, result); } @@ -516,10 +511,9 @@ namespace System.Text return fallbackEncoding; } #if FEATURE_CODEPAGES_FILE - [System.Security.SecurityCritical] // auto-generated private static Encoding GetEncodingRare(int codepage) { - Contract.Assert(codepage != 0 && codepage != 1200 && codepage != 1201 && codepage != 65001, + Debug.Assert(codepage != 0 && codepage != 1200 && codepage != 1201 && codepage != 65001, "[Encoding.GetEncodingRare]This code page (" + codepage + ") isn't supported by GetEncodingRare!"); Encoding result; switch (codepage) @@ -585,7 +579,6 @@ namespace System.Text return result; } - [System.Security.SecurityCritical] // auto-generated private static Encoding GetEncodingCodePage(int CodePage) { // Single Byte or Double Byte Code Page? (0 if not found) @@ -795,7 +788,7 @@ namespace System.Text throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); if (value == null) - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); Contract.EndContractBlock(); encoderFallback = value; @@ -817,7 +810,7 @@ namespace System.Text throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); if (value == null) - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); Contract.EndContractBlock(); decoderFallback = value; @@ -865,7 +858,7 @@ namespace System.Text { if (chars == null) { - throw new ArgumentNullException("chars", + throw new ArgumentNullException(nameof(chars), Environment.GetResourceString("ArgumentNull_Array")); } Contract.EndContractBlock(); @@ -876,8 +869,8 @@ namespace System.Text [Pure] public virtual int GetByteCount(String s) { - if (s==null) - throw new ArgumentNullException("s"); + if (s == null) + throw new ArgumentNullException(nameof(s)); Contract.EndContractBlock(); char[] chars = s.ToCharArray(); @@ -891,23 +884,50 @@ namespace System.Text [Pure] public abstract int GetByteCount(char[] chars, int index, int count); + // Returns the number of bytes required to encode a string range. + // + [Pure] + public int GetByteCount(string s, int index, int count) + { + if (s == null) + throw new ArgumentNullException(nameof(s), + Environment.GetResourceString("ArgumentNull_String")); + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index), + Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + if (count < 0) + throw new ArgumentOutOfRangeException(nameof(count), + Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + if (index > s.Length - count) + throw new ArgumentOutOfRangeException(nameof(index), + Environment.GetResourceString("ArgumentOutOfRange_IndexCount")); + Contract.EndContractBlock(); + + unsafe + { + fixed (char* pChar = s) + { + return GetByteCount(pChar + index, count); + } + } + } + // We expect this to be the workhorse for NLS encodings // unfortunately for existing overrides, it has to call the [] version, // which is really slow, so this method should be avoided if you're calling // a 3rd party encoding. [Pure] - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public virtual unsafe int GetByteCount(char* chars, int count) { // Validate input parameters if (chars == null) - throw new ArgumentNullException("chars", + throw new ArgumentNullException(nameof(chars), Environment.GetResourceString("ArgumentNull_Array")); if (count < 0) - throw new ArgumentOutOfRangeException("count", + throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -922,7 +942,6 @@ namespace System.Text // For NLS Encodings, workhorse takes an encoder (may be null) // Always validate parameters before calling internal version, which will only assert. - [System.Security.SecurityCritical] // auto-generated internal virtual unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder) { Contract.Requires(chars != null); @@ -939,7 +958,7 @@ namespace System.Text { if (chars == null) { - throw new ArgumentNullException("chars", + throw new ArgumentNullException(nameof(chars), Environment.GetResourceString("ArgumentNull_Array")); } Contract.EndContractBlock(); @@ -976,29 +995,67 @@ namespace System.Text public virtual byte[] GetBytes(String s) { if (s == null) - throw new ArgumentNullException("s", + throw new ArgumentNullException(nameof(s), Environment.GetResourceString("ArgumentNull_String")); Contract.EndContractBlock(); int byteCount = GetByteCount(s); byte[] bytes = new byte[byteCount]; int bytesReceived = GetBytes(s, 0, s.Length, bytes, 0); - Contract.Assert(byteCount == bytesReceived); + Debug.Assert(byteCount == bytesReceived); return bytes; } + // Returns a byte array containing the encoded representation of the given + // string range. + // + [Pure] + public byte[] GetBytes(string s, int index, int count) + { + if (s == null) + throw new ArgumentNullException(nameof(s), + Environment.GetResourceString("ArgumentNull_String")); + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index), + Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + if (count < 0) + throw new ArgumentOutOfRangeException(nameof(count), + Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + if (index > s.Length - count) + throw new ArgumentOutOfRangeException(nameof(index), + Environment.GetResourceString("ArgumentOutOfRange_IndexCount")); + Contract.EndContractBlock(); + + unsafe + { + fixed (char* pChar = s) + { + int byteCount = GetByteCount(pChar + index, count); + if (byteCount == 0) + return Array.Empty<byte>(); + + byte[] bytes = new byte[byteCount]; + fixed (byte* pBytes = &bytes[0]) + { + int bytesReceived = GetBytes(pChar + index, count, pBytes, byteCount); + Debug.Assert(byteCount == bytesReceived); + } + return bytes; + } + } + } + public virtual int GetBytes(String s, int charIndex, int charCount, byte[] bytes, int byteIndex) { - if (s==null) - throw new ArgumentNullException("s"); + if (s == null) + throw new ArgumentNullException(nameof(s)); Contract.EndContractBlock(); return GetBytes(s.ToCharArray(), charIndex, charCount, bytes, byteIndex); } // This is our internal workhorse // Always validate parameters before calling internal version, which will only assert. - [System.Security.SecurityCritical] // auto-generated internal virtual unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS encoder) { @@ -1022,7 +1079,6 @@ namespace System.Text // could easily overflow our output buffer. Therefore we do an extra test // when we copy the buffer so that we don't overflow byteCount either. - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public virtual unsafe int GetBytes(char* chars, int charCount, @@ -1030,11 +1086,11 @@ namespace System.Text { // Validate input parameters if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? "bytes" : "chars", + throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), Environment.GetResourceString("ArgumentNull_Array")); if (charCount < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException((charCount<0 ? "charCount" : "byteCount"), + throw new ArgumentOutOfRangeException((charCount<0 ? nameof(charCount) : nameof(byteCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -1051,7 +1107,7 @@ namespace System.Text // Do the work int result = GetBytes(arrChar, 0, charCount, arrByte, 0); - Contract.Assert(result <= byteCount, "[Encoding.GetBytes]Returned more bytes than we have space for"); + Debug.Assert(result <= byteCount, "[Encoding.GetBytes]Returned more bytes than we have space for"); // Copy the byte array // WARNING: We MUST make sure that we don't copy too many bytes. We can't @@ -1076,7 +1132,7 @@ namespace System.Text { if (bytes == null) { - throw new ArgumentNullException("bytes", + throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); } Contract.EndContractBlock(); @@ -1092,18 +1148,17 @@ namespace System.Text // We expect this to be the workhorse for NLS Encodings, but for existing // ones we need a working (if slow) default implimentation) [Pure] - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public virtual unsafe int GetCharCount(byte* bytes, int count) { // Validate input parameters if (bytes == null) - throw new ArgumentNullException("bytes", + throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); if (count < 0) - throw new ArgumentOutOfRangeException("count", + throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -1118,7 +1173,6 @@ namespace System.Text // This is our internal workhorse // Always validate parameters before calling internal version, which will only assert. - [System.Security.SecurityCritical] // auto-generated internal virtual unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder) { return GetCharCount(bytes, count); @@ -1132,7 +1186,7 @@ namespace System.Text { if (bytes == null) { - throw new ArgumentNullException("bytes", + throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); } Contract.EndContractBlock(); @@ -1181,7 +1235,6 @@ namespace System.Text // could easily overflow our output buffer. Therefore we do an extra test // when we copy the buffer so that we don't overflow charCount either. - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public virtual unsafe int GetChars(byte* bytes, int byteCount, @@ -1189,11 +1242,11 @@ namespace System.Text { // Validate input parameters if (chars == null || bytes == null) - throw new ArgumentNullException(chars == null ? "chars" : "bytes", + throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); if (byteCount < 0 || charCount < 0) - throw new ArgumentOutOfRangeException((byteCount<0 ? "byteCount" : "charCount"), + throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -1210,7 +1263,7 @@ namespace System.Text // Do the work int result = GetChars(arrByte, 0, byteCount, arrChar, 0); - Contract.Assert(result <= charCount, "[Encoding.GetChars]Returned more chars than we have space for"); + Debug.Assert(result <= charCount, "[Encoding.GetChars]Returned more chars than we have space for"); // Copy the char array // WARNING: We MUST make sure that we don't copy too many chars. We can't @@ -1230,7 +1283,6 @@ namespace System.Text // This is our internal workhorse // Always validate parameters before calling internal version, which will only assert. - [System.Security.SecurityCritical] // auto-generated internal virtual unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS decoder) { @@ -1238,16 +1290,15 @@ namespace System.Text } - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public unsafe string GetString(byte* bytes, int byteCount) { if (bytes == null) - throw new ArgumentNullException("bytes", Environment.GetResourceString("ArgumentNull_Array")); + throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); if (byteCount < 0) - throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); return String.CreateStringFromEncoding(bytes, byteCount, this); @@ -1306,7 +1357,6 @@ namespace System.Text return new DefaultDecoder(this); } - [System.Security.SecuritySafeCritical] private static Encoding CreateDefaultEncoding() { // defaultEncoding should be null if we get here, but we can't @@ -1391,7 +1441,7 @@ namespace System.Text public virtual String GetString(byte[] bytes) { if (bytes == null) - throw new ArgumentNullException("bytes", + throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); Contract.EndContractBlock(); @@ -1482,7 +1532,6 @@ namespace System.Text EncodingName, EncoderFallback.GetType()), "bytes"); } - [System.Security.SecurityCritical] // auto-generated internal void ThrowBytesOverflow(EncoderNLS encoder, bool nothingEncoded) { if (encoder == null || encoder.m_throwOnOverflow || nothingEncoded) @@ -1507,7 +1556,6 @@ namespace System.Text EncodingName, DecoderFallback.GetType()), "chars"); } - [System.Security.SecurityCritical] // auto-generated internal void ThrowCharsOverflow(DecoderNLS decoder, bool nothingDecoded) { if (decoder == null || decoder.m_throwOnOverflow || nothingDecoded) @@ -1541,7 +1589,7 @@ namespace System.Text // Constructor called by serialization, have to handle deserializing from Everett internal DefaultEncoder(SerializationInfo info, StreamingContext context) { - if (info==null) throw new ArgumentNullException("info"); + if (info==null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); // All we have is our encoding @@ -1558,7 +1606,6 @@ namespace System.Text } // Just get it from GetEncoding - [System.Security.SecurityCritical] // auto-generated public Object GetRealObject(StreamingContext context) { // upon deserialization since the DefaultEncoder implement IObjectReference the @@ -1584,11 +1631,10 @@ namespace System.Text } // ISerializable implementation, get data for this object - [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // Any info? - if (info==null) throw new ArgumentNullException("info"); + if (info==null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); // All we have is our encoding @@ -1608,7 +1654,6 @@ namespace System.Text return m_encoding.GetByteCount(chars, index, count); } - [System.Security.SecurityCritical] // auto-generated [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public unsafe override int GetByteCount(char* chars, int count, bool flush) { @@ -1641,7 +1686,6 @@ namespace System.Text return m_encoding.GetBytes(chars, charIndex, charCount, bytes, byteIndex); } - [System.Security.SecurityCritical] // auto-generated [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush) @@ -1667,7 +1711,7 @@ namespace System.Text internal DefaultDecoder(SerializationInfo info, StreamingContext context) { // Any info? - if (info==null) throw new ArgumentNullException("info"); + if (info==null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); // All we have is our encoding @@ -1684,7 +1728,6 @@ namespace System.Text } // Just get it from GetEncoding - [System.Security.SecurityCritical] // auto-generated public Object GetRealObject(StreamingContext context) { // upon deserialization since the DefaultEncoder implement IObjectReference the @@ -1705,11 +1748,10 @@ namespace System.Text } // ISerializable implementation, get data for this object - [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // Any info? - if (info==null) throw new ArgumentNullException("info"); + if (info==null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); // All we have is our encoding @@ -1733,7 +1775,6 @@ namespace System.Text return m_encoding.GetCharCount(bytes, index, count); } - [System.Security.SecurityCritical] // auto-generated [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public unsafe override int GetCharCount(byte* bytes, int count, bool flush) { @@ -1770,7 +1811,6 @@ namespace System.Text return m_encoding.GetChars(bytes, byteIndex, byteCount, chars, charIndex); } - [System.Security.SecurityCritical] // auto-generated [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) @@ -1782,24 +1822,17 @@ namespace System.Text internal class EncodingCharBuffer { - [SecurityCritical] unsafe char* chars; - [SecurityCritical] unsafe char* charStart; - [SecurityCritical] unsafe char* charEnd; int charCountResult = 0; Encoding enc; DecoderNLS decoder; - [SecurityCritical] unsafe byte* byteStart; - [SecurityCritical] unsafe byte* byteEnd; - [SecurityCritical] unsafe byte* bytes; DecoderFallbackBuffer fallbackBuffer; - [System.Security.SecurityCritical] // auto-generated internal unsafe EncodingCharBuffer(Encoding enc, DecoderNLS decoder, char* charStart, int charCount, byte* byteStart, int byteCount) { @@ -1821,12 +1854,11 @@ namespace System.Text // If we're getting chars or getting char count we don't expect to have // to remember fallbacks between calls (so it should be empty) - Contract.Assert(fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer.Remaining == 0, "[Encoding.EncodingCharBuffer.EncodingCharBuffer]Expected empty fallback buffer for getchars/charcount"); fallbackBuffer.InternalInitialize(bytes, charEnd); } - [System.Security.SecurityCritical] // auto-generated internal unsafe bool AddChar(char ch, int numBytes) { if (chars != null) @@ -1845,14 +1877,12 @@ namespace System.Text return true; } - [System.Security.SecurityCritical] // auto-generated internal unsafe bool AddChar(char ch) { return AddChar(ch,1); } - [System.Security.SecurityCritical] // auto-generated internal unsafe bool AddChar(char ch1, char ch2, int numBytes) { // Need room for 2 chars @@ -1866,7 +1896,6 @@ namespace System.Text return AddChar(ch1, numBytes) && AddChar(ch2, numBytes); } - [System.Security.SecurityCritical] // auto-generated internal unsafe void AdjustBytes(int count) { bytes += count; @@ -1874,7 +1903,6 @@ namespace System.Text internal unsafe bool MoreData { - [System.Security.SecurityCritical] // auto-generated get { return bytes < byteEnd; @@ -1882,7 +1910,6 @@ namespace System.Text } // Do we have count more bytes? - [System.Security.SecurityCritical] // auto-generated internal unsafe bool EvenMoreData(int count) { return (bytes <= byteEnd - count); @@ -1890,10 +1917,9 @@ namespace System.Text // GetNextByte shouldn't be called unless the caller's already checked more data or even more data, // but we'll double check just to make sure. - [System.Security.SecurityCritical] // auto-generated internal unsafe byte GetNextByte() { - Contract.Assert(bytes < byteEnd, "[EncodingCharBuffer.GetNextByte]Expected more date"); + Debug.Assert(bytes < byteEnd, "[EncodingCharBuffer.GetNextByte]Expected more date"); if (bytes >= byteEnd) return 0; return *(bytes++); @@ -1901,14 +1927,12 @@ namespace System.Text internal unsafe int BytesUsed { - [System.Security.SecurityCritical] // auto-generated get { return (int)(bytes - byteStart); } } - [System.Security.SecurityCritical] // auto-generated internal unsafe bool Fallback(byte fallbackByte) { // Build our buffer @@ -1918,7 +1942,6 @@ namespace System.Text return Fallback(byteBuffer); } - [System.Security.SecurityCritical] // auto-generated internal unsafe bool Fallback(byte byte1, byte byte2) { // Build our buffer @@ -1928,7 +1951,6 @@ namespace System.Text return Fallback(byteBuffer); } - [System.Security.SecurityCritical] // auto-generated internal unsafe bool Fallback(byte byte1, byte byte2, byte byte3, byte byte4) { // Build our buffer @@ -1938,7 +1960,6 @@ namespace System.Text return Fallback(byteBuffer); } - [System.Security.SecurityCritical] // auto-generated internal unsafe bool Fallback(byte[] byteBuffer) { // Do the fallback and add the data. @@ -1974,24 +1995,17 @@ namespace System.Text internal class EncodingByteBuffer { - [SecurityCritical] unsafe byte* bytes; - [SecurityCritical] unsafe byte* byteStart; - [SecurityCritical] unsafe byte* byteEnd; - [SecurityCritical] unsafe char* chars; - [SecurityCritical] unsafe char* charStart; - [SecurityCritical] unsafe char* charEnd; int byteCountResult = 0; Encoding enc; EncoderNLS encoder; internal EncoderFallbackBuffer fallbackBuffer; - [System.Security.SecurityCritical] // auto-generated internal unsafe EncodingByteBuffer(Encoding inEncoding, EncoderNLS inEncoder, byte* inByteStart, int inByteCount, char* inCharStart, int inCharCount) { @@ -2020,10 +2034,9 @@ namespace System.Text fallbackBuffer.InternalInitialize(chars, charEnd, encoder, bytes != null); } - [System.Security.SecurityCritical] // auto-generated internal unsafe bool AddByte(byte b, int moreBytesExpected) { - Contract.Assert(moreBytesExpected >= 0, "[EncodingByteBuffer.AddByte]expected non-negative moreBytesExpected"); + Debug.Assert(moreBytesExpected >= 0, "[EncodingByteBuffer.AddByte]expected non-negative moreBytesExpected"); if (bytes != null) { if (bytes >= byteEnd - moreBytesExpected) @@ -2039,31 +2052,26 @@ namespace System.Text return true; } - [System.Security.SecurityCritical] // auto-generated internal unsafe bool AddByte(byte b1) { return (AddByte(b1, 0)); } - [System.Security.SecurityCritical] // auto-generated internal unsafe bool AddByte(byte b1, byte b2) { return (AddByte(b1, b2, 0)); } - [System.Security.SecurityCritical] // auto-generated internal unsafe bool AddByte(byte b1, byte b2, int moreBytesExpected) { return (AddByte(b1, 1 + moreBytesExpected) && AddByte(b2, moreBytesExpected)); } - [System.Security.SecurityCritical] // auto-generated internal unsafe bool AddByte(byte b1, byte b2, byte b3) { return AddByte(b1, b2, b3, (int)0); } - [System.Security.SecurityCritical] // auto-generated internal unsafe bool AddByte(byte b1, byte b2, byte b3, int moreBytesExpected) { return (AddByte(b1, 2 + moreBytesExpected) && @@ -2071,7 +2079,6 @@ namespace System.Text AddByte(b3, moreBytesExpected)); } - [System.Security.SecurityCritical] // auto-generated internal unsafe bool AddByte(byte b1, byte b2, byte b3, byte b4) { return (AddByte(b1, 3) && @@ -2080,14 +2087,13 @@ namespace System.Text AddByte(b4, 0)); } - [System.Security.SecurityCritical] // auto-generated internal unsafe void MovePrevious(bool bThrow) { if (fallbackBuffer.bFallingBack) fallbackBuffer.MovePrevious(); // don't use last fallback else { - Contract.Assert(chars > charStart || + Debug.Assert(chars > charStart || ((bThrow == true) && (bytes == byteStart)), "[EncodingByteBuffer.MovePrevious]expected previous data or throw"); if (chars > charStart) @@ -2098,7 +2104,6 @@ namespace System.Text enc.ThrowBytesOverflow(encoder, bytes == byteStart); // Throw? (and reset fallback if not converting) } - [System.Security.SecurityCritical] // auto-generated internal unsafe bool Fallback(char charFallback) { // Do the fallback @@ -2107,7 +2112,6 @@ namespace System.Text internal unsafe bool MoreData { - [System.Security.SecurityCritical] // auto-generated get { // See if fallbackBuffer is not empty or if there's data left in chars buffer. @@ -2115,7 +2119,6 @@ namespace System.Text } } - [System.Security.SecurityCritical] // auto-generated internal unsafe char GetNextChar() { // See if there's something in our fallback buffer @@ -2133,7 +2136,6 @@ namespace System.Text internal unsafe int CharsUsed { - [System.Security.SecurityCritical] // auto-generated get { return (int)(chars - charStart); diff --git a/src/mscorlib/src/System/Text/EncodingForwarder.cs b/src/mscorlib/src/System/Text/EncodingForwarder.cs index d4bcf800e3..9a8dd26627 100644 --- a/src/mscorlib/src/System/Text/EncodingForwarder.cs +++ b/src/mscorlib/src/System/Text/EncodingForwarder.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security; @@ -31,23 +32,22 @@ namespace System.Text // the parameter, it will call the same method again, which will eventually // lead to a StackOverflowException. - [SecuritySafeCritical] public unsafe static int GetByteCount(Encoding encoding, char[] chars, int index, int count) { // Validate parameters - Contract.Assert(encoding != null); // this parameter should only be affected internally, so just do a debug check here + Debug.Assert(encoding != null); // this parameter should only be affected internally, so just do a debug check here if (chars == null) { - throw new ArgumentNullException("chars", Environment.GetResourceString("ArgumentNull_Array")); + throw new ArgumentNullException(nameof(chars), Environment.GetResourceString("ArgumentNull_Array")); } if (index < 0 || count < 0) { - throw new ArgumentOutOfRangeException(index < 0 ? "index" : "count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (chars.Length - index < count) { - throw new ArgumentOutOfRangeException("chars", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); + throw new ArgumentOutOfRangeException(nameof(chars), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); } Contract.EndContractBlock(); @@ -60,13 +60,12 @@ namespace System.Text return encoding.GetByteCount(pChars + index, count, encoder: null); } - [SecuritySafeCritical] public unsafe static int GetByteCount(Encoding encoding, string s) { - Contract.Assert(encoding != null); + Debug.Assert(encoding != null); if (s == null) { - string paramName = encoding is ASCIIEncoding ? "chars" : "s"; // ASCIIEncoding calls the string chars + string paramName = encoding is ASCIIEncoding ? "chars" : nameof(s); // ASCIIEncoding calls the string chars // UTF8Encoding does this as well, but it originally threw an ArgumentNull for "s" so don't check for that throw new ArgumentNullException(paramName); } @@ -84,17 +83,16 @@ namespace System.Text return encoding.GetByteCount(pChars, s.Length, encoder: null); } - [SecurityCritical] public unsafe static int GetByteCount(Encoding encoding, char* chars, int count) { - Contract.Assert(encoding != null); + Debug.Assert(encoding != null); if (chars == null) { - throw new ArgumentNullException("chars", Environment.GetResourceString("ArgumentNull_Array")); + throw new ArgumentNullException(nameof(chars), Environment.GetResourceString("ArgumentNull_Array")); } if (count < 0) { - throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); @@ -102,28 +100,27 @@ namespace System.Text return encoding.GetByteCount(chars, count, encoder: null); } - [SecuritySafeCritical] public unsafe static int GetBytes(Encoding encoding, string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { - Contract.Assert(encoding != null); + Debug.Assert(encoding != null); if (s == null || bytes == null) { - string stringName = encoding is ASCIIEncoding ? "chars" : "s"; // ASCIIEncoding calls the first parameter chars - throw new ArgumentNullException(s == null ? stringName : "bytes", Environment.GetResourceString("ArgumentNull_Array")); + string stringName = encoding is ASCIIEncoding ? "chars" : nameof(s); // ASCIIEncoding calls the first parameter chars + throw new ArgumentNullException(s == null ? stringName : nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); } if (charIndex < 0 || charCount < 0) { - throw new ArgumentOutOfRangeException(charIndex < 0 ? "charIndex" : "charCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (s.Length - charIndex < charCount) { - string stringName = encoding is ASCIIEncoding ? "chars" : "s"; // ASCIIEncoding calls the first parameter chars + string stringName = encoding is ASCIIEncoding ? "chars" : nameof(s); // ASCIIEncoding calls the first parameter chars // Duplicate the above check since we don't want the overhead of a type check on the general path throw new ArgumentOutOfRangeException(stringName, Environment.GetResourceString("ArgumentOutOfRange_IndexCount")); } if (byteIndex < 0 || byteIndex > bytes.Length) { - throw new ArgumentOutOfRangeException("byteIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(byteIndex), Environment.GetResourceString("ArgumentOutOfRange_Index")); } Contract.EndContractBlock(); @@ -139,25 +136,24 @@ namespace System.Text } } - [SecuritySafeCritical] public unsafe static int GetBytes(Encoding encoding, char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { - Contract.Assert(encoding != null); + Debug.Assert(encoding != null); if (chars == null || bytes == null) { - throw new ArgumentNullException(chars == null ? "chars" : "bytes", Environment.GetResourceString("ArgumentNull_Array")); + throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); } if (charIndex < 0 || charCount < 0) { - throw new ArgumentOutOfRangeException(charIndex < 0 ? "charIndex" : "charCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (chars.Length - charIndex < charCount) { - throw new ArgumentOutOfRangeException("chars", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); + throw new ArgumentOutOfRangeException(nameof(chars), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); } if (byteIndex < 0 || byteIndex > bytes.Length) { - throw new ArgumentOutOfRangeException("byteIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(byteIndex), Environment.GetResourceString("ArgumentOutOfRange_Index")); } Contract.EndContractBlock(); @@ -180,38 +176,36 @@ namespace System.Text } } - [SecurityCritical] public unsafe static int GetBytes(Encoding encoding, char* chars, int charCount, byte* bytes, int byteCount) { - Contract.Assert(encoding != null); + Debug.Assert(encoding != null); if (bytes == null || chars == null) { - throw new ArgumentNullException(bytes == null ? "bytes" : "chars", Environment.GetResourceString("ArgumentNull_Array")); + throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), Environment.GetResourceString("ArgumentNull_Array")); } if (charCount < 0 || byteCount < 0) { - throw new ArgumentOutOfRangeException(charCount < 0 ? "charCount" : "byteCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); return encoding.GetBytes(chars, charCount, bytes, byteCount, encoder: null); } - [SecuritySafeCritical] public unsafe static int GetCharCount(Encoding encoding, byte[] bytes, int index, int count) { - Contract.Assert(encoding != null); + Debug.Assert(encoding != null); if (bytes == null) { - throw new ArgumentNullException("bytes", Environment.GetResourceString("ArgumentNull_Array")); + throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); } if (index < 0 || count < 0) { - throw new ArgumentOutOfRangeException(index < 0 ? "index" : "count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (bytes.Length - index < count) { - throw new ArgumentOutOfRangeException("bytes", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); + throw new ArgumentOutOfRangeException(nameof(bytes), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); } Contract.EndContractBlock(); @@ -224,42 +218,40 @@ namespace System.Text return encoding.GetCharCount(pBytes + index, count, decoder: null); } - [SecurityCritical] public unsafe static int GetCharCount(Encoding encoding, byte* bytes, int count) { - Contract.Assert(encoding != null); + Debug.Assert(encoding != null); if (bytes == null) { - throw new ArgumentNullException("bytes", Environment.GetResourceString("ArgumentNull_Array")); + throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); } if (count < 0) { - throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); return encoding.GetCharCount(bytes, count, decoder: null); } - [SecuritySafeCritical] public unsafe static int GetChars(Encoding encoding, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { - Contract.Assert(encoding != null); + Debug.Assert(encoding != null); if (bytes == null || chars == null) { - throw new ArgumentNullException(bytes == null ? "bytes" : "chars", Environment.GetResourceString("ArgumentNull_Array")); + throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), Environment.GetResourceString("ArgumentNull_Array")); } if (byteIndex < 0 || byteCount < 0) { - throw new ArgumentOutOfRangeException(byteIndex < 0 ? "byteIndex" : "byteCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (bytes.Length - byteIndex < byteCount) { - throw new ArgumentOutOfRangeException("bytes", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); + throw new ArgumentOutOfRangeException(nameof(bytes), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); } if (charIndex < 0 || charIndex > chars.Length) { - throw new ArgumentOutOfRangeException("charIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(charIndex), Environment.GetResourceString("ArgumentOutOfRange_Index")); } Contract.EndContractBlock(); @@ -280,42 +272,40 @@ namespace System.Text } } - [SecurityCritical] public unsafe static int GetChars(Encoding encoding, byte* bytes, int byteCount, char* chars, int charCount) { - Contract.Assert(encoding != null); + Debug.Assert(encoding != null); if (bytes == null || chars == null) { - throw new ArgumentNullException(bytes == null ? "bytes" : "chars", Environment.GetResourceString("ArgumentNull_Array")); + throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), Environment.GetResourceString("ArgumentNull_Array")); } if (charCount < 0 || byteCount < 0) { - throw new ArgumentOutOfRangeException(charCount < 0 ? "charCount" : "byteCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); return encoding.GetChars(bytes, byteCount, chars, charCount, decoder: null); } - [SecuritySafeCritical] public unsafe static string GetString(Encoding encoding, byte[] bytes, int index, int count) { - Contract.Assert(encoding != null); + Debug.Assert(encoding != null); if (bytes == null) { - throw new ArgumentNullException("bytes", Environment.GetResourceString("ArgumentNull_Array")); + throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); } if (index < 0 || count < 0) { // ASCIIEncoding has different names for its parameters here (byteIndex, byteCount) bool ascii = encoding is ASCIIEncoding; - string indexName = ascii ? "byteIndex" : "index"; - string countName = ascii ? "byteCount" : "count"; + string indexName = ascii ? "byteIndex" : nameof(index); + string countName = ascii ? "byteCount" : nameof(count); throw new ArgumentOutOfRangeException(index < 0 ? indexName : countName, Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (bytes.Length - index < count) { - throw new ArgumentOutOfRangeException("bytes", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); + throw new ArgumentOutOfRangeException(nameof(bytes), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); } Contract.EndContractBlock(); diff --git a/src/mscorlib/src/System/Text/EncodingNLS.cs b/src/mscorlib/src/System/Text/EncodingNLS.cs index d670d6daa7..fbddf37e88 100644 --- a/src/mscorlib/src/System/Text/EncodingNLS.cs +++ b/src/mscorlib/src/System/Text/EncodingNLS.cs @@ -50,7 +50,6 @@ namespace System.Text return EncodingForwarder.GetByteCount(this, s); } - [System.Security.SecurityCritical] // auto-generated public override unsafe int GetByteCount(char* chars, int count) { return EncodingForwarder.GetByteCount(this, chars, count); @@ -77,7 +76,6 @@ namespace System.Text return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex); } - [System.Security.SecurityCritical] // auto-generated public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { return EncodingForwarder.GetBytes(this, chars, charCount, bytes, byteCount); @@ -91,7 +89,6 @@ namespace System.Text return EncodingForwarder.GetCharCount(this, bytes, index, count); } - [System.Security.SecurityCritical] // auto-generated public override unsafe int GetCharCount(byte* bytes, int count) { return EncodingForwarder.GetCharCount(this, bytes, count); @@ -103,7 +100,6 @@ namespace System.Text return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex); } - [System.Security.SecurityCritical] // auto-generated public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { return EncodingForwarder.GetChars(this, bytes, byteCount, chars, charCount); diff --git a/src/mscorlib/src/System/Text/EncodingProvider.cs b/src/mscorlib/src/System/Text/EncodingProvider.cs index b1dea2cd3c..a7f745a753 100644 --- a/src/mscorlib/src/System/Text/EncodingProvider.cs +++ b/src/mscorlib/src/System/Text/EncodingProvider.cs @@ -45,7 +45,7 @@ namespace System.Text internal static void AddProvider(EncodingProvider provider) { if (provider == null) - throw new ArgumentNullException("provider"); + throw new ArgumentNullException(nameof(provider)); lock (s_InternalSyncObject) { diff --git a/src/mscorlib/src/System/Text/GB18030Encoding.cs b/src/mscorlib/src/System/Text/GB18030Encoding.cs index 98746fcdb0..8ed52a6ab8 100644 --- a/src/mscorlib/src/System/Text/GB18030Encoding.cs +++ b/src/mscorlib/src/System/Text/GB18030Encoding.cs @@ -85,6 +85,7 @@ namespace System.Text { using System; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Text; using System.Runtime.InteropServices; @@ -107,10 +108,8 @@ namespace System.Text // This is the table of 4 byte conversions. private const int GBLast4ByteCode = 0x99FB; [NonSerialized] - [SecurityCritical] unsafe internal char* map4BytesToUnicode = null; // new char[GBLast4ByteCode + 1]; // Need to map all 4 byte sequences to Unicode [NonSerialized] - [SecurityCritical] unsafe internal byte* mapUnicodeTo4BytesFlags = null; // new byte[0x10000 / 8]; // Need 1 bit for each code point to say if its 4 byte or not private const int GB18030 = 54936; @@ -120,37 +119,33 @@ namespace System.Text private const int GBLastSurrogateOffset = 0x12E247; // GBE3329A35 // We have to load the 936 code page tables, so impersonate 936 as our base - [System.Security.SecurityCritical] // auto-generated internal GB18030Encoding() : base(GB18030, 936) { } // Constructor called by serialization. - [System.Security.SecurityCritical] // auto-generated internal GB18030Encoding(SerializationInfo info, StreamingContext context) : base(GB18030, 936) { // Set up our base, also throws if info was empty DeserializeEncoding(info, context); - Contract.Assert(info!=null, "[GB18030Encoding(Serialization...)] Expected null info to throw"); + Debug.Assert(info!=null, "[GB18030Encoding(Serialization...)] Expected null info to throw"); // Already build our code page, fallbacks & read only, so we're good to go! } // ISerializable implementation - [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // Make sure to get the base stuff too This throws if info is null SerializeEncoding(info, context); - Contract.Assert(info!=null, "[GB18030.GetObjectData] Expected null info to throw"); + Debug.Assert(info!=null, "[GB18030.GetObjectData] Expected null info to throw"); // Everett doesn't need more than the basics } // This loads our base 936 code page and then applys the changes from the tableUnicodeToGBDiffs table. // See table comments for table format. - [System.Security.SecurityCritical] // auto-generated protected override unsafe void LoadManagedCodePage() { // Use base code page loading algorithm. @@ -199,7 +194,7 @@ namespace System.Text // It was GB 18030 4 byte data, next <data> characters are 4 byte sequences. while (data > 0) { - Contract.Assert(count4Byte <= GBLast4ByteCode, + Debug.Assert(count4Byte <= GBLast4ByteCode, "[GB18030Encoding.LoadManagedCodePage] Found too many 4 byte codes in data table."); // Set the 4 byte -> Unicode value @@ -217,11 +212,11 @@ namespace System.Text } // unicodeCount should've wrapped back to 0 - Contract.Assert(unicodeCount == 0, + Debug.Assert(unicodeCount == 0, "[GB18030Encoding.LoadManagedCodePage] Expected unicodeCount to wrap around to 0 as all chars were processed"); // We should've read in GBLast4ByteCode 4 byte sequences - Contract.Assert(count4Byte == GBLast4ByteCode + 1, + Debug.Assert(count4Byte == GBLast4ByteCode + 1, "[GB18030Encoding.LoadManagedCodePage] Expected 0x99FB to be last 4 byte offset, found 0x" + count4Byte.ToString("X4", CultureInfo.InvariantCulture)); // Need to flag ourselves saying we've built this CP. @@ -238,7 +233,6 @@ namespace System.Text // Is4Byte // Checks the 4 byte table and returns true if this is a 4 byte code. // Its a 4 byte code if the flag is set in mapUnicodeTo4BytesFlags - [System.Security.SecurityCritical] // auto-generated internal unsafe bool Is4Byte(char charTest) { // See what kind it is @@ -247,26 +241,24 @@ namespace System.Text } // GetByteCount - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder) { // Just call GetBytes() with null bytes return GetBytes(chars, count, null, 0, encoder); } - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already // We'll allow null bytes as a count -// Contract.Assert(bytes != null, "[GB18030Encoding.GetBytes]bytes is null"); - Contract.Assert(byteCount >= 0, "[GB18030Encoding.GetBytes]byteCount is negative"); - Contract.Assert(chars != null, "[GB18030Encoding.GetBytes]chars is null"); - Contract.Assert(charCount >= 0, "[GB18030Encoding.GetBytes]charCount is negative"); +// Debug.Assert(bytes != null, "[GB18030Encoding.GetBytes]bytes is null"); + Debug.Assert(byteCount >= 0, "[GB18030Encoding.GetBytes]byteCount is negative"); + Debug.Assert(chars != null, "[GB18030Encoding.GetBytes]chars is null"); + Debug.Assert(charCount >= 0, "[GB18030Encoding.GetBytes]charCount is negative"); // Assert because we shouldn't be able to have a null encoder. - Contract.Assert(encoderFallback != null, "[GB18030Encoding.GetBytes]Attempting to use null encoder fallback"); + Debug.Assert(encoderFallback != null, "[GB18030Encoding.GetBytes]Attempting to use null encoder fallback"); // Get any left over characters char charLeftOver = (char)0; @@ -289,7 +281,7 @@ namespace System.Text // Have to check for charLeftOver if (charLeftOver != 0) { - Contract.Assert(Char.IsHighSurrogate(charLeftOver), + Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[GB18030Encoding.GetBytes] leftover character should be high surrogate, not 0x" + ((int)charLeftOver).ToString("X4", CultureInfo.InvariantCulture)); // If our next char isn't a low surrogate, then we need to do fallback. @@ -319,7 +311,7 @@ namespace System.Text offset /= 0x7e; byte byte2 = (byte)((offset % 0x0a) + 0x30); offset /= 0x0a; - Contract.Assert(offset < 0x6f, + Debug.Assert(offset < 0x6f, "[GB18030Encoding.GetBytes](1) Expected offset < 0x6f, not 0x" + offset.ToString("X2", CultureInfo.InvariantCulture)); charLeftOver = (char)0; @@ -369,7 +361,7 @@ namespace System.Text iBytes /= 0x7e; byte byte2 = (byte)((iBytes % 0x0a) + 0x30); iBytes /= 0x0a; - Contract.Assert(iBytes < 0x7e, + Debug.Assert(iBytes < 0x7e, "[GB18030Encoding.GetBytes]Expected iBytes < 0x7e, not 0x" + iBytes.ToString("X2", CultureInfo.InvariantCulture)); if (!buffer.AddByte((byte)(iBytes + 0x81), byte2, byte3, byte4)) break; @@ -436,23 +428,21 @@ namespace System.Text } // This is internal and called by something else, - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) { // Just call GetChars() with null chars to count return GetChars(bytes, count, null, 0, baseDecoder); } - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS baseDecoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already // We'll allow null chars as a count - Contract.Assert(bytes != null, "[GB18030Encoding.GetChars]bytes is null"); - Contract.Assert(byteCount >= 0, "[GB18030Encoding.GetChars]byteCount is negative"); -// Contract.Assert(chars != null, "[GB18030Encoding.GetChars]chars is null"); - Contract.Assert(charCount >= 0, "[GB18030Encoding.GetChars]charCount is negative"); + Debug.Assert(bytes != null, "[GB18030Encoding.GetChars]bytes is null"); + Debug.Assert(byteCount >= 0, "[GB18030Encoding.GetChars]byteCount is negative"); +// Debug.Assert(chars != null, "[GB18030Encoding.GetChars]chars is null"); + Debug.Assert(charCount >= 0, "[GB18030Encoding.GetChars]charCount is negative"); // Fix our decoder GB18030Decoder decoder = (GB18030Decoder)baseDecoder; @@ -793,7 +783,7 @@ namespace System.Text public override int GetMaxByteCount(int charCount) { if (charCount < 0) - throw new ArgumentOutOfRangeException("charCount", + throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -807,7 +797,7 @@ namespace System.Text byteCount *= 4; if (byteCount > 0x7fffffff) - throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); + throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); return (int)byteCount; } @@ -815,7 +805,7 @@ namespace System.Text public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) - throw new ArgumentOutOfRangeException("byteCount", + throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -828,7 +818,7 @@ namespace System.Text charCount *= DecoderFallback.MaxCharCount; if (charCount > 0x7fffffff) - throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow")); + throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow")); return (int)charCount; } @@ -852,11 +842,10 @@ namespace System.Text } // Constructor called by serialization, have to handle deserializing from Everett - [System.Security.SecurityCritical] // auto-generated internal GB18030Decoder(SerializationInfo info, StreamingContext context) { // Any info? - if (info==null) throw new ArgumentNullException("info"); + if (info==null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); try @@ -879,11 +868,10 @@ namespace System.Text } // ISerializable implementation, get data for this object - [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // Any info? - if (info==null) throw new ArgumentNullException("info"); + if (info==null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); // Save Whidbey data diff --git a/src/mscorlib/src/System/Text/ISCIIEncoding.cs b/src/mscorlib/src/System/Text/ISCIIEncoding.cs index 89d9c9953a..751b8217c0 100644 --- a/src/mscorlib/src/System/Text/ISCIIEncoding.cs +++ b/src/mscorlib/src/System/Text/ISCIIEncoding.cs @@ -9,6 +9,7 @@ namespace System.Text { using System; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.Serialization; @@ -72,13 +73,13 @@ namespace System.Text defaultCodePage = codePage - 57000; // Legal windows code pages are between Devanagari and Punjabi - Contract.Assert(defaultCodePage >= CodeDevanagari && defaultCodePage <= CodePunjabi, + Debug.Assert(defaultCodePage >= CodeDevanagari && defaultCodePage <= CodePunjabi, "[ISCIIEncoding] Code page (" + codePage + " isn't supported by ISCIIEncoding!"); // This shouldn't really be possible if (defaultCodePage < CodeDevanagari || defaultCodePage > CodePunjabi) throw new ArgumentException(Environment.GetResourceString( - "Argument_CodepageNotSupported", codePage), "codePage"); + "Argument_CodepageNotSupported", codePage), nameof(codePage)); } // Constructor called by serialization. @@ -86,17 +87,16 @@ namespace System.Text { // Actually this can't ever get called, MLangCodePageEncoding is our proxy // (In Everett this was done by MLang) - Contract.Assert(false, "Didn't expect to make it to ISCIIEncoding serialization constructor"); + Debug.Assert(false, "Didn't expect to make it to ISCIIEncoding serialization constructor"); throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException")); } // ISerializable implementation - [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // Make sure to get the base stuff too This throws if info is null SerializeEncoding(info, context); - Contract.Assert(info!=null, "[ISCIIEncoding.GetObjectData] Expected null info to throw"); + Debug.Assert(info!=null, "[ISCIIEncoding.GetObjectData] Expected null info to throw"); // Just need Everett MLangCodePageEncoding maxCharSize info.AddValue("m_maxByteSize", 2); @@ -111,7 +111,7 @@ namespace System.Text public override int GetMaxByteCount(int charCount) { if (charCount < 0) - throw new ArgumentOutOfRangeException("charCount", + throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -125,7 +125,7 @@ namespace System.Text byteCount *= 4; if (byteCount > 0x7fffffff) - throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); + throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); return (int)byteCount; } @@ -135,7 +135,7 @@ namespace System.Text public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) - throw new ArgumentOutOfRangeException("byteCount", + throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -149,13 +149,12 @@ namespace System.Text charCount *= DecoderFallback.MaxCharCount; if (charCount > 0x7fffffff) - throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow")); + throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow")); return (int)charCount; } // Our workhorse version - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS baseEncoder) { // Use null pointer to ask GetBytes for count @@ -163,15 +162,14 @@ namespace System.Text } // Workhorse - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetBytes(char *chars, int charCount, byte* bytes, int byteCount, EncoderNLS baseEncoder) { // Allow null bytes for counting - Contract.Assert(chars != null, "[ISCIIEncoding.GetBytes]chars!=null"); -// Contract.Assert(bytes != null, "[ISCIIEncoding.GetBytes]bytes!=null"); - Contract.Assert(charCount >=0, "[ISCIIEncoding.GetBytes]charCount >=0"); - Contract.Assert(byteCount >=0, "[ISCIIEncoding.GetBytes]byteCount >=0"); + Debug.Assert(chars != null, "[ISCIIEncoding.GetBytes]chars!=null"); +// Debug.Assert(bytes != null, "[ISCIIEncoding.GetBytes]bytes!=null"); + Debug.Assert(charCount >=0, "[ISCIIEncoding.GetBytes]charCount >=0"); + Debug.Assert(byteCount >=0, "[ISCIIEncoding.GetBytes]byteCount >=0"); // Need the ISCII Encoder ISCIIEncoder encoder = (ISCIIEncoder) baseEncoder; @@ -268,7 +266,7 @@ namespace System.Text // See if our code page ("font" in ISCII spec) has to change // (This if doesn't add character, just changes character set) - Contract.Assert(indicScript!=0, "[ISCIIEncoding.GetBytes]expected an indic script value"); + Debug.Assert(indicScript!=0, "[ISCIIEncoding.GetBytes]expected an indic script value"); if (indicScript != currentCodePage) { // It changed, spit out the ATR @@ -279,7 +277,7 @@ namespace System.Text currentCodePage = indicScript; // We only know how to map from Unicode to pages from Devanagari to Punjabi (2 to 11) - Contract.Assert(currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi, + Debug.Assert(currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi, "[ISCIIEncoding.GetBytes]Code page (" + currentCodePage + " shouldn't appear in ISCII from Unicode table!"); } @@ -294,7 +292,7 @@ namespace System.Text if (indicTwoBytes != 0) { // This one needs another byte - Contract.Assert((indicTwoBytes >> 12) > 0 && (indicTwoBytes >> 12) <= 3, + Debug.Assert((indicTwoBytes >> 12) > 0 && (indicTwoBytes >> 12) <= 3, "[ISCIIEncoding.GetBytes]Expected indicTwoBytes from 1-3, not " + (indicTwoBytes >> 12)); // Already did buffer checking, but... @@ -341,7 +339,6 @@ namespace System.Text } // Workhorse - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) { // Just call GetChars with null chars saying we want count @@ -354,16 +351,15 @@ namespace System.Text // Devenagari F0, B8 -> \u0952 // Devenagari F0, BF -> \u0970 // Some characters followed by E9 become a different character instead. - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS baseDecoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already // Allow null chars for counting - Contract.Assert(bytes != null, "[ISCIIEncoding.GetChars]bytes is null"); - Contract.Assert(byteCount >= 0, "[ISCIIEncoding.GetChars]byteCount is negative"); -// Contract.Assert(chars != null, "[ISCIIEncoding.GetChars]chars is null"); - Contract.Assert(charCount >= 0, "[ISCIIEncoding.GetChars]charCount is negative"); + Debug.Assert(bytes != null, "[ISCIIEncoding.GetChars]bytes is null"); + Debug.Assert(byteCount >= 0, "[ISCIIEncoding.GetChars]byteCount is negative"); +// Debug.Assert(chars != null, "[ISCIIEncoding.GetChars]chars is null"); + Debug.Assert(charCount >= 0, "[ISCIIEncoding.GetChars]charCount is negative"); // Need the ISCII Decoder ISCIIDecoder decoder = (ISCIIDecoder) baseDecoder; @@ -395,7 +391,7 @@ namespace System.Text // Get our current code page index (some code pages are dups) int currentCodePageIndex = -1; - Contract.Assert(currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi, + Debug.Assert(currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi, "[ISCIIEncoding.GetChars]Decoder code page must be >= Devanagari and <= Punjabi, not " + currentCodePage); if (currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi) @@ -415,7 +411,7 @@ namespace System.Text bLastSpecial = false; // One and only one of our flags should be set - Contract.Assert(((bLastVirama ? 1 : 0) + (bLastATR ? 1 : 0) + + Debug.Assert(((bLastVirama ? 1 : 0) + (bLastATR ? 1 : 0) + (bLastDevenagariStressAbbr ? 1 : 0) + ((cLastCharForNextNukta > 0) ? 1 : 0)) == 1, String.Format(CultureInfo.InvariantCulture, @@ -476,10 +472,10 @@ namespace System.Text bLastATR = false; // we know we can't have any of these other modes - Contract.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in bLastATR mode"); - Contract.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in bLastATR mode"); - Contract.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastATR mode"); - Contract.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastATR mode"); + Debug.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in bLastATR mode"); + Debug.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in bLastATR mode"); + Debug.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastATR mode"); + Debug.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastATR mode"); // Keep processing this byte } @@ -508,10 +504,10 @@ namespace System.Text bLastVirama = false; // We know we can't have any of these other modes - Contract.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in bLastVirama mode"); - Contract.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in bLastVirama mode"); - Contract.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastVirama mode"); - Contract.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastVirama mode"); + Debug.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in bLastVirama mode"); + Debug.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in bLastVirama mode"); + Debug.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastVirama mode"); + Debug.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastVirama mode"); } else if (bLastDevenagariStressAbbr) { @@ -544,15 +540,15 @@ namespace System.Text // (last character was added when mode was set) bLastDevenagariStressAbbr = false; - Contract.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in bLastDevenagariStressAbbr mode"); - Contract.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in bLastDevenagariStressAbbr mode"); - Contract.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastDevenagariStressAbbr mode"); - Contract.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastDevenagariStressAbbr mode"); + Debug.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in bLastDevenagariStressAbbr mode"); + Debug.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in bLastDevenagariStressAbbr mode"); + Debug.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastDevenagariStressAbbr mode"); + Debug.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastDevenagariStressAbbr mode"); } else { // We were checking for next char being a nukta - Contract.Assert(cLastCharForNextNukta > 0 && cLastCharForNoNextNukta > 0, + Debug.Assert(cLastCharForNextNukta > 0 && cLastCharForNoNextNukta > 0, "[ISCIIEncoding.GetChars]No other special case found, but cLastCharFor(No)NextNukta variable(s) aren't set."); // We'll either add combined char or last char @@ -574,14 +570,14 @@ namespace System.Text // Keep processing this byte, turn off mode. cLastCharForNextNukta = cLastCharForNoNextNukta = '\0'; - Contract.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in cLastCharForNextNukta mode"); - Contract.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in cLastCharForNextNukta mode"); - Contract.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in cLastCharForNextNukta mode"); + Debug.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in cLastCharForNextNukta mode"); + Debug.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in cLastCharForNextNukta mode"); + Debug.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in cLastCharForNextNukta mode"); } } // Now bLastSpecial should be false and all flags false. - Contract.Assert (!bLastSpecial && !bLastDevenagariStressAbbr && !bLastVirama && !bLastATR && + Debug.Assert (!bLastSpecial && !bLastDevenagariStressAbbr && !bLastVirama && !bLastATR && cLastCharForNextNukta == '\0', "[ISCIIEncoding.GetChars]No special state for last code point should exist at this point."); @@ -600,7 +596,7 @@ namespace System.Text continue; } - Contract.Assert (currentCodePageIndex != -1, "[ISCIIEncoding.GetChars]Expected valid currentCodePageIndex != -1"); + Debug.Assert (currentCodePageIndex != -1, "[ISCIIEncoding.GetChars]Expected valid currentCodePageIndex != -1"); char ch = IndicMapping[currentCodePageIndex, 0, b - MultiByteBegin]; char cAlt = IndicMapping[currentCodePageIndex, 1, b - MultiByteBegin]; @@ -646,7 +642,7 @@ namespace System.Text } // We must be the Devenagari special case for F0, B8 & F0, BF - Contract.Assert(currentCodePage == CodeDevanagari && b == DevenagariExt, + Debug.Assert(currentCodePage == CodeDevanagari && b == DevenagariExt, String.Format(CultureInfo.InvariantCulture, "[ISCIIEncoding.GetChars] Devenagari special case must {0} not {1} or in Devanagari code page {2} not {3}.", DevenagariExt, b, CodeDevanagari, currentCodePage)); @@ -701,7 +697,7 @@ namespace System.Text cLastCharForNoNextNukta != '\0' || bLastATR || bLastDevenagariStressAbbr) { // Either not flushing or had state (from convert) - Contract.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow, + Debug.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow, "[ISCIIEncoding.GetChars]Expected no state or not converting or not flushing"); decoder.currentCodePage = currentCodePage; decoder.bLastVirama = bLastVirama; diff --git a/src/mscorlib/src/System/Text/ISO2022Encoding.cs b/src/mscorlib/src/System/Text/ISO2022Encoding.cs index fe57e7cc57..fca579fe56 100644 --- a/src/mscorlib/src/System/Text/ISO2022Encoding.cs +++ b/src/mscorlib/src/System/Text/ISO2022Encoding.cs @@ -28,6 +28,7 @@ namespace System.Text { using System.Globalization; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Text; using System.Runtime.InteropServices; @@ -53,7 +54,6 @@ namespace System.Text // We have to load the 936 code page tables, so impersonate 936 as our base // This pretends to be other code pages as far as memory sections are concerned. - [System.Security.SecurityCritical] // auto-generated internal ISO2022Encoding(int codePage) : base(codePage, tableBaseCodePages[codePage % 10]) { this.m_bUseMlangTypeForSerialization = true; @@ -61,11 +61,10 @@ namespace System.Text // Constructor called by serialization. // Note: We use the base GetObjectData however - [System.Security.SecurityCritical] // auto-generated internal ISO2022Encoding(SerializationInfo info, StreamingContext context) : base(info, context) { // Actually this can't ever get called, CodePageEncoding is our proxy - Contract.Assert(false, "Didn't expect to make it to DBCSCodePageEncoding serialization constructor"); + Debug.Assert(false, "Didn't expect to make it to DBCSCodePageEncoding serialization constructor"); throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException")); } @@ -102,7 +101,6 @@ namespace System.Text ModeNOOP = -3 } - [System.Security.SecurityCritical] // auto-generated protected unsafe override String GetMemorySectionName() { int iUseCodePage = this.bFlagDataTable ? dataTableCodePage : CodePage; @@ -123,7 +121,7 @@ namespace System.Text strFormat = "CodePage_{0}_{1}_{2}_{3}_{4}_HZ"; break; default: - Contract.Assert(false, "[ISO2022Encoding.GetMemorySectionName] Don't expect to get here for code page " + this.CodePage); + Debug.Assert(false, "[ISO2022Encoding.GetMemorySectionName] Don't expect to get here for code page " + this.CodePage); strFormat = "CodePage_{0}_{1}_{2}_{3}_{4}"; break; } @@ -263,28 +261,26 @@ namespace System.Text } // GetByteCount - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS baseEncoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(count >= 0, "[ISO2022Encoding.GetByteCount]count is negative"); - Contract.Assert(chars != null, "[ISO2022Encoding.GetByteCount]chars is null"); + Debug.Assert(count >= 0, "[ISO2022Encoding.GetByteCount]count is negative"); + Debug.Assert(chars != null, "[ISO2022Encoding.GetByteCount]chars is null"); // Just call GetBytes with null byte* to get count return GetBytes(chars, count, null, 0, baseEncoder); } - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS baseEncoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(chars != null, "[ISO2022Encoding.GetBytes]chars is null"); - Contract.Assert(byteCount >= 0, "[ISO2022Encoding.GetBytes]byteCount is negative"); - Contract.Assert(charCount >= 0, "[ISO2022Encoding.GetBytes]charCount is negative"); + Debug.Assert(chars != null, "[ISO2022Encoding.GetBytes]chars is null"); + Debug.Assert(byteCount >= 0, "[ISO2022Encoding.GetBytes]byteCount is negative"); + Debug.Assert(charCount >= 0, "[ISO2022Encoding.GetBytes]charCount is negative"); // Assert because we shouldn't be able to have a null encoder. - Contract.Assert(encoderFallback != null, "[ISO2022Encoding.GetBytes]Attempting to use null encoder fallback"); + Debug.Assert(encoderFallback != null, "[ISO2022Encoding.GetBytes]Attempting to use null encoder fallback"); // Fix our encoder ISO2022Encoder encoder = (ISO2022Encoder)baseEncoder; @@ -316,25 +312,23 @@ namespace System.Text } // This is internal and called by something else, - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) { // Just assert, we're called internally so these should be safe, checked already - Contract.Assert(bytes != null, "[ISO2022Encoding.GetCharCount]bytes is null"); - Contract.Assert(count >= 0, "[ISO2022Encoding.GetCharCount]byteCount is negative"); + Debug.Assert(bytes != null, "[ISO2022Encoding.GetCharCount]bytes is null"); + Debug.Assert(count >= 0, "[ISO2022Encoding.GetCharCount]byteCount is negative"); // Just call getChars with null char* to get count return GetChars(bytes, count, null, 0, baseDecoder); } - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS baseDecoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(bytes != null, "[ISO2022Encoding.GetChars]bytes is null"); - Contract.Assert(byteCount >= 0, "[ISO2022Encoding.GetChars]byteCount is negative"); - Contract.Assert(charCount >= 0, "[ISO2022Encoding.GetChars]charCount is negative"); + Debug.Assert(bytes != null, "[ISO2022Encoding.GetChars]bytes is null"); + Debug.Assert(byteCount >= 0, "[ISO2022Encoding.GetChars]byteCount is negative"); + Debug.Assert(charCount >= 0, "[ISO2022Encoding.GetChars]charCount is negative"); // Fix our decoder ISO2022Decoder decoder = (ISO2022Decoder)baseDecoder; @@ -358,7 +352,7 @@ namespace System.Text iCount = GetCharsCP52936( bytes, byteCount, chars, charCount, decoder); break; default: - Contract.Assert(false, "[ISO2022Encoding.GetChars] had unexpected code page"); + Debug.Assert(false, "[ISO2022Encoding.GetChars] had unexpected code page"); break; } @@ -399,7 +393,6 @@ namespace System.Text // undefined, so we maintain that behavior when decoding. We will never generate characters using // that technique, but the decoder will process them. // - [System.Security.SecurityCritical] // auto-generated private unsafe int GetBytesCP5022xJP(char* chars, int charCount, byte* bytes, int byteCount, ISO2022Encoder encoder) { @@ -422,7 +415,7 @@ namespace System.Text // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { - Contract.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP5022xJP]leftover character should be high surrogate"); + Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP5022xJP]leftover character should be high surrogate"); // It has to be a high surrogate, which we don't support, so it has to be a fallback buffer.Fallback(charLeftOver); @@ -483,7 +476,7 @@ namespace System.Text else { // 50221 does halfwidth katakana by escape sequence - Contract.Assert(CodePage == 50221, "[ISO2022Encoding.GetBytesCP5022xJP]Expected Code Page 50221"); + Debug.Assert(CodePage == 50221, "[ISO2022Encoding.GetBytesCP5022xJP]Expected Code Page 50221"); // Add our escape sequence if (!buffer.AddByte(ESCAPE, unchecked((byte)'('), unchecked((byte)'I'))) @@ -642,7 +635,6 @@ namespace System.Text // Also Mlang always assumed KR mode, even if the designator wasn't found yet, so we do that as // well. So basically we just ignore <ESC>$)C when decoding. // - [System.Security.SecurityCritical] // auto-generated private unsafe int GetBytesCP50225KR(char* chars, int charCount, byte* bytes, int byteCount, ISO2022Encoder encoder) { @@ -665,7 +657,7 @@ namespace System.Text // We may have a l left over character from last time, try and process it. if (charLeftOver > 0) { - Contract.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP50225KR]leftover character should be high surrogate"); + Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP50225KR]leftover character should be high surrogate"); // It has to be a high surrogate, which we don't support, so it has to be a fallback buffer.Fallback(charLeftOver); @@ -765,7 +757,7 @@ namespace System.Text if (!encoder.MustFlush || encoder.charLeftOver != (char)0) { // We should be not flushing or converting - Contract.Assert(!encoder.MustFlush || !encoder.m_throwOnOverflow, + Debug.Assert(!encoder.MustFlush || !encoder.m_throwOnOverflow, "[ISO2022Encoding.GetBytesCP50225KR]Expected no left over data or not flushing or not converting"); encoder.shiftInOutMode = shiftOutMode; } @@ -793,7 +785,6 @@ namespace System.Text // // This encoding is designed for transmission by e-mail and news. No bytes should have high bit set. // (all bytes <= 0x7f) - [System.Security.SecurityCritical] // auto-generated private unsafe int GetBytesCP52936(char* chars, int charCount, byte* bytes, int byteCount, ISO2022Encoder encoder) { @@ -813,7 +804,7 @@ namespace System.Text // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { - Contract.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP52936]leftover character should be high surrogate"); + Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP52936]leftover character should be high surrogate"); // It has to be a high surrogate, which we don't support, so it has to be a fallback buffer.Fallback(charLeftOver); @@ -928,7 +919,6 @@ namespace System.Text return buffer.Count; } - [System.Security.SecurityCritical] // auto-generated private unsafe int GetCharsCP5022xJP(byte* bytes, int byteCount, char* chars, int charCount, ISO2022Decoder decoder) { @@ -1139,7 +1129,7 @@ namespace System.Text if (!decoder.MustFlush || escapeCount != 0) { // Either not flushing or had state (from convert) - Contract.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow, + Debug.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow, "[ISO2022Encoding.GetCharsCP5022xJP]Expected no state or not converting or not flushing"); decoder.currentMode = currentMode; @@ -1233,7 +1223,7 @@ namespace System.Text private byte DecrementEscapeBytes(ref byte[] bytes, ref int count) { - Contract.Assert(count > 0, "[ISO2022Encoding.DecrementEscapeBytes]count > 0"); + Debug.Assert(count > 0, "[ISO2022Encoding.DecrementEscapeBytes]count > 0"); // Decrement our count count--; @@ -1256,7 +1246,6 @@ namespace System.Text // Note that in DBCS mode mlang passed through ' ', '\t' and '\n' as SBCS characters // probably to allow mailer formatting without too much extra work. - [System.Security.SecurityCritical] // auto-generated private unsafe int GetCharsCP50225KR(byte* bytes, int byteCount, char* chars, int charCount, ISO2022Decoder decoder) { @@ -1441,7 +1430,7 @@ namespace System.Text if (!decoder.MustFlush || escapeCount != 0) { // Either not flushing or had state (from convert) - Contract.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow, + Debug.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow, "[ISO2022Encoding.GetCharsCP50225KR]Expected no state or not converting or not flushing"); decoder.currentMode = currentMode; @@ -1496,12 +1485,11 @@ namespace System.Text // // This encoding is designed for transmission by e-mail and news. No bytes should have high bit set. // (all bytes <= 0x7f) - [System.Security.SecurityCritical] // auto-generated private unsafe int GetCharsCP52936(byte* bytes, int byteCount, char* chars, int charCount, ISO2022Decoder decoder) { - Contract.Assert(byteCount >=0, "[ISO2022Encoding.GetCharsCP52936]count >=0"); - Contract.Assert(bytes!=null, "[ISO2022Encoding.GetCharsCP52936]bytes!=null"); + Debug.Assert(byteCount >=0, "[ISO2022Encoding.GetCharsCP52936]count >=0"); + Debug.Assert(bytes!=null, "[ISO2022Encoding.GetCharsCP52936]bytes!=null"); // Get our info. Encoding.EncodingCharBuffer buffer = new Encoding.EncodingCharBuffer( @@ -1612,7 +1600,7 @@ namespace System.Text if (currentMode != ISO2022Modes.ModeASCII) { // Should be ModeHZ - Contract.Assert(currentMode == ISO2022Modes.ModeHZ, "[ISO2022Encoding.GetCharsCP52936]Expected ModeHZ"); + Debug.Assert(currentMode == ISO2022Modes.ModeHZ, "[ISO2022Encoding.GetCharsCP52936]Expected ModeHZ"); char cm; // Everett allowed characters < 0x20 to be passed as if they were ASCII @@ -1737,7 +1725,7 @@ namespace System.Text else { // Either not flushing or had state (from convert) - Contract.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow, + Debug.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow, "[ISO2022Encoding.GetCharsCP52936]Expected no state or not converting or not flushing"); decoder.currentMode = currentMode; @@ -1754,7 +1742,7 @@ namespace System.Text public override int GetMaxByteCount(int charCount) { if (charCount < 0) - throw new ArgumentOutOfRangeException("charCount", + throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -1801,7 +1789,7 @@ namespace System.Text byteCount += extraStart + extraEnd; if (byteCount > 0x7fffffff) - throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); + throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); return (int)byteCount; } @@ -1809,7 +1797,7 @@ namespace System.Text public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) - throw new ArgumentOutOfRangeException("byteCount", + throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -1839,7 +1827,7 @@ namespace System.Text charCount *= DecoderFallback.MaxCharCount; if (charCount > 0x7fffffff) - throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow")); + throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow")); return (int)charCount; } diff --git a/src/mscorlib/src/System/Text/Latin1Encoding.cs b/src/mscorlib/src/System/Text/Latin1Encoding.cs index a24f9c00ae..56a6c1f949 100644 --- a/src/mscorlib/src/System/Text/Latin1Encoding.cs +++ b/src/mscorlib/src/System/Text/Latin1Encoding.cs @@ -5,6 +5,7 @@ namespace System.Text { using System; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.InteropServices; @@ -43,12 +44,11 @@ namespace System.Text } // ISerializable implementation, serialize it as a CodePageEncoding - [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // Make sure to get the base stuff too This throws if info is null SerializeEncoding(info, context); - Contract.Assert(info!=null, "[Latin1Encoding.GetObjectData] Expected null info to throw"); + Debug.Assert(info!=null, "[Latin1Encoding.GetObjectData] Expected null info to throw"); // In Everett this is a CodePageEncoding, so it needs maxCharSize info.AddValue("CodePageEncoding+maxCharSize", 1); @@ -61,15 +61,14 @@ namespace System.Text // GetByteCount // Note: We start by assuming that the output will be the same as count. Having // an encoder or fallback may change that assumption - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetByteCount(char* chars, int charCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(charCount >= 0, "[Latin1Encoding.GetByteCount]count is negative"); - Contract.Assert(chars != null, "[Latin1Encoding.GetByteCount]chars is null"); + Debug.Assert(charCount >= 0, "[Latin1Encoding.GetByteCount]count is negative"); + Debug.Assert(chars != null, "[Latin1Encoding.GetByteCount]chars is null"); // Assert because we shouldn't be able to have a null encoder. - Contract.Assert(encoderFallback != null, "[Latin1Encoding.GetByteCount]Attempting to use null fallback encoder"); + Debug.Assert(encoderFallback != null, "[Latin1Encoding.GetByteCount]Attempting to use null fallback encoder"); char charLeftOver = (char)0; @@ -79,13 +78,13 @@ namespace System.Text if (encoder != null) { charLeftOver = encoder.charLeftOver; - Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), + Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), "[Latin1Encoding.GetByteCount]leftover character should be high surrogate"); fallback = encoder.Fallback as EncoderReplacementFallback; // Verify that we have no fallbackbuffer, for Latin1 its always empty, so just assert - Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || + Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[Latin1CodePageEncoding.GetByteCount]Expected empty fallback buffer"); } @@ -122,7 +121,7 @@ namespace System.Text if (charLeftOver > 0) { // Initialize the buffer - Contract.Assert(encoder != null, + Debug.Assert(encoder != null, "[Latin1Encoding.GetByteCount]Expected encoder if we have charLeftOver"); fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false); @@ -171,24 +170,23 @@ namespace System.Text byteCount++; } - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[Latin1Encoding.GetByteCount]Expected Empty fallback buffer"); return byteCount; } - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(bytes != null, "[Latin1Encoding.GetBytes]bytes is null"); - Contract.Assert(byteCount >= 0, "[Latin1Encoding.GetBytes]byteCount is negative"); - Contract.Assert(chars != null, "[Latin1Encoding.GetBytes]chars is null"); - Contract.Assert(charCount >= 0, "[Latin1Encoding.GetBytes]charCount is negative"); + Debug.Assert(bytes != null, "[Latin1Encoding.GetBytes]bytes is null"); + Debug.Assert(byteCount >= 0, "[Latin1Encoding.GetBytes]byteCount is negative"); + Debug.Assert(chars != null, "[Latin1Encoding.GetBytes]chars is null"); + Debug.Assert(charCount >= 0, "[Latin1Encoding.GetBytes]charCount is negative"); // Assert because we shouldn't be able to have a null encoder. - Contract.Assert(encoderFallback != null, "[Latin1Encoding.GetBytes]Attempting to use null encoder fallback"); + Debug.Assert(encoderFallback != null, "[Latin1Encoding.GetBytes]Attempting to use null encoder fallback"); // Get any left over characters & check fast or slower fallback type char charLeftOver = (char)0; @@ -197,11 +195,11 @@ namespace System.Text { charLeftOver = encoder.charLeftOver; fallback = encoder.Fallback as EncoderReplacementFallback; - Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), + Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), "[Latin1Encoding.GetBytes]leftover character should be high surrogate"); // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert - Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || + Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[Latin1CodePageEncoding.GetBytes]Expected empty fallback buffer"); } @@ -284,7 +282,7 @@ namespace System.Text { // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback - Contract.Assert(encoder != null, + Debug.Assert(encoder != null, "[Latin1Encoding.GetBytes]Expected encoder if we have charLeftOver"); fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(chars, charEnd, encoder, true); @@ -338,7 +336,7 @@ namespace System.Text { // Didn't use this char, throw it. Chars should've advanced by now // If we had encoder fallback data it would've thrown before the loop - Contract.Assert(chars > charStart, + Debug.Assert(chars > charStart, "[Latin1Encoding.GetBytes]Expected chars to have advanced (fallback case)"); chars--; fallbackBuffer.InternalReset(); @@ -356,11 +354,11 @@ namespace System.Text if (bytes >= byteEnd) { // didn't use this char, we'll throw or use buffer - Contract.Assert(fallbackBuffer == null || fallbackBuffer.bFallingBack == false, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.bFallingBack == false, "[Latin1Encoding.GetBytes]Expected fallback to have throw initially if insufficient space"); if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false) { - Contract.Assert(chars > charStart, + Debug.Assert(chars > charStart, "[Latin1Encoding.GetBytes]Expected chars to have advanced (fallback case)"); chars--; // don't use last char } @@ -385,34 +383,32 @@ namespace System.Text encoder.m_charsUsed = (int)(chars - charStart); } - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[Latin1Encoding.GetBytes]Expected Empty fallback buffer"); return (int)(bytes - byteStart); } // This is internal and called by something else, - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder) { // Just assert, we're called internally so these should be safe, checked already - Contract.Assert(bytes != null, "[Latin1Encoding.GetCharCount]bytes is null"); - Contract.Assert(count >= 0, "[Latin1Encoding.GetCharCount]byteCount is negative"); + Debug.Assert(bytes != null, "[Latin1Encoding.GetCharCount]bytes is null"); + Debug.Assert(count >= 0, "[Latin1Encoding.GetCharCount]byteCount is negative"); // Just return length, SBCS stay the same length because they don't map to surrogate // pairs and we don't have to fallback because all latin1Encoding code points are unicode return count; } - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS decoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(bytes != null, "[Latin1Encoding.GetChars]bytes is null"); - Contract.Assert(byteCount >= 0, "[Latin1Encoding.GetChars]byteCount is negative"); - Contract.Assert(chars != null, "[Latin1Encoding.GetChars]chars is null"); - Contract.Assert(charCount >= 0, "[Latin1Encoding.GetChars]charCount is negative"); + Debug.Assert(bytes != null, "[Latin1Encoding.GetChars]bytes is null"); + Debug.Assert(byteCount >= 0, "[Latin1Encoding.GetChars]byteCount is negative"); + Debug.Assert(chars != null, "[Latin1Encoding.GetChars]chars is null"); + Debug.Assert(charCount >= 0, "[Latin1Encoding.GetChars]charCount is negative"); // Need byteCount chars, otherwise too small buffer if (charCount < byteCount) @@ -446,7 +442,7 @@ namespace System.Text public override int GetMaxByteCount(int charCount) { if (charCount < 0) - throw new ArgumentOutOfRangeException("charCount", + throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -459,14 +455,14 @@ namespace System.Text // 1 to 1 for most characters. Only surrogates with fallbacks have less. if (byteCount > 0x7fffffff) - throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); + throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); return (int)byteCount; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) - throw new ArgumentOutOfRangeException("byteCount", + throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -478,7 +474,7 @@ namespace System.Text charCount *= DecoderFallback.MaxCharCount; if (charCount > 0x7fffffff) - throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow")); + throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow")); return (int)charCount; } diff --git a/src/mscorlib/src/System/Text/MLangCodePageEncoding.cs b/src/mscorlib/src/System/Text/MLangCodePageEncoding.cs index 53924a936d..a82db91b98 100644 --- a/src/mscorlib/src/System/Text/MLangCodePageEncoding.cs +++ b/src/mscorlib/src/System/Text/MLangCodePageEncoding.cs @@ -13,6 +13,7 @@ namespace System.Text using System; using System.Runtime.Serialization; using System.Security.Permissions; + using System.Diagnostics; using System.Diagnostics.Contracts; /*=================================MLangCodePageEncoding================================== @@ -46,7 +47,7 @@ namespace System.Text internal MLangCodePageEncoding(SerializationInfo info, StreamingContext context) { // Any info? - if (info==null) throw new ArgumentNullException("info"); + if (info==null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); // All versions have a code page @@ -76,7 +77,6 @@ namespace System.Text } // Just get it from GetEncoding - [System.Security.SecurityCritical] // auto-generated public Object GetRealObject(StreamingContext context) { // Get our encoding (Note: This has default fallbacks for readonly and everett cases) @@ -95,11 +95,10 @@ namespace System.Text } // ISerializable implementation - [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // We cannot ever call this. - Contract.Assert(false, "Didn't expect to make it to MLangCodePageEncoding ISerializable.GetObjectData"); + Debug.Assert(false, "Didn't expect to make it to MLangCodePageEncoding ISerializable.GetObjectData"); throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException")); } @@ -115,25 +114,23 @@ namespace System.Text internal MLangEncoder(SerializationInfo info, StreamingContext context) { // Any info? - if (info==null) throw new ArgumentNullException("info"); + if (info==null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); this.realEncoding = (Encoding)info.GetValue("m_encoding", typeof(Encoding)); } // Just get it from GetEncoder - [System.Security.SecurityCritical] // auto-generated public Object GetRealObject(StreamingContext context) { return this.realEncoding.GetEncoder(); } // ISerializable implementation, get data for this object - [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // We cannot ever call this. - Contract.Assert(false, "Didn't expect to make it to MLangCodePageEncoding.MLangEncoder.GetObjectData"); + Debug.Assert(false, "Didn't expect to make it to MLangCodePageEncoding.MLangEncoder.GetObjectData"); throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException")); } } @@ -151,25 +148,23 @@ namespace System.Text internal MLangDecoder(SerializationInfo info, StreamingContext context) { // Any info? - if (info==null) throw new ArgumentNullException("info"); + if (info==null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); this.realEncoding = (Encoding)info.GetValue("m_encoding", typeof(Encoding)); } // Just get it from GetDecoder - [System.Security.SecurityCritical] // auto-generated public Object GetRealObject(StreamingContext context) { return this.realEncoding.GetDecoder(); } // ISerializable implementation, get data for this object - [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // We cannot ever call this. - Contract.Assert(false, "Didn't expect to make it to MLangCodePageEncoding.MLangDecoder.GetObjectData"); + Debug.Assert(false, "Didn't expect to make it to MLangCodePageEncoding.MLangDecoder.GetObjectData"); throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException")); } } diff --git a/src/mscorlib/src/System/Text/Normalization.Unix.cs b/src/mscorlib/src/System/Text/Normalization.Unix.cs new file mode 100644 index 0000000000..d49bdc6c21 --- /dev/null +++ b/src/mscorlib/src/System/Text/Normalization.Unix.cs @@ -0,0 +1,123 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Security; +using System.Text; + +namespace System.Text +{ + static partial class Normalization + { + public static bool IsNormalized(this string strInput, NormalizationForm normalizationForm) + { + ValidateArguments(strInput, normalizationForm); + + int ret = Interop.GlobalizationInterop.IsNormalized(normalizationForm, strInput, strInput.Length); + + if (ret == -1) + { + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"), nameof(strInput)); + } + + return ret == 1; + } + + public static string Normalize(this string strInput, NormalizationForm normalizationForm) + { + ValidateArguments(strInput, normalizationForm); + + char[] buf = new char[strInput.Length]; + + for (int attempts = 2; attempts > 0; attempts--) + { + int realLen = Interop.GlobalizationInterop.NormalizeString(normalizationForm, strInput, strInput.Length, buf, buf.Length); + + if (realLen == -1) + { + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"), nameof(strInput)); + } + + if (realLen <= buf.Length) + { + return new string(buf, 0, realLen); + } + + buf = new char[realLen]; + } + + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"), nameof(strInput)); + } + + // ----------------------------- + // ---- PAL layer ends here ---- + // ----------------------------- + + private static void ValidateArguments(string strInput, NormalizationForm normalizationForm) + { + if (strInput == null) + { + throw new ArgumentNullException(nameof(strInput)); + } + + if (normalizationForm != NormalizationForm.FormC && normalizationForm != NormalizationForm.FormD && + normalizationForm != NormalizationForm.FormKC && normalizationForm != NormalizationForm.FormKD) + { + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNormalizationForm"), nameof(normalizationForm)); + } + + if (HasInvalidUnicodeSequence(strInput)) + { + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"), nameof(strInput)); + } + } + + /// <summary> + /// ICU does not signal an error during normalization if the input string has invalid unicode, + /// unlike Windows (which uses the ERROR_NO_UNICODE_TRANSLATION error value to signal an error). + /// + /// We walk the string ourselves looking for these bad sequences so we can continue to throw + /// ArgumentException in these cases. + /// </summary> + private static bool HasInvalidUnicodeSequence(string s) + { + for (int i = 0; i < s.Length; i++) + { + char c = s[i]; + + if (c < '\ud800') + { + continue; + } + + if (c == '\uFFFE') + { + return true; + } + + // If we see low surrogate before a high one, the string is invalid. + if (char.IsLowSurrogate(c)) + { + return true; + } + + if (char.IsHighSurrogate(c)) + { + if (i + 1 >= s.Length || !char.IsLowSurrogate(s[i + 1])) + { + // A high surrogate at the end of the string or a high surrogate + // not followed by a low surrogate + return true; + } + else + { + i++; // consume the low surrogate. + continue; + } + } + } + + return false; + } + } +} diff --git a/src/mscorlib/src/System/Text/Normalization.Windows.cs b/src/mscorlib/src/System/Text/Normalization.Windows.cs new file mode 100644 index 0000000000..b2faf0db68 --- /dev/null +++ b/src/mscorlib/src/System/Text/Normalization.Windows.cs @@ -0,0 +1,286 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Text +{ + using System; + using System.Security; + using System.Globalization; + using System.Text; + using System.Runtime.CompilerServices; + using System.Runtime.InteropServices; + using System.Runtime.Versioning; + using System.Diagnostics; + using System.Diagnostics.Contracts; + + // This internal class wraps up our normalization behavior + + internal class Normalization + { + // + // Flags that track whether given normalization form was initialized + // +#if !FEATURE_NORM_IDNA_ONLY + private static volatile bool NFC; + private static volatile bool NFD; + private static volatile bool NFKC; + private static volatile bool NFKD; +#endif // !FEATURE_NORM_IDNA_ONLY + private static volatile bool IDNA; +#if !FEATURE_NORM_IDNA_ONLY + private static volatile bool NFCDisallowUnassigned; + private static volatile bool NFDDisallowUnassigned; + private static volatile bool NFKCDisallowUnassigned; + private static volatile bool NFKDDisallowUnassigned; +#endif // !FEATURE_NORM_IDNA_ONLY + private static volatile bool IDNADisallowUnassigned; + private static volatile bool Other; + + // These are error codes we get back from the Normalization DLL + private const int ERROR_SUCCESS = 0; + private const int ERROR_NOT_ENOUGH_MEMORY = 8; + private const int ERROR_INVALID_PARAMETER = 87; + private const int ERROR_INSUFFICIENT_BUFFER = 122; + private const int ERROR_NO_UNICODE_TRANSLATION = 1113; + + static private unsafe void InitializeForm(NormalizationForm form, String strDataFile) + { + byte* pTables = null; + + // Normalization uses OS on Win8 + if (!Environment.IsWindows8OrAbove) + { + if (strDataFile == null) + { + // They were supposed to have a form that we know about! + throw new ArgumentException( + Environment.GetResourceString("Argument_InvalidNormalizationForm")); + } + + // Tell the DLL where to find our data + pTables = GlobalizationAssembly.GetGlobalizationResourceBytePtr( + typeof(Normalization).Assembly, strDataFile); + if (pTables == null) + { + // Unable to load the specified normalizationForm, + // tables not loaded from file + throw new ArgumentException( + Environment.GetResourceString("Argument_InvalidNormalizationForm")); + } + } + + nativeNormalizationInitNormalization(form, pTables); + } + + static private void EnsureInitialized(NormalizationForm form) + { + switch ((ExtendedNormalizationForms)form) + { +#if !FEATURE_NORM_IDNA_ONLY + case ExtendedNormalizationForms.FormC: + if (NFC) return; + InitializeForm(form, "normnfc.nlp"); + NFC = true; + break; + + case ExtendedNormalizationForms.FormD: + if (NFD) return; + InitializeForm(form, "normnfd.nlp"); + NFD = true; + break; + + case ExtendedNormalizationForms.FormKC: + if (NFKC) return; + InitializeForm(form, "normnfkc.nlp"); + NFKC = true; + break; + + case ExtendedNormalizationForms.FormKD: + if (NFKD) return; + InitializeForm(form, "normnfkd.nlp"); + NFKD = true; + break; +#endif // !FEATURE_NORM_IDNA_ONLY + + case ExtendedNormalizationForms.FormIdna: + if (IDNA) return; + InitializeForm(form, "normidna.nlp"); + IDNA = true; + break; + +#if !FEATURE_NORM_IDNA_ONLY + case ExtendedNormalizationForms.FormCDisallowUnassigned: + if (NFCDisallowUnassigned) return; + InitializeForm(form, "normnfc.nlp"); + NFCDisallowUnassigned = true; + break; + + case ExtendedNormalizationForms.FormDDisallowUnassigned: + if (NFDDisallowUnassigned) return; + InitializeForm(form, "normnfd.nlp"); + NFDDisallowUnassigned = true; + break; + + case ExtendedNormalizationForms.FormKCDisallowUnassigned: + if (NFKCDisallowUnassigned) return; + InitializeForm(form, "normnfkc.nlp"); + NFKCDisallowUnassigned = true; + break; + + case ExtendedNormalizationForms.FormKDDisallowUnassigned: + if (NFKDDisallowUnassigned) return; + InitializeForm(form, "normnfkd.nlp"); + NFKDDisallowUnassigned = true; + break; +#endif // !FEATURE_NORM_IDNA_ONLY + + case ExtendedNormalizationForms.FormIdnaDisallowUnassigned: + if (IDNADisallowUnassigned) return; + InitializeForm(form, "normidna.nlp"); + IDNADisallowUnassigned = true; + break; + + default: + if (Other) return; + InitializeForm(form, null); + Other = true; + break; + } + } + + internal static bool IsNormalized(String strInput, NormalizationForm normForm) + { + Contract.Requires(strInput != null); + + EnsureInitialized(normForm); + + int iError = ERROR_SUCCESS; + bool result = nativeNormalizationIsNormalizedString( + normForm, + ref iError, + strInput, + strInput.Length); + + switch(iError) + { + // Success doesn't need to do anything + case ERROR_SUCCESS: + break; + + // Do appropriate stuff for the individual errors: + case ERROR_INVALID_PARAMETER: + case ERROR_NO_UNICODE_TRANSLATION: + throw new ArgumentException( + Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex" ), + nameof(strInput)); + case ERROR_NOT_ENOUGH_MEMORY: + throw new OutOfMemoryException( + Environment.GetResourceString("Arg_OutOfMemoryException")); + default: + throw new InvalidOperationException( + Environment.GetResourceString("UnknownError_Num", iError)); + } + + return result; + } + + internal static String Normalize(String strInput, NormalizationForm normForm) + { + Contract.Requires(strInput != null); + + EnsureInitialized(normForm); + + int iError = ERROR_SUCCESS; + + // Guess our buffer size first + int iLength = nativeNormalizationNormalizeString(normForm, ref iError, strInput, strInput.Length, null, 0); + + // Could have an error (actually it'd be quite hard to have an error here) + if (iError != ERROR_SUCCESS) + { + if (iError == ERROR_INVALID_PARAMETER) + throw new ArgumentException( + Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex" ), + nameof(strInput)); + + // We shouldn't really be able to get here..., guessing length is + // a trivial math function... + // Can't really be Out of Memory, but just in case: + if (iError == ERROR_NOT_ENOUGH_MEMORY) + throw new OutOfMemoryException( + Environment.GetResourceString("Arg_OutOfMemoryException")); + + // Who knows what happened? Not us! + throw new InvalidOperationException( + Environment.GetResourceString("UnknownError_Num", iError)); + } + + // Don't break for empty strings (only possible for D & KD and not really possible at that) + if (iLength == 0) return String.Empty; + + // Someplace to stick our buffer + char[] cBuffer = null; + + for (;;) + { + // (re)allocation buffer and normalize string + cBuffer = new char[iLength]; + + iLength = nativeNormalizationNormalizeString( + normForm, + ref iError, + strInput, + strInput.Length, + cBuffer, + cBuffer.Length); + + if (iError == ERROR_SUCCESS) + break; + + // Could have an error (actually it'd be quite hard to have an error here) + switch(iError) + { + // Do appropriate stuff for the individual errors: + case ERROR_INSUFFICIENT_BUFFER: + Debug.Assert(iLength > cBuffer.Length, "Buffer overflow should have iLength > cBuffer.Length"); + continue; + + case ERROR_INVALID_PARAMETER: + case ERROR_NO_UNICODE_TRANSLATION: + // Illegal code point or order found. Ie: FFFE or D800 D800, etc. + throw new ArgumentException( + Environment.GetResourceString("Argument_InvalidCharSequence", iLength ), + nameof(strInput)); + case ERROR_NOT_ENOUGH_MEMORY: + throw new OutOfMemoryException( + Environment.GetResourceString("Arg_OutOfMemoryException")); + + default: + // We shouldn't get here... + throw new InvalidOperationException( + Environment.GetResourceString("UnknownError_Num", iError)); + } + } + + // Copy our buffer into our new string, which will be the appropriate size + return new String(cBuffer, 0, iLength); + } + + [MethodImplAttribute(MethodImplOptions.InternalCall)] + unsafe private static extern int nativeNormalizationNormalizeString( + NormalizationForm normForm, ref int iError, + String lpSrcString, int cwSrcLength, + char[] lpDstString, int cwDstLength); + + [MethodImplAttribute(MethodImplOptions.InternalCall)] + unsafe private static extern bool nativeNormalizationIsNormalizedString( + NormalizationForm normForm, ref int iError, + String lpString, int cwLength); + + [SuppressUnmanagedCodeSecurity] + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + unsafe private static extern void nativeNormalizationInitNormalization( + NormalizationForm normForm, byte* pTableData); + } +} diff --git a/src/mscorlib/src/System/Text/Normalization.cs b/src/mscorlib/src/System/Text/Normalization.cs index ce3c0c8e32..e7e733a587 100644 --- a/src/mscorlib/src/System/Text/Normalization.cs +++ b/src/mscorlib/src/System/Text/Normalization.cs @@ -4,15 +4,6 @@ namespace System.Text { - using System; - using System.Security; - using System.Globalization; - using System.Text; - using System.Runtime.CompilerServices; - using System.Runtime.InteropServices; - using System.Runtime.Versioning; - using System.Diagnostics.Contracts; - // This is the enumeration for Normalization Forms [System.Runtime.InteropServices.ComVisible(true)] public enum NormalizationForm @@ -42,309 +33,4 @@ namespace System.Text #endif // !FEATURE_NORM_IDNA_ONLY FormIdnaDisallowUnassigned = 0x10d } - - // This internal class wraps up our normalization behavior - - internal class Normalization - { - // - // Flags that track whether given normalization form was initialized - // -#if !FEATURE_NORM_IDNA_ONLY - private static volatile bool NFC; - private static volatile bool NFD; - private static volatile bool NFKC; - private static volatile bool NFKD; -#endif // !FEATURE_NORM_IDNA_ONLY - private static volatile bool IDNA; -#if !FEATURE_NORM_IDNA_ONLY - private static volatile bool NFCDisallowUnassigned; - private static volatile bool NFDDisallowUnassigned; - private static volatile bool NFKCDisallowUnassigned; - private static volatile bool NFKDDisallowUnassigned; -#endif // !FEATURE_NORM_IDNA_ONLY - private static volatile bool IDNADisallowUnassigned; - private static volatile bool Other; - - // These are error codes we get back from the Normalization DLL - private const int ERROR_SUCCESS = 0; - private const int ERROR_NOT_ENOUGH_MEMORY = 8; - private const int ERROR_INVALID_PARAMETER = 87; - private const int ERROR_INSUFFICIENT_BUFFER = 122; - private const int ERROR_NO_UNICODE_TRANSLATION = 1113; - - [System.Security.SecurityCritical] // auto-generated - static private unsafe void InitializeForm(NormalizationForm form, String strDataFile) - { -#if FEATURE_COREFX_GLOBALIZATION - //TODO: Implement this fully. We might need a PAL here. - throw new NotImplementedException(); -#else - byte* pTables = null; - - // Normalization uses OS on Win8 - if (!Environment.IsWindows8OrAbove) - { - if (strDataFile == null) - { - // They were supposed to have a form that we know about! - throw new ArgumentException( - Environment.GetResourceString("Argument_InvalidNormalizationForm")); - } - - // Tell the DLL where to find our data - pTables = GlobalizationAssembly.GetGlobalizationResourceBytePtr( - typeof(Normalization).Assembly, strDataFile); - if (pTables == null) - { - // Unable to load the specified normalizationForm, - // tables not loaded from file - throw new ArgumentException( - Environment.GetResourceString("Argument_InvalidNormalizationForm")); - } - } - - nativeNormalizationInitNormalization(form, pTables); -#endif - } - - [System.Security.SecurityCritical] // auto-generated - static private void EnsureInitialized(NormalizationForm form) - { - switch ((ExtendedNormalizationForms)form) - { -#if !FEATURE_NORM_IDNA_ONLY - case ExtendedNormalizationForms.FormC: - if (NFC) return; - InitializeForm(form, "normnfc.nlp"); - NFC = true; - break; - - case ExtendedNormalizationForms.FormD: - if (NFD) return; - InitializeForm(form, "normnfd.nlp"); - NFD = true; - break; - - case ExtendedNormalizationForms.FormKC: - if (NFKC) return; - InitializeForm(form, "normnfkc.nlp"); - NFKC = true; - break; - - case ExtendedNormalizationForms.FormKD: - if (NFKD) return; - InitializeForm(form, "normnfkd.nlp"); - NFKD = true; - break; -#endif // !FEATURE_NORM_IDNA_ONLY - - case ExtendedNormalizationForms.FormIdna: - if (IDNA) return; - InitializeForm(form, "normidna.nlp"); - IDNA = true; - break; - -#if !FEATURE_NORM_IDNA_ONLY - case ExtendedNormalizationForms.FormCDisallowUnassigned: - if (NFCDisallowUnassigned) return; - InitializeForm(form, "normnfc.nlp"); - NFCDisallowUnassigned = true; - break; - - case ExtendedNormalizationForms.FormDDisallowUnassigned: - if (NFDDisallowUnassigned) return; - InitializeForm(form, "normnfd.nlp"); - NFDDisallowUnassigned = true; - break; - - case ExtendedNormalizationForms.FormKCDisallowUnassigned: - if (NFKCDisallowUnassigned) return; - InitializeForm(form, "normnfkc.nlp"); - NFKCDisallowUnassigned = true; - break; - - case ExtendedNormalizationForms.FormKDDisallowUnassigned: - if (NFKDDisallowUnassigned) return; - InitializeForm(form, "normnfkd.nlp"); - NFKDDisallowUnassigned = true; - break; -#endif // !FEATURE_NORM_IDNA_ONLY - - case ExtendedNormalizationForms.FormIdnaDisallowUnassigned: - if (IDNADisallowUnassigned) return; - InitializeForm(form, "normidna.nlp"); - IDNADisallowUnassigned = true; - break; - - default: - if (Other) return; - InitializeForm(form, null); - Other = true; - break; - } - } - - [System.Security.SecurityCritical] - internal static bool IsNormalized(String strInput, NormalizationForm normForm) - { - Contract.Requires(strInput != null); - - EnsureInitialized(normForm); - - int iError = ERROR_SUCCESS; - bool result = nativeNormalizationIsNormalizedString( - normForm, - ref iError, - strInput, - strInput.Length); - - switch(iError) - { - // Success doesn't need to do anything - case ERROR_SUCCESS: - break; - - // Do appropriate stuff for the individual errors: - case ERROR_INVALID_PARAMETER: - case ERROR_NO_UNICODE_TRANSLATION: - throw new ArgumentException( - Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex" ), - "strInput"); - case ERROR_NOT_ENOUGH_MEMORY: - throw new OutOfMemoryException( - Environment.GetResourceString("Arg_OutOfMemoryException")); - default: - throw new InvalidOperationException( - Environment.GetResourceString("UnknownError_Num", iError)); - } - - return result; - } - - [System.Security.SecurityCritical] - internal static String Normalize(String strInput, NormalizationForm normForm) - { - Contract.Requires(strInput != null); - - EnsureInitialized(normForm); - - int iError = ERROR_SUCCESS; - - // Guess our buffer size first - int iLength = nativeNormalizationNormalizeString(normForm, ref iError, strInput, strInput.Length, null, 0); - - // Could have an error (actually it'd be quite hard to have an error here) - if (iError != ERROR_SUCCESS) - { - if (iError == ERROR_INVALID_PARAMETER) - throw new ArgumentException( - Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex" ), - "strInput"); - - // We shouldn't really be able to get here..., guessing length is - // a trivial math function... - // Can't really be Out of Memory, but just in case: - if (iError == ERROR_NOT_ENOUGH_MEMORY) - throw new OutOfMemoryException( - Environment.GetResourceString("Arg_OutOfMemoryException")); - - // Who knows what happened? Not us! - throw new InvalidOperationException( - Environment.GetResourceString("UnknownError_Num", iError)); - } - - // Don't break for empty strings (only possible for D & KD and not really possible at that) - if (iLength == 0) return String.Empty; - - // Someplace to stick our buffer - char[] cBuffer = null; - - for (;;) - { - // (re)allocation buffer and normalize string - cBuffer = new char[iLength]; - - iLength = nativeNormalizationNormalizeString( - normForm, - ref iError, - strInput, - strInput.Length, - cBuffer, - cBuffer.Length); - - if (iError == ERROR_SUCCESS) - break; - - // Could have an error (actually it'd be quite hard to have an error here) - switch(iError) - { - // Do appropriate stuff for the individual errors: - case ERROR_INSUFFICIENT_BUFFER: - Contract.Assert(iLength > cBuffer.Length, "Buffer overflow should have iLength > cBuffer.Length"); - continue; - - case ERROR_INVALID_PARAMETER: - case ERROR_NO_UNICODE_TRANSLATION: - // Illegal code point or order found. Ie: FFFE or D800 D800, etc. - throw new ArgumentException( - Environment.GetResourceString("Argument_InvalidCharSequence", iLength ), - "strInput"); - case ERROR_NOT_ENOUGH_MEMORY: - throw new OutOfMemoryException( - Environment.GetResourceString("Arg_OutOfMemoryException")); - - default: - // We shouldn't get here... - throw new InvalidOperationException( - Environment.GetResourceString("UnknownError_Num", iError)); - } - } - - // Copy our buffer into our new string, which will be the appropriate size - return new String(cBuffer, 0, iLength); - } - -#if !FEATURE_COREFX_GLOBALIZATION - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.InternalCall)] - unsafe private static extern int nativeNormalizationNormalizeString( - NormalizationForm normForm, ref int iError, - String lpSrcString, int cwSrcLength, - char[] lpDstString, int cwDstLength); - - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.InternalCall)] - unsafe private static extern bool nativeNormalizationIsNormalizedString( - NormalizationForm normForm, ref int iError, - String lpString, int cwLength); - - [System.Security.SecurityCritical] // auto-generated - [SuppressUnmanagedCodeSecurity] - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - unsafe private static extern void nativeNormalizationInitNormalization( - NormalizationForm normForm, byte* pTableData); -#else - unsafe private static int nativeNormalizationNormalizeString( - NormalizationForm normForm, ref int iError, - String lpSrcString, int cwSrcLength, - char[] lpDstString, int cwDstLength) - { - throw new NotImplementedException(); - } - - unsafe private static bool nativeNormalizationIsNormalizedString( - NormalizationForm normForm, ref int iError, - String lpString, int cwLength) - { - throw new NotImplementedException(); - } - - unsafe private static void nativeNormalizationInitNormalization( - NormalizationForm normForm, byte* pTableData) - { - throw new NotImplementedException(); - } -#endif - } } diff --git a/src/mscorlib/src/System/Text/SBCSCodePageEncoding.cs b/src/mscorlib/src/System/Text/SBCSCodePageEncoding.cs index ce611d8b1f..8b07149fb7 100644 --- a/src/mscorlib/src/System/Text/SBCSCodePageEncoding.cs +++ b/src/mscorlib/src/System/Text/SBCSCodePageEncoding.cs @@ -6,6 +6,7 @@ namespace System.Text { using System; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Text; using System.Threading; @@ -20,13 +21,10 @@ namespace System.Text { // Pointers to our memory section parts [NonSerialized] - [SecurityCritical] unsafe char* mapBytesToUnicode = null; // char 256 [NonSerialized] - [SecurityCritical] unsafe byte* mapUnicodeToBytes = null; // byte 65536 [NonSerialized] - [SecurityCritical] unsafe int* mapCodePageCached = null; // to remember which CP is cached const char UNKNOWN_CHAR=(char)0xFFFD; @@ -37,23 +35,20 @@ namespace System.Text [NonSerialized] char charUnknown; - [System.Security.SecurityCritical] // auto-generated public SBCSCodePageEncoding(int codePage) : this(codePage, codePage) { } - [System.Security.SecurityCritical] // auto-generated internal SBCSCodePageEncoding(int codePage, int dataCodePage) : base(codePage, dataCodePage) { } // Constructor called by serialization. // Note: We use the base GetObjectData however - [System.Security.SecurityCritical] // auto-generated internal SBCSCodePageEncoding(SerializationInfo info, StreamingContext context) : base(0) { // Actually this can't ever get called, CodePageEncoding is our proxy - Contract.Assert(false, "Didn't expect to make it to SBCSCodePageEncoding serialization constructor"); + Debug.Assert(false, "Didn't expect to make it to SBCSCodePageEncoding serialization constructor"); throw new ArgumentNullException("this"); } @@ -69,11 +64,10 @@ namespace System.Text // byte < 0x20 means skip the next n positions. (Where n is the byte #) // byte == 1 means that next word is another unicode code point # // byte == 0 is unknown. (doesn't override initial WCHAR[256] table! - [System.Security.SecurityCritical] // auto-generated protected override unsafe void LoadManagedCodePage() { // Should be loading OUR code page - Contract.Assert(pCodePage->CodePage == this.dataTableCodePage, + Debug.Assert(pCodePage->CodePage == this.dataTableCodePage, "[SBCSCodePageEncoding.LoadManagedCodePage]Expected to load data table code page"); // Make sure we're really a 1 byte code page @@ -96,7 +90,7 @@ namespace System.Text // If its cached (& filled in) we don't have to do anything else if (*mapCodePageCached != 0) { - Contract.Assert(*mapCodePageCached == this.dataTableCodePage, + Debug.Assert(*mapCodePageCached == this.dataTableCodePage, "[DBCSCodePageEncoding.LoadManagedCodePage]Expected mapped section cached page to be same as data table code page. Cached : " + *mapCodePageCached + " Expected:" + this.dataTableCodePage); @@ -151,7 +145,6 @@ namespace System.Text } // Read in our best fit table - [System.Security.SecurityCritical] // auto-generated protected unsafe override void ReadBestFitTable() { // Lock so we don't confuse ourselves. @@ -180,7 +173,7 @@ namespace System.Text while ((byteTemp = *((ushort*)pData)) != 0) { - Contract.Assert(arrayTemp[byteTemp] == UNKNOWN_CHAR, String.Format(CultureInfo.InvariantCulture, + Debug.Assert(arrayTemp[byteTemp] == UNKNOWN_CHAR, String.Format(CultureInfo.InvariantCulture, "[SBCSCodePageEncoding::ReadBestFitTable] Expected unallocated byte (not 0x{2:X2}) for best fit byte at 0x{0:X2} for code page {1}", byteTemp, CodePage, (int)arrayTemp[byteTemp])); pData += 2; @@ -281,7 +274,7 @@ namespace System.Text arrayTemp[iBestFitCount++] = mapBytesToUnicode[input]; // This won't work if it won't round trip. - Contract.Assert(arrayTemp[iBestFitCount-1] != (char)0, + Debug.Assert(arrayTemp[iBestFitCount-1] != (char)0, String.Format(CultureInfo.InvariantCulture, "[SBCSCodePageEncoding.ReadBestFitTable] No valid Unicode value {0:X4} for round trip bytes {1:X4}, encoding {2}", (int)mapBytesToUnicode[input], (int)input, CodePage)); @@ -299,15 +292,14 @@ namespace System.Text // GetByteCount // Note: We start by assuming that the output will be the same as count. Having // an encoder or fallback may change that assumption - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(count >= 0, "[SBCSCodePageEncoding.GetByteCount]count is negative"); - Contract.Assert(chars != null, "[SBCSCodePageEncoding.GetByteCount]chars is null"); + Debug.Assert(count >= 0, "[SBCSCodePageEncoding.GetByteCount]count is negative"); + Debug.Assert(chars != null, "[SBCSCodePageEncoding.GetByteCount]chars is null"); // Assert because we shouldn't be able to have a null encoder. - Contract.Assert(encoderFallback != null, "[SBCSCodePageEncoding.GetByteCount]Attempting to use null fallback"); + Debug.Assert(encoderFallback != null, "[SBCSCodePageEncoding.GetByteCount]Attempting to use null fallback"); CheckMemorySection(); @@ -319,12 +311,12 @@ namespace System.Text if (encoder != null) { charLeftOver = encoder.charLeftOver; - Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), + Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), "[SBCSCodePageEncoding.GetByteCount]leftover character should be high surrogate"); fallback = encoder.Fallback as EncoderReplacementFallback; // Verify that we have no fallbackbuffer, actually for SBCS this is always empty, so just assert - Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || + Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[SBCSCodePageEncoding.GetByteCount]Expected empty fallback buffer at start"); } @@ -363,7 +355,7 @@ namespace System.Text { // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback - Contract.Assert(encoder != null, "[SBCSCodePageEncoding.GetByteCount]Expect to have encoder if we have a charLeftOver"); + Debug.Assert(encoder != null, "[SBCSCodePageEncoding.GetByteCount]Expect to have encoder if we have a charLeftOver"); fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false); @@ -414,24 +406,23 @@ namespace System.Text byteCount++; } - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[SBCSEncoding.GetByteCount]Expected Empty fallback buffer at end"); return (int)byteCount; } - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(bytes != null, "[SBCSCodePageEncoding.GetBytes]bytes is null"); - Contract.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetBytes]byteCount is negative"); - Contract.Assert(chars != null, "[SBCSCodePageEncoding.GetBytes]chars is null"); - Contract.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetBytes]charCount is negative"); + Debug.Assert(bytes != null, "[SBCSCodePageEncoding.GetBytes]bytes is null"); + Debug.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetBytes]byteCount is negative"); + Debug.Assert(chars != null, "[SBCSCodePageEncoding.GetBytes]chars is null"); + Debug.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetBytes]charCount is negative"); // Assert because we shouldn't be able to have a null encoder. - Contract.Assert(encoderFallback != null, "[SBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback"); + Debug.Assert(encoderFallback != null, "[SBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback"); CheckMemorySection(); @@ -443,12 +434,12 @@ namespace System.Text if (encoder != null) { charLeftOver = encoder.charLeftOver; - Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), + Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), "[SBCSCodePageEncoding.GetBytes]leftover character should be high surrogate"); fallback = encoder.Fallback as EncoderReplacementFallback; // Verify that we have no fallbackbuffer, for SBCS its always empty, so just assert - Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || + Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[SBCSCodePageEncoding.GetBytes]Expected empty fallback buffer at start"); // if (encoder.m_throwOnOverflow && encoder.InternalHasFallbackBuffer && @@ -545,7 +536,7 @@ namespace System.Text { // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback - Contract.Assert(encoder != null, "[SBCSCodePageEncoding.GetBytes]Expect to have encoder if we have a charLeftOver"); + Debug.Assert(encoder != null, "[SBCSCodePageEncoding.GetBytes]Expect to have encoder if we have a charLeftOver"); fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(chars, charEnd, encoder, true); @@ -598,7 +589,7 @@ namespace System.Text if (fallbackBuffer.Remaining > byteEnd - bytes) { // Didn't use this char, reset it - Contract.Assert(chars > charStart, + Debug.Assert(chars > charStart, "[SBCSCodePageEncoding.GetBytes]Expected chars to have advanced (fallback)"); chars--; fallbackBuffer.InternalReset(); @@ -615,11 +606,11 @@ namespace System.Text if (bytes >= byteEnd) { // didn't use this char, we'll throw or use buffer - Contract.Assert(fallbackBuffer == null || fallbackBuffer.bFallingBack == false, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.bFallingBack == false, "[SBCSCodePageEncoding.GetBytes]Expected to NOT be falling back"); if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false) { - Contract.Assert(chars > charStart, + Debug.Assert(chars > charStart, "[SBCSCodePageEncoding.GetBytes]Expected chars to have advanced (normal)"); chars--; // don't use last char } @@ -645,19 +636,18 @@ namespace System.Text } // Expect Empty fallback buffer for SBCS - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[SBCSEncoding.GetBytes]Expected Empty fallback buffer at end"); return (int)(bytes - byteStart); } // This is internal and called by something else, - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder) { // Just assert, we're called internally so these should be safe, checked already - Contract.Assert(bytes != null, "[SBCSCodePageEncoding.GetCharCount]bytes is null"); - Contract.Assert(count >= 0, "[SBCSCodePageEncoding.GetCharCount]byteCount is negative"); + Debug.Assert(bytes != null, "[SBCSCodePageEncoding.GetCharCount]bytes is null"); + Debug.Assert(count >= 0, "[SBCSCodePageEncoding.GetCharCount]byteCount is negative"); CheckMemorySection(); @@ -676,7 +666,7 @@ namespace System.Text { fallback = decoder.Fallback as DecoderReplacementFallback; bUseBestFit = decoder.Fallback.IsMicrosoftBestFitFallback; - Contract.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || + Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[SBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start"); } @@ -729,22 +719,21 @@ namespace System.Text } // Fallback buffer must be empty - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[SBCSEncoding.GetCharCount]Expected Empty fallback buffer at end"); // Converted sequence is same length as input return charCount; } - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS decoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already - Contract.Assert(bytes != null, "[SBCSCodePageEncoding.GetChars]bytes is null"); - Contract.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetChars]byteCount is negative"); - Contract.Assert(chars != null, "[SBCSCodePageEncoding.GetChars]chars is null"); - Contract.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetChars]charCount is negative"); + Debug.Assert(bytes != null, "[SBCSCodePageEncoding.GetChars]bytes is null"); + Debug.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetChars]byteCount is negative"); + Debug.Assert(chars != null, "[SBCSCodePageEncoding.GetChars]chars is null"); + Debug.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetChars]charCount is negative"); CheckMemorySection(); @@ -768,7 +757,7 @@ namespace System.Text { fallback = decoder.Fallback as DecoderReplacementFallback; bUseBestFit = decoder.Fallback.IsMicrosoftBestFitFallback; - Contract.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || + Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[SBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start"); } @@ -848,7 +837,7 @@ namespace System.Text } // Use fallback buffer - Contract.Assert(bytes > byteStart, + Debug.Assert(bytes > byteStart, "[SBCSCodePageEncoding.GetChars]Expected bytes to have advanced already (unknown byte)"); byteBuffer[0] = *(bytes - 1); // Fallback adds fallback to chars, but doesn't increment chars unless the whole thing fits. @@ -866,7 +855,7 @@ namespace System.Text // Make sure we have buffer space if (chars >= charEnd) { - Contract.Assert(bytes > byteStart, + Debug.Assert(bytes > byteStart, "[SBCSCodePageEncoding.GetChars]Expected bytes to have advanced already (known byte)"); bytes--; // unused byte ThrowCharsOverflow(decoder, bytes == byteStart); // throw? @@ -883,7 +872,7 @@ namespace System.Text decoder.m_bytesUsed = (int)(bytes - byteStart); // Expect Empty fallback buffer for GetChars - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[SBCSEncoding.GetChars]Expected Empty fallback buffer at end"); return (int)(chars - charStart); @@ -892,7 +881,7 @@ namespace System.Text public override int GetMaxByteCount(int charCount) { if (charCount < 0) - throw new ArgumentOutOfRangeException("charCount", + throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -905,14 +894,14 @@ namespace System.Text // 1 to 1 for most characters. Only surrogates with fallbacks have less. if (byteCount > 0x7fffffff) - throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); + throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); return (int)byteCount; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) - throw new ArgumentOutOfRangeException("byteCount", + throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -924,7 +913,7 @@ namespace System.Text charCount *= DecoderFallback.MaxCharCount; if (charCount > 0x7fffffff) - throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow")); + throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow")); return (int)charCount; } diff --git a/src/mscorlib/src/System/Text/StringBuilder.cs b/src/mscorlib/src/System/Text/StringBuilder.cs index 8026c98e78..f20146fe00 100644 --- a/src/mscorlib/src/System/Text/StringBuilder.cs +++ b/src/mscorlib/src/System/Text/StringBuilder.cs @@ -20,7 +20,9 @@ namespace System.Text { using System.Security; using System.Threading; using System.Globalization; + using System.Diagnostics; using System.Diagnostics.Contracts; + using System.Collections.Generic; // This class represents a mutable string. It is convenient for situations in // which it is desirable to modify a string, perhaps by removing, replacing, or @@ -55,7 +57,7 @@ namespace System.Text { internal char[] m_ChunkChars; // The characters in this block internal StringBuilder m_ChunkPrevious; // Link to the block logically before this block internal int m_ChunkLength; // The index in m_ChunkChars that represent the end of the block - internal int m_ChunkOffset; // The logial offset (sum of all characters in previous blocks) + internal int m_ChunkOffset; // The logical offset (sum of all characters in previous blocks) internal int m_MaxCapacity = 0; // @@ -117,18 +119,17 @@ namespace System.Text { // Creates a new string builder from the specifed substring with the specified // capacity. The maximum number of characters is set by capacity. // - [System.Security.SecuritySafeCritical] // auto-generated public StringBuilder(String value, int startIndex, int length, int capacity) { if (capacity<0) { - throw new ArgumentOutOfRangeException("capacity", - Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", "capacity")); + throw new ArgumentOutOfRangeException(nameof(capacity), + Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", nameof(capacity))); } if (length<0) { - throw new ArgumentOutOfRangeException("length", - Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegNum", "length")); + throw new ArgumentOutOfRangeException(nameof(length), + Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegNum", nameof(length))); } if (startIndex<0) { - throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndex")); + throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex")); } Contract.EndContractBlock(); @@ -136,7 +137,7 @@ namespace System.Text { value = String.Empty; } if (startIndex > value.Length - length) { - throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_IndexLength")); + throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_IndexLength")); } m_MaxCapacity = Int32.MaxValue; if (capacity == 0) { @@ -158,14 +159,14 @@ namespace System.Text { // and a maximum capacity of maxCapacity. public StringBuilder(int capacity, int maxCapacity) { if (capacity>maxCapacity) { - throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_Capacity")); + throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_Capacity")); } if (maxCapacity<1) { - throw new ArgumentOutOfRangeException("maxCapacity", Environment.GetResourceString("ArgumentOutOfRange_SmallMaxCapacity")); + throw new ArgumentOutOfRangeException(nameof(maxCapacity), Environment.GetResourceString("ArgumentOutOfRange_SmallMaxCapacity")); } if (capacity<0) { - throw new ArgumentOutOfRangeException("capacity", - Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", "capacity")); + throw new ArgumentOutOfRangeException(nameof(capacity), + Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", nameof(capacity))); } Contract.EndContractBlock(); @@ -177,10 +178,9 @@ namespace System.Text { m_ChunkChars = new char[capacity]; } - [System.Security.SecurityCritical] // auto-generated private StringBuilder(SerializationInfo info, StreamingContext context) { if (info == null) - throw new ArgumentNullException("info"); + throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); int persistedCapacity = 0; @@ -240,11 +240,10 @@ namespace System.Text { VerifyClassInvariant(); } - [System.Security.SecurityCritical] // auto-generated void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (info==null) { - throw new ArgumentNullException("info"); + throw new ArgumentNullException(nameof(info)); } Contract.EndContractBlock(); @@ -264,21 +263,21 @@ namespace System.Text { for (; ; ) { // All blocks have copy of the maxCapacity. - Contract.Assert(currentBlock.m_MaxCapacity == maxCapacity, "Bad maxCapacity"); - Contract.Assert(currentBlock.m_ChunkChars != null, "Empty Buffer"); + Debug.Assert(currentBlock.m_MaxCapacity == maxCapacity, "Bad maxCapacity"); + Debug.Assert(currentBlock.m_ChunkChars != null, "Empty Buffer"); - Contract.Assert(currentBlock.m_ChunkLength <= currentBlock.m_ChunkChars.Length, "Out of range length"); - Contract.Assert(currentBlock.m_ChunkLength >= 0, "Negative length"); - Contract.Assert(currentBlock.m_ChunkOffset >= 0, "Negative offset"); + Debug.Assert(currentBlock.m_ChunkLength <= currentBlock.m_ChunkChars.Length, "Out of range length"); + Debug.Assert(currentBlock.m_ChunkLength >= 0, "Negative length"); + Debug.Assert(currentBlock.m_ChunkOffset >= 0, "Negative offset"); StringBuilder prevBlock = currentBlock.m_ChunkPrevious; if (prevBlock == null) { - Contract.Assert(currentBlock.m_ChunkOffset == 0, "First chunk's offset is not 0"); + Debug.Assert(currentBlock.m_ChunkOffset == 0, "First chunk's offset is not 0"); break; } // There are no gaps in the blocks. - Contract.Assert(currentBlock.m_ChunkOffset == prevBlock.m_ChunkOffset + prevBlock.m_ChunkLength, "There is a gap between chunks!"); + Debug.Assert(currentBlock.m_ChunkOffset == prevBlock.m_ChunkOffset + prevBlock.m_ChunkLength, "There is a gap between chunks!"); currentBlock = prevBlock; } } @@ -287,13 +286,13 @@ namespace System.Text { get { return m_ChunkChars.Length + m_ChunkOffset; } set { if (value < 0) { - throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NegativeCapacity")); + throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_NegativeCapacity")); } if (value > MaxCapacity) { - throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_Capacity")); + throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_Capacity")); } if (value < Length) { - throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity")); + throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity")); } Contract.EndContractBlock(); @@ -317,7 +316,7 @@ namespace System.Text { // public int EnsureCapacity(int capacity) { if (capacity < 0) { - throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_NegativeCapacity")); + throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_NegativeCapacity")); } Contract.EndContractBlock(); @@ -326,7 +325,6 @@ namespace System.Text { return Capacity; } - [System.Security.SecuritySafeCritical] // auto-generated public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); @@ -357,7 +355,7 @@ namespace System.Text { } else { - throw new ArgumentOutOfRangeException("chunkLength", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(chunkLength), Environment.GetResourceString("ArgumentOutOfRange_Index")); } } chunk = chunk.m_ChunkPrevious; @@ -370,26 +368,25 @@ namespace System.Text { // Converts a substring of this string builder to a String. - [System.Security.SecuritySafeCritical] // auto-generated public String ToString(int startIndex, int length) { Contract.Ensures(Contract.Result<String>() != null); int currentLength = this.Length; if (startIndex < 0) { - throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndex")); + throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex")); } if (startIndex > currentLength) { - throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndexLargerThanLength")); + throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndexLargerThanLength")); } if (length < 0) { - throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NegativeLength")); + throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NegativeLength")); } if (startIndex > (currentLength - length)) { - throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_IndexLength")); + throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_IndexLength")); } VerifyClassInvariant(); @@ -433,7 +430,7 @@ namespace System.Text { } else { - throw new ArgumentOutOfRangeException("chunkCount", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(chunkCount), Environment.GetResourceString("ArgumentOutOfRange_Index")); } } } @@ -463,11 +460,11 @@ namespace System.Text { set { //If the new length is less than 0 or greater than our Maximum capacity, bail. if (value<0) { - throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NegativeLength")); + throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_NegativeLength")); } if (value>MaxCapacity) { - throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity")); + throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity")); } Contract.EndContractBlock(); @@ -477,7 +474,7 @@ namespace System.Text { { m_ChunkLength = 0; m_ChunkOffset = 0; - Contract.Assert(Capacity >= originalCapacity, "setting the Length should never decrease the Capacity"); + Debug.Assert(Capacity >= originalCapacity, "setting the Length should never decrease the Capacity"); return; } @@ -499,7 +496,7 @@ namespace System.Text { int newLen = originalCapacity - chunk.m_ChunkOffset; char[] newArray = new char[newLen]; - Contract.Assert(newLen > chunk.m_ChunkChars.Length, "the new chunk should be larger than the one it is replacing"); + Debug.Assert(newLen > chunk.m_ChunkChars.Length, "the new chunk should be larger than the one it is replacing"); Array.Copy(chunk.m_ChunkChars, newArray, chunk.m_ChunkLength); m_ChunkChars = newArray; @@ -509,7 +506,7 @@ namespace System.Text { m_ChunkLength = value - chunk.m_ChunkOffset; VerifyClassInvariant(); } - Contract.Assert(Capacity >= originalCapacity, "setting the Length should never decrease the Capacity"); + Debug.Assert(Capacity >= originalCapacity, "setting the Length should never decrease the Capacity"); } } @@ -539,13 +536,13 @@ namespace System.Text { if (indexInBlock >= 0) { if (indexInBlock >= chunk.m_ChunkLength) - throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); chunk.m_ChunkChars[indexInBlock] = value; return; } chunk = chunk.m_ChunkPrevious; if (chunk == null) - throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); } } } @@ -553,7 +550,7 @@ namespace System.Text { // Appends a character at the end of this string builder. The capacity is adjusted as needed. public StringBuilder Append(char value, int repeatCount) { if (repeatCount<0) { - throw new ArgumentOutOfRangeException("repeatCount", Environment.GetResourceString("ArgumentOutOfRange_NegativeCount")); + throw new ArgumentOutOfRangeException(nameof(repeatCount), Environment.GetResourceString("ArgumentOutOfRange_NegativeCount")); } Contract.Ensures(Contract.Result<StringBuilder>() != null); Contract.EndContractBlock(); @@ -561,6 +558,14 @@ namespace System.Text { if (repeatCount==0) { return this; } + + // this is where we can check if the repeatCount will put us over m_MaxCapacity + // We are doing the check here to prevent the corruption of the StringBuilder. + int newLength = Length + repeatCount; + if (newLength > m_MaxCapacity || newLength < repeatCount) { + throw new ArgumentOutOfRangeException(nameof(repeatCount), Environment.GetResourceString("ArgumentOutOfRange_LengthGreaterThanCapacity")); + } + int idx = m_ChunkLength; while (repeatCount > 0) { @@ -573,7 +578,7 @@ namespace System.Text { { m_ChunkLength = idx; ExpandByABlock(repeatCount); - Contract.Assert(m_ChunkLength == 0, "Expand should create a new block"); + Debug.Assert(m_ChunkLength == 0, "Expand should create a new block"); idx = 0; } } @@ -583,10 +588,9 @@ namespace System.Text { } // Appends an array of characters at the end of this string builder. The capacity is adjusted as needed. - [System.Security.SecuritySafeCritical] // auto-generated public StringBuilder Append(char[] value, int startIndex, int charCount) { if (startIndex < 0) { - throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive")); + throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive")); } if (charCount<0) { throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive")); @@ -598,7 +602,7 @@ namespace System.Text { if (startIndex == 0 && charCount == 0) { return this; } - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } if (charCount > value.Length - startIndex) { throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Index")); @@ -620,7 +624,6 @@ namespace System.Text { // Appends a copy of this string at the end of this string builder. - [System.Security.SecuritySafeCritical] // auto-generated public StringBuilder Append(String value) { Contract.Ensures(Contract.Result<StringBuilder>() != null); @@ -659,7 +662,6 @@ namespace System.Text { // We put this fixed in its own helper to avoid the cost zero initing valueChars in the // case we don't actually use it. - [System.Security.SecuritySafeCritical] // auto-generated private void AppendHelper(string value) { unsafe { fixed (char* valueChars = value) @@ -668,23 +670,20 @@ namespace System.Text { } [MethodImplAttribute(MethodImplOptions.InternalCall)] - [SecurityCritical] internal unsafe extern void ReplaceBufferInternal(char* newBuffer, int newLength); [MethodImplAttribute(MethodImplOptions.InternalCall)] - [SecurityCritical] internal unsafe extern void ReplaceBufferAnsiInternal(sbyte* newBuffer, int newLength); // Appends a copy of the characters in value from startIndex to startIndex + // count at the end of this string builder. - [System.Security.SecuritySafeCritical] // auto-generated public StringBuilder Append(String value, int startIndex, int count) { if (startIndex < 0) { - throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index")); } if (count < 0) { - throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive")); + throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive")); } Contract.Ensures(Contract.Result<StringBuilder>() != null); @@ -694,7 +693,7 @@ namespace System.Text { if (startIndex == 0 && count == 0) { return this; } - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } if (count == 0) { @@ -702,7 +701,7 @@ namespace System.Text { } if (startIndex > value.Length - count) { - throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index")); } unsafe @@ -730,19 +729,18 @@ namespace System.Text { } [System.Runtime.InteropServices.ComVisible(false)] - [SecuritySafeCritical] public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { if (destination == null) { - throw new ArgumentNullException("destination"); + throw new ArgumentNullException(nameof(destination)); } if (count < 0) { - throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("Arg_NegativeArgCount")); + throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("Arg_NegativeArgCount")); } if (destinationIndex < 0) { - throw new ArgumentOutOfRangeException("destinationIndex", - Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegNum", "destinationIndex")); + throw new ArgumentOutOfRangeException(nameof(destinationIndex), + Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegNum", nameof(destinationIndex))); } if (destinationIndex > destination.Length - count) { @@ -750,7 +748,7 @@ namespace System.Text { } if ((uint)sourceIndex > (uint)Length) { - throw new ArgumentOutOfRangeException("sourceIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(sourceIndex), Environment.GetResourceString("ArgumentOutOfRange_Index")); } if (sourceIndex > Length - count) { @@ -794,10 +792,9 @@ namespace System.Text { // The capacity is adjusted as needed. If value equals String.Empty, this // string builder is not changed. // - [System.Security.SecuritySafeCritical] // auto-generated public StringBuilder Insert(int index, String value, int count) { if (count < 0) { - throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.Ensures(Contract.Result<StringBuilder>() != null); Contract.EndContractBlock(); @@ -805,7 +802,7 @@ namespace System.Text { //Range check the index. int currentLength = Length; if ((uint)index > (uint)currentLength) { - throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); } //If value is null, empty or count is 0, do nothing. This is ECMA standard. @@ -819,7 +816,7 @@ namespace System.Text { if (insertingChars > MaxCapacity - this.Length) { throw new OutOfMemoryException(); } - Contract.Assert(insertingChars + this.Length < Int32.MaxValue); + Debug.Assert(insertingChars + this.Length < Int32.MaxValue); StringBuilder chunk; int indexInChunk; @@ -843,11 +840,11 @@ namespace System.Text { // public StringBuilder Remove(int startIndex, int length) { if (length<0) { - throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NegativeLength")); + throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NegativeLength")); } if (startIndex<0) { - throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndex")); + throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex")); } if (length > Length - startIndex) { @@ -989,7 +986,6 @@ namespace System.Text { } // Appends all of the characters in value to the current instance. - [System.Security.SecuritySafeCritical] // auto-generated public StringBuilder Append(char[] value) { Contract.Ensures(Contract.Result<StringBuilder>() != null); @@ -1003,6 +999,88 @@ namespace System.Text { return this; } + // Append joined values with a separator between each value. + public unsafe StringBuilder AppendJoin<T>(char separator, params T[] values) + { + // Defer argument validation to the internal function + return AppendJoinCore(&separator, 1, values); + } + + public unsafe StringBuilder AppendJoin<T>(string separator, params T[] values) + { + separator = separator ?? string.Empty; + fixed (char* pSeparator = separator) + { + // Defer argument validation to the internal function + return AppendJoinCore(pSeparator, separator.Length, values); + } + } + + public unsafe StringBuilder AppendJoin<T>(char separator, IEnumerable<T> values) + { + // Defer argument validation to the internal function + return AppendJoinCore(&separator, 1, values); + } + + public unsafe StringBuilder AppendJoin<T>(string separator, IEnumerable<T> values) + { + separator = separator ?? string.Empty; + fixed (char* pSeparator = separator) + { + // Defer argument validation to the internal function + return AppendJoinCore(pSeparator, separator.Length, values); + } + } + + private unsafe StringBuilder AppendJoinCore<T>(char* separator, int separatorLength, params T[] values) + { + if (values == null) + throw new ArgumentNullException(nameof(values)); + Contract.Ensures(Contract.Result<StringBuilder>() != null); + + if (values.Length == 0) + return this; + + var value = values[0]; + if (value != null) + Append(value.ToString()); + + for (var i = 1; i < values.Length; i++) + { + Append(separator, separatorLength); + value = values[i]; + if (value != null) + Append(value.ToString()); + } + return this; + } + + private unsafe StringBuilder AppendJoinCore<T>(char* separator, int separatorLength, IEnumerable<T> values) + { + if (values == null) + throw new ArgumentNullException(nameof(values)); + Contract.Ensures(Contract.Result<StringBuilder>() != null); + + using (var en = values.GetEnumerator()) + { + if (!en.MoveNext()) + return this; + + var value = en.Current; + if (value != null) + Append(value.ToString()); + + while (en.MoveNext()) + { + Append(separator, separatorLength); + value = en.Current; + if (value != null) + Append(value.ToString()); + } + } + return this; + } + /*====================================Insert==================================== ** ==============================================================================*/ @@ -1012,10 +1090,9 @@ namespace System.Text { // The capacity is adjusted as needed. If value equals String.Empty, the // StringBuilder is not changed. // - [System.Security.SecuritySafeCritical] // auto-generated public StringBuilder Insert(int index, String value) { if ((uint)index > (uint)Length) { - throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); } Contract.Ensures(Contract.Result<StringBuilder>() != null); Contract.EndContractBlock(); @@ -1075,7 +1152,6 @@ namespace System.Text { // the buffer at index. Existing characters are shifted to make room for the new text. // The capacity is adjusted as needed. If value equals String.Empty, the // StringBuilder is not changed. - [SecuritySafeCritical] public StringBuilder Insert(int index, char value) { Contract.Ensures(Contract.Result<StringBuilder>() != null); @@ -1092,7 +1168,7 @@ namespace System.Text { // public StringBuilder Insert(int index, char[] value) { if ((uint)index > (uint)Length) { - throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); } Contract.Ensures(Contract.Result<StringBuilder>() != null); Contract.EndContractBlock(); @@ -1106,13 +1182,12 @@ namespace System.Text { // value inserted into the buffer at index. Existing characters are shifted // to make room for the new text and capacity is adjusted as required. If value is null, the StringBuilder // is unchanged. Characters are taken from value starting at position startIndex. - [System.Security.SecuritySafeCritical] // auto-generated public StringBuilder Insert(int index, char[] value, int startIndex, int charCount) { Contract.Ensures(Contract.Result<StringBuilder>() != null); int currentLength = Length; if ((uint)index > (uint)currentLength) { - throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); } //If they passed in a null char array, just jump out quickly. @@ -1121,12 +1196,12 @@ namespace System.Text { { return this; } - throw new ArgumentNullException("value", Environment.GetResourceString("ArgumentNull_String")); + throw new ArgumentNullException(nameof(value), Environment.GetResourceString("ArgumentNull_String")); } //Range check the array. if (startIndex < 0) { - throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndex")); + throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex")); } if (charCount < 0) { @@ -1134,7 +1209,7 @@ namespace System.Text { } if (startIndex > value.Length - charCount) { - throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index")); } if (charCount > 0) @@ -1255,7 +1330,7 @@ namespace System.Text { { // To preserve the original exception behavior, throw an exception about format if both // args and format are null. The actual null check for format is in AppendFormatHelper. - throw new ArgumentNullException((format == null) ? "format" : "args"); + throw new ArgumentNullException((format == null) ? nameof(format) : nameof(args)); } Contract.Ensures(Contract.Result<String>() != null); Contract.EndContractBlock(); @@ -1283,7 +1358,7 @@ namespace System.Text { { // To preserve the original exception behavior, throw an exception about format if both // args and format are null. The actual null check for format is in AppendFormatHelper. - throw new ArgumentNullException((format == null) ? "format" : "args"); + throw new ArgumentNullException((format == null) ? nameof(format) : nameof(args)); } Contract.Ensures(Contract.Result<String>() != null); Contract.EndContractBlock(); @@ -1301,7 +1376,7 @@ namespace System.Text { internal StringBuilder AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args) { if (format == null) { - throw new ArgumentNullException("format"); + throw new ArgumentNullException(nameof(format)); } Contract.Ensures(Contract.Result<StringBuilder>() != null); Contract.EndContractBlock(); @@ -1582,19 +1657,19 @@ namespace System.Text { int currentLength = Length; if ((uint)startIndex > (uint)currentLength) { - throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index")); } if (count < 0 || startIndex > currentLength - count) { - throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Index")); } if (oldValue == null) { - throw new ArgumentNullException("oldValue"); + throw new ArgumentNullException(nameof(oldValue)); } if (oldValue.Length == 0) { - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "oldValue"); + throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(oldValue)); } if (newValue == null) @@ -1648,7 +1723,7 @@ namespace System.Text { chunk = FindChunkForIndex(index); indexInChunk = index - chunk.m_ChunkOffset; - Contract.Assert(chunk != null || count == 0, "Chunks ended prematurely"); + Debug.Assert(chunk != null || count == 0, "Chunks ended prematurely"); } } VerifyClassInvariant(); @@ -1668,11 +1743,11 @@ namespace System.Text { int currentLength = Length; if ((uint)startIndex > (uint)currentLength) { - throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index")); } if (count < 0 || startIndex > currentLength - count) { - throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Index")); } int endIndex = startIndex + count; @@ -1702,14 +1777,20 @@ namespace System.Text { /// <summary> /// Appends 'value' of length 'count' to the stringBuilder. /// </summary> - [SecurityCritical] [System.CLSCompliantAttribute(false)] public unsafe StringBuilder Append(char* value, int valueCount) { // We don't check null value as this case will throw null reference exception anyway if (valueCount < 0) { - throw new ArgumentOutOfRangeException("valueCount", Environment.GetResourceString("ArgumentOutOfRange_NegativeCount")); + throw new ArgumentOutOfRangeException(nameof(valueCount), Environment.GetResourceString("ArgumentOutOfRange_NegativeCount")); + } + + // this is where we can check if the valueCount will put us over m_MaxCapacity + // We are doing the check here to prevent the corruption of the StringBuilder. + int newLength = Length + valueCount; + if (newLength > m_MaxCapacity || newLength < valueCount) { + throw new ArgumentOutOfRangeException(nameof(valueCount), Environment.GetResourceString("ArgumentOutOfRange_LengthGreaterThanCapacity")); } // This case is so common we want to optimize for it heavily. @@ -1732,7 +1813,7 @@ namespace System.Text { // Expand the builder to add another chunk. int restLength = valueCount - firstLength; ExpandByABlock(restLength); - Contract.Assert(m_ChunkLength == 0, "Expand did not make a new block"); + Debug.Assert(m_ChunkLength == 0, "Expand did not make a new block"); // Copy the second chunk ThreadSafeCopy(value + firstLength, m_ChunkChars, 0, restLength); @@ -1745,12 +1826,11 @@ namespace System.Text { /// <summary> /// Inserts 'value' of length 'cou /// </summary> - [SecurityCritical] unsafe private void Insert(int index, char* value, int valueCount) { if ((uint)index > (uint)Length) { - throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); } if (valueCount > 0) @@ -1768,7 +1848,6 @@ namespace System.Text { /// replacements in bulk (and therefore very efficiently. /// with the string 'value'. /// </summary> - [System.Security.SecuritySafeCritical] // auto-generated private void ReplaceAllInChunk(int[] replacements, int replacementsCount, StringBuilder sourceChunk, int removeCount, string value) { if (replacementsCount <= 0) @@ -1798,9 +1877,9 @@ namespace System.Text { break; int gapEnd = replacements[i]; - Contract.Assert(gapStart < sourceChunk.m_ChunkChars.Length, "gap starts at end of buffer. Should not happen"); - Contract.Assert(gapStart <= gapEnd, "negative gap size"); - Contract.Assert(gapEnd <= sourceChunk.m_ChunkLength, "gap too big"); + Debug.Assert(gapStart < sourceChunk.m_ChunkChars.Length, "gap starts at end of buffer. Should not happen"); + Debug.Assert(gapStart <= gapEnd, "negative gap size"); + Debug.Assert(gapEnd <= sourceChunk.m_ChunkLength, "gap too big"); if (delta != 0) // can skip the sliding of gaps if source an target string are the same size. { // Copy the gap data between the current replacement and the the next replacement @@ -1810,7 +1889,7 @@ namespace System.Text { else { targetIndexInChunk += gapEnd - gapStart; - Contract.Assert(targetIndexInChunk <= targetChunk.m_ChunkLength, "gap not in chunk"); + Debug.Assert(targetIndexInChunk <= targetChunk.m_ChunkLength, "gap not in chunk"); } } @@ -1855,7 +1934,6 @@ namespace System.Text { /// point at the end of the characters just copyied (thus you can splice in strings from multiple /// places by calling this mulitple times. /// </summary> - [SecurityCritical] unsafe private void ReplaceInPlaceAtChunk(ref StringBuilder chunk, ref int indexInChunk, char* value, int count) { if (count != 0) @@ -1863,7 +1941,7 @@ namespace System.Text { for (; ; ) { int lengthInChunk = chunk.m_ChunkLength - indexInChunk; - Contract.Assert(lengthInChunk >= 0, "index not in chunk"); + Debug.Assert(lengthInChunk >= 0, "index not in chunk"); int lengthToCopy = Math.Min(lengthInChunk, count); ThreadSafeCopy(value, chunk.m_ChunkChars, indexInChunk, lengthToCopy); @@ -1888,7 +1966,6 @@ namespace System.Text { /// The only way to do this is to copy all interesting variables out of the heap and then do the /// bounds check. This is what we do here. /// </summary> - [SecurityCritical] unsafe private static void ThreadSafeCopy(char* sourcePtr, char[] destination, int destinationIndex, int count) { if (count > 0) @@ -1900,11 +1977,10 @@ namespace System.Text { } else { - throw new ArgumentOutOfRangeException("destinationIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(destinationIndex), Environment.GetResourceString("ArgumentOutOfRange_Index")); } } } - [SecurityCritical] private static void ThreadSafeCopy(char[] source, int sourceIndex, char[] destination, int destinationIndex, int count) { if (count > 0) @@ -1918,13 +1994,12 @@ namespace System.Text { } else { - throw new ArgumentOutOfRangeException("sourceIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(sourceIndex), Environment.GetResourceString("ArgumentOutOfRange_Index")); } } } // Copies the source StringBuilder to the destination IntPtr memory allocated with len bytes. - [System.Security.SecurityCritical] // auto-generated internal unsafe void InternalCopy(IntPtr dest, int len) { if(len ==0) return; @@ -1957,13 +2032,13 @@ namespace System.Text { /// <returns></returns> private StringBuilder FindChunkForIndex(int index) { - Contract.Assert(0 <= index && index <= Length, "index not in string"); + Debug.Assert(0 <= index && index <= Length, "index not in string"); StringBuilder ret = this; while (ret.m_ChunkOffset > index) ret = ret.m_ChunkPrevious; - Contract.Assert(ret != null, "index not in string"); + Debug.Assert(ret != null, "index not in string"); return ret; } @@ -1974,13 +2049,13 @@ namespace System.Text { /// <returns></returns> private StringBuilder FindChunkForByte(int byteIndex) { - Contract.Assert(0 <= byteIndex && byteIndex <= Length*sizeof(char), "Byte Index not in string"); + Debug.Assert(0 <= byteIndex && byteIndex <= Length*sizeof(char), "Byte Index not in string"); StringBuilder ret = this; while (ret.m_ChunkOffset*sizeof(char) > byteIndex) ret = ret.m_ChunkPrevious; - Contract.Assert(ret != null, "Byte Index not in string"); + Debug.Assert(ret != null, "Byte Index not in string"); return ret; } @@ -2063,12 +2138,11 @@ namespace System.Text { /// If dontMoveFollowingChars is true, then the room must be made by inserting a chunk BEFORE the /// current chunk (this is what it does most of the time anyway) /// </summary> - [System.Security.SecuritySafeCritical] // auto-generated private void MakeRoom(int index, int count, out StringBuilder chunk, out int indexInChunk, bool doneMoveFollowingChars) { VerifyClassInvariant(); - Contract.Assert(count > 0, "Count must be strictly positive"); - Contract.Assert(index >= 0, "Index can't be negative"); + Debug.Assert(count > 0, "Count must be strictly positive"); + Debug.Assert(index >= 0, "Index can't be negative"); if (count + Length > m_MaxCapacity || count + Length < count) throw new ArgumentOutOfRangeException("requiredLength", Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity")); @@ -2133,8 +2207,8 @@ namespace System.Text { /// </summary> private StringBuilder(int size, int maxCapacity, StringBuilder previousBlock) { - Contract.Assert(size > 0, "size not positive"); - Contract.Assert(maxCapacity > 0, "maxCapacity not positive"); + Debug.Assert(size > 0, "size not positive"); + Debug.Assert(maxCapacity > 0, "maxCapacity not positive"); m_ChunkChars = new char[size]; m_MaxCapacity = maxCapacity; m_ChunkPrevious = previousBlock; @@ -2147,11 +2221,10 @@ namespace System.Text { /// Removes 'count' characters from the logical index 'startIndex' and returns the chunk and /// index in the chunk of that logical index in the out parameters. /// </summary> - [SecuritySafeCritical] private void Remove(int startIndex, int count, out StringBuilder chunk, out int indexInChunk) { VerifyClassInvariant(); - Contract.Assert(startIndex >= 0 && startIndex < Length, "startIndex not in string"); + Debug.Assert(startIndex >= 0 && startIndex < Length, "startIndex not in string"); int endIndex = startIndex + count; @@ -2180,7 +2253,7 @@ namespace System.Text { } chunk = chunk.m_ChunkPrevious; } - Contract.Assert(chunk != null, "fell off beginning of string!"); + Debug.Assert(chunk != null, "fell off beginning of string!"); int copyTargetIndexInChunk = indexInChunk; int copyCount = endChunk.m_ChunkLength - endIndexInChunk; @@ -2210,7 +2283,7 @@ namespace System.Text { if (copyTargetIndexInChunk != endIndexInChunk) // Sometimes no move is necessary ThreadSafeCopy(endChunk.m_ChunkChars, endIndexInChunk, endChunk.m_ChunkChars, copyTargetIndexInChunk, copyCount); - Contract.Assert(chunk != null, "fell off beginning of string!"); + Debug.Assert(chunk != null, "fell off beginning of string!"); VerifyClassInvariant(); } } diff --git a/src/mscorlib/src/System/Text/SurrogateEncoder.cs b/src/mscorlib/src/System/Text/SurrogateEncoder.cs index 409e8a34aa..bbfa180f29 100644 --- a/src/mscorlib/src/System/Text/SurrogateEncoder.cs +++ b/src/mscorlib/src/System/Text/SurrogateEncoder.cs @@ -12,6 +12,7 @@ namespace System.Text using System; using System.Runtime.Serialization; using System.Security.Permissions; + using System.Diagnostics; using System.Diagnostics.Contracts; /*=================================SurrogateEncoder================================== @@ -30,7 +31,7 @@ namespace System.Text internal SurrogateEncoder(SerializationInfo info, StreamingContext context) { // Any info? - if (info==null) throw new ArgumentNullException("info"); + if (info==null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); // All versions have a code page @@ -38,7 +39,6 @@ namespace System.Text } // Just get it from GetEncoding - [System.Security.SecurityCritical] // auto-generated public Object GetRealObject(StreamingContext context) { // Need to get our Encoding's Encoder @@ -46,11 +46,10 @@ namespace System.Text } // ISerializable implementation - [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // We cannot ever call this. - Contract.Assert(false, "Didn't expect to make it to SurrogateEncoder.GetObjectData"); + Debug.Assert(false, "Didn't expect to make it to SurrogateEncoder.GetObjectData"); throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException")); } } diff --git a/src/mscorlib/src/System/Text/UTF32Encoding.cs b/src/mscorlib/src/System/Text/UTF32Encoding.cs index 0bdbaefbf2..a7ac1d8539 100644 --- a/src/mscorlib/src/System/Text/UTF32Encoding.cs +++ b/src/mscorlib/src/System/Text/UTF32Encoding.cs @@ -10,6 +10,7 @@ namespace System.Text { using System; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; // Encodes text into and out of UTF-32. UTF-32 is a way of writing @@ -109,7 +110,6 @@ namespace System.Text return EncodingForwarder.GetByteCount(this, s); } - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public override unsafe int GetByteCount(char* chars, int count) { @@ -137,7 +137,6 @@ namespace System.Text return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex); } - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { @@ -152,7 +151,6 @@ namespace System.Text return EncodingForwarder.GetCharCount(this, bytes, index, count); } - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public override unsafe int GetCharCount(byte* bytes, int count) { @@ -165,7 +163,6 @@ namespace System.Text return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex); } - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { @@ -182,11 +179,10 @@ namespace System.Text // End of overridden methods which use EncodingForwarder - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetByteCount(char *chars, int count, EncoderNLS encoder) { - Contract.Assert(chars!=null, "[UTF32Encoding.GetByteCount]chars!=null"); - Contract.Assert(count >=0, "[UTF32Encoding.GetByteCount]count >=0"); + Debug.Assert(chars!=null, "[UTF32Encoding.GetByteCount]chars!=null"); + Debug.Assert(count >=0, "[UTF32Encoding.GetByteCount]count >=0"); char* end = chars + count; char* charStart = chars; @@ -248,7 +244,7 @@ namespace System.Text // We are missing our low surrogate, decrement chars and fallback the high surrogate // The high surrogate may have come from the encoder, but nothing else did. - Contract.Assert(chars > charStart, + Debug.Assert(chars > charStart, "[UTF32Encoding.GetByteCount]Expected chars to have advanced if no low surrogate"); chars--; @@ -296,26 +292,25 @@ namespace System.Text // Check for overflows. if (byteCount < 0) - throw new ArgumentOutOfRangeException("count", Environment.GetResourceString( + throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString( "ArgumentOutOfRange_GetByteCountOverflow")); // Shouldn't have anything in fallback buffer for GetByteCount // (don't have to check m_throwOnOverflow for count) - Contract.Assert(fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer.Remaining == 0, "[UTF32Encoding.GetByteCount]Expected empty fallback buffer at end"); // Return our count return byteCount; } - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetBytes(char *chars, int charCount, byte* bytes, int byteCount, EncoderNLS encoder) { - Contract.Assert(chars!=null, "[UTF32Encoding.GetBytes]chars!=null"); - Contract.Assert(bytes!=null, "[UTF32Encoding.GetBytes]bytes!=null"); - Contract.Assert(byteCount >=0, "[UTF32Encoding.GetBytes]byteCount >=0"); - Contract.Assert(charCount >=0, "[UTF32Encoding.GetBytes]charCount >=0"); + Debug.Assert(chars!=null, "[UTF32Encoding.GetBytes]chars!=null"); + Debug.Assert(bytes!=null, "[UTF32Encoding.GetBytes]bytes!=null"); + Debug.Assert(byteCount >=0, "[UTF32Encoding.GetBytes]byteCount >=0"); + Debug.Assert(charCount >=0, "[UTF32Encoding.GetBytes]charCount >=0"); char* charStart = chars; char* charEnd = chars + charCount; @@ -384,7 +379,7 @@ namespace System.Text { // If we don't have enough room, then either we should've advanced a while // or we should have bytes==byteStart and throw below - Contract.Assert(chars > charStart + 1 || bytes == byteStart, + Debug.Assert(chars > charStart + 1 || bytes == byteStart, "[UnicodeEncoding.GetBytes]Expected chars to have when no room to add surrogate pair"); chars-=2; // Aren't using those 2 chars } @@ -412,7 +407,7 @@ namespace System.Text // We are missing our low surrogate, decrement chars and fallback the high surrogate // The high surrogate may have come from the encoder, but nothing else did. - Contract.Assert(chars > charStart, + Debug.Assert(chars > charStart, "[UTF32Encoding.GetBytes]Expected chars to have advanced if no low surrogate"); chars--; @@ -453,7 +448,7 @@ namespace System.Text else { // Must've advanced already - Contract.Assert(chars > charStart, + Debug.Assert(chars > charStart, "[UTF32Encoding.GetBytes]Expected chars to have advanced if normal character"); chars--; // Aren't using this char } @@ -487,7 +482,7 @@ namespace System.Text } // Fix our encoder if we have one - Contract.Assert(highSurrogate == 0 || (encoder != null && !encoder.MustFlush), + Debug.Assert(highSurrogate == 0 || (encoder != null && !encoder.MustFlush), "[UTF32Encoding.GetBytes]Expected encoder to be flushed."); if (encoder != null) @@ -503,11 +498,10 @@ namespace System.Text return (int)(bytes - byteStart); } - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) { - Contract.Assert(bytes!=null, "[UTF32Encoding.GetCharCount]bytes!=null"); - Contract.Assert(count >=0, "[UTF32Encoding.GetCharCount]count >=0"); + Debug.Assert(bytes!=null, "[UTF32Encoding.GetCharCount]bytes!=null"); + Debug.Assert(count >=0, "[UTF32Encoding.GetCharCount]count >=0"); UTF32Decoder decoder = (UTF32Decoder)baseDecoder; @@ -532,7 +526,7 @@ namespace System.Text // Shouldn't have anything in fallback buffer for GetCharCount // (don't have to check m_throwOnOverflow for chars or count) - Contract.Assert(fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer.Remaining == 0, "[UTF32Encoding.GetCharCount]Expected empty fallback buffer at start"); } else @@ -635,25 +629,24 @@ namespace System.Text // Check for overflows. if (charCount < 0) - throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); + throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); // Shouldn't have anything in fallback buffer for GetCharCount // (don't have to check m_throwOnOverflow for chars or count) - Contract.Assert(fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer.Remaining == 0, "[UTF32Encoding.GetCharCount]Expected empty fallback buffer at end"); // Return our count return charCount; } - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS baseDecoder) { - Contract.Assert(chars!=null, "[UTF32Encoding.GetChars]chars!=null"); - Contract.Assert(bytes!=null, "[UTF32Encoding.GetChars]bytes!=null"); - Contract.Assert(byteCount >=0, "[UTF32Encoding.GetChars]byteCount >=0"); - Contract.Assert(charCount >=0, "[UTF32Encoding.GetChars]charCount >=0"); + Debug.Assert(chars!=null, "[UTF32Encoding.GetChars]chars!=null"); + Debug.Assert(bytes!=null, "[UTF32Encoding.GetChars]bytes!=null"); + Debug.Assert(byteCount >=0, "[UTF32Encoding.GetChars]byteCount >=0"); + Debug.Assert(charCount >=0, "[UTF32Encoding.GetChars]charCount >=0"); UTF32Decoder decoder = (UTF32Decoder)baseDecoder; @@ -680,7 +673,7 @@ namespace System.Text // Shouldn't have anything in fallback buffer for GetChars // (don't have to check m_throwOnOverflow for chars) - Contract.Assert(fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer.Remaining == 0, "[UTF32Encoding.GetChars]Expected empty fallback buffer at start"); } else @@ -741,7 +734,7 @@ namespace System.Text // Couldn't fallback, throw or wait til next time // We either read enough bytes for bytes-=4 to work, or we're // going to throw in ThrowCharsOverflow because chars == charStart - Contract.Assert(bytes >= byteStart + 4 || chars == charStart, + Debug.Assert(bytes >= byteStart + 4 || chars == charStart, "[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (bad surrogate)"); bytes-=4; // get back to where we were iChar=0; // Remembering nothing @@ -765,7 +758,7 @@ namespace System.Text // Throwing or stopping // We either read enough bytes for bytes-=4 to work, or we're // going to throw in ThrowCharsOverflow because chars == charStart - Contract.Assert(bytes >= byteStart + 4 || chars == charStart, + Debug.Assert(bytes >= byteStart + 4 || chars == charStart, "[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (surrogate)"); bytes-=4; // get back to where we were iChar=0; // Remembering nothing @@ -782,7 +775,7 @@ namespace System.Text // Throwing or stopping // We either read enough bytes for bytes-=4 to work, or we're // going to throw in ThrowCharsOverflow because chars == charStart - Contract.Assert(bytes >= byteStart + 4 || chars == charStart, + Debug.Assert(bytes >= byteStart + 4 || chars == charStart, "[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (normal char)"); bytes-=4; // get back to where we were iChar=0; // Remembering nothing @@ -846,7 +839,7 @@ namespace System.Text // Shouldn't have anything in fallback buffer for GetChars // (don't have to check m_throwOnOverflow for chars) - Contract.Assert(fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer.Remaining == 0, "[UTF32Encoding.GetChars]Expected empty fallback buffer at end"); // Return our count @@ -885,7 +878,7 @@ namespace System.Text public override int GetMaxByteCount(int charCount) { if (charCount < 0) - throw new ArgumentOutOfRangeException("charCount", + throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -899,7 +892,7 @@ namespace System.Text byteCount *= 4; if (byteCount > 0x7fffffff) - throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); + throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); return (int)byteCount; } @@ -908,7 +901,7 @@ namespace System.Text public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) - throw new ArgumentOutOfRangeException("byteCount", + throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -929,7 +922,7 @@ namespace System.Text } if (charCount > 0x7fffffff) - throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow")); + throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow")); return (int)charCount; } diff --git a/src/mscorlib/src/System/Text/UTF7Encoding.cs b/src/mscorlib/src/System/Text/UTF7Encoding.cs index 654fb8b80f..624ca735f6 100644 --- a/src/mscorlib/src/System/Text/UTF7Encoding.cs +++ b/src/mscorlib/src/System/Text/UTF7Encoding.cs @@ -11,6 +11,7 @@ namespace System.Text using System; using System.Runtime.Serialization; using System.Security.Permissions; + using System.Diagnostics; using System.Diagnostics.Contracts; @@ -175,7 +176,6 @@ namespace System.Text return EncodingForwarder.GetByteCount(this, s); } - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public override unsafe int GetByteCount(char* chars, int count) @@ -205,7 +205,6 @@ namespace System.Text return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex); } - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) @@ -221,7 +220,6 @@ namespace System.Text return EncodingForwarder.GetCharCount(this, bytes, index, count); } - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public override unsafe int GetCharCount(byte* bytes, int count) @@ -235,7 +233,6 @@ namespace System.Text return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex); } - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) @@ -254,23 +251,21 @@ namespace System.Text // End of overridden methods which use EncodingForwarder - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS baseEncoder) { - Contract.Assert(chars!=null, "[UTF7Encoding.GetByteCount]chars!=null"); - Contract.Assert(count >=0, "[UTF7Encoding.GetByteCount]count >=0"); + Debug.Assert(chars!=null, "[UTF7Encoding.GetByteCount]chars!=null"); + Debug.Assert(count >=0, "[UTF7Encoding.GetByteCount]count >=0"); // Just call GetBytes with bytes == null return GetBytes(chars, count, null, 0, baseEncoder); } - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS baseEncoder) { - Contract.Assert(byteCount >=0, "[UTF7Encoding.GetBytes]byteCount >=0"); - Contract.Assert(chars!=null, "[UTF7Encoding.GetBytes]chars!=null"); - Contract.Assert(charCount >=0, "[UTF7Encoding.GetBytes]charCount >=0"); + Debug.Assert(byteCount >=0, "[UTF7Encoding.GetBytes]byteCount >=0"); + Debug.Assert(chars!=null, "[UTF7Encoding.GetBytes]chars!=null"); + Debug.Assert(charCount >=0, "[UTF7Encoding.GetBytes]charCount >=0"); // Get encoder info UTF7Encoding.Encoder encoder = (UTF7Encoding.Encoder)baseEncoder; @@ -405,23 +400,21 @@ namespace System.Text return buffer.Count; } - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) { - Contract.Assert(count >=0, "[UTF7Encoding.GetCharCount]count >=0"); - Contract.Assert(bytes!=null, "[UTF7Encoding.GetCharCount]bytes!=null"); + Debug.Assert(count >=0, "[UTF7Encoding.GetCharCount]count >=0"); + Debug.Assert(bytes!=null, "[UTF7Encoding.GetCharCount]bytes!=null"); // Just call GetChars with null char* to do counting return GetChars(bytes, count, null, 0, baseDecoder); } - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS baseDecoder) { - Contract.Assert(byteCount >=0, "[UTF7Encoding.GetChars]byteCount >=0"); - Contract.Assert(bytes!=null, "[UTF7Encoding.GetChars]bytes!=null"); - Contract.Assert(charCount >=0, "[UTF7Encoding.GetChars]charCount >=0"); + Debug.Assert(byteCount >=0, "[UTF7Encoding.GetChars]byteCount >=0"); + Debug.Assert(bytes!=null, "[UTF7Encoding.GetChars]bytes!=null"); + Debug.Assert(charCount >=0, "[UTF7Encoding.GetChars]charCount >=0"); // Might use a decoder UTF7Encoding.Decoder decoder = (UTF7Encoding.Decoder) baseDecoder; @@ -440,7 +433,7 @@ namespace System.Text bitCount = decoder.bitCount; firstByte = decoder.firstByte; - Contract.Assert(firstByte == false || decoder.bitCount <= 0, + Debug.Assert(firstByte == false || decoder.bitCount <= 0, "[UTF7Encoding.GetChars]If remembered bits, then first byte flag shouldn't be set"); } @@ -599,7 +592,7 @@ namespace System.Text public override int GetMaxByteCount(int charCount) { if (charCount < 0) - throw new ArgumentOutOfRangeException("charCount", + throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -623,7 +616,7 @@ namespace System.Text // check for overflow if (byteCount > 0x7fffffff) - throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); + throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); return (int)byteCount; } @@ -632,7 +625,7 @@ namespace System.Text public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) - throw new ArgumentOutOfRangeException("byteCount", + throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -663,7 +656,7 @@ namespace System.Text internal Decoder(SerializationInfo info, StreamingContext context) { // Any info? - if (info==null) throw new ArgumentNullException("info"); + if (info==null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); // Get common info @@ -674,11 +667,10 @@ namespace System.Text } // ISerializable implementation, get data for this object - [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // Any info? - if (info==null) throw new ArgumentNullException("info"); + if (info==null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); // Save Whidbey data @@ -727,7 +719,7 @@ namespace System.Text internal Encoder(SerializationInfo info, StreamingContext context) { // Any info? - if (info==null) throw new ArgumentNullException("info"); + if (info==null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); // Get common info @@ -737,11 +729,10 @@ namespace System.Text } // ISerializable implementation, get data for this object - [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // Any info? - if (info==null) throw new ArgumentNullException("info"); + if (info==null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); // Save Whidbey data @@ -825,8 +816,8 @@ namespace System.Text public override bool Fallback(byte[] bytesUnknown, int index) { // We expect no previous fallback in our buffer - Contract.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.Fallback] Can't have recursive fallbacks"); - Contract.Assert(bytesUnknown.Length == 1, "[DecoderUTF7FallbackBuffer.Fallback] Only possible fallback case should be 1 unknown byte"); + Debug.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.Fallback] Can't have recursive fallbacks"); + Debug.Assert(bytesUnknown.Length == 1, "[DecoderUTF7FallbackBuffer.Fallback] Only possible fallback case should be 1 unknown byte"); // Go ahead and get our fallback cFallback = (char)bytesUnknown[0]; @@ -872,7 +863,6 @@ namespace System.Text } // Clear the buffer - [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe void Reset() { iCount = -1; @@ -880,13 +870,12 @@ namespace System.Text } // This version just counts the fallback and doesn't actually copy anything. - [System.Security.SecurityCritical] // auto-generated internal unsafe override int InternalFallback(byte[] bytes, byte* pBytes) // Right now this has both bytes and bytes[], since we might have extra bytes, hence the // array, and we might need the index, hence the byte* { // We expect no previous fallback in our buffer - Contract.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.InternalFallback] Can't have recursive fallbacks"); + Debug.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.InternalFallback] Can't have recursive fallbacks"); if (bytes.Length != 1) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex")); diff --git a/src/mscorlib/src/System/Text/UTF8Encoding.cs b/src/mscorlib/src/System/Text/UTF8Encoding.cs index a527de7b61..ba19649b56 100644 --- a/src/mscorlib/src/System/Text/UTF8Encoding.cs +++ b/src/mscorlib/src/System/Text/UTF8Encoding.cs @@ -21,6 +21,7 @@ namespace System.Text using System.Globalization; using System.Runtime.Serialization; using System.Security.Permissions; + using System.Diagnostics; using System.Diagnostics.Contracts; // Encodes text into and out of UTF-8. UTF-8 is a way of writing @@ -129,7 +130,6 @@ namespace System.Text return EncodingForwarder.GetByteCount(this, chars); } - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public override unsafe int GetByteCount(char* chars, int count) @@ -158,7 +158,6 @@ namespace System.Text return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex); } - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) @@ -174,7 +173,6 @@ namespace System.Text return EncodingForwarder.GetCharCount(this, bytes, index, count); } - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public override unsafe int GetCharCount(byte* bytes, int count) @@ -188,7 +186,6 @@ namespace System.Text return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex); } - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) @@ -209,7 +206,6 @@ namespace System.Text // To simplify maintenance, the structure of GetByteCount and GetBytes should be // kept the same as much as possible - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetByteCount(char *chars, int count, EncoderNLS baseEncoder) { // For fallback we may need a fallback buffer. @@ -254,7 +250,7 @@ namespace System.Text } else { // Case of surrogates in the fallback. if (fallbackBuffer != null && fallbackBuffer.bFallingBack) { - Contract.Assert(ch >= 0xD800 && ch <= 0xDBFF, + Debug.Assert(ch >= 0xD800 && ch <= 0xDBFF, "[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString("X4", CultureInfo.InvariantCulture)); ch = fallbackBuffer.InternalGetNextChar(); @@ -286,7 +282,7 @@ namespace System.Text } if (ch > 0) { - Contract.Assert(ch >= 0xD800 && ch <= 0xDBFF, + Debug.Assert(ch >= 0xD800 && ch <= 0xDBFF, "[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString("X4", CultureInfo.InvariantCulture)); // use separate helper variables for local contexts so that the jit optimizations @@ -557,7 +553,7 @@ namespace System.Text } #endif - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[UTF8Encoding.GetByteCount]Expected Empty fallback buffer"); return byteCount; @@ -566,14 +562,12 @@ namespace System.Text // diffs two char pointers using unsigned arithmetic. The unsigned arithmetic // is good enough for us, and it tends to generate better code than the signed // arithmetic generated by default - [System.Security.SecurityCritical] // auto-generated unsafe private static int PtrDiff(char *a, char* b) { return (int)(((uint)((byte*)a - (byte*)b)) >> 1); } // byte* flavor just for parity - [System.Security.SecurityCritical] // auto-generated unsafe private static int PtrDiff(byte* a, byte* b) { return (int)(a - b); @@ -586,14 +580,13 @@ namespace System.Text // Our workhorse // Note: We ignore mismatched surrogates, unless the exception flag is set in which case we throw - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS baseEncoder) { - Contract.Assert(chars!=null, "[UTF8Encoding.GetBytes]chars!=null"); - Contract.Assert(byteCount >=0, "[UTF8Encoding.GetBytes]byteCount >=0"); - Contract.Assert(charCount >=0, "[UTF8Encoding.GetBytes]charCount >=0"); - Contract.Assert(bytes!=null, "[UTF8Encoding.GetBytes]bytes!=null"); + Debug.Assert(chars!=null, "[UTF8Encoding.GetBytes]chars!=null"); + Debug.Assert(byteCount >=0, "[UTF8Encoding.GetBytes]byteCount >=0"); + Debug.Assert(charCount >=0, "[UTF8Encoding.GetBytes]charCount >=0"); + Debug.Assert(bytes!=null, "[UTF8Encoding.GetBytes]bytes!=null"); UTF8Encoder encoder = null; @@ -642,7 +635,7 @@ namespace System.Text } else { // Case of leftover surrogates in the fallback buffer if (fallbackBuffer != null && fallbackBuffer.bFallingBack) { - Contract.Assert(ch >= 0xD800 && ch <= 0xDBFF, + Debug.Assert(ch >= 0xD800 && ch <= 0xDBFF, "[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString("X4", CultureInfo.InvariantCulture)); int cha = ch; @@ -670,7 +663,7 @@ namespace System.Text if (ch > 0) { // We have a high surrogate left over from a previous loop. - Contract.Assert(ch >= 0xD800 && ch <= 0xDBFF, + Debug.Assert(ch >= 0xD800 && ch <= 0xDBFF, "[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString("X4", CultureInfo.InvariantCulture)); // use separate helper variables for local contexts so that the jit optimizations @@ -767,7 +760,7 @@ namespace System.Text if (ch > 0xFFFF) pSrc--; // Was surrogate, didn't use 2nd part either } - Contract.Assert(pSrc >= chars || pTarget == bytes, + Debug.Assert(pSrc >= chars || pTarget == bytes, "[UTF8Encoding.GetBytes]Expected pSrc to be within buffer or to throw with insufficient room."); ThrowBytesOverflow(encoder, pTarget == bytes); // Throw if we must ch = 0; // Nothing left over (we backed up to start of pair if supplimentary) @@ -989,7 +982,7 @@ namespace System.Text pTarget++; } - Contract.Assert(pTarget <= pAllocatedBufferEnd, "[UTF8Encoding.GetBytes]pTarget <= pAllocatedBufferEnd"); + Debug.Assert(pTarget <= pAllocatedBufferEnd, "[UTF8Encoding.GetBytes]pTarget <= pAllocatedBufferEnd"); #endif // FASTLOOP @@ -1000,14 +993,14 @@ namespace System.Text // Do we have to set the encoder bytes? if (encoder != null) { - Contract.Assert(!encoder.MustFlush || ch == 0, + Debug.Assert(!encoder.MustFlush || ch == 0, "[UTF8Encoding.GetBytes] Expected no mustflush or 0 leftover ch " + ch.ToString("X2", CultureInfo.InvariantCulture)); encoder.surrogateChar = ch; encoder.m_charsUsed = (int)(pSrc - chars); } - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 || + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 || baseEncoder == null || !baseEncoder.m_throwOnOverflow, "[UTF8Encoding.GetBytes]Expected empty fallback buffer if not converting"); @@ -1029,11 +1022,10 @@ namespace System.Text // // To simplify maintenance, the structure of GetCharCount and GetChars should be // kept the same as much as possible - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) { - Contract.Assert(count >=0, "[UTF8Encoding.GetCharCount]count >=0"); - Contract.Assert(bytes!=null, "[UTF8Encoding.GetCharCount]bytes!=null"); + Debug.Assert(count >=0, "[UTF8Encoding.GetCharCount]count >=0"); + Debug.Assert(bytes!=null, "[UTF8Encoding.GetCharCount]bytes!=null"); // Initialize stuff byte *pSrc = bytes; @@ -1052,7 +1044,7 @@ namespace System.Text // Shouldn't have anything in fallback buffer for GetCharCount // (don't have to check m_throwOnOverflow for count) - Contract.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, + Debug.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[UTF8Encoding.GetCharCount]Expected empty fallback buffer at start"); } @@ -1087,7 +1079,7 @@ namespace System.Text ch = (ch << 6) | (cha & 0x3F); if ((ch & FinalByte) == 0) { - Contract.Assert( (ch & (SupplimentarySeq | ThreeByteSeq)) != 0, + Debug.Assert( (ch & (SupplimentarySeq | ThreeByteSeq)) != 0, "[UTF8Encoding.GetChars]Invariant volation"); if ((ch & SupplimentarySeq) != 0) { @@ -1408,7 +1400,7 @@ namespace System.Text // Shouldn't have anything in fallback buffer for GetCharCount // (don't have to check m_throwOnOverflow for count) - Contract.Assert(fallback == null || fallback.Remaining == 0, + Debug.Assert(fallback == null || fallback.Remaining == 0, "[UTF8Encoding.GetCharCount]Expected empty fallback buffer at end"); return charCount; @@ -1424,14 +1416,13 @@ namespace System.Text // // To simplify maintenance, the structure of GetCharCount and GetChars should be // kept the same as much as possible - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS baseDecoder) { - Contract.Assert(chars!=null, "[UTF8Encoding.GetChars]chars!=null"); - Contract.Assert(byteCount >=0, "[UTF8Encoding.GetChars]count >=0"); - Contract.Assert(charCount >=0, "[UTF8Encoding.GetChars]charCount >=0"); - Contract.Assert(bytes!=null, "[UTF8Encoding.GetChars]bytes!=null"); + Debug.Assert(chars!=null, "[UTF8Encoding.GetChars]chars!=null"); + Debug.Assert(byteCount >=0, "[UTF8Encoding.GetChars]count >=0"); + Debug.Assert(charCount >=0, "[UTF8Encoding.GetChars]charCount >=0"); + Debug.Assert(bytes!=null, "[UTF8Encoding.GetChars]bytes!=null"); byte *pSrc = bytes; char *pTarget = chars; @@ -1448,7 +1439,7 @@ namespace System.Text // Shouldn't have anything in fallback buffer for GetChars // (don't have to check m_throwOnOverflow for chars, we always use all or none so always should be empty) - Contract.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, + Debug.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[UTF8Encoding.GetChars]Expected empty fallback buffer at start"); } @@ -1483,7 +1474,7 @@ namespace System.Text if ((ch & FinalByte) == 0) { // Not at last byte yet - Contract.Assert( (ch & (SupplimentarySeq | ThreeByteSeq)) != 0, + Debug.Assert( (ch & (SupplimentarySeq | ThreeByteSeq)) != 0, "[UTF8Encoding.GetChars]Invariant volation"); if ((ch & SupplimentarySeq) != 0) { @@ -1546,14 +1537,14 @@ namespace System.Text { // Ran out of buffer space // Need to throw an exception? - Contract.Assert(pSrc >= bytes || pTarget == chars, + Debug.Assert(pSrc >= bytes || pTarget == chars, "[UTF8Encoding.GetChars]Expected to throw or remain in byte buffer after fallback"); fallback.InternalReset(); ThrowCharsOverflow(baseDecoder, pTarget == chars); ch = 0; break; } - Contract.Assert(pSrc >= bytes, + Debug.Assert(pSrc >= bytes, "[UTF8Encoding.GetChars]Expected invalid byte sequence to have remained within the byte array"); ch = 0; continue; @@ -1639,7 +1630,7 @@ namespace System.Text // Throw that we don't have enough room (pSrc could be < chars if we had started to process // a 4 byte sequence alredy) - Contract.Assert(pSrc >= bytes || pTarget == chars, + Debug.Assert(pSrc >= bytes || pTarget == chars, "[UTF8Encoding.GetChars]Expected pSrc to be within input buffer or throw due to no output]"); ThrowCharsOverflow(baseDecoder, pTarget == chars); @@ -1893,7 +1884,7 @@ namespace System.Text } #endif // FASTLOOP - Contract.Assert(pTarget <= pAllocatedBufferEnd, "[UTF8Encoding.GetChars]pTarget <= pAllocatedBufferEnd"); + Debug.Assert(pTarget <= pAllocatedBufferEnd, "[UTF8Encoding.GetChars]pTarget <= pAllocatedBufferEnd"); // no pending bits at this point ch = 0; @@ -1920,7 +1911,7 @@ namespace System.Text // This'll back us up the appropriate # of bytes if we didn't get anywhere if (!FallbackInvalidByteSequence(ref pSrc, ch, fallback, ref pTarget)) { - Contract.Assert(pSrc >= bytes || pTarget == chars, + Debug.Assert(pSrc >= bytes || pTarget == chars, "[UTF8Encoding.GetChars]Expected to throw or remain in byte buffer while flushing"); // Ran out of buffer space @@ -1928,7 +1919,7 @@ namespace System.Text fallback.InternalReset(); ThrowCharsOverflow(baseDecoder, pTarget == chars); } - Contract.Assert(pSrc >= bytes, + Debug.Assert(pSrc >= bytes, "[UTF8Encoding.GetChars]Expected flushing invalid byte sequence to have remained within the byte array"); ch = 0; } @@ -1939,7 +1930,7 @@ namespace System.Text // If we're storing flush data we expect all bits to be used or else // we're stuck in the middle of a conversion - Contract.Assert(!baseDecoder.MustFlush || ch == 0 || !baseDecoder.m_throwOnOverflow, + Debug.Assert(!baseDecoder.MustFlush || ch == 0 || !baseDecoder.m_throwOnOverflow, "[UTF8Encoding.GetChars]Expected no must flush or no left over bits or no throw on overflow."); // Remember our leftover bits. @@ -1950,7 +1941,7 @@ namespace System.Text // Shouldn't have anything in fallback buffer for GetChars // (don't have to check m_throwOnOverflow for chars) - Contract.Assert(fallback == null || fallback.Remaining == 0, + Debug.Assert(fallback == null || fallback.Remaining == 0, "[UTF8Encoding.GetChars]Expected empty fallback buffer at end"); return PtrDiff(pTarget, chars); @@ -1959,7 +1950,6 @@ namespace System.Text // During GetChars we had an invalid byte sequence // pSrc is backed up to the start of the bad sequence if we didn't have room to // fall it back. Otherwise pSrc remains wher it is. - [System.Security.SecurityCritical] // auto-generated private unsafe bool FallbackInvalidByteSequence( ref byte* pSrc, int ch, DecoderFallbackBuffer fallback, ref char* pTarget) { @@ -1982,7 +1972,6 @@ namespace System.Text // During GetCharCount we had an invalid byte sequence // pSrc is used to find the index that points to the invalid bytes, // however the byte[] contains the fallback bytes (in case the index is -1) - [System.Security.SecurityCritical] // auto-generated private unsafe int FallbackInvalidByteSequence( byte* pSrc, int ch, DecoderFallbackBuffer fallback) { @@ -2001,7 +1990,6 @@ namespace System.Text // Note that some of these bytes may have come from a previous fallback, so we cannot // just decrement the pointer and use the values we read. In those cases we have // to regenerate the original values. - [System.Security.SecurityCritical] // auto-generated private unsafe byte[] GetBytesUnknown(ref byte* pSrc, int ch) { // Get our byte[] @@ -2085,7 +2073,7 @@ namespace System.Text public override int GetMaxByteCount(int charCount) { if (charCount < 0) - throw new ArgumentOutOfRangeException("charCount", + throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -2099,7 +2087,7 @@ namespace System.Text byteCount *= 3; if (byteCount > 0x7fffffff) - throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); + throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); return (int)byteCount; } @@ -2108,7 +2096,7 @@ namespace System.Text public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) - throw new ArgumentOutOfRangeException("byteCount", + throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -2123,7 +2111,7 @@ namespace System.Text } if (charCount > 0x7fffffff) - throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow")); + throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow")); return (int)charCount; } @@ -2174,7 +2162,7 @@ namespace System.Text internal UTF8Encoder(SerializationInfo info, StreamingContext context) { // Any info? - if (info==null) throw new ArgumentNullException("info"); + if (info==null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); // Get common info @@ -2194,11 +2182,10 @@ namespace System.Text } // ISerializable implementation, get data for this object - [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // Any info? - if (info==null) throw new ArgumentNullException("info"); + if (info==null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); // Save Whidbey data @@ -2247,7 +2234,7 @@ namespace System.Text internal UTF8Decoder(SerializationInfo info, StreamingContext context) { // Any info? - if (info==null) throw new ArgumentNullException("info"); + if (info==null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); // Get common info @@ -2268,11 +2255,10 @@ namespace System.Text } // ISerializable implementation, get data for this object - [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // Any info? - if (info==null) throw new ArgumentNullException("info"); + if (info==null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); // Save new Whidbey data diff --git a/src/mscorlib/src/System/Text/UnicodeEncoding.cs b/src/mscorlib/src/System/Text/UnicodeEncoding.cs index 41d4f3b5ea..25255c3230 100644 --- a/src/mscorlib/src/System/Text/UnicodeEncoding.cs +++ b/src/mscorlib/src/System/Text/UnicodeEncoding.cs @@ -12,6 +12,7 @@ namespace System.Text using System.Globalization; using System.Runtime.Serialization; using System.Security.Permissions; + using System.Diagnostics; using System.Diagnostics.Contracts; @@ -109,7 +110,6 @@ namespace System.Text return EncodingForwarder.GetByteCount(this, s); } - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public override unsafe int GetByteCount(char* chars, int count) @@ -138,7 +138,6 @@ namespace System.Text return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex); } - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) @@ -154,7 +153,6 @@ namespace System.Text return EncodingForwarder.GetCharCount(this, bytes, index, count); } - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public override unsafe int GetCharCount(byte* bytes, int count) @@ -168,7 +166,6 @@ namespace System.Text return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex); } - [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) @@ -187,11 +184,10 @@ namespace System.Text // End of overridden methods which use EncodingForwarder - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder) { - Contract.Assert(chars!=null, "[UnicodeEncoding.GetByteCount]chars!=null"); - Contract.Assert(count >= 0, "[UnicodeEncoding.GetByteCount]count >=0"); + Debug.Assert(chars!=null, "[UnicodeEncoding.GetByteCount]chars!=null"); + Debug.Assert(count >= 0, "[UnicodeEncoding.GetByteCount]count >=0"); // Start by assuming each char gets 2 bytes int byteCount = count << 1; @@ -200,7 +196,7 @@ namespace System.Text // (If they were all invalid chars, this would actually be wrong, // but that's a ridiculously large # so we're not concerned about that case) if (byteCount < 0) - throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); + throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); char* charStart = chars; char* charEnd = chars + count; @@ -340,7 +336,7 @@ namespace System.Text // Unwind the current character, this should be safe because we // don't have leftover data in the fallback, so chars must have // advanced already. - Contract.Assert(chars > charStart, + Debug.Assert(chars > charStart, "[UnicodeEncoding.GetByteCount]Expected chars to have advanced in unexpected high surrogate"); chars--; @@ -407,7 +403,7 @@ namespace System.Text // Rewind the current character, fallback previous character. // this should be safe because we don't have leftover data in the // fallback, so chars must have advanced already. - Contract.Assert(chars > charStart, + Debug.Assert(chars > charStart, "[UnicodeEncoding.GetByteCount]Expected chars to have advanced when expected low surrogate"); chars--; @@ -448,7 +444,7 @@ namespace System.Text // Throw it, using our complete character throw new ArgumentException( Environment.GetResourceString("Argument_RecursiveFallback", - charLeftOver), "chars"); + charLeftOver), nameof(chars)); } else { @@ -473,21 +469,20 @@ namespace System.Text // Shouldn't have anything in fallback buffer for GetByteCount // (don't have to check m_throwOnOverflow for count) - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[UnicodeEncoding.GetByteCount]Expected empty fallback buffer at end"); // Don't remember fallbackBuffer.encoder for counting return byteCount; } - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS encoder) { - Contract.Assert(chars!=null, "[UnicodeEncoding.GetBytes]chars!=null"); - Contract.Assert(byteCount >=0, "[UnicodeEncoding.GetBytes]byteCount >=0"); - Contract.Assert(charCount >=0, "[UnicodeEncoding.GetBytes]charCount >=0"); - Contract.Assert(bytes!=null, "[UnicodeEncoding.GetBytes]bytes!=null"); + Debug.Assert(chars!=null, "[UnicodeEncoding.GetBytes]chars!=null"); + Debug.Assert(byteCount >=0, "[UnicodeEncoding.GetBytes]byteCount >=0"); + Debug.Assert(charCount >=0, "[UnicodeEncoding.GetBytes]charCount >=0"); + Debug.Assert(bytes!=null, "[UnicodeEncoding.GetBytes]bytes!=null"); char charLeftOver = (char)0; char ch; @@ -691,7 +686,7 @@ namespace System.Text // Unwind the current character, this should be safe because we // don't have leftover data in the fallback, so chars must have // advanced already. - Contract.Assert(chars > charStart, + Debug.Assert(chars > charStart, "[UnicodeEncoding.GetBytes]Expected chars to have advanced in unexpected high surrogate"); chars--; @@ -757,7 +752,7 @@ namespace System.Text { // If we don't have enough room, then either we should've advanced a while // or we should have bytes==byteStart and throw below - Contract.Assert(chars > charStart + 1 || bytes == byteStart, + Debug.Assert(chars > charStart + 1 || bytes == byteStart, "[UnicodeEncoding.GetBytes]Expected chars to have when no room to add surrogate pair"); chars-=2; // Didn't use either surrogate } @@ -786,7 +781,7 @@ namespace System.Text // Rewind the current character, fallback previous character. // this should be safe because we don't have leftover data in the // fallback, so chars must have advanced already. - Contract.Assert(chars > charStart, + Debug.Assert(chars > charStart, "[UnicodeEncoding.GetBytes]Expected chars to have advanced after expecting low surrogate"); chars--; @@ -820,7 +815,7 @@ namespace System.Text { // Lonely charLeftOver (from previous call) would've been caught up above, // so this must be a case where we've already read an input char. - Contract.Assert(chars > charStart, + Debug.Assert(chars > charStart, "[UnicodeEncoding.GetBytes]Expected chars to have advanced for failed fallback"); chars--; // Not using this char } @@ -851,7 +846,7 @@ namespace System.Text // Throw it, using our complete character throw new ArgumentException( Environment.GetResourceString("Argument_RecursiveFallback", - charLeftOver), "chars"); + charLeftOver), nameof(chars)); } else { @@ -888,10 +883,10 @@ namespace System.Text // Remember charLeftOver if we must, or clear it if we're flushing // (charLeftOver should be 0 if we're flushing) - Contract.Assert((encoder != null && !encoder.MustFlush) || charLeftOver == (char)0, + Debug.Assert((encoder != null && !encoder.MustFlush) || charLeftOver == (char)0, "[UnicodeEncoding.GetBytes] Expected no left over characters if flushing"); - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 || + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 || encoder == null || !encoder.m_throwOnOverflow, "[UnicodeEncoding.GetBytes]Expected empty fallback buffer if not converting"); @@ -901,11 +896,10 @@ namespace System.Text return (int)(bytes - byteStart); } - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) { - Contract.Assert(bytes!=null, "[UnicodeEncoding.GetCharCount]bytes!=null"); - Contract.Assert(count >= 0, "[UnicodeEncoding.GetCharCount]count >=0"); + Debug.Assert(bytes!=null, "[UnicodeEncoding.GetCharCount]bytes!=null"); + Debug.Assert(count >= 0, "[UnicodeEncoding.GetCharCount]count >=0"); UnicodeEncoding.Decoder decoder = (UnicodeEncoding.Decoder)baseDecoder; @@ -944,7 +938,7 @@ namespace System.Text // Shouldn't have anything in fallback buffer for GetCharCount // (don't have to check m_throwOnOverflow for count) - Contract.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, + Debug.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[UnicodeEncoding.GetCharCount]Expected empty fallback buffer at start"); } @@ -1234,20 +1228,19 @@ namespace System.Text // Shouldn't have anything in fallback buffer for GetCharCount // (don't have to check m_throwOnOverflow for count) - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[UnicodeEncoding.GetCharCount]Expected empty fallback buffer at end"); return charCount; } - [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS baseDecoder ) { - Contract.Assert(chars!=null, "[UnicodeEncoding.GetChars]chars!=null"); - Contract.Assert(byteCount >=0, "[UnicodeEncoding.GetChars]byteCount >=0"); - Contract.Assert(charCount >=0, "[UnicodeEncoding.GetChars]charCount >=0"); - Contract.Assert(bytes!=null, "[UnicodeEncoding.GetChars]bytes!=null"); + Debug.Assert(chars!=null, "[UnicodeEncoding.GetChars]chars!=null"); + Debug.Assert(byteCount >=0, "[UnicodeEncoding.GetChars]byteCount >=0"); + Debug.Assert(charCount >=0, "[UnicodeEncoding.GetChars]charCount >=0"); + Debug.Assert(bytes!=null, "[UnicodeEncoding.GetChars]bytes!=null"); UnicodeEncoding.Decoder decoder = (UnicodeEncoding.Decoder)baseDecoder; @@ -1263,7 +1256,7 @@ namespace System.Text // Shouldn't have anything in fallback buffer for GetChars // (don't have to check m_throwOnOverflow for chars) - Contract.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, + Debug.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[UnicodeEncoding.GetChars]Expected empty fallback buffer at start"); } @@ -1421,7 +1414,7 @@ namespace System.Text { // couldn't fall back lonely surrogate // We either advanced bytes or chars should == charStart and throw below - Contract.Assert(bytes >= byteStart + 2 || chars == charStart, + Debug.Assert(bytes >= byteStart + 2 || chars == charStart, "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (bad surrogate)"); bytes-=2; // didn't use these 2 bytes fallbackBuffer.InternalReset(); @@ -1470,7 +1463,7 @@ namespace System.Text { // couldn't fall back lonely surrogate // We either advanced bytes or chars should == charStart and throw below - Contract.Assert(bytes >= byteStart + 2 || chars == charStart, + Debug.Assert(bytes >= byteStart + 2 || chars == charStart, "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (lonely surrogate)"); bytes-=2; // didn't use these 2 bytes fallbackBuffer.InternalReset(); @@ -1487,7 +1480,7 @@ namespace System.Text { // couldn't find room for this surrogate pair // We either advanced bytes or chars should == charStart and throw below - Contract.Assert(bytes >= byteStart + 2 || chars == charStart, + Debug.Assert(bytes >= byteStart + 2 || chars == charStart, "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (surrogate pair)"); bytes-=2; // didn't use these 2 bytes ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output @@ -1529,7 +1522,7 @@ namespace System.Text { // couldn't fall back high surrogate, or char that would be next // We either advanced bytes or chars should == charStart and throw below - Contract.Assert(bytes >= byteStart + 2 || chars == charStart, + Debug.Assert(bytes >= byteStart + 2 || chars == charStart, "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (no low surrogate)"); bytes-=2; // didn't use these 2 bytes fallbackBuffer.InternalReset(); @@ -1546,7 +1539,7 @@ namespace System.Text { // 2 bytes couldn't fall back // We either advanced bytes or chars should == charStart and throw below - Contract.Assert(bytes >= byteStart + 2 || chars == charStart, + Debug.Assert(bytes >= byteStart + 2 || chars == charStart, "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (normal)"); bytes-=2; // didn't use these bytes ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output @@ -1591,7 +1584,7 @@ namespace System.Text { // 2 bytes couldn't fall back // We either advanced bytes or chars should == charStart and throw below - Contract.Assert(bytes >= byteStart + 2 || chars == charStart, + Debug.Assert(bytes >= byteStart + 2 || chars == charStart, "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (decoder)"); bytes-=2; // didn't use these bytes if (lastByte >= 0) @@ -1644,7 +1637,7 @@ namespace System.Text // Remember our decoder if we must if (decoder != null) { - Contract.Assert((decoder.MustFlush == false) || ((lastChar == (char)0) && (lastByte == -1)), + Debug.Assert((decoder.MustFlush == false) || ((lastChar == (char)0) && (lastByte == -1)), "[UnicodeEncoding.GetChars] Expected no left over chars or bytes if flushing" // + " " + ((int)lastChar).ToString("X4") + " " + lastByte.ToString("X2") ); @@ -1659,7 +1652,7 @@ namespace System.Text // Shouldn't have anything in fallback buffer for GetChars // (don't have to check m_throwOnOverflow for count or chars) - Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[UnicodeEncoding.GetChars]Expected empty fallback buffer at end"); return (int)(chars - charStart); @@ -1697,7 +1690,7 @@ namespace System.Text public override int GetMaxByteCount(int charCount) { if (charCount < 0) - throw new ArgumentOutOfRangeException("charCount", + throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -1711,7 +1704,7 @@ namespace System.Text byteCount <<= 1; if (byteCount > 0x7fffffff) - throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); + throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); return (int)byteCount; } @@ -1720,7 +1713,7 @@ namespace System.Text public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) - throw new ArgumentOutOfRangeException("byteCount", + throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); @@ -1735,7 +1728,7 @@ namespace System.Text charCount *= DecoderFallback.MaxCharCount; if (charCount > 0x7fffffff) - throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow")); + throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow")); return (int)charCount; } @@ -1781,7 +1774,7 @@ namespace System.Text internal Decoder(SerializationInfo info, StreamingContext context) { // Any info? - if (info==null) throw new ArgumentNullException("info"); + if (info==null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); // Get Common Info @@ -1803,11 +1796,10 @@ namespace System.Text } // ISerializable implementation, get data for this object - [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // Any info? - if (info==null) throw new ArgumentNullException("info"); + if (info==null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); // Save Whidbey data |