Imported Upstream version 4.0.0~alpha1

Former-commit-id: 806294f5ded97629b74c85c09952f2a74fe182d9
This commit is contained in:
Jo Shields
2015-04-07 09:35:12 +01:00
parent 283343f570
commit 3c1f479b9d
22469 changed files with 2931443 additions and 869343 deletions

View File

@ -0,0 +1,30 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//
// File: RegistryOptions.cs
//
// <OWNER>[....]</OWNER>
//
// Implements Microsoft.Win32.RegistryOptions
//
// ======================================================================================
#if !FEATURE_PAL
namespace Microsoft.Win32 {
using System;
[Flags]
public enum RegistryOptions {
None = Win32Native.REG_OPTION_NON_VOLATILE, // 0x0000
Volatile = Win32Native.REG_OPTION_VOLATILE, // 0x0001
///
/// Consider exposing more options in a future release. Users can access this
/// functionality by calling [RegistryKey].Handle and pinvoking
///
/// CreateLink = Win32Native.REG_OPTION_CREATE_LINK, // 0x0002
/// BackupRestore = Win32Native.REG_OPTION_BACKUP_RESTORE,// 0x0004
};
}
#endif // !FEATURE_PAL

View File

@ -0,0 +1,21 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace Microsoft.Win32 {
[System.Runtime.InteropServices.ComVisible(true)]
public enum RegistryValueKind {
String = Win32Native.REG_SZ,
ExpandString = Win32Native.REG_EXPAND_SZ,
Binary = Win32Native.REG_BINARY,
DWord = Win32Native.REG_DWORD,
MultiString = Win32Native.REG_MULTI_SZ,
QWord = Win32Native.REG_QWORD,
Unknown = 0, // REG_NONE is defined as zero but BCL
[System.Runtime.InteropServices.ComVisible(false)]
None = unchecked((int)0xFFFFFFFF), // mistakingly overrode this value.
} // Now instead of using Win32Native.REG_NONE we use "-1" and play games internally.
}

View File

@ -0,0 +1,24 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//
// File: RegistryOptions.cs
//
// <OWNER>[....]</OWNER>
//
// Implements Microsoft.Win32.RegistryView
//
// ======================================================================================
#if !FEATURE_PAL
namespace Microsoft.Win32 {
using System;
public enum RegistryView {
Default = 0, // 0x0000 operate on the default registry view
Registry64 = Win32Native.KEY_WOW64_64KEY, // 0x0100 operate on the 64-bit registry view
Registry32 = Win32Native.KEY_WOW64_32KEY, // 0x0200 operate on the 32-bit registry view
};
}
#endif // !FEATURE_PAL

View File

