public unsafe override void Write(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (count < 0) { throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (buffer.Length - offset < count) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); } if (!this._isOpen) { __Error.StreamIsClosed(); } if (!this.CanWrite) { __Error.WriteNotSupported(); } long num = Interlocked.Read(ref this._position); long num2 = Interlocked.Read(ref this._length); long num3 = num + (long)count; if (num3 < 0L) { throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong")); } if (num3 > this._capacity) { throw new NotSupportedException(Environment.GetResourceString("IO.IO_FixedCapacity")); } if (this._buffer == null) { if (num > num2) { Buffer.ZeroMemory(this._mem + num2, num - num2); } if (num3 > num2) { Interlocked.Exchange(ref this._length, num3); } } if (this._buffer != null) { long num4 = this._capacity - num; if (num4 < (long)count) { throw new ArgumentException(Environment.GetResourceString("Arg_BufferTooSmall")); } byte *ptr = null; RuntimeHelpers.PrepareConstrainedRegions(); try { this._buffer.AcquirePointer(ref ptr); Buffer.Memcpy(ptr + num + this._offset, 0, buffer, offset, count); goto IL_16D; } finally { if (ptr != null) { this._buffer.ReleasePointer(); } } } Buffer.Memcpy(this._mem + num, 0, buffer, offset, count); IL_16D: Interlocked.Exchange(ref this._position, num3); }
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 void ShimNotificationCallback(object state, bool timeout) { // First we need to get the notification from the shim factory. IntPtr enlistmentHandleIntPtr = IntPtr.Zero; ShimNotificationType shimNotificationType = ShimNotificationType.None; bool isSinglePhase = false; bool abortingHint = false; UInt32 prepareInfoSize = 0; CoTaskMemHandle prepareInfoBuffer = null; bool holdingNotificationLock = false; bool cleanExit = false; IDtcProxyShimFactory localProxyShimFactory = null; if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(SR.GetString(SR.TraceSourceOletx), "OletxTransactionManager.ShimNotificationCallback" ); } // This lock doesn't really protect any of our data. It is here so that if an exception occurs // while calling out to the app, we get an escalation to AppDomainUnload. Thread.BeginCriticalRegion(); try { do { // Take a local copy of the proxyShimFactory because if we get an RM TMDown notification, // we will still hold the critical section in that factory, but processing of the TMDown will // cause replacement of the OletxTransactionManager.proxyShimFactory. localProxyShimFactory = OletxTransactionManager.proxyShimFactory; try { Thread.BeginThreadAffinity(); RuntimeHelpers.PrepareConstrainedRegions(); try { localProxyShimFactory.GetNotification( out enlistmentHandleIntPtr, out shimNotificationType, out isSinglePhase, out abortingHint, out holdingNotificationLock, out prepareInfoSize, out prepareInfoBuffer ); } finally { if (holdingNotificationLock) { if ((HandleTable.FindHandle(enlistmentHandleIntPtr)) is OletxInternalResourceManager) { // In this case we know that the TM has gone down and we need to exchange // the native lock for a managed lock. processingTmDown = true; #pragma warning disable 0618 //@ System.Threading.Monitor.Enter(OletxTransactionManager.proxyShimFactory); #pragma warning restore 0618 } else { holdingNotificationLock = false; } localProxyShimFactory.ReleaseNotificationLock(); } Thread.EndThreadAffinity(); } // If a TM down is being processed it is possible that the native lock // has been exchanged for a managed lock. In that case we need to attempt // to take a lock to hold up processing more events until the TM down // processing is complete. if (processingTmDown) { lock (OletxTransactionManager.proxyShimFactory) { // We don't do any work under this lock just make sure that we // can take it. } } if (ShimNotificationType.None != shimNotificationType) { Object target = HandleTable.FindHandle(enlistmentHandleIntPtr); // Next, based on the notification type, cast the Handle accordingly and make // the appropriate call on the enlistment. switch (shimNotificationType) { case ShimNotificationType.Phase0RequestNotify: { try { OletxPhase0VolatileEnlistmentContainer ph0VolEnlistContainer = target as OletxPhase0VolatileEnlistmentContainer; if (null != ph0VolEnlistContainer) { DiagnosticTrace.SetActivityId( ph0VolEnlistContainer.TransactionIdentifier); //CSDMain 91509 - We now synchronize this call with the AddDependentClone call in RealOleTxTransaction ph0VolEnlistContainer.Phase0Request(abortingHint); } else { OletxEnlistment enlistment = target as OletxEnlistment; if (null != enlistment) { DiagnosticTrace.SetActivityId( enlistment.TransactionIdentifier); enlistment.Phase0Request(abortingHint); } else { Environment.FailFast(SR.GetString(SR.InternalError)); } } } finally { // We aren't going to get any more notifications on this. HandleTable.FreeHandle(enlistmentHandleIntPtr); } break; } case ShimNotificationType.VoteRequestNotify: { OletxPhase1VolatileEnlistmentContainer ph1VolEnlistContainer = target as OletxPhase1VolatileEnlistmentContainer; if (null != ph1VolEnlistContainer) { DiagnosticTrace.SetActivityId( ph1VolEnlistContainer.TransactionIdentifier); ph1VolEnlistContainer.VoteRequest(); } else { Environment.FailFast(SR.GetString(SR.InternalError)); } break; } case ShimNotificationType.CommittedNotify: { try { OutcomeEnlistment outcomeEnlistment = target as OutcomeEnlistment; if (null != outcomeEnlistment) { DiagnosticTrace.SetActivityId( outcomeEnlistment.TransactionIdentifier); outcomeEnlistment.Committed(); } else { OletxPhase1VolatileEnlistmentContainer ph1VolEnlistContainer = target as OletxPhase1VolatileEnlistmentContainer; if (null != ph1VolEnlistContainer) { DiagnosticTrace.SetActivityId( ph1VolEnlistContainer.TransactionIdentifier); ph1VolEnlistContainer.Committed(); } else { Environment.FailFast(SR.GetString(SR.InternalError)); } } } finally { // We aren't going to get any more notifications on this. HandleTable.FreeHandle(enlistmentHandleIntPtr); } break; } case ShimNotificationType.AbortedNotify: { try { OutcomeEnlistment outcomeEnlistment = target as OutcomeEnlistment; if (null != outcomeEnlistment) { DiagnosticTrace.SetActivityId( outcomeEnlistment.TransactionIdentifier); outcomeEnlistment.Aborted(); } else { OletxPhase1VolatileEnlistmentContainer ph1VolEnlistContainer = target as OletxPhase1VolatileEnlistmentContainer; if (null != ph1VolEnlistContainer) { DiagnosticTrace.SetActivityId( ph1VolEnlistContainer.TransactionIdentifier); ph1VolEnlistContainer.Aborted(); } // else // Voters may receive notifications even // in cases where they therwise respond // negatively to the vote request. It is // also not guaranteed that we will get a // notification if we do respond negatively. // The only safe thing to do is to free the // Handle when we abort the transaction // with a voter. These two things together // mean that we cannot guarantee that this // Handle will be alive when we get this // notification. } } finally { // We aren't going to get any more notifications on this. HandleTable.FreeHandle(enlistmentHandleIntPtr); } break; } case ShimNotificationType.InDoubtNotify: { try { OutcomeEnlistment outcomeEnlistment = target as OutcomeEnlistment; if (null != outcomeEnlistment) { DiagnosticTrace.SetActivityId( outcomeEnlistment.TransactionIdentifier); outcomeEnlistment.InDoubt(); } else { OletxPhase1VolatileEnlistmentContainer ph1VolEnlistContainer = target as OletxPhase1VolatileEnlistmentContainer; if (null != ph1VolEnlistContainer) { DiagnosticTrace.SetActivityId( ph1VolEnlistContainer.TransactionIdentifier); ph1VolEnlistContainer.InDoubt(); } else { Environment.FailFast(SR.GetString(SR.InternalError)); } } } finally { // We aren't going to get any more notifications on this. HandleTable.FreeHandle(enlistmentHandleIntPtr); } break; } case ShimNotificationType.PrepareRequestNotify: { byte[] prepareInfo = new byte[prepareInfoSize]; Marshal.Copy(prepareInfoBuffer.DangerousGetHandle(), prepareInfo, 0, Convert.ToInt32(prepareInfoSize)); bool enlistmentDone = true; try { OletxEnlistment enlistment = target as OletxEnlistment; if (null != enlistment) { DiagnosticTrace.SetActivityId( enlistment.TransactionIdentifier); enlistmentDone = enlistment.PrepareRequest( isSinglePhase, prepareInfo ); } else { Environment.FailFast(SR.GetString(SR.InternalError)); } } finally { if (enlistmentDone) { HandleTable.FreeHandle(enlistmentHandleIntPtr); } } break; } case ShimNotificationType.CommitRequestNotify: { try { OletxEnlistment enlistment = target as OletxEnlistment; if (null != enlistment) { DiagnosticTrace.SetActivityId( enlistment.TransactionIdentifier); enlistment.CommitRequest(); } else { Environment.FailFast(SR.GetString(SR.InternalError)); } } finally { // We aren't going to get any more notifications on this. HandleTable.FreeHandle(enlistmentHandleIntPtr); } break; } case ShimNotificationType.AbortRequestNotify: { try { OletxEnlistment enlistment = target as OletxEnlistment; if (null != enlistment) { DiagnosticTrace.SetActivityId( enlistment.TransactionIdentifier); enlistment.AbortRequest(); } else { Environment.FailFast(SR.GetString(SR.InternalError)); } } finally { // We aren't going to get any more notifications on this. HandleTable.FreeHandle(enlistmentHandleIntPtr); } break; } case ShimNotificationType.EnlistmentTmDownNotify: { try { OletxEnlistment enlistment = target as OletxEnlistment; if (null != enlistment) { DiagnosticTrace.SetActivityId( enlistment.TransactionIdentifier); enlistment.TMDown(); } else { Environment.FailFast(SR.GetString(SR.InternalError)); } } finally { // We aren't going to get any more notifications on this. HandleTable.FreeHandle(enlistmentHandleIntPtr); } break; } case ShimNotificationType.ResourceManagerTmDownNotify: { OletxResourceManager resourceManager = target as OletxResourceManager; try { if (null != resourceManager) { resourceManager.TMDown(); } else { OletxInternalResourceManager internalResourceManager = target as OletxInternalResourceManager; if (null != internalResourceManager) { internalResourceManager.TMDown(); } else { Environment.FailFast(SR.GetString(SR.InternalError)); } } } finally { HandleTable.FreeHandle(enlistmentHandleIntPtr); } // Note that we don't free the gchandle on the OletxResourceManager. These objects // are not going to go away. break; } default: { Environment.FailFast(SR.GetString(SR.InternalError)); break; } } } } finally { if (null != prepareInfoBuffer) { prepareInfoBuffer.Close(); } if (holdingNotificationLock) { holdingNotificationLock = false; processingTmDown = false; System.Threading.Monitor.Exit(OletxTransactionManager.proxyShimFactory); } } }while (ShimNotificationType.None != shimNotificationType); cleanExit = true; } finally { if (holdingNotificationLock) { holdingNotificationLock = false; processingTmDown = false; System.Threading.Monitor.Exit(OletxTransactionManager.proxyShimFactory); } if (!cleanExit && enlistmentHandleIntPtr != IntPtr.Zero) { HandleTable.FreeHandle(enlistmentHandleIntPtr); } Thread.EndCriticalRegion(); } if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(SR.GetString(SR.TraceSourceOletx), "OletxTransactionManager.ShimNotificationCallback" ); } }
[System.Security.SecuritySafeCritical] // auto-generated public LocalDataStoreSlot AllocateDataSlot() { bool tookLock = false; RuntimeHelpers.PrepareConstrainedRegions(); try { Monitor.Enter(this, ref tookLock); LocalDataStoreSlot slot; int slotTableSize = m_SlotInfoTable.Length; // In case FreeDataSlot has moved the pointer back, the next slot may not be available. // Find the first actually available slot. int availableSlot = m_FirstAvailableSlot; while (availableSlot < slotTableSize) { if (!m_SlotInfoTable[availableSlot]) { break; } availableSlot++; } // Check if there are any slots left. if (availableSlot >= slotTableSize) { // The table is full so we need to increase its size. int newSlotTableSize; if (slotTableSize < SlotTableDoubleThreshold) { // The table is still relatively small so double it. newSlotTableSize = slotTableSize * 2; } else { // The table is relatively large so simply increase its size by a given amount. newSlotTableSize = slotTableSize + LargeSlotTableSizeIncrease; } // Allocate the new slot info table. bool[] newSlotInfoTable = new bool[newSlotTableSize]; // Copy the old array into the new one. Array.Copy(m_SlotInfoTable, newSlotInfoTable, slotTableSize); m_SlotInfoTable = newSlotInfoTable; } // availableSlot is the index of the empty slot. m_SlotInfoTable[availableSlot] = true; // We do not need to worry about overflowing m_CookieGenerator. It would take centuries // of intensive slot allocations on current machines to get the 2^64 counter to overflow. // We will perform the increment with overflow check just to play it on the safe side. slot = new LocalDataStoreSlot(this, availableSlot, checked (m_CookieGenerator++)); // Save the new "first available slot".hint m_FirstAvailableSlot = availableSlot + 1; // Return the selected slot return(slot); } finally { if (tookLock) { Monitor.Exit(this); } } }
public byte[] Next(byte[] challenge) { byte[] outBytes; var outputBuffer = new SecurityBufferDescriptor(__maxTokenSize); bool credentialAddRefSuccess = false; bool contextAddRefSuccess = false; #if NET452 RuntimeHelpers.PrepareConstrainedRegions(); #endif try { _credential.DangerousAddRef(ref credentialAddRefSuccess); DangerousAddRef(ref contextAddRefSuccess); } catch (Exception ex) { if (credentialAddRefSuccess) { _credential.DangerousRelease(); credentialAddRefSuccess = false; } if (contextAddRefSuccess) { DangerousRelease(); contextAddRefSuccess = false; } if (!(ex is ObjectDisposedException)) { throw; } } finally { try { var flags = SspiContextFlags.MutualAuth; uint result; long timestamp; var credentialHandle = _credential._sspiHandle; if (challenge == null || challenge.Length == 0) { result = NativeMethods.InitializeSecurityContext( ref credentialHandle, IntPtr.Zero, _servicePrincipalName, flags, 0, DataRepresentation.Network, IntPtr.Zero, 0, ref _sspiHandle, ref outputBuffer, out flags, out timestamp); } else { var serverToken = new SecurityBufferDescriptor(challenge); try { result = NativeMethods.InitializeSecurityContext( ref credentialHandle, ref _sspiHandle, _servicePrincipalName, flags, 0, DataRepresentation.Network, ref serverToken, 0, ref _sspiHandle, ref outputBuffer, out flags, out timestamp); } finally { serverToken.Free(); } } _credential.DangerousRelease(); DangerousRelease(); if (result != NativeMethods.SEC_E_OK && result != NativeMethods.SEC_I_CONTINUE_NEEDED) { throw NativeMethods.CreateException(result, "Unable to initialize security context."); } outBytes = outputBuffer.ToByteArray(); _isInitialized = result == NativeMethods.SEC_E_OK; } finally { outputBuffer.Free(); } } return(outBytes); }
public void KillProcess(int[] Pids, string path) { //long formal; //int size = Marshal.SizeOf(typeof(SYSTEM_BASIC_INFORMATION)); //IntPtr ptr = Marshal.AllocHGlobal(size); //Console.WriteLine("NTSTATUS: " + APIQuerySystemInformation(SYSTEM_INFORMATION_CLASS.SystemHandleInformation, ptr, size, out formal).ToString("X")); //SYSTEM_BASIC_INFORMATION INFO = ((SYSTEM_BASIC_INFORMATION)Marshal.PtrToStructure(ptr, typeof(SYSTEM_BASIC_INFORMATION))); //Console.WriteLine(INFO.NumberOfProcessors); //Console.WriteLine(formal); int length = 0x10000; int returnLength; NT_STATUS ret; do { IntPtr ptr = Marshal.AllocHGlobal(length); RuntimeHelpers.PrepareConstrainedRegions(); try { ret = NtQuerySystemInformation(SYSTEM_INFORMATION_CLASS.SystemHandleInformation, ptr, length, out returnLength); if (ret == NT_STATUS.STATUS_INFO_LENGTH_MISMATCH) { length = ((returnLength + 0xffff) & ~0xffff); } else { if (ret == NT_STATUS.STATUS_SUCCESS) { int handleCount = Marshal.ReadInt32(ptr); int offset = sizeof(int); int size = Marshal.SizeOf(typeof(SYSTEM_HANDLE_ENTRY)); for (int i = 0; i < handleCount; i++) { SYSTEM_HANDLE_ENTRY handleEntry = (SYSTEM_HANDLE_ENTRY)Marshal.PtrToStructure((IntPtr)((int)ptr + offset), typeof(SYSTEM_HANDLE_ENTRY)); SystemHandleType handleType; IntPtr handle = (IntPtr)handleEntry.HandleValue; foreach (int pid in Pids) { if (handleEntry.OwnerPid == pid) { if (GetHandleType(handle, handleEntry.OwnerPid, out handleType)) { if (handleType == SystemHandleType.OB_TYPE_FILE) { string devicePath; if (GetFileNameFromHandle(handle, handleEntry.OwnerPid, out devicePath)) { string dosPath; if (ConvertDevicePathToDosPath(devicePath, out dosPath)) { if (dosPath.Contains(path)) { System.Diagnostics.Process.GetProcessById(handleEntry.OwnerPid).Kill(); } } } } } } } offset += size; } } } } finally { Marshal.FreeHGlobal(ptr); } }while (ret == NT_STATUS.STATUS_INFO_LENGTH_MISMATCH); }
/// <summary> /// カーソルの画像を取得する /// </summary> /// <param name="iconHandle"> /// カーソルアイコンへのハンドル /// </param> /// <param name="iconInfo"> /// カーソルアイコン情報 /// </param> /// <param name="backgroundImage"> /// カーソルの背景画像(NULLを指定した場合は白一色の背景として描画する) /// </param> /// <param name="drawPoint"> /// 背景画像に対してカーソルを描画する座標 /// (背景画像を使用しない場合は NULL を指定する)</param> /// <exception cref="PlatformInvokeException"> /// Win32Apiの下記の処理の呼び出しに失敗した場合に発生 /// ・「DLL:gdi32.dll、メソッド:CreateCompatibleDC」 /// ・「DLL:gdi32.dll、メソッド:SelectObject」 /// ・「DLL:gdi32.dll、メソッド:BitBlt」 /// ・「DLL:gdi32.dll、メソッド:DeleteObject」 /// ・「DLL:gdi32.dll、メソッド:DeleteDC」 /// </exception> /// <exception cref="Win32OperateException"> /// Win32Apiの下記の処理に失敗した場合に発生 /// ・「DLL:gdi32.dll、メソッド:CreateCompatibleDC」 /// ・「DLL:gdi32.dll、メソッド:SelectObject」 /// ・「DLL:gdi32.dll、メソッド:BitBlt」 /// ・「DLL:gdi32.dll、メソッド:DeleteObject」 /// ・「DLL:gdi32.dll、メソッド:DeleteDC」 /// </exception> /// <returns>カーソル画像(取得できない場合はNULLを返却する)</returns> private static Bitmap GetCursorImage( SafeCopyIconHandle iconHandle, IconInfo.ICONINFO iconInfo, Bitmap backgroundImage = null, Point?drawPoint = null) { // カラー・マスク情報が存在するか判定 bool hasColor = IsBitmap(iconInfo.ColorBitmapHandle); bool hasMask = IsBitmap(iconInfo.MaskBitmapHandle); // アイコンのカラー、マスクの両方が取得できない場合 // 画像情報は取得できないため NULL を返す if (!hasColor && !hasMask) { return(null); } // アイコンのハンドルからカーソルアイコンを取得する Icon cursorIcon; try { cursorIcon = Icon.FromHandle(iconHandle.Handle); } catch (ExternalException) { // アイコンのハンドルからカーソルアイコンを生成できない場合、NULL を返す return(null); } // カーソルがモノクロかカラーでそれぞれ取得を行う if (hasColor) { // カラーの場合 // アイコン画像をビットマップ形式に変換して、そのまま返す return(cursorIcon.ToBitmap()); } // モノクロの場合 // 画像に関するリソースの解放用の宣言 Bitmap cursorImage = null; Graphics cursorImageGraphics = null; Bitmap baseImage = null; Bitmap maskImage = null; bool isCreateBase = false; try { // 各画像データの生成 // カーソル画像と、グラフィックオブジェクト生成 cursorImage = new Bitmap(cursorIcon.Width, cursorIcon.Height); cursorImageGraphics = Graphics.FromImage(cursorImage); // 背景画像の生成 // 引数で背景画像が与えられていない場合、白一色の背景画像を生成する if (backgroundImage == null) { baseImage = new Bitmap(cursorIcon.Width, cursorIcon.Height); using (Graphics graphics = Graphics.FromImage(baseImage)) { graphics.FillRectangle(Brushes.White, graphics.VisibleClipBounds); } isCreateBase = true; } else { isCreateBase = false; } // マスク画像の生成 maskImage = Image.FromHbitmap(iconInfo.MaskBitmapHandle); // アンマネージリソースの解放用の宣言 SafeDCHandle cursorHdc = null; SafeDCHandle baseHdc = null; SafeDCHandle maskHdc = null; IntPtr beforeBase = IntPtr.Zero; IntPtr beforeMask = IntPtr.Zero; RuntimeHelpers.PrepareConstrainedRegions(); try { // カーソル画像のデバイスコンテキストを取得 cursorHdc = new SafeDCHandle(cursorImageGraphics); // 背景画像のデバイスコンテキストを取得 IntPtr baseHBitmap = isCreateBase ? baseImage.GetHbitmap() : backgroundImage.GetHbitmap(); baseHdc = CreateCompatibleDC(IntPtr.Zero); beforeBase = SelectBitmap(baseHdc, baseHBitmap); // マスク画像のデバイスコンテキストを取得 IntPtr maskHBitmap = maskImage.GetHbitmap(); maskHdc = CreateCompatibleDC(IntPtr.Zero); beforeMask = SelectBitmap(maskHdc, maskHBitmap); // 画像の合成処理 int width = cursorImage.Width; int height = cursorImage.Height; Point base1Pt = drawPoint ?? new Point(0, 0); Point mask1Pt = new Point(0, 0); Point mask2Pt = new Point(0, maskImage.Height / 2); BitBlt(cursorHdc, 0, 0, width, height, baseHdc, base1Pt.X, base1Pt.Y, ROPCode.SRCCOPY); BitBlt(cursorHdc, 0, 0, width, height, maskHdc, mask1Pt.X, mask1Pt.Y, ROPCode.SRCAND); BitBlt(cursorHdc, 0, 0, width, height, maskHdc, mask2Pt.X, mask2Pt.Y, ROPCode.SRCINVERT); } finally { // リソースの解放処理 // カーソル画像に関するリソースの解放 try { } finally { cursorHdc.Dispose(); } // 元となる背景画像に関するリソースの解放 try { if (baseHdc != null) { IntPtr baseHandle = SelectBitmap(baseHdc, beforeBase); if (baseHandle != IntPtr.Zero) { DeleteObject(baseHandle); } } } finally { baseHdc?.Dispose(); } // マスク画像に関するリソースの解放 try { if (maskHdc != null) { IntPtr maskHandle = SelectBitmap(maskHdc, beforeMask); if (maskHandle != IntPtr.Zero) { DeleteObject(maskHandle); } } } finally { maskHdc?.Dispose(); } } } catch { // 例外発生時はカーソル画像を破棄する cursorImage.Dispose(); // 発生した例外はそのままスローする throw; } finally { // 画像リソースを解放する cursorImageGraphics?.Dispose(); baseImage?.Dispose(); maskImage?.Dispose(); } // 背景画像を白一色で生成した場合、背景を透過する if (isCreateBase) { cursorImage.MakeTransparent(Color.White); } // 合成したカーソル画像を返す return(cursorImage); }
[System.Security.SecuritySafeCritical] // auto-generated public override void Write(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (count < 0) { throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (buffer.Length - offset < count) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); } Contract.EndContractBlock(); // Keep contract validation in [....] with WriteAsync(..) if (!_isOpen) { __Error.StreamIsClosed(); } if (!CanWrite) { __Error.WriteNotSupported(); } long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition long len = Interlocked.Read(ref _length); long n = pos + count; // Check for overflow if (n < 0) { throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong")); } if (n > _capacity) { throw new NotSupportedException(Environment.GetResourceString("IO.IO_FixedCapacity")); } if (_buffer == null) { // Check to see whether we are now expanding the stream and must // zero any memory in the middle. if (pos > len) { unsafe { Buffer.ZeroMemory(_mem + len, pos - len); } } // set length after zeroing memory to avoid race condition of accessing unzeroed memory if (n > len) { Interlocked.Exchange(ref _length, n); } } if (_buffer != null) { long bytesLeft = _capacity - pos; if (bytesLeft < count) { throw new ArgumentException(Environment.GetResourceString("Arg_BufferTooSmall")); } unsafe { byte *pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); Buffer.Memcpy(pointer + pos + _offset, 0, buffer, offset, count); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } else { unsafe { Buffer.Memcpy(_mem + pos, 0, buffer, offset, count); } } Interlocked.Exchange(ref _position, n); return; }
[System.Security.SecuritySafeCritical] // auto-generated public override void WriteByte(byte value) { if (!_isOpen) { __Error.StreamIsClosed(); } if (!CanWrite) { __Error.WriteNotSupported(); } long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition long len = Interlocked.Read(ref _length); long n = pos + 1; if (pos >= len) { // Check for overflow if (n < 0) { throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong")); } if (n > _capacity) { throw new NotSupportedException(Environment.GetResourceString("IO.IO_FixedCapacity")); } // Check to see whether we are now expanding the stream and must // zero any memory in the middle. // don't do if created from SafeBuffer if (_buffer == null) { if (pos > len) { unsafe { Buffer.ZeroMemory(_mem + len, pos - len); } } // set length after zeroing memory to avoid race condition of accessing unzeroed memory Interlocked.Exchange(ref _length, n); } } if (_buffer != null) { unsafe { byte *pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); *(pointer + pos + _offset) = value; } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } else { unsafe { _mem[pos] = value; } } Interlocked.Exchange(ref _position, n); }
[System.Security.SecurityCritical] // auto-generated internal void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access, bool skipSecurityCheck) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (length < 0) { throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (buffer.ByteLength < (ulong)(offset + length)) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSafeBufferOffLen")); } if (access < FileAccess.Read || access > FileAccess.ReadWrite) { throw new ArgumentOutOfRangeException("access"); } Contract.EndContractBlock(); if (_isOpen) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CalledTwice")); } #if !DISABLE_CAS_USE if (!skipSecurityCheck) { #pragma warning disable 618 new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); #pragma warning restore 618 } #endif // check for wraparound unsafe { byte *pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { buffer.AcquirePointer(ref pointer); if ((pointer + offset + length) < pointer) { throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamWrapAround")); } } finally { if (pointer != null) { buffer.ReleasePointer(); } } } _offset = offset; _buffer = buffer; _length = length; _capacity = length; _access = access; _isOpen = true; }
[System.Security.SecuritySafeCritical] // auto-generated public override int Read([In, Out] byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (count < 0) { throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (buffer.Length - offset < count) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); } Contract.EndContractBlock(); // Keep this in [....] with contract validation in ReadAsync if (!_isOpen) { __Error.StreamIsClosed(); } if (!CanRead) { __Error.ReadNotSupported(); } // Use a local variable to avoid a race where another thread // changes our position after we decide we can read some bytes. long pos = Interlocked.Read(ref _position); long len = Interlocked.Read(ref _length); long n = len - pos; if (n > count) { n = count; } if (n <= 0) { return(0); } int nInt = (int)n; // Safe because n <= count, which is an Int32 if (nInt < 0) { nInt = 0; // _position could be beyond EOF } Contract.Assert(pos + nInt >= 0, "_position + n >= 0"); // len is less than 2^63 -1. if (_buffer != null) { unsafe { byte *pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); Buffer.Memcpy(buffer, offset, pointer + pos + _offset, 0, nInt); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } else { unsafe { Buffer.Memcpy(buffer, offset, _mem + pos, 0, nInt); } } Interlocked.Exchange(ref _position, pos + n); return(nInt); }
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlTransaction.xml' path='docs/members[@name="SqlTransaction"]/RollbackTransactionName/*' /> public void Rollback(string transactionName) { SqlConnection.ExecutePermission.Demand(); // MDAC 81476 ZombieCheck(); SqlStatistics statistics = null; using (TryEventScope.Create("<sc.SqlTransaction.Rollback|API> {0} transactionName='{1}'", ObjectID, transactionName)) { TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); try { #if DEBUG TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); try { tdsReliabilitySection.Start(); #else { #endif //DEBUG bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_connection); statistics = SqlStatistics.StartTimer(Statistics); _isFromAPI = true; _internalTransaction.Rollback(transactionName); } #if DEBUG finally { tdsReliabilitySection.Stop(); } #endif //DEBUG } catch (System.OutOfMemoryException e) { _connection.Abort(e); throw; } catch (System.StackOverflowException e) { _connection.Abort(e); throw; } catch (System.Threading.ThreadAbortException e) { _connection.Abort(e); SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget); throw; } finally { _isFromAPI = false; SqlStatistics.StopTimer(statistics); } } }
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlTransaction.xml' path='docs/members[@name="SqlTransaction"]/Rollback2/*' /> override public void Rollback() { if (Is2005PartialZombie) { // Put something in the trace in case a customer has an issue SqlClientEventSource.Log.TryAdvancedTraceEvent("<sc.SqlTransaction.Rollback|ADV> {0} partial zombie no rollback required", ObjectID); _internalTransaction = null; // 2005 zombification } else { ZombieCheck(); SqlStatistics statistics = null; using (TryEventScope.Create("<sc.SqlTransaction.Rollback|API> {0}", ObjectID)) { SqlClientEventSource.Log.TryCorrelationTraceEvent("<sc.SqlTransaction.Rollback|API|Correlation> ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); try { #if DEBUG TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); try { tdsReliabilitySection.Start(); #else { #endif //DEBUG bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_connection); statistics = SqlStatistics.StartTimer(Statistics); _isFromAPI = true; _internalTransaction.Rollback(); } #if DEBUG finally { tdsReliabilitySection.Stop(); } #endif //DEBUG } catch (System.OutOfMemoryException e) { _connection.Abort(e); throw; } catch (System.StackOverflowException e) { _connection.Abort(e); throw; } catch (System.Threading.ThreadAbortException e) { _connection.Abort(e); SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget); throw; } finally { _isFromAPI = false; SqlStatistics.StopTimer(statistics); } } } }
//////////////////////////////////////////////////////////////////////////////////////// // PUBLIC METHODS //////////////////////////////////////////////////////////////////////////////////////// /// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlTransaction.xml' path='docs/members[@name="SqlTransaction"]/Commit/*' /> override public void Commit() { SqlConnection.ExecutePermission.Demand(); // MDAC 81476 ZombieCheck(); SqlStatistics statistics = null; using (TryEventScope.Create("<sc.SqlTransaction.Commit|API> {0}", ObjectID)) { SqlClientEventSource.Log.TryCorrelationTraceEvent("<sc.SqlTransaction.Commit|API|Correlation> ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); try { #if DEBUG TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); try { tdsReliabilitySection.Start(); #else { #endif //DEBUG bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_connection); statistics = SqlStatistics.StartTimer(Statistics); _isFromAPI = true; _internalTransaction.Commit(); } #if DEBUG finally { tdsReliabilitySection.Stop(); } #endif //DEBUG } catch (System.OutOfMemoryException e) { _connection.Abort(e); throw; } catch (System.StackOverflowException e) { _connection.Abort(e); throw; } catch (System.Threading.ThreadAbortException e) { _connection.Abort(e); SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget); throw; } catch (SqlException e) { // GitHub Issue #130 - When a timeout exception has occurred on transaction completion request, // this connection may not be in reusable state. // We will abort this connection and make sure it does not go back to the pool. var innerException = e.InnerException as Win32Exception; if (innerException != null && innerException.NativeErrorCode == TdsEnums.SNI_WAIT_TIMEOUT) { _connection.Abort(e); } throw; } finally { _isFromAPI = false; SqlStatistics.StopTimer(statistics); } } }
public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, IsolatedStorageFile isf) { if (path == null) { throw new ArgumentNullException("path"); } if ((path.Length == 0) || path.Equals(@"\")) { throw new ArgumentException(Environment.GetResourceString("IsolatedStorage_Path")); } ulong num = 0L; bool flag = false; bool locked = false; if (isf == null) { this.m_OwnedStore = true; isf = IsolatedStorageFile.GetUserStoreForDomain(); } if (isf.Disposed) { throw new ObjectDisposedException(null, Environment.GetResourceString("IsolatedStorage_StoreNotOpen")); } this.m_isf = isf; FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.AllAccess, this.m_isf.RootDirectory); permission.Assert(); permission.PermitOnly(); this.m_GivenPath = path; this.m_FullPath = this.m_isf.GetFullPath(this.m_GivenPath); RuntimeHelpers.PrepareConstrainedRegions(); try { switch (mode) { case FileMode.CreateNew: flag = true; break; case FileMode.Create: case FileMode.OpenOrCreate: case FileMode.Truncate: case FileMode.Append: this.m_isf.Lock(ref locked); try { num = IsolatedStorageFile.RoundToBlockSize((ulong)LongPathFile.GetLength(this.m_FullPath)); } catch (FileNotFoundException) { flag = true; } catch { } break; case FileMode.Open: break; default: throw new ArgumentException(Environment.GetResourceString("IsolatedStorage_FileOpenMode")); } if (flag) { this.m_isf.ReserveOneBlock(); } try { this.m_fs = new FileStream(this.m_FullPath, mode, access, share, bufferSize, FileOptions.None, this.m_GivenPath, true, true); } catch { if (flag) { this.m_isf.UnreserveOneBlock(); } throw; } if (!flag && ((mode == FileMode.Truncate) || (mode == FileMode.Create))) { ulong num2 = IsolatedStorageFile.RoundToBlockSize((ulong)this.m_fs.Length); if (num > num2) { this.m_isf.Unreserve(num - num2); } else if (num2 > num) { this.m_isf.Reserve(num2 - num); } } } finally { if (locked) { this.m_isf.Unlock(); } } CodeAccessPermission.RevertAll(); }
private void WriteRowSourceToServer(int columnCount) { this.CreateOrValidateConnection("WriteToServer"); bool flag = false; RuntimeHelpers.PrepareConstrainedRegions(); SNIHandle target = null; try { target = SqlInternalConnection.GetBestEffortCleanupTarget(this._connection); this._columnMappings.ReadOnly = true; this._localColumnMappings = this._columnMappings; if (this._localColumnMappings.Count > 0) { this._localColumnMappings.ValidateCollection(); foreach (SqlBulkCopyColumnMapping mapping2 in this._localColumnMappings) { if (mapping2._internalSourceColumnOrdinal == -1) { flag = true; break; } } } else { this._localColumnMappings = new SqlBulkCopyColumnMappingCollection(); this._localColumnMappings.CreateDefaultMapping(columnCount); } if (flag) { int ordinal = -1; flag = false; if (this._localColumnMappings.Count > 0) { foreach (SqlBulkCopyColumnMapping mapping in this._localColumnMappings) { if (mapping._internalSourceColumnOrdinal != -1) { continue; } string name = this.UnquotedName(mapping.SourceColumn); switch (this._rowSourceType) { case ValueSourceType.IDataReader: try { ordinal = ((IDataRecord)this._rowSource).GetOrdinal(name); } catch (IndexOutOfRangeException exception4) { throw SQL.BulkLoadNonMatchingColumnName(name, exception4); } break; case ValueSourceType.DataTable: ordinal = ((DataTable)this._rowSource).Columns.IndexOf(name); break; case ValueSourceType.RowArray: ordinal = ((DataRow[])this._rowSource)[0].Table.Columns.IndexOf(name); break; } if (ordinal == -1) { throw SQL.BulkLoadNonMatchingColumnName(name); } mapping._internalSourceColumnOrdinal = ordinal; } } } this.WriteToServerInternal(); } catch (OutOfMemoryException exception3) { this._connection.Abort(exception3); throw; } catch (StackOverflowException exception2) { this._connection.Abort(exception2); throw; } catch (ThreadAbortException exception) { this._connection.Abort(exception); SqlInternalConnection.BestEffortCleanup(target); throw; } finally { this._columnMappings.ReadOnly = false; } }
private OdbcDataReader ExecuteReaderObject(CommandBehavior behavior, string method, bool needReader, object[] methodArguments, ODBC32.SQL_API odbcApiMethod) { // MDAC 68324 OdbcDataReader localReader = null; try { DisposeDeadDataReader(); // this is a no-op if cmdState is not Fetching ValidateConnectionAndTransaction(method); // cmdState will change to Executing if (0 != (CommandBehavior.SingleRow & behavior)) { // CommandBehavior.SingleRow implies CommandBehavior.SingleResult behavior |= CommandBehavior.SingleResult; } ODBC32.RetCode retcode; OdbcStatementHandle stmt = GetStatementHandle().StatementHandle; _cmdWrapper.Canceling = false; if (null != _weakDataReaderReference) { if (_weakDataReaderReference.IsAlive) { object target = _weakDataReaderReference.Target; if (null != target && _weakDataReaderReference.IsAlive) { if (!((OdbcDataReader)target).IsClosed) { throw ADP.OpenReaderExists(); // MDAC 66411 } } } } localReader = new OdbcDataReader(this, _cmdWrapper, behavior); //Set command properties //Not all drivers support timeout. So fail silently if error if (!Connection.ProviderInfo.NoQueryTimeout) { TrySetStatementAttribute(stmt, ODBC32.SQL_ATTR.QUERY_TIMEOUT, (IntPtr)this.CommandTimeout); } // todo: If we remember the state we can omit a lot of SQLSetStmtAttrW calls ... // if we do not create a reader we do not even need to do that if (needReader) { if (Connection.IsV3Driver) { if (!Connection.ProviderInfo.NoSqlSoptSSNoBrowseTable && !Connection.ProviderInfo.NoSqlSoptSSHiddenColumns) { // Need to get the metadata information //SQLServer actually requires browse info turned on ahead of time... //Note: We ignore any failures, since this is SQLServer specific //We won't specialcase for SQL Server but at least for non-V3 drivers if (localReader.IsBehavior(CommandBehavior.KeyInfo)) { if (!_cmdWrapper._ssKeyInfoModeOn) { TrySetStatementAttribute(stmt, (ODBC32.SQL_ATTR)ODBC32.SQL_SOPT_SS.NOBROWSETABLE, (IntPtr)ODBC32.SQL_NB.ON); TrySetStatementAttribute(stmt, (ODBC32.SQL_ATTR)ODBC32.SQL_SOPT_SS.HIDDEN_COLUMNS, (IntPtr)ODBC32.SQL_HC.ON); _cmdWrapper._ssKeyInfoModeOff = false; _cmdWrapper._ssKeyInfoModeOn = true; } } else { if (!_cmdWrapper._ssKeyInfoModeOff) { TrySetStatementAttribute(stmt, (ODBC32.SQL_ATTR)ODBC32.SQL_SOPT_SS.NOBROWSETABLE, (IntPtr)ODBC32.SQL_NB.OFF); TrySetStatementAttribute(stmt, (ODBC32.SQL_ATTR)ODBC32.SQL_SOPT_SS.HIDDEN_COLUMNS, (IntPtr)ODBC32.SQL_HC.OFF); _cmdWrapper._ssKeyInfoModeOff = true; _cmdWrapper._ssKeyInfoModeOn = false; } } } } } if (localReader.IsBehavior(CommandBehavior.KeyInfo) || localReader.IsBehavior(CommandBehavior.SchemaOnly)) { retcode = stmt.Prepare(CommandText); if (ODBC32.RetCode.SUCCESS != retcode) { _connection.HandleError(stmt, retcode); } } bool mustRelease = false; CNativeBuffer parameterBuffer = _cmdWrapper._nativeParameterBuffer; RuntimeHelpers.PrepareConstrainedRegions(); try { //Handle Parameters //Note: We use the internal variable as to not instante a new object collection, //for the common case of using no parameters. if ((null != _parameterCollection) && (0 < _parameterCollection.Count)) { int parameterBufferSize = _parameterCollection.CalcParameterBufferSize(this); if (null == parameterBuffer || parameterBuffer.Length < parameterBufferSize) { if (null != parameterBuffer) { parameterBuffer.Dispose(); } parameterBuffer = new CNativeBuffer(parameterBufferSize); _cmdWrapper._nativeParameterBuffer = parameterBuffer; } else { parameterBuffer.ZeroMemory(); } parameterBuffer.DangerousAddRef(ref mustRelease); _parameterCollection.Bind(this, _cmdWrapper, parameterBuffer); } if (!localReader.IsBehavior(CommandBehavior.SchemaOnly)) { // Can't get the KeyInfo after command execution (SQL Server only since it does not support multiple // results on the same connection). Stored procedures (SP) do not return metadata before actual execution // Need to check the column count since the command type may not be set to SP for a SP. if ((localReader.IsBehavior(CommandBehavior.KeyInfo) || localReader.IsBehavior(CommandBehavior.SchemaOnly)) && (CommandType != CommandType.StoredProcedure)) { Int16 cColsAffected; retcode = stmt.NumberOfResultColumns(out cColsAffected); if (retcode == ODBC32.RetCode.SUCCESS || retcode == ODBC32.RetCode.SUCCESS_WITH_INFO) { if (cColsAffected > 0) { localReader.GetSchemaTable(); } } else if (retcode == ODBC32.RetCode.NO_DATA) { // do nothing } else { // any other returncode indicates an error _connection.HandleError(stmt, retcode); } } switch (odbcApiMethod) { case ODBC32.SQL_API.SQLEXECDIRECT: if (localReader.IsBehavior(CommandBehavior.KeyInfo) || _isPrepared) { //Already prepared, so use SQLExecute retcode = stmt.Execute(); // Build metadata here // localReader.GetSchemaTable(); } else { #if DEBUG //if (AdapterSwitches.OleDbTrace.TraceInfo) { // ADP.DebugWriteLine("SQLExecDirectW: " + CommandText); //} #endif //SQLExecDirect retcode = stmt.ExecuteDirect(CommandText); } break; case ODBC32.SQL_API.SQLTABLES: retcode = stmt.Tables((string)methodArguments[0], //TableCatalog (string)methodArguments[1], //TableSchema, (string)methodArguments[2], //TableName (string)methodArguments[3]); //TableType break; case ODBC32.SQL_API.SQLCOLUMNS: retcode = stmt.Columns((string)methodArguments[0], //TableCatalog (string)methodArguments[1], //TableSchema (string)methodArguments[2], //TableName (string)methodArguments[3]); //ColumnName break; case ODBC32.SQL_API.SQLPROCEDURES: retcode = stmt.Procedures((string)methodArguments[0], //ProcedureCatalog (string)methodArguments[1], //ProcedureSchema (string)methodArguments[2]); //procedureName break; case ODBC32.SQL_API.SQLPROCEDURECOLUMNS: retcode = stmt.ProcedureColumns((string)methodArguments[0], //ProcedureCatalog (string)methodArguments[1], //ProcedureSchema (string)methodArguments[2], //procedureName (string)methodArguments[3]); //columnName break; case ODBC32.SQL_API.SQLSTATISTICS: retcode = stmt.Statistics((string)methodArguments[0], //TableCatalog (string)methodArguments[1], //TableSchema (string)methodArguments[2], //TableName (Int16)methodArguments[3], //IndexTrpe (Int16)methodArguments[4]); //Accuracy break; case ODBC32.SQL_API.SQLGETTYPEINFO: retcode = stmt.GetTypeInfo((Int16)methodArguments[0]); //SQL Type break; default: // this should NEVER happen Debug.Assert(false, "ExecuteReaderObjectcalled with unsupported ODBC API method."); throw ADP.InvalidOperation(method.ToString()); } //Note: Execute will return NO_DATA for Update/Delete non-row returning queries if ((ODBC32.RetCode.SUCCESS != retcode) && (ODBC32.RetCode.NO_DATA != retcode)) { _connection.HandleError(stmt, retcode); } } // end SchemaOnly } finally { if (mustRelease) { parameterBuffer.DangerousRelease(); } } _weakDataReaderReference = new WeakReference(localReader); // XXXCommand.Execute should position reader on first row returning result // any exceptions in the initial non-row returning results should be thrown // from from ExecuteXXX not the DataReader if (!localReader.IsBehavior(CommandBehavior.SchemaOnly)) { localReader.FirstResult(); } _cmdState = ConnectionState.Fetching; } finally { if (ConnectionState.Fetching != _cmdState) { if (null != localReader) { // clear bindings so we don't grab output parameters on a failed execute if (null != _parameterCollection) { _parameterCollection.ClearBindings(); } ((IDisposable)localReader).Dispose(); } if (ConnectionState.Closed != _cmdState) { _cmdState = ConnectionState.Closed; } } } return(localReader); }
private void WriteToServerInternal() { string tDSCommand = null; bool flag3 = false; bool flag2 = false; int[] useSqlValue = null; int num5 = this._batchSize; bool flag4 = false; if (this._batchSize > 0) { flag4 = true; } Exception inner = null; this._rowsCopied = 0; if (this._destinationTableName == null) { throw SQL.BulkLoadMissingDestinationTable(); } if (this.ReadFromRowSource()) { RuntimeHelpers.PrepareConstrainedRegions(); try { bool flag = true; this._parser = this._connection.Parser; this._stateObj = this._parser.GetSession(this); this._stateObj._bulkCopyOpperationInProgress = true; try { BulkCopySimpleResultSet set; this._stateObj.StartSession(this.ObjectID); try { set = this.CreateAndExecuteInitialQuery(); } catch (SqlException exception5) { throw SQL.BulkLoadInvalidDestinationTable(this._destinationTableName, exception5); } this._rowsUntilNotification = this._notifyAfter; tDSCommand = this.AnalyzeTargetAndCreateUpdateBulkCommand(set); if (this._sortedColumnMappings.Count == 0) { return; } this._stateObj.SniContext = SniContext.Snix_SendRows; Label_00DD: if (this.IsCopyOption(SqlBulkCopyOptions.UseInternalTransaction)) { this._internalTransaction = this._connection.BeginTransaction(); } this.SubmitUpdateBulkCommand(set, tDSCommand); try { this.WriteMetaData(set); object[] objArray = new object[this._sortedColumnMappings.Count]; if (useSqlValue == null) { useSqlValue = new int[objArray.Length]; } int num3 = num5; do { for (int i = 0; i < objArray.Length; i++) { _ColumnMapping mapping = (_ColumnMapping)this._sortedColumnMappings[i]; _SqlMetaData metadata = mapping._metadata; object obj2 = this.GetValueFromSourceRow(mapping._sourceColumnOrdinal, metadata, useSqlValue, i); objArray[i] = this.ConvertValue(obj2, metadata); } this._parser.WriteByte(0xd1, this._stateObj); for (int j = 0; j < objArray.Length; j++) { _ColumnMapping mapping2 = (_ColumnMapping)this._sortedColumnMappings[j]; _SqlMetaData data = mapping2._metadata; if (data.type != SqlDbType.Variant) { this._parser.WriteBulkCopyValue(objArray[j], data, this._stateObj); } else { this._parser.WriteSqlVariantDataRowValue(objArray[j], this._stateObj); } } this._rowsCopied++; if (((this._notifyAfter > 0) && (this._rowsUntilNotification > 0)) && (--this._rowsUntilNotification == 0)) { try { this._stateObj.BcpLock = true; flag2 = this.FireRowsCopiedEvent((long)this._rowsCopied); Bid.Trace("<sc.SqlBulkCopy.WriteToServerInternal|INFO> \n"); if (ConnectionState.Open != this._connection.State) { goto Label_02F7; } } catch (Exception exception2) { if (!ADP.IsCatchableExceptionType(exception2)) { throw; } inner = OperationAbortedException.Aborted(exception2); goto Label_02F7; } finally { this._stateObj.BcpLock = false; } if (flag2) { goto Label_02F7; } this._rowsUntilNotification = this._notifyAfter; } if (this._rowsUntilNotification > this._notifyAfter) { this._rowsUntilNotification = this._notifyAfter; } flag3 = this.ReadFromRowSource(); if (flag4) { num3--; if (num3 == 0) { goto Label_02F7; } } }while (flag3); } catch (NullReferenceException) { this._stateObj.CancelRequest(); throw; } catch (Exception exception4) { if (ADP.IsCatchableExceptionType(exception4)) { this._stateObj.CancelRequest(); } throw; } Label_02F7: if (ConnectionState.Open != this._connection.State) { throw ADP.OpenConnectionRequired("WriteToServer", this._connection.State); } this._parser.WriteBulkCopyDone(this._stateObj); this._parser.Run(RunBehavior.UntilDone, null, null, null, this._stateObj); if (flag2 || (inner != null)) { throw OperationAbortedException.Aborted(inner); } if (this._internalTransaction != null) { this._internalTransaction.Commit(); this._internalTransaction = null; } if (flag3) { goto Label_00DD; } this._localColumnMappings = null; } catch (Exception exception3) { flag = ADP.IsCatchableExceptionType(exception3); if (flag) { this._stateObj._internalTimeout = false; if (this._internalTransaction != null) { if (!this._internalTransaction.IsZombied) { this._internalTransaction.Rollback(); } this._internalTransaction = null; } } throw; } finally { if (flag && (this._stateObj != null)) { this._stateObj.CloseSession(); } } } finally { if (this._stateObj != null) { this._stateObj._bulkCopyOpperationInProgress = false; this._stateObj = null; } } } }
static int CreateMutexHandle(bool initiallyOwned, String name, Win32Native.SECURITY_ATTRIBUTES securityAttribute, out SafeWaitHandle mutexHandle) { int errorCode; bool fAffinity = false; while (true) { mutexHandle = Win32Native.CreateMutex(securityAttribute, initiallyOwned, name); errorCode = Marshal.GetLastWin32Error(); if (!mutexHandle.IsInvalid) { break; } if (errorCode == Win32Native.ERROR_ACCESS_DENIED) { // If a mutex with the name already exists, OS will try to open it with FullAccess. // It might fail if we don't have enough access. In that case, we try to open the mutex will modify and synchronize access. // RuntimeHelpers.PrepareConstrainedRegions(); try { try { } finally { #if !FEATURE_CORECLR Thread.BeginThreadAffinity(); #endif fAffinity = true; } mutexHandle = Win32Native.OpenMutex(Win32Native.MUTEX_MODIFY_STATE | Win32Native.SYNCHRONIZE, false, name); if (!mutexHandle.IsInvalid) { errorCode = Win32Native.ERROR_ALREADY_EXISTS; } else { errorCode = Marshal.GetLastWin32Error(); } } finally { if (fAffinity) { #if !FEATURE_CORECLR Thread.EndThreadAffinity(); #endif } } // There could be a race condition here, the other owner of the mutex can free the mutex, // We need to retry creation in that case. if (errorCode != Win32Native.ERROR_FILE_NOT_FOUND) { if (errorCode == Win32Native.ERROR_SUCCESS) { errorCode = Win32Native.ERROR_ALREADY_EXISTS; } break; } } else { break; } } return(errorCode); }
internal static void CreateLocalDBInstance(string instance) { DemandLocalDBPermissions(); if (s_configurableInstances == null) { // load list of instances from configuration, mark them as not created bool lockTaken = false; RuntimeHelpers.PrepareConstrainedRegions(); try { Monitor.Enter(s_configLock, ref lockTaken); if (s_configurableInstances == null) { Dictionary <string, InstanceInfo> tempConfigurableInstances = new Dictionary <string, InstanceInfo>(StringComparer.OrdinalIgnoreCase); object section = PrivilegedConfigurationManager.GetSection("system.data.localdb"); if (section != null) // if no section just skip creation { // validate section type LocalDBConfigurationSection configSection = section as LocalDBConfigurationSection; if (configSection == null) { throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_BadConfigSectionType")); } foreach (LocalDBInstanceElement confElement in configSection.LocalDbInstances) { Debug.Assert(confElement.Name != null && confElement.Version != null, "Both name and version should not be null"); tempConfigurableInstances.Add(confElement.Name.Trim(), new InstanceInfo(confElement.Version.Trim())); } } else { Bid.Trace("<sc.LocalDBAPI.CreateLocalDBInstance> No system.data.localdb section found in configuration"); } s_configurableInstances = tempConfigurableInstances; } } finally { if (lockTaken) { Monitor.Exit(s_configLock); } } } InstanceInfo instanceInfo = null; if (!s_configurableInstances.TryGetValue(instance, out instanceInfo)) { return; // instance name was not in the config } if (instanceInfo.created) { return; // instance has already been created } Debug.Assert(!instance.Contains("\0"), "Instance name should contain embedded nulls"); if (instanceInfo.version.Contains("\0")) { throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_InvalidVersion"), instance: instance); } // LocalDBCreateInstance is thread- and cross-process safe method, it is OK to call from two threads simultaneously int hr = LocalDBCreateInstance(instanceInfo.version, instance, flags: 0); Bid.Trace("<sc.LocalDBAPI.CreateLocalDBInstance> Starting creation of instance %ls version %ls", instance, instanceInfo.version); if (hr < 0) { throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_CreateFailed"), instance: instance, localDbError: hr); } Bid.Trace("<sc.LocalDBAPI.CreateLocalDBInstance> Finished creation of instance %ls", instance); instanceInfo.created = true; // mark instance as created } // CreateLocalDbInstance
protected OdbcHandle(ODBC32.SQL_HANDLE handleType, OdbcHandle parentHandle) : base(IntPtr.Zero, true) { _handleType = handleType; bool mustRelease = false; ODBC32.RetCode retcode = ODBC32.RetCode.SUCCESS; // using ConstrainedRegions to make the native ODBC call and AddRef the parent RuntimeHelpers.PrepareConstrainedRegions(); try { // validate handleType switch (handleType) { case ODBC32.SQL_HANDLE.ENV: Debug.Assert(null == parentHandle, "did not expect a parent handle"); retcode = UnsafeNativeMethods.SQLAllocHandle(handleType, IntPtr.Zero, out base.handle); break; case ODBC32.SQL_HANDLE.DBC: case ODBC32.SQL_HANDLE.STMT: // must addref before calling native so it won't be released just after Debug.Assert(null != parentHandle, "expected a parent handle"); // safehandle can't be null parentHandle.DangerousAddRef(ref mustRelease); retcode = UnsafeNativeMethods.SQLAllocHandle(handleType, parentHandle, out base.handle); break; // case ODBC32.SQL_HANDLE.DESC: default: Debug.Assert(false, "unexpected handleType"); break; } } finally { if (mustRelease) { switch (handleType) { case ODBC32.SQL_HANDLE.DBC: case ODBC32.SQL_HANDLE.STMT: if (IntPtr.Zero != base.handle) { // must assign _parentHandle after a handle is actually created // since ReleaseHandle will only call DangerousRelease if a handle exists _parentHandle = parentHandle; } else { // without a handle, ReleaseHandle may not be called parentHandle.DangerousRelease(); } break; } } } Bid.TraceSqlReturn("<odbc.SQLAllocHandle|API|ODBC|RET> %08X{SQLRETURN}\n", retcode); if ((ADP.PtrZero == base.handle) || (ODBC32.RetCode.SUCCESS != retcode)) { // throw ODBC.CantAllocateEnvironmentHandle(retcode); } }
internal void SetPropertySet(int index, Guid propertySet, ItagDBPROP[] properties) { if ((index < 0) || (PropertySetCount <= index)) { if (lastErrorFromProvider != null) { // add extra error information for CSS/stress troubleshooting. // We need to keep same exception type to avoid breaking change with Orcas RTM/SP1. throw ADP.InternalError(ADP.InternalErrorCode.InvalidBuffer, lastErrorFromProvider); } else { throw ADP.InternalError(ADP.InternalErrorCode.InvalidBuffer); } } Debug.Assert(Guid.Empty != propertySet, "invalid propertySet"); Debug.Assert((null != properties) && (0 < properties.Length), "invalid properties"); IntPtr countOfBytes = (IntPtr)(properties.Length * ODB.SizeOf_tagDBPROP); tagDBPROPSET propset = new tagDBPROPSET(properties.Length, propertySet); bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); IntPtr propsetPtr = ADP.IntPtrOffset(DangerousGetHandle(), index * ODB.SizeOf_tagDBPROPSET); RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { // must allocate and clear the memory without interruption propset.rgProperties = SafeNativeMethods.CoTaskMemAlloc(countOfBytes); if (ADP.PtrZero != propset.rgProperties) { // clearing is important so that we don't treat existing // garbage as important information during releaseHandle SafeNativeMethods.ZeroMemory(propset.rgProperties, (int)countOfBytes); // writing the structure to native memory so that it knows to free the referenced pointers Marshal.StructureToPtr(propset, propsetPtr, false /*deleteold*/); } } if (ADP.PtrZero == propset.rgProperties) { throw new OutOfMemoryException(); } for (int i = 0; i < properties.Length; ++i) { Debug.Assert(null != properties[i], $"null tagDBPROP {i.ToString(CultureInfo.InvariantCulture)}"); IntPtr propertyPtr = ADP.IntPtrOffset(propset.rgProperties, i * ODB.SizeOf_tagDBPROP); Marshal.StructureToPtr(properties[i], propertyPtr, false /*deleteold*/); } } finally { if (mustRelease) { DangerousRelease(); } } }
public byte[] EncryptMessage(byte[] plainTextBytes) { byte[] outBytes; bool contextAddRefSuccess = false; SecurityPackageContextSizes sizes; #if NET452 RuntimeHelpers.PrepareConstrainedRegions(); #endif try { DangerousAddRef(ref contextAddRefSuccess); } catch (Exception ex) { if (contextAddRefSuccess) { DangerousRelease(); contextAddRefSuccess = false; } if (!(ex is ObjectDisposedException)) { throw; } } finally { uint result = NativeMethods.QueryContextAttributes( ref _sspiHandle, QueryContextAttributes.Sizes, out sizes); DangerousRelease(); if (result != NativeMethods.SEC_E_OK) { throw NativeMethods.CreateException(result, "Unable to get the query context attribute sizes."); } } var buffers = new SecurityBuffer[] { new SecurityBuffer(new byte[sizes.SecurityTrailer], SecurityBufferType.Token), new SecurityBuffer(plainTextBytes, SecurityBufferType.Data), new SecurityBuffer(new byte[sizes.BlockSize], SecurityBufferType.Padding) }; var descriptor = new SecurityBufferDescriptor(buffers); #if NET452 RuntimeHelpers.PrepareConstrainedRegions(); #endif try { DangerousAddRef(ref contextAddRefSuccess); } catch (Exception ex) { if (contextAddRefSuccess) { DangerousRelease(); contextAddRefSuccess = false; } if (!(ex is ObjectDisposedException)) { throw; } } finally { try { uint result = NativeMethods.EncryptMessage( ref _sspiHandle, EncryptQualityOfProtection.WrapNoEncrypt, ref descriptor, 0); DangerousRelease(); if (result != NativeMethods.SEC_E_OK) { throw NativeMethods.CreateException(result, "Unable to encrypt message."); } outBytes = descriptor.ToByteArray(); } finally { descriptor.Free(); } } return(outBytes); }
internal OleDbHResult InitializeAndCreateSession(OleDbConnectionString constr, ref SessionWrapper sessionWrapper) { OleDbHResult hr; bool mustRelease = false; IntPtr idbCreateSession = IntPtr.Zero; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); // native COM rules are the QI result is the 'this' pointer // the pointer stored at that location is the vtable // since IUnknown is a public,shipped COM interface, its layout will not change (ever) IntPtr vtable = Marshal.ReadIntPtr(base.handle, 0); IntPtr method = Marshal.ReadIntPtr(vtable, 0); // we cache the QueryInterface delegate to prevent recreating it on every call UnsafeNativeMethods.IUnknownQueryInterface QueryInterface = constr.DangerousDataSourceIUnknownQueryInterface; // since the delegate lifetime is longer than the original instance used to create it // we double check before each usage to verify the delegates function pointer if ((null == QueryInterface) || (method != Marshal.GetFunctionPointerForDelegate(QueryInterface))) { QueryInterface = (UnsafeNativeMethods.IUnknownQueryInterface)Marshal.GetDelegateForFunctionPointer(method, typeof(UnsafeNativeMethods.IUnknownQueryInterface)); constr.DangerousDataSourceIUnknownQueryInterface = QueryInterface; } // native COM rules are the QI result is the 'this' pointer // the pointer stored at that location is the vtable // since IDBInitialize is a public,shipped COM interface, its layout will not change (ever) vtable = Marshal.ReadIntPtr(base.handle, 0); method = Marshal.ReadIntPtr(vtable, 3 * IntPtr.Size); // Initialize is the 4'th vtable entry // we cache the Initialize delegate to prevent recreating it on every call UnsafeNativeMethods.IDBInitializeInitialize Initialize = constr.DangerousIDBInitializeInitialize; // since the delegate lifetime is longer than the original instance used to create it // we double check before each usage to verify the delegates function pointer if ((null == Initialize) || (method != Marshal.GetFunctionPointerForDelegate(Initialize))) { Initialize = (UnsafeNativeMethods.IDBInitializeInitialize)Marshal.GetDelegateForFunctionPointer(method, typeof(UnsafeNativeMethods.IDBInitializeInitialize)); constr.DangerousIDBInitializeInitialize = Initialize; } // call IDBInitialize::Initialize via the delegate hr = Initialize(base.handle); // we don't ever expect DB_E_ALREADYINITIALIZED, but since we checked in V1.0 - its propagated along if ((0 <= hr) || (OleDbHResult.DB_E_ALREADYINITIALIZED == hr)) { // call IUnknown::QueryInterface via the delegate hr = (OleDbHResult)QueryInterface(base.handle, ref ODB.IID_IDBCreateSession, ref idbCreateSession); if ((0 <= hr) && (IntPtr.Zero != idbCreateSession)) { // native COM rules are the QI result is the 'this' pointer // the pointer stored at that location is the vtable // since IDBCreateSession is a public,shipped COM interface, its layout will not change (ever) vtable = Marshal.ReadIntPtr(idbCreateSession, 0); method = Marshal.ReadIntPtr(vtable, 3 * IntPtr.Size); // CreateSession is the 4'th vtable entry UnsafeNativeMethods.IDBCreateSessionCreateSession CreateSession = constr.DangerousIDBCreateSessionCreateSession; // since the delegate lifetime is longer than the original instance used to create it // we double check before each usage to verify the delegates function pointer if ((null == CreateSession) || (method != Marshal.GetFunctionPointerForDelegate(CreateSession))) { CreateSession = (UnsafeNativeMethods.IDBCreateSessionCreateSession)Marshal.GetDelegateForFunctionPointer(method, typeof(UnsafeNativeMethods.IDBCreateSessionCreateSession)); constr.DangerousIDBCreateSessionCreateSession = CreateSession; } // if I have a delegate for CreateCommand directly ask for IDBCreateCommand if (null != constr.DangerousIDBCreateCommandCreateCommand) { // call IDBCreateSession::CreateSession via the delegate directly for IDBCreateCommand hr = CreateSession(idbCreateSession, IntPtr.Zero, ref ODB.IID_IDBCreateCommand, ref sessionWrapper); if ((0 <= hr) && !sessionWrapper.IsInvalid) { // double check the cached delegate is correct sessionWrapper.VerifyIDBCreateCommand(constr); } } else { // otherwise ask for IUnknown (it may be first time usage or IDBCreateCommand not supported) hr = CreateSession(idbCreateSession, IntPtr.Zero, ref ODB.IID_IUnknown, ref sessionWrapper); if ((0 <= hr) && !sessionWrapper.IsInvalid) { // and check support for IDBCreateCommand and create delegate for CreateCommand sessionWrapper.QueryInterfaceIDBCreateCommand(constr); } } } } } finally { if (IntPtr.Zero != idbCreateSession) { // release the QI for IDBCreateSession Marshal.Release(idbCreateSession); } if (mustRelease) { // release the AddRef on DataLinks DangerousRelease(); } } return(hr); }
// public methods public byte[] DecryptMessage(int messageLength, byte[] encryptedBytes) { byte[] decryptedBytes; byte[] encryptedMessage = new byte[messageLength]; Array.Copy(encryptedBytes, 0, encryptedMessage, 0, messageLength); int securityTrailerLength = encryptedBytes.Length - messageLength; byte[] securityTrailer = new byte[securityTrailerLength]; Array.Copy(encryptedBytes, messageLength, securityTrailer, 0, securityTrailerLength); var buffers = new SecurityBuffer[] { new SecurityBuffer(encryptedBytes, SecurityBufferType.Data), new SecurityBuffer(securityTrailer, SecurityBufferType.Stream) }; var descriptor = new SecurityBufferDescriptor(buffers); bool contextAddRefSuccess = false; #if NET452 RuntimeHelpers.PrepareConstrainedRegions(); #endif try { DangerousAddRef(ref contextAddRefSuccess); } catch (Exception ex) { if (contextAddRefSuccess) { DangerousRelease(); contextAddRefSuccess = false; } if (!(ex is ObjectDisposedException)) { throw; } } finally { try { uint quality; var result = NativeMethods.DecryptMessage( ref _sspiHandle, ref descriptor, 0, out quality); if (result != NativeMethods.SEC_E_OK) { throw NativeMethods.CreateException(result, "Unable to decrypt message."); } decryptedBytes = descriptor.ToByteArray(); } finally { descriptor.Free(); } } return(decryptedBytes); }
public static byte[] CreateSelfSignCertificatePfx( string x500, DateTime startTime, DateTime endTime, SecureString password) { byte[] pfxData; if (x500 == null) { x500 = ""; } SystemTime startSystemTime = ToSystemTime(startTime); SystemTime endSystemTime = ToSystemTime(endTime); string containerName = Guid.NewGuid().ToString(); GCHandle dataHandle = new GCHandle(); IntPtr providerContext = IntPtr.Zero; IntPtr cryptKey = IntPtr.Zero; IntPtr certContext = IntPtr.Zero; IntPtr certStore = IntPtr.Zero; IntPtr storeCertContext = IntPtr.Zero; IntPtr passwordPtr = IntPtr.Zero; RuntimeHelpers.PrepareConstrainedRegions(); try { Check(NativeMethods.CryptAcquireContextW( out providerContext, containerName, null, 1, // PROV_RSA_FULL 8)); // CRYPT_NEWKEYSET Check(NativeMethods.CryptGenKey( providerContext, 1, // AT_KEYEXCHANGE 1, // CRYPT_EXPORTABLE out cryptKey)); IntPtr errorStringPtr; int nameDataLength = 0; byte[] nameData; // errorStringPtr gets a pointer into the middle of the x500 string, // so x500 needs to be pinned until after we've copied the value // of errorStringPtr. dataHandle = GCHandle.Alloc(x500, GCHandleType.Pinned); if (!NativeMethods.CertStrToNameW( 0x00010001, // X509_ASN_ENCODING | PKCS_7_ASN_ENCODING dataHandle.AddrOfPinnedObject(), 3, // CERT_X500_NAME_STR = 3 IntPtr.Zero, null, ref nameDataLength, out errorStringPtr)) { string error = Marshal.PtrToStringUni(errorStringPtr); throw new ArgumentException(error); } nameData = new byte[nameDataLength]; if (!NativeMethods.CertStrToNameW( 0x00010001, // X509_ASN_ENCODING | PKCS_7_ASN_ENCODING dataHandle.AddrOfPinnedObject(), 3, // CERT_X500_NAME_STR = 3 IntPtr.Zero, nameData, ref nameDataLength, out errorStringPtr)) { string error = Marshal.PtrToStringUni(errorStringPtr); throw new ArgumentException(error); } dataHandle.Free(); dataHandle = GCHandle.Alloc(nameData, GCHandleType.Pinned); CryptoApiBlob nameBlob = new CryptoApiBlob( nameData.Length, dataHandle.AddrOfPinnedObject()); CryptKeyProviderInformation kpi = new CryptKeyProviderInformation(); kpi.ContainerName = containerName; kpi.ProviderType = 1; // PROV_RSA_FULL kpi.KeySpec = 1; // AT_KEYEXCHANGE certContext = NativeMethods.CertCreateSelfSignCertificate( providerContext, ref nameBlob, 0, ref kpi, IntPtr.Zero, // default = SHA1RSA ref startSystemTime, ref endSystemTime, IntPtr.Zero); Check(certContext != IntPtr.Zero); dataHandle.Free(); certStore = NativeMethods.CertOpenStore( "Memory", // sz_CERT_STORE_PROV_MEMORY 0, IntPtr.Zero, 0x2000, // CERT_STORE_CREATE_NEW_FLAG IntPtr.Zero); Check(certStore != IntPtr.Zero); Check(NativeMethods.CertAddCertificateContextToStore( certStore, certContext, 1, // CERT_STORE_ADD_NEW out storeCertContext)); NativeMethods.CertSetCertificateContextProperty( storeCertContext, 2, // CERT_KEY_PROV_INFO_PROP_ID 0, ref kpi); if (password != null) { passwordPtr = Marshal.SecureStringToCoTaskMemUnicode(password); } CryptoApiBlob pfxBlob = new CryptoApiBlob(); Check(NativeMethods.PFXExportCertStoreEx( certStore, ref pfxBlob, passwordPtr, IntPtr.Zero, 7)); // EXPORT_PRIVATE_KEYS | REPORT_NO_PRIVATE_KEY | REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY pfxData = new byte[pfxBlob.DataLength]; dataHandle = GCHandle.Alloc(pfxData, GCHandleType.Pinned); pfxBlob.Data = dataHandle.AddrOfPinnedObject(); Check(NativeMethods.PFXExportCertStoreEx( certStore, ref pfxBlob, passwordPtr, IntPtr.Zero, 7)); // EXPORT_PRIVATE_KEYS | REPORT_NO_PRIVATE_KEY | REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY dataHandle.Free(); } finally { if (passwordPtr != IntPtr.Zero) { Marshal.ZeroFreeCoTaskMemUnicode(passwordPtr); } if (dataHandle.IsAllocated) { dataHandle.Free(); } if (certContext != IntPtr.Zero) { NativeMethods.CertFreeCertificateContext(certContext); } if (storeCertContext != IntPtr.Zero) { NativeMethods.CertFreeCertificateContext(storeCertContext); } if (certStore != IntPtr.Zero) { NativeMethods.CertCloseStore(certStore, 0); } if (cryptKey != IntPtr.Zero) { NativeMethods.CryptDestroyKey(cryptKey); } if (providerContext != IntPtr.Zero) { NativeMethods.CryptReleaseContext(providerContext, 0); NativeMethods.CryptAcquireContextW( out providerContext, containerName, null, 1, // PROV_RSA_FULL 0x10); // CRYPT_DELETEKEYSET } } return(pfxData); }
internal OletxCommittableTransaction CreateTransaction( TransactionOptions properties ) { OletxCommittableTransaction tx = null; RealOletxTransaction realTransaction = null; ITransactionShim transactionShim = null; Guid txIdentifier = Guid.Empty; OutcomeEnlistment outcomeEnlistment = null; // Demand the distributed transation permission to create one of // these. DistributedTransactionPermission txPerm = new DistributedTransactionPermission(PermissionState.Unrestricted); txPerm.Demand(); TransactionManager.ValidateIsolationLevel(properties.IsolationLevel); // Never create a transaction with an IsolationLevel of Unspecified. if (IsolationLevel.Unspecified == properties.IsolationLevel) { properties.IsolationLevel = configuredTransactionOptions.IsolationLevel; } properties.Timeout = TransactionManager.ValidateTimeout(properties.Timeout); this.dtcTransactionManagerLock.AcquireReaderLock(-1); try { // OletxTransactionIsolationLevel oletxIsoLevel = OletxTransactionManager.ConvertIsolationLevel(properties.IsolationLevel); UInt32 oletxTimeout = DtcTransactionManager.AdjustTimeout(properties.Timeout); outcomeEnlistment = new OutcomeEnlistment(); IntPtr outcomeEnlistmentHandle = IntPtr.Zero; RuntimeHelpers.PrepareConstrainedRegions(); try { outcomeEnlistmentHandle = HandleTable.AllocHandle(outcomeEnlistment); dtcTransactionManager.ProxyShimFactory.BeginTransaction( oletxTimeout, oletxIsoLevel, outcomeEnlistmentHandle, out txIdentifier, out transactionShim ); } catch (COMException ex) { OletxTransactionManager.ProxyException(ex); throw; } finally { if (transactionShim == null && outcomeEnlistmentHandle != IntPtr.Zero) { HandleTable.FreeHandle(outcomeEnlistmentHandle); } } realTransaction = new RealOletxTransaction( this, transactionShim, outcomeEnlistment, txIdentifier, oletxIsoLevel, true ); tx = new OletxCommittableTransaction(realTransaction); if (DiagnosticTrace.Information) { TransactionCreatedTraceRecord.Trace(SR.GetString(SR.TraceSourceOletx), tx.TransactionTraceId ); } } finally { this.dtcTransactionManagerLock.ReleaseReaderLock(); } return(tx); }
//[ResourceExposure(ResourceScope::None)] // // Notes on SecureString: Writing out security sensitive information to managed buffer should be avoid as these can be moved // around by GC. There are two set of information which falls into this category: passwords and new changed password which // are passed in as SecureString by a user. Writing out clear passwords information is delayed until this layer to ensure that // the information is written out to buffer which is pinned in this method already. This also ensures that processing a clear password // is done right before it is written out to SNI_Packet where gets encrypted properly. // TdsParserStaticMethods.EncryptPassword operation is also done here to minimize the time the clear password is held in memory. Any changes // to loose encryption algorithm is changed it should be done in both in this method as well as TdsParserStaticMethods.EncryptPassword. // Up to current release, it is also guaranteed that both password and new change password will fit into a single login packet whose size is fixed to 4096 // So, there is no splitting logic is needed. internal static void SNIPacketSetData(SNIPacket packet, Byte[] data, Int32 length, SecureString[] passwords, // pointer to the passwords which need to be written out to SNI Packet Int32[] passwordOffsets // Offset into data buffer where the password to be written out to ) { Debug.Assert(passwords == null || (passwordOffsets != null && passwords.Length == passwordOffsets.Length), "The number of passwords does not match the number of password offsets"); bool mustRelease = false; bool mustClearBuffer = false; IntPtr clearPassword = IntPtr.Zero; // provides a guaranteed finally block – without this it isn’t guaranteed – non interruptable by fatal exceptions RuntimeHelpers.PrepareConstrainedRegions(); try { unsafe { fixed(byte *pin_data = &data[0]) { } if (passwords != null) { // Process SecureString for (int i = 0; i < passwords.Length; ++i) { // SecureString is used if (passwords[i] != null) { // provides a guaranteed finally block – without this it isn’t guaranteed – non interruptable by fatal exceptions RuntimeHelpers.PrepareConstrainedRegions(); try { // ========================================================================== // Get the clear text of secure string without converting it to String type // ========================================================================== clearPassword = Marshal.SecureStringToCoTaskMemUnicode(passwords[i]); // ========================================================================================================================== // Losely encrypt the clear text - The encryption algorithm should exactly match the TdsParserStaticMethods.EncryptPassword // ========================================================================================================================== unsafe { char *pwChar = (char *)clearPassword.ToPointer(); byte *pByte = (byte *)(clearPassword.ToPointer()); int s; byte bLo; byte bHi; int passwordsLength = passwords[i].Length; for (int j = 0; j < passwordsLength; ++j) { s = (int)*pwChar; bLo = (byte)(s & 0xff); bHi = (byte)((s >> 8) & 0xff); *(pByte++) = (Byte)((((bLo & 0x0f) << 4) | (bLo >> 4)) ^ 0xa5); *(pByte++) = (Byte)((((bHi & 0x0f) << 4) | (bHi >> 4)) ^ 0xa5); ++pwChar; } // =========================================================== // Write out the losely encrypted passwords to data buffer // =========================================================== mustClearBuffer = true; Marshal.Copy(clearPassword, data, passwordOffsets[i], passwordsLength * 2); } } finally { // Make sure that we clear the security sensitive information if (clearPassword != IntPtr.Zero) { Marshal.ZeroFreeCoTaskMemUnicode(clearPassword); } } } } } packet.DangerousAddRef(ref mustRelease); Debug.Assert(mustRelease, "AddRef Failed!"); fixed(byte *pin_data = &data[0]) { SNIPacketSetData(packet, pin_data, (uint)length); } } } finally { if (mustRelease) { packet.DangerousRelease(); } // Make sure that we clear the security sensitive information // data->Initialize() is not safe to call under CER if (mustClearBuffer) { for (int i = 0; i < data.Length; ++i) { data[i] = 0; } } } }
private bool TryEnterReadLock(int millisecondsTimeout, ref bool success) { var ctstate = CurrentThreadState; if (CheckState(ctstate, millisecondsTimeout, LockState.Read)) { ++ctstate.ReaderRecursiveCount; return(true); } // This is downgrading from upgradable, no need for check since // we already have a sort-of read lock that's going to disappear // after user calls ExitUpgradeableReadLock. // Same idea when recursion is allowed and a write thread wants to // go for a Read too. if (ctstate.LockState.Has(LockState.Upgradable) || (!_noRecursion && ctstate.LockState.Has(LockState.Write))) { RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { Interlocked.Add(ref _rwlock, _rwRead); ctstate.LockState |= LockState.Read; ++ctstate.ReaderRecursiveCount; success = true; } return(true); } _numReadWaiters++; int val; var start = millisecondsTimeout == -1 ? 0 : _stopwatch.ElapsedMilliseconds; do { /* Check if a writer is present (RwWrite) or if there is someone waiting to * acquire a writer lock in the queue (RwWait | RwWaitUpgrade). */ if ((_rwlock & (_rwWrite | _rwWait | _rwWaitUpgrade)) > 0) { _writerDoneEvent.Wait(ComputeTimeout(millisecondsTimeout, start)); continue; } /* Optimistically try to add ourselves to the reader value * if the adding was too late and another writer came in between * we revert the operation. */ RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { if (((val = Interlocked.Add(ref _rwlock, _rwRead)) & (_rwWrite | _rwWait | _rwWaitUpgrade)) == 0) { /* If we are the first reader, reset the event to let other threads * sleep correctly if they try to acquire write lock */ if (val >> _rwReadBit == 1) { _readerDoneEvent.Reset(); } ctstate.LockState ^= LockState.Read; ++ctstate.ReaderRecursiveCount; --_numReadWaiters; success = true; } else { Interlocked.Add(ref _rwlock, -_rwRead); } } if (success) { return(true); } _writerDoneEvent.Wait(ComputeTimeout(millisecondsTimeout, start)); } while (millisecondsTimeout == -1 || (_stopwatch.ElapsedMilliseconds - start) < millisecondsTimeout); --_numReadWaiters; return(false); }
public unsafe override int Read([In][Out] byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (count < 0) { throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (buffer.Length - offset < count) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); } if (!this._isOpen) { __Error.StreamIsClosed(); } if (!this.CanRead) { __Error.ReadNotSupported(); } long num = Interlocked.Read(ref this._position); long num2 = Interlocked.Read(ref this._length); long num3 = num2 - num; if (num3 > (long)count) { num3 = (long)count; } if (num3 <= 0L) { return(0); } int num4 = (int)num3; if (num4 < 0) { num4 = 0; } if (this._buffer != null) { byte *ptr = null; RuntimeHelpers.PrepareConstrainedRegions(); try { this._buffer.AcquirePointer(ref ptr); Buffer.Memcpy(buffer, offset, ptr + num + this._offset, 0, num4); goto IL_10A; } finally { if (ptr != null) { this._buffer.ReleasePointer(); } } } Buffer.Memcpy(buffer, offset, this._mem + num, 0, num4); IL_10A: Interlocked.Exchange(ref this._position, num + num3); return(num4); }