Merge pull request #3213 from henricm/fix-for-win-securestring-to-bstr
[mono.git] / mcs / class / referencesource / System / compmod / microsoft / win32 / UnsafeNativeMethods.cs
1 //------------------------------------------------------------------------------
2 // <copyright file="UnsafeNativeMethods.cs" company="Microsoft">
3 //     Copyright (c) Microsoft Corporation.  All rights reserved.
4 // </copyright>
5 //------------------------------------------------------------------------------
6
7 namespace Microsoft.Win32 {
8     using System.Runtime.InteropServices;
9     using System.Runtime.Versioning;
10     using System;
11     using System.Diagnostics;
12     using System.Diagnostics.CodeAnalysis;
13 #if !SILVERLIGHT
14     using System.Threading;
15     using System.Security.Permissions;
16     using System.Collections;
17     using System.IO;
18     using System.Text;
19     using Microsoft.Win32;
20     using Microsoft.Win32.SafeHandles;
21     using System.Configuration; 
22
23     [HostProtectionAttribute(MayLeakOnAbort = true)]
24     [System.Security.SuppressUnmanagedCodeSecurity]
25 #endif // !SILVERLIGHT
26     internal static class UnsafeNativeMethods {
27
28         [DllImport(ExternDll.Kernel32, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
29         [ResourceExposure(ResourceScope.Machine)]
30         public static extern IntPtr GetStdHandle(int type);
31
32 #if !FEATURE_PAL && !FEATURE_CORESYSTEM
33         [DllImport(ExternDll.User32, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
34         [ResourceExposure(ResourceScope.None)]
35         public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
36
37         [DllImport(ExternDll.User32, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
38         [ResourceExposure(ResourceScope.Machine)]
39         public static extern IntPtr GetDC(IntPtr hWnd);
40
41         [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage", Justification = "reviewed")]
42         [DllImport(ExternDll.Gdi32, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
43         [ResourceExposure(ResourceScope.None)]
44         public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
45
46         [DllImport(ExternDll.User32, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
47         [ResourceExposure(ResourceScope.None)]
48         public static extern int GetSystemMetrics(int nIndex);
49 #endif // !FEATURE_PAL && !FEATURE_CORESYSTEM
50
51 #if !SILVERLIGHT       
52         [DllImport(ExternDll.User32, ExactSpelling=true)]
53         [ResourceExposure(ResourceScope.Process)]
54         public static extern IntPtr GetProcessWindowStation();
55         [DllImport(ExternDll.User32, SetLastError=true)]
56         [ResourceExposure(ResourceScope.None)]
57         public static extern bool GetUserObjectInformation(HandleRef hObj, int nIndex, [MarshalAs(UnmanagedType.LPStruct)] NativeMethods.USEROBJECTFLAGS pvBuffer, int nLength, ref int lpnLengthNeeded);
58         [DllImport(ExternDll.Kernel32, CharSet=System.Runtime.InteropServices.CharSet.Auto, BestFitMapping=false)]
59         [ResourceExposure(ResourceScope.Machine)]
60         public static extern IntPtr GetModuleHandle(string modName);
61         [DllImport(ExternDll.User32, CharSet=System.Runtime.InteropServices.CharSet.Auto, BestFitMapping=false)]
62         [ResourceExposure(ResourceScope.None)]
63         public static extern bool GetClassInfo(HandleRef hInst, string lpszClass, [In, Out] NativeMethods.WNDCLASS_I wc);
64
65         [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)]
66         [ResourceExposure(ResourceScope.None)]
67         public static extern bool IsWindow(HandleRef hWnd);
68
69         //SetClassLong won't work correctly for 64-bit: we should use SetClassLongPtr instead.  On
70         //32-bit, SetClassLongPtr is just #defined as SetClassLong.  SetClassLong really should 
71         //take/return int instead of IntPtr/HandleRef, but since we're running this only for 32-bit
72         //it'll be OK.
73         public static IntPtr SetClassLong(HandleRef hWnd, int nIndex, IntPtr dwNewLong) {
74             if (IntPtr.Size == 4) {
75                 return SetClassLongPtr32(hWnd, nIndex, dwNewLong);
76             }
77             return SetClassLongPtr64(hWnd, nIndex, dwNewLong);
78         }
79         [DllImport(ExternDll.User32, CharSet = System.Runtime.InteropServices.CharSet.Auto, EntryPoint = "SetClassLong")]
80         [ResourceExposure(ResourceScope.None)]
81         [SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable")]
82         public static extern IntPtr SetClassLongPtr32(HandleRef hwnd, int nIndex, IntPtr dwNewLong);
83         [SuppressMessage("Microsoft.Interoperability", "CA1400:PInvokeEntryPointsShouldExist")]
84         [DllImport(ExternDll.User32, CharSet = System.Runtime.InteropServices.CharSet.Auto, EntryPoint = "SetClassLongPtr")]
85         [ResourceExposure(ResourceScope.None)]
86         public static extern IntPtr SetClassLongPtr64(HandleRef hwnd, int nIndex, IntPtr dwNewLong);
87
88         //SetWindowLong won't work correctly for 64-bit: we should use SetWindowLongPtr instead.  On
89         //32-bit, SetWindowLongPtr is just #defined as SetWindowLong.  SetWindowLong really should 
90         //take/return int instead of IntPtr/HandleRef, but since we're running this only for 32-bit
91         //it'll be OK.
92         public static IntPtr SetWindowLong(HandleRef hWnd, int nIndex, HandleRef dwNewLong) 
93         {
94             if (IntPtr.Size == 4)
95             {
96                 return SetWindowLongPtr32(hWnd, nIndex, dwNewLong);
97             }
98             return SetWindowLongPtr64(hWnd, nIndex, dwNewLong);
99         }
100         [SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable")]
101         [DllImport(ExternDll.User32, CharSet = CharSet.Auto, EntryPoint = "SetWindowLong")]
102         [ResourceExposure(ResourceScope.None)]
103         public static extern IntPtr SetWindowLongPtr32(HandleRef hWnd, int nIndex, HandleRef dwNewLong);
104         [SuppressMessage("Microsoft.Interoperability", "CA1400:PInvokeEntryPointsShouldExist")]
105         [DllImport(ExternDll.User32, CharSet = CharSet.Auto, EntryPoint = "SetWindowLongPtr")]
106         [ResourceExposure(ResourceScope.None)]
107         public static extern IntPtr SetWindowLongPtr64(HandleRef hWnd, int nIndex, HandleRef dwNewLong);
108
109
110         [DllImport(ExternDll.User32, CharSet=System.Runtime.InteropServices.CharSet.Auto, SetLastError=true, BestFitMapping=false)]
111         [ResourceExposure(ResourceScope.None)]
112         public static extern short RegisterClass(NativeMethods.WNDCLASS wc);
113         [DllImport(ExternDll.User32, CharSet=System.Runtime.InteropServices.CharSet.Auto, SetLastError=true, BestFitMapping=false)]
114         [ResourceExposure(ResourceScope.None)]
115         public static extern short UnregisterClass(string lpClassName, HandleRef hInstance);
116         [DllImport(ExternDll.User32, CharSet=System.Runtime.InteropServices.CharSet.Auto, SetLastError=true, BestFitMapping=true)]
117         [ResourceExposure(ResourceScope.Process)]
118         public static extern IntPtr CreateWindowEx(int exStyle, string lpszClassName, string lpszWindowName, int style, int x, int y, int width,
119                                               int height, HandleRef hWndParent, HandleRef hMenu, HandleRef hInst, [MarshalAs(UnmanagedType.AsAny)] object pvParam);
120         [DllImport(ExternDll.User32, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
121         [ResourceExposure(ResourceScope.None)]
122         public static extern IntPtr SendMessage(HandleRef hWnd, int msg, IntPtr wParam, IntPtr lParam);
123         [DllImport(ExternDll.Kernel32, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
124         [ResourceExposure(ResourceScope.Process)]
125         public static extern bool SetConsoleCtrlHandler(NativeMethods.ConHndlr handler, int add);
126         [DllImport(ExternDll.User32, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
127         [ResourceExposure(ResourceScope.None)]
128         public static extern IntPtr DefWindowProc(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
129
130         [DllImport(ExternDll.User32, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
131         [ResourceExposure(ResourceScope.Process)]
132         public static extern bool DestroyWindow(HandleRef hWnd);
133
134         [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)]
135         [ResourceExposure(ResourceScope.None)]
136         public static extern int MsgWaitForMultipleObjectsEx(int nCount, IntPtr pHandles, int dwMilliseconds, int dwWakeMask, int dwFlags);
137
138         [DllImport(ExternDll.User32, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
139         [ResourceExposure(ResourceScope.None)]
140         public static extern int DispatchMessage([In] ref NativeMethods.MSG msg);
141
142         [DllImport(ExternDll.User32, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
143         [ResourceExposure(ResourceScope.None)]
144         public static extern bool PeekMessage([In, Out] ref NativeMethods.MSG msg, HandleRef hwnd, int msgMin, int msgMax, int remove);
145         [DllImport(ExternDll.User32, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
146         [ResourceExposure(ResourceScope.None)]
147         public static extern IntPtr SetTimer(HandleRef hWnd, HandleRef nIDEvent, int uElapse, HandleRef lpTimerProc);
148
149         [DllImport(ExternDll.User32, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
150         [ResourceExposure(ResourceScope.None)]
151         public static extern bool KillTimer(HandleRef hwnd, HandleRef idEvent);
152
153         [DllImport(ExternDll.User32, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
154         [ResourceExposure(ResourceScope.None)]
155         public static extern bool TranslateMessage([In, Out] ref NativeMethods.MSG msg);
156         [DllImport(ExternDll.Kernel32, CharSet=System.Runtime.InteropServices.CharSet.Ansi, BestFitMapping=false)]
157         [ResourceExposure(ResourceScope.Process)]
158         public static extern IntPtr GetProcAddress(HandleRef hModule, string lpProcName);
159
160         [DllImport(ExternDll.User32, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
161         [ResourceExposure(ResourceScope.None)]
162         public static extern bool PostMessage(HandleRef hwnd, int msg, IntPtr wparam, IntPtr lparam);
163
164         [DllImport(ExternDll.Wtsapi32, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
165         [ResourceExposure(ResourceScope.None)]
166         public static extern bool WTSRegisterSessionNotification(HandleRef hWnd, int dwFlags);
167
168         [DllImport(ExternDll.Wtsapi32, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
169         [ResourceExposure(ResourceScope.None)]
170         public static extern bool WTSUnRegisterSessionNotification(HandleRef hWnd);
171
172         private static IntPtr GetCurrentProcessToken() { return new IntPtr(-4); }
173
174         private const int ERROR_SUCCESS = 0;
175
176         enum AppPolicyClrCompat
177         {
178             AppPolicyClrCompat_Others = 0,
179             AppPolicyClrCompat_ClassicDesktop = 1,
180             AppPolicyClrCompat_Universal = 2,
181             AppPolicyClrCompat_PackagedDesktop = 3
182         };
183
184         [DllImport(ExternDll.Kernel32, CharSet = CharSet.None, EntryPoint = "AppPolicyGetClrCompat")]
185         [System.Security.SecuritySafeCritical]
186         [return: MarshalAs(UnmanagedType.I4)]
187         private static extern Int32 _AppPolicyGetClrCompat(IntPtr processToken, out AppPolicyClrCompat appPolicyClrCompat);
188
189         private const int ERROR_INSUFFICIENT_BUFFER = 0x007A;
190         private const int ERROR_NO_PACKAGE_IDENTITY = 0x3d54;
191
192         // AppModel.h functions (Win8+)
193         [DllImport(ExternDll.Kernel32, CharSet = CharSet.None, EntryPoint = "GetCurrentPackageId")]
194         [System.Security.SecuritySafeCritical]
195         [return: MarshalAs(UnmanagedType.I4)]
196         private static extern Int32 _GetCurrentPackageId(ref Int32 pBufferLength, Byte[] pBuffer);
197
198         // Copied from Win32Native.cs
199         // Note - do NOT use this to call methods.  Use P/Invoke, which will
200         // do much better things w.r.t. marshaling, pinning memory, security 
201         // stuff, better interactions with thread aborts, etc.  This is used
202         // solely by DoesWin32MethodExist for avoiding try/catch EntryPointNotFoundException
203         // in scenarios where an OS Version check is insufficient
204         [DllImport(ExternDll.Kernel32, CharSet=CharSet.Ansi, BestFitMapping=false, SetLastError=true, ExactSpelling=true)]
205         [ResourceExposure(ResourceScope.None)]
206         private static extern IntPtr GetProcAddress(IntPtr hModule, String methodName);
207
208         [System.Security.SecurityCritical]  // auto-generated
209         private static bool DoesWin32MethodExist(String moduleName, String methodName)
210         {
211             // GetModuleHandle does not increment the module's ref count, so we don't need to call FreeLibrary.
212             IntPtr hModule = GetModuleHandle(moduleName);
213             if (hModule == IntPtr.Zero) {
214                 Debug.Assert(hModule != IntPtr.Zero, "GetModuleHandle failed.  Dll isn't loaded?");
215                 return false;
216             }
217             IntPtr functionPointer = GetProcAddress(hModule, methodName);
218             return (functionPointer != IntPtr.Zero);       
219         }
220         
221         [System.Security.SecuritySafeCritical]
222         private static bool _IsPackagedProcess()
223         {
224             Version windows8Version = new Version(6, 2, 0, 0);
225             OperatingSystem os = Environment.OSVersion;
226             bool osSupportsPackagedProcesses = os.Platform == PlatformID.Win32NT && os.Version >= windows8Version;
227
228             if (osSupportsPackagedProcesses && DoesWin32MethodExist(ExternDll.Kernel32, "AppPolicyGetClrCompat"))
229             {
230                 // Use AppPolicyGetClrCompat if it is available. Return true if and only if this is a UWA which means if
231                 // this is packaged desktop app this method will return false. This may cause some confusion however 
232                 // this is necessary to make the behavior of packaged desktop apps identical to desktop apps.
233                 AppPolicyClrCompat appPolicyClrCompat;
234                 return _AppPolicyGetClrCompat(GetCurrentProcessToken(), out appPolicyClrCompat) == ERROR_SUCCESS && 
235                     appPolicyClrCompat == AppPolicyClrCompat.AppPolicyClrCompat_Universal;
236             }
237             else if(osSupportsPackagedProcesses && DoesWin32MethodExist(ExternDll.Kernel32, "GetCurrentPackageId"))
238             {
239                 Int32 bufLen = 0;
240                 // Will return ERROR_INSUFFICIENT_BUFFER when running within a packaged application,
241                 // and will return ERROR_NO_PACKAGE_IDENTITY otherwise.
242                 return _GetCurrentPackageId(ref bufLen, null) == ERROR_INSUFFICIENT_BUFFER;
243             }
244             else
245             {   // We must be running on a downlevel OS.
246                 return false;
247             }
248         }
249
250         [System.Security.SecuritySafeCritical]
251         internal static Lazy<bool> IsPackagedProcess = new Lazy<bool>(() => _IsPackagedProcess());
252
253
254         // File src\services\system\io\unsafenativemethods.cs
255
256         public const int FILE_READ_DATA = (0x0001),
257         FILE_LIST_DIRECTORY = (0x0001),
258         FILE_WRITE_DATA = (0x0002),
259         FILE_ADD_FILE = (0x0002),
260         FILE_APPEND_DATA = (0x0004),
261         FILE_ADD_SUBDIRECTORY = (0x0004),
262         FILE_CREATE_PIPE_INSTANCE = (0x0004),
263         FILE_READ_EA = (0x0008),
264         FILE_WRITE_EA = (0x0010),
265         FILE_EXECUTE = (0x0020),
266         FILE_TRAVERSE = (0x0020),
267         FILE_DELETE_CHILD = (0x0040),
268         FILE_READ_ATTRIBUTES = (0x0080),
269         FILE_WRITE_ATTRIBUTES = (0x0100),
270         FILE_SHARE_READ = 0x00000001,
271         FILE_SHARE_WRITE = 0x00000002,
272         FILE_SHARE_DELETE = 0x00000004,
273         FILE_ATTRIBUTE_READONLY = 0x00000001,
274         FILE_ATTRIBUTE_HIDDEN = 0x00000002,
275         FILE_ATTRIBUTE_SYSTEM = 0x00000004,
276         FILE_ATTRIBUTE_DIRECTORY = 0x00000010,
277         FILE_ATTRIBUTE_ARCHIVE = 0x00000020,
278         FILE_ATTRIBUTE_NORMAL = 0x00000080,
279         FILE_ATTRIBUTE_TEMPORARY = 0x00000100,
280         FILE_ATTRIBUTE_COMPRESSED = 0x00000800,
281         FILE_ATTRIBUTE_OFFLINE = 0x00001000,
282         FILE_NOTIFY_CHANGE_FILE_NAME = 0x00000001,
283         FILE_NOTIFY_CHANGE_DIR_NAME = 0x00000002,
284         FILE_NOTIFY_CHANGE_ATTRIBUTES = 0x00000004,
285         FILE_NOTIFY_CHANGE_SIZE = 0x00000008,
286         FILE_NOTIFY_CHANGE_LAST_WRITE = 0x00000010,
287         FILE_NOTIFY_CHANGE_LAST_ACCESS = 0x00000020,
288         FILE_NOTIFY_CHANGE_CREATION = 0x00000040,
289         FILE_NOTIFY_CHANGE_SECURITY = 0x00000100,
290         FILE_ACTION_ADDED = 0x00000001,
291         FILE_ACTION_REMOVED = 0x00000002,
292         FILE_ACTION_MODIFIED = 0x00000003,
293         FILE_ACTION_RENAMED_OLD_NAME = 0x00000004,
294         FILE_ACTION_RENAMED_NEW_NAME = 0x00000005,
295         FILE_CASE_SENSITIVE_SEARCH = 0x00000001,
296         FILE_CASE_PRESERVED_NAMES = 0x00000002,
297         FILE_UNICODE_ON_DISK = 0x00000004,
298         FILE_PERSISTENT_ACLS = 0x00000008,
299         FILE_FILE_COMPRESSION = 0x00000010,
300         OPEN_EXISTING = 3,
301         OPEN_ALWAYS = 4,
302         FILE_FLAG_WRITE_THROUGH = unchecked((int)0x80000000),
303         FILE_FLAG_OVERLAPPED = 0x40000000,
304         FILE_FLAG_NO_BUFFERING = 0x20000000,
305         FILE_FLAG_RANDOM_ACCESS = 0x10000000,
306         FILE_FLAG_SEQUENTIAL_SCAN = 0x08000000,
307         FILE_FLAG_DELETE_ON_CLOSE = 0x04000000,
308         FILE_FLAG_BACKUP_SEMANTICS = 0x02000000,
309         FILE_FLAG_POSIX_SEMANTICS = 0x01000000,
310         FILE_TYPE_UNKNOWN = 0x0000,
311         FILE_TYPE_DISK = 0x0001,
312         FILE_TYPE_CHAR = 0x0002,
313         FILE_TYPE_PIPE = 0x0003,
314         FILE_TYPE_REMOTE = unchecked((int)0x8000),
315         FILE_VOLUME_IS_COMPRESSED = 0x00008000;
316
317         [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage", Justification = "reviewed")]
318         [DllImport(ExternDll.Advapi32, CharSet=System.Runtime.InteropServices.CharSet.Unicode, SetLastError=true)]
319         [ResourceExposure(ResourceScope.None)]
320         public extern static int LookupAccountSid(string systemName, byte[] pSid, StringBuilder szUserName, ref int userNameSize, StringBuilder szDomainName, ref int domainNameSize, ref int eUse);
321
322         public const int GetFileExInfoStandard = 0;
323
324         [StructLayout(LayoutKind.Sequential)]
325         public struct WIN32_FILE_ATTRIBUTE_DATA {
326             internal int fileAttributes;
327             internal uint ftCreationTimeLow;
328             internal uint ftCreationTimeHigh;
329             internal uint ftLastAccessTimeLow;
330             internal uint ftLastAccessTimeHigh;
331             internal uint ftLastWriteTimeLow;
332             internal uint ftLastWriteTimeHigh;
333             internal uint fileSizeHigh;
334             internal uint fileSizeLow;
335         }
336
337         // file Windows Forms
338         [DllImport(ExternDll.Version, CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=false)]
339         [ResourceExposure(ResourceScope.Machine)]
340         public static extern int GetFileVersionInfoSize(string lptstrFilename, out int handle);
341         [DllImport(ExternDll.Version, CharSet=CharSet.Auto, BestFitMapping=false)]
342         [ResourceExposure(ResourceScope.Machine)]
343         public static extern bool GetFileVersionInfo(string lptstrFilename, int dwHandle, int dwLen, HandleRef lpData);
344         [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
345         [SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments")]
346         [DllImport(ExternDll.Kernel32, CharSet=CharSet.Auto)]
347         [ResourceExposure(ResourceScope.Machine)]
348         public static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
349         [DllImport(ExternDll.Version, CharSet=CharSet.Auto, BestFitMapping=false)]
350         [ResourceExposure(ResourceScope.Process)]   // Review usages to see if versioning problems exist in distant callers
351         public static extern bool VerQueryValue(HandleRef pBlock, string lpSubBlock, [In, Out] ref IntPtr lplpBuffer, out int len);
352         [DllImport(ExternDll.Version, CharSet=CharSet.Auto, BestFitMapping=true)]
353         [ResourceExposure(ResourceScope.None)]
354         public static extern int VerLanguageName( int langID, StringBuilder lpBuffer, int nSize);
355
356         [DllImport(ExternDll.Advapi32, CharSet=System.Runtime.InteropServices.CharSet.Unicode, SetLastError=true)]
357         [ResourceExposure(ResourceScope.Machine)]
358         public static extern bool ReportEvent(SafeHandle hEventLog, short type, ushort category,
359                                                 uint eventID, byte[] userSID, short numStrings, int dataLen, HandleRef strings,
360                                                 byte[] rawData);
361         [DllImport(ExternDll.Advapi32, CharSet=System.Runtime.InteropServices.CharSet.Unicode, SetLastError=true)]
362         [ResourceExposure(ResourceScope.Machine)]
363         public static extern bool ClearEventLog(SafeHandle hEventLog, HandleRef lpctstrBackupFileName);
364         [DllImport(ExternDll.Advapi32, CharSet=System.Runtime.InteropServices.CharSet.Unicode, SetLastError=true)]
365         [ResourceExposure(ResourceScope.None)]
366         public static extern bool GetNumberOfEventLogRecords(SafeHandle hEventLog, out int count);
367         [DllImport(ExternDll.Advapi32, CharSet=System.Runtime.InteropServices.CharSet.Unicode, SetLastError=true)]
368         [ResourceExposure(ResourceScope.None)]
369         [return: MarshalAs(UnmanagedType.Bool)]
370         [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage", Justification = "[....]: EventLog is protected by EventLogPermission")]
371         public static extern bool GetOldestEventLogRecord(SafeHandle hEventLog, out int number);
372         [DllImport(ExternDll.Advapi32, CharSet=System.Runtime.InteropServices.CharSet.Unicode, SetLastError=true)]
373         [ResourceExposure(ResourceScope.Machine)]
374         [return: MarshalAs(UnmanagedType.Bool)]
375         [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage", Justification = "[....]: EventLog is protected by EventLogPermission")]
376         public static extern bool ReadEventLog(SafeHandle hEventLog, int dwReadFlags,
377                                                  int dwRecordOffset, byte[] buffer, int numberOfBytesToRead, out int bytesRead,
378                                                  out int minNumOfBytesNeeded);
379         [DllImport(ExternDll.Advapi32, CharSet=System.Runtime.InteropServices.CharSet.Unicode, SetLastError=true)]
380         [ResourceExposure(ResourceScope.None)]
381         [return: MarshalAs(UnmanagedType.Bool)]
382         [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage", Justification = "[....]: EventLog is protected by EventLogPermission")]
383         public static extern bool NotifyChangeEventLog(SafeHandle hEventLog, SafeWaitHandle hEvent);
384
385         [DllImport(ExternDll.Kernel32, EntryPoint="ReadDirectoryChangesW", CharSet=System.Runtime.InteropServices.CharSet.Auto, SetLastError=true)]
386         [ResourceExposure(ResourceScope.None)]
387         public unsafe static extern bool ReadDirectoryChangesW(SafeFileHandle hDirectory, HandleRef lpBuffer,
388                                                                 int nBufferLength, int bWatchSubtree, int dwNotifyFilter, out int lpBytesReturned,
389                                                                 NativeOverlapped* overlappedPointer, HandleRef lpCompletionRoutine);
390
391         //////////////////// Serial Port structs ////////////////////
392         // Declaration for C# representation of Win32 Device Control Block (DCB)
393         // structure.  Note that all flag properties are encapsulated in the Flags field here,
394         // and accessed/set through SerialStream's GetDcbFlag(...) and SetDcbFlag(...) methods.
395         internal struct DCB
396         {
397
398             public uint DCBlength;
399             public uint BaudRate;
400             public uint Flags;
401             public ushort wReserved;
402             public ushort XonLim;
403             public ushort XoffLim;
404             public byte ByteSize;
405             public byte Parity;
406             public byte StopBits;
407             public byte XonChar;
408             public byte XoffChar;
409             public byte ErrorChar;
410             public byte EofChar;
411             public byte EvtChar;
412             public ushort wReserved1;
413         }
414
415         // Declaration for C# representation of Win32 COMSTAT structure associated with
416         // a file handle to a serial communications resource.  SerialStream's
417         // InBufferBytes and OutBufferBytes directly expose cbInQue and cbOutQue to reading, respectively.
418         internal struct COMSTAT
419         {
420             public uint Flags;
421             public uint cbInQue;
422             public uint cbOutQue;
423         }
424
425         // Declaration for C# representation of Win32 COMMTIMEOUTS
426         // structure associated with a file handle to a serial communications resource.
427         ///Currently the only set fields are ReadTotalTimeoutConstant
428         // and WriteTotalTimeoutConstant.
429         internal struct COMMTIMEOUTS
430         {
431             public int ReadIntervalTimeout;
432             public int ReadTotalTimeoutMultiplier;
433             public int ReadTotalTimeoutConstant;
434             public int WriteTotalTimeoutMultiplier;
435             public int WriteTotalTimeoutConstant;
436         }
437
438         // Declaration for C# representation of Win32 COMMPROP
439         // structure associated with a file handle to a serial communications resource.
440         // Currently the only fields used are dwMaxTxQueue, dwMaxRxQueue, and dwMaxBaud
441         // to ensure that users provide appropriate settings to the SerialStream constructor.
442         internal struct COMMPROP
443         {
444             public ushort  wPacketLength;
445             public ushort  wPacketVersion;
446             public int dwServiceMask;
447             public int dwReserved1;
448             public int dwMaxTxQueue;
449             public int dwMaxRxQueue;
450             public int dwMaxBaud;
451             public int dwProvSubType;
452             public int dwProvCapabilities;
453             public int dwSettableParams;
454             public int dwSettableBaud;
455             public ushort wSettableData;
456             public ushort  wSettableStopParity;
457             public int dwCurrentTxQueue;
458             public int dwCurrentRxQueue;
459             public int dwProvSpec1;
460             public int dwProvSpec2;
461             public char wcProvChar;
462         }
463         //////////////////// end Serial Port structs ////////////////////
464
465         //////////////////// Serial Port methods ////////////////////
466
467         
468
469         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
470         [ResourceExposure(ResourceScope.Machine)]
471         internal static extern SafeFileHandle CreateFile(String lpFileName,
472             int dwDesiredAccess, int dwShareMode,
473             IntPtr securityAttrs, int dwCreationDisposition,
474             int dwFlagsAndAttributes, IntPtr hTemplateFile);
475
476         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
477         [ResourceExposure(ResourceScope.None)]
478         internal static extern bool GetCommState(
479             SafeFileHandle hFile,  // handle to communications device
480             ref DCB lpDCB    // device-control block
481             );
482
483         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
484         [ResourceExposure(ResourceScope.None)]
485         internal static extern bool SetCommState(
486             SafeFileHandle hFile,  // handle to communications device
487             ref DCB lpDCB    // device-control block
488             );
489
490
491         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
492         [ResourceExposure(ResourceScope.None)]
493         internal static extern bool GetCommModemStatus(
494             SafeFileHandle hFile,        // handle to communications device
495             ref int lpModemStat  // control-register values
496             );
497
498         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
499         [ResourceExposure(ResourceScope.None)]
500         internal static extern bool SetupComm(
501             SafeFileHandle hFile,     // handle to communications device
502             int dwInQueue,  // size of input buffer
503             int dwOutQueue  // size of output buffer
504             );
505
506         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
507         [ResourceExposure(ResourceScope.None)]
508         internal static extern bool SetCommTimeouts(
509             SafeFileHandle hFile,                  // handle to comm device
510             ref COMMTIMEOUTS lpCommTimeouts  // time-out values
511             );
512
513         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
514         [ResourceExposure(ResourceScope.None)]
515         internal static extern bool SetCommBreak(
516             SafeFileHandle hFile                 // handle to comm device
517             );
518
519         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
520         [ResourceExposure(ResourceScope.None)]
521         internal static extern bool ClearCommBreak(
522             SafeFileHandle hFile                 // handle to comm device
523             );
524
525         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
526         [ResourceExposure(ResourceScope.None)]
527         internal static extern bool ClearCommError(
528             SafeFileHandle hFile,                 // handle to comm device
529             ref int lpErrors,
530             ref COMSTAT lpStat
531             );
532
533         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
534         [ResourceExposure(ResourceScope.None)]
535         internal static extern bool ClearCommError(
536             SafeFileHandle hFile,                 // handle to comm device
537             ref int lpErrors,
538             IntPtr lpStat
539             );
540         
541         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
542         [ResourceExposure(ResourceScope.None)]
543         internal static extern bool PurgeComm(
544             SafeFileHandle hFile,  // handle to communications resource
545             uint dwFlags  // action to perform
546             );
547
548         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
549         [ResourceExposure(ResourceScope.None)]
550         internal static extern bool FlushFileBuffers(SafeFileHandle hFile);
551     
552         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
553         [ResourceExposure(ResourceScope.None)]
554         internal static extern bool GetCommProperties(
555             SafeFileHandle hFile,           // handle to comm device
556             ref COMMPROP lpCommProp   // communications properties
557             );
558
559         // All actual file Read/Write methods, which are declared to be unsafe.
560         [DllImport(ExternDll.Kernel32, SetLastError=true)]
561         [ResourceExposure(ResourceScope.None)]
562         unsafe internal static extern int ReadFile(SafeFileHandle handle, byte* bytes, int numBytesToRead, IntPtr numBytesRead, NativeOverlapped* overlapped);
563
564         [DllImport(ExternDll.Kernel32, SetLastError=true)]
565         [ResourceExposure(ResourceScope.None)]
566         unsafe internal static extern int ReadFile(SafeFileHandle handle, byte* bytes, int numBytesToRead, out int numBytesRead, IntPtr overlapped);
567
568         [DllImport(ExternDll.Kernel32 , SetLastError=true)]
569         [ResourceExposure(ResourceScope.None)]
570         unsafe internal static extern int WriteFile(SafeFileHandle handle, byte* bytes, int numBytesToWrite, IntPtr numBytesWritten, NativeOverlapped* lpOverlapped);
571
572         [DllImport(ExternDll.Kernel32 , SetLastError=true)]
573         [ResourceExposure(ResourceScope.None)]
574         unsafe internal static extern int WriteFile(SafeFileHandle handle, byte* bytes, int numBytesToWrite, out int numBytesWritten, IntPtr lpOverlapped);
575
576         [DllImport(ExternDll.Kernel32 , SetLastError=true)]
577         [ResourceExposure(ResourceScope.None)]
578         internal static extern int GetFileType(
579             SafeFileHandle hFile   // handle to file
580             );
581         [DllImport(ExternDll.Kernel32 , SetLastError=true)]
582         [ResourceExposure(ResourceScope.None)]
583         internal static extern bool EscapeCommFunction(
584             SafeFileHandle hFile, // handle to communications device
585             int dwFunc      // extended function to perform
586             );
587
588         [DllImport(ExternDll.Kernel32 , SetLastError=true)]
589         [ResourceExposure(ResourceScope.None)]
590         unsafe internal static extern bool WaitCommEvent(
591             SafeFileHandle hFile,                // handle to comm device
592             int* lpEvtMask,                      // event type
593             NativeOverlapped* lpOverlapped       // overlapped structure
594             );
595
596         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
597         [ResourceExposure(ResourceScope.None)]
598         unsafe internal static extern bool SetCommMask(
599             SafeFileHandle hFile,
600             int dwEvtMask
601         );
602
603         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
604         [ResourceExposure(ResourceScope.None)]
605         unsafe internal static extern bool GetOverlappedResult(
606             SafeFileHandle hFile,
607             NativeOverlapped* lpOverlapped,
608             ref int lpNumberOfBytesTransferred,
609             bool bWait
610         );
611
612
613       //////////////////// end Serial Port methods ////////////////////
614
615         [DllImport(ExternDll.Advapi32, CharSet=CharSet.Auto, SetLastError=true)]
616         internal static extern 
617         bool GetTokenInformation (
618             [In]  IntPtr                TokenHandle,
619             [In]  uint                  TokenInformationClass,
620             [In]  IntPtr                TokenInformation,
621             [In]  uint                  TokenInformationLength,
622             [Out] out uint              ReturnLength);
623
624         internal const int TokenIsAppContainer = 29;
625
626         
627         [ComImport, Guid("00000003-0000-0000-C000-000000000046"),
628         InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
629         internal interface IMarshal 
630         {
631             [PreserveSig]
632             int GetUnmarshalClass( 
633                 ref Guid riid,
634                 IntPtr pv,
635                 int dwDestContext,
636                 IntPtr pvDestContext,
637                 int mshlflags,
638                 out Guid pCid);
639         
640             [PreserveSig]
641             int GetMarshalSizeMax( 
642                 ref Guid riid,
643                 IntPtr pv,
644                 int dwDestContext,
645                 IntPtr pvDestContext,
646                 int mshlflags,
647                 out int pSize);
648        
649             [PreserveSig]
650             int MarshalInterface( 
651                 IntPtr pStm,
652                 ref Guid riid,
653                 IntPtr pv,
654                 int dwDestContext,
655                 IntPtr pvDestContext,
656                 int mshlflags);
657        
658             [PreserveSig]
659             int UnmarshalInterface( 
660                 IntPtr pStm,
661                 ref Guid riid,
662                 out IntPtr ppv);
663        
664             [PreserveSig]
665             int ReleaseMarshalData(IntPtr pStm);
666         
667             [PreserveSig]
668             int DisconnectObject(int dwReserved);
669         }
670
671
672         [DllImport(ExternDll.Ole32)]
673         [ResourceExposure(ResourceScope.None)]
674         internal static extern int CoGetStandardMarshal(
675                 ref Guid riid,
676                 IntPtr pv,
677                 int dwDestContext,
678                 IntPtr pvDestContext,
679                 int mshlflags,
680                 out IntPtr ppMarshal
681         );
682
683 #endif // !SILVERLIGHT
684
685     }
686 }