Exemple #1
0
        internal Mutex(bool initiallyOwned, String name, out bool createdNew, Win32Native.SECURITY_ATTRIBUTES secAttrs) 
        {
            if (null != name && Path.MAX_PATH < name.Length) 
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", name));
            }
            Contract.EndContractBlock();

            CreateMutexWithGuaranteedCleanup(initiallyOwned, name, out createdNew, secAttrs);
        }
Exemple #2
0
 internal void CreateMutexWithGuaranteedCleanup(bool initiallyOwned, String name, out bool createdNew, Win32Native.SECURITY_ATTRIBUTES secAttrs)
 {
     RuntimeHelpers.CleanupCode cleanupCode = new RuntimeHelpers.CleanupCode(MutexCleanupCode);
     MutexCleanupInfo cleanupInfo = new MutexCleanupInfo(null, false);
     MutexTryCodeHelper tryCodeHelper = new MutexTryCodeHelper(initiallyOwned, cleanupInfo, name, secAttrs, this);
     RuntimeHelpers.TryCode tryCode = new RuntimeHelpers.TryCode(tryCodeHelper.MutexTryCode);
     RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(
         tryCode,
         cleanupCode,
         cleanupInfo);             
     createdNew = tryCodeHelper.m_newMutex;
 }
Exemple #3
0
 internal void PopulateFrom(Win32Native.WIN32_FIND_DATA findData)
 {
     this.fileAttributes = findData.dwFileAttributes;
     this.ftCreationTimeLow = findData.ftCreationTime_dwLowDateTime;
     this.ftCreationTimeHigh = findData.ftCreationTime_dwHighDateTime;
     this.ftLastAccessTimeLow = findData.ftLastAccessTime_dwLowDateTime;
     this.ftLastAccessTimeHigh = findData.ftLastAccessTime_dwHighDateTime;
     this.ftLastWriteTimeLow = findData.ftLastWriteTime_dwLowDateTime;
     this.ftLastWriteTimeHigh = findData.ftLastWriteTime_dwHighDateTime;
     this.fileSizeHigh = findData.nFileSizeHigh;
     this.fileSizeLow = findData.nFileSizeLow;
 }
Exemple #4
0
        internal Mutex(bool initiallyOwned, String name, out bool createdNew, Win32Native.SECURITY_ATTRIBUTES secAttrs) 
        {
            if (name == string.Empty)
            {
                // Empty name is treated as an unnamed mutex. Set to null, and we will check for null from now on.
                name = null;
            }
#if !PLATFORM_UNIX
            if (name != null && System.IO.Path.MaxPath < name.Length)
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), nameof(name));
            }
