/// <summary> /// Checks the parameters passed into a Read() method are valid /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="count"></param> internal static void ValidateReadParameters(byte[] buffer, int offset, int count) { if (buffer == null) { throw ADP.ArgumentNull(nameof(buffer)); } if (offset < 0) { throw ADP.ArgumentOutOfRange(nameof(offset)); } if (count < 0) { throw ADP.ArgumentOutOfRange(nameof(count)); } try { if (checked (offset + count) > buffer.Length) { throw ExceptionBuilder.InvalidOffsetLength(); } } catch (OverflowException) { // If we've overflowed when adding offset and count, then they never would have fit into buffer anyway throw ExceptionBuilder.InvalidOffsetLength(); } }
public static CompareOptions CompareOptionsFromSqlCompareOptions(System.Data.SqlTypes.SqlCompareOptions compareOptions) { CompareOptions none = CompareOptions.None; ValidateSqlCompareOptions(compareOptions); if ((compareOptions & (System.Data.SqlTypes.SqlCompareOptions.BinarySort | System.Data.SqlTypes.SqlCompareOptions.BinarySort2)) != System.Data.SqlTypes.SqlCompareOptions.None) { throw ADP.ArgumentOutOfRange("compareOptions"); } if ((compareOptions & System.Data.SqlTypes.SqlCompareOptions.IgnoreCase) != System.Data.SqlTypes.SqlCompareOptions.None) { none |= CompareOptions.IgnoreCase; } if ((compareOptions & System.Data.SqlTypes.SqlCompareOptions.IgnoreNonSpace) != System.Data.SqlTypes.SqlCompareOptions.None) { none |= CompareOptions.IgnoreNonSpace; } if ((compareOptions & System.Data.SqlTypes.SqlCompareOptions.IgnoreKanaType) != System.Data.SqlTypes.SqlCompareOptions.None) { none |= CompareOptions.IgnoreKanaType; } if ((compareOptions & System.Data.SqlTypes.SqlCompareOptions.IgnoreWidth) != System.Data.SqlTypes.SqlCompareOptions.None) { none |= CompareOptions.IgnoreWidth; } return(none); }
public static CompareOptions CompareOptionsFromSqlCompareOptions(SqlCompareOptions compareOptions) { CompareOptions options = CompareOptions.None; ValidateSqlCompareOptions(compareOptions); if ((compareOptions & (SqlCompareOptions.BinarySort | SqlCompareOptions.BinarySort2)) != 0) { throw ADP.ArgumentOutOfRange("compareOptions"); } else { if ((compareOptions & SqlCompareOptions.IgnoreCase) != 0) { options |= CompareOptions.IgnoreCase; } if ((compareOptions & SqlCompareOptions.IgnoreNonSpace) != 0) { options |= CompareOptions.IgnoreNonSpace; } if ((compareOptions & SqlCompareOptions.IgnoreKanaType) != 0) { options |= CompareOptions.IgnoreKanaType; } if ((compareOptions & SqlCompareOptions.IgnoreWidth) != 0) { options |= CompareOptions.IgnoreWidth; } } return(options); }
/// <summary> /// Checks the the parameters passed into a Read() method are valid /// </summary> /// <param name="buffer"></param> /// <param name="index"></param> /// <param name="count"></param> internal static void ValidateReadParameters(char[] buffer, int index, int count) { if (buffer == null) { throw ADP.ArgumentNull(ADP.ParameterBuffer); } if (index < 0) { throw ADP.ArgumentOutOfRange(ADP.ParameterIndex); } if (count < 0) { throw ADP.ArgumentOutOfRange(ADP.ParameterCount); } try { if (checked (index + count) > buffer.Length) { throw ExceptionBuilder.InvalidOffsetLength(); } } catch (OverflowException) { // If we've overflowed when adding index and count, then they never would have fit into buffer anyway throw ExceptionBuilder.InvalidOffsetLength(); } }
override public int Read(byte[] buffer, int offset, int count) { int cb; int intCount = 0; if (null == _cachedBytes) { throw ADP.StreamClosed(); } if (null == buffer) { throw ADP.ArgumentNull(nameof(buffer)); } if ((offset < 0) || (count < 0)) { throw ADP.ArgumentOutOfRange(string.Empty, (offset < 0 ? nameof(offset) : nameof(count))); } if (buffer.Length - offset < count) { throw ADP.ArgumentOutOfRange(nameof(count)); } if (_cachedBytes.Count <= _currentArrayIndex) { return(0); // Everything is read! } while (count > 0) { if (_cachedBytes[_currentArrayIndex].Length <= _currentPosition) { _currentArrayIndex++; // We are done reading this chunk, go to next if (_cachedBytes.Count > _currentArrayIndex) { _currentPosition = 0; } else { break; } } cb = _cachedBytes[_currentArrayIndex].Length - _currentPosition; if (cb > count) { cb = count; } Buffer.BlockCopy(_cachedBytes[_currentArrayIndex], _currentPosition, buffer, offset, cb); _currentPosition += cb; count -= (int)cb; offset += (int)cb; intCount += (int)cb; } return(intCount); }
override public DataTable GetDataSources() { #if MONO timeoutTime = 0; throw new NotImplementedException(); #else (new NamedPermissionSet("FullTrust")).Demand(); // SQLBUDT 244304 char[] buffer = null; StringBuilder strbldr = new StringBuilder(); Int32 bufferSize = 1024; Int32 readLength = 0; buffer = new char[bufferSize]; bool more = true; bool failure = false; IntPtr handle = ADP.PtrZero; RuntimeHelpers.PrepareConstrainedRegions(); try { timeoutTime = TdsParserStaticMethods.GetTimeoutSeconds(timeoutSeconds); RuntimeHelpers.PrepareConstrainedRegions(); try {} finally { handle = SNINativeMethodWrapper.SNIServerEnumOpen(); } if (ADP.PtrZero != handle) { while (more && !TdsParserStaticMethods.TimeoutHasExpired(timeoutTime)) { readLength = SNINativeMethodWrapper.SNIServerEnumRead(handle, buffer, bufferSize, ref more); if (readLength > bufferSize) { failure = true; more = false; } else if (0 < readLength) { strbldr.Append(buffer, 0, readLength); } } } } finally { if (ADP.PtrZero != handle) { SNINativeMethodWrapper.SNIServerEnumClose(handle); } } if (failure) { Debug.Assert(false, "GetDataSources:SNIServerEnumRead returned bad length"); Bid.Trace("<sc.SqlDataSourceEnumerator.GetDataSources|ERR> GetDataSources:SNIServerEnumRead returned bad length, requested %d, received %d", bufferSize, readLength); throw ADP.ArgumentOutOfRange("readLength"); } return(ParseServerEnumString(strbldr.ToString())); #endif }
internal static uint CTL_CODE(ushort deviceType, ushort function, byte method, byte access) { if (function > 0xfff) { throw ADP.ArgumentOutOfRange("function"); } return((uint)((((deviceType << 0x10) | (access << 14)) | (function << 2)) | method)); }
public override void SetLength(long value) { if (value < 0) { throw ADP.ArgumentOutOfRange("value"); } ValueUtilsSmi.SetBytesLength(_sink, _setters, _ordinal, _metaData, value); }
private static Tuple <string, int, Encoding> GetDetailsForLcid(int lcid) { if (lcid < 0) { throw ADP.ArgumentOutOfRange("lcid"); } return(s_cachedEncodings.GetOrAdd(lcid, GetDetailsInternal)); }
public override void SetLength(long value) { if (value < 0) { throw ADP.ArgumentOutOfRange("value"); } _stream.SetLength(_sink, value * sizeof(char)); _sink.ProcessMessagesAndThrow(); }
public override void SetLength(long value) { if (value < 0L) { throw ADP.ArgumentOutOfRange("value"); } this._stream.SetLength(this._sink, value * 2L); this._sink.ProcessMessagesAndThrow(); }
public override DataTable GetDataSources() { new NamedPermissionSet("FullTrust").Demand(); char[] wStr = null; StringBuilder builder = new StringBuilder(); int pcbBuf = 0x400; int charCount = 0; wStr = new char[pcbBuf]; bool fMore = true; bool flag = false; IntPtr ptrZero = ADP.PtrZero; RuntimeHelpers.PrepareConstrainedRegions(); try { this.timeoutTime = TdsParserStaticMethods.GetTimeoutSeconds(30); RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { ptrZero = SNINativeMethodWrapper.SNIServerEnumOpen(); } if (ADP.PtrZero != ptrZero) { while (fMore && !TdsParserStaticMethods.TimeoutHasExpired(this.timeoutTime)) { charCount = SNINativeMethodWrapper.SNIServerEnumRead(ptrZero, wStr, pcbBuf, ref fMore); if (charCount > pcbBuf) { flag = true; fMore = false; } else if (0 < charCount) { builder.Append(wStr, 0, charCount); } } } } finally { if (ADP.PtrZero != ptrZero) { SNINativeMethodWrapper.SNIServerEnumClose(ptrZero); } } if (flag) { Bid.Trace("<sc.SqlDataSourceEnumerator.GetDataSources|ERR> GetDataSources:SNIServerEnumRead returned bad length, requested %d, received %d", pcbBuf, charCount); throw ADP.ArgumentOutOfRange("readLength"); } return(ParseServerEnumString(builder.ToString())); }
public override int Read(byte[] buffer, int offset, int count) { int num2 = 0; byte[] sourceArray = null; if (this._cachedBytes == null) { throw ADP.StreamClosed("Read"); } if (buffer == null) { throw ADP.ArgumentNull("buffer"); } if ((offset < 0) || (count < 0)) { throw ADP.ArgumentOutOfRange(string.Empty, (offset < 0) ? "offset" : "count"); } if ((buffer.Length - offset) < count) { throw ADP.ArgumentOutOfRange("count"); } if (this._cachedBytes.Count > this._currentArrayIndex) { sourceArray = (byte[])this._cachedBytes[this._currentArrayIndex]; while (count > 0) { if (sourceArray.Length <= this._currentPosition) { this._currentArrayIndex++; if (this._cachedBytes.Count <= this._currentArrayIndex) { return(num2); } sourceArray = (byte[])this._cachedBytes[this._currentArrayIndex]; this._currentPosition = 0; } int length = sourceArray.Length - this._currentPosition; if (length > count) { length = count; } Array.Copy(sourceArray, this._currentPosition, buffer, offset, length); this._currentPosition += length; count -= length; offset += length; num2 += length; } return(num2); } return(0); }
/// <summary> <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/kernel/defining-i-o-control-codes">CTL_CODE</a> method.</summary> /// <param name="deviceType">Identifies the device type. This value must match the value that is set in the DeviceType member of the driver's DEVICE_OBJECT structure.</param> /// <param name="function">Identifies the function to be performed by the driver. Values of less than 0x800 are reserved for Microsoft. Values of 0x800 and higher can be used by vendors.</param> /// <param name="method">Indicates how the system will pass data between the caller of DeviceIoControl (or IoBuildDeviceIoControlRequest) and the driver that handles the IRP.</param> /// <param name="access">Indicates the type of access that a caller must request when opening the file object that represents the device (see IRP_MJ_CREATE).</param> internal static unsafe uint CTL_CODE( ushort deviceType, ushort function, byte method, byte access) { // MaxFunctionCode specifies the maximum value of the FunctionCode field in the FSCTLs (or IOCTLs for IOCTL tests). The maximum possible value is 4095. // See https://docs.microsoft.com/en-us/windows-hardware/drivers/develop/how-to-select-and-configure-the-device-fundamental-tests if (function > 4095) { throw ADP.ArgumentOutOfRange("function"); } return((uint)((deviceType << 16) | (access << 14) | (function << 2) | method)); }
internal int SetChars(long fieldOffset, char[] buffer, int bufferOffset, int length) { int ndataIndex = (int)fieldOffset; if (IsNull || (StorageType.CharArray != _type && StorageType.String != _type)) { if (ndataIndex != 0) { // set the first time: should start from the beginning throw ADP.ArgumentOutOfRange("fieldOffset"); } _object = new char[length]; _type = StorageType.CharArray; _isNull = false; CharsLength = length; } else { if (ndataIndex > CharsLength) { // no gap is allowed throw ADP.ArgumentOutOfRange("fieldOffset"); } if (StorageType.String == _type) { // convert string to char[] _object = ((string)_object).ToCharArray(); _type = StorageType.CharArray; } if (ndataIndex + length > CharsLength) { // beyond the current length int cchars = ((char[])_object).Length; if (ndataIndex + length > cchars) { // dynamic expansion char[] data = new char[Math.Max(ndataIndex + length, 2 * cchars)]; Debug.Assert(CharsLength < Int32.MaxValue); Array.Copy((char[])_object, 0, data, 0, (int)CharsLength); _object = data; } CharsLength = ndataIndex + length; } } Array.Copy(buffer, bufferOffset, (char[])_object, ndataIndex, length); return(length); }
internal static SmiExtendedMetaData SqlMetaDataToSmiExtendedMetaData(SqlMetaData source) { string xmlSchemaCollectionName = null; string xmlSchemaCollectionOwningSchema = null; string xmlSchemaCollectionDatabase = null; if (SqlDbType.Xml == source.SqlDbType) { xmlSchemaCollectionDatabase = source.XmlSchemaCollectionDatabase; xmlSchemaCollectionOwningSchema = source.XmlSchemaCollectionOwningSchema; xmlSchemaCollectionName = source.XmlSchemaCollectionName; } else if (SqlDbType.Udt == source.SqlDbType) { string serverTypeName = source.ServerTypeName; if (serverTypeName != null) { string[] strArray = SqlParameter.ParseTypeName(serverTypeName, true); if (1 == strArray.Length) { xmlSchemaCollectionName = strArray[0]; } else if (2 == strArray.Length) { xmlSchemaCollectionOwningSchema = strArray[0]; xmlSchemaCollectionName = strArray[1]; } else { if (3 != strArray.Length) { throw ADP.ArgumentOutOfRange("typeName"); } xmlSchemaCollectionDatabase = strArray[0]; xmlSchemaCollectionOwningSchema = strArray[1]; xmlSchemaCollectionName = strArray[2]; } if (((!ADP.IsEmpty(xmlSchemaCollectionDatabase) && (0xff < xmlSchemaCollectionDatabase.Length)) || (!ADP.IsEmpty(xmlSchemaCollectionOwningSchema) && (0xff < xmlSchemaCollectionOwningSchema.Length))) || (!ADP.IsEmpty(xmlSchemaCollectionName) && (0xff < xmlSchemaCollectionName.Length))) { throw ADP.ArgumentOutOfRange("typeName"); } } } return(new SmiExtendedMetaData(source.SqlDbType, source.MaxLength, source.Precision, source.Scale, source.LocaleId, source.CompareOptions, source.Type, source.Name, xmlSchemaCollectionDatabase, xmlSchemaCollectionOwningSchema, xmlSchemaCollectionName)); }
internal int SetChars(long fieldOffset, char[] buffer, int bufferOffset, int length) { int destinationIndex = (int)fieldOffset; if (this.IsNull || ((StorageType.CharArray != this._type) && (StorageType.String != this._type))) { if (destinationIndex != 0) { throw ADP.ArgumentOutOfRange("fieldOffset"); } this._object = new char[length]; this._type = StorageType.CharArray; this._isNull = false; this.CharsLength = length; } else { if (destinationIndex > this.CharsLength) { throw ADP.ArgumentOutOfRange("fieldOffset"); } if (StorageType.String == this._type) { this._object = ((string)this._object).ToCharArray(); this._type = StorageType.CharArray; } if ((destinationIndex + length) > this.CharsLength) { int num2 = ((char[])this._object).Length; if ((destinationIndex + length) > num2) { char[] destinationArray = new char[Math.Max((int)(destinationIndex + length), (int)(2 * num2))]; Array.Copy((char[])this._object, 0L, destinationArray, 0L, this.CharsLength); this._object = destinationArray; } this.CharsLength = destinationIndex + length; } } Array.Copy(buffer, bufferOffset, (char[])this._object, destinationIndex, length); return(length); }
// -------------------------------------------------------------- // Public methods // -------------------------------------------------------------- public override long Seek(long offset, SeekOrigin origin) { CheckIfStreamClosed("Seek"); long lPosition = 0; switch (origin) { case SeekOrigin.Begin: if (offset < 0 || offset > _sqlchars.Length) { throw ADP.ArgumentOutOfRange("offset"); } _lPosition = offset; break; case SeekOrigin.Current: lPosition = _lPosition + offset; if (lPosition < 0 || lPosition > _sqlchars.Length) { throw ADP.ArgumentOutOfRange("offset"); } _lPosition = lPosition; break; case SeekOrigin.End: lPosition = _sqlchars.Length + offset; if (lPosition < 0 || lPosition > _sqlchars.Length) { throw ADP.ArgumentOutOfRange("offset"); } _lPosition = lPosition; break; default: throw ADP.ArgumentOutOfRange("offset");; } return(_lPosition); }
internal int SetBytes(long fieldOffset, byte[] buffer, int bufferOffset, int length) { int ndataIndex = (int)fieldOffset; if (IsNull || StorageType.ByteArray != _type) { if (ndataIndex != 0) // set the first time: should start from the beginning { throw ADP.ArgumentOutOfRange("fieldOffset"); } _object = new byte[length]; _type = StorageType.ByteArray; _isNull = false; BytesLength = length; } else { if (ndataIndex > BytesLength) // no gap is allowed { throw ADP.ArgumentOutOfRange("fieldOffset"); } if (ndataIndex + length > BytesLength) // beyond the current length { int cbytes = ((byte[])_object).Length; if (ndataIndex + length > cbytes) // dynamic expansion { byte[] data = new byte[Math.Max(ndataIndex + length, 2 * cbytes)]; Buffer.BlockCopy((byte[])_object, 0, data, 0, (int)BytesLength); _object = data; } BytesLength = ndataIndex + length; } } Buffer.BlockCopy(buffer, bufferOffset, (byte[])_object, ndataIndex, length); return(length); }
public override long Seek(long offset, SeekOrigin origin) { this.CheckIfStreamClosed("Seek"); long num = 0L; switch (origin) { case SeekOrigin.Begin: if ((offset < 0L) || (offset > this.m_sqlchars.Length)) { throw ADP.ArgumentOutOfRange("offset"); } this.m_lPosition = offset; break; case SeekOrigin.Current: num = this.m_lPosition + offset; if ((num < 0L) || (num > this.m_sqlchars.Length)) { throw ADP.ArgumentOutOfRange("offset"); } this.m_lPosition = num; break; case SeekOrigin.End: num = this.m_sqlchars.Length + offset; if ((num < 0L) || (num > this.m_sqlchars.Length)) { throw ADP.ArgumentOutOfRange("offset"); } this.m_lPosition = num; break; default: throw ADP.ArgumentOutOfRange("offset"); } return(this.m_lPosition); }
internal int SetBytes(long fieldOffset, byte[] buffer, int bufferOffset, int length) { int dstOffset = (int)fieldOffset; if (this.IsNull || (StorageType.ByteArray != this._type)) { if (dstOffset != 0) { throw ADP.ArgumentOutOfRange("fieldOffset"); } this._object = new byte[length]; this._type = StorageType.ByteArray; this._isNull = false; this.BytesLength = length; } else { if (dstOffset > this.BytesLength) { throw ADP.ArgumentOutOfRange("fieldOffset"); } if ((dstOffset + length) > this.BytesLength) { int num2 = ((byte[])this._object).Length; if ((dstOffset + length) > num2) { byte[] dst = new byte[Math.Max((int)(dstOffset + length), (int)(2 * num2))]; Buffer.BlockCopy((byte[])this._object, 0, dst, 0, (int)this.BytesLength); this._object = dst; } this.BytesLength = dstOffset + length; } } Buffer.BlockCopy(buffer, bufferOffset, (byte[])this._object, dstOffset, length); return(length); }
private unsafe void OpenSqlFileStream ( string sPath, byte[] transactionContext, System.IO.FileAccess access, System.IO.FileOptions options, long allocationSize ) { //----------------------------------------------------------------- // precondition validation // these should be checked by any caller of this method // ensure we have validated and normalized the path before Debug.Assert(sPath != null); Debug.Assert(transactionContext != null); if (access != System.IO.FileAccess.Read && access != System.IO.FileAccess.Write && access != System.IO.FileAccess.ReadWrite) { throw ADP.ArgumentOutOfRange("access"); } // FileOptions is a set of flags, so AND the given value against the set of values we do not support if ((options & ~(System.IO.FileOptions.WriteThrough | System.IO.FileOptions.Asynchronous | System.IO.FileOptions.RandomAccess | System.IO.FileOptions.SequentialScan)) != 0) { throw ADP.ArgumentOutOfRange("options"); } //----------------------------------------------------------------- // normalize the provided path // * compress path to remove any occurrences of '.' or '..' // * trim whitespace from the beginning and end of the path // * ensure that the path starts with '\\' // * ensure that the path does not start with '\\.\' sPath = GetFullPathInternal(sPath); Microsoft.Win32.SafeHandles.SafeFileHandle hFile = null; Interop.NtDll.DesiredAccess nDesiredAccess = Interop.NtDll.DesiredAccess.FILE_READ_ATTRIBUTES | Interop.NtDll.DesiredAccess.SYNCHRONIZE; Interop.NtDll.CreateOptions dwCreateOptions = 0; Interop.NtDll.CreateDisposition dwCreateDisposition = 0; System.IO.FileShare nShareAccess = System.IO.FileShare.None; switch (access) { case System.IO.FileAccess.Read: nDesiredAccess |= Interop.NtDll.DesiredAccess.FILE_READ_DATA; nShareAccess = System.IO.FileShare.Delete | System.IO.FileShare.ReadWrite; dwCreateDisposition = Interop.NtDll.CreateDisposition.FILE_OPEN; break; case System.IO.FileAccess.Write: nDesiredAccess |= Interop.NtDll.DesiredAccess.FILE_WRITE_DATA; nShareAccess = System.IO.FileShare.Delete | System.IO.FileShare.Read; dwCreateDisposition = Interop.NtDll.CreateDisposition.FILE_OVERWRITE; break; case System.IO.FileAccess.ReadWrite: default: // we validate the value of 'access' parameter in the beginning of this method Debug.Assert(access == System.IO.FileAccess.ReadWrite); nDesiredAccess |= Interop.NtDll.DesiredAccess.FILE_READ_DATA | Interop.NtDll.DesiredAccess.FILE_WRITE_DATA; nShareAccess = System.IO.FileShare.Delete | System.IO.FileShare.Read; dwCreateDisposition = Interop.NtDll.CreateDisposition.FILE_OVERWRITE; break; } if ((options & System.IO.FileOptions.WriteThrough) != 0) { dwCreateOptions |= Interop.NtDll.CreateOptions.FILE_WRITE_THROUGH; } if ((options & System.IO.FileOptions.Asynchronous) == 0) { dwCreateOptions |= Interop.NtDll.CreateOptions.FILE_SYNCHRONOUS_IO_NONALERT; } if ((options & System.IO.FileOptions.SequentialScan) != 0) { dwCreateOptions |= Interop.NtDll.CreateOptions.FILE_SEQUENTIAL_ONLY; } if ((options & System.IO.FileOptions.RandomAccess) != 0) { dwCreateOptions |= Interop.NtDll.CreateOptions.FILE_RANDOM_ACCESS; } try { // NOTE: the Name property is intended to reveal the publicly available moniker for the // FILESTREAM attributed column data. We will not surface the internal processing that // takes place to create the mappedPath. string mappedPath = InitializeNtPath(sPath); int retval = 0; Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out uint oldMode); try { if (transactionContext.Length >= ushort.MaxValue) { throw ADP.ArgumentOutOfRange("transactionContext"); } int headerSize = sizeof(Interop.NtDll.FILE_FULL_EA_INFORMATION); int fullSize = headerSize + transactionContext.Length + s_eaNameString.Length; byte[] buffer = ArrayPool <byte> .Shared.Rent(fullSize); fixed(byte *b = buffer) { Interop.NtDll.FILE_FULL_EA_INFORMATION *ea = (Interop.NtDll.FILE_FULL_EA_INFORMATION *)b; ea->NextEntryOffset = 0; ea->Flags = 0; ea->EaNameLength = (byte)(s_eaNameString.Length - 1); // Length does not include terminating null character. ea->EaValueLength = (ushort)transactionContext.Length; // We could continue to do pointer math here, chose to use Span for convenience to // make sure we get the other members in the right place. Span <byte> data = buffer.AsSpan(headerSize); s_eaNameString.AsSpan().CopyTo(data); data = data.Slice(s_eaNameString.Length); transactionContext.AsSpan().CopyTo(data); (int status, IntPtr handle) = Interop.NtDll.CreateFile( path: mappedPath.AsSpan(), rootDirectory: IntPtr.Zero, createDisposition: dwCreateDisposition, desiredAccess: nDesiredAccess, shareAccess: nShareAccess, fileAttributes: 0, createOptions: dwCreateOptions, eaBuffer: b, eaLength: (uint)fullSize); retval = status; hFile = new SafeFileHandle(handle, true); } ArrayPool <byte> .Shared.Return(buffer); } finally { Interop.Kernel32.SetThreadErrorMode(oldMode, out oldMode); } switch (retval) { case 0: break; case Interop.Errors.ERROR_SHARING_VIOLATION: throw ADP.InvalidOperation(System.SRHelper.GetString(SR.SqlFileStream_FileAlreadyInTransaction)); case Interop.Errors.ERROR_INVALID_PARAMETER: throw ADP.Argument(System.SRHelper.GetString(SR.SqlFileStream_InvalidParameter)); case Interop.Errors.ERROR_FILE_NOT_FOUND: { System.IO.DirectoryNotFoundException e = new System.IO.DirectoryNotFoundException(); ADP.TraceExceptionAsReturnValue(e); throw e; } default: { uint error = Interop.NtDll.RtlNtStatusToDosError(retval); if (error == ERROR_MR_MID_NOT_FOUND) { // status code could not be mapped to a Win32 error code error = (uint)retval; } System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(unchecked ((int)error)); ADP.TraceExceptionAsReturnValue(e); throw e; } } if (hFile.IsInvalid) { System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Interop.Errors.ERROR_INVALID_HANDLE); ADP.TraceExceptionAsReturnValue(e); throw e; } if (Interop.Kernel32.GetFileType(hFile) != Interop.Kernel32.FileTypes.FILE_TYPE_DISK) { hFile.Dispose(); throw ADP.Argument(System.SRHelper.GetString(SR.SqlFileStream_PathNotValidDiskResource)); } // if the user is opening the SQL FileStream in read/write mode, we assume that they want to scan // through current data and then append new data to the end, so we need to tell SQL Server to preserve // the existing file contents. if (access == System.IO.FileAccess.ReadWrite) { uint ioControlCode = Interop.Kernel32.CTL_CODE(FILE_DEVICE_FILE_SYSTEM, IoControlCodeFunctionCode, (byte)Interop.Kernel32.IoControlTransferType.METHOD_BUFFERED, (byte)Interop.Kernel32.IoControlCodeAccess.FILE_ANY_ACCESS); if (!Interop.Kernel32.DeviceIoControl(hFile, ioControlCode, IntPtr.Zero, 0, IntPtr.Zero, 0, out uint cbBytesReturned, IntPtr.Zero)) { System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); ADP.TraceExceptionAsReturnValue(e); throw e; } } // now that we've successfully opened a handle on the path and verified that it is a file, // use the SafeFileHandle to initialize our internal System.IO.FileStream instance System.Diagnostics.Debug.Assert(_m_fs == null); _m_fs = new System.IO.FileStream(hFile, access, DefaultBufferSize, ((options & System.IO.FileOptions.Asynchronous) != 0)); } catch { if (hFile != null && !hFile.IsInvalid) { hFile.Dispose(); } throw; } }
// The class SQL defines the exceptions that are specific to the SQL Adapter. // The class contains functions that take the proper informational variables and then construct // the appropriate exception with an error string obtained from the resource Framework.txt. // The exception is then returned to the caller, so that the caller may then throw from its // location so that the catcher of the exception will have the appropriate call stack. // This class is used so that there will be compile time checking of error // messages. The resource Framework.txt will ensure proper string text based on the appropriate // locale. // // SQL specific exceptions // // // SQL.Connection // static internal Exception InvalidInternalPacketSize(string str) { return(ADP.ArgumentOutOfRange(str)); }
static internal Exception InvalidPacketSize() { return(ADP.ArgumentOutOfRange(Res.GetString(Res.SQL_InvalidTDSPacketSize))); }
internal static ArgumentOutOfRangeException InvalidSqlDependencyTimeout(string param) { return(ADP.ArgumentOutOfRange(SR.GetString(SR.SqlDependency_InvalidTimeout), param)); }
// // SQL.DataCommand // static internal ArgumentOutOfRangeException NotSupportedEnumerationValue(Type type, int value) { return(ADP.ArgumentOutOfRange(Res.GetString(Res.SQL_NotSupportedEnumerationValue, type.Name, value.ToString(System.Globalization.CultureInfo.InvariantCulture)), type.Name)); }
override public int Read(byte[] buffer, int offset, int count) { int intCount = 0; int cBufferedData = 0; if ((null == _reader)) { throw ADP.StreamClosed(); } if (null == buffer) { throw ADP.ArgumentNull(nameof(buffer)); } if ((offset < 0) || (count < 0)) { throw ADP.ArgumentOutOfRange(string.Empty, (offset < 0 ? nameof(offset) : nameof(count))); } if (buffer.Length - offset < count) { throw ADP.ArgumentOutOfRange(nameof(count)); } // Need to find out if we should add byte order mark or not. // We need to add this if we are getting ntext xml, not if we are getting binary xml // Binary Xml always begins with the bytes 0xDF and 0xFF // If we aren't getting these, then we are getting unicode xml if (_bom > 0) { // Read and buffer the first two bytes _bufferedData = new byte[2]; cBufferedData = ReadBytes(_bufferedData, 0, 2); // Check to se if we should add the byte order mark if ((cBufferedData < 2) || ((_bufferedData[0] == 0xDF) && (_bufferedData[1] == 0xFF))) { _bom = 0; } while (count > 0) { if (_bom > 0) { buffer[offset] = (byte)_bom; _bom >>= 8; offset++; count--; intCount++; } else { break; } } } if (cBufferedData > 0) { while (count > 0) { buffer[offset++] = _bufferedData[0]; intCount++; count--; if ((cBufferedData > 1) && (count > 0)) { buffer[offset++] = _bufferedData[1]; intCount++; count--; break; } } _bufferedData = null; } intCount += ReadBytes(buffer, offset, count); return(intCount); }
private void OpenSqlFileStream ( string path, byte[] transactionContext, System.IO.FileAccess access, System.IO.FileOptions options, Int64 allocationSize ) { //----------------------------------------------------------------- // precondition validation // these should be checked by any caller of this method // ensure we have validated and normalized the path before Debug.Assert(path != null); Debug.Assert(transactionContext != null); if (access != FileAccess.Read && access != FileAccess.Write && access != FileAccess.ReadWrite) { throw ADP.ArgumentOutOfRange("access"); } // FileOptions is a set of flags, so AND the given value against the set of values we do not support if ((options & ~(FileOptions.WriteThrough | FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.SequentialScan)) != 0) { throw ADP.ArgumentOutOfRange("options"); } //----------------------------------------------------------------- // normalize the provided path // * compress path to remove any occurences of '.' or '..' // * trim whitespace from the beginning and end of the path // * ensure that the path starts with '\\' // * ensure that the path does not start with '\\.\' // * ensure that the path is not longer than Int16.MaxValue path = GetFullPathInternal(path); // ensure the running code has permission to read/write the file DemandAccessPermission(path, access); FileFullEaInformation eaBuffer = null; SecurityQualityOfService qos = null; UnicodeString objectName = null; Microsoft.Win32.SafeHandles.SafeFileHandle hFile = null; int nDesiredAccess = UnsafeNativeMethods.FILE_READ_ATTRIBUTES | UnsafeNativeMethods.SYNCHRONIZE; UInt32 dwCreateOptions = 0; UInt32 dwCreateDisposition = 0; System.IO.FileShare shareAccess = System.IO.FileShare.None; switch (access) { case System.IO.FileAccess.Read: nDesiredAccess |= UnsafeNativeMethods.FILE_READ_DATA; shareAccess = System.IO.FileShare.Delete | System.IO.FileShare.ReadWrite; dwCreateDisposition = (uint)UnsafeNativeMethods.CreationDisposition.FILE_OPEN; break; case System.IO.FileAccess.Write: nDesiredAccess |= UnsafeNativeMethods.FILE_WRITE_DATA; shareAccess = System.IO.FileShare.Delete | System.IO.FileShare.Read; dwCreateDisposition = (uint)UnsafeNativeMethods.CreationDisposition.FILE_OVERWRITE; break; case System.IO.FileAccess.ReadWrite: default: // we validate the value of 'access' parameter in the beginning of this method Debug.Assert(access == System.IO.FileAccess.ReadWrite); nDesiredAccess |= UnsafeNativeMethods.FILE_READ_DATA | UnsafeNativeMethods.FILE_WRITE_DATA; shareAccess = System.IO.FileShare.Delete | System.IO.FileShare.Read; dwCreateDisposition = (uint)UnsafeNativeMethods.CreationDisposition.FILE_OVERWRITE; break; } if ((options & System.IO.FileOptions.WriteThrough) != 0) { dwCreateOptions |= (uint)UnsafeNativeMethods.CreateOption.FILE_WRITE_THROUGH; } if ((options & System.IO.FileOptions.Asynchronous) == 0) { dwCreateOptions |= (uint)UnsafeNativeMethods.CreateOption.FILE_SYNCHRONOUS_IO_NONALERT; } if ((options & System.IO.FileOptions.SequentialScan) != 0) { dwCreateOptions |= (uint)UnsafeNativeMethods.CreateOption.FILE_SEQUENTIAL_ONLY; } if ((options & System.IO.FileOptions.RandomAccess) != 0) { dwCreateOptions |= (uint)UnsafeNativeMethods.CreateOption.FILE_RANDOM_ACCESS; } try { eaBuffer = new FileFullEaInformation(transactionContext); qos = new SecurityQualityOfService(UnsafeNativeMethods.SecurityImpersonationLevel.SecurityAnonymous, false, false); // NOTE: the Name property is intended to reveal the publicly available moniker for the // FILESTREAM attributed column data. We will not surface the internal processing that // takes place to create the mappedPath. string mappedPath = InitializeNtPath(path); objectName = new UnicodeString(mappedPath); UnsafeNativeMethods.OBJECT_ATTRIBUTES oa; oa.length = Marshal.SizeOf(typeof(UnsafeNativeMethods.OBJECT_ATTRIBUTES)); oa.rootDirectory = IntPtr.Zero; oa.attributes = (int)UnsafeNativeMethods.Attributes.CaseInsensitive; oa.securityDescriptor = IntPtr.Zero; oa.securityQualityOfService = qos; oa.objectName = objectName; UnsafeNativeMethods.IO_STATUS_BLOCK ioStatusBlock; uint oldMode; uint retval = 0; UnsafeNativeMethods.SetErrorModeWrapper(UnsafeNativeMethods.SEM_FAILCRITICALERRORS, out oldMode); try { Bid.Trace("<sc.SqlFileStream.OpenSqlFileStream|ADV> %d#, desiredAccess=0x%08x, allocationSize=%I64d, fileAttributes=0x%08x, shareAccess=0x%08x, dwCreateDisposition=0x%08x, createOptions=0x%08x\n", ObjectID, (int)nDesiredAccess, allocationSize, 0, (int)shareAccess, dwCreateDisposition, dwCreateOptions); retval = UnsafeNativeMethods.NtCreateFile(out hFile, nDesiredAccess, ref oa, out ioStatusBlock, ref allocationSize, 0, shareAccess, dwCreateDisposition, dwCreateOptions, eaBuffer, (uint)eaBuffer.Length); } finally { UnsafeNativeMethods.SetErrorModeWrapper(oldMode, out oldMode); } switch (retval) { case 0: break; case UnsafeNativeMethods.STATUS_SHARING_VIOLATION: throw ADP.InvalidOperation(Res.GetString(Res.SqlFileStream_FileAlreadyInTransaction)); case UnsafeNativeMethods.STATUS_INVALID_PARAMETER: throw ADP.Argument(Res.GetString(Res.SqlFileStream_InvalidParameter)); case UnsafeNativeMethods.STATUS_OBJECT_NAME_NOT_FOUND: { System.IO.DirectoryNotFoundException e = new System.IO.DirectoryNotFoundException(); ADP.TraceExceptionAsReturnValue(e); throw e; } default: { uint error = UnsafeNativeMethods.RtlNtStatusToDosError(retval); if (error == UnsafeNativeMethods.ERROR_MR_MID_NOT_FOUND) { // status code could not be mapped to a Win32 error code error = retval; } System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(unchecked ((int)error)); ADP.TraceExceptionAsReturnValue(e); throw e; } } if (hFile.IsInvalid) { System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(UnsafeNativeMethods.ERROR_INVALID_HANDLE); ADP.TraceExceptionAsReturnValue(e); throw e; } UnsafeNativeMethods.FileType fileType = UnsafeNativeMethods.GetFileType(hFile); if (fileType != UnsafeNativeMethods.FileType.Disk) { hFile.Dispose(); throw ADP.Argument(Res.GetString(Res.SqlFileStream_PathNotValidDiskResource)); } // if the user is opening the SQL FileStream in read/write mode, we assume that they want to scan // through current data and then append new data to the end, so we need to tell SQL Server to preserve // the existing file contents. if (access == System.IO.FileAccess.ReadWrite) { uint ioControlCode = UnsafeNativeMethods.CTL_CODE(UnsafeNativeMethods.FILE_DEVICE_FILE_SYSTEM, IoControlCodeFunctionCode, (byte)UnsafeNativeMethods.Method.METHOD_BUFFERED, (byte)UnsafeNativeMethods.Access.FILE_ANY_ACCESS); uint cbBytesReturned = 0; if (!UnsafeNativeMethods.DeviceIoControl(hFile, ioControlCode, IntPtr.Zero, 0, IntPtr.Zero, 0, out cbBytesReturned, IntPtr.Zero)) { System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); ADP.TraceExceptionAsReturnValue(e); throw e; } } // now that we've successfully opened a handle on the path and verified that it is a file, // use the SafeFileHandle to initialize our internal System.IO.FileStream instance // NOTE: need to assert UnmanagedCode permissions for this constructor. This is relatively benign // in that we've done much the same validation as in the FileStream(string path, ...) ctor case // most notably, validating that the handle type corresponds to an on-disk file. bool bRevertAssert = false; try { SecurityPermission sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); sp.Assert(); bRevertAssert = true; System.Diagnostics.Debug.Assert(m_fs == null); m_fs = new System.IO.FileStream(hFile, access, DefaultBufferSize, ((options & System.IO.FileOptions.Asynchronous) != 0)); } finally { if (bRevertAssert) { SecurityPermission.RevertAssert(); } } } catch { if (hFile != null && !hFile.IsInvalid) { hFile.Dispose(); } throw; } finally { if (eaBuffer != null) { eaBuffer.Dispose(); eaBuffer = null; } if (qos != null) { qos.Dispose(); qos = null; } if (objectName != null) { objectName.Dispose(); objectName = null; } } }
private void InitializeEaBuffer(byte[] transactionContext) { if (transactionContext.Length >= UInt16.MaxValue) { throw ADP.ArgumentOutOfRange("transactionContext"); } UnsafeNativeMethods.FILE_FULL_EA_INFORMATION eaBuffer; eaBuffer.nextEntryOffset = 0; eaBuffer.flags = 0; eaBuffer.EaName = 0; // string will be written as ANSI chars, so Length == ByteLength in this case eaBuffer.EaNameLength = (byte)EA_NAME_STRING.Length; eaBuffer.EaValueLength = (ushort)transactionContext.Length; // allocate sufficient memory to contain the FILE_FULL_EA_INFORMATION struct and // the contiguous name/value pair in eaName (note: since the struct already // contains one byte for eaName, we don't need to allocate a byte for the // null character separator). m_cbBuffer = Marshal.SizeOf(eaBuffer) + eaBuffer.EaNameLength + eaBuffer.EaValueLength; IntPtr pbBuffer = IntPtr.Zero; RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { pbBuffer = Marshal.AllocHGlobal(m_cbBuffer); if (pbBuffer != IntPtr.Zero) { SetHandle(pbBuffer); } } bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); IntPtr ptr = DangerousGetHandle(); // write struct into buffer Marshal.StructureToPtr(eaBuffer, ptr, false); // write property name into buffer System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding(); byte [] asciiName = ascii.GetBytes(EA_NAME_STRING); // calculate offset at which to write the name/value pair System.Diagnostics.Debug.Assert(Marshal.OffsetOf(typeof(UnsafeNativeMethods.FILE_FULL_EA_INFORMATION), "EaName").ToInt64() <= (Int64)Int32.MaxValue); int cbOffset = Marshal.OffsetOf(typeof(UnsafeNativeMethods.FILE_FULL_EA_INFORMATION), "EaName").ToInt32(); for (int i = 0; cbOffset < m_cbBuffer && i < eaBuffer.EaNameLength; i++, cbOffset++) { Marshal.WriteByte(ptr, cbOffset, asciiName[i]); } System.Diagnostics.Debug.Assert(cbOffset < m_cbBuffer); // write null character separator Marshal.WriteByte(ptr, cbOffset, 0); cbOffset++; System.Diagnostics.Debug.Assert(cbOffset < m_cbBuffer || transactionContext.Length == 0 && cbOffset == m_cbBuffer); // write transaction context ID for (int i = 0; cbOffset < m_cbBuffer && i < eaBuffer.EaValueLength; i++, cbOffset++) { Marshal.WriteByte(ptr, cbOffset, transactionContext[i]); } } finally { if (mustRelease) { DangerousRelease(); } } }
internal static ArgumentOutOfRangeException NotSupportedEnumerationValue(Type type, int value) { return(ADP.ArgumentOutOfRange(Res.GetString("ODBC_NotSupportedEnumerationValue", new object[] { type.Name, value.ToString(CultureInfo.InvariantCulture) }), type.Name)); }