@ -0,0 +1,179 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//-------------------------------------------------------------
// FusionInterfaces.cs
//
// This implements wrappers to Fusion interfaces
//-------------------------------------------------------------
namespace Microsoft.Win32
{
using System;
using System.IO;
using System.Collections;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Globalization;
using StringBuilder = System.Text.StringBuilder;
//-------------------------------------------------------------
// Interfaces defined by fusion
//-------------------------------------------------------------
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("21b8916c-f28e-11d2-a473-00c04f8ef448")]
interface IAssemblyEnum
{
[PreserveSig()]
int GetNextAssembly(out IApplicationContext ppAppCtx, out IAssemblyName ppName, uint dwFlags);
[PreserveSig()]
int Reset();
[PreserveSig()]
int Clone(out IAssemblyEnum ppEnum);
}
[ComImport,InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("7c23ff90-33af-11d3-95da-00a024a85b51")]
interface IApplicationContext
{
void SetContextNameObject(IAssemblyName pName);
void GetContextNameObject(out IAssemblyName ppName);
void Set([MarshalAs(UnmanagedType.LPWStr)] String szName, int pvValue, uint cbValue, uint dwFlags);
void Get([MarshalAs(UnmanagedType.LPWStr)] String szName, out int pvValue, ref uint pcbValue, uint dwFlags);
void GetDynamicDirectory(out int wzDynamicDir, ref uint pdwSize);
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("CD193BC0-B4BC-11d2-9833-00C04FC31D2E")]
interface IAssemblyName
{
[PreserveSig()]
int SetProperty(uint PropertyId, IntPtr pvProperty, uint cbProperty);
[PreserveSig()]
int GetProperty(uint PropertyId, IntPtr pvProperty, ref uint pcbProperty);
[PreserveSig()]
int Finalize();
[PreserveSig()]
int GetDisplayName(IntPtr szDisplayName, ref uint pccDisplayName, uint dwDisplayFlags);
[PreserveSig()]
int BindToObject(Object /*REFIID*/ refIID,
Object /*IAssemblyBindSink*/ pAsmBindSink,
IApplicationContext pApplicationContext,
[MarshalAs(UnmanagedType.LPWStr)] String szCodeBase,
Int64 llFlags,
int pvReserved,
uint cbReserved,
out int ppv);
[PreserveSig()]
int GetName(out uint lpcwBuffer, out int pwzName);
[PreserveSig()]
int GetVersion(out uint pdwVersionHi, out uint pdwVersionLow);
[PreserveSig()]
int IsEqual(IAssemblyName pName, uint dwCmpFlags);
[PreserveSig()]
int Clone(out IAssemblyName pName);
}
internal static class ASM_CACHE
{
public const uint ZAP = 0x1;
public const uint GAC = 0x2;
public const uint DOWNLOAD = 0x4;
}
internal static class CANOF
{
public const uint PARSE_DISPLAY_NAME = 0x1;
public const uint SET_DEFAULT_VALUES = 0x2;
}
internal static class ASM_NAME
{
public const uint PUBLIC_KEY = 0;
public const uint PUBLIC_KEY_TOKEN = PUBLIC_KEY + 1;
public const uint HASH_VALUE = PUBLIC_KEY_TOKEN + 1;
public const uint NAME = HASH_VALUE + 1;
public const uint MAJOR_VERSION = NAME + 1;
public const uint MINOR_VERSION = MAJOR_VERSION + 1;
public const uint BUILD_NUMBER = MINOR_VERSION + 1;
public const uint REVISION_NUMBER = BUILD_NUMBER + 1;
public const uint CULTURE = REVISION_NUMBER + 1;
public const uint PROCESSOR_ID_ARRAY = CULTURE + 1;
public const uint OSINFO_ARRAY = PROCESSOR_ID_ARRAY + 1;
public const uint HASH_ALGID = OSINFO_ARRAY + 1;
public const uint ALIAS = HASH_ALGID + 1;
public const uint CODEBASE_URL = ALIAS + 1;
public const uint CODEBASE_LASTMOD = CODEBASE_URL + 1;
public const uint NULL_PUBLIC_KEY = CODEBASE_LASTMOD + 1;
public const uint NULL_PUBLIC_KEY_TOKEN = NULL_PUBLIC_KEY + 1;
public const uint CUSTOM = NULL_PUBLIC_KEY_TOKEN + 1;
public const uint NULL_CUSTOM = CUSTOM + 1;
public const uint MVID = NULL_CUSTOM + 1;
public const uint _32_BIT_ONLY = MVID + 1;
public const uint MAX_PARAMS = _32_BIT_ONLY + 1;
}
internal static class Fusion
{
[System.Security.SecurityCritical] // auto-generated
public static void ReadCache(ArrayList alAssems, String name, uint nFlag)
{
IAssemblyEnum aEnum = null;
IAssemblyName aName = null;
IAssemblyName aNameEnum = null;
IApplicationContext AppCtx = null;
int hr;
if (name != null)
{
hr = Win32Native.CreateAssemblyNameObject(out aNameEnum, name, CANOF.PARSE_DISPLAY_NAME, IntPtr.Zero);
if (hr != 0)
Marshal.ThrowExceptionForHR(hr);
}
hr = Win32Native.CreateAssemblyEnum(out aEnum, AppCtx, aNameEnum, nFlag, IntPtr.Zero);
if (hr != 0)
Marshal.ThrowExceptionForHR(hr);
for (; ; )
{
hr = aEnum.GetNextAssembly(out AppCtx, out aName, 0);
if (hr != 0)
{
if (hr < 0)
Marshal.ThrowExceptionForHR(hr);
break;
}
String sDisplayName = GetDisplayName(aName, 0);
if (sDisplayName == null)
continue;
alAssems.Add(sDisplayName);
} // for (;;)
}
[System.Security.SecuritySafeCritical] // auto-generated
static unsafe String GetDisplayName(IAssemblyName aName, uint dwDisplayFlags)
{
uint iLen=0;
String sDisplayName = null;
aName.GetDisplayName((IntPtr)0, ref iLen, dwDisplayFlags);
if (iLen > 0) {
IntPtr pDisplayName=(IntPtr)0;
// Do some memory allocating here
// We need to assume that a wide character is 2 bytes.
byte[] data = new byte[((int)iLen+1)*2];
fixed (byte *dataptr = data) {
pDisplayName = new IntPtr((void *) dataptr);
aName.GetDisplayName(pDisplayName, ref iLen, dwDisplayFlags);
sDisplayName = Marshal.PtrToStringUni(pDisplayName);
}
}
return sDisplayName;
}
}
}

View File