#endif
            Contract.EndContractBlock();

            CreateMutexWithGuaranteedCleanup(initiallyOwned, name, out createdNew, secAttrs);
        }
 internal MutexTryCodeHelper(bool initiallyOwned,MutexCleanupInfo cleanupInfo, String name, Win32Native.SECURITY_ATTRIBUTES secAttrs, Mutex mutex)
 {
     m_initiallyOwned = initiallyOwned;
     m_cleanupInfo = cleanupInfo;
     m_name = name;
     m_secAttrs = secAttrs;
     m_mutex = mutex;
 }
 internal unsafe 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)
 {
     int num;
     if (path == null)
     {
         throw new ArgumentNullException("path", Environment.GetResourceString("ArgumentNull_Path"));
     }
     if (path.Length == 0)
     {
         throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
     }
     FileSystemRights rights2 = (FileSystemRights) rights;
     this._fileName = msgPath;
     this._exposedHandle = false;
     FileShare share2 = share & ~FileShare.Inheritable;
     string paramName = null;
     if ((mode < FileMode.CreateNew) || (mode > FileMode.Append))
     {
         paramName = "mode";
     }
     else if (!useRights && ((access < FileAccess.Read) || (access > FileAccess.ReadWrite)))
     {
         paramName = "access";
     }
     else if (useRights && ((rights2 < FileSystemRights.ListDirectory) || (rights2 > FileSystemRights.FullControl)))
     {
         paramName = "rights";
     }
     else if ((share2 < FileShare.None) || (share2 > (FileShare.Delete | FileShare.ReadWrite)))
     {
         paramName = "share";
     }
     if (paramName != null)
     {
         throw new ArgumentOutOfRangeException(paramName, Environment.GetResourceString("ArgumentOutOfRange_Enum"));
     }
     if ((options != FileOptions.None) && ((options & 0x3ffbfff) != FileOptions.None))
     {
         throw new ArgumentOutOfRangeException("options", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
     }
     if (bufferSize <= 0)
     {
         throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
     }
     if (((!useRights && ((access & FileAccess.Write) == 0)) || (useRights && ((rights2 & FileSystemRights.Write) == 0))) && (((mode == FileMode.Truncate) || (mode == FileMode.CreateNew)) || ((mode == FileMode.Create) || (mode == FileMode.Append))))
     {
         if (!useRights)
         {
             throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFileMode&AccessCombo", new object[] { mode, access }));
         }
         throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFileMode&RightsCombo", new object[] { mode, rights2 }));
     }
     if (useRights && (mode == FileMode.Truncate))
     {
         if (rights2 != FileSystemRights.Write)
         {
             throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFileModeTruncate&RightsCombo", new object[] { mode, rights2 }));
         }
         useRights = false;
         access = FileAccess.Write;
     }
     if (!useRights)
     {
         num = (access == FileAccess.Read) ? -2147483648 : ((access == FileAccess.Write) ? 0x40000000 : -1073741824);
     }
     else
     {
         num = rights;
     }
     int maxPathLength = useLongPath ? Path.MaxLongPath : Path.MaxPath;
     string str2 = Path.NormalizePath(path, true, maxPathLength);
     this._fileName = str2;
     if (str2.StartsWith(@"\\.\", StringComparison.Ordinal))
     {
         throw new ArgumentException(Environment.GetResourceString("Arg_DevicesNotSupported"));
     }
     FileIOPermissionAccess noAccess = FileIOPermissionAccess.NoAccess;
     if ((!useRights && ((access & FileAccess.Read) != 0)) || (useRights && ((rights2 & FileSystemRights.ReadAndExecute) != 0)))
     {
         if (mode == FileMode.Append)
         {
             throw new ArgumentException(Environment.GetResourceString("Argument_InvalidAppendMode"));
         }
         noAccess |= FileIOPermissionAccess.Read;
     }
     if (((!useRights && ((access & FileAccess.Write) != 0)) || (useRights && ((rights2 & (FileSystemRights.TakeOwnership | FileSystemRights.ChangePermissions | FileSystemRights.Delete | FileSystemRights.Write | FileSystemRights.DeleteSubdirectoriesAndFiles)) != 0))) || ((useRights && ((rights2 & FileSystemRights.Synchronize) != 0)) && (mode == FileMode.OpenOrCreate)))
     {
         if (mode == FileMode.Append)
         {
             noAccess |= FileIOPermissionAccess.Append;
         }
         else
         {
             noAccess |= FileIOPermissionAccess.Write;
         }
     }
     AccessControlActions control = ((secAttrs != null) && (secAttrs.pSecurityDescriptor != null)) ? AccessControlActions.Change : AccessControlActions.None;
     new FileIOPermission(noAccess, control, new string[] { str2 }, false, false).Demand();
     share &= ~FileShare.Inheritable;
     bool flag2 = mode == FileMode.Append;
     if (mode == FileMode.Append)
     {
         mode = FileMode.OpenOrCreate;
     }
     if (_canUseAsync && ((options & FileOptions.Asynchronous) != FileOptions.None))
     {
         this._isAsync = true;
     }
     else
     {
         options &= ~FileOptions.Asynchronous;
     }
     int dwFlagsAndAttributes = (int) options;
     dwFlagsAndAttributes |= 0x100000;
     int newMode = Win32Native.SetErrorMode(1);
     try
     {
         string str3 = str2;
         if (useLongPath)
         {
             str3 = Path.AddLongPathPrefix(str3);
         }
         this._handle = Win32Native.SafeCreateFile(str3, num, share, secAttrs, mode, dwFlagsAndAttributes, Win32Native.NULL);
         if (this._handle.IsInvalid)
         {
             int errorCode = Marshal.GetLastWin32Error();
             if ((errorCode == 3) && str2.Equals(Directory.InternalGetDirectoryRoot(str2)))
             {
                 errorCode = 5;
             }
             bool flag3 = false;
             if (!bFromProxy)
             {
                 try
                 {
                     new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new string[] { this._fileName }, false, false).Demand();
                     flag3 = true;
                 }
                 catch (SecurityException)
                 {
                 }
             }
             if (flag3)
             {
                 __Error.WinIOError(errorCode, this._fileName);
             }
             else
             {
                 __Error.WinIOError(errorCode, msgPath);
             }
         }
     }
     finally
     {
         Win32Native.SetErrorMode(newMode);
     }
     if (Win32Native.GetFileType(this._handle) != 1)
     {
         this._handle.Close();
         throw new NotSupportedException(Environment.GetResourceString("NotSupported_FileStreamOnNonFiles"));
     }
     if (this._isAsync)
     {
         bool flag4 = false;
         new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
         try
         {
             flag4 = ThreadPool.BindHandle(this._handle);
         }
         finally
         {
             CodeAccessPermission.RevertAssert();
             if (!flag4)
             {
                 this._handle.Close();
             }
         }
         if (!flag4)
         {
             throw new IOException(Environment.GetResourceString("IO.IO_BindHandleFailed"));
         }
     }
     if (!useRights)
     {
         this._canRead = (access & FileAccess.Read) != 0;
         this._canWrite = (access & FileAccess.Write) != 0;
     }
     else
     {
         this._canRead = (rights2 & FileSystemRights.ListDirectory) != 0;
         this._canWrite = ((rights2 & FileSystemRights.CreateFiles) != 0) || ((rights2 & FileSystemRights.AppendData) != 0);
     }
     this._canSeek = true;
     this._isPipe = false;
     this._pos = 0L;
     this._bufferSize = bufferSize;
     this._readPos = 0;
     this._readLen = 0;
     this._writePos = 0;
     if (flag2)
     {
         this._appendStart = this.SeekCore(0L, SeekOrigin.End);
     }
     else
     {
         this._appendStart = -1L;
     }
 }
 internal void InitializeFrom(Win32Native.WIN32_FIND_DATA findData)
 {
     _data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
     _data.PopulateFrom(findData);
     _dataInitialised = 0;
 }
Exemple #8
0
        /// <summary>
        /// Retrieves an array of strings containing all the value names.
        /// </summary>
        public unsafe string[] GetValueNames()
        {
            EnsureNotDisposed();
            var names = new List <string>();

            // Names in the registry aren't usually very long, although they can go to as large
            // as 16383 characters (MaxValueLength).
            //
            // Every call to RegEnumValue will allocate another buffer to get the data from
            // NtEnumerateValueKey before copying it back out to our passed in buffer. This can
            // add up quickly- we'll try to keep the memory pressure low and grow the buffer
            // only if needed.

            char[] name = ArrayPool <char> .Shared.Rent(100);

            try
            {
                int result;
                int nameLength = name.Length;

                while ((result = Win32Native.RegEnumValue(
                            _hkey,
                            names.Count,
                            name,
                            ref nameLength,
                            IntPtr.Zero,
                            null,
                            null,
                            null)) != Interop.Errors.ERROR_NO_MORE_ITEMS)
                {
                    switch (result)
                    {
                    // The size is only ever reported back correctly in the case
                    // of ERROR_SUCCESS. It will almost always be changed, however.
                    case Interop.Errors.ERROR_SUCCESS:
                        names.Add(new string(name, 0, nameLength));
                        break;

                    case Interop.Errors.ERROR_MORE_DATA:
                        if (IsPerfDataKey())
                        {
                            // Enumerating the values for Perf keys always returns
                            // ERROR_MORE_DATA, but has a valid name. Buffer does need
                            // to be big enough however. 8 characters is the largest
                            // known name. The size isn't returned, but the string is
                            // null terminated.
                            fixed(char *c = &name[0])
                            {
                                names.Add(new string(c));
                            }
                        }
                        else
                        {
                            char[] oldName   = name;
                            int    oldLength = oldName.Length;
                            name = null;
                            ArrayPool <char> .Shared.Return(oldName);

                            name = ArrayPool <char> .Shared.Rent(checked (oldLength * 2));
                        }
                        break;

                    default:
                        // Throw the error
                        Win32Error(result, null);
                        break;
                    }

                    // Always set the name length back to the buffer size
                    nameLength = name.Length;
                }
            }
            finally
            {
                if (name != null)
                {
                    ArrayPool <char> .Shared.Return(name);
                }
            }

            return(names.ToArray());
        }
        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;
        }
Exemple #10
0
 public TimeZoneInformation(Win32Native.DynamicTimeZoneInformation dtzi) {
     Bias = dtzi.Bias;
     StandardName = dtzi.StandardName;
     StandardDate = dtzi.StandardDate;
     StandardBias = dtzi.StandardBias;
     DaylightName = dtzi.DaylightName;
     DaylightDate = dtzi.DaylightDate;
     DaylightBias = dtzi.DaylightBias;
 }
Exemple #11
0
 [System.Security.SecurityCritical]  // auto-generated
 private static bool IsKeyDownEvent(Win32Native.InputRecord ir) {
     return (ir.eventType == Win32Native.KEY_EVENT && ir.keyEvent.keyDown);
 } 
Exemple #12
0
 internal static bool SetConsoleCursorPosition(IntPtr hConsoleOutput, Win32Native.COORD cursorPosition);
Exemple #13
0
 internal static SafeFileHandle UnsafeCreateFile(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, Win32Native.SECURITY_ATTRIBUTES securityAttrs, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile)
 {
     return Win32Native.CreateFile(lpFileName, dwDesiredAccess, dwShareMode, securityAttrs, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
 }
Exemple #14
0
        internal object InternalGetValue(string name, object defaultValue, bool doNotExpand, bool checkSecurity)
        {
            if (checkSecurity)
            {
                // Name can be null!  It's the most common use of RegQueryValueEx
                EnsureNotDisposed();
            }

            object data     = defaultValue;
            int    type     = 0;
            int    datasize = 0;

            int ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, (byte[])null, ref datasize);

            if (ret != 0)
            {
                if (IsPerfDataKey())
                {
                    int size      = 65000;
                    int sizeInput = size;

                    int    r;
                    byte[] blob = new byte[size];
                    while (Interop.Errors.ERROR_MORE_DATA == (r = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, blob, ref sizeInput)))
                    {
                        if (size == int.MaxValue)
                        {
                            // ERROR_MORE_DATA was returned however we cannot increase the buffer size beyond int.MaxValue
                            Win32Error(r, name);
                        }
                        else if (size > (int.MaxValue / 2))
                        {
                            // at this point in the loop "size * 2" would cause an overflow
                            size = int.MaxValue;
                        }
                        else
                        {
                            size *= 2;
                        }
                        sizeInput = size;
                        blob      = new byte[size];
                    }
                    if (r != 0)
                    {
                        Win32Error(r, name);
                    }
                    return(blob);
                }
                else
                {
                    // For stuff like ERROR_FILE_NOT_FOUND, we want to return null (data).
                    // Some OS's returned ERROR_MORE_DATA even in success cases, so we
                    // want to continue on through the function.
                    if (ret != Interop.Errors.ERROR_MORE_DATA)
                    {
                        return(data);
                    }
                }
            }

            if (datasize < 0)
            {
                // unexpected code path
                Debug.Fail("[InternalGetValue] RegQueryValue returned ERROR_SUCCESS but gave a negative datasize");
                datasize = 0;
            }


            switch (type)
            {
            case Win32Native.REG_NONE:
            case Win32Native.REG_DWORD_BIG_ENDIAN:
            case Win32Native.REG_BINARY:
            {
                byte[] blob = new byte[datasize];
                ret  = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize);
                data = blob;
            }
            break;

            case Win32Native.REG_QWORD:
            {            // also REG_QWORD_LITTLE_ENDIAN
                if (datasize > 8)
                {
                    // prevent an AV in the edge case that datasize is larger than sizeof(long)
                    goto case Win32Native.REG_BINARY;
                }
                long blob = 0;
                Debug.Assert(datasize == 8, "datasize==8");
                // Here, datasize must be 8 when calling this
                ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, ref blob, ref datasize);

                data = blob;
            }
            break;

            case Win32Native.REG_DWORD:
            {            // also REG_DWORD_LITTLE_ENDIAN
                if (datasize > 4)
                {
                    // prevent an AV in the edge case that datasize is larger than sizeof(int)
                    goto case Win32Native.REG_QWORD;
                }
                int blob = 0;
                Debug.Assert(datasize == 4, "datasize==4");
                // Here, datasize must be four when calling this
                ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, ref blob, ref datasize);

                data = blob;
            }
            break;

            case Win32Native.REG_SZ:
            {
                if (datasize % 2 == 1)
                {
                    // handle the case where the registry contains an odd-byte length (corrupt data?)
                    try
                    {
                        datasize = checked (datasize + 1);
                    }
                    catch (OverflowException e)
                    {
                        throw new IOException(SR.Arg_RegGetOverflowBug, e);
                    }
                }
                char[] blob = new char[datasize / 2];

                ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize);
                if (blob.Length > 0 && blob[blob.Length - 1] == (char)0)
                {
                    data = new string(blob, 0, blob.Length - 1);
                }
                else
                {
                    // in the very unlikely case the data is missing null termination,
                    // pass in the whole char[] to prevent truncating a character
                    data = new string(blob);
                }
            }
            break;

            case Win32Native.REG_EXPAND_SZ:
            {
                if (datasize % 2 == 1)
                {
                    // handle the case where the registry contains an odd-byte length (corrupt data?)
                    try
                    {
                        datasize = checked (datasize + 1);
                    }
                    catch (OverflowException e)
                    {
                        throw new IOException(SR.Arg_RegGetOverflowBug, e);
                    }
                }
                char[] blob = new char[datasize / 2];

                ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize);

                if (blob.Length > 0 && blob[blob.Length - 1] == (char)0)
                {
                    data = new string(blob, 0, blob.Length - 1);
                }
                else
                {
                    // in the very unlikely case the data is missing null termination,
                    // pass in the whole char[] to prevent truncating a character
                    data = new string(blob);
                }

                if (!doNotExpand)
                {
                    data = Environment.ExpandEnvironmentVariables((string)data);
                }
            }
            break;

            case Win32Native.REG_MULTI_SZ:
            {
                if (datasize % 2 == 1)
                {
                    // handle the case where the registry contains an odd-byte length (corrupt data?)
                    try
                    {
                        datasize = checked (datasize + 1);
                    }
                    catch (OverflowException e)
                    {
                        throw new IOException(SR.Arg_RegGetOverflowBug, e);
                    }
                }
                char[] blob = new char[datasize / 2];

                ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize);

                // make sure the string is null terminated before processing the data
                if (blob.Length > 0 && blob[blob.Length - 1] != (char)0)
                {
                    try
                    {
                        char[] newBlob = new char[checked (blob.Length + 1)];
                        for (int i = 0; i < blob.Length; i++)
                        {
                            newBlob[i] = blob[i];
                        }
                        newBlob[newBlob.Length - 1] = (char)0;
                        blob = newBlob;
                    }
                    catch (OverflowException e)
                    {
                        throw new IOException(SR.Arg_RegGetOverflowBug, e);
                    }
                    blob[blob.Length - 1] = (char)0;
                }


                IList <string> strings = new List <string>();
                int            cur     = 0;
                int            len     = blob.Length;

                while (ret == 0 && cur < len)
                {
                    int nextNull = cur;
                    while (nextNull < len && blob[nextNull] != (char)0)
                    {
                        nextNull++;
                    }

                    if (nextNull < len)
                    {
                        Debug.Assert(blob[nextNull] == (char)0, "blob[nextNull] should be 0");
                        if (nextNull - cur > 0)
                        {
                            strings.Add(new string(blob, cur, nextNull - cur));
                        }
                        else
                        {
                            // we found an empty string.  But if we're at the end of the data,
                            // it's just the extra null terminator.
                            if (nextNull != len - 1)
                            {
                                strings.Add(string.Empty);
                            }
                        }
                    }
                    else
                    {
                        strings.Add(new string(blob, cur, len - cur));
                    }
                    cur = nextNull + 1;
                }

                data = new string[strings.Count];
                strings.CopyTo((string[])data, 0);
            }
            break;

            case Win32Native.REG_LINK:
            default:
                break;
            }

            return(data);
        }
