internal static bool EnableTokenPrivilege(string privilegeName, ref Win32Native.TOKEN_PRIVILEGE oldPrivilegeState) { bool flag = false; Win32Native.TOKEN_PRIVILEGE tOKENPRIVILEGE = new Win32Native.TOKEN_PRIVILEGE(); if (Win32Native.LookupPrivilegeValue(null, privilegeName, ref tOKENPRIVILEGE.Privilege.Luid)) { IntPtr currentProcess = Win32Native.GetCurrentProcess(); if (currentProcess != IntPtr.Zero) { IntPtr zero = IntPtr.Zero; if (Win32Native.OpenProcessToken(currentProcess, 40, out zero)) { Win32Native.PRIVILEGE_SET luid = new Win32Native.PRIVILEGE_SET(); luid.Privilege.Luid = tOKENPRIVILEGE.Privilege.Luid; luid.PrivilegeCount = 1; luid.Control = 1; bool flag1 = false; if (!Win32Native.PrivilegeCheck(zero, ref luid, out flag1) || !flag1) { tOKENPRIVILEGE.PrivilegeCount = 1; tOKENPRIVILEGE.Privilege.Attributes = 2; int num = Marshal.SizeOf(typeof(Win32Native.TOKEN_PRIVILEGE)); int num1 = 0; if (Win32Native.AdjustTokenPrivileges(zero, false, ref tOKENPRIVILEGE, num, out oldPrivilegeState, ref num1)) { int lastWin32Error = Marshal.GetLastWin32Error(); if (lastWin32Error != 0) { if (lastWin32Error == 0x514) { oldPrivilegeState.PrivilegeCount = 0; flag = true; } } else { flag = true; } } } else { oldPrivilegeState.PrivilegeCount = 0; flag = true; } } if (zero != IntPtr.Zero) { Win32Native.CloseHandle(zero); } Win32Native.CloseHandle(currentProcess); } } return flag; }
internal static int GetSecurityInfo(ResourceType resourceType, string name, SafeHandle handle, AccessControlSections accessControlSections, out RawSecurityDescriptor resultSd) { resultSd = null; new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); SecurityInfos securityInfos = (SecurityInfos)0; Privilege privilege = null; if ((accessControlSections & AccessControlSections.Owner) != AccessControlSections.None) { securityInfos |= SecurityInfos.Owner; } if ((accessControlSections & AccessControlSections.Group) != AccessControlSections.None) { securityInfos |= SecurityInfos.Group; } if ((accessControlSections & AccessControlSections.Access) != AccessControlSections.None) { securityInfos |= SecurityInfos.DiscretionaryAcl; } if ((accessControlSections & AccessControlSections.Audit) != AccessControlSections.None) { securityInfos |= SecurityInfos.SystemAcl; privilege = new Privilege("SeSecurityPrivilege"); } RuntimeHelpers.PrepareConstrainedRegions(); IntPtr intPtr5; int num; try { if (privilege != null) { try { privilege.Enable(); } catch (PrivilegeNotHeldException) { } } if (name != null) { IntPtr intPtr; IntPtr intPtr2; IntPtr intPtr3; IntPtr intPtr4; num = (int)Win32Native.GetSecurityInfoByName(name, (uint)resourceType, (uint)securityInfos, out intPtr, out intPtr2, out intPtr3, out intPtr4, out intPtr5); } else { if (handle == null) { throw new SystemException(); } if (handle.IsInvalid) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSafeHandle"), "handle"); } IntPtr intPtr; IntPtr intPtr2; IntPtr intPtr3; IntPtr intPtr4; num = (int)Win32Native.GetSecurityInfoByHandle(handle, (uint)resourceType, (uint)securityInfos, out intPtr, out intPtr2, out intPtr3, out intPtr4, out intPtr5); } if (num == 0 && IntPtr.Zero.Equals(intPtr5)) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoSecurityDescriptor")); } if (num == 1300 || num == 1314) { throw new PrivilegeNotHeldException("SeSecurityPrivilege"); } if (num == 5 || num == 1347) { throw new UnauthorizedAccessException(); } if (num != 0) { goto IL_162; } } catch { if (privilege != null) { privilege.Revert(); } throw; } finally { if (privilege != null) { privilege.Revert(); } } uint securityDescriptorLength = Win32Native.GetSecurityDescriptorLength(intPtr5); byte[] array = new byte[securityDescriptorLength]; Marshal.Copy(intPtr5, array, 0, (int)securityDescriptorLength); Win32Native.LocalFree(intPtr5); resultSd = new RawSecurityDescriptor(array, 0); return(0); IL_162: if (num == 8) { throw new OutOfMemoryException(); } return(num); }
override protected bool ReleaseHandle() { return(Win32Native.CloseHandle(handle)); }
internal unsafe int GetFullPathName() { if (useStackAlloc) { char *finalBuffer = stackalloc char[Path.MaxPath + 1];//分配最终缓存数组 int result = Win32Native.GetFullPathName(m_arrayPtr, Path.MaxPath + 1, finalBuffer, IntPtr.Zero); // If success, the return buffer length does not account for the terminating null character. // If in-sufficient buffer, the return buffer length does account for the path + the terminating null character. // If failure, the return buffer length is zero if (result > Path.MaxPath) { char *tempBuffer = stackalloc char[result]; finalBuffer = tempBuffer; result = Win32Native.GetFullPathName(m_arrayPtr, result, finalBuffer, IntPtr.Zero); } // Full path is genuinely long if (result >= Path.MaxPath) { throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong")); } Contract.Assert(result < Path.MaxPath, "did we accidently remove a PathTooLongException check?"); if (result == 0 && m_arrayPtr[0] != '\0') { __Error.WinIOError(); } else if (result < Path.MaxPath) { // Null terminate explicitly (may be only needed for some cases such as empty strings) // GetFullPathName return length doesn't account for null terminating char... finalBuffer[result] = '\0'; // Safe to write directly as result is < Path.MaxPath } // We have expanded the paths and GetLongPathName may or may not behave differently from before. // We need to call it again to see: doNotTryExpandShortFileName = false; String.wstrcpy(m_arrayPtr, finalBuffer, result); // Doesn't account for null terminating char. Think of this as the last // valid index into the buffer but not the length of the buffer Length = result; return(result); } else { StringBuilder finalBuffer = new StringBuilder(m_capacity + 1);//构造StringBuilder int result = Win32Native.GetFullPathName(m_sb.ToString(), m_capacity + 1, finalBuffer, IntPtr.Zero); // If success, the return buffer length does not account for the terminating null character. // If in-sufficient buffer, the return buffer length does account for the path + the terminating null character. // If failure, the return buffer length is zero // 如果成功, if (result > m_maxPath) { finalBuffer.Length = result; result = Win32Native.GetFullPathName(m_sb.ToString(), result, finalBuffer, IntPtr.Zero); } // Fullpath is genuinely long if (result >= m_maxPath) { throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong")); } Contract.Assert(result < m_maxPath, "did we accidentally remove a PathTooLongException check?"); if (result == 0 && m_sb[0] != '\0') { if (Length >= m_maxPath) { throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong")); } __Error.WinIOError(); } // We have expanded the paths and GetLongPathName may or may not behave differently from before. // We need to call it again to see: doNotTryExpandShortFileName = false; m_sb = finalBuffer; return(result); } }
public static String ExpandEnvironmentVariables(String name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } Contract.EndContractBlock(); if (name.Length == 0) { return(name); } if (AppDomain.IsAppXModel() && !AppDomain.IsAppXDesignMode()) { // Environment variable accessors are not approved modern API. // Behave as if no variables are defined in this case. return(name); } int currentSize = 100; StringBuilder blob = new StringBuilder(currentSize); // A somewhat reasonable default size #if PLATFORM_UNIX // Win32Native.ExpandEnvironmentStrings isn't available int lastPos = 0, pos; while (lastPos < name.Length && (pos = name.IndexOf('%', lastPos + 1)) >= 0) { if (name[lastPos] == '%') { string key = name.Substring(lastPos + 1, pos - lastPos - 1); string value = Environment.GetEnvironmentVariable(key); if (value != null) { blob.Append(value); lastPos = pos + 1; continue; } } blob.Append(name.Substring(lastPos, pos - lastPos)); lastPos = pos; } blob.Append(name.Substring(lastPos)); #else int size; blob.Length = 0; size = Win32Native.ExpandEnvironmentStrings(name, blob, currentSize); if (size == 0) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } while (size > currentSize) { currentSize = size; blob.Capacity = currentSize; blob.Length = 0; size = Win32Native.ExpandEnvironmentStrings(name, blob, currentSize); if (size == 0) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } } #endif // PLATFORM_UNIX return(blob.ToString()); }
private static string TryExpandShortFileName(StringBuffer outputBuffer, string originalPath) { // We'll have one of a few cases by now (the normalized path will have already: // // 1. Dos path (C:\) // 2. Dos UNC (\\Server\Share) // 3. Dos device path (\\.\C:\, \\?\C:\) // // We want to put the extended syntax on the front if it doesn't already have it, which may mean switching from \\.\. uint rootLength = PathInternal.GetRootLength(outputBuffer); bool isDevice = PathInternal.IsDevice(outputBuffer); StringBuffer inputBuffer = null; bool isDosUnc = false; uint rootDifference = 0; bool wasDotDevice = false; // Add the extended prefix before expanding to allow growth over MAX_PATH if (isDevice) { // We have one of the following (\\?\ or \\.\) // We will never get \??\ here as GetFullPathName() does not recognize \??\ and will return it as C:\??\ (or whatever the current drive is). inputBuffer = new StringBuffer(); inputBuffer.Append(outputBuffer); if (outputBuffer[2] == '.') { wasDotDevice = true; inputBuffer[2] = '?'; } } else { // \\Server\Share, but not \\.\ or \\?\. // We need to know this to be able to push \\?\UNC\ on if required isDosUnc = outputBuffer.Length > 1 && outputBuffer[0] == '\\' && outputBuffer[1] == '\\' && !PathInternal.IsDevice(outputBuffer); rootDifference = GetInputBuffer(outputBuffer, isDosUnc, out inputBuffer); } rootLength += rootDifference; uint inputLength = inputBuffer.Length; bool success = false; uint foundIndex = inputBuffer.Length - 1; while (!success) { uint result = Win32Native.GetLongPathNameW(inputBuffer.GetHandle(), outputBuffer.GetHandle(), outputBuffer.CharCapacity); // Replace any temporary null we added if (inputBuffer[foundIndex] == '\0') { inputBuffer[foundIndex] = '\\'; } if (result == 0) { // Look to see if we couldn't find the file int error = Marshal.GetLastWin32Error(); if (error != Win32Native.ERROR_FILE_NOT_FOUND && error != Win32Native.ERROR_PATH_NOT_FOUND) { // Some other failure, give up break; } // We couldn't find the path at the given index, start looking further back in the string. foundIndex--; for (; foundIndex > rootLength && inputBuffer[foundIndex] != '\\'; foundIndex--) { ; } if (foundIndex == rootLength) { // Can't trim the path back any further break; } else { // Temporarily set a null in the string to get Windows to look further up the path inputBuffer[foundIndex] = '\0'; } } else if (result > outputBuffer.CharCapacity) { // Not enough space. The result count for this API does not include the null terminator. outputBuffer.EnsureCharCapacity(result); result = Win32Native.GetLongPathNameW(inputBuffer.GetHandle(), outputBuffer.GetHandle(), outputBuffer.CharCapacity); } else { // Found the path success = true; outputBuffer.Length = result; if (foundIndex < inputLength - 1) { // It was a partial find, put the non-existent part of the path back outputBuffer.Append(inputBuffer, foundIndex, inputBuffer.Length - foundIndex); } } } // Strip out the prefix and return the string StringBuffer bufferToUse = success ? outputBuffer : inputBuffer; if (wasDotDevice) { bufferToUse[2] = '.'; } string returnValue = null; int newLength = (int)(bufferToUse.Length - rootDifference); if (isDosUnc) { // Need to go from \\?\UNC\ to \\?\UN\\ bufferToUse[(uint)PathInternal.UncExtendedPathPrefix.Length - 1] = '\\'; } // We now need to strip out any added characters at the front of the string if (bufferToUse.SubstringEquals(originalPath, rootDifference, newLength)) { // Use the original path to avoid allocating returnValue = originalPath; } else { returnValue = bufferToUse.Substring(rootDifference, newLength); } inputBuffer.Dispose(); return(returnValue); }
protected override bool ReleaseHandle() { return(Win32Native.CloseHandle(base.handle)); }
// We can remove this link demand in a future version - we will // have scenarios for this in partial trust in the future, but // we're doing this just to restrict this in case the code below // is somehow incorrect. public MemoryFailPoint(int sizeInMegabytes) { if (sizeInMegabytes <= 0) { throw new ArgumentOutOfRangeException(nameof(sizeInMegabytes), SR.ArgumentOutOfRange_NeedNonNegNum); } #if !FEATURE_PAL // Remove this when CheckForAvailableMemory is able to provide legitimate estimates ulong size = ((ulong)sizeInMegabytes) << 20; _reservedMemory = size; // Check to see that we both have enough memory on the system // and that we have enough room within the user section of the // process's address space. Also, we need to use the GC segment // size, not the amount of memory the user wants to allocate. // Consider correcting this to reflect free memory within the GC // heap, and to check both the normal & large object heaps. ulong segmentSize = (ulong)(Math.Ceiling((double)size / s_GCSegmentSize) * s_GCSegmentSize); if (segmentSize >= s_topOfMemory) { throw new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_TooBig); } ulong requestedSizeRounded = (ulong)(Math.Ceiling((double)sizeInMegabytes / MemoryCheckGranularity) * MemoryCheckGranularity); //re-convert into bytes requestedSizeRounded <<= 20; ulong availPageFile = 0; // available VM (physical + page file) ulong totalAddressSpaceFree = 0; // non-contiguous free address space // Check for available memory, with 2 attempts at getting more // memory. // Stage 0: If we don't have enough, trigger a GC. // Stage 1: If we don't have enough, try growing the swap file. // Stage 2: Update memory state, then fail or leave loop. // // (In the future, we could consider adding another stage after // Stage 0 to run finalizers. However, before doing that make sure // that we could abort this constructor when we call // GC.WaitForPendingFinalizers, noting that this method uses a CER // so it can't be aborted, and we have a critical finalizer. It // would probably work, but do some thinking first.) for (int stage = 0; stage < 3; stage++) { CheckForAvailableMemory(out availPageFile, out totalAddressSpaceFree); // If we have enough room, then skip some stages. // Note that multiple threads can still lead to a race condition for our free chunk // of address space, which can't be easily solved. ulong reserved = (ulong)Volatile.Read(ref s_failPointReservedMemory); ulong segPlusReserved = segmentSize + reserved; bool overflow = segPlusReserved < segmentSize || segPlusReserved < reserved; bool needPageFile = availPageFile < (requestedSizeRounded + reserved + LowMemoryFudgeFactor) || overflow; bool needAddressSpace = totalAddressSpaceFree < segPlusReserved || overflow; // Ensure our cached amount of free address space is not stale. long now = Environment.TickCount; // Handle wraparound. if ((now > LastTimeCheckingAddressSpace + CheckThreshold || now < LastTimeCheckingAddressSpace) || LastKnownFreeAddressSpace < (long)segmentSize) { CheckForFreeAddressSpace(segmentSize, false); } bool needContiguousVASpace = (ulong)LastKnownFreeAddressSpace < segmentSize; #if false Console.WriteLine($"MemoryFailPoint:" + $"Checking for {(segmentSize >> 20)} MB, " + $"for allocation size of {sizeInMegabytes} MB, " + $"stage {stage}. " + $"Need page file? {needPageFile} " + $"Need Address Space? {needAddressSpace} " + $"Need Contiguous address space? {needContiguousVASpace} " + $"Avail page file: {(availPageFile >> 20)} MB " + $"Total free VA space: {totalAddressSpaceFree >> 20} MB " + $"Contiguous free address space (found): {LastKnownFreeAddressSpace >> 20} MB " + $"Space reserved via process's MemoryFailPoints: {reserved} MB"); #endif if (!needPageFile && !needAddressSpace && !needContiguousVASpace) { break; } switch (stage) { case 0: // The GC will release empty segments to the OS. This will // relieve us from having to guess whether there's // enough memory in either GC heap, and whether // internal fragmentation will prevent those // allocations from succeeding. GC.Collect(); continue; case 1: // Do this step if and only if the page file is too small. if (!needPageFile) { continue; } // Attempt to grow the OS's page file. Note that we ignore // any allocation routines from the host intentionally. RuntimeHelpers.PrepareConstrainedRegions(); // This shouldn't overflow due to the if clauses above. UIntPtr numBytes = new UIntPtr(segmentSize); unsafe { void *pMemory = Win32Native.VirtualAlloc(null, numBytes, Win32Native.MEM_COMMIT, Win32Native.PAGE_READWRITE); if (pMemory != null) { bool r = Win32Native.VirtualFree(pMemory, UIntPtr.Zero, Win32Native.MEM_RELEASE); if (!r) { throw Win32Marshal.GetExceptionForLastWin32Error(); } } } continue; case 2: // The call to CheckForAvailableMemory above updated our // state. if (needPageFile || needAddressSpace) { InsufficientMemoryException e = new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint); #if DEBUG e.Data["MemFailPointState"] = new MemoryFailPointState(sizeInMegabytes, segmentSize, needPageFile, needAddressSpace, needContiguousVASpace, availPageFile >> 20, totalAddressSpaceFree >> 20, LastKnownFreeAddressSpace >> 20, reserved); #endif throw e; } if (needContiguousVASpace) { InsufficientMemoryException e = new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_VAFrag); #if DEBUG e.Data["MemFailPointState"] = new MemoryFailPointState(sizeInMegabytes, segmentSize, needPageFile, needAddressSpace, needContiguousVASpace, availPageFile >> 20, totalAddressSpaceFree >> 20, LastKnownFreeAddressSpace >> 20, reserved); #endif throw e; } break; default: Debug.Fail("Fell through switch statement!"); break; } } // Success - we have enough room the last time we checked. // Now update our shared state in a somewhat atomic fashion // and handle a simple race condition with other MemoryFailPoint instances. AddToLastKnownFreeAddressSpace(-((long)size)); if (LastKnownFreeAddressSpace < 0) { CheckForFreeAddressSpace(segmentSize, true); } RuntimeHelpers.PrepareConstrainedRegions(); Interlocked.Add(ref s_failPointReservedMemory, (long)size); _mustSubtractReservation = true; #endif }
private void AddSearchableDirsToStack(Directory.SearchData localSearchData) { Contract.Requires(localSearchData != null); String searchPath = Path.Combine(localSearchData.fullPath, "*"); SafeFindHandle hnd = null; Win32Native.WIN32_FIND_DATA data = new Win32Native.WIN32_FIND_DATA(); try { // Get all files and dirs hnd = Win32Native.FindFirstFile(searchPath, data); if (hnd.IsInvalid) { int hr = Marshal.GetLastWin32Error(); // This could happen if the dir doesn't contain any files. // Continue with the recursive search though, eventually // searchStack will become empty if (hr == Win32Native.ERROR_FILE_NOT_FOUND || hr == Win32Native.ERROR_NO_MORE_FILES || hr == Win32Native.ERROR_PATH_NOT_FOUND) { return; } HandleError(hr, localSearchData.fullPath); } // Add subdirs to searchStack. Exempt ReparsePoints as appropriate int incr = 0; do { if (FileSystemEnumerableHelpers.IsDir(data)) { String tempFullPath = Path.Combine(localSearchData.fullPath, data.cFileName); String tempUserPath = Path.Combine(localSearchData.userPath, data.cFileName); SearchOption option = localSearchData.searchOption; #if EXCLUDE_REPARSEPOINTS // Traverse reparse points depending on the searchoption specified if ((searchDataSubDir.searchOption == SearchOption.AllDirectories) && (0 != (data.dwFileAttributes & Win32Native.FILE_ATTRIBUTE_REPARSE_POINT))) { option = SearchOption.TopDirectoryOnly; } #endif // Setup search data for the sub directory and push it into the stack Directory.SearchData searchDataSubDir = new Directory.SearchData(tempFullPath, tempUserPath, option); searchStack.Insert(incr++, searchDataSubDir); } } while (Win32Native.FindNextFile(hnd, data)); // We don't care about errors here } finally { if (hnd != null) { hnd.Dispose(); } } }
public override bool MoveNext() { Win32Native.WIN32_FIND_DATA data = new Win32Native.WIN32_FIND_DATA(); switch (state) { case STATE_INIT: { if (empty) { state = STATE_FINISH; goto case STATE_FINISH; } if (searchData.searchOption == SearchOption.TopDirectoryOnly) { state = STATE_FIND_NEXT_FILE; if (current != null) { return(true); } else { goto case STATE_FIND_NEXT_FILE; } } else { state = STATE_SEARCH_NEXT_DIR; goto case STATE_SEARCH_NEXT_DIR; } } case STATE_SEARCH_NEXT_DIR: { Debug.Assert(searchData.searchOption != SearchOption.TopDirectoryOnly, "should not reach this code path if searchOption == TopDirectoryOnly"); // Traverse directory structure. We need to get '*' while (searchStack.Count > 0) { searchData = searchStack[0]; Debug.Assert((searchData.fullPath != null), "fullpath can't be null!"); searchStack.RemoveAt(0); // Traverse the subdirs AddSearchableDirsToStack(searchData); // Execute searchCriteria against the current directory String searchPath = Path.Combine(searchData.fullPath, searchCriteria); // Open a Find handle _hnd = Win32Native.FindFirstFile(searchPath, data); if (_hnd.IsInvalid) { int hr = Marshal.GetLastWin32Error(); if (hr == Win32Native.ERROR_FILE_NOT_FOUND || hr == Win32Native.ERROR_NO_MORE_FILES || hr == Win32Native.ERROR_PATH_NOT_FOUND) { continue; } _hnd.Dispose(); HandleError(hr, searchData.fullPath); } state = STATE_FIND_NEXT_FILE; SearchResult searchResult = CreateSearchResult(searchData, data); if (_resultHandler.IsResultIncluded(searchResult)) { current = _resultHandler.CreateObject(searchResult); return(true); } else { goto case STATE_FIND_NEXT_FILE; } } state = STATE_FINISH; goto case STATE_FINISH; } case STATE_FIND_NEXT_FILE: { if (searchData != null && _hnd != null) { // Keep asking for more matching files/dirs, add it to the list while (Win32Native.FindNextFile(_hnd, data)) { SearchResult searchResult = CreateSearchResult(searchData, data); if (_resultHandler.IsResultIncluded(searchResult)) { current = _resultHandler.CreateObject(searchResult); return(true); } } // Make sure we quit with a sensible error. int hr = Marshal.GetLastWin32Error(); if (_hnd != null) { _hnd.Dispose(); } // ERROR_FILE_NOT_FOUND is valid here because if the top level // dir doen't contain any subdirs and matching files then // we will get here with this errorcode from the searchStack walk if ((hr != 0) && (hr != Win32Native.ERROR_NO_MORE_FILES) && (hr != Win32Native.ERROR_FILE_NOT_FOUND)) { HandleError(hr, searchData.fullPath); } } if (searchData.searchOption == SearchOption.TopDirectoryOnly) { state = STATE_FINISH; goto case STATE_FINISH; } else { state = STATE_SEARCH_NEXT_DIR; goto case STATE_SEARCH_NEXT_DIR; } } case STATE_FINISH: { Dispose(); break; } } return(false); }
internal void SignalNoCallbacksRunning() { Contract.Assert(m_notifyWhenNoCallbacksRunning != null); Win32Native.SetEvent(m_notifyWhenNoCallbacksRunning.SafeWaitHandle); }
override protected bool ReleaseHandle() { // LsaDeregisterLogonProcess returns an NTSTATUS return(Win32Native.LsaDeregisterLogonProcess(handle) >= 0); }
override protected bool ReleaseHandle() { // LsaFreeReturnBuffer returns an NTSTATUS return(Win32Native.LsaFreeReturnBuffer(handle) >= 0); }
/// <summary> /// Override windows message loop handling. /// </summary> /// <param name="m">The Windows <see cref="T:System.Windows.Forms.Message"/> to process.</param> protected override void WndProc(ref Message m) { long wparam = m.WParam.ToInt64(); switch (m.Msg) { case WM_SIZE: if (wparam == SIZE_MINIMIZED) { previousWindowState = FormWindowState.Minimized; OnPauseRendering(EventArgs.Empty); } else { Rectangle rect; Win32Native.GetClientRect(m.HWnd, out rect); if (rect.Bottom - rect.Top == 0) { // Rapidly clicking the task bar to minimize and restore a window // can cause a WM_SIZE message with SIZE_RESTORED when // the window has actually become minimized due to rapid change // so just ignore this message } else if (wparam == SIZE_MAXIMIZED) { if (previousWindowState == FormWindowState.Minimized) { OnResumeRendering(EventArgs.Empty); } previousWindowState = FormWindowState.Maximized; OnUserResized(EventArgs.Empty); UpdateScreen(); cachedSize = Size; } else if (wparam == SIZE_RESTORED) { if (previousWindowState == FormWindowState.Minimized) { OnResumeRendering(EventArgs.Empty); } if (!sizeMove && (Size != cachedSize || previousWindowState == FormWindowState.Maximized)) { previousWindowState = FormWindowState.Normal; // Only update when cachedSize is != 0 if (cachedSize != Size.Empty) { OnUserResized(EventArgs.Empty); UpdateScreen(); } cachedSize = Size; } previousWindowState = FormWindowState.Normal; } } break; case WM_ACTIVATEAPP: if (wparam != 0) { OnAppActivated(EventArgs.Empty); } else { OnAppDeactivated(EventArgs.Empty); } break; case WM_POWERBROADCAST: if (wparam == PBT_APMQUERYSUSPEND) { OnSystemSuspend(EventArgs.Empty); m.Result = new IntPtr(1); return; } else if (wparam == PBT_APMRESUMESUSPEND) { OnSystemResume(EventArgs.Empty); m.Result = new IntPtr(1); return; } break; case WM_MENUCHAR: m.Result = new IntPtr(MNC_CLOSE << 16); // IntPtr(MAKELRESULT(0, MNC_CLOSE)); return; case WM_SYSCOMMAND: wparam &= 0xFFF0; if (wparam == SC_MONITORPOWER || wparam == SC_SCREENSAVE) { var e = new CancelEventArgs(); OnScreensaver(e); if (e.Cancel) { m.Result = IntPtr.Zero; return; } } break; } base.WndProc(ref m); }
public void MoveTo(string destDirName) { if (destDirName == null) { throw new ArgumentNullException("destDirName"); } if (destDirName.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destDirName"); } Contract.EndContractBlock(); Directory.CheckPermissions(DisplayPath, FullPath, checkHost: true, access: FileSecurityStateAccess.Write | FileSecurityStateAccess.Read); string fullDestDirName = Path.GetFullPathInternal(destDirName); if (!fullDestDirName.EndsWith(Path.DirectorySeparatorChar)) { fullDestDirName = fullDestDirName + Path.DirectorySeparatorChar; } // Demand read & write permission to destination. The reason is // we hand back a DirectoryInfo to the destination that would allow // you to read a directory listing from that directory. Sure, you // had the ability to read the file contents in the old location, // but you technically also need read permissions to the new // location as well, and write is not a true superset of read. Directory.CheckPermissions(destDirName, fullDestDirName, checkHost: true, access: FileSecurityStateAccess.Write | FileSecurityStateAccess.Read); String fullSourcePath; if (FullPath.EndsWith(Path.DirectorySeparatorChar)) { fullSourcePath = FullPath; } else { fullSourcePath = FullPath + Path.DirectorySeparatorChar; } if (String.Compare(fullSourcePath, fullDestDirName, StringComparison.OrdinalIgnoreCase) == 0) { throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustBeDifferent")); } String sourceRoot = Path.GetPathRoot(fullSourcePath); String destinationRoot = Path.GetPathRoot(fullDestDirName); if (String.Compare(sourceRoot, destinationRoot, StringComparison.OrdinalIgnoreCase) != 0) { throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustHaveSameRoot")); } if (!Win32Native.MoveFile(FullPath, destDirName)) { int hr = Marshal.GetLastWin32Error(); if (hr == Win32Native.ERROR_FILE_NOT_FOUND) // A dubious error code { hr = Win32Native.ERROR_PATH_NOT_FOUND; __Error.WinIOError(hr, DisplayPath); } if (hr == Win32Native.ERROR_ACCESS_DENIED) // We did this for Win9x. We can't change it for backcomp. { throw new IOException(Environment.GetResourceString("UnauthorizedAccess_IODenied_Path", DisplayPath)); } __Error.WinIOError(hr, string.Empty); } FullPath = fullDestDirName; OriginalPath = destDirName; DisplayPath = GetDisplayName(OriginalPath, FullPath); // Flush any cached information about the directory. _dataInitialised = -1; }
internal static bool RestoreTokenPrivilege(string privilegeName, ref Win32Native.TOKEN_PRIVILEGE previousPrivilegeState) { if (previousPrivilegeState.PrivilegeCount != 0) { bool flag = false; Win32Native.TOKEN_PRIVILEGE tOKENPRIVILEGE = new Win32Native.TOKEN_PRIVILEGE(); if (Win32Native.LookupPrivilegeValue(null, privilegeName, ref tOKENPRIVILEGE.Privilege.Luid) && tOKENPRIVILEGE.Privilege.Luid.HighPart == previousPrivilegeState.Privilege.Luid.HighPart && tOKENPRIVILEGE.Privilege.Luid.LowPart == previousPrivilegeState.Privilege.Luid.LowPart) { IntPtr currentProcess = Win32Native.GetCurrentProcess(); if (currentProcess != IntPtr.Zero) { IntPtr zero = IntPtr.Zero; if (Win32Native.OpenProcessToken(currentProcess, 40, out zero)) { int num = Marshal.SizeOf(typeof(Win32Native.TOKEN_PRIVILEGE)); int num1 = 0; if (Win32Native.AdjustTokenPrivileges(zero, false, ref previousPrivilegeState, num, out tOKENPRIVILEGE, ref num1) && Marshal.GetLastWin32Error() == 0) { flag = true; } } if (zero != IntPtr.Zero) { Win32Native.CloseHandle(zero); } Win32Native.CloseHandle(currentProcess); } } return flag; } else { return true; } }
internal FileSystemEnumerableIterator(String path, String originalUserPath, String searchPattern, SearchOption searchOption, SearchResultHandler <TSource> resultHandler, bool checkHost) { Contract.Requires(path != null); Contract.Requires(originalUserPath != null); Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); Contract.Requires(resultHandler != null); oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS); searchStack = new List <Directory.SearchData>(); String normalizedSearchPattern = NormalizeSearchPattern(searchPattern); if (normalizedSearchPattern.Length == 0) { empty = true; } else { _resultHandler = resultHandler; this.searchOption = searchOption; fullPath = Path.GetFullPathInternal(path); String fullSearchString = GetFullSearchString(fullPath, normalizedSearchPattern); normalizedSearchPath = Path.GetDirectoryName(fullSearchString); if (CodeAccessSecurityEngine.QuickCheckForAllDemands()) { // Full trust, just need to validate incoming paths // (we don't need to get the demand directory as it has no impact) FileIOPermission.EmulateFileIOPermissionChecks(fullPath); FileIOPermission.EmulateFileIOPermissionChecks(normalizedSearchPath); } else { // Not full trust, need to check for rights string[] demandPaths = new string[2]; // Any illegal chars such as *, ? will be caught by FileIOPermission.HasIllegalCharacters demandPaths[0] = Directory.GetDemandDir(fullPath, true); // For filters like foo\*.cs we need to verify if the directory foo is not denied access. // Do a demand on the combined path so that we can fail early in case of deny demandPaths[1] = Directory.GetDemandDir(normalizedSearchPath, true); new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandPaths, false, false).Demand(); } _checkHost = checkHost; // normalize search criteria searchCriteria = GetNormalizedSearchCriteria(fullSearchString, normalizedSearchPath); // fix up user path String searchPatternDirName = Path.GetDirectoryName(normalizedSearchPattern); String userPathTemp = originalUserPath; if (searchPatternDirName != null && searchPatternDirName.Length != 0) { userPathTemp = Path.CombineNoChecks(userPathTemp, searchPatternDirName); } this.userPath = userPathTemp; searchData = new Directory.SearchData(normalizedSearchPath, this.userPath, searchOption); CommonInit(); } }
internal unsafe BaseCodePageEncoding(int codepage, int dataCodePage) : base((codepage == 0) ? Win32Native.GetACP() : codepage) { this.bFlagDataTable = true; this.pCodePage = null; this.dataTableCodePage = dataCodePage; this.LoadCodePageTables(); }
protected override bool ReleaseHandle() { return(Win32Native.LsaFreeMemory(this.handle) == 0); }
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable private RuntimeAssembly GetSatelliteAssembly(CultureInfo lookForCulture, ref StackCrawlMark stackMark) { if (!_mediator.LookedForSatelliteContractVersion) { _mediator.SatelliteContractVersion = _mediator.ObtainSatelliteContractVersion(_mediator.MainAssembly); _mediator.LookedForSatelliteContractVersion = true; } RuntimeAssembly satellite = null; String satAssemblyName = GetSatelliteAssemblyName(); // Look up the satellite assembly, but don't let problems // like a partially signed satellite assembly stop us from // doing fallback and displaying something to the user. // Yet also somehow log this error for a developer. try { satellite = _mediator.MainAssembly.InternalGetSatelliteAssembly(satAssemblyName, lookForCulture, _mediator.SatelliteContractVersion, false, ref stackMark); } // Jun 08: for cases other than ACCESS_DENIED, we'll assert instead of throw to give release builds more opportunity to fallback. // #pragma warning disable 168 catch (FileLoadException fle) #pragma warning restore { #if !MONO // Ignore cases where the loader gets an access // denied back from the OS. This showed up for // href-run exe's at one point. int hr = fle._HResult; if (hr != Win32Native.MakeHRFromErrorCode(Win32Native.ERROR_ACCESS_DENIED)) { Contract.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + " with error code 0x" + hr.ToString("X", CultureInfo.InvariantCulture) + Environment.NewLine + "Exception: " + fle); } #endif } // Don't throw for zero-length satellite assemblies, for compat with v1 catch (BadImageFormatException bife) { Contract.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + Environment.NewLine + "Exception: " + bife); } #if !FEATURE_CORECLR && !MONO if (FrameworkEventSource.IsInitialized) { if (satellite != null) { FrameworkEventSource.Log.ResourceManagerGetSatelliteAssemblySucceeded(_mediator.BaseName, _mediator.MainAssembly, lookForCulture.Name, satAssemblyName); } else { FrameworkEventSource.Log.ResourceManagerGetSatelliteAssemblyFailed(_mediator.BaseName, _mediator.MainAssembly, lookForCulture.Name, satAssemblyName); } } #endif return(satellite); }
private unsafe static string TryExpandShortFileName(StringBuffer outputBuffer, string originalPath) { // We guarantee we'll expand short names for paths that only partially exist. As such, we need to find the part of the path that actually does exist. To // avoid allocating like crazy we'll create only one input array and modify the contents with embedded nulls. Contract.Assert(!PathInternal.IsPartiallyQualified(outputBuffer), "should have resolved by now"); using (StringBuffer inputBuffer = new StringBuffer(outputBuffer)) { bool success = false; uint lastIndex = outputBuffer.Length - 1; uint foundIndex = lastIndex; uint rootLength = PathInternal.GetRootLength(outputBuffer); while (!success) { uint result = Win32Native.GetLongPathNameW(inputBuffer.GetHandle(), outputBuffer.GetHandle(), outputBuffer.CharCapacity); // Replace any temporary null we added if (inputBuffer[foundIndex] == '\0') { inputBuffer[foundIndex] = '\\'; } if (result == 0) { // Look to see if we couldn't find the file int error = Marshal.GetLastWin32Error(); if (error != Win32Native.ERROR_FILE_NOT_FOUND && error != Win32Native.ERROR_PATH_NOT_FOUND) { // Some other failure, give up break; } // We couldn't find the path at the given index, start looking further back in the string. foundIndex--; for (; foundIndex > rootLength && inputBuffer[foundIndex] != '\\'; foundIndex--) { ; } if (foundIndex == rootLength) { // Can't trim the path back any further break; } else { // Temporarily set a null in the string to get Windows to look further up the path inputBuffer[foundIndex] = '\0'; } } else if (result > outputBuffer.CharCapacity) { // Not enough space. The result count for this API does not include the null terminator. outputBuffer.EnsureCharCapacity(result); } else { // Found the path success = true; outputBuffer.Length = result; if (foundIndex < lastIndex) { // It was a partial find, put the non-existant part of the path back outputBuffer.Append(inputBuffer, foundIndex, inputBuffer.Length - foundIndex); } } } StringBuffer bufferToUse = success ? outputBuffer : inputBuffer; if (bufferToUse.SubstringEquals(originalPath)) { // Use the original path to avoid allocating return(originalPath); } return(bufferToUse.ToString()); } }
internal COMException(int hresult) : base(Win32Native.GetMessage(hresult)) { this.SetErrorCode(hresult); }
private static void SetEnvironmentVariableCore(string variable, string value, EnvironmentVariableTarget target) { if (target == EnvironmentVariableTarget.Process) { SetEnvironmentVariableCore(variable, value); return; } #if !FEATURE_WIN32_REGISTRY // other targets ignored return; #else // explicitly null out value if is the empty string. if (string.IsNullOrEmpty(value) || value[0] == '\0') { value = null; } RegistryKey baseKey; string keyName; if (target == EnvironmentVariableTarget.Machine) { baseKey = Registry.LocalMachine; keyName = @"System\CurrentControlSet\Control\Session Manager\Environment"; } else if (target == EnvironmentVariableTarget.User) { Debug.Assert(target == EnvironmentVariableTarget.User); // User-wide environment variables stored in the registry are limited to 255 chars for the environment variable name. const int MaxUserEnvVariableLength = 255; if (variable.Length >= MaxUserEnvVariableLength) { throw new ArgumentException(GetResourceString("Argument_LongEnvVarValue"), nameof(variable)); } baseKey = Registry.CurrentUser; keyName = "Environment"; } else { throw new ArgumentException(GetResourceString("Arg_EnumIllegalVal", (int)target)); } using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: true)) { if (environmentKey != null) { if (value == null) { environmentKey.DeleteValue(variable, throwOnMissingValue: false); } else { environmentKey.SetValue(variable, value); } } } // send a WM_SETTINGCHANGE message to all windows IntPtr r = Win32Native.SendMessageTimeout(new IntPtr(Win32Native.HWND_BROADCAST), Win32Native.WM_SETTINGCHANGE, IntPtr.Zero, "Environment", 0, 1000, IntPtr.Zero); if (r == IntPtr.Zero) { Debug.Assert(false, "SetEnvironmentVariable failed: " + Marshal.GetLastWin32Error()); } #endif // FEATURE_WIN32_REGISTRY }
[HandleProcessCorruptedStateExceptions] // #endif // FEATURE_CORRUPTING_EXCEPTIONS internal unsafe IntPtr ToUniStr(bool allocateFromHeap) { EnsureNotDisposed(); int length = m_length; IntPtr ptr = IntPtr.Zero; IntPtr result = IntPtr.Zero; byte * bufferPtr = null; RuntimeHelpers.PrepareConstrainedRegions(); try { RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { if (allocateFromHeap) { ptr = Marshal.AllocHGlobal((length + 1) * 2); } else { #if FEATURE_COMINTEROP ptr = Marshal.AllocCoTaskMem((length + 1) * 2); #else // FEATURE_COMINTEROP Contract.Assert(false, "allocateFromHeap must never be set to false when FEATURE_COMINTEROP isn't enabled!"); throw new NotSupportedException(); #endif // FEATURE_COMINTEROP } } if (ptr == IntPtr.Zero) { throw new OutOfMemoryException(); } UnProtectMemory(); m_buffer.AcquirePointer(ref bufferPtr); Buffer.Memcpy((byte *)ptr.ToPointer(), bufferPtr, length * 2); char *endptr = (char *)ptr.ToPointer(); *(endptr + length) = '\0'; result = ptr; } catch (Exception) { ProtectMemory(); throw; } finally { ProtectMemory(); if (result == IntPtr.Zero) { // If we failed for any reason, free the new buffer if (ptr != IntPtr.Zero) { Win32Native.ZeroMemory(ptr, (UIntPtr)(length * 2)); if (allocateFromHeap) { Marshal.FreeHGlobal(ptr); } else { #if FEATURE_COMINTEROP Marshal.FreeCoTaskMem(ptr); #else // FEATURE_COMINTEROP Contract.Assert(false, "allocateFromHeap must never be set to false when FEATURE_COMINTEROP isn't enabled!"); throw new NotSupportedException(); #endif // FEATURE_COMINTEROP } } } if (bufferPtr != null) { m_buffer.ReleasePointer(); } } return(result); }
protected override void DestroyWindowCore(HandleRef hwnd) { Win32Native.SetParent(childHandle, IntPtr.Zero); }
[HandleProcessCorruptedStateExceptions] // #endif // FEATURE_CORRUPTING_EXCEPTIONS internal unsafe IntPtr ToAnsiStr(bool allocateFromHeap) { EnsureNotDisposed(); IntPtr ptr = IntPtr.Zero; IntPtr result = IntPtr.Zero; int byteCount = 0; RuntimeHelpers.PrepareConstrainedRegions(); try { // GetAnsiByteCount uses the string data, so the calculation must happen after we are decrypted. UnProtectMemory(); // allocating an extra char for terminating zero byteCount = GetAnsiByteCount() + 1; RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { if (allocateFromHeap) { ptr = Marshal.AllocHGlobal(byteCount); } else { #if FEATURE_COMINTEROP ptr = Marshal.AllocCoTaskMem(byteCount); #else // FEATURE_COMINTEROP Contract.Assert(false, "allocateFromHeap must never be set to false when FEATURE_COMINTEROP isn't enabled!"); throw new NotSupportedException(); #endif // FEATURE_COMINTEROP } } if (ptr == IntPtr.Zero) { throw new OutOfMemoryException(); } GetAnsiBytes((byte *)ptr.ToPointer(), byteCount); result = ptr; } catch (Exception) { ProtectMemory(); throw; } finally { ProtectMemory(); if (result == IntPtr.Zero) { // If we failed for any reason, free the new buffer if (ptr != IntPtr.Zero) { Win32Native.ZeroMemory(ptr, (UIntPtr)byteCount); if (allocateFromHeap) { Marshal.FreeHGlobal(ptr); } else { #if FEATURE_COMINTEROP Marshal.FreeCoTaskMem(ptr); #else // FEATURE_COMINTEROP Contract.Assert(false, "allocateFromHeap must never be set to false when FEATURE_COMINTEROP isn't enabled!"); throw new NotSupportedException(); #endif // FEATURE_COMINTEROP } } } } return(result); }
internal unsafe bool TryExpandShortFileName() { if (doNotTryExpandShortFileName) { return(false); } if (useStackAlloc) { NullTerminate(); char *buffer = UnsafeGetArrayPtr(); char *shortFileNameBuffer = stackalloc char[Path.MaxPath + 1]; int r = Win32Native.GetLongPathName(buffer, shortFileNameBuffer, Path.MaxPath); // If success, the return buffer length does not account for the terminating null character. // If in-sufficient buffer, the return buffer length does account for the path + the terminating null character. // If failure, the return buffer length is zero if (r >= Path.MaxPath) { throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong")); } if (r == 0) { // Note: GetLongPathName will return ERROR_INVALID_FUNCTION on a // path like \\.\PHYSICALDEVICE0 - some device driver doesn't // support GetLongPathName on that string. This behavior is // by design, according to the Core File Services team. // We also get ERROR_NOT_ENOUGH_QUOTA in SQL_CLR_STRESS runs // intermittently on paths like D:\DOCUME~1\user\LOCALS~1\Temp\ // We do not need to call GetLongPathName if we know it will fail becasue the path does not exist: int lastErr = Marshal.GetLastWin32Error(); if (lastErr == Win32Native.ERROR_FILE_NOT_FOUND || lastErr == Win32Native.ERROR_PATH_NOT_FOUND) { doNotTryExpandShortFileName = true; } return(false); } // Safe to copy as we have already done Path.MaxPath bound checking String.wstrcpy(buffer, shortFileNameBuffer, r); Length = r; // We should explicitly null terminate as in some cases the long version of the path // might actually be shorter than what we started with because of Win32's normalization // Safe to write directly as bufferLength is guaranteed to be < Path.MaxPath NullTerminate(); return(true); } else { StringBuilder sb = GetStringBuilder(); String origName = sb.ToString(); String tempName = origName; bool addedPrefix = false; if (tempName.Length > Path.MaxPath) { tempName = Path.AddLongPathPrefix(tempName); addedPrefix = true; } sb.Capacity = m_capacity; sb.Length = 0; int r = Win32Native.GetLongPathName(tempName, sb, m_capacity); if (r == 0) { // Note: GetLongPathName will return ERROR_INVALID_FUNCTION on a // path like \\.\PHYSICALDEVICE0 - some device driver doesn't // support GetLongPathName on that string. This behavior is // by design, according to the Core File Services team. // We also get ERROR_NOT_ENOUGH_QUOTA in SQL_CLR_STRESS runs // intermittently on paths like D:\DOCUME~1\user\LOCALS~1\Temp\ // We do not need to call GetLongPathName if we know it will fail becasue the path does not exist: int lastErr = Marshal.GetLastWin32Error(); if (Win32Native.ERROR_FILE_NOT_FOUND == lastErr || Win32Native.ERROR_PATH_NOT_FOUND == lastErr) { doNotTryExpandShortFileName = true; } sb.Length = 0; sb.Append(origName); return(false); } if (addedPrefix) { r -= 4; } // If success, the return buffer length does not account for the terminating null character. // If in-sufficient buffer, the return buffer length does account for the path + the terminating null character. // If failure, the return buffer length is zero if (r >= m_maxPath) { throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong")); } sb = Path.RemoveLongPathPrefix(sb); Length = sb.Length; return(true); } }
override protected bool ReleaseHandle() { Win32Native.ZeroMemory(handle, (UIntPtr)(Win32Native.SysStringLen(handle) * 2)); Win32Native.SysFreeString(handle); return(true); }
internal static int SetSecurityInfo(ResourceType type, string name, SafeHandle handle, SecurityInfos securityInformation, SecurityIdentifier owner, SecurityIdentifier group, GenericAcl sacl, GenericAcl dacl) { byte[] array = null; byte[] array2 = null; byte[] array3 = null; byte[] array4 = null; Privilege privilege = null; new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); if (owner != null) { int binaryLength = owner.BinaryLength; array = new byte[binaryLength]; owner.GetBinaryForm(array, 0); } if (group != null) { int binaryLength = group.BinaryLength; array2 = new byte[binaryLength]; group.GetBinaryForm(array2, 0); } if (dacl != null) { int binaryLength = dacl.BinaryLength; array4 = new byte[binaryLength]; dacl.GetBinaryForm(array4, 0); } if (sacl != null) { int binaryLength = sacl.BinaryLength; array3 = new byte[binaryLength]; sacl.GetBinaryForm(array3, 0); } if ((securityInformation & SecurityInfos.SystemAcl) != (SecurityInfos)0) { privilege = new Privilege("SeSecurityPrivilege"); } RuntimeHelpers.PrepareConstrainedRegions(); int num; try { if (privilege != null) { try { privilege.Enable(); } catch (PrivilegeNotHeldException) { } } if (name != null) { num = (int)Win32Native.SetSecurityInfoByName(name, (uint)type, (uint)securityInformation, array, array2, array4, array3); } else { if (handle == null) { throw new InvalidProgramException(); } if (handle.IsInvalid) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSafeHandle"), "handle"); } num = (int)Win32Native.SetSecurityInfoByHandle(handle, (uint)type, (uint)securityInformation, array, array2, array4, array3); } if (num == 1300 || num == 1314) { throw new PrivilegeNotHeldException("SeSecurityPrivilege"); } if (num == 5 || num == 1347) { throw new UnauthorizedAccessException(); } if (num != 0) { goto IL_159; } } catch { if (privilege != null) { privilege.Revert(); } throw; } finally { if (privilege != null) { privilege.Revert(); } } return(0); IL_159: if (num == 8) { throw new OutOfMemoryException(); } return(num); }
[System.Security.SecurityCritical] // auto-generated private unsafe static int ReadFileNative(SafeFileHandle hFile, byte[] bytes, int offset, int count, bool useFileAPIs, bool isPipe, out int bytesRead) { Contract.Requires(offset >= 0, "offset >= 0"); Contract.Requires(count >= 0, "count >= 0"); Contract.Requires(bytes != null, "bytes != null"); // Don't corrupt memory when multiple threads are erroneously writing // to this stream simultaneously. if (bytes.Length - offset < count) { throw new IndexOutOfRangeException(Environment.GetResourceString("IndexOutOfRange_IORaceCondition")); } Contract.EndContractBlock(); // You can't use the fixed statement on an array of length 0. if (bytes.Length == 0) { bytesRead = 0; return(Win32Native.ERROR_SUCCESS); } // First, wait bytes to become available. This is preferable to letting ReadFile block, // since ReadFile is not abortable (via Thread.Abort), while WaitForAvailableConsoleInput is. #if !FEATURE_CORESYSTEM // CoreSystem isn't signaling stdin when input is available so we can't block on it WaitForAvailableConsoleInput(hFile, isPipe); #endif bool readSuccess; if (useFileAPIs) { fixed(byte *p = bytes) { readSuccess = (0 != Win32Native.ReadFile(hFile, p + offset, count, out bytesRead, IntPtr.Zero)); } } else { fixed(byte *p = bytes) { int charsRead; readSuccess = Win32Native.ReadConsoleW(hFile, p + offset, count / BytesPerWChar, out charsRead, IntPtr.Zero); bytesRead = charsRead * BytesPerWChar; } } if (readSuccess) { return(Win32Native.ERROR_SUCCESS); } int errorCode = Marshal.GetLastWin32Error(); // For pipes that are closing or broken, just stop. // (E.g. ERROR_NO_DATA ("pipe is being closed") is returned when we write to a console that is closing; // ERROR_BROKEN_PIPE ("pipe was closed") is returned when stdin was closed, which is mot an error, but EOF.) if (errorCode == Win32Native.ERROR_NO_DATA || errorCode == Win32Native.ERROR_BROKEN_PIPE) { return(Win32Native.ERROR_SUCCESS); } return(errorCode); }
private static string TranslateReturnCode(Win32Native.CredUIReturnCodes result) { return string.Format("Invalid operation: {0}", result); }
public unsafe MemoryFailPoint(int sizeInMegabytes) { if (sizeInMegabytes <= 0) { throw new ArgumentOutOfRangeException("sizeInMegabytes", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } ulong num = ((ulong)sizeInMegabytes) << 20; this._reservedMemory = num; ulong size = (ulong)(Math.Ceiling((double)(((float)num) / ((float)GCSegmentSize))) * GCSegmentSize); if (size >= TopOfMemory) { throw new InsufficientMemoryException(Environment.GetResourceString("InsufficientMemory_MemFailPoint_TooBig")); } ulong availPageFile = 0L; ulong totalAddressSpaceFree = 0L; for (int i = 0; i < 3; i++) { CheckForAvailableMemory(out availPageFile, out totalAddressSpaceFree); ulong memoryFailPointReservedMemory = SharedStatics.MemoryFailPointReservedMemory; ulong num7 = size + memoryFailPointReservedMemory; bool flag = (num7 < size) || (num7 < memoryFailPointReservedMemory); bool flag2 = (availPageFile < (num7 + ((ulong)0x1000000L))) || flag; bool flag3 = (totalAddressSpaceFree < num7) || flag; long tickCount = Environment.TickCount; if (((tickCount > (LastTimeCheckingAddressSpace + 0x2710L)) || (tickCount < LastTimeCheckingAddressSpace)) || (LastKnownFreeAddressSpace < size)) { CheckForFreeAddressSpace(size, false); } bool flag4 = LastKnownFreeAddressSpace < size; if ((!flag2 && !flag3) && !flag4) { break; } switch (i) { case 0: { GC.Collect(); continue; } case 1: if (!flag2) { continue; } RuntimeHelpers.PrepareConstrainedRegions(); try { continue; } finally { UIntPtr numBytes = new UIntPtr(size); void * address = Win32Native.VirtualAlloc(null, numBytes, 0x1000, 4); if ((address != null) && !Win32Native.VirtualFree(address, UIntPtr.Zero, 0x8000)) { __Error.WinIOError(); } } break; case 2: break; default: { continue; } } if (flag2 || flag3) { InsufficientMemoryException exception = new InsufficientMemoryException(Environment.GetResourceString("InsufficientMemory_MemFailPoint")); throw exception; } if (flag4) { InsufficientMemoryException exception2 = new InsufficientMemoryException(Environment.GetResourceString("InsufficientMemory_MemFailPoint_VAFrag")); throw exception2; } } Interlocked.Add(ref LastKnownFreeAddressSpace, (long)-num); if (LastKnownFreeAddressSpace < 0L) { CheckForFreeAddressSpace(size, true); } RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { SharedStatics.AddMemoryFailPointReservation((long)num); this._mustSubtractReservation = true; } }
internal void SignalNoCallbacksRunning() { Win32Native.SetEvent(m_notifyWhenNoCallbacksRunning.SafeWaitHandle); }
internal void Init(String path, FileMode mode, FileAccess access, int rights, bool useRights, FileShare share, int bufferSize, FileOptions options, Win32Native.SECURITY_ATTRIBUTES secAttrs, String msgPath, bool bFromProxy, bool useLongPath) { if (path == null) throw new ArgumentNullException("path", Environment.GetResourceString("ArgumentNull_Path")); if (path.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath")); Contract.EndContractBlock(); #if !FEATURE_PAL && FEATURE_MACL FileSystemRights fileSystemRights = (FileSystemRights)rights; #endif // msgPath must be safe to hand back to untrusted code. _fileName = msgPath; // To handle odd cases of finalizing partially constructed objects. _exposedHandle = false; #if FEATURE_PAL Contract.Assert(!useRights, "Specifying FileSystemRights is not supported on this platform!"); #endif // don't include inheritable in our bounds check for share FileShare tempshare = share & ~FileShare.Inheritable; String badArg = null; if (mode < FileMode.CreateNew || mode > FileMode.Append) badArg = "mode"; else if (!useRights && (access < FileAccess.Read || access > FileAccess.ReadWrite)) badArg = "access"; #if !FEATURE_PAL && FEATURE_MACL else if (useRights && (fileSystemRights < FileSystemRights.ReadData || fileSystemRights > FileSystemRights.FullControl)) badArg = "rights"; #endif else if (tempshare < FileShare.None || tempshare > (FileShare.ReadWrite | FileShare.Delete)) badArg = "share"; if (badArg != null) throw new ArgumentOutOfRangeException(badArg, Environment.GetResourceString("ArgumentOutOfRange_Enum")); // NOTE: any change to FileOptions enum needs to be matched here in the error validation if (options != FileOptions.None && (options & ~(FileOptions.WriteThrough | FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.DeleteOnClose | FileOptions.SequentialScan | FileOptions.Encrypted | (FileOptions)0x20000000 /* NoBuffering */)) != 0) throw new ArgumentOutOfRangeException("options", Environment.GetResourceString("ArgumentOutOfRange_Enum")); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); // Write access validation #if !FEATURE_PAL && FEATURE_MACL if ((!useRights && (access & FileAccess.Write) == 0) || (useRights && (fileSystemRights & FileSystemRights.Write) == 0)) #else if (!useRights && (access & FileAccess.Write) == 0) #endif //!FEATURE_PAL && FEATURE_MACL { if (mode==FileMode.Truncate || mode==FileMode.CreateNew || mode==FileMode.Create || mode==FileMode.Append) { // No write access if (!useRights) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFileMode&AccessCombo", mode, access)); #if !FEATURE_PAL && FEATURE_MACL else throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFileMode&RightsCombo", mode, fileSystemRights)); #endif //!FEATURE_PAL && FEATURE_MACL } } #if !FEATURE_PAL && FEATURE_MACL // FileMode.Truncate only works with GENERIC_WRITE (FileAccess.Write), source:MSDN // For backcomp use FileAccess.Write when FileSystemRights.Write is specified if (useRights && (mode == FileMode.Truncate)) { if (fileSystemRights == FileSystemRights.Write) { useRights = false; access = FileAccess.Write; } else { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFileModeTruncate&RightsCombo", mode, fileSystemRights)); } } #endif int fAccess; if (!useRights) { fAccess = access == FileAccess.Read? GENERIC_READ: access == FileAccess.Write? GENERIC_WRITE: GENERIC_READ | GENERIC_WRITE; } else { fAccess = rights; } // Get absolute path - Security needs this to prevent something // like trying to create a file in c:\tmp with the name // "..\WinNT\System32\ntoskrnl.exe". Store it for user convenience. int maxPath = useLongPath ? Path.MaxLongPath : Path.MaxPath; String filePath = Path.NormalizePath(path, true, maxPath); _fileName = filePath; // Prevent access to your disk drives as raw block devices. if (filePath.StartsWith("\\\\.\\", StringComparison.Ordinal)) throw new ArgumentException(Environment.GetResourceString("Arg_DevicesNotSupported")); // Build up security permissions required, as well as validate we // have a sensible set of parameters. IE, creating a brand new file // for reading doesn't make much sense. FileIOPermissionAccess secAccess = FileIOPermissionAccess.NoAccess; #if !FEATURE_PAL && FEATURE_MACL if ((!useRights && (access & FileAccess.Read) != 0) || (useRights && (fileSystemRights & FileSystemRights.ReadAndExecute) != 0)) #else if (!useRights && (access & FileAccess.Read) != 0) #endif //!FEATURE_PAL && FEATURE_MACL { if (mode==FileMode.Append) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidAppendMode")); else secAccess = secAccess | FileIOPermissionAccess.Read; } // I can't think of any combos of FileMode we should disallow if we // don't have read access. Writing would pretty much always be valid // in those cases. // For any FileSystemRights other than ReadAndExecute, demand Write permission // This is probably bit overkill for TakeOwnership etc but we don't have any // matching FileIOPermissionAccess to demand. It is better that we ask for Write permission. #if !FEATURE_PAL && FEATURE_MACL // FileMode.OpenOrCreate & FileSystemRights.Synchronize can create 0-byte file; demand write if ((!useRights && (access & FileAccess.Write) != 0) || (useRights && (fileSystemRights & (FileSystemRights.Write | FileSystemRights.Delete | FileSystemRights.DeleteSubdirectoriesAndFiles | FileSystemRights.ChangePermissions | FileSystemRights.TakeOwnership)) != 0) || (useRights && ((fileSystemRights & FileSystemRights.Synchronize) != 0) && mode==FileMode.OpenOrCreate) ) #else if (!useRights && (access & FileAccess.Write) != 0) #endif //!FEATURE_PAL && FEATURE_MACL { if (mode==FileMode.Append) secAccess = secAccess | FileIOPermissionAccess.Append; else secAccess = secAccess | FileIOPermissionAccess.Write; } #if !FEATURE_PAL && FEATURE_MACL bool specifiedAcl; unsafe { specifiedAcl = secAttrs != null && secAttrs.pSecurityDescriptor != null; } AccessControlActions control = specifiedAcl ? AccessControlActions.Change : AccessControlActions.None; new FileIOPermission(secAccess, control, new String[] { filePath }, false, false).Demand(); #else new FileIOPermission(secAccess, new String[] { filePath }, false, false).Demand(); #endif // Our Inheritable bit was stolen from Windows, but should be set in // the security attributes class. Don't leave this bit set. share &= ~FileShare.Inheritable; bool seekToEnd = (mode==FileMode.Append); // Must use a valid Win32 constant here... if (mode == FileMode.Append) mode = FileMode.OpenOrCreate; // WRT async IO, do the right thing for whatever platform we're on. // This way, someone can easily write code that opens a file // asynchronously no matter what their platform is. if (_canUseAsync && (options & FileOptions.Asynchronous) != 0) _isAsync = true; else options &= ~FileOptions.Asynchronous; int flagsAndAttributes = (int) options; #if !FEATURE_PAL // For mitigating local elevation of privilege attack through named pipes // make sure we always call CreateFile with SECURITY_ANONYMOUS so that the // named pipe server can't impersonate a high privileged client security context flagsAndAttributes|= (Win32Native.SECURITY_SQOS_PRESENT | Win32Native.SECURITY_ANONYMOUS); #endif // Don't pop up a dialog for reading from an emtpy floppy drive int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS); try { String tempPath = filePath; if (useLongPath) tempPath = Path.AddLongPathPrefix(tempPath); _handle = Win32Native.SafeCreateFile(tempPath, fAccess, share, secAttrs, mode, flagsAndAttributes, Win32Native.NULL); if (_handle.IsInvalid) { // Return a meaningful exception, using the RELATIVE path to // the file to avoid returning extra information to the caller // unless they have path discovery permission, in which case // the full path is fine & useful. // NT5 oddity - when trying to open "C:\" as a FileStream, // we usually get ERROR_PATH_NOT_FOUND from the OS. We should // probably be consistent w/ every other directory. int errorCode = Marshal.GetLastWin32Error(); if (errorCode==__Error.ERROR_PATH_NOT_FOUND && filePath.Equals(Directory.InternalGetDirectoryRoot(filePath))) errorCode = __Error.ERROR_ACCESS_DENIED; // We need to give an exception, and preferably it would include // the fully qualified path name. Do security check here. If // we fail, give back the msgPath, which should not reveal much. // While this logic is largely duplicated in // __Error.WinIOError, we need this for // IsolatedStorageFileStream. bool canGiveFullPath = false; if (!bFromProxy) { try { new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new String[] { _fileName }, false, false ).Demand(); canGiveFullPath = true; } catch(SecurityException) {} } if (canGiveFullPath) __Error.WinIOError(errorCode, _fileName); else __Error.WinIOError(errorCode, msgPath); } } finally { Win32Native.SetErrorMode(oldMode); } // Disallow access to all non-file devices from the FileStream // constructors that take a String. Everyone else can call // CreateFile themselves then use the constructor that takes an // IntPtr. Disallows "con:", "com1:", "lpt1:", etc. int fileType = Win32Native.GetFileType(_handle); if (fileType != Win32Native.FILE_TYPE_DISK) { _handle.Close(); throw new NotSupportedException(Environment.GetResourceString("NotSupported_FileStreamOnNonFiles")); } #if !FEATURE_PAL #if !FEATURE_CORECLR // This is necessary for async IO using IO Completion ports via our // managed Threadpool API's. This (theoretically) calls the OS's // BindIoCompletionCallback method, and passes in a stub for the // LPOVERLAPPED_COMPLETION_ROUTINE. This stub looks at the Overlapped // struct for this request and gets a delegate to a managed callback // from there, which it then calls on a threadpool thread. (We allocate // our native OVERLAPPED structs 2 pointers too large and store EE state // & GC handles there, one to an IAsyncResult, the other to a delegate.) if (_isAsync) { bool b = false; // BindHandle requires UnmanagedCode permission new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); try { b = ThreadPool.BindHandle(_handle); } finally { CodeAccessPermission.RevertAssert(); if (!b) { // We should close the handle so that the handle is not open until SafeFileHandle GC Contract.Assert(!_exposedHandle, "Are we closing handle that we exposed/not own, how?"); _handle.Close(); } } if (!b) throw new IOException(Environment.GetResourceString("IO.IO_BindHandleFailed")); } #endif // FEATURE_CORECLR #endif //!FEATURE_PAL if (!useRights) { _canRead = (access & FileAccess.Read) != 0; _canWrite = (access & FileAccess.Write) != 0; } #if !FEATURE_PAL && FEATURE_MACL else { _canRead = (fileSystemRights & FileSystemRights.ReadData) != 0; _canWrite = ((fileSystemRights & FileSystemRights.WriteData) != 0) || ((fileSystemRights & FileSystemRights.AppendData) != 0); } #endif //!FEATURE_PAL && FEATURE_MACL _canSeek = true; _isPipe = false; _pos = 0; _bufferSize = bufferSize; _readPos = 0; _readLen = 0; _writePos = 0; // For Append mode... if (seekToEnd) { _appendStart = SeekCore(0, SeekOrigin.End); } else { _appendStart = -1; } }