@ -0,0 +1,137 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: OAVariantLib
**
**
** Purpose: This class only exists to provide support for
** implenting IDispatch on managed objects. It is
** used to provide OleAut style coercion rules.
**
**
===========================================================*/
namespace Microsoft.Win32 {
using System;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using CultureInfo = System.Globalization.CultureInfo;
internal static class OAVariantLib
{
#region Constants
// Constants for VariantChangeType from OleAuto.h
public const int NoValueProp = 0x01;
public const int AlphaBool = 0x02;
public const int NoUserOverride = 0x04;
public const int CalendarHijri = 0x08;
public const int LocalBool = 0x10;
internal static readonly Type [] ClassTypes = {
typeof(Empty),
typeof(void),
typeof(Boolean),
typeof(Char),
typeof(SByte),
typeof(Byte),
typeof(Int16),
typeof(UInt16),
typeof(Int32),
typeof(UInt32),
typeof(Int64),
typeof(UInt64),
typeof(Single),
typeof(Double),
typeof(String),
typeof(void),
typeof(DateTime),
typeof(TimeSpan),
typeof(Object),
typeof(Decimal),
null, // Enums - what do we do here?
typeof(Missing),
typeof(DBNull),
};
// Keep these numbers in [....] w/ the above array.
private const int CV_OBJECT=0x12;
#endregion
#region Internal Methods
/**
* Changes a Variant from one type to another, calling the OLE
* Automation VariantChangeTypeEx routine. Note the legal types here are
* restricted to the subset of what can be legally found in a VB
* Variant and the types that CLR supports explicitly in the
* CLR Variant class.
*/
[System.Security.SecurityCritical] // auto-generated
internal static Variant ChangeType(Variant source, Type targetClass, short options, CultureInfo culture)
{
if (targetClass == null)
throw new ArgumentNullException("targetClass");
if (culture == null)
throw new ArgumentNullException("culture");
Variant result = new Variant ();
ChangeTypeEx(ref result, ref source,
#if FEATURE_USE_LCID
culture.LCID,
#else
// @CORESYSTODO: what does CoreSystem expect for this argument?
0,
#endif
targetClass.TypeHandle.Value, GetCVTypeFromClass(targetClass), options);
return result;
}
#endregion
#region Private Helpers
private static int GetCVTypeFromClass(Type ctype)
{
Contract.Requires(ctype != null);
#if _DEBUG
BCLDebug.Assert(ClassTypes[CV_OBJECT] == typeof(Object), "OAVariantLib::ClassTypes[CV_OBJECT] == Object.class");
#endif
int cvtype=-1;
for (int i=0; i<ClassTypes.Length; i++) {
if (ctype.Equals(ClassTypes[i])) {
cvtype=i;
break;
}
}
// OleAut Binder works better if unrecognized
// types were changed to Object. So don't throw here.
if (cvtype == -1)
cvtype = CV_OBJECT;
return cvtype;
}
#endregion
#region Private FCalls
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ResourceExposure(ResourceScope.None)]
private static extern void ChangeTypeEx(ref Variant result, ref Variant source, int lcid, IntPtr typeHandle, int cvType, short flags);
#endregion
}
}

View File