Exemple #15
0
 internal static bool SetFileTime(SafeFileHandle hFile, Win32Native.FILE_TIME* creationTime, Win32Native.FILE_TIME* lastAccessTime, Win32Native.FILE_TIME* lastWriteTime);
Exemple #16
0
 internal static bool SetConsoleWindowInfo(IntPtr hConsoleOutput, bool absolute, Win32Native.SMALL_RECT* consoleWindow);
Exemple #17
0
 internal static bool SetConsoleScreenBufferSize(IntPtr hConsoleOutput, Win32Native.COORD size);
 internal static extern void _GetDateNotBefore(SafeCertContextHandle safeCertContext, ref Win32Native.FILE_TIME fileTime);
Exemple #19
0
        [System.Security.SecurityCritical]  // auto-generated
        private static ConsoleColor ColorAttributeToConsoleColor(Win32Native.Color c)
        { 
            // Turn background colors into foreground colors.
            if ((c & Win32Native.Color.BackgroundMask) != 0) 
                c = (Win32Native.Color) (((int)c) >> 4); 

            return (ConsoleColor) c; 
        }
Exemple #20
0
 internal static UIntPtr VirtualQuery(void* address, ref Win32Native.MEMORY_BASIC_INFORMATION buffer, UIntPtr sizeOfBuffer);
