Initial commit
[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 const int ERROR_INSUFFICIENT_BUFFER = 0x007A;
173         private const int ERROR_NO_PACKAGE_IDENTITY = 0x3d54;
174
175         // AppModel.h functions (Win8+)
176         [DllImport(ExternDll.Kernel32, CharSet = CharSet.None, EntryPoint = "GetCurrentPackageId")]
177         [System.Security.SecuritySafeCritical]
178         [return: MarshalAs(UnmanagedType.I4)]
179         private static extern Int32 _GetCurrentPackageId(ref Int32 pBufferLength, Byte[] pBuffer);
180
181         // Copied from Win32Native.cs
182         // Note - do NOT use this to call methods.  Use P/Invoke, which will
183         // do much better things w.r.t. marshaling, pinning memory, security 
184         // stuff, better interactions with thread aborts, etc.  This is used
185         // solely by DoesWin32MethodExist for avoiding try/catch EntryPointNotFoundException
186         // in scenarios where an OS Version check is insufficient
187         [DllImport(ExternDll.Kernel32, CharSet=CharSet.Ansi, BestFitMapping=false, SetLastError=true, ExactSpelling=true)]
188         [ResourceExposure(ResourceScope.None)]
189         private static extern IntPtr GetProcAddress(IntPtr hModule, String methodName);
190
191         [System.Security.SecurityCritical]  // auto-generated
192         private static bool DoesWin32MethodExist(String moduleName, String methodName)
193         {
194             // GetModuleHandle does not increment the module's ref count, so we don't need to call FreeLibrary.
195             IntPtr hModule = GetModuleHandle(moduleName);
196             if (hModule == IntPtr.Zero) {
197                 Debug.Assert(hModule != IntPtr.Zero, "GetModuleHandle failed.  Dll isn't loaded?");
198                 return false;
199             }
200             IntPtr functionPointer = GetProcAddress(hModule, methodName);
201             return (functionPointer != IntPtr.Zero);       
202         }
203         
204         [System.Security.SecuritySafeCritical]
205         private static bool _IsPackagedProcess()
206         {
207             OperatingSystem os = Environment.OSVersion;
208             if(os.Platform == PlatformID.Win32NT && os.Version >= new Version(6,2,0,0) && DoesWin32MethodExist(ExternDll.Kernel32, "GetCurrentPackageId"))
209             {
210                 Int32 bufLen = 0;
211                 // Will return ERROR_INSUFFICIENT_BUFFER when running within a packaged application,
212                 // and will return ERROR_NO_PACKAGE_IDENTITY otherwise.
213                 return _GetCurrentPackageId(ref bufLen, null) == ERROR_INSUFFICIENT_BUFFER;
214             }
215             else
216             {   // We must be running on a downlevel OS.
217                 return false;
218             }
219         }
220
221         [System.Security.SecuritySafeCritical]
222         internal static Lazy<bool> IsPackagedProcess = new Lazy<bool>(() => _IsPackagedProcess());
223
224
225         // File src\services\system\io\unsafenativemethods.cs
226
227         public const int FILE_READ_DATA = (0x0001),
228         FILE_LIST_DIRECTORY = (0x0001),
229         FILE_WRITE_DATA = (0x0002),
230         FILE_ADD_FILE = (0x0002),
231         FILE_APPEND_DATA = (0x0004),
232         FILE_ADD_SUBDIRECTORY = (0x0004),
233         FILE_CREATE_PIPE_INSTANCE = (0x0004),
234         FILE_READ_EA = (0x0008),
235         FILE_WRITE_EA = (0x0010),
236         FILE_EXECUTE = (0x0020),
237         FILE_TRAVERSE = (0x0020),
238         FILE_DELETE_CHILD = (0x0040),
239         FILE_READ_ATTRIBUTES = (0x0080),
240         FILE_WRITE_ATTRIBUTES = (0x0100),
241         FILE_SHARE_READ = 0x00000001,
242         FILE_SHARE_WRITE = 0x00000002,
243         FILE_SHARE_DELETE = 0x00000004,
244         FILE_ATTRIBUTE_READONLY = 0x00000001,
245         FILE_ATTRIBUTE_HIDDEN = 0x00000002,
246         FILE_ATTRIBUTE_SYSTEM = 0x00000004,
247         FILE_ATTRIBUTE_DIRECTORY = 0x00000010,
248         FILE_ATTRIBUTE_ARCHIVE = 0x00000020,
249         FILE_ATTRIBUTE_NORMAL = 0x00000080,
250         FILE_ATTRIBUTE_TEMPORARY = 0x00000100,
251         FILE_ATTRIBUTE_COMPRESSED = 0x00000800,
252         FILE_ATTRIBUTE_OFFLINE = 0x00001000,
253         FILE_NOTIFY_CHANGE_FILE_NAME = 0x00000001,
254         FILE_NOTIFY_CHANGE_DIR_NAME = 0x00000002,
255         FILE_NOTIFY_CHANGE_ATTRIBUTES = 0x00000004,
256         FILE_NOTIFY_CHANGE_SIZE = 0x00000008,
257         FILE_NOTIFY_CHANGE_LAST_WRITE = 0x00000010,
258         FILE_NOTIFY_CHANGE_LAST_ACCESS = 0x00000020,
259         FILE_NOTIFY_CHANGE_CREATION = 0x00000040,
260         FILE_NOTIFY_CHANGE_SECURITY = 0x00000100,
261         FILE_ACTION_ADDED = 0x00000001,
262         FILE_ACTION_REMOVED = 0x00000002,
263         FILE_ACTION_MODIFIED = 0x00000003,
264         FILE_ACTION_RENAMED_OLD_NAME = 0x00000004,
265         FILE_ACTION_RENAMED_NEW_NAME = 0x00000005,
266         FILE_CASE_SENSITIVE_SEARCH = 0x00000001,
267         FILE_CASE_PRESERVED_NAMES = 0x00000002,
268         FILE_UNICODE_ON_DISK = 0x00000004,
269         FILE_PERSISTENT_ACLS = 0x00000008,
270         FILE_FILE_COMPRESSION = 0x00000010,
271         OPEN_EXISTING = 3,
272         OPEN_ALWAYS = 4,
273         FILE_FLAG_WRITE_THROUGH = unchecked((int)0x80000000),
274         FILE_FLAG_OVERLAPPED = 0x40000000,
275         FILE_FLAG_NO_BUFFERING = 0x20000000,
276         FILE_FLAG_RANDOM_ACCESS = 0x10000000,
277         FILE_FLAG_SEQUENTIAL_SCAN = 0x08000000,
278         FILE_FLAG_DELETE_ON_CLOSE = 0x04000000,
279         FILE_FLAG_BACKUP_SEMANTICS = 0x02000000,
280         FILE_FLAG_POSIX_SEMANTICS = 0x01000000,
281         FILE_TYPE_UNKNOWN = 0x0000,
282         FILE_TYPE_DISK = 0x0001,
283         FILE_TYPE_CHAR = 0x0002,
284         FILE_TYPE_PIPE = 0x0003,
285         FILE_TYPE_REMOTE = unchecked((int)0x8000),
286         FILE_VOLUME_IS_COMPRESSED = 0x00008000;
287
288         [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage", Justification = "reviewed")]
289         [DllImport(ExternDll.Advapi32, CharSet=System.Runtime.InteropServices.CharSet.Unicode, SetLastError=true)]
290         [ResourceExposure(ResourceScope.None)]
291         public extern static int LookupAccountSid(string systemName, byte[] pSid, StringBuilder szUserName, ref int userNameSize, StringBuilder szDomainName, ref int domainNameSize, ref int eUse);
292
293         public const int GetFileExInfoStandard = 0;
294
295         [StructLayout(LayoutKind.Sequential)]
296         public struct WIN32_FILE_ATTRIBUTE_DATA {
297             internal int fileAttributes;
298             internal uint ftCreationTimeLow;
299             internal uint ftCreationTimeHigh;
300             internal uint ftLastAccessTimeLow;
301             internal uint ftLastAccessTimeHigh;
302             internal uint ftLastWriteTimeLow;
303             internal uint ftLastWriteTimeHigh;
304             internal uint fileSizeHigh;
305             internal uint fileSizeLow;
306         }
307
308         // file Windows Forms
309         [DllImport(ExternDll.Version, CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=false)]
310         [ResourceExposure(ResourceScope.Machine)]
311         public static extern int GetFileVersionInfoSize(string lptstrFilename, out int handle);
312         [DllImport(ExternDll.Version, CharSet=CharSet.Auto, BestFitMapping=false)]
313         [ResourceExposure(ResourceScope.Machine)]
314         public static extern bool GetFileVersionInfo(string lptstrFilename, int dwHandle, int dwLen, HandleRef lpData);
315         [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
316         [SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments")]
317         [DllImport(ExternDll.Kernel32, CharSet=CharSet.Auto)]
318         [ResourceExposure(ResourceScope.Machine)]
319         public static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
320         [DllImport(ExternDll.Version, CharSet=CharSet.Auto, BestFitMapping=false)]
321         [ResourceExposure(ResourceScope.Process)]   // Review usages to see if versioning problems exist in distant callers
322         public static extern bool VerQueryValue(HandleRef pBlock, string lpSubBlock, [In, Out] ref IntPtr lplpBuffer, out int len);
323         [DllImport(ExternDll.Version, CharSet=CharSet.Auto, BestFitMapping=true)]
324         [ResourceExposure(ResourceScope.None)]
325         public static extern int VerLanguageName( int langID, StringBuilder lpBuffer, int nSize);
326
327         [DllImport(ExternDll.Advapi32, CharSet=System.Runtime.InteropServices.CharSet.Unicode, SetLastError=true)]
328         [ResourceExposure(ResourceScope.Machine)]
329         public static extern bool ReportEvent(SafeHandle hEventLog, short type, ushort category,
330                                                 uint eventID, byte[] userSID, short numStrings, int dataLen, HandleRef strings,
331                                                 byte[] rawData);
332         [DllImport(ExternDll.Advapi32, CharSet=System.Runtime.InteropServices.CharSet.Unicode, SetLastError=true)]
333         [ResourceExposure(ResourceScope.Machine)]
334         public static extern bool ClearEventLog(SafeHandle hEventLog, HandleRef lpctstrBackupFileName);
335         [DllImport(ExternDll.Advapi32, CharSet=System.Runtime.InteropServices.CharSet.Unicode, SetLastError=true)]
336         [ResourceExposure(ResourceScope.None)]
337         public static extern bool GetNumberOfEventLogRecords(SafeHandle hEventLog, out int count);
338         [DllImport(ExternDll.Advapi32, CharSet=System.Runtime.InteropServices.CharSet.Unicode, SetLastError=true)]
339         [ResourceExposure(ResourceScope.None)]
340         [return: MarshalAs(UnmanagedType.Bool)]
341         [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage", Justification = "[....]: EventLog is protected by EventLogPermission")]
342         public static extern bool GetOldestEventLogRecord(SafeHandle hEventLog, out int number);
343         [DllImport(ExternDll.Advapi32, CharSet=System.Runtime.InteropServices.CharSet.Unicode, SetLastError=true)]
344         [ResourceExposure(ResourceScope.Machine)]
345         [return: MarshalAs(UnmanagedType.Bool)]
346         [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage", Justification = "[....]: EventLog is protected by EventLogPermission")]
347         public static extern bool ReadEventLog(SafeHandle hEventLog, int dwReadFlags,
348                                                  int dwRecordOffset, byte[] buffer, int numberOfBytesToRead, out int bytesRead,
349                                                  out int minNumOfBytesNeeded);
350         [DllImport(ExternDll.Advapi32, CharSet=System.Runtime.InteropServices.CharSet.Unicode, SetLastError=true)]
351         [ResourceExposure(ResourceScope.None)]
352         [return: MarshalAs(UnmanagedType.Bool)]
353         [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage", Justification = "[....]: EventLog is protected by EventLogPermission")]
354         public static extern bool NotifyChangeEventLog(SafeHandle hEventLog, SafeWaitHandle hEvent);
355
356         [DllImport(ExternDll.Kernel32, EntryPoint="ReadDirectoryChangesW", CharSet=System.Runtime.InteropServices.CharSet.Auto, SetLastError=true)]
357         [ResourceExposure(ResourceScope.None)]
358         public unsafe static extern bool ReadDirectoryChangesW(SafeFileHandle hDirectory, HandleRef lpBuffer,
359                                                                 int nBufferLength, int bWatchSubtree, int dwNotifyFilter, out int lpBytesReturned,
360                                                                 NativeOverlapped* overlappedPointer, HandleRef lpCompletionRoutine);
361
362         //////////////////// Serial Port structs ////////////////////
363         // Declaration for C# representation of Win32 Device Control Block (DCB)
364         // structure.  Note that all flag properties are encapsulated in the Flags field here,
365         // and accessed/set through SerialStream's GetDcbFlag(...) and SetDcbFlag(...) methods.
366         internal struct DCB
367         {
368
369             public uint DCBlength;
370             public uint BaudRate;
371             public uint Flags;
372             public ushort wReserved;
373             public ushort XonLim;
374             public ushort XoffLim;
375             public byte ByteSize;
376             public byte Parity;
377             public byte StopBits;
378             public byte XonChar;
379             public byte XoffChar;
380             public byte ErrorChar;
381             public byte EofChar;
382             public byte EvtChar;
383             public ushort wReserved1;
384         }
385
386         // Declaration for C# representation of Win32 COMSTAT structure associated with
387         // a file handle to a serial communications resource.  SerialStream's
388         // InBufferBytes and OutBufferBytes directly expose cbInQue and cbOutQue to reading, respectively.
389         internal struct COMSTAT
390         {
391             public uint Flags;
392             public uint cbInQue;
393             public uint cbOutQue;
394         }
395
396         // Declaration for C# representation of Win32 COMMTIMEOUTS
397         // structure associated with a file handle to a serial communications resource.
398         ///Currently the only set fields are ReadTotalTimeoutConstant
399         // and WriteTotalTimeoutConstant.
400         internal struct COMMTIMEOUTS
401         {
402             public int ReadIntervalTimeout;
403             public int ReadTotalTimeoutMultiplier;
404             public int ReadTotalTimeoutConstant;
405             public int WriteTotalTimeoutMultiplier;
406             public int WriteTotalTimeoutConstant;
407         }
408
409         // Declaration for C# representation of Win32 COMMPROP
410         // structure associated with a file handle to a serial communications resource.
411         // Currently the only fields used are dwMaxTxQueue, dwMaxRxQueue, and dwMaxBaud
412         // to ensure that users provide appropriate settings to the SerialStream constructor.
413         internal struct COMMPROP
414         {
415             public ushort  wPacketLength;
416             public ushort  wPacketVersion;
417             public int dwServiceMask;
418             public int dwReserved1;
419             public int dwMaxTxQueue;
420             public int dwMaxRxQueue;
421             public int dwMaxBaud;
422             public int dwProvSubType;
423             public int dwProvCapabilities;
424             public int dwSettableParams;
425             public int dwSettableBaud;
426             public ushort wSettableData;
427             public ushort  wSettableStopParity;
428             public int dwCurrentTxQueue;
429             public int dwCurrentRxQueue;
430             public int dwProvSpec1;
431             public int dwProvSpec2;
432             public char wcProvChar;
433         }
434         //////////////////// end Serial Port structs ////////////////////
435
436         //////////////////// Serial Port methods ////////////////////
437
438         
439
440         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
441         [ResourceExposure(ResourceScope.Machine)]
442         internal static extern SafeFileHandle CreateFile(String lpFileName,
443             int dwDesiredAccess, int dwShareMode,
444             IntPtr securityAttrs, int dwCreationDisposition,
445             int dwFlagsAndAttributes, IntPtr hTemplateFile);
446
447         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
448         [ResourceExposure(ResourceScope.None)]
449         internal static extern bool GetCommState(
450             SafeFileHandle hFile,  // handle to communications device
451             ref DCB lpDCB    // device-control block
452             );
453
454         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
455         [ResourceExposure(ResourceScope.None)]
456         internal static extern bool SetCommState(
457             SafeFileHandle hFile,  // handle to communications device
458             ref DCB lpDCB    // device-control block
459             );
460
461
462         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
463         [ResourceExposure(ResourceScope.None)]
464         internal static extern bool GetCommModemStatus(
465             SafeFileHandle hFile,        // handle to communications device
466             ref int lpModemStat  // control-register values
467             );
468
469         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
470         [ResourceExposure(ResourceScope.None)]
471         internal static extern bool SetupComm(
472             SafeFileHandle hFile,     // handle to communications device
473             int dwInQueue,  // size of input buffer
474             int dwOutQueue  // size of output buffer
475             );
476
477         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
478         [ResourceExposure(ResourceScope.None)]
479         internal static extern bool SetCommTimeouts(
480             SafeFileHandle hFile,                  // handle to comm device
481             ref COMMTIMEOUTS lpCommTimeouts  // time-out values
482             );
483
484         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
485         [ResourceExposure(ResourceScope.None)]
486         internal static extern bool SetCommBreak(
487             SafeFileHandle hFile                 // handle to comm device
488             );
489
490         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
491         [ResourceExposure(ResourceScope.None)]
492         internal static extern bool ClearCommBreak(
493             SafeFileHandle hFile                 // handle to comm device
494             );
495
496         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
497         [ResourceExposure(ResourceScope.None)]
498         internal static extern bool ClearCommError(
499             SafeFileHandle hFile,                 // handle to comm device
500             ref int lpErrors,
501             ref COMSTAT lpStat
502             );
503
504         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
505         [ResourceExposure(ResourceScope.None)]
506         internal static extern bool ClearCommError(
507             SafeFileHandle hFile,                 // handle to comm device
508             ref int lpErrors,
509             IntPtr lpStat
510             );
511         
512         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
513         [ResourceExposure(ResourceScope.None)]
514         internal static extern bool PurgeComm(
515             SafeFileHandle hFile,  // handle to communications resource
516             uint dwFlags  // action to perform
517             );
518
519         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
520         [ResourceExposure(ResourceScope.None)]
521         internal static extern bool FlushFileBuffers(SafeFileHandle hFile);
522     
523         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
524         [ResourceExposure(ResourceScope.None)]
525         internal static extern bool GetCommProperties(
526             SafeFileHandle hFile,           // handle to comm device
527             ref COMMPROP lpCommProp   // communications properties
528             );
529
530         // All actual file Read/Write methods, which are declared to be unsafe.
531         [DllImport(ExternDll.Kernel32, SetLastError=true)]
532         [ResourceExposure(ResourceScope.None)]
533         unsafe internal static extern int ReadFile(SafeFileHandle handle, byte* bytes, int numBytesToRead, IntPtr numBytesRead, NativeOverlapped* overlapped);
534
535         [DllImport(ExternDll.Kernel32, SetLastError=true)]
536         [ResourceExposure(ResourceScope.None)]
537         unsafe internal static extern int ReadFile(SafeFileHandle handle, byte* bytes, int numBytesToRead, out int numBytesRead, IntPtr overlapped);
538
539         [DllImport(ExternDll.Kernel32 , SetLastError=true)]
540         [ResourceExposure(ResourceScope.None)]
541         unsafe internal static extern int WriteFile(SafeFileHandle handle, byte* bytes, int numBytesToWrite, IntPtr numBytesWritten, NativeOverlapped* lpOverlapped);
542
543         [DllImport(ExternDll.Kernel32 , SetLastError=true)]
544         [ResourceExposure(ResourceScope.None)]
545         unsafe internal static extern int WriteFile(SafeFileHandle handle, byte* bytes, int numBytesToWrite, out int numBytesWritten, IntPtr lpOverlapped);
546
547         [DllImport(ExternDll.Kernel32 , SetLastError=true)]
548         [ResourceExposure(ResourceScope.None)]
549         internal static extern int GetFileType(
550             SafeFileHandle hFile   // handle to file
551             );
552         [DllImport(ExternDll.Kernel32 , SetLastError=true)]
553         [ResourceExposure(ResourceScope.None)]
554         internal static extern bool EscapeCommFunction(
555             SafeFileHandle hFile, // handle to communications device
556             int dwFunc      // extended function to perform
557             );
558
559         [DllImport(ExternDll.Kernel32 , SetLastError=true)]
560         [ResourceExposure(ResourceScope.None)]
561         unsafe internal static extern bool WaitCommEvent(
562             SafeFileHandle hFile,                // handle to comm device
563             int* lpEvtMask,                      // event type
564             NativeOverlapped* lpOverlapped       // overlapped structure
565             );
566
567         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
568         [ResourceExposure(ResourceScope.None)]
569         unsafe internal static extern bool SetCommMask(
570             SafeFileHandle hFile,
571             int dwEvtMask
572         );
573
574         [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
575         [ResourceExposure(ResourceScope.None)]
576         unsafe internal static extern bool GetOverlappedResult(
577             SafeFileHandle hFile,
578             NativeOverlapped* lpOverlapped,
579             ref int lpNumberOfBytesTransferred,
580             bool bWait
581         );
582
583
584       //////////////////// end Serial Port methods ////////////////////
585
586         [DllImport(ExternDll.Advapi32, CharSet=CharSet.Auto, SetLastError=true)]
587         internal static extern 
588         bool GetTokenInformation (
589             [In]  IntPtr                TokenHandle,
590             [In]  uint                  TokenInformationClass,
591             [In]  IntPtr                TokenInformation,
592             [In]  uint                  TokenInformationLength,
593             [Out] out uint              ReturnLength);
594
595         internal const int TokenIsAppContainer = 29;
596
597         
598         [ComImport, Guid("00000003-0000-0000-C000-000000000046"),
599         InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
600         internal interface IMarshal 
601         {
602             [PreserveSig]
603             int GetUnmarshalClass( 
604                 ref Guid riid,
605                 IntPtr pv,
606                 int dwDestContext,
607                 IntPtr pvDestContext,
608                 int mshlflags,
609                 out Guid pCid);
610         
611             [PreserveSig]
612             int GetMarshalSizeMax( 
613                 ref Guid riid,
614                 IntPtr pv,
615                 int dwDestContext,
616                 IntPtr pvDestContext,
617                 int mshlflags,
618                 out int pSize);
619        
620             [PreserveSig]
621             int MarshalInterface( 
622                 IntPtr pStm,
623                 ref Guid riid,
624                 IntPtr pv,
625                 int dwDestContext,
626                 IntPtr pvDestContext,
627                 int mshlflags);
628        
629             [PreserveSig]
630             int UnmarshalInterface( 
631                 IntPtr pStm,
632                 ref Guid riid,
633                 out IntPtr ppv);
634        
635             [PreserveSig]
636             int ReleaseMarshalData(IntPtr pStm);
637         
638             [PreserveSig]
639             int DisconnectObject(int dwReserved);
640         }
641
642
643         [DllImport(ExternDll.Ole32)]
644         [ResourceExposure(ResourceScope.None)]
645         internal static extern int CoGetStandardMarshal(
646                 ref Guid riid,
647                 IntPtr pv,
648                 int dwDestContext,
649                 IntPtr pvDestContext,
650                 int mshlflags,
651                 out IntPtr ppMarshal
652         );
653
654 #endif // !SILVERLIGHT
655
656     }
657 }