@ -0,0 +1,190 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
#if FEATURE_WIN32_REGISTRY
namespace Microsoft.Win32 {
using System;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
#if !FEATURE_PAL
/**
* Registry encapsulation. Contains members representing all top level system
* keys.
*
* @security(checkClassLinking=on)
*/
//This class contains only static members and does not need to be serializable.
[ComVisible(true)]
public static class Registry {
[System.Security.SecuritySafeCritical] // auto-generated
static Registry()
{
}
/**
* Current User Key.
*
* This key should be used as the root for all user specific settings.
*/
[ResourceExposure(ResourceScope.Machine)]
public static readonly RegistryKey CurrentUser = RegistryKey.GetBaseKey(RegistryKey.HKEY_CURRENT_USER);
/**
* Local Machine Key.
*
* This key should be used as the root for all machine specific settings.
*/
[ResourceExposure(ResourceScope.Machine)]
public static readonly RegistryKey LocalMachine = RegistryKey.GetBaseKey(RegistryKey.HKEY_LOCAL_MACHINE);
/**
* Classes Root Key.
*
* This is the root key of class information.
*/
[ResourceExposure(ResourceScope.Machine)]
public static readonly RegistryKey ClassesRoot = RegistryKey.GetBaseKey(RegistryKey.HKEY_CLASSES_ROOT);
/**
* Users Root Key.
*
* This is the root of users.
*/
[ResourceExposure(ResourceScope.Machine)]
public static readonly RegistryKey Users = RegistryKey.GetBaseKey(RegistryKey.HKEY_USERS);
/**
* Performance Root Key.
*
* This is where dynamic performance data is stored on NT.
*/
[ResourceExposure(ResourceScope.Machine)]
public static readonly RegistryKey PerformanceData = RegistryKey.GetBaseKey(RegistryKey.HKEY_PERFORMANCE_DATA);
/**
* Current Config Root Key.
*
* This is where current configuration information is stored.
*/
[ResourceExposure(ResourceScope.Machine)]
public static readonly RegistryKey CurrentConfig = RegistryKey.GetBaseKey(RegistryKey.HKEY_CURRENT_CONFIG);
/**
* Dynamic Data Root Key.
*
* LEGACY: This is where dynamic performance data is stored on Win9X.
* This does not exist on NT.
*/
[ResourceExposure(ResourceScope.Machine)]
[Obsolete("The DynData registry key only works on Win9x, which is no longer supported by the CLR. On NT-based operating systems, use the PerformanceData registry key instead.")]
public static readonly RegistryKey DynData = RegistryKey.GetBaseKey(RegistryKey.HKEY_DYN_DATA);
//
// Following function will parse a keyName and returns the basekey for it.
// It will also store the subkey name in the out parameter.
// If the keyName is not valid, we will throw ArgumentException.
// The return value shouldn't be null.
//
[System.Security.SecurityCritical] // auto-generated
private static RegistryKey GetBaseKeyFromKeyName(string keyName, out string subKeyName) {
if( keyName == null) {
throw new ArgumentNullException("keyName");
}
string basekeyName;
int i = keyName.IndexOf('\\');
if( i != -1) {
basekeyName = keyName.Substring(0, i).ToUpper(System.Globalization.CultureInfo.InvariantCulture);
}
else {
basekeyName = keyName.ToUpper(System.Globalization.CultureInfo.InvariantCulture);
}
RegistryKey basekey = null;
switch(basekeyName) {
case "HKEY_CURRENT_USER":
basekey = Registry.CurrentUser;
break;
case "HKEY_LOCAL_MACHINE":
basekey = Registry.LocalMachine;
break;
case "HKEY_CLASSES_ROOT":
basekey = Registry.ClassesRoot;
break;
case "HKEY_USERS":
basekey = Registry.Users;
break;
case "HKEY_PERFORMANCE_DATA":
basekey = Registry.PerformanceData;
break;
case "HKEY_CURRENT_CONFIG":
basekey = Registry.CurrentConfig;
break;
case "HKEY_DYN_DATA":
basekey = RegistryKey.GetBaseKey(RegistryKey.HKEY_DYN_DATA);
break;
default:
throw new ArgumentException(Environment.GetResourceString("Arg_RegInvalidKeyName", "keyName"));
}
if( i == -1 || i == keyName.Length) {
subKeyName = string.Empty;
}
else {
subKeyName = keyName.Substring(i + 1, keyName.Length - i - 1);
}
return basekey;
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static object GetValue(string keyName, string valueName, object defaultValue ) {
string subKeyName;
RegistryKey basekey = GetBaseKeyFromKeyName(keyName, out subKeyName);
BCLDebug.Assert(basekey != null, "basekey can't be null.");
RegistryKey key = basekey.OpenSubKey(subKeyName);
if(key == null) { // if the key doesn't exist, do nothing
return null;
}
try {
return key.GetValue(valueName, defaultValue);
}
finally {
key.Close();
}
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void SetValue(string keyName, string valueName, object value ) {
SetValue(keyName, valueName, value, RegistryValueKind.Unknown);
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void SetValue(string keyName, string valueName, object value, RegistryValueKind valueKind ) {
string subKeyName;
RegistryKey basekey = GetBaseKeyFromKeyName(keyName, out subKeyName);
BCLDebug.Assert(basekey != null, "basekey can't be null!");
RegistryKey key = basekey.CreateSubKey(subKeyName);
BCLDebug.Assert(key != null, "An exception should be thrown if failed!");
try {
key.SetValue(valueName, value, valueKind);
}
finally {
key.Close();
}
}
}
#endif // !FEATURE_PAL
}
#endif // FEATURE_WIN32_REGISTRY

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,47 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: SafeFileHandle
**
**
** A wrapper for file handles
**
**
===========================================================*/
using System;
using System.Security;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using Microsoft.Win32;
namespace Microsoft.Win32.SafeHandles {
[System.Security.SecurityCritical] // auto-generated_required
public sealed class SafeFileHandle: SafeHandleZeroOrMinusOneIsInvalid {
private SafeFileHandle() : base(true)
{
}
public SafeFileHandle(IntPtr preexistingHandle, bool ownsHandle) : base(ownsHandle) {
SetHandle(preexistingHandle);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
override protected bool ReleaseHandle()
{
return Win32Native.CloseHandle(handle);
}
}
}

View File

@ -0,0 +1,47 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: SafeFileMappingHandle
**
**
** A wrapper for file handles
**
**
===========================================================*/
using System;
using System.Security;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
namespace Microsoft.Win32.SafeHandles
{
[System.Security.SecurityCritical] // auto-generated
internal sealed class SafeFileMappingHandle : SafeHandleZeroOrMinusOneIsInvalid
{
[System.Security.SecurityCritical] // auto-generated_required
internal SafeFileMappingHandle() : base(true) {}
// 0 is an Invalid Handle
[System.Security.SecurityCritical] // auto-generated_required
internal SafeFileMappingHandle(IntPtr handle, bool ownsHandle) : base (ownsHandle)
{
SetHandle(handle);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
override protected bool ReleaseHandle()
{
return Win32Native.CloseHandle(handle);
}
}
}

View File

@ -0,0 +1,37 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: SafeFindHandle
**
**
** A wrapper for find handles
**
**
===========================================================*/
using System;
using System.Security;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using Microsoft.Win32;
namespace Microsoft.Win32.SafeHandles {
[System.Security.SecurityCritical] // auto-generated
internal sealed class SafeFindHandle : SafeHandleZeroOrMinusOneIsInvalid
{
[System.Security.SecurityCritical] // auto-generated_required
internal SafeFindHandle() : base(true) {}
[System.Security.SecurityCritical]
override protected bool ReleaseHandle()
{
return Win32Native.FindClose(handle);
}
}
}

View File

@ -0,0 +1,35 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: SafeLibraryHandle
**
============================================================*/
namespace Microsoft.Win32 {
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
[System.Security.SecurityCritical] // auto-generated
[HostProtectionAttribute(MayLeakOnAbort = true)]
sealed internal class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid {
internal SafeLibraryHandle() : base(true) {}
[System.Security.SecurityCritical]
override protected bool ReleaseHandle()
{
return UnsafeNativeMethods.FreeLibrary(handle);
}
}
}

View File

@ -0,0 +1,29 @@
// <OWNER>clrbclc</OWNER>
namespace Microsoft.Win32.SafeHandles {
#if !FEATURE_PAL
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
[System.Security.SecurityCritical] // auto-generated
internal sealed class SafeLocalAllocHandle : SafeBuffer {
private SafeLocalAllocHandle () : base(true) {}
// 0 is an Invalid Handle
internal SafeLocalAllocHandle (IntPtr handle) : base (true) {
SetHandle(handle);
}
internal static SafeLocalAllocHandle InvalidHandle {
get { return new SafeLocalAllocHandle(IntPtr.Zero); }
}
[System.Security.SecurityCritical]
override protected bool ReleaseHandle()
{
return Win32Native.LocalFree(handle) == IntPtr.Zero;
}
}
#endif
}

View File

@ -0,0 +1,38 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
namespace Microsoft.Win32.SafeHandles
{
/// <summary>
/// Handle to a VM PEFile *
/// </summary>
[SecurityCritical]
internal sealed class SafePEFileHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private SafePEFileHandle() : base(true)
{
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SuppressUnmanagedCodeSecurity]
private static extern void ReleaseSafePEFileHandle(IntPtr peFile);
[SecurityCritical]
protected override bool ReleaseHandle()
{
ReleaseSafePEFileHandle(handle);
return true;
}
}
}

View File

@ -0,0 +1,46 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//
// File: SafeRegistryHandle.cs
//
// <OWNER>[....]</OWNER>
//
// Implements Microsoft.Win32.SafeHandles.SafeRegistryHandle
//
// ======================================================================================
#if !FEATURE_PAL
namespace Microsoft.Win32.SafeHandles {
using System;
using System.Security;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
[System.Security.SecurityCritical]
public sealed class SafeRegistryHandle : SafeHandleZeroOrMinusOneIsInvalid {
[System.Security.SecurityCritical]
internal SafeRegistryHandle() : base(true) {}
[System.Security.SecurityCritical]
public SafeRegistryHandle(IntPtr preexistingHandle, bool ownsHandle) : base(ownsHandle) {
SetHandle(preexistingHandle);
}
[System.Security.SecurityCritical]
override protected bool ReleaseHandle() {
return (RegCloseKey(handle) == Win32Native.ERROR_SUCCESS);
}
[DllImport(Win32Native.ADVAPI32),
SuppressUnmanagedCodeSecurity,
ResourceExposure(ResourceScope.None),
ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static extern int RegCloseKey(IntPtr hKey);
}
}
#endif // !FEATURE_PAL

View File

@ -0,0 +1,54 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: SafeViewOfFileHandle
**
**
** A wrapper for file handles
**
**
===========================================================*/
using System;
using System.Security;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
namespace Microsoft.Win32.SafeHandles
{
[System.Security.SecurityCritical] // auto-generated
internal sealed class SafeViewOfFileHandle : SafeHandleZeroOrMinusOneIsInvalid
{
[System.Security.SecurityCritical] // auto-generated_required
internal SafeViewOfFileHandle() : base(true) {}
// 0 is an Invalid Handle
[System.Security.SecurityCritical] // auto-generated_required
internal SafeViewOfFileHandle(IntPtr handle, bool ownsHandle) : base (ownsHandle) {
SetHandle(handle);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
override protected bool ReleaseHandle()
{
if (Win32Native.UnmapViewOfFile(handle))
{
handle = IntPtr.Zero;
return true;
}
return false;
}
}
}

View File

@ -0,0 +1,99 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: SafeWaitHandle
**
**
** A wrapper for Win32 events (mutexes, auto reset events, and
** manual reset events). Used by WaitHandle.
**
**
===========================================================*/
using System;
using System.Security;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using Microsoft.Win32;
using System.Threading;
namespace Microsoft.Win32.SafeHandles {
[System.Security.SecurityCritical] // auto-generated_required
public sealed class SafeWaitHandle : SafeHandleZeroOrMinusOneIsInvalid
{
// Special case flags for Mutexes enables workaround for known OS bug at
// http://support.microsoft.com/default.aspx?scid=kb;en-us;889318
// One machine-wide mutex serializes all OpenMutex and CloseHandle operations.
// bIsMutex: if true, we need to grab machine-wide mutex before doing any Close ops.
// Initialized to false by the runtime.
private bool bIsMutex;
// bIsMutex: if true, we need to avoid grabbing the machine-wide mutex before Close ops,
// since that mutex is, of course, this very handle.
// Initialized to false by the runtime.
private bool bIsReservedMutex;
// Called by P/Invoke marshaler
private SafeWaitHandle() : base(true)
{
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public SafeWaitHandle(IntPtr existingHandle, bool ownsHandle) : base(ownsHandle)
{
SetHandle(existingHandle);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
override protected bool ReleaseHandle()
{
#if !FEATURE_CORECLR
if (!bIsMutex || Environment.HasShutdownStarted)
return Win32Native.CloseHandle(handle);
bool bReturn = false;
bool bMutexObtained = false;
try
{
if (!bIsReservedMutex)
{
Mutex.AcquireReservedMutex(ref bMutexObtained);
}
bReturn = Win32Native.CloseHandle(handle);
}
finally
{
if (bMutexObtained)
Mutex.ReleaseReservedMutex();
}
return bReturn;
#else
return Win32Native.CloseHandle(handle);
#endif
}
internal void SetAsMutex()
{
bIsMutex = true;
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal void SetAsReservedMutex()
{
bIsReservedMutex = true;
}
}
}

View File

@ -0,0 +1,113 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//
// Abstract derivations of SafeHandle designed to provide the common
// functionality supporting Win32 handles. More specifically, they describe how
// an invalid handle looks (for instance, some handles use -1 as an invalid
// handle value, others use 0).
//
// Further derivations of these classes can specialise this even further (e.g.
// file or registry handles).
//
//
namespace Microsoft.Win32.SafeHandles
{
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Security.Permissions;
using System.Runtime.ConstrainedExecution;
// Class of safe handle which uses 0 or -1 as an invalid handle.
[System.Security.SecurityCritical] // auto-generated_required
#if !FEATURE_CORECLR
[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
#endif
public abstract class SafeHandleZeroOrMinusOneIsInvalid : SafeHandle
{
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
protected SafeHandleZeroOrMinusOneIsInvalid(bool ownsHandle) : base(IntPtr.Zero, ownsHandle)
{
}
#if FEATURE_CORECLR
// A default constructor is needed to satisfy CoreCLR inheritence rules. It should not be called at runtime
protected SafeHandleZeroOrMinusOneIsInvalid()
{
throw new NotImplementedException();
}
#endif // FEATURE_CORECLR
public override bool IsInvalid {
[System.Security.SecurityCritical]
get { return handle.IsNull() || handle == new IntPtr(-1); }
}
}
// Class of safe handle which uses only -1 as an invalid handle.
[System.Security.SecurityCritical] // auto-generated_required
#if !FEATURE_CORECLR
[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
#endif
public abstract class SafeHandleMinusOneIsInvalid : SafeHandle
{
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
protected SafeHandleMinusOneIsInvalid(bool ownsHandle) : base(new IntPtr(-1), ownsHandle)
{
}
#if FEATURE_CORECLR
// A default constructor is needed to satisfy CoreCLR inheritence rules. It should not be called at runtime
protected SafeHandleMinusOneIsInvalid()
{
throw new NotImplementedException();
}
#endif // FEATURE_CORECLR
public override bool IsInvalid {
[System.Security.SecurityCritical]
get { return handle == new IntPtr(-1); }
}
}
// Class of critical handle which uses 0 or -1 as an invalid handle.
[System.Security.SecurityCritical] // auto-generated_required
#if !FEATURE_CORECLR
[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
#endif
public abstract class CriticalHandleZeroOrMinusOneIsInvalid : CriticalHandle
{
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
protected CriticalHandleZeroOrMinusOneIsInvalid() : base(IntPtr.Zero)
{
}
public override bool IsInvalid {
[System.Security.SecurityCritical]
get { return handle.IsNull() || handle == new IntPtr(-1); }
}
}
// Class of critical handle which uses only -1 as an invalid handle.
[System.Security.SecurityCritical] // auto-generated_required
#if !FEATURE_CORECLR
[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
#endif
public abstract class CriticalHandleMinusOneIsInvalid : CriticalHandle
{
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
protected CriticalHandleMinusOneIsInvalid() : base(new IntPtr(-1))
{
}
public override bool IsInvalid {
[System.Security.SecurityCritical]
get { return handle == new IntPtr(-1); }
}
}
}

View File

@ -0,0 +1,254 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: UnsafeNativeMethods
**
============================================================*/
namespace Microsoft.Win32 {
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Diagnostics.Tracing;
[System.Security.SecurityCritical] // auto-generated
[SuppressUnmanagedCodeSecurityAttribute()]
internal static class UnsafeNativeMethods {
[DllImport(Win32Native.KERNEL32, EntryPoint="GetTimeZoneInformation", SetLastError = true, ExactSpelling = true)]
[ResourceExposure(ResourceScope.None)]
internal static extern int GetTimeZoneInformation(out Win32Native.TimeZoneInformation lpTimeZoneInformation);
[DllImport(Win32Native.KERNEL32, EntryPoint="GetDynamicTimeZoneInformation", SetLastError = true, ExactSpelling = true)]
[ResourceExposure(ResourceScope.None)]
internal static extern int GetDynamicTimeZoneInformation(out Win32Native.DynamicTimeZoneInformation lpDynamicTimeZoneInformation);
//
// BOOL GetFileMUIPath(
// DWORD dwFlags,
// PCWSTR pcwszFilePath,
// PWSTR pwszLanguage,
// PULONG pcchLanguage,
// PWSTR pwszFileMUIPath,
// PULONG pcchFileMUIPath,
// PULONGLONG pululEnumerator
// );
//
[DllImport(Win32Native.KERNEL32, EntryPoint="GetFileMUIPath", SetLastError = true, ExactSpelling = true)]
[ResourceExposure(ResourceScope.Machine)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetFileMUIPath(
int flags,
[MarshalAs(UnmanagedType.LPWStr)]
String filePath,
[MarshalAs(UnmanagedType.LPWStr)]
StringBuilder language,
ref int languageLength,
[MarshalAs(UnmanagedType.LPWStr)]
StringBuilder fileMuiPath,
ref int fileMuiPathLength,
ref Int64 enumerator);
[DllImport(Win32Native.USER32, EntryPoint="LoadStringW", SetLastError=true, CharSet=CharSet.Unicode, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
[ResourceExposure(ResourceScope.Process)]
internal static extern int LoadString(SafeLibraryHandle handle, int id, StringBuilder buffer, int bufferLength);
[DllImport(Win32Native.KERNEL32, CharSet=System.Runtime.InteropServices.CharSet.Unicode, SetLastError=true)]
[ResourceExposure(ResourceScope.Machine)]
internal static extern SafeLibraryHandle LoadLibraryEx(string libFilename, IntPtr reserved, int flags);
[DllImport(Win32Native.KERNEL32, CharSet=System.Runtime.InteropServices.CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
[ResourceExposure(ResourceScope.None)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static extern bool FreeLibrary(IntPtr hModule);
[SecurityCritical]
[SuppressUnmanagedCodeSecurityAttribute()]
internal static unsafe class ManifestEtw
{
//
// Constants error coded returned by ETW APIs
//
// The event size is larger than the allowed maximum (64k - header).
internal const int ERROR_ARITHMETIC_OVERFLOW = 534;
// Occurs when filled buffers are trying to flush to disk,
// but disk IOs are not happening fast enough.
// This happens when the disk is slow and event traffic is heavy.
// Eventually, there are no more free (empty) buffers and the event is dropped.
internal const int ERROR_NOT_ENOUGH_MEMORY = 8;
internal const int ERROR_MORE_DATA = 0xEA;
//
// ETW Methods
//
internal const int EVENT_CONTROL_CODE_DISABLE_PROVIDER = 0;
internal const int EVENT_CONTROL_CODE_ENABLE_PROVIDER = 1;
internal const int EVENT_CONTROL_CODE_CAPTURE_STATE = 2;
//
// Callback
//
[SecurityCritical]
internal unsafe delegate void EtwEnableCallback(
[In] ref Guid sourceId,
[In] int isEnabled,
[In] byte level,
[In] long matchAnyKeywords,
[In] long matchAllKeywords,
[In] EVENT_FILTER_DESCRIPTOR* filterData,
[In] void* callbackContext
);
//
// Registration APIs
//
[SecurityCritical]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventRegister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
internal static extern unsafe uint EventRegister(
[In] ref Guid providerId,
[In]EtwEnableCallback enableCallback,
[In]void* callbackContext,
[In][Out]ref long registrationHandle
);
//
[SecurityCritical]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventUnregister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
internal static extern uint EventUnregister([In] long registrationHandle);
//
// Writing (Publishing/Logging) APIs
//
//
[SecurityCritical]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventWrite", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
internal static extern unsafe int EventWrite(
[In] long registrationHandle,
[In] ref EventDescriptor eventDescriptor,
[In] int userDataCount,
[In] EventProvider.EventData* userData
);
[SecurityCritical]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventWriteString", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
internal static extern unsafe int EventWriteString(
[In] long registrationHandle,
[In] byte level,
[In] long keyword,
[In] string msg
);
[StructLayout(LayoutKind.Sequential)]
unsafe internal struct EVENT_FILTER_DESCRIPTOR
{
public long Ptr;
public int Size;
public int Type;
};
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventWriteTransfer", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SuppressUnmanagedCodeSecurityAttribute] // Don't do security checks
internal static extern int EventWriteTransfer(
[In] long registrationHandle,
[In] ref EventDescriptor eventDescriptor,
[In] Guid* activityId,
[In] Guid* relatedActivityId,
[In] int userDataCount,
[In] EventProvider.EventData* userData
);
internal enum ActivityControl : uint
{
EVENT_ACTIVITY_CTRL_GET_ID = 1,
EVENT_ACTIVITY_CTRL_SET_ID = 2,
EVENT_ACTIVITY_CTRL_CREATE_ID = 3,
EVENT_ACTIVITY_CTRL_GET_SET_ID = 4,
EVENT_ACTIVITY_CTRL_CREATE_SET_ID = 5
};
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventActivityIdControl", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SuppressUnmanagedCodeSecurityAttribute] // Don't do security checks
internal static extern int EventActivityIdControl([In] ActivityControl ControlCode, [In][Out] ref Guid ActivityId);
// Support for EnumerateTraceGuidsEx
internal enum TRACE_QUERY_INFO_CLASS
{
TraceGuidQueryList,
TraceGuidQueryInfo,
TraceGuidQueryProcess,
TraceStackTracingInfo,
MaxTraceSetInfoClass
};
internal struct TRACE_GUID_INFO
{
public int InstanceCount;
public int Reserved;
};
internal struct TRACE_PROVIDER_INSTANCE_INFO
{
public int NextOffset;
public int EnableCount;
public int Pid;
public int Flags;
};
internal struct TRACE_ENABLE_INFO
{
public int IsEnabled;
public byte Level;
public byte Reserved1;
public ushort LoggerId;
public int EnableProperty;
public int Reserved2;
public long MatchAnyKeyword;
public long MatchAllKeyword;
};
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EnumerateTraceGuidsEx", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SuppressUnmanagedCodeSecurityAttribute] // Don't do security checks
internal static extern int EnumerateTraceGuidsEx(
TRACE_QUERY_INFO_CLASS TraceQueryInfoClass,
void* InBuffer,
int InBufferSize,
void* OutBuffer,
int OutBufferSize,
ref int ReturnLength);
}
#if !FEATURE_PAL && !FEATURE_CORECLR
[SecurityCritical]
[DllImport("combase.dll", PreserveSig = true)]
internal static extern int RoGetActivationFactory(
[MarshalAs(UnmanagedType.HString)] string activatableClassId,
[In] ref Guid iid,
[Out,MarshalAs(UnmanagedType.IInspectable)] out Object factory);
#endif
}
}

View File

@ -0,0 +1 @@
4a257e119ae905e5fb449f7709050e0aa08969be