Exemple #21
0
        public unsafe void SetValue(string name, object value, RegistryValueKind valueKind)
        {
            if (value == null)
            {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
            }

            if (name != null && name.Length > MaxValueLength)
            {
                throw new ArgumentException(SR.Arg_RegValStrLenBug);
            }

            if (!Enum.IsDefined(typeof(RegistryValueKind), valueKind))
            {
                throw new ArgumentException(SR.Arg_RegBadKeyKind, nameof(valueKind));
            }

            EnsureWriteable();

            if (valueKind == RegistryValueKind.Unknown)
            {
                // this is to maintain compatibility with the old way of autodetecting the type.
                // SetValue(string, object) will come through this codepath.
                valueKind = CalculateValueKind(value);
            }

            int ret = 0;

            try
            {
                switch (valueKind)
                {
                case RegistryValueKind.ExpandString:
                case RegistryValueKind.String:
                {
                    string data = value.ToString();
                    ret = Win32Native.RegSetValueEx(_hkey,
                                                    name,
                                                    0,
                                                    valueKind,
                                                    data,
                                                    checked (data.Length * 2 + 2));
                    break;
                }

                case RegistryValueKind.MultiString:
                {
                    // Other thread might modify the input array after we calculate the buffer length.
                    // Make a copy of the input array to be safe.
                    string[] dataStrings = (string[])(((string[])value).Clone());
                    int      sizeInBytes = 0;

                    // First determine the size of the array
                    //
                    for (int i = 0; i < dataStrings.Length; i++)
                    {
                        if (dataStrings[i] == null)
                        {
                            ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetStrArrNull);
                        }
                        sizeInBytes = checked (sizeInBytes + (dataStrings[i].Length + 1) * 2);
                    }
                    sizeInBytes = checked (sizeInBytes + 2);

                    byte[] basePtr = new byte[sizeInBytes];
                    fixed(byte *b = basePtr)
                    {
                        IntPtr currentPtr = new IntPtr((void *)b);

                        // Write out the strings...
                        //
                        for (int i = 0; i < dataStrings.Length; i++)
                        {
                            // Assumes that the Strings are always null terminated.
                            string.InternalCopy(dataStrings[i], currentPtr, (checked (dataStrings[i].Length * 2)));
                            currentPtr = new IntPtr((long)currentPtr + (checked (dataStrings[i].Length * 2)));
                            *(char *)(currentPtr.ToPointer()) = '\0';
                            currentPtr = new IntPtr((long)currentPtr + 2);
                        }

                        *(char *)(currentPtr.ToPointer()) = '\0';
                        currentPtr = new IntPtr((long)currentPtr + 2);

                        ret = Win32Native.RegSetValueEx(_hkey,
                                                        name,
                                                        0,
                                                        RegistryValueKind.MultiString,
                                                        basePtr,
                                                        sizeInBytes);
                    }
                    break;
                }

                case RegistryValueKind.None:
                case RegistryValueKind.Binary:
                    byte[] dataBytes = (byte[])value;
                    ret = Win32Native.RegSetValueEx(_hkey,
                                                    name,
                                                    0,
                                                    (valueKind == RegistryValueKind.None ? Win32Native.REG_NONE : RegistryValueKind.Binary),
                                                    dataBytes,
                                                    dataBytes.Length);
                    break;

                case RegistryValueKind.DWord:
                {
                    // We need to use Convert here because we could have a boxed type cannot be
                    // unboxed and cast at the same time.  I.e. ((int)(object)(short) 5) will fail.
                    int data = Convert.ToInt32(value, System.Globalization.CultureInfo.InvariantCulture);

                    ret = Win32Native.RegSetValueEx(_hkey,
                                                    name,
                                                    0,
                                                    RegistryValueKind.DWord,
                                                    ref data,
                                                    4);
                    break;
                }

                case RegistryValueKind.QWord:
                {
                    long data = Convert.ToInt64(value, System.Globalization.CultureInfo.InvariantCulture);

                    ret = Win32Native.RegSetValueEx(_hkey,
                                                    name,
                                                    0,
                                                    RegistryValueKind.QWord,
                                                    ref data,
                                                    8);
                    break;
                }
                }
            }
            catch (OverflowException)
            {
                ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind);
            }
            catch (InvalidOperationException)
            {
                ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind);
            }
            catch (FormatException)
            {
                ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind);
            }
            catch (InvalidCastException)
            {
                ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind);
            }

            if (ret == 0)
            {
                SetDirty();
            }
            else
            {
                Win32Error(ret, null);
            }
        }
Exemple #22
0
 [System.Security.SecurityCritical]  // auto-generated
 private static bool IsAltKeyDown(Win32Native.InputRecord ir) { 
     return (((ControlKeyState) ir.keyEvent.controlKeyState)
                       & (ControlKeyState.LeftAltPressed | ControlKeyState.RightAltPressed)) != 0;
 }
Exemple #23
0
 internal static bool WriteConsoleOutput(IntPtr hConsoleOutput, Win32Native.CHAR_INFO* buffer, Win32Native.COORD bufferSize, Win32Native.COORD bufferCoord, ref Win32Native.SMALL_RECT writeRegion);
Exemple #24
0
 [System.Security.SecurityCritical]  // auto-generated 
 private static bool IsModKey(Win32Native.InputRecord ir) { 
     // We should also skip over Shift, Control, and Alt, as well as caps lock.
     // Apparently we don't need to check for 0xA0 through 0xA5, which are keys like 
     // Left Control & Right Control. See the ConsoleKey enum for these values.
     short keyCode = ir.keyEvent.virtualKeyCode;
     return ((keyCode >= 0x10 && keyCode <= 0x12)
             || keyCode == 0x14 || keyCode == 0x90 || keyCode == 0x91); 
 }
		internal static extern bool GetVersionEx(Win32Native.OSVERSIONINFOEX osVer);
            internal MutexTryCodeHelper(bool initiallyOwned,MutexCleanupInfo cleanupInfo, String name, Win32Native.SECURITY_ATTRIBUTES secAttrs, Mutex mutex)
            {
                Contract.Assert(name == null || name.Length != 0);

                m_initiallyOwned = initiallyOwned;
                m_cleanupInfo = cleanupInfo;
                m_name = name;
                m_secAttrs = secAttrs;
                m_mutex = mutex;
            }
Exemple #27
0
        internal Mutex(bool initiallyOwned, String name, out bool createdNew, Win32Native.SECURITY_ATTRIBUTES secAttrs) 
        {
            if (name != null)
            {
#if PLATFORM_UNIX
                throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_NamedSynchronizationPrimitives"));
#else
                if (System.IO.Path.MaxPath < name.Length)
                {
                    throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", name));
                }
#endif
            }
            Contract.EndContractBlock();

            CreateMutexWithGuaranteedCleanup(initiallyOwned, name, out createdNew, secAttrs);
        }
        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)
        {
            // msgPath must be safe to hand back to untrusted code.

            _fileName = msgPath;  // To handle odd cases of finalizing partially constructed objects.
            _exposedHandle = false;

            if (path == null)
                throw new ArgumentNullException("path", Environment.GetResourceString("ArgumentNull_Path"));
            if (path.Length == 0)
                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));

            BCLDebug.Assert(!useRights, "Specifying FileSystemRights is not supported on this platform!");
          
            // 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";
            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 (!useRights && (access & FileAccess.Write) == 0) { 
                if (mode==FileMode.Truncate || mode==FileMode.CreateNew || mode==FileMode.Create || mode==FileMode.Append) {
                    // No write access
                    if (!useRights)
                        throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_InvalidFileMode&AccessCombo"), mode, access));
                }
            }


            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.
            String filePath = Path.GetFullPathInternal(path);

            _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 (!useRights && (access & FileAccess.Read) != 0) {
                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 (!useRights && (access & FileAccess.Write) != 0) { 
                if (mode==FileMode.Append)
                    secAccess = secAccess | FileIOPermissionAccess.Append;
                else
                    secAccess = secAccess | FileIOPermissionAccess.Write;
            }

            new FileIOPermission(secAccess, new String[] { filePath }, false, false).Demand();
            // 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;
            
            // Don't pop up a dialog for reading from an emtpy floppy drive
            int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
            try {
                _handle = Win32Native.SafeCreateFile(filePath, 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 (!useRights) {
                _canRead = (access & FileAccess.Read) != 0;
                _canWrite = (access & FileAccess.Write) != 0;
            }

            _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;
            }
        }
 internal static bool IsFile(Win32Native.WIN32_FIND_DATA data)
 {
     return (0 == (data.dwFileAttributes & 0x10));
 }
Exemple #30
0
 public RegistryTimeZoneInformation(Win32Native.TimeZoneInformation tzi) {
     Bias = tzi.Bias;
     StandardDate = tzi.StandardDate;
     StandardBias = tzi.StandardBias;
     DaylightDate = tzi.DaylightDate;
     DaylightBias = tzi.DaylightBias;
 }
 internal static bool IsDir(Win32Native.WIN32_FIND_DATA data)
 {
     return ((((data.dwFileAttributes & 0x10) != 0) && !data.cFileName.Equals(".")) && !data.cFileName.Equals(".."));
 }
 private static extern bool InternalGetNlsVersionEx(IntPtr handle, IntPtr handleOrigin, String localeName, ref Win32Native.NlsVersionInfoEx lpNlsVersionInformation);
Exemple #33
0
        internal void CreateMutexWithGuaranteedCleanup(bool initiallyOwned, String name, out bool createdNew, Win32Native.SECURITY_ATTRIBUTES secAttrs)
        {
#if FEATURE_LEGACYNETCF
            if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8)
                name = WinCEObjectNameQuirk(name);
#endif

            RuntimeHelpers.CleanupCode cleanupCode = new RuntimeHelpers.CleanupCode(MutexCleanupCode);
            MutexCleanupInfo cleanupInfo = new MutexCleanupInfo(null, false);
            MutexTryCodeHelper tryCodeHelper = new MutexTryCodeHelper(initiallyOwned, cleanupInfo, name, secAttrs, this);
            RuntimeHelpers.TryCode tryCode = new RuntimeHelpers.TryCode(tryCodeHelper.MutexTryCode);
            RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(
                tryCode,
                cleanupCode,
                cleanupInfo);             
            createdNew = tryCodeHelper.m_newMutex